content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import os
def dwritef2(obj, path):
"""The dwritef2() function writes the object @p obj to the Python
pickle file whose path is pointed to by @p path. Non-existent
directories of @p path are created as necessary.
@param obj Object to write, as created by e.g. dpack()
@param path Path of output file
@ret... | 5816a8bcacbc45c3931ee9b217c1c579883caf12 | 3,647,600 |
def calculate_area(geometry):
"""
Calculate geometry area
:param geometry: GeoJSON geometry
:return: the geometry area
"""
coords = get_coords_from_geometry(
geometry, ["Polygon", "MultiPolygon"], raise_exception=False
)
if get_input_dimensions(coords) >= 4:
areas = l... | 6bc08b57c3416c14f5eca00acbe914a06053b81e | 3,647,601 |
from pathlib import Path
import re
def read_prb(file):
"""
Read a PRB file and return a ProbeGroup object.
Since PRB do not handle contact shape then circle of 5um are put.
Same for contact shape a dummy tip is put.
PRB format do not contain any information about the channel of the probe
Onl... | f46c8befbd348c1473867d5c7475911ce960830c | 3,647,602 |
import os
import pathlib
def alt_credits():
""" Route for alt credits page. Uses json list to generate page body """
alternate_credits = tasks.json_list(os.path.join(pathlib.Path(__file__).parent.absolute(),'static/alt_credits.json'))
return render_template('alt_credits.html',title='collegeSMART - Alterna... | 2ad6c1b374153c79efbd0b71d36c1c5771e30795 | 3,647,603 |
def CreateNode(parent, node_type, position, wx_id):
""" Create an instance of a node associated with the specified name.
:param parent: parent of the node object (usually a wx.Window)
:param node_type: type of node from registry - the IDName
:param position: default position for the node
:param wx_... | d0a68d584bde29ef47b8e1a1a3129261cbdb6df4 | 3,647,604 |
import json
def decode_json_content(content):
"""
Decodes a given string content to a JSON object
:param str content: content to be decoded to JSON.
:return: A JSON object if the string could be successfully decoded and None otherwise
:rtype: json or None
"""
try:
return json.loads... | b0a65734876fd012feb89c606a9c7a0dced866b6 | 3,647,605 |
def plot_dist(noise_feats, label=None, ymax=1.1, color=None, title=None, save_path=None):
"""
Kernel density plot of the number of noisy features included in explanations,
for a certain number of test samples
"""
if not any(noise_feats): # handle special case where noise_feats=0
noise_feat... | 33623c77434b936a730064890a80d34d1f5ac143 | 3,647,606 |
import chunk
def simple_simulate(choosers, spec, nest_spec,
skims=None, locals_d=None,
chunk_size=0, custom_chooser=None,
log_alt_losers=False,
want_logsums=False,
estimator=None,
trace_label=None, ... | 92e06a6b57add21e0b3bd1fcd537d6818786d19c | 3,647,607 |
def state(predicate):
"""DBC helper for reusable, simple predicates for object-state tests used in both preconditions and postconditions"""
@wraps(predicate)
def wrapped_predicate(s, *args, **kwargs):
return predicate(s)
return wrapped_predicate | 0c9116ccd3fba1b431ce0a492bc6337406954cd8 | 3,647,608 |
import math
def dpp(kernel_matrix, max_length, epsilon=1E-10):
"""
Our proposed fast implementation of the greedy algorithm
:param kernel_matrix: 2-d array
:param max_length: positive int
:param epsilon: small positive scalar
:return: list
"""
item_size = kernel_matrix.shape[0]
cis... | fd6c141f1a2f80971ed8e6e5d36b0d074bcdc4b9 | 3,647,609 |
def adjust_image_resolution(data):
"""Given image data, shrink it to no greater than 1024 for its larger
dimension."""
inputbytes = cStringIO.StringIO(data)
output = cStringIO.StringIO()
try:
im = Image.open(inputbytes)
im.thumbnail((240, 240), Image.ANTIALIAS)
# co... | d2fedb68e79b1aed0ce0a209d43bb6b16d492f16 | 3,647,610 |
import sys
import time
def timing_function():
"""
There's a better timing function available in Python 3.3+
Otherwise use the old one.
TODO: This could be a static analysis at the top of the module
"""
if sys.version_info[0] >= 3 and sys.version_info[1] >= 3:
return time.monotonic()
... | 0de5d8ed8eb93617cec6feef47bf51441ef9a73e | 3,647,611 |
from datetime import datetime
def parse_date(txt):
""" Returns None or parsed date as {h, m, D, M, Y}. """
date = None
clock = None
for word in txt.split(' '):
if date is None:
try:
date = datetime.strptime(word, "%d-%m-%Y")
continue
exc... | 80660673d6b4179fa7b4907983ed84bc41c4189b | 3,647,612 |
import os
import six
def diff_configurations(model_config, bench_config, model_bundle, bench_bundle):
"""
Description
Args:
model_config: a dictionary with the model configuration data
bench_config: a dictionary with the benchmark configuration data
model_bundle: a LIVVkit model b... | a756c9694e50a8ace29e6c518e22fa11f3744b89 | 3,647,613 |
import six
import tarfile
import zipfile
import os
import shutil
def _extract_archive(file_path, path='.', archive_format='auto'):
"""Extracts an archive if it matches tar, tar.gz, tar.bz, or zip formats.
Arguments:
file_path: path to the archive file
path: path to extract the archive file
... | aba0d2e47c19c7d11fc8eefbd4c1f110df0a5f4e | 3,647,614 |
def calc_angle(m, n):
"""
Calculate the cosθ,
where θ is the angle between 2 vectors, m and n.
"""
if inner_p_s(m, n) == -1:
print('Error! The 2 vectors should belong on the same space Rn!')
elif inner_p_s(m,n) == 0:
print('The cosine of the two vectors is 0, so th... | e0361370a9479eaf7e706673d71c88d25c110473 | 3,647,615 |
def Seuil_var(img):
"""
This fonction compute threshold value. In first the image's histogram is calculated. The threshold value is set to the first indexe of histogram wich respect the following criterion : DH > 0, DH(i)/H(i) > 0.1 , H(i) < 0.01 % of the Norm.
In : img : ipl Image : image to treated
... | 435e8eeca0ddff618a2491b0529f1252d8566721 | 3,647,616 |
def convert_numpy(file_path, dst=None, orient='row', hold=False, axisf=False, *arg):
"""
Extract an array of data stored in a .npy file or DATABLOCK
Parameters
---------
file_path : path (str)
Full path to the file to be extracted.
dst : str
Full path to the file wh... | 2ac1b25277b466cdcd5c6d78844a7bccee9817a6 | 3,647,617 |
def index():
"""Every time the html page refreshes this function is called.
Checks for any activity from the user (setting an alarm, deleting an alarm,
or deleting a notification)
:return: The html template with alarms and notifications added
"""
notification_scheduler.run(blocking=False)
... | 845ba53918bb44d3170a2e93e93346212ccc1247 | 3,647,618 |
import json
import time
def check_icinga_should_run(state_file: str) -> bool:
"""Return True if the script should continue to update the state file, False if the state file is fresh enough."""
try:
with open(state_file) as f:
state = json.load(f)
except Exception as e:
logger.e... | d508f000eb28da42b43049f49ac180702d49bdc7 | 3,647,619 |
def ln_new_model_to_gll(py, new_flag_dir, output_dir):
"""
make up the new gll directory based on the OUTPUT_MODEL.
"""
script = f"{py} -m seisflow.scripts.structure_inversion.ln_new_model_to_gll --new_flag_dir {new_flag_dir} --output_dir {output_dir}; \n"
return script | acdf28cbc2231bd2f33ae418136ce7da0fce421f | 3,647,620 |
def deserialize_item(item: dict):
"""Deserialize DynamoDB item to Python types.
Args:
item: item to deserialize
Return: deserialized item
"""
return {k: DDB_DESERIALIZER.deserialize(v) for k, v in item.items()} | 451d97ed656982b5b8df4fb2178051560cb5d8bd | 3,647,621 |
def good_result(path_value, pred, source=None, target_path=''):
"""Constructs a JsonFoundValueResult where pred returns value as valid."""
source = path_value.value if source is None else source
return jp.PathValueResult(pred=pred, source=source, target_path=target_path,
path_value=pat... | 2cfeab7df8b52d64cabad973bffeb1723d9e3215 | 3,647,622 |
def bot_properties(bot_id):
"""
Return all available properties for the given bot. The bot id should be
available in the `app.config` dictionary.
"""
bot_config = app.config['BOTS'][bot_id]
return [pd[0] for pd in bot_config['properties']] | a7922173d31fbb0d6b20ef1112cef6f88fe4749a | 3,647,623 |
def find_path(ph_tok_list, dep_parse, link_anchor, ans_anchor, edge_dict, ph_dict):
"""
:param dep_parse: dependency graph
:param link_anchor: token index of the focus word (0-based)
:param ans_anchor: token index of the answer (0-based)
:param link_category: the category of the current focus link
... | 51b621f1f1cdffd645b1528884603a383abf12a5 | 3,647,624 |
import os
def get_theme_section_directories(theme_folder:str, sections:list = []) -> list:
"""Gets a list of the available sections for a theme
Explanation
-----------
Essentially this function goes into a theme folder (full path to a theme), looks for a folder
called sections and returns a list... | 5e024546bbf878e0954660d4bd5adb765ffd7e43 | 3,647,625 |
import logging
def download_video_url(
video_url: str,
pipeline: PipelineContext,
destination="%(title)s.%(ext)s",
progress=ProgressMonitor.NULL,
):
"""Download a single video from the ."""
config = pipeline.config
logger = logging.getLogger(__name__)
logger.info("Starting video downl... | f3546d929fa6c976479fe86b945bb87279a22341 | 3,647,626 |
def get_block_name(source):
"""Get block name version from source."""
url_parts = urlparse(source)
file_name = url_parts.path
extension = file_name.split(".")[-1]
new_path = file_name.replace("." + extension, "_block." + extension)
new_file_name = urlunparse(
(
url_parts.s... | ae2792a4c56baaa9045ed49961ad1c5029191d3d | 3,647,627 |
import token
def int_to_symbol(i):
""" Convert numeric symbol or token to a desriptive name.
"""
try:
return symbol.sym_name[i]
except KeyError:
return token.tok_name[i] | 6f939d359dd92961f199dfd412dced3ecaef3a60 | 3,647,628 |
def debugger(parser, token):
"""
Activates a debugger session in both passes of the template renderer
"""
pudb.set_trace()
return DebuggerNode() | a1ab924ee2ccb1e2389c7432444a829e70a7392b | 3,647,629 |
def cranimp(i, s, m, N):
"""
Calculates the result of c_i,s^dag a_s acting on an integer m. Returns the new basis state and the fermionic prefactor.
Spin: UP - s=0, DOWN - s=1.
"""
offi = 2*(N-i)-1-s
offimp = 2*(N+1)-1-s
m1 = flipBit(m, offimp)
if m1<m:
m2=flipBit(m1, offi)
if m2>m1:
prefactor = prefac... | aa64f6f5e9d0e596a801d854baf4e222e2f2192e | 3,647,630 |
def _can_beeify():
""" Determines if the random chance to beeify has occured """
return randint(0, 12) == 0 | c79a116a6d1529d69f88c35a1264735d475b26d4 | 3,647,631 |
def get_object_classes(db):
"""return a list of all object classes"""
list=[]
for item in classinfo:
list.append(item)
return list | e95676f19f3bf042a5f531d708f2e12a0ab3813f | 3,647,632 |
import os
import _sha256
import itertools
def load_arviz_data(dataset=None, data_home=None):
"""Load a local or remote pre-made dataset.
Run with no parameters to get a list of all available models.
The directory to save to can also be set with the environement
variable `ARVIZ_HOME`. The checksum of... | 8cf1020c5e9e9aaa8dbd184ddc9f400a7caaef5f | 3,647,633 |
def get_ax(rows=1, cols=1, size=8):
"""Return a Matplotlib Axes array to be used in
all visualizations in the notebook. Provide a
central point to control graph sizes.
Change the default size attribute to control the size
of rendered images
"""
_, ax = plt.subplots(rows, cols, figsize=(size... | 0a79458ad335856198d5208071581685cd7c34a0 | 3,647,634 |
from typing import Mapping
from typing import Any
import os
import json
def prepare_ablation_from_config(config: Mapping[str, Any], directory: str, save_artifacts: bool):
"""Prepare a set of ablation study directories."""
metadata = config['metadata']
optuna_config = config['optuna']
ablation_config =... | c084361ac51102eaf84e3016f3a0c50f1ef9313f | 3,647,635 |
def spin_coherent(j, theta, phi, type='ket'):
"""Generates the spin state |j, m>, i.e. the eigenstate
of the spin-j Sz operator with eigenvalue m.
Parameters
----------
j : float
The spin of the state.
theta : float
Angle from z axis.
phi : float
Angle from x axis... | e64d207aeb27a5cf2ccdb1dff13da52be294c903 | 3,647,636 |
from operator import add
def vgg_upsampling(classes, target_shape=None, scale=1, weight_decay=0., block_name='featx'):
"""A VGG convolutional block with bilinear upsampling for decoding.
:param classes: Integer, number of classes
:param scale: Float, scale factor to the input feature, varing from 0 to 1
... | 9c372520adc3185a8b61b57ed73cc303f47c8275 | 3,647,637 |
def show_toolbar(request):
"""Determine if toolbar will be displayed."""
return settings.DEBUG | d29dfd9c6e29509a882c0654802d993c0928bd22 | 3,647,638 |
def compute_metrics(logits, labels, weights):
"""Compute summary metrics."""
loss, weight_sum = compute_weighted_cross_entropy(logits, labels, weights)
acc, _ = compute_weighted_accuracy(logits, labels, weights)
metrics = {
'loss': loss,
'accuracy': acc,
'denominator': weight_sum,
}
return... | c969b2aadf9b16b1c26755dc1db4f1f24faa2c11 | 3,647,639 |
def start_session(web_session=None):
"""Starts a SQL Editor Session
Args:
web_session (object): The web_session object this session will belong to
Returns:
A dict holding the result message
"""
new_session = SqleditorModuleSession(web_session)
result = Response.ok("New SQL Edit... | 596603e5bc1d21df95728b4797a64cb4ff78fa2a | 3,647,640 |
async def error_middleware(request: Request, handler: t.Callable[[Request], t.Awaitable[Response]]) -> Response:
"""logs an exception and returns an error message to the client
"""
try:
return await handler(request)
except Exception as e:
logger.exception(e)
return json_response(... | 28748bd2018a0527ef740d8bed9c74983900e655 | 3,647,641 |
def init_mobility_accordion():
"""
Initialize the accordion for mobility tab.
Args: None
Returns:
mobility_accordion (object): dash html.Div that contains individual accordions
"""
accord_1 = init_accordion_element(
title="Mobility Index",
id='id_mobility_index',
... | 25c5475e8ea972d057d230526d8dcc82b27d8ee0 | 3,647,642 |
def per_image_whiten(X):
""" Subtracts the mean of each image in X and renormalizes them to unit norm.
"""
num_examples, height, width, depth = X.shape
X_flat = X.reshape((num_examples, -1))
X_mean = X_flat.mean(axis=1)
X_cent = X_flat - X_mean[:, None]
X_norm = np.sqrt( np.sum( X_cent * X... | f831860c3697e6eac637b2fb3e502570fa4f31af | 3,647,643 |
def fill_defaults(data, vals) -> dict:
"""Fill defaults if source is not present"""
for val in vals:
_name = val['name']
_type = val['type'] if 'type' in val else 'str'
_source = val['source'] if 'source' in val else _name
if _type == 'str':
_default = val['default']... | aa5df5bca76f1eaa426bf4e416a540fb725eb730 | 3,647,644 |
def static_shuttle_between():
"""
Route endpoint to show real shuttle data within a certain time range at once.
Returns:
rendered website displaying all points at once.
Example:
http://127.0.0.1:5000/?start_time=2018-02-14%2015:40:00&end_time=2018-02-14%2016:02:00
"""
start_tim... | eea24bb0abe90fe7b708ff8a9c73c2795f07865a | 3,647,645 |
def read_data(inargs, infiles, ref_cube=None):
"""Read data."""
clim_dict = {}
trend_dict = {}
for filenum, infile in enumerate(infiles):
cube = iris.load_cube(infile, gio.check_iris_var(inargs.var))
if ref_cube:
branch_time = None if inargs.branch_times[filenum] == 'default... | a3ffc2172394fe5a44e8239152a3f7b7ee660559 | 3,647,646 |
import json
async def create_account(*, user):
"""
Open an account for a user
Save account details in json file
"""
with open("mainbank.json", "r") as f:
users = json.load(f)
if str(user.id) in users:
return False
else:
users[str(user.id)] = {"wallet": 0, "bank": 0}... | 0e1aaccfd0c9cda6238ba8caa90e80979540f2e8 | 3,647,647 |
import ntpath
import genericpath
def commonpath(paths):
"""Given a sequence of path names, returns the longest common sub-path."""
if not paths:
raise ValueError('commonpath() arg is an empty sequence')
if isinstance(paths[0], bytes):
sep = b'\\'
altsep = b'/'
curdir = b'... | a8ef082e2944138ea08d409e273d724fd5d489eb | 3,647,648 |
from .slicing import sanitize_index
from functools import reduce
from operator import mul
import tokenize
from re import M
def reshape(x, shape):
""" Reshape array to new shape
This is a parallelized version of the ``np.reshape`` function with the
following limitations:
1. It assumes that the array... | 2e8ed79f95319e02cacf78ce790b6dc550ac4e29 | 3,647,649 |
def get_state(module_instance, incremental_state, key_postfix):
""" Helper for extracting incremental state """
if incremental_state is None:
return None
full_key = _get_full_key(module_instance, key_postfix)
return incremental_state.get(full_key, None) | b3ba8f10fd26ed8878cb608076873cad52a19841 | 3,647,650 |
def get_lenovo_urls(from_date, to_date):
"""
Extracts URL on which the data about vulnerabilities are available.
:param from_date: start of date interval
:param to_date: end of date interval
:return: urls
"""
lenovo_url = config['vendor-cve']['lenovo_url']
len_p = LenovoMainPageParser(l... | 503f078d9a4b78d60792a2019553f65432c21320 | 3,647,651 |
def normalize_batch_in_training(x, gamma, beta,
reduction_axes, epsilon=1e-3):
"""
Computes mean and std for batch then apply batch_normalization on batch.
# Arguments
x: Input tensor or variable.
gamma: Tensor by which to scale the input.
beta: Tens... | 2c1cc9368438cbd62d48c71da013848068a7664e | 3,647,652 |
from ase.build import get_deviation_from_optimal_cell_shape, find_optimal_cell_shape
def supercell_scaling_by_target_atoms(structure, min_atoms=60, max_atoms=120,
target_shape='sc', lower_search_limit=-2, upper_search_limit=2,
verbose=False):... | 24d7db41a0f270b037eac411fca3f5a6d9a4d8a7 | 3,647,653 |
def itemAPIEndpoint(categoryid):
"""Return page to display JSON formatted information of item."""
items = session.query(Item).filter_by(category_id=categoryid).all()
return jsonify(Items=[i.serialize for i in items]) | 33abd39d7d7270fe3b040c228d11b0017a8b7f83 | 3,647,654 |
def command(settings_module,
command,
bin_env=None,
pythonpath=None,
*args, **kwargs):
"""
run arbitrary django management command
"""
da = _get_django_admin(bin_env)
cmd = "{0} {1} --settings={2}".format(da, command, settings_module)
if pythonpat... | 6f7f4193b95df786d6c1540f4c687dec89cf01a6 | 3,647,655 |
def read_input(fpath):
"""
Read an input file, and return a list of tuples, each item
containing a single line.
Args:
fpath (str): File path of the file to read.
Returns:
list of tuples:
[ (xxx, xxx, xxx) ]
"""
with open(fpath, 'r') as f:
data = [... | ceeb418403bef286eda82ba18cd0ac8e4899ea4f | 3,647,656 |
import os
def get_parquet_lists():
"""
Load all .parquet files and get train and test splits
"""
parquet_files = [f for f in os.listdir(
Config.data_dir) if f.endswith(".parquet")]
train_files = [f for f in parquet_files if 'train' in f]
test_files = [f for f in parquet_files if 'test... | 2e533b4526562d70aab1c2ee79f1bebb3e3652af | 3,647,657 |
def find_level(key):
"""
Find the last 15 bits of a key, corresponding to a level.
"""
return key & LEVEL_MASK | 30c454220e6dac36c1612b5a1a5abf53a7a2911c | 3,647,658 |
def _whctrs(anchor):
"""return width, height, x center, and y center for an anchor (window)."""
w = anchor[2] - anchor[0] + 1
h = anchor[3] - anchor[1] + 1
x_ctr = anchor[0] + 0.5 * (w - 1)
y_ctr = anchor[1] + 0.5 * (h - 1)
return w, h, x_ctr, y_ctr | e1a6ff1745aac77e80996bfbb98f42c18af059d7 | 3,647,659 |
def filter_tiddlers(tiddlers, filters, environ=None):
"""
Return a generator of tiddlers resulting from filtering the provided
iterator of tiddlers by the provided filters.
If filters is a string, it will be parsed for filters.
"""
if isinstance(filters, basestring):
filters, _ = parse_... | 25c86fdcb6f924ce8349d45b999ebe491c4b6299 | 3,647,660 |
def apply_move(board_state, move, side):
"""Returns a copy of the given board_state with the desired move applied.
Args:
board_state (3x3 tuple of int): The given board_state we want to apply the move to.
move (int, int): The position we want to make the move in.
side (int): The side we... | b47da6ddab3bd1abf99ee558471a3696e46b8352 | 3,647,661 |
import copy
from functools import reduce
def merge(dicts, overwrite=False, append=False, list_of_dicts=False):
""" merge dicts,
starting with dicts[1] into dicts[0]
Parameters
----------
dicts : list[dict]
list of dictionaries
overwrite : bool
if true allow overwriting of curr... | fdbde1c83f2fbcb74be5c4fb1376af4981655ad7 | 3,647,662 |
import re
def compute_delivery_period_index(frequency = None,
delivery_begin_dt_local = None,
delivery_end_date_local = None,
tz_local = None,
profile ... | 4eb47c857a235a7db31624dc78c83f291f0ba67a | 3,647,663 |
def make_proxy(global_conf, address, allowed_request_methods="",
suppress_http_headers=""):
"""
Make a WSGI application that proxies to another address:
``address``
the full URL ending with a trailing ``/``
``allowed_request_methods``:
a space seperated list of request m... | 054bcce2d10db2947d5322283e4e3c87328688cb | 3,647,664 |
import unittest
def test():
"""Runs the unit tests without test coverage."""
tests = unittest.TestLoader().discover('eachday/tests',
pattern='test*.py')
result = unittest.TextTestRunner(verbosity=2).run(tests)
if result.wasSuccessful():
return 0
r... | 3d8fcfada7309e62215fd2b3a1913ed51d5f14f8 | 3,647,665 |
async def save_training_result(r: dependency.TrainingResultHttpBody):
"""
Saves the model training statistics to the database. This method is called only by registered dataset
microservices.
:param r: Training Result with updated fields sent by dataset microservice
:return: {'status': 'success'} i... | 60302a3053a8be3781ad8da9e75b05aed85a5b06 | 3,647,666 |
def sort2nd(xs):
"""Returns a list containing the same elements as xs, but sorted by their
second elements."""
xs.sort(cmp2nd)
return xs | 9b9ccef6794db2cfaa31492eeddb0d6344ff30e5 | 3,647,667 |
def is_one_of_type(val, types):
"""Returns whether the given value is one of the given types.
:param val: The value to evaluate
:param types: A sequence of types to check against.
:return: Whether the given value is one of the given types.
"""
result = False
val_type = type(val)
for tt ... | 4bda5ebc41aa7377a93fdb02ce85c50b9042e2c1 | 3,647,668 |
import os
import fnmatch
import re
def load_qadata(qa_dir):
"""
:param qa_dir: the file path of the provided QA dataset, eg: /data/preprocessed_data_10k/test;
:return: the dictionary of the QA dataset, for instance QA_1_;
"""
print("begin_load_qadata")
qa_set = {}
# os.walk: generates the ... | 3f0060d34ca47951efb29388f723fe75bfaa875a | 3,647,669 |
def get_online(cheat_id):
"""Получение онлайна чита
---
consumes:
- application/json
parameters:
- in: path
name: cheat_id
type: string
description: ObjectId чита в строковом формате
responses:
200:
desc... | bcfc0c44a0284ad298f533bdb8afd1e415be13b8 | 3,647,670 |
def grpc_client_connection(svc: str = None, target: str = None, session: Session = None) -> Channel:
"""
Create a new GRPC client connection from a service name, target endpoint and session
@param svc: The name of the service to which we're trying to connect (ex. blue)
@param target: The endpoint, assoc... | fc805b15c1d94bcde5ac4eacfc72d854f860f95f | 3,647,671 |
def aqi(pm25):
"""AQI Calculator
Calculates AQI from PM2.5 using EPA formula and breakpoints from:
https://www.airnow.gov/sites/default/files/2018-05/aqi-technical
-assistance-document-may2016.pdf
Args:
- pm25 (int or float): PM2.5 in ug/m3
"""
if pm25 < 0:
raise ValueErr... | 199066221d91a527ea3c2f3f67a994eb13b7a708 | 3,647,672 |
from django.db import connection
def require_lock(model, lock='ACCESS EXCLUSIVE'):
"""
Decorator for PostgreSQL's table-level lock functionality
Example:
@transaction.commit_on_success
@require_lock(MyModel, 'ACCESS EXCLUSIVE')
def myview(request)
...
PostgreSQL's... | 1cfa74246ddbde9840f5e519e1481cd8773fb038 | 3,647,673 |
def welcome():
"""List all available api routes."""
# Set the app.route() decorator for the "/api/v1.0/precipitation" route
return (
f"Available Routes:<br/>"
f"/api/v1.0/names<br/>"
f"/api/v1.0/precipitation"
) | 74d6509fede66bf4243b9e4a4e107391b13aef16 | 3,647,674 |
def pbootstrap(data, R, fun, initval = None, ncpus = 1):
"""
:func pbootstrap: Calls boot method for R iteration in parallel and gets estimates of y-intercept
and slope
:param data: data - contains dataset
:param R: number of iterations
:param func: optim - function to get estimate of y-intercept and slo... | f5d1b523969735ef30873f593472e79f8399622c | 3,647,675 |
def _el_orb(string):
"""Parse the element and orbital argument strings.
The presence of an element without any orbitals means that we want to plot
all of its orbitals.
Args:
string (str): The element and orbitals as a string, in the form
``"C.s.p,O"``.
Returns:
dict: T... | 654d085347913bca2fd2834816b988ea81ab7164 | 3,647,676 |
import numpy
def create_LOFAR_configuration(antfile: str, meta: dict = None) -> Configuration:
""" Define from the LOFAR configuration file
:param antfile:
:param meta:
:return: Configuration
"""
antxyz = numpy.genfromtxt(antfile, skip_header=2, usecols=[1, 2, 3], delimiter=",")
nants = a... | 0ed07f1cdd0ef193e51cf88d336cbb421f6ea248 | 3,647,677 |
def fmla_for_filt(filt):
"""
transform a set of column filters
from a dictionary like
{ 'varX':['lv11','lvl2'],...}
into an R selector expression like
'varX %in% c("lvl1","lvl2")' & ...
"""
return ' & '.join([
'{var} %in% c({lvls})'.format(
var=k,
... | 149d23822a408ad0d96d7cefd393b489b4b7ecfa | 3,647,678 |
def sfen_board(ban):
"""Convert ban (nrow*nrow array) to sfen string
"""
s = ''
num = 0
for iy in range(nrow):
for ix in range(nrow):
i = iy*nrow + ix
if ban[i]:
if num:
s += str(num)
num = 0
s +=... | 55bf08c39457278ff8aaca35f1dd5f3fd6955590 | 3,647,679 |
import time
def join_simple_tables(G_df_dict, G_data_info, G_hist, is_train, remain_time):
"""
获得G_df_dict['BIG']
"""
start = time.time()
if is_train:
if 'relations' in G_data_info:
G_hist['join_simple_tables'] = [x for x in G_data_info['relations'] if
... | ba625cee3d4ede6939b8e12ce734f85325044349 | 3,647,680 |
def create_epochs(data, events_onsets, sampling_rate=1000, duration=1, onset=0, index=None):
"""
Epoching a dataframe.
Parameters
----------
data : pandas.DataFrame
Data*time.
events_onsets : list
A list of event onsets indices.
sampling_rate : int
Sampling rate (sam... | d173b04d5e5835509a41b3ac2288d0d01ff54784 | 3,647,681 |
from typing import Type
def is_equal_limit_site(
site: SiteToUse, limit_site: SiteToUse, site_class: Type[Site]
) -> None:
"""Check if site is a limit site."""
if site_class == Site:
return site.point.x == limit_site.x and site.point.y == limit_site.y
elif site_class == WeightedSite:
r... | 1ebe8b18749bb42cf1e55e89a1e861b687f8881b | 3,647,682 |
def get_header(filename):
"""retrieves the header of an image
Args:
filename (str): file name
Returns:
(str): header
"""
im = fabio.open(filename)
return im.header | a3c195d23b671179bc765c081c0a1e6b9119a71d | 3,647,683 |
def gaussian_ll_pdf(x, mu, sigma):
"""Evaluates the (unnormalized) log of the normal PDF at point x
Parameters
----------
x : float or array-like
point at which to evaluate the log pdf
mu : float or array-like
mean of the normal on a linear scale
sigma : float or array-like
... | dbf1e389ad8349093c6262b2c595a2e511f2cb28 | 3,647,684 |
def _show_traceback(method):
"""decorator for showing tracebacks in IPython"""
def m(self, *args, **kwargs):
try:
return(method(self, *args, **kwargs))
except Exception as e:
ip = get_ipython()
if ip is None:
self.log.warn("Exception in widget ... | 28909d57247d68200adf1e658ed4d3f7c36f0221 | 3,647,685 |
def ecdf(data):
"""Compute ECDF for a one-dimensional array of measurements."""
# Number of data points
n = len(data)
# x-data for the ECDF
x = np.sort(data)
# y-data for the ECDF
y = np.arange(1, len(x)+1) / n
return x, y | e0271f87e2c031a55c84de94dbfed34ec34d34f1 | 3,647,686 |
def import_module_part(request, pk):
"""Module part import. Use an .xlsx file to submit grades to a module part
On GET the user is presented with a file upload form.
On POST, the submitted .xlsx file is processed by the system, registering Grade object for each grade in the excel
file. It dynamically ... | a915b426b8c870ee62a154a1370080e87a7de42f | 3,647,687 |
from typing import Tuple
def ordered_pair(x: complex) -> Tuple[float, float]:
"""
Returns the tuple (a, b), like the ordered pair
in the complex plane
"""
return (x.real, x.imag) | c67e43cf80194f7a5c7c5fd20f2e52464816d056 | 3,647,688 |
import os
def find_fits_file(plate_dir_list, fits_partial_path):
"""
Returns a path
:rtype : basestring
"""
for plate_dir in plate_dir_list:
fits_path = os.path.join(plate_dir, fits_partial_path)
if os.path.exists(fits_path):
return fits_path
return None | 24c5c0e8a42cc5f91e3935c8250b217ac2becd3f | 3,647,689 |
from FuXi.Rete.RuleStore import SetupRuleStore
def HornFromDL(owlGraph, safety=DATALOG_SAFETY_NONE, derivedPreds=[], complSkip=[]):
"""
Takes an OWL RDF graph, an indication of what level of ruleset safety
(see: http://code.google.com/p/fuxi/wiki/FuXiUserManual#Rule_Safety) to apply,
and a list of der... | 37dfe479dd0f150956261197b47cfbd468285f92 | 3,647,690 |
def _assembleMatrix(data, indices, indptr, shape):
"""
Generic assemble matrix function to create a CSR matrix
Parameters
----------
data : array
Data values for matrix
indices : int array
CSR type indices
indptr : int array
Row pointer
shape : tuple-like
... | 6ada37b14270b314bcc6ba1ef55da10c07619731 | 3,647,691 |
def mock_state_store(decoy: Decoy) -> StateStore:
"""Get a mocked out StateStore."""
return decoy.mock(cls=StateStore) | db8e9e99dcd4bbc37094b09febb63c849550bc81 | 3,647,692 |
from typing import Callable
from typing import List
def beam_search_runner_range(output_series: str,
decoder: BeamSearchDecoder,
max_rank: int = None,
postprocess: Callable[
[List[str]], List[str]]=... | 01c63368219f4e1c95a7557df585893d68134478 | 3,647,693 |
def read_variants(
pipeline, # type: beam.Pipeline
all_patterns, # type: List[str]
pipeline_mode, # type: PipelineModes
allow_malformed_records, # type: bool
representative_header_lines=None, # type: List[str]
pre_infer_headers=False, # type: bool
sample_name_encoding=SampleNameEncodin... | 5f706219ccc5a5f59980122b4fdac93e35056f5d | 3,647,694 |
import numpy
def carla_location_to_numpy_vector(carla_location):
"""
Convert a carla location to a icv vector3
Considers the conversion from left-handed system (unreal) to right-handed
system (icv)
:param carla_location: the carla location
:type carla_location: carla.Location
:return: a ... | a207ec5d878a07e62f96f21cd33c980cb1e5dacc | 3,647,695 |
def prev_cur_next(lst):
"""
Returns list of tuples (prev, cur, next) for each item in list, where
"prev" and "next" are the previous and next items in the list,
respectively, or None if they do not exist.
"""
return zip([None] + lst[:-1], lst, lst[1:]) + [(lst[-2], lst[-1], None)] | c00cd27e1eaeffd335a44ac625cb740f126a06e5 | 3,647,696 |
import pathlib
def vet_input_path(filename):
"""
Check if the given input file exists.
Returns a pathlib.Path object if everything is OK, raises
InputFileException if not.
"""
putative_path = pathlib.Path(filename)
if putative_path.exists():
if not putative_path.is_file():
... | 9c517cf9e56781b995d7109ea0983171760cf58c | 3,647,697 |
import requests
def check_for_updates(repo: str = REPO) -> str:
"""
Check for updates to the current version.
"""
message = ""
url = f"https://api.github.com/repos/{repo}/releases/latest"
response = requests.get(url)
if response.status_code != 200:
raise RuntimeError(
... | 0d3b37a74e252552f1e912a0d7072b60a34de86d | 3,647,698 |
def _process_image(record, training):
"""Decodes the image and performs data augmentation if training."""
image = tf.io.decode_raw(record, tf.uint8)
image = tf.cast(image, tf.float32)
image = tf.reshape(image, [32, 32, 3])
image = image * (1. / 255) - 0.5
if training:
padding = 4
image = tf.image.re... | 0a255d954c7ca537f10be6ac5c077fd99aaf72cd | 3,647,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.