content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def plot_roc_curve(y_true_arr, y_pred_proba_arr, labels_arr, pos_label=None, plot_thres_for_idx=None,
log_wandb=False):
"""Function for plotting ROC curve
Args:
y_true_arr (list/np.array): list of all GT arrays
y_pred_proba_arr (list/np.array): list of all predicted probabili... | 5,293,600 |
def _pillow2array(img, flag='color', channel_order='bgr'):
"""Convert a pillow image to numpy array.
Args:
img (:obj:`PIL.Image.Image`): The image loaded using PIL
flag (str): Flags specifying the color type of a loaded image,
candidates are 'color', 'grayscale' and 'unchanged'.
... | 5,293,601 |
def get_eval_fn(model: torch.nn.Module):
"""Get the evaluation function for server side.
Parameters
----------
model
The model we want to evaluate.
Returns
-------
evaluate
The evaluation function
"""
def evaluate(weights: fl.common.Weights) -> Optional[Tuple[float... | 5,293,602 |
def build_rnn_dataset(dataframes, tokenizer=lambda s: s.split()):
"""
Given an SST reader, return the dataset as (X, y) training pairs.
Parameters
----------
dataframes : pd.DataFrame or list of pd.DataFrame
The dataset or datasets to process, as read in by
`sentiment_reader`.
... | 5,293,603 |
def api_user_current_bar():
"""Request endpoint to change a user's current bar
:param int user_id: ID of the user to modity
:param int bar_id: ID of the bar to set as user's current view default
If 0, will use the configured default bar
:param string next: Should be the URL of the current page s... | 5,293,604 |
def _default_line_time_factory(self: "Kymo"):
"""Line time in seconds"""
if self.timestamps.shape[1] > 1:
ns_to_sec = 1e-9
return (self.timestamps[0, 1] - self.timestamps[0, 0]) * ns_to_sec
else:
raise RuntimeError(
"This kymograph consists of only a single line. It is no... | 5,293,605 |
def B(i,j,k):
"""
Tensor B used in constructing ROMs.
Parameters
----------
i : int
j : int
k : int
Indices in the tensor.
Returns
-------
int
Tensor output.
"""
if i == j + k:
return -1
elif j == i + k or k == i + j:
return 1
el... | 5,293,606 |
def magic(data):
"""Mime-Type anhand eines Datenstroms raten."""
if data[0:2] == '\xff\xd8': # JPEG Start of Image
return 'image/jpeg', '.jpg'
elif data[0:4] == '\x89PNG':
return 'image/png', '.png'
elif data[0:4] == '%PDF':
return 'application/pdf', '.pdf'
else:
LOG... | 5,293,607 |
def spline(pts):
"""Generate coordinates for a cubic spline.
A 4-dimensional (3rd order) spline is guided by a polyline through
the provided list of points. At least 3 points must be specified.
"""
from supreme.lib.nurbs.Crv import Crv
if len(pts) < 3:
raise ValueError("At least 3 da... | 5,293,608 |
def read_metadata(input_dir):
"""Read metadata JSON file in +input_dir+ into a dictionary"""
metadata_path = os.path.join(input_dir, METADATA_FILENAME)
with open(metadata_path) as src:
return json.load(src) | 5,293,609 |
def logout():
"""登出"""
session.pop("user_id", None)
session.pop("nick_name", None)
session.pop("mobile", None)
# session.pop('user_id', None)
# session.pop('nick_name', None)
# session.pop('mobile', None)
session.pop('is_admin', None)
return jsonify(errno=RET.OK, errmsg="退出登录成功") | 5,293,610 |
def boost_python_pattern_generator(asg, pattern=None, *args, **kwargs):
"""
"""
return boost_python_generator(asg, asg.declarations(pattern=pattern), *args, **kwargs) | 5,293,611 |
def make_upload_chart(gfunc, yaml_path, json_path, title):
"""Create an upload chart
Args:
gfunc: the group by function
yaml_path: the template path
json_path: the path to write to
title: the title of the chart
Retuns:
the chart JSON
"""
return pipe(
gfunc,
... | 5,293,612 |
def _yuzu_ism(model, X_0, precomputation, device='cpu', use_layers=use_layers,
ignore_layers=ignore_layers, terminal_layers=terminal_layers, verbose=False):
"""Perform ISM using compressed sensing to reduce the necessary compute.
This function will take a model, a reference sequence, and a set of
sequ... | 5,293,613 |
def recv_process():
""" Receive a Shipment """
try:
recv_id = long(request.args[0])
except (IndexError, ValueError):
# recv_id missing from URL or invalid
redirect(URL(f="recv"))
rtable = s3db.inv_recv
if not auth.s3_has_permission("update", rtable, record_id=recv_id):
... | 5,293,614 |
async def test_not_connected(hass, monkeypatch):
"""Test Error when sending commands to a disconnected device."""
import pytest
from homeassistant.core import HomeAssistantError
test_device = RflinkCommand("DUMMY_DEVICE")
RflinkCommand.set_rflink_protocol(None)
with pytest.raises(HomeAssistantE... | 5,293,615 |
def check(schema: dict) -> dict:
"""
Validate JADN schema against JSON schema,
Validate JADN schema against JADN meta-schema, then
Perform additional checks on type definitions
"""
# Add empty Fields if not present
schema_types = [TypeDefinition(*t) for t in schema['types']]
schema['type... | 5,293,616 |
def validate_log_translations(logical_line, filename):
"""Check if log levels has translations and if it's correct.
S369
S370
S371
S372
"""
# NOTE(Kezar): sahara/tests included because we don't require translations
# in tests. sahara/openstack/common included because it's part imported... | 5,293,617 |
def resmlp_24_224():
"""
ResMLP-24
Paper: ResMLP: Feedforward networks for image classification...
Link: https://arxiv.org/abs/2105.03404
"""
cfg = MLPMixerConfig(
name="resmlp_24_224",
url="[timm]",
patch_size=16,
embed_dim=384,
nb_blocks=24,
mlp_... | 5,293,618 |
def h2abc(h):
"""Returns a description of the cell in terms of the length of the
lattice vectors and the angles between them in radians.
Takes the representation of the system box in terms of an upper triangular
matrix of column vectors, and returns the representation in terms of the
lattice vec... | 5,293,619 |
def test_no_module_conversion(structure):
"""Make sure a warnings is raised and None is returned for conversions with non-existing modules"""
import importlib
from optimade.adapters.warnings import AdapterPackageNotFound
CONVERSION_MAPPING = {
"aiida": ["aiida_structuredata"],
"ase": ["... | 5,293,620 |
def get_joint_distribution(
trials,
mean_prior=lambda: tfd.Uniform(0., 1.),
inverse_concentration_prior=lambda: tfd.HalfNormal(5.)):
"""Returns a joint distribution over parameters and successes."""
param_shape = ps.shape(trials)[:1]
mean = tfd.Sample(mean_prior(), param_shape)
inverse_concentration... | 5,293,621 |
def open_file_next_key(event):
""" call open_file_next from bind"""
open_file_next() | 5,293,622 |
def format_data(data, indent):
"""Format a bytestring as a C string literal.
Arguments:
data: Bytestring to write
indent: Indentation for each line, a string
Returns:
A multiline string containing the code, with indentation before every line
including the first. There is no final ne... | 5,293,623 |
def survey_series_rheader(r):
"""
The series rheader
"""
if r.representation == "html":
db = current.db
s3db = current.s3db
tablename, record = s3_rheader_resource(r)
if not record:
series_id = current.request.vars.series
table = s3db.survey_... | 5,293,624 |
def send_tasks_to_trello(username: str, user_dict: dict):
"""This function sends tasks from database that are stored as not sended to trello.
Args:
username (str): The username for the owner of the tasks.
user_dict (dict): User dictionary with keys to acces to trello.
"""
client = Trell... | 5,293,625 |
def get_byte(evm: Evm) -> None:
"""
For a word (defined by next top element of the stack), retrieve the
Nth byte (0-indexed and defined by top element of stack) from the
left (most significant) to right (least significant).
Parameters
----------
evm :
The current EVM frame.
Rai... | 5,293,626 |
def sample(bn, cond=None):
"""
Sample every variables of a Bayesian Network
:param bn: a Bayesian Network
:param cond: dict, given variables
:return:
"""
g = bn.DAG
cond = cond if cond else dict()
if any(nod not in cond for nod in bn.Exo):
raise ValueError('Exogenous nodes do... | 5,293,627 |
async def async_get_config_entry_diagnostics(
hass: HomeAssistant, entry: ConfigEntry
) -> dict[str, Any]:
"""Return diagnostics for a config entry."""
# Currently we only support a single device
device = hass.data[DOMAIN][entry.entry_id][VICARE_DEVICE_CONFIG]
data: dict[str, Any] = json.loads(
... | 5,293,628 |
def load_image_lists(frame_list_file, prefix="", return_list=False):
"""
Load image paths and labels from a "frame list".
Each line of the frame list contains:
`original_vido_id video_id frame_id path labels`
Args:
frame_list_file (string): path to the frame list.
prefix (str): the p... | 5,293,629 |
def predict_single(classifier: GaussianNB, test_data:List[Text], num: int = 200):
"""
predicts the most probable class value for the given test tokens and model
Parameters
----------
classifier: GaussianNB
model that holds the bag of words model
test_data: List[Text]
li... | 5,293,630 |
def psf_to_inhg(psf):
"""Convert lb/ft^2 to inches of mercury."""
return psf * 0.014139030952735 | 5,293,631 |
def post_request_with_retries(url, json_payload, verify_ssl=True):
"""This function performs a POST request with a total of 5 retries in case of timeouts or connection issues.
.. versionchanged:: 3.2.0
The query URL is now made into an absolute URL as necessary before performing the API request.
..... | 5,293,632 |
def filt(data, cutoff, fs=1., order=1, rp=10., rs=10., kind='butter', btype='low', ftype='filtfilt', axis=0, analog=False):
"""
Apply a digital filter.
:param data:
:param cutoff:
:param fs:
:param order:
:param rp:
:param rs:
:param kind:
:param btype:
:param ftype:
:par... | 5,293,633 |
def remove_exceptions(words):
""" Removes exceptions from the resulting words """
return [word for word in words if root(word) not in EXCEPTIONS] | 5,293,634 |
def main():
"""
Main function to parse args and take action
"""
# Build our a list of arguments and parse them
args = buildArgs().parse_args()
# Ensure needed folders exits [lvm, exposed]
if not os.path.exists(f"{ROOT}/.lvm"):
os.mkdir(f"{ROOT}/.lvm")
if not os.path.exists(f"{RO... | 5,293,635 |
def generate_request_closing_user_report(agency_ein: str, date_from: str, date_to: str, email_to: list):
"""Generates a report of requests that were closed in a time frame.
Generates a report of requests in a time frame with the following tabs:
1) Total number of opened and closed requests.
2) Total nu... | 5,293,636 |
def df_to_json(df, json_path):
"""
Convert specified spark dataframe to json and write to the specified json_path.
:param df: spark dataframe to convert
:param json_path: path where json should be written
"""
df.coalesce(1).write.format('json').save(json_path)
json_file = glob.glob(json_pat... | 5,293,637 |
def convert_ring_to_sub_molecule(ring):
"""
This function takes a ring structure (can either be monoring or polyring) to create a new
submolecule with newly deep copied atoms
Outputted submolecules may have incomplete valence and may cause errors with some Molecule.methods(), such
as update_atomty... | 5,293,638 |
def generate_first_goal(roi_boundaries, vehicle_pos, parking_pos):
"""
generate goal for forward task
"""
x = roi_boundaries[4].x + 4
y = (roi_boundaries[6].y + roi_boundaries[5].y) / 2 \
+ (roi_boundaries[6].y - roi_boundaries[5].y) / 4 - 1.1
theta = 2... | 5,293,639 |
def solver_ode(X: np.ndarray, model: dict, flag_contact: np.array,T:float):
"""
param:
X: current q, qdot
model: add tau, ST
return:
Xdot: next qdot, qddot
"""
from scipy.integrate import solve_ivp
status = -1
# Calculate state vector by ODE
t0 = 0
tf = T... | 5,293,640 |
def compute_acc(Y, log_dist_a, n_se=2, return_er=False):
"""compute the accuracy of the prediction, over time
- optionally return the standard error
- assume n_action == y_dim + 1
Parameters
----------
Y : 3d tensor
[n_examples, T_total, y_dim]
log_dist_a : 3d tensor
[n_exam... | 5,293,641 |
def remove_old_nodes(nodes, delta):
"""
remove nodes older than a certain limit
"""
limit = NOW_TIMESTAMP - delta
old_keys = []
for key, node in nodes.items():
if node.lastseen < limit:
old_keys.append(key)
count = 0
for key in old_keys:
del nodes[key]
... | 5,293,642 |
def numeric_col_spreads(df=None, non_numeric_cols=None):
"""Showcase metrics by discrete combinations"""
#non_numeric_cols.append('Churn')
logging.info(non_numeric_cols)
temp_df = df.groupby(non_numeric_cols).\
agg({'Churn': ['min','mean', 'median', 'max', 'sum', 'count']})
temp_df.columns =... | 5,293,643 |
def on_user_create(sender, user: settings.AUTH_USER_MODEL, **kwargs):
"""
Creates a user profile whenever new user has been created.
"""
user: User = User.objects.get(pk=user.id)
# TODO: Users should get their semester from USOS service in the future
try:
UserProfile.objects.get(user=u... | 5,293,644 |
def uni_emojis() -> dict:
"""
Load all unicode emojis in 72x72 (folder from twemoji).
Since this is pretty fast we do it in the main thread
"""
emo_imgs = {}
twemoji_path = join("Image", "72x72")
emofiles = listdir(twemoji_path)
# for every emoji file in twemoji
for emofile in tqdm(emofiles, desc="Unicode Emoj... | 5,293,645 |
def gen_edge_adj_random(path='data/freebase/', edge_dim=130,ps=True):
"""
Args:
path:
K:
Returns:
node_neigh:
edge_idx:
edge_emb:
edge_neigh:
"""
MA_file = "movie_actor"
MD_file = "movie_director"
MW_file = "movie_writer"
movies = []
... | 5,293,646 |
def get_closest_point(points, point):
""" Get the closest point in an array of points to the given point. """
if len(points) == 1:
return 0, points[0]
min_dist = None
min_pt = None
min_i = None
for i, pt in enumerate(points):
v = [point[j] - pt[j] for j in range(0, 3)]
di... | 5,293,647 |
def login():
"""
Login Page
"""
session.pop("user_email", None)
print("IN LOGIN")
if request.method == "POST":
u_name = request.form.get('Name')
u_email = request.form.get('Email Id')
u_num = request.form.get('Mobile No')
u_pwd = request.form.get('Password')
... | 5,293,648 |
def get_facemesh_coords(landmark_list, img):
"""Extract FaceMesh landmark coordinates into 468x3 NumPy array.
"""
h, w = img.shape[:2] # grab width and height from image
xyz = [(lm.x, lm.y, lm.z) for lm in landmark_list.landmark]
return np.multiply(xyz, [w, h, w]).astype(int) | 5,293,649 |
def main():
"""Write your expression here."""
wgs84_srs = osr.SpatialReference()
wgs84_srs.ImportFromEPSG(4326)
sinusoidal_raster1_path = 'solution_111_tar_80_res_2km_carbon_0.tif'
raster_2_path = 'realized_e_source_abs_ann_mean.tif'
raster_3_path = '1.5d_ha_per_pixel.tif'
raster2_info = p... | 5,293,650 |
def decode_resource(name):
"""Load and decode sublime text resource.
Arguments:
name - Name of the resource file to load.
returns:
This function always returns a valid dict object of the decoded
resource. The returned object is empty if something goes wrong.
"""
try:
... | 5,293,651 |
def main(query):
"""
get all entities from the server if needed, then return the closest matches to user
"""
if need_to_cache():
get_all_entities()
entities = load_entities()
matches = match_query(query, entities)
alfred_output(matches, entities) | 5,293,652 |
def get_dtw(action_list, env_output_list, environment):
"""Dynamic Time Warping (DTW).
Muller, Meinard. "Dynamic time warping."
Information retrieval for music and motion (2007): 69-84.
Dynamic Programming implementation, O(NM) time and memory complexity.
Args:
action_list: List of actions.
env_out... | 5,293,653 |
def get_version(v):
"""
Generate a PEP386 compliant version
Stolen from django.utils.version.get_version
:param v tuple: A five part tuple indicating the version
:returns str: Compliant version
"""
assert isinstance(v, tuple)
assert len(v) == 5
assert v[3] in ('alpha', 'beta', 'rc... | 5,293,654 |
def test_get_synonyms_ungrounded():
"""raises InvalidAgentError when the agent is not recognized or if the
input submitted is not valid XML or is not in the correct format
"""
bs.get_synonyms(Agent('x', db_refs={'xxx': '123'})) | 5,293,655 |
def cpdf_shape(e, p, x):
"""The conditional probability distribution function of the shape parameters
e and p (ellipticity and prolateness) given the curvature x, as defined by
Bardeen, Bond, Kaiser & Szalay (1986) in equation (7.6), together with
(A15), (C4) and (C3)."""
# BBKS eqn. (C3):
chi =... | 5,293,656 |
def create_instances(context):
"""
Args:
context: bdd context
Returns:
"""
for instance in EC2_INSTANCE_DATA:
create_ec2_instance(context, EC2_INSTANCE_DATA[instance]) | 5,293,657 |
def get_nuc2prot():
"""
Returns a dict of nucleotide accessions numbers as keys and
protein acession numbers as values.
"""
nuc2prot_acc = {}
with open("./data/download/nucleotide2protein", "r") as handle:
line = handle.readline()
while line:
prot, nuc = line.split("... | 5,293,658 |
def MeasureTime(function):
"""Measure the execution time as a decorator.
Returns:
: The return of the wrapped function
Example::
from ml_dev_utils.Timer import MeasureTime
@MeasureTime
def my_function():
print("my awesome code")
The measured duration time... | 5,293,659 |
def _repo_names_to_urls(
repo_names: Iterable[str], org_name: str, api: plug.PlatformAPI
) -> Tuple[List[str], List[str]]:
"""Use the repo_names to extract urls to the repos. Look for git
repos with the correct names in the local directory and create local uris
for them. For the rest, create urls to th... | 5,293,660 |
def config_connection(db_params):
"""
Construct module name from server type, and import module.
The DbConn class consists of a number of methods and attributes.
Some of these need to be customised for use according to the actual
RDBMS in use. The customised versions are stored in their own modules... | 5,293,661 |
def tadsize_chart(genome_name):
"""
Determine the distance threshold to build coverage tracks.
Args:
genome_name (string): name of the reference genome;
ex: mammals, drosophila, c_elegans, s_pombe, c_crescentus
Returns:
dist_thresh (int): integer specifying dist... | 5,293,662 |
def vertices_of_mesh(bsp, mesh_index: int) -> List[VertexReservedX]:
"""gets the VertexReservedX linked to bsp.MESHES[mesh_index]"""
# https://raw.githubusercontent.com/Wanty5883/Titanfall2/master/tools/TitanfallMapExporter.py (McSimp)
mesh = bsp.MESHES[mesh_index]
material_sort = bsp.MATERIAL_SORT[mesh... | 5,293,663 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry, async_add_entities):
"""Set up tuya sensors dynamically through tuya discovery."""
print("switch init")
hass.data[DOMAIN][TUYA_HA_TUYA_MAP].update(TUYA_HA_MAP)
# platform = config_entry.data[CONF_PLATFORM]
async def async_discov... | 5,293,664 |
def convert_results_to_table(results, aggregation="average"):
"""
Convert results to table
Args:
results (dict): results dictionary
aggregation (str): aggregation method, either average or sum
"""
headers = []
columns = []
for target_task, source_tasks in results.items():
... | 5,293,665 |
def object_at(desc):
"""object_at(id) -> object
id is an int returning from id() or a hex string of id()
Fetches all live objects, finds the one with given id, and returns
it. Warning: THIS IS FOR DEBUGGING ONLY. IT IS SLOW."""
if isinstance(desc, int):
target_id = desc
elif isinstanc... | 5,293,666 |
def collapse_cr_map(dq_map):
"""Transform a 4D array containing cosmic ray hit locations
(1 for CR hit, 0 for no hit), into a 3D (integration, y, x)
map that lists for each pixel the group number of the first
CR hit. If that pixel has no CR hits in the integration, then
it will have a value of NaN.
... | 5,293,667 |
def pretty_league(league):
"""Formats a detailed league view in a PrettyTable"""
fields = ["Previous rank", "Current rank", "Arrow up/down", "Team name", "Manager name",
"Gameweek score", "Total score", "Team Id"]
table = PrettyTable(field_names=fields)
table.title = league.name
for t ... | 5,293,668 |
def pix2np(pix):
"""
Converts a pixmap buffer into a numpy array
"""
# pix.samples = sequence of bytes of the image pixels like RGBA
#pix.h = height in pixels
#pix.w = width in pixels
# pix.n = number of components per pixel (depends on the colorspace and alpha)
im = np.frombuffer(pix.sa... | 5,293,669 |
def get_org_menu_extras(org):
"""
Check if there are any Config Attributes for extra org related menus in different pages
:param org: Organization Object
:return: Object with additional org menus to show. e.g. archive_buttons:
{
"url": "/apps/shipping/p--0000-0015/sxd/device/",
... | 5,293,670 |
def deep_dict_merge(source: Dict, dest: Dict):
"""Merge dictionaries recursively (i.e. deep merge)."""
for key, value in source.items():
if isinstance(value, dict):
# get node or create one
node = dest.setdefault(key, {})
deep_dict_merge(value, node)
el... | 5,293,671 |
def split_with_semicolon(input_lines):
"""
文末までで1行になるように行を連結して作り直す
連結するときは単語間に1つのスペースを入れる
コメント文を含む場合は連結しない
ラベルが先頭に出現する場合は連結しない
Args:
input_lines(list): 入力ファイル
Returns:
list: 整形された文字列
"""
splited_lines = []
output_lines = []
for line in input_lines:
spl... | 5,293,672 |
def get_challenge():
"""Calc game Q&A generation.
generate two random numbers
and calculate result of random operation
Returns:
dictionary:
key QUESTION (string) : operation description;
key ANSWER (string) : result of operation
"""
num1 = randint(_min(), _max()... | 5,293,673 |
def _los(da, eos, sos):
"""
LOS = Length of season (in DOY)
"""
los = eos - sos
# handle negative values
los = xr.where(
los >= 0,
los,
da.time.dt.dayofyear.values[-1] +
(eos.where(los < 0) - sos.where(los < 0)),
)
return los | 5,293,674 |
def test_fallback_Jacobian_qnode(monkeypatch):
"""Test the decorator fallsback to Jacobian QNode if it
can't determine the device model"""
dev = qml.device('default.gaussian', wires=1)
# use monkeypatch to avoid setting class attributes
with monkeypatch.context() as m:
m.setitem(dev._capabi... | 5,293,675 |
def construct_pdp_query(
metarels,
dwpc=None,
path_style="list",
return_property="name",
property="name",
join_hint="midpoint",
index_hint=False,
unique_nodes=True,
aggregate_columns=False,
):
"""
Create a Cypher query for computing the path degree product for a type of path.... | 5,293,676 |
def get_sparclur_renderers():
"""Helper function that returns a list of all SPARCLUR Renderers"""
present_renderers: List[Renderer] = \
[renderer for renderer in _sparclur_parsers.values() if issubclass(renderer, Renderer)]
return present_renderers | 5,293,677 |
def set_view_port(left: int, top: int, right: int, bottom: int, clip: bool = True, image: Image = None):
"""
Set the view port of the the specified image.
View port is the drawing zone on the image.
>>> from easygraphics import *
>>> init_graph(800,600)
>>> draw_rect(100,100,300,300)
>>> s... | 5,293,678 |
def load_component_from_url(
cUrl: str, tProperties: "Tuple[PropertyValue]"
) -> "XComponent":
"""
Open or Create a document from it's URL.
Args:
cUrl (str): specifies the URL of the document to load
New documents are created from URL's such as:
* ``private:factory/sdra... | 5,293,679 |
def get_fields(search_input):
"""
Forms the field properties for a search input based on the input type and properties stored in the database.
For some types it returns a list with only one field for which the label is empty. Because it takes the label of
its fieldsets while rendering. For others, it re... | 5,293,680 |
def read_and_save_tfrec_path(config, rootdir, filename_tfrec_pickle=None, dataset='0'):
"""
Read all paths of tfrecords and save into the pickle files
:param rootdir: type str: rootdir of saving tfrecords dataset
:param filename_tfrec_pickle: type str: Filename of pickle which stores the paths of all tf... | 5,293,681 |
def sub_menu(context, root):
"""Returns the sub menu items, the children of the root page. Only live
pages that have the show_in_menus setting on are returned."""
menu_pages = root.get_children().live().in_menu()
return {'request': context['request'], 'root': root,
'menu_pages': menu_pages} | 5,293,682 |
def remove_networks(force: bool):
"""Remove unused networks."""
if force is False:
click.secho(" --force is not set so I won't do anything", fg='red')
return
res = get_docker_client().networks.prune()
if res['NetworksDeleted'] is None:
print(' No network to remove')
re... | 5,293,683 |
def forge_database_args(options: ImmutableMultiDict) -> t.List[str]:
"""Forges command for database selection based on submitted options
Input:
- options: user submitted parameters via HTML form
Output:
- base: appropriate (based on submitted options) argument list
"""
# TODO futu... | 5,293,684 |
def create(logger, interface):
"""
Create this interface in Xen.
:param logger: A logger used for logging possible errors.
:type logger: seealso:: :class:`logging:Logger`
:param interface: Interface-instance to reconfigure.
:type interface: Interface
"""
con = getXenConnection(interfa... | 5,293,685 |
def alembic_config(postgres):
"""Создает объект с конфигурацией для alembic, настроенный на временную БД."""
cmd_options = SimpleNamespace(
config="alembic.ini", name="migrations", pg_url=postgres, raiseerr=False, x=None
)
return make_alembic_config(cmd_options) | 5,293,686 |
def get_setting(name):
"""
Возвращает значение для настройки, или дефолт, если он задан, или None.
Если настройка обязательная, но она не задана - выбрасывает исключение.
"""
if hasattr(settings, name):
return getattr(settings, name)
if name in REQUIRED_SETTINGS:
_raise_required... | 5,293,687 |
def is_word_in_file(fname, word):
""" Search word in given file. This function skips empty files.
"""
f = open(fname)
try:
s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
if s.find(word) != -1:
return True
return False
except ValueError:
pass
ret... | 5,293,688 |
def Difference(left, right): # pylint: disable=invalid-name
"""
@type: left: Iterable[Any]
@rtype: set[Any]
"""
return to_set(left).difference(to_set(right)) | 5,293,689 |
def signal_handler(signal, frame):
"""
This is the SIGINT handler that allows us to intercept CTRL+C.
When this is triggered, it will wait until the primary loop ends
the current iteration before ending. Press CTRL+C twice to kill
immediately.
:param signal: Unused.
:param frame: Unused.
... | 5,293,690 |
def dump_cache(db, tag):
"""Dump the given cache."""
print(f'\n===== {tag} =====\n')
if db is None:
print('db is None!')
return
# Create a dict, sorted by file prefixes.
d: Dict[str, Any]= {}
for key in db.keys():
key = key[0]
val = db.get(key)
data = key.... | 5,293,691 |
def getP2PKHOpCode(pkScript):
"""
getP2PKHOpCode returns opNonstake for non-stake transactions, or
the stake op code tag for stake transactions.
Args:
pkScript (ByteArray): The pubkey script.
Returns:
int: The opcode tag for the script types parsed from the script.
"""
scri... | 5,293,692 |
def test_savi_bad_input(spectral_index_test_data):
"""Test for PlantCV."""
index_array = spectral_index.savi(spectral_index_test_data.load_hsi(), distance=20)
with pytest.raises(RuntimeError):
_ = spectral_index.savi(hsi=index_array, distance=20) | 5,293,693 |
def emat(st1, yt, t, a=None):
"""
returns exponential moving average for a t-period EMA and incremental value
where st1 is the previous average, yt is the incr value, and t is the size of the avg
a can optionally be overridden with a specific coefficient, else 2/(t-1) is used
"""
# St = a... | 5,293,694 |
def generate_dates_in_year_df(year, spark):
"""Generate all dates and all hours between in the given year"""
date = datetime.datetime.strptime(f"01/01/{year}", "%d/%m/%Y")
end = datetime.datetime.strptime(f"01/01/{year+1}", "%d/%m/%Y")
dates = list()
while date != end:
for i in range(24):
... | 5,293,695 |
def get_swiftclient():
""" For this script, the authentication implementation is just the quickest
means possible to a demonstration.
"""
swift_conn = swiftclient.client.Connection(
authurl=os.environ.get("OS_AUTH_URL"),
user=os.environ.get("OS_USERNAME"),
key=os.environ.get("OS_... | 5,293,696 |
def plot_kmeans(result ,names, colors, country, season, mapbox_access_token):
"""
Creates and interactive html output of the clusters, if the number of points is more 100K randomly sample 50K of them
result: Dataframe, constaining k-means clustering results under the column 'label'
names: List of clust... | 5,293,697 |
def edit_nickname_to_custom_palette(palette_id=None, existing_nickname=None, new_nickname=None):
"""This changes the nickname of the given palette to something new, first checking if its valid."""
if not new_nickname:
raise ValueError('Must include a new nickname')
palette = _return_palette(palett... | 5,293,698 |
def _fitFunc(pfit, pfitKeys, x, y, err=None, func=None,
pfix=None, verbose=False, follow=None):
"""
interface to leastsq from scipy:
- x,y,err are the data to fit: f(x) = y +- err
- pfit is a list of the paramters
- pfitsKeys are the keys to build the dict
pfit and pfix (optional) a... | 5,293,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.