content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def finding_the_percentage(n: int, arr: List[str], query_name: str) -> str:
"""
>>> finding_the_percentage(3, ['Krishna 67 68 69', 'Arjun 70 98 63',
... 'Malika 52 56 60'], 'Malika')
'56.00'
>>> finding_the_percentage(2, ['Harsh 25 26.5 28', 'Anurag 26 28 30'],
... 'Harsh')
'26.50'
"""
... | 5,347,800 |
def mvg_logpdf_fixedcov(x, mean, inv_cov):
"""
Log-pdf of the multivariate Gaussian distribution where the determinant and inverse of the covariance matrix are
precomputed and fixed.
Note that this neglects the additive constant: -0.5 * (len(x) * log(2 * pi) + log_det_cov), because it is
irrelevant ... | 5,347,801 |
def noisy_image_data_generator(
dataset,
batch_size: int = 32,
min_value: float = 0.0,
max_value: float = 255.0,
min_noise_std: float = 0.01,
max_noise_std: float = 10.0,
random_invert: bool = False,
random_brightness: bool = False,
zoom_range: flo... | 5,347,802 |
def app_dir(app_name: str = APP_NAME) -> Path:
"""Finds the application data directory for the current platform.
If it does not exists, it creates the required directory tree.
Returns:
The path to the root app directory.
"""
if sys.platform == "win32":
path = Path.home() / "AppData... | 5,347,803 |
def make_frac_grid(frac_spacing, numrows=50, numcols=50, model_grid=None,
seed=0):
"""Create a grid that contains a network of random fractures.
Creates and returns a grid containing a network of random fractures, which
are represented as 1's embedded in a grid of 0's.
Parame... | 5,347,804 |
def generate_colors():
"""
Generate random colors.
To get visually distinct colors, generate them in HSV space then
convert to RGB.
"""
N = 30
brightness = 0.7
hsv = [(i / N, 1, brightness) for i in range(N)]
colors = list(map(lambda c: colorsys.hsv_to_rgb(*c), hsv))
perm = [15, 13, 25, 12, 19, 8, 2... | 5,347,805 |
def secant_method(f, x0, x1, iterations):
"""Return the root calculated using the secant method."""
for i in range(iterations):
f_x1 = f(x1)
x2 = x1 - f_x1 * (x1 - x0) / (f_x1 - f(x0) + 1e-9).float()
x0, x1 = x1, x2
return x2 | 5,347,806 |
def to_skopt_space(x):
"""converts the space x into skopt compatible space"""
if isinstance(x, list):
if all([isinstance(s, Dimension) for s in x]):
_space = Space(x)
elif len(x) == 1 and isinstance(x[0], tuple):
if len(x[0]) == 2:
if 'int' in x[0][0].__cl... | 5,347,807 |
def build_response(status=OK, etag='etag', modified='modified', max_age=None):
"""Make a requests.Response object suitable for testing.
Args:
status: HTTP status
exp-time: cache expire time (set to future for fresh cache, past for
stale cache (defaults to stale))
etag: etag ... | 5,347,808 |
def _do_outer_cv(searcher, X, y, outer_cv, scoring, error_score="raise", outfile=None):
"""Do outer cross-validation for nested CV
Parameters
----------
searcher : object
SearchCV object
X : numpy array
Containing features
y : numpy array
Target values or labels
oute... | 5,347,809 |
def split_list(big_list: List[T], delimiter: T) -> List[List[T]]:
"""Like string.split(foo), except for lists."""
cur_list: List[T] = []
parts: List[List[T]] = []
for item in big_list:
if item == delimiter:
if cur_list:
parts.append(cur_list)
cur_list ... | 5,347,810 |
def generate_partitions(data):
"""
Generates a random nested partition for an array of integers
:param data:
:return:
"""
if len(data) == 1:
return data
else:
mask1 = np.random.choice(len(data), np.floor(len(data)/2), replace=False)
par1 = [data[i] for i in range(le... | 5,347,811 |
def adjust_shapefile_to_aoi(data_uri, aoi_uri, output_uri, \
empty_raster_allowed = False):
"""Adjust the shapefile's data to the aoi, i.e.reproject & clip data points.
Inputs:
- data_uri: uri to the shapefile to adjust
- aoi_uri: uir to a single polygon shapefile
- ... | 5,347,812 |
def randomRectangularCluster(nRow, nCol, minL, maxL, mask=None):
"""
Create a random rectangular cluster neutral landscape model with
values ranging 0-1.
Parameters
----------
nRow : int
The number of rows in the array.
nCol : int
The number of columns in the array.
... | 5,347,813 |
def auth(credentials_file_path):
"""Shows basic usage of the Sheets API.
Prints values from a sample spreadsheet.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
... | 5,347,814 |
def add_arc():
"""
:return: arc object
"""
l_hand = GArc(200, 200, 60, 150, x=480, y=270)
l_hand.filled = True
l_hand.fill_color = "#8eded9"
r_hand = GArc(200, 200, -30, 120, x=650, y=300)
r_hand.filled = True
r_hand.fill_color = "#8eded9"
return l_hand, r_hand | 5,347,815 |
def get_data_item_or_add(results_dic, name, n_hid, epochs, horizon, timesteps):
""" Return or create a new DataItem in `results_dic` with the corresponding
metadata.
"""
if name not in results_dic:
results_dic[name] = []
found = False
for item in results_dic[name]:
if item.is_me... | 5,347,816 |
def _split_compound_loc(compound_loc):
"""Split a tricky compound location string (PRIVATE).
>>> list(_split_compound_loc("123..145"))
['123..145']
>>> list(_split_compound_loc("123..145,200..209"))
['123..145', '200..209']
>>> list(_split_compound_loc("one-of(200,203)..300"))
['one-of(200,... | 5,347,817 |
def midcurve_atm_fwd_rate(asset: Asset, expiration_tenor: str, forward_tenor: str, termination_tenor: str,
benchmark_type: str = None,
floating_rate_tenor: str = None,
clearing_house: str = None, location: PricingLocation = None, *, source: s... | 5,347,818 |
def test_primary_2():
"""
>>> db = get_connection('sqlite://')
>>> db.metadata.drop_all()
>>> class Group(Model):
... name = Field(unicode, primary_key=True)
>>> class User(Model):
... username = Field(unicode, primary_key=True)
... year = Field(int, default=30)
... g... | 5,347,819 |
def extrode_multiple_urls(urls):
""" Return the last (right) url value """
if urls:
return urls.split(',')[-1]
return urls | 5,347,820 |
def save_sms_sjjs_data(data):
"""
保存短信接收数据
@params:
data : 保存数据(必填参数) list
"""
# return 'save_sms_sjjs_data success!'
db = MySqLHelper()
sql = """INSERT IGNORE INTO t_603_sms_sjjs (ip_addr, d_time, isp_ip, sjjs_1m)
VALUES (%s,%s,%s,%s)"""
try:
... | 5,347,821 |
def build_header(cp: Config) -> str:
"""Build the email header for a SMTP email message"""
header = '\n'.join([
'From: {}'.format(cp.sender),
'To: {}'.format(''.join(cp.receiver)),
'Subject: {}\n\n'.format(cp.subject)
])
return header | 5,347,822 |
def apex_distance(r0, rc, Rc, uvec):
"""
Implements equation (E4) of TYH18
"""
R0 = rc + Rc * uvec - r0
return np.hypot(*R0) | 5,347,823 |
def test_tracker_8():
"""
Test tracking over an empty frame.
"""
peaks = {"x" : numpy.array([1.0, 2.0, 3.0]),
"y" : numpy.array([1.0, 1.0, 1.0]),
"sum" : numpy.array([4.0, 4.0, 4.0])}
empty = {"x" : numpy.array([]),
"y" : numpy.array([]),
"sum" : ... | 5,347,824 |
def copy_attr(a, b, include=(), exclude=()):
"""Copy attributes from b to a, options to only include [...] and to
exclude [...]."""
for k, v in b.__dict__.items():
if (len(include) and k not in include) or k.startswith("_") or k in exclude:
continue
else:
setattr(a, k... | 5,347,825 |
def test_span_char_start_and_char_end():
"""Test chart_start and char_end of TemporarySpan that comes from Ngrams.apply."""
ngrams = Ngrams()
sent = Sentence()
sent.text = "BC548BG"
sent.words = ["BC548BG"]
sent.char_offsets = [0]
sent.abs_char_offsets = [0]
result = list(ngrams.apply(se... | 5,347,826 |
def train(env, make_policy, make_optimizer, *,
epochs=100,
gamma=.96,
lr_inner=1., # lr for the inner loop steps
lr_outer=1., # lr for the outer loop steps
lr_value=.1, # lr for the value function estimator
lr_om=.1, # lr... | 5,347,827 |
def pixel2phase(data):
"""
converts each channel of images in the data to phase component of its 2-dimensional discrete Fourier transform.
:param data: numpy array with shape (nb_images, img_rows, img_cols, nb_channels)
:return: numpy array with same shape as data
"""
channels = data.shape... | 5,347,828 |
def take_last_while(predicate, list):
"""Returns a new list containing the last n elements of a given list, passing
each value to the supplied predicate function, and terminating when the
predicate function returns false. Excludes the element that caused the
predicate function to fail. The predicate fun... | 5,347,829 |
def main():
"""
TODO:This function can output a blurred image.
"""
old_img = SimpleImage("images/smiley-face.png")
old_img.show()
blurred_img = blur(old_img)
for i in range(4):
blurred_img = blur(blurred_img)
blurred_img.show() | 5,347,830 |
def get_notes() -> str:
"""Scrape notes and disclaimers from dashboard."""
# As of 6/5/20, the only disclaimer is "Data update weekdays at 4:30pm"
with get_firefox() as driver:
notes = []
match = re.compile('disclaimers?', re.IGNORECASE)
driver.implicitly_wait(30)
driver.get(... | 5,347,831 |
def func(num1, num2):
"""
the function will divide two given numbers
with each others and print the result
:param num1: the first number
:type num1: int
:param num2: the second number
:type num2: int
:return: the result of dividing the 2 numbers/
:rtype: float
... | 5,347,832 |
def signup_logout(request):
"""
Just wrapping the built in
"""
return logout_view(request, template_name='logged_out.html') | 5,347,833 |
def stress_rotation(stress, angle):
"""
Rotates a stress vector against a given angle.
This rotates the stress from local to the global axis sytem.
Use a negative angle to rotate from global to local system.
The stress vector must be in Voigt notation and engineering stress is used.
Parameters... | 5,347,834 |
def blue_noise(x=None, hue=None, data=None, dodge=False, orient='v', plot_width=None,
color='black', palette='tab10', size=3, centralized=False,
filename='', scaling=10):
""" Renders a *Blue Noise Plot* from the given data.
Args:
x (str in data): Variables that specify pos... | 5,347,835 |
def get_repository(auth_user: check_auth, repository_id: hug.types.text):
"""
GET: /repository/{repository_id}
Returns the CLA repository requested by UUID.
"""
return cla.controllers.repository.get_repository(repository_id) | 5,347,836 |
def _isDebug():
"""*bool* = "--debug" or "--debugger" """
return options is not None and (options.debug or options.debugger) | 5,347,837 |
def _and(mat,other,obj,m):
"""
Can only be used with '&' operator not with 'and'
Multi-column boolean matrices' values are compared with 'and' operator, meaning that 1 false value
causes whole row to be reduced to a false value
"""
if mat.BOOL_MAT:
if isinstance(other,obj):
... | 5,347,838 |
def MAP (request, resource, optimize_already_mapped_nfs=True,
migration_handler_name=None, migration_coeff=None,
load_balance_coeff=None, edge_cost_coeff=None,
time_limit=None, mip_gap_limit=None, node_limit=None, logger=None,
**migration_handler_kwargs):
"""
Starts an offline op... | 5,347,839 |
def generate_terms(reg):
""" Generate the Terms layer """
layer_generator = terms.Terms(reg)
print NodeEncoder().encode(layer_generator.build()) | 5,347,840 |
def _parcel_profile_helper(pressure, temperature, dewpt):
"""Help calculate parcel profiles.
Returns the temperature and pressure, above, below, and including the LCL. The
other calculation functions decide what to do with the pieces.
"""
# Find the LCL
press_lcl, temp_lcl = lcl(pressure[0], t... | 5,347,841 |
def write_readme_files(org_name, repo_name, filetype="rst", ignore=None, header=""):
"""Write readme files into the docs directory under their package names
"""
# We look for markdown files, as readmes on github for the strands
# repositories are written in markdown
readmes = get_repo_files(org_name... | 5,347,842 |
def extract_subject(subj, mask_name, summary_func=np.mean,
residual=False, exp_name=None):
"""Extract timeseries from within a mask, summarizing flexibly.
Parameters
----------
subj : string
subject name
mask_name : string
name of mask in data hierarchy
summa... | 5,347,843 |
def best_param_search(low=1, margin=1, func=None):
"""
Perform a binary search to determine the best parameter value.
In this specific context, the best
parameter is (the highest) value of the parameter (e.g. batch size)
that can be used to run a func(tion)
(e.g., training) successfully. Beyond ... | 5,347,844 |
def configure_plugins_plugin_uninstall(request, pk):
"""
Disables a plugin from the system
:param request:
:param pk: The primary key of the plugin to be disabled
:return:
"""
# TODO: See about pulling this out into a common methods
plugin = get_object_or_404(Plugin, pk=pk)
action = ... | 5,347,845 |
def freeze_params(model: nn.Module) -> None:
"""Disable weight updates on given model.
Args:
model (nn.Module): model
"""
for par in model.parameters():
par.requires_grad = False | 5,347,846 |
def get_supervised_timeseries_data_set(data, input_steps):
"""This function transforms a univariate timeseries into a supervised learning problem where the input consists
of sequences of length input_steps and the output is the prediction of the next step
"""
series = pd.Series(data)
data_set = pd.D... | 5,347,847 |
def _add_layer_metadata(map_layer, layer_cfg):
"""Add layer metadata.
Renders a jinja template to a temporary file location as a valid QGIS qmd
metadata file. This metadata then gets associated with the `map_layer` using
its `loadNamedMetadata` method. This metadata gets written to the project
file... | 5,347,848 |
def test_AbstractGrid_uniform_attributes(
attr,
type,
type_in_iter,
value,
abstract_grid_uniform,
):
"""
Tests that the attributes of AbstractGrid have the correct type and
values for the fixture abstract_grid_uniform.
"""
attr = getattr(abstract_grid_uniform, attr)
assert is... | 5,347,849 |
def _format_axes(ax):
"""
Adjust axis parameters.
Parameters
----------
ax : axis
Axis object (matplotlib).
"""
from matplotlib.ticker import AutoMinorLocator
# Draw major and minor tick marks inwards
ax.tick_params(
axis='both', which='both', direction='in',
... | 5,347,850 |
def load_df(name):
"""Load a pandas dataframe from csv file at results/name."""
load_name = os.path.join(here, "..", "results", name)
df = pd.read_csv(load_name)
return df | 5,347,851 |
def load_template_spectra_from_folder(parent_folder,
spectrum_identifier,
normalization=None):
"""
Load template spectrum data into a dictionary. This allows templates from
different folders to be loaded into different dictionaries.... | 5,347,852 |
def remove_screenshot_from_object(request):
"""
Removes the screenshot from being associated with a top-level object.
:param request: The Django request.
:type request: :class:`django.http.HttpRequest`
:returns: :class:`django.http.HttpResponse`
"""
analyst = request.user.username
obj ... | 5,347,853 |
def read_csv_as_dicts(
filename,
newline="",
delimiter=",",
quotechar='"',
encoding="utf-8",
remove_prefix=True,
prefix="dv.",
json_cols=CSV_JSON_COLS,
false_values=["FALSE"],
true_values=["TRUE"],
):
"""Read in CSV file into a list of :class:`dict`.
This offers an easy ... | 5,347,854 |
def update_order():
""" endpoint for updating an existing order.
---
parameters:
- name: x-access-token
in: header
type: string
required: true
- name: order_id
in: path
type: integer
required: true
- name: meal_id
in: formData
... | 5,347,855 |
def get_rewrite_outputs(wrapped_model: nn.Module,
model_inputs: Dict[str, Union[Tuple, List,
torch.Tensor]],
deploy_cfg: mmcv.Config,
run_with_backend: bool = True) -> Tuple[Any, bool]:
"""T... | 5,347,856 |
def _get_implied_dependencies(path: str) -> list:
""" Attempt to replace _get_requirements_from_file
Extracts import statements via regex.
Does not catch all import statements and its
use was rolled back.
Might still be overhauled and integrated again.
"""
_python_files = search_filename(
... | 5,347,857 |
def get_interface_breakout_param(dut,**kwargs):
"""
Author: Naveen Nag
email : naveen.nagaraju@broadcom.com
:param dut:
:param interface:
:param fields:
:return: interface breakout speed
Usage:
port.get_interface_breakout_param(dut1, 'Ethernet4')
:return - ['4x10G', 'Completed... | 5,347,858 |
def get_process_basic_window_enriched(cb, print_detail, window):
"""
Text
Args:
cb (CBCloudAPI): API object
print_detail (bool): whether to print full info to the console, useful for debugging
window (str): period to search
Returns:
process_guid of the first process in ... | 5,347,859 |
def merge_bams(bams, output_file, sort_by="index"):
"""Merge a list of .bam files into a single sorted, indexed .bam file"""
if sort_by not in ["index", "name"]:
raise ValueError(
"sort_by must be one of ['name', 'index'], not %s" % sort_by
)
# Empty bams cause samtools error, ... | 5,347,860 |
def home():
"""Home view"""
if flask.session.get('userid'):
leaderboard_players = rankedlist(
member=db.web.session.query(
models.Member).get(
flask.session['userid']))
member = db.web.session.query(
models.Member).get(
flask.se... | 5,347,861 |
def is_number(string):
""" Tests if a string is valid float. """
try:
float(string)
return True
except ValueError:
return False | 5,347,862 |
def recursive_load_gfx(path, accept=(".png", ".bmp", ".svg")):
"""
Load graphics files.
This operates on a one folder at a time basis.
Note: An empty string doesn't count as invalid,
since that represents a folder name.
"""
colorkey = c.UGLY_PURPLE
graphics = {}
for pic in os.listd... | 5,347,863 |
def inputs(filename, batch_size, n_read_threads = 3, num_epochs = None, image_width = 200, image_height=290):
"""
reads the paired images for comparison
input: name of the file to load from, parameters of the loading process
output: the two images and the label (a logit classifier for 2 class - yes or no)
"""... | 5,347,864 |
def combinedlogger(
log_name,
log_level=logging.WARN,
syslogger_format="%(levelname)s %(message)s",
consolelogger_format="%(asctime)s %(levelname)s %(message)s",
):
"""
Returns a combined SysLogHandler/StreamHandler logging instance
with formatters
"""
if "LOGLEVEL" in os.environ:
... | 5,347,865 |
def abs_p_diff(predict_table, categA='sandwich', categB='sushi'):
"""Calculates the absolute distance between two category predictions
:param predict_table: as returned by `predict_table`
:param categA: the first of two categories to compare
:param categB: the second of two categoreis to compare
:r... | 5,347,866 |
def _is_target_feature(column_names, column_mapping):
"""Assert that a feature only contains target columns if it contains any."""
column_names_set = set(column_names)
column_types = set(column['type']
for column_name, column in column_mapping.iteritems()
if column_name i... | 5,347,867 |
def server_upload_document(path: str, title: str, peer: int, document_type: str = "doc") -> \
typing.Tuple[bool, typing.Union[str, typing.Any]]:
""" Uploads document to the server and returns it (as document string). """
try:
# Trying to upload document.
# Getting api for the uploader.... | 5,347,868 |
def _default_mono_text_dataset_hparams():
"""Returns hyperparameters of a mono text dataset with default values.
See :meth:`texar.MonoTextData.default_hparams` for details.
"""
return {
"files": [],
"compression_type": None,
"vocab_file": "",
"embedding_init": Embedding.... | 5,347,869 |
def validate_engine_mode(engine_mode):
"""
Validate database EngineMode for DBCluster
Property: DBCluster.EngineMode
"""
VALID_DB_ENGINE_MODES = (
"provisioned",
"serverless",
"parallelquery",
"global",
"multimaster",
)
if engine_mode not in VALID_DB... | 5,347,870 |
def GetBlameListForV2Build(build):
""" Uses gitiles_commit from the previous build and current build to get
blame_list.
Args:
build (build_pb2.Build): All info about the build.
Returns:
(list of str): Blame_list of the build.
"""
search_builds_response = buildbucket_client.SearchV2BuildsOnBuil... | 5,347,871 |
def run_command(cmd, log_method=log.info):
"""Subprocess wrapper for capturing output of processes to logs
"""
if isinstance(cmd, str):
cmd = cmd.split(" ")
start = datetime.utcnow()
log_method("Starting run_command for: {}".format(" ".join([str(x) for x in cmd])))
p = sp.Popen(cmd, bufs... | 5,347,872 |
def jar(state: State, fail: Fail):
"""
Store a function by a name
"""
(identifier, (code, rest)) = state.infinite_stack()
if identifier.tag != "atom":
fail(f"{identifier} is not an atom")
if code.tag not in ["code", "native"]:
fail(f"{code} is not code")
if code.tag == "cod... | 5,347,873 |
def _write_info(hass, auth):
"""Write auth info for specified mode.
Pass in None for data to remove authentication for that mode.
"""
path = hass.config.path(AUTH_FILE)
mode = get_mode(hass)
if os.path.isfile(path):
with open(path) as file:
content = json.load(file)
els... | 5,347,874 |
def insert_new_post(post_arg_set):
"""
insert new post into redis
"""
api, post_data, acct_data, page_id, config = post_arg_set
try:
post_id = post_data['id'] if post_data.has_key('id') else None
except Exception as e:
log.error( e )
else:
# parse date
if post_data.has_key('created_tim... | 5,347,875 |
def get_ideology_lookup(schema):
"""
getter function to enable ideology lookup for a concept
input: group schema
output: generator object of ideology-list(concept) pairs
(TODO: will require a check for correct format of group schema)
"""
for ideology, attribute in schema.items():
... | 5,347,876 |
def existant_file(filepath:str):
"""Argparse type, raising an error if given file does not exists"""
if not os.path.exists(filepath):
raise argparse.ArgumentTypeError(
" file {} doesn't exists".format(C_FILE + filepath + C_ENDC)
)
return filepath | 5,347,877 |
def get_daily_activity(p_sap_date: str) -> dict:
""" Returns activities on the given date """
fiori_url = config.CONSTANTS["ECZ_DAHA_DAILY_URL"] + "?date=" + p_sap_date
resp = requests.get(
fiori_url,
auth=HTTPBasicAuth(
config.CONSTANTS["ECZ_DAHA_USER"],
config.CONST... | 5,347,878 |
def load_example_abc(title: Optional[str] = None) -> str:
"""Load a random example ABC if `title` not provided.
Case ignored in the title.
"""
if title is None:
import random
k = random.choice(list(examples))
else:
k = title.lower()
abc = examples.get(k)
if abc is ... | 5,347,879 |
def load_config(config_file_path):
"""
Load the config ini, parse settings to WORC
Args:
config_file_path (String): path of the .ini config file
Returns:
settings_dict (dict): dict with the loaded settings
"""
if not os.path.exists(config_file_path):
e = f'File {config_... | 5,347,880 |
def get_last_confirmed() -> Dict:
"""
This function get the last day saved on mongodb and
show us the confirmed cases and the accumulated.
- The country is the only needed path parameter.
"""
date = db.find({}, {"date": 1, "_id": 0}).sort("date", -1).limit(1)
date = list(date)
pipeline ... | 5,347,881 |
def plot_modes(Nsq, depth, nmodes, wmodes, pmodes, rmodes):
"""Plot Brunt-Vaisala (buoyancy) frequency profile and 3 sets of modes
(vertical velocity, horizontal velocity, and vertical density) in 4 panes.
:arg Nsq: Brunt-Vaisala (buoyancy) frequencies squared in [1/s^2]
:type Nsq: :class:`numpy.ndarra... | 5,347,882 |
def _newNode( cls, named ):
"""Construct new instance of cls, set proper color, and add to objects"""
if not scene.visible:
scene.visible = 1
if not [k for k in ('color','red','green','blue') if k in named]:
named['color'] = scene.foreground
if 'display' in named:
target = named[... | 5,347,883 |
def index_f_and_f(dump_pk, user_pk):
"""
Run all plugin for a new index on dask
"""
dask_client = Client(settings.DASK_SCHEDULER_URL)
fire_and_forget(dask_client.submit(unzip_then_run, dump_pk, user_pk)) | 5,347,884 |
def MplJs():
"""
Serves the generated matplotlib javascript file. The content
is dynamically generated based on which toolbar functions the
user has defined. Call `FigureManagerWebAgg` to get its
content.
"""
js_content = FigureManagerWebAgg.get_javascript()
resp = make_response(js_con... | 5,347,885 |
def load_jupyter_server_extension(nbapp):
"""Load the Jupyter server extension.
"""
config = JupyterLabGit(config=nbapp.config)
git = Git(nbapp.web_app.settings['contents_manager'], config)
nbapp.web_app.settings["git"] = git
setup_handlers(nbapp.web_app) | 5,347,886 |
def VVSS2021_fig4_plot(data, model, sizes=fig_sizes, cmaps=colormaps):
"""
Create and save a plot of the results from the linear regression reaction time model
:param data: the data frame
:param model: the fitted reaction time model
:param cmaps: a dictionary of colormaps
:param sizes: a diction... | 5,347,887 |
def end_db_session(error):
"""Commit any changes or rollback on failure."""
if hasattr(g, "db_session"):
db_session = g.db_session
try:
if error:
raise error
db_session.commit()
except SQLAlchemyError:
db_session.rollback()
... | 5,347,888 |
def stat(noten):
""" Berechne Mittelwert, Median, min, max, oberes und unteres Quantil """
minimum = round(min(noten), 2)
maximum = round(max(noten), 2)
_median = median(noten)
_mittelwert = mittelwert(noten)
[unteres_quartil, oberes_quartil] = quartile(noten)
return [minimum, unteres_quarti... | 5,347,889 |
def check_order_type_enabled(order_type):
"""Assert that the input order type is enabled in the settings
Parameters
----------
order_type: oseoserver.constants.OrderType
Enumeration value
"""
generic_config = utilities.get_generic_order_config(order_type)
if not generic_config.get... | 5,347,890 |
def translation_activate_block(function=None, language=None):
"""
Activate language only for one method or function
"""
def _translation_activate_block(function):
def _decorator(*args, **kwargs):
tmp_language = translation.get_language()
try:
translation.... | 5,347,891 |
def exportItems():
"""
Export the API items into form for use in another script.
"""
infile=open(api_item_filename,'w')
#write function lead in
infile.write("# Auto-generated file (see get-api_items.py)\n#\n\ndef get_mapped_items():\n\tmapped_wiki_inline_code = dict()\n" )
for ... | 5,347,892 |
def _loaded_schema_collections(schema_file_relative_dir) -> SchemaCollectionManager:
"""A loaded ``SchemaCollectionManager`` object, but this should never be modified. This object manages ``Schema``
objects corresponding to ``tests/{datasets,formats,licenses}.yaml``. Note that these are not necessarily the same... | 5,347,893 |
def dag(name=None, child_tasks=None, edges=None, target=None):
"""
Create a DAG task
Args:
name (str): Name for the task
child_tasks (list [Task]): Child tasks within this dag
edges (list [tuple (Ref, Ref)]): List of tuples of ref(Task).
Each ... | 5,347,894 |
async def async_validate_pdf_signature(
embedded_sig: EmbeddedPdfSignature,
signer_validation_context: ValidationContext = None,
ts_validation_context: ValidationContext = None,
ac_validation_context: ValidationC... | 5,347,895 |
def get_one_to_many_foreign_key_column_name(model, name):
"""
Returns the constituent column names for the foreign key on the remote
table of the one-to-many relationship specified by name.
Args:
model (class or object): The given model class or model instance.
name (string): The name o... | 5,347,896 |
def parse_args():
""" parse the args from the cli """
logger.debug("parse_args()")
parser = argparse.ArgumentParser(description='Check the status of dnsmasq')
parser.add_argument('-v', '--verbose', action='store_true', default=None, help='Verbose?')
parser.add_argument('--url', default='www.redhat.... | 5,347,897 |
def parse_args(args):
"""Parse command line parameters
Args:
args ([str]): command line parameters as list of strings
Returns:
:obj:`argparse.Namespace`: command line parameters namespace
"""
parser = argparse.ArgumentParser(
description="Just a Fibonacci demonstration")
pa... | 5,347,898 |
def screen_handler():
"""
Prints to stdout with a well formated style:
[CALLER_PARENT/CALLER @ TIME]: text - Output created by writer program
"""
global to_print
while True:
if to_print != []:
if to_print[0][1] == "!stop":
print(r'Closing Print function...', e... | 5,347,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.