content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import gettext
def delete(page_id):
"""Delete a page."""
page = _get_page(page_id)
page_name = page.name
site_id = page.site_id
success, event = page_service.delete_page(page.id, initiator_id=g.user.id)
if not success:
flash_error(
gettext('Page "%(name)s" could not be d... | 9c858d19b27f42e71d6aa19ae636e282925f0492 | 3,649,900 |
def drift_var():
"""
Concept drift:
1. n_drifts
2. concept_sigmoid_spacing (None for sudden)
3. incremental [True] or gradual [False]
4. recurring [True] or non-recurring [False]
"""
return [(10, None, False, False), (10, 5, False, False), (10, 5, True, False)] | 34f2c55f928a16cca8c52307853ab32f56ecd954 | 3,649,901 |
def get_generators(matrix):
"""
Given a matrix in H-rep, gets the v-rep
Turns out, the code is the same as get_inequalities,
since lrs determines the directions based on the input.
Left like this for readability.
"""
return get_inequalities(matrix) | ab5c2059544842d5010cae1211acc7da9e021994 | 3,649,902 |
def num_instances(diff, flag=False):
"""returns the number of times the mother and daughter have
pallindromic ages in their lives, given the difference in age.
If flag==True, prints the details."""
daughter = 0
count = 0
while True:
mother = daughter + diff
if are_reversed(daught... | 84d39159c594b25aabfc9efceef0d13ebc15a817 | 3,649,903 |
import inspect
def get_dipy_workflows(module):
"""Search for DIPY workflow class.
Parameters
----------
module : object
module object
Returns
-------
l_wkflw : list of tuple
This a list of tuple containing 2 elements:
Worflow name, Workflow class obj
Examples... | a119d6defd6c741777c3fa2f1add6bc700357dbd | 3,649,904 |
def azel_fit(coo_ref, coo_meas, nsamp=2000, ntune=2000, target_accept=0.95, random_seed=8675309):
"""
Fit full az/el pointing model using PyMC3. The terms are analogous to those used by TPOINT(tm). This fit includes
the eight normal terms used in `~pytelpoint.transform.azel` with additional terms, az_sigma ... | 22c3989049933b55643d11bfb2aebeb4c629ed60 | 3,649,905 |
from pathlib import Path
import os
def repository_path(relative_path: str) -> Path:
"""
Resolve `relative_path` relative to the root of the repository.
"""
return Path(os.path.join(REPOSITORY_ROOT), relative_path).resolve() | 5228678023ef53d8b8ae55e8b3a7050b8db96115 | 3,649,906 |
def geojson_to_labels(geojson_dict, crs_transformer, extent=None):
"""Convert GeoJSON to ObjectDetectionLabels object.
If extent is provided, filter out the boxes that lie "more than a little
bit" outside the extent.
Args:
geojson_dict: dict in GeoJSON format
crs_transformer: used to c... | d8e0ed7034796235c6311d47eb234bfd0f38e68a | 3,649,907 |
def processed_transcript(df):
"""
Cleans the Transcript table by splitting value fileds and replacing nan values, drop extra columns
PARAMETERS:
transcript dataframe
RETURNS:
Cleaned transcript dataframe
"""
#expand the dictionary to coulmns (reward, amount, offre... | 452668d6d9616ca382f7968e0ac4dd52658be9f6 | 3,649,908 |
import six
def _TestSuiteName(dash_json_dict):
"""Extracts a test suite name from Dashboard JSON.
The dashboard JSON may contain a field "test_suite_name". If this is not
present or it is None, the dashboard will fall back to using "benchmark_name"
in the "chart_data" dict.
"""
name = None
if dash_json... | 1b2e6cbd820bde3b24be5cca107e49ea2dabc732 | 3,649,909 |
def create_default_prior(name, default_priors_file=None):
"""Make a default prior for a parameter with a known name.
Parameters
----------
name: str
Parameter name
default_priors_file: str, optional
If given, a file containing the default priors.
Return
------
prior: Pr... | e0ddbaf10e0288ba939637cb1b2ce685756c966b | 3,649,910 |
def clean_data(list_in):
"""
Inputs:
list_in - filtered list of ticket orders
Outputs:
Return list of tuples, each tuple contains
(last name, first name, note,[tickets])
"""
notes_list = []
data_out = []
for row in list_in:
trimmed_row = row[row.index('Purcha... | f2cdf17895d1661e40b64f3fcc9ff92558f53bdd | 3,649,911 |
def adfuller(
vdf,
column: str,
ts: str,
by: list = [],
p: int = 1,
with_trend: bool = False,
regresults: bool = False,
):
"""
---------------------------------------------------------------------------
Augmented Dickey Fuller test (Time Series stationarity).
Parameters
----------
vdf: ... | 8f78b2128c981af15a84ac94f54435da4aee0c6c | 3,649,912 |
from typing import Union
from typing import List
from typing import Dict
from typing import Optional
def get_routes_bend180(
ports: Union[List[Port], Dict[str, Port]],
bend: ComponentOrFactory = bend_euler,
cross_section: CrossSectionFactory = strip,
bend_port1: Optional[str] = None,
bend_port2: O... | f5ec1539a04c0c9eee9184d190e265af4e187ef0 | 3,649,913 |
import json
def list_datasets(github_repo="Ouranosinc/xclim-testdata", branch="main"):
"""Return a DataFrame listing all xclim test datasets available on the GitHub repo for the given branch.
The result includes the filepath, as passed to `open_dataset`, the file size (in KB) and the html url to the file.
... | 199c56efcb105d9ff043f2a7c1ef51857a8b9b77 | 3,649,914 |
import logging
def make_layerwise_projection_unshrink(*, server_state_type,
client_update_output_type,
server_update_fn, server_model_fn,
client_model_fn, shrink_unshrink_info):
"""Creates an unshrin... | 315e7096a45047abbb23bb444f13065f9c87dfc5 | 3,649,915 |
import json
def embed_terms(args, classes, dest, use_cache=True, path_to_json='ebd_cache.json'):
"""
Embeds class strings into word representations.
:param args
:param classes: (list of str) topic classes
:param dest: (str) path to destination file
:param path_to_json: (str) path to json file... | 8521b4828907c0083492b0d03848aeeb452d17e6 | 3,649,916 |
from pathlib import Path
def wf_paths(reachable):
"""
Construct all well-formed paths satisfying a given condition.
The condition is as follows: all the paths have height equal to
the ceiling of log_2(`reachable` + 1). `reachable` is interpreted
as a bitfield, with 1 meaning that the correspondin... | 86b0a2e6408a8257e201f21058459aea4aceac00 | 3,649,917 |
def get_imagemodel_in_rar(rar_path, mode):
""" 압축파일(rar_path)의 이미지파일의 name, width, height를 모아서 반환한다."""
image_models = []
with rarfile.RarFile(rar_path) as rf:
for name in rf.namelist():
if is_hidden_or_trash(name):
continue
if is_extensions_allow_image(name)... | ea94406e17b66bbbf0288b8f0cb03cdd723a2d63 | 3,649,918 |
from re import L
def run_single(i,threshold_area_fraction,death_to_birth_rate_ratio,domain_size_multiplier,return_history=False):
"""run a single voronoi tessellation model simulation"""
rates = (DEATH_RATE,DEATH_RATE/death_to_birth_rate_ratio)
rand = np.random.RandomState()
history = lib.run_simulati... | b4ef11ae873f69b472a2c41c2f5d33e88ed1169a | 3,649,919 |
def matrixmult (A, B):
"""Matrix multiplication function
This function returns the product of a matrix multiplication given two matrices.
Let the dimension of the matrix A be: m by n,
let the dimension of the matrix B be: p by q,
multiplication will only possible if n = p,
thus creating a matr... | 98065981c8047d927bacb07877dbf173ba379159 | 3,649,920 |
def TorsLattice(data = None, *args, **kwargs):
"""
Construct a lattice of torsion classes from various forms of input data
This raises an error if the constructed lattice is not semidistributive,
since the lattice of torsion classes is semidistributive.
INPUT:
- ``data``, ``*args``, ``**kwarg... | e07cfef58b2927b8e3c660ee20cc0c6bc365fa4b | 3,649,921 |
def get_accumulated_report(trigger_id, mission='fermi'):
"""
Return the last value for each keyword on the summary page for a given trigger_id
:param trigger_id:
:param mission: 'fermi' or 'swift'
:return:
"""
if 'fermi' in mission:
site = fermi_grb_site
elif 'swift' in mission:
... | de77dc845a48d6572b2ff9229eed57e7fd55b38c | 3,649,922 |
import torch
def sample(model, x, steps, temperature=1.0, sample=False, top_k=None):
"""
take a conditioning sequence of indices in x (of shape (b,t)) and predict the next token in
the sequence, feeding the predictions back into the model each time. Clearly the sampling
has quadratic complexity unlike... | c63ab2c001b7c88568d12d836da65abb368a8f31 | 3,649,923 |
def get_numbers(number, size, *, fg=DEFAULT_FGCHARACTER, bg=DEFAULT_BGCHARACTER):
"""Creates a shape of numbers.
Positional arguments:
number - number to print.
size - size of the shape.
Keyword arguments:
fg - foreground character.
bg - background character.
... | 1cc992796f7118cbc0b19938ece0f87ed146a0d2 | 3,649,924 |
import os
import sys
def config_from_env(key, config_schema=None):
"""Read config from a file path in os.env.
Args:
key (str) : Key represents an evironment variable to read config path
config_schema (trafaret): Trafaret object that defines the schema of the config.
If None, the... | cdeb2f32a1de803f2d2fb92451b9833e1718e5ec | 3,649,925 |
def to_cmyk(r: int, g: int, b: int) -> _cmyk:
"""
Takes RGB values 0->255 and returns their values
in the CMYK namespace.
https://www.rapidtables.com/convert/color/rgb-to-cmyk.html
"""
r, g, b = to_float(r, g, b)
k = 1 - max(r, g, b)
c = (1 - r - k) / (1 - k)
m = (1 - g - k) / (1 -... | 804f12c944ba0c0a740ca94c3e622b061db57dc5 | 3,649,926 |
def GetHostsInClusters(datacenter, clusterNames=[], connectionState=None):
"""
Return list of host objects from given cluster names.
@param datacenter: datacenter object
@type datacenter: Vim.Datacenter
@param clusterNames: cluster name list
@type clusterNames: string[]
@param connectionSta... | c9722212e239eaec930da34dac2b5c82d45178fe | 3,649,927 |
def get_gfa_targets(tiles, gfafile, faintlim=99, gaiadr="dr2"):
"""Returns a list of tables of GFA targets on each tile
Args:
tiles: table with columns TILEID, RA, DEC; or Tiles object
targets: table of targets with columsn RA, DEC
gaiadr: string, must be either "dr2" or "edr3" (d... | aa8c5a42babca87d26ad93538035734db54574f8 | 3,649,928 |
from sympy import hyper, meijerg
from re import S
def meijerint_indefinite(f, x):
"""
Compute an indefinite integral of ``f`` by rewriting it as a G function.
Examples
========
>>> from sympy.integrals.meijerint import meijerint_indefinite
>>> from sympy import sin
>>> from sympy.abc imp... | 5f4669476aee46ecf359c8d0de59acbe0762cb3d | 3,649,929 |
from typing import Tuple
from typing import Union
def fit_size(
img: IMG,
size: Tuple[int, int],
mode: FitSizeMode = FitSizeMode.INCLUDE,
direction: FitSizeDir = FitSizeDir.CENTER,
bg_color: Union[str, float, Tuple[float, ...]] = (255, 255, 255, 0),
) -> IMG:
"""
调整图片到指定的大小,超出部分裁剪,不足部分设为指定... | 6cc33cb8c3fff4edec3bf15978f8cedc056a5e0c | 3,649,930 |
import os
import csv
import sys
def load_iot_config(ini: dict):
"""
"""
if not verify_params(ini, 'iot', ['file', 'filedir']):
return {}
# Set file directory
iot_params = ini['iot']
filedir = iot_params['filedir']
filedir = filedir.strip(" ")
if filedir == "":
# HOME ... | 15121a76fc54b57c296fc7fb13c88911b9df15c4 | 3,649,931 |
import winreg
def supports_colour():
"""
Return True if the running system's terminal supports colour,
and False otherwise.
Adapted from https://github.com/django/django/blob/master/django/core/management/color.py
"""
def vt_codes_enabled_in_windows_registry():
"""
Check the W... | d567b7818c314d345a30f10dffd99c7a3b411c3e | 3,649,932 |
def next_code(value: int, mul: int = 252533, div: int = 33554393) -> int:
"""
Returns the value of the next code given the value of the current code
The first code is `20151125`.
After that, each code is generated by taking the previous one, multiplying it by `252533`,
and then keeping the remainder... | a9e5183e405574cc56a138a244f14de08ea68d00 | 3,649,933 |
import os
import subprocess
import shlex
import sys
def main() -> int:
"""Runs a program specified by command-line arguments."""
args = argument_parser().parse_args()
if not args.command or args.command[0] != '--':
return 1
env = os.environ.copy()
# Command starts after the "--".
com... | 62b01ad68221afb0e272c63a1747c3ef1bf02034 | 3,649,934 |
def read_csv_to_lol(full_path, sep=";"):
"""
Read csv file into lists of list.
Make sure to have a empty line at the bottom
"""
with open(full_path, 'r') as ff:
# read from CSV
data = ff.readlines()
# New line at the end of each line is removed
data = [i.replace("\n", "") for... | e53c46c6a8eabaece788111530fbf859dd23133f | 3,649,935 |
def read_experiment(path):
"""
Discovers CSV files an experiment produced and construct columns
for the experiment's conditions from the sub-directory structure.
Args:
path: path to the experiment's results.
Returns:
pd.DataFrame
"""
objects = list(path.rglob('*.csv'))
... | e9797fb71a0e9ba89e211fd0d079d5040e3a4639 | 3,649,936 |
from bs4 import BeautifulSoup
def single_keyword_search(keyword):
"""
구글에 keyword 검색결과를 html로 받아온뒤에 그 안에 일반 게시물 분류에 속하는
class='r' 부분만 모아서 return해주는 함수 입니다.
Args:
Keyword (String) : 구글에 검색할 Keyword
Returns:
title_list (bs4.element.ResultSet) : 구글 검색에서 확인된 일반게시물(class='r')들의 모... | 45909878da1c135c4dc6b1209c98ffc5e7e21b29 | 3,649,937 |
def partial_list(ys, xs, specified_shapes=None):
"""
Args:
ys: A list of tensors. Each tensor will be differentiated with the partial_nd
xs: A Tensor to be used for differentiation, or a list of tensors to be used for differentiation with the smae length as ys
specified_shapes: A list of... | 24b0d2583f21cd4497e1c38d79643e44eaab693e | 3,649,938 |
def _GuessBrowserName(bisect_bot):
"""Returns a browser name string for Telemetry to use."""
default = 'release'
browser_map = namespaced_stored_object.Get(_BOT_BROWSER_MAP_KEY)
if not browser_map:
return default
for bot_name_prefix, browser_name in browser_map:
if bisect_bot.startswith(bot_name_prefi... | b6b0fedd238aff07bfa46c61e9d792087b647a13 | 3,649,939 |
from re import T
import functools
import collections
def compile_train_function(network, batch_size, learning_rate):
"""Compiles the training function.
Args:
network: The network instance.
batch_size: The training batch size.
learning_rate: The learning rate.
Returns:
The upda... | 57778a2428d4348f6594d04ec35bc821a4fd8122 | 3,649,940 |
import json
import sys
import os
def json_loads(data):
"""Load json data, allowing - to represent stdin."""
if data is None:
return ""
if data == "-":
return json.load(sys.stdin)
elif os.path.exists(data):
with open(data, 'r') as handle:
return json.load(handle)
... | f5bdad826578108adccc32ca93ecd474954bfb7d | 3,649,941 |
def filter_values(freq, values, nthOct: int = 3):
"""
Filters the given values into nthOct bands.
Parameters
----------
freq : ndarray
Array containing the frequency axis.
values : ndarray
Array containing the magnitude values to be filtered.
nthOct : int, optional
F... | 2a1b270049f1c2869fa03d7bc2a4f64658646b7a | 3,649,942 |
def create_project(request):
"""View to create new project"""
user = request.user
if user.is_annotator:
error = ErrorMessage(header="Access denied", message="Only admin and managers can create projects")
return render(request, 'error.html', {'error':error})
if request.method == "POST":
... | 34d6def496c9ddac99710425a9550be7fa8eba58 | 3,649,943 |
from typing import Optional
import pathlib
def limit(
observed_CLs: np.ndarray,
expected_CLs: np.ndarray,
poi_values: np.ndarray,
figure_path: Optional[pathlib.Path] = None,
close_figure: bool = False,
) -> mpl.figure.Figure:
"""Draws observed and expected CLs values as function of the paramet... | 85bf753844083dcfbea8273cabe6cf7c0513c6d9 | 3,649,944 |
def get_genlu_code(cursor, label):
"""Find or create the code for this label."""
if label not in GENLU_CODES:
cursor.execute("SELECT max(id) from general_landuse")
row = cursor.fetchone()
newval = 0 if row[0] is None else row[0] + 1
LOG.debug("Inserting new general landuse code: ... | a5bcfef36601a87648c21c93386b58afd7563fd7 | 3,649,945 |
def make_predictions(clf_object,predictors_str,data_source):
"""make_predictions comes up with predictions
from given input data
Input:
clf_object
object
constructed classification model
predictors_str
nd str array
stri... | ed5f29e65ddf3d7f7081b89e6f747925de944567 | 3,649,946 |
def no_span_nodes(tree, debug=False, root_id=None):
"""Return True, iff there is no span node in the given ParentedTree."""
assert isinstance(tree, ParentedTree)
if root_id is None:
root_id = tree.root_id
span_label = debug_root_label('span', debug=debug, root_id=root_id)
if tree.label() =... | 0baf0b47071b1f7faaaa5cd08bffbdc38d534afe | 3,649,947 |
def get_token_annualized(address, days):
"""Return annualized returns for a specific token.
Args:
days [int]: Days ago for which to display annualized returns.
address [str]: Ethereum token address.
Return:
dict: Annualized returns for a specified token.
key [str]: Day... | 734b64fdce65d069eebd5fd62270b24fd2d27100 | 3,649,948 |
import random
import string
def generate_random_string(N):
"""
Generate a random string
Parameters
-------------
N
length of the string
Returns
-------------
random_string
Random string
"""
return ''.join(random.choice(string.ascii_uppercase + string.digits) f... | 3e2e672140e18546260a0882fa6cf06073bdf8e7 | 3,649,949 |
import re
def extract_charm_name_from_url(charm_url):
"""Extract the charm name from the charm url.
E.g. Extract 'heat' from local:bionic/heat-12
:param charm_url: Name of model to query.
:type charm_url: str
:returns: Charm name
:rtype: str
"""
charm_name = re.sub(r'-[0-9]+$', '', c... | 9905d6b5c7a2f5047bc939d1b6e23d128ee8984d | 3,649,950 |
def class_name(service_name: str) -> str:
"""Map service name to .pyi class name."""
return f"Service_{service_name}" | b4bed8a677f9eedfcd66d6d37078075b0967ea20 | 3,649,951 |
def interesting_columns(df):
"""Returns non-constant column names of a dataframe."""
return sorted(set(df.columns) - set(constant_columns(df))) | 84e548e806bcfd9031d620d3c02f942f60fa53cc | 3,649,952 |
def liberty_str(s):
"""
>>> liberty_str("hello")
'"hello"'
>>> liberty_str('he"llo')
Traceback (most recent call last):
...
ValueError: '"' is not allow in the string: 'he"llo'
>>> liberty_str(1.0)
'"1.0000000000"'
>>> liberty_str(1)
'"1.0000000000"'
>>> liberty_... | 2bc56be42a062668f94c9cc88baa94f5f73feaa3 | 3,649,953 |
import warnings
def is_valid_dm(D, tol=0.0, throw=False, name="D", warning=False):
"""
Return True if input array is a valid distance matrix.
Distance matrices must be 2-dimensional numpy arrays.
They must have a zero-diagonal, and they must be symmetric.
Parameters
----------
D : ndarra... | e21163a5d68fa5cf1c2e0bbed34276c7e5a6b851 | 3,649,954 |
from types import SimpleNamespace
import scipy
def solve_gradwavefront(data, excludeself=False, predict_at=None,
fix_covar=False, **kw):
"""Find turbulent contributions to measured fiber positions.
Assumes that the turbulent contributions can be modeled as the
gradient of a wavefr... | 94733f5cf073aa44752fa395fe24f66fc9524049 | 3,649,955 |
from typing import Any
def str_to_py(value: str):
"""Convert an string value to a native python type."""
rv: Any
if is_boolean_state(value):
rv = get_boolean(value)
elif is_integer(value):
rv = get_integer(value)
elif is_float(value):
rv = get_float(value)
else:
... | b0a5d0fbe573be6d9d961ac5c3c1895fd82539eb | 3,649,956 |
from typing import Dict
from typing import Any
from typing import Tuple
import json
import requests
def action(request: Dict[str, Any]) -> Tuple[str, int]:
"""Triggered from Slack action via an HTTPS endpoint.
Args:
request (dict): Request payload.
"""
if request.method != 'POST':
ret... | fdf24beee3e5dc929f575883114987419967b2e9 | 3,649,957 |
def inmemory():
"""Returns an xodb database backed by an in-memory xapian
database. Does not support spelling correction.
"""
return open(xapian.inmemory_open(), spelling=False, inmem=True) | ed67dd9bd7d70c5aab33c963dfed4e2103f5cfd1 | 3,649,958 |
def all(iterable: object) -> bool:
"""all."""
for element in iterable:
if not element:
return False
return True | 130a93230538122f35e29a6ec4ad5fca0efd835b | 3,649,959 |
def ind2slice(Is):
"""Convert boolean and integer index arrays to slices.
Integer and boolean arrays are converted to slices that span the selected elements, but may include additional
elements. If possible, the slices are stepped.
Arguments
---------
Is : tuple
tuple of indices (slice... | 6be6a82750f9f73b2008c528ff192b07b8e0a784 | 3,649,960 |
def cleanup_mediawiki(text):
"""Modify mediawiki markup to make it pandoc ready.
Long term this needs to be highly configurable on a site-by-site
basis, but for now I'll put local hacks here.
Returns tuple: cleaned up text, list of any categories
"""
# This tag was probably setup via SyntaxHig... | c4f210d60e847740f4b36ed321cfd4f95b88b39f | 3,649,961 |
import re
def select_devices(devices):
""" 选择设备 """
device_count = len(devices)
print("Device list:")
print("0) All devices")
for i, d in enumerate(devices, start=1):
print("%d) %s\t%s" % (i, d['serial'], d['model']))
print("q) Exit this operation")
selected = input("\nselect: ")
... | 91c405c8a198deb01e8abecc592ac2286dc712fd | 3,649,962 |
def Fill( h ):
"""fill every empty value in histogram with
previous value.
"""
new_h = []
x,v = h[0]
if type(v) == ListType or type(v) == TupleType:
l = len(v)
previous_v = [0] * l
else:
previous_v = 0
for x, v in h:
if type(v) == ListType or t... | 429a4d723c38692e8ee0ebaea2fda1ec008cded6 | 3,649,963 |
from re import L
def pendulum(theta, S, mg, drag) -> ps.Composition:
"""Draw a free body animation of a pendulum.
params:
theta: the angle from the vertical at which the pendulum is.
S: the force exerted toward the pivot.
mg: the force owing to gravity.
drag: the force acting ... | 9dd7918b00bae82600d4bb064461f7b6e58e9fb2 | 3,649,964 |
def get_items():
"""Fetches items from `INITIAL_OFFSET` in batches of `PAGINATION_OFFSET` until there are no
more """
offset = INITIAL_OFFSET
items = []
while True:
batch = get_page_of_items(JSON_ENDPOINT.format(offset))
if not batch:
break
items.extend(batch)
... | b0950ee8eb291cceb1f0871e918b5aff26b6c2ab | 3,649,965 |
def tcombinations_with_replacement(iterable, r):
"""
>>> tcombinations_with_replacement('ABCD', 0)
((),)
>>> tcombinations_with_replacement('ABCD', 1)
(('A',), ('B',), ('C',), ('D',))
>>> tcombinations_with_replacement('ABCD', 2)
(('A', 'A'), ('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'B'), (... | 432c826751bcfc1aa7bfef36cd25a198e6fe7b72 | 3,649,966 |
def discreteFiber(c, s, B=I3, ndiv=120, invert=False, csym=None, ssym=None):
"""
Generate symmetrically reduced discrete orientation fiber.
Parameters
----------
c : TYPE
DESCRIPTION.
s : TYPE
DESCRIPTION.
B : TYPE, optional
DESCRIPTION. The default is I3.
ndiv :... | fd6c19886b16f715f472d85fb48d6289a42cd105 | 3,649,967 |
import random
def random_organism(invalid_data):
"""
Generate Random Organism
return: string containing "organism" name from CanCOGeN vocabulary.
"""
return random.choice(covid19_vocab_dict.get('organism')), global_valid_data | 9319d04ddf874c43d84489c2b20c52cee334a8c1 | 3,649,968 |
import matplotlib.pyplot as plt
def fate_bias(adata,
group,
basis='umap',
fate_bias_df=None,
figsize=(6, 4),
save_show_or_return='show',
save_kwargs={},
**cluster_maps_kwargs
):
"""Plot the lineage (fat... | d1246bbcca11439c6577e7fd3f3fb635aaa2a9f7 | 3,649,969 |
def comput_mean_ndcg(df, k):
"""
Input:rating_info
(usr_id, movie_id, rating)
output: 平均ndcg
对每一种人 得到他真实分数和预测分数的dataframe
然后得到values
"""
#df.insert(df.shape[1], 'pred', pred)
#print(df.groupby('user_id'))
piece = dict(list(df.groupby('user_id')))
ndcg_list = []
f... | 70bcb630b7df9940a76499f34a769bd2dca90283 | 3,649,970 |
from typing import List
def to_im_list(IMs: List[str]):
"""Converts a list of string to IM Objects"""
return [IM.from_str(im) for im in IMs] | 9694500ae2f5fa7c203100a5a1756fe71af862cc | 3,649,971 |
def ref_ellipsoid(refell, UNITS='MKS'):
"""
Computes parameters for a reference ellipsoid
Arguments
---------
refell: reference ellipsoid name
Keyword arguments
-----------------
UNITS: output units
MKS: meters, kilograms, seconds
CGS: centimeters, grams, seconds
""... | 8f5032af1375d758445ed139bc4a2d6989f15dc5 | 3,649,972 |
def is_number(s):
"""
Check if it is a number.
Args:
s: The variable that needs to be checked.
Returns:
bool: True if float, False otherwise.
"""
try:
float(s)
return True
except ValueError:
return False | 071aeac26a5a907caf1764dc20d7de1c6408714b | 3,649,973 |
import time
import pickle
import json
def index():
"""
搜索提示功能
根据输入的值自动联想,支持中文,英文,英文首字母
:return: response
"""
start_time = time.time()
# 输入词转小写
wd = request.args.get('wd').lower()
user_id = request.args.get('user_id')
if user_id and user_id != 'None':
print(user_id)
... | 7ab07d20dea10c6bd16d899c8c9298f02bd9f17e | 3,649,974 |
import itertools
def combineSets(listOfSets):
"""
Combines sets of strings by taking the cross product of the sets and \
concatenating the elements in the resulting tuples
:param listOfSets: 2-D list of strings
:returns: a list of strings
"""
totalCrossProduct = ['']
for i in ... | 26a383d224716fd8f4cf8589607e2df1ccb82a7e | 3,649,975 |
def list_all_connections(pg_id='root', descendants=True):
"""
Lists all connections for a given Process Group ID
Args:
pg_id (str): ID of the Process Group to retrieve Connections from
descendants (bool): True to recurse child PGs, False to not
Returns:
(list): List of Connecti... | 6df326ff521f175b3ccfe4b1d2488328fe6e6213 | 3,649,976 |
import os
def find_file(fname):
"""
Return the full file name (path plus name) to file fname.
fname is the name of the file to find.
If the file fname is not found, then simply return None.
"""
for d in get_cli_search_dirs():
full_filename = os.path.join(d, fname)
if os.path.... | 6892d0fb6349c9029d557daa25b4a394a38a0311 | 3,649,977 |
def _GetTombstoneData(device, tombstone_file):
"""Retrieve the tombstone data from the device
Args:
device: An instance of DeviceUtils.
tombstone_file: the tombstone to retrieve
Returns:
A list of lines
"""
return device.old_interface.GetProtectedFileContents(
'/data/tombstones/' + tombsto... | 99322ea3d67e150f4433c713159eb7bc8069271f | 3,649,978 |
import time
def _strTogYear(v):
"""Test gYear value
@param v: the literal string
@return v
@raise ValueError: invalid value
"""
try:
time.strptime(v+"-01-01", "%Y-%m-%d")
return v
except:
raise ValueError("Invalid gYear %s" % v) | a65e04c2d3790d3d55bbc8788d6802e1aae1b78c | 3,649,979 |
def aca_full_pivoting(A, epsilon):
"""ACA with full pivoting as in the lecture
Takes in a matrix, and returns the CUR decomposition
"""
# R0 = A
Rk = A.copy()
I_list = []
J_list = []
while frobenius_norm(Rk) > epsilon*frobenius_norm(A):
i, j = np.unravel_index(np.argmax(np.abs(R... | 96bcfd4b8cb560904efc4ab6cfac6473d8dafe47 | 3,649,980 |
from typing import List
import os
def get_word_cloud(words: List[str], max_words=500, image_path=None, image_name=None):
"""
Create a word cloud based on a set of words.
Args:
words (List[str]):
List of words to be included in the word cloud.
max_words (int):
Maxim... | 3ccbfe615d08f68ea7160848c254b7354d509a83 | 3,649,981 |
import os
import fnmatch
def get_data_sets(cnn_n_input, data_directory="data_set/", n_data_sets=5):
"""
Retrieve data and partition it into n_data_sets for cross-validation.
"""
print("Partitioning data into", str(n_data_sets), "splits.")
# Get list of labels
list_labels = extract_data.get_l... | 3adcc276d3e69b98650728d70fe27d57d12c8349 | 3,649,982 |
import os
def _get_pyo_codes(fmt='', dtype='int16', file_out=''):
"""Convert file and data formats to int codes, e.g., wav int16 -> (0, 0).
"""
if not fmt:
dot_ext = os.path.splitext(file_out)[1]
fmt = dot_ext.lower().strip('.')
if fmt in pyo_formats:
file_fmt = pyo_formats[fm... | 12ff9d453542dfd77459bd5424ef65c9328bfaf5 | 3,649,983 |
def catch_gpu_memory_error( f ):
"""
Decorator that calls the function `f` and catches any GPU memory
error, during the execution of f.
If a memory error occurs, this decorator prints a corresponding message
and aborts the simulation (using MPI abort if needed)
"""
# Redefine the original f... | 1201236b7d2217fcfc3fcb95905f8f4e2f89af06 | 3,649,984 |
def horizontal_tail_planform_raymer(horizontal_stabilizer, wing, l_ht,c_ht):
"""Adjusts reference area before calling generic wing planform function to compute wing planform values.
Assumptions:
None
Source:
Raymer
Inputs:
horizontal_stabilizer [SUAVE data structure]
... | 860a020e3e2b06943df2689bd54707a051fb30b2 | 3,649,985 |
from improved_permissions.roles import ALLOW_MODE
def inherit_check(role_s, permission):
"""
Check if the role class has the following
permission in inherit mode.
"""
role = get_roleclass(role_s)
if role.inherit is True:
if role.get_inherit_mode() == ALLOW_MODE:
return Tru... | 5dbaa7afee9802ea1eda4cec869dd44395faf0e5 | 3,649,986 |
import random
def giveHint(indexValue, myBoard):
"""Return a random matching card given the index of a card
and a game board"""
validMatches = []
card = myBoard[indexValue]
for c in myBoard:
if (card[0] == c[0]) and (myBoard.index(c) != indexValue):
validMatches.append(myBoard.... | e578f40e7d7e2e17ddac53f9cfdc219e47c861cd | 3,649,987 |
async def make_getmatch_embed(data):
"""Generate the embed description and other components for a getmatch() command.
As with its parent, remember that this currently does not support non team-vs.
`data` is expected to be the output of `get_individual_match_data()`.
The following `dict` is returned... | c37e0d6ee948259e4ad898d3cafb8e13b6452d80 | 3,649,988 |
def allreduceCommunicate_op(node, comm):
"""Make a new instance of AllReduceCommunicateOp and call the instance.
Parameters:
----
node : Node
The Node to do allreduce
Returns:
----
A new Node instance created by Op.
"""
return AllReduceCommunicateOp(node, comm) | 5096a9014ae349e39c2d59de77845221ffdddb10 | 3,649,989 |
def reduce_fn(state, values):
"""tf.data.Dataset-friendly implementation of mean and variance."""
k, n, ex, ex2 = state
# If this is the first iteration, we pick the first value to be 'k',
# which helps with precision - we assume that k is close to an average
# value and calculate mean and variance with respe... | 473bb8cae3e898f3a166250fbdb805ad55aaaea9 | 3,649,990 |
def winged_edge(
face_features: np.ndarray,
edge_features: np.ndarray,
coedge_features: np.ndarray,
coedge_to_next: np.ndarray,
coedge_to_mate: np.ndarray,
coedge_to_face: np.ndarray,
coedge_to_edge: np.ndarray,
):
"""Create graph according to the `winged edge` configuration."""
coe... | 8f023d4e6133b044c435737e49ae768c83f089ca | 3,649,991 |
def dollar_format(dollars):
"""
Args:
dollars (any): A dollar value (Any value that can be turned into a float can be used - int, Decimal, str, etc.)
Returns:
str: The formatted string
"""
decimal_dollars = Decimal(dollars)
if decimal_dollars < 0:
return "-${:,.2f}".forma... | d9f8a9195a92af39df9754e14bae723060c335b1 | 3,649,992 |
from typing import Callable
from typing import Any
def check_aea_project(
f: Callable, check_aea_version: bool = True, check_finger_prints: bool = False
) -> Callable:
"""
Check the consistency of the project as a decorator.
- try to load agent configuration file
- iterate over all the agent pack... | 31d909116613be819b61be16160bd72227462853 | 3,649,993 |
def find_closest_cross(wire1_path, wire2_path):
"""
Compare the coordinates of two wire paths to find the crossing point
closest (Manhattan Distance) to the origin (0,0).
Returns a list of crossing points, the closest crossing point and its distance to the start point
"""
best_result ... | c91c5db3bb09cdfc74c4c71c92bf46274eb8d88c | 3,649,994 |
import re
def add_signature_source(service, **_):
"""
Add a signature source for a given service
Variables:
service => Service to which we want to add the source to
Arguments:
None
Data Block:
{
"uri": "http://somesite/file_to_get", # URI to fetch for parsing ... | 65526852dee90f077e0c8b52fc53e725043ffc1e | 3,649,995 |
def edit_screen_item(self, request, form):
""" Edit a screen. """
layout = ManageScreensLayout(self, request)
if form.submitted(request):
form.update_model(self)
request.message(_('Screen modified.'), 'success')
request.app.pages_cache.flush()
return redirect(layout.manage... | 456837172860c808c2347d556cb8aaa4fcf59fbb | 3,649,996 |
def get_xyz_t():
"""
CIELAB to XYZ の逆関数の中の値を
XYZ のぞれぞれについて求める。
"""
c, l, h = symbols('c, l, h', real=True)
xt = (l + 16) / 116 + (c * cos(h)) / 500
yt = (l + 16) / 116
zt = (l + 16) / 116 - (c * sin(h)) / 200
xyz_t = [xt, yt, zt]
return xyz_t, c, l, h | e823744ada693fb525d57f5a616c89677c8ed0a5 | 3,649,997 |
async def home():
"""
Home page, welcome
Returns:
Rendered template of homepage
"""
return await render_template('home.html') | a981c121c64a99359adac620dfa0f58d31a63956 | 3,649,998 |
import torch
def compute_inverse_interpolation_img(weights, indices, img, b, h_i, w_i):
"""
weights: [b, h*w]
indices: [b, h*w]
img: [b, h*w, a, b, c, ...]
"""
w0, w1, w2, w3 = weights
ff_idx, cf_idx, fc_idx, cc_idx = indices
k = len(img.size()) - len(w0.size())
img_0 = w0[(...,) ... | 6b69aa5ca372a9c8f976512191d4626919d71311 | 3,649,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.