content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def compute_convergence(output, output_prev):
"""
Compute the convergence by comparing with the output from the previous
iteration.
The convergence is measured as the mean of a XOR operation on two vectors.
Parameters
----------
output, output_prev : np.ndarray
Current and previous... | 7ea1e931598ed8dcf8466fb4df327391943187c1 | 52,700 |
def disconnect_rest_handler(remote, *args, **kwargs):
"""Handle unlinking of remote account."""
_disconnect(remote, *args, **kwargs)
redirect_url = current_app.config['OAUTHCLIENT_REST_REMOTE_APPS'][
remote.name]['disconnect_redirect_url']
return response_handler(remote, redirect_url) | 8ed09f0e60688fd20383c7c4d98e307872356a6e | 52,701 |
import sqlite3
def viewData():
"""
displays data from the database
"""
con = sqlite3.connect("library.db")
cur = con.cursor()
cur.execute("SELECT * FROM book")
row = cur.fetchall()
con.close()
return row | 2717b438fce5986078cfe6ca798d05499465cb57 | 52,702 |
from typing import List
from typing import Dict
def get_sites(vs30_values: List, rrup_values: Dict):
"""Creates a dictionary
pair of a different Vs30 and Sites
Parameters
----------
vs30_values: List
list of Vs30s
rrup_values: Dict
dictionary of Rrups np.ndarray
"""
# ... | 8ae4f419ebc40c41f907e7e7a637625388ceed5a | 52,703 |
import os
import errno
def get_reconstruction_models_and_pred_dir(prefix, should_create=True, start_dir=None, previous_purchases=None) -> str:
""" Create the output directory containing reconstruction output
:param prefix: prefix
:param should_create: should we create the directory or not
:param star... | cf8f2bf0d4cd7f4b6fd404b27ed75ca6d54bb0a9 | 52,704 |
def part_2():
"""
Returns either a bool or an int. The bool is returned if no end is found in the instructions.
The int is the value in the accumulator before termination.
"""
found_end = False
for i, instruction in enumerate(INSTRUCTIONS):
if instruction[0] == "nop":
INSTRUC... | a0d6a9d24bbb44e881a1933b292ce7e6b0918563 | 52,705 |
def _get_school_options_for_a_b_for_most():
"""Get the educ_options starting March 15th until April 5th.
Situation:
- BY:
- source: https://bit.ly/3lOZowy
- <50 incidence: normal schooling
- 50-100 incidence: A/B schooling
- >100 incidence: distance for all except graduatio... | 49b9f7eaffb6a670b3f2696f2ac3bb934ecfba27 | 52,706 |
def pad_dataset_normal(tokenizer_fn):
"""We will pad the data.
Based on name of the dataset, we will pad it accordingly
Args:
tokenizer_fn ([type]): [A function which returns dict of list of list]
Returns:
[type]: [description]
"""
@wraps(tokenizer_fn)
def pad_fn(*args, **... | d03352e26d8315aae573075edba72195360ffebc | 52,707 |
from typing import Optional
def add_comment(
post: k_models.KookaburraPost, content: str, author: settings.AUTH_USER_MODEL
) -> Optional[k_models.KookaburraComment]:
"""
Add a comment to a post, doing some checks beforehand.
"""
# Check that the post is allowed to comment
if not post.commentin... | 65b372bf058a721faa3f672e322f43f1fcd137e7 | 52,708 |
import json
def get_profile_name(host, network):
"""
Get the profile name from Docker
A profile is created in Docker for each Network object.
The profile name is a randomly generated string.
:param host: DockerHost object
:param network: Network object
:return: String: profile name
""... | 37128df21074c75e53e9567c51301c76578947f2 | 52,709 |
def S7_parabola(M,S,gamma):
"""
Computes the intial conditions for the disrupting galaxy.
"""
R1 = -55
R2 = 25-(R1**2)/100
vR = np.sqrt((2*gamma*(M+S))/np.linalg.norm([R1,R2]))
if R1 == 0:
vR1,vR2 = vR,0
else:
theta = np.arctan(abs(R1/50))
if R2 > 0:
... | ef975c4e4c1a9d129cd7cf1af7efb1d9088367e0 | 52,710 |
from typing import Union
from pathlib import Path
import os
def reroot_path(root: Union[str, Path], filename: str) -> str:
"""Returns the basename of filename, joined to root."""
return os.path.join(root, os.path.basename(filename)) | d593cd2f19d973511494682adee636b62211cc08 | 52,711 |
def create_compression_joint(joint, end_parent, description, point_constraint = False):
"""
joint need to be a joint with a child joint. Child joint is automatically found.
"""
end_joint = cmds.listRelatives(joint, c = True, type = 'joint')
parent_transform = cmds.listRelatives(joint, p = True)... | 49c97c12ef22bd954a40241e7d1ec68889abb63e | 52,712 |
def get_simple (ftype, data, alphabet=features.DNA, sparse=False):
"""Return SimpleFeatures.
@param ftype Feature type, e.g. Real, Byte
@param data Train/test data for feature creation
@param alphabet Alphabet for feature creation
@param sparse Is feature sparse?
@return Dict with SimpleFeatures train/test
"""
... | 3029746b834c09b616627e19a1f4f6d6fd64a9a3 | 52,713 |
import functools
def checker(func, options=None):
"""Checks for producers methods.
Print:
* Alteration in objects hash.
* Numpy errors.
"""
if options is None:
options = []
@functools.wraps(func)
def wrapper(*args, **kwargs):
self = args[0]
if hasattr(self,... | f65982d4450ddecd7ccdc16f44a8d8e5752432ea | 52,714 |
def _absolute_path(repo_root, path):
"""Converts path relative to the repo root into an absolute file path."""
return repo_root + "/" + path | bae7013db933e58343f0d6b3f90dfa100de74b7e | 52,715 |
def run_all():
"""Default function that is called by the runner if nothing else is specified"""
return _make_runner(['test_fails', 'test_skipped', 'test_passes']) | d20576564b01296da29985177517813e36c9cc00 | 52,716 |
def psnr(x, y, vmax=-1):
"""
psnr - compute the Peack Signal to Noise Ratio
p = psnr(x,y,vmax);
defined by :
p = 10*log10( vmax^2 / |x-y|^2 )
|x-y|^2 = mean( (x(:)-y(:)).^2 )
if vmax is ommited, then
vmax = max(max(x(:)),max(y(:)))
Copyright (c) 2014 ... | e00baca3ad9ba3cc323b6e8c2f82ec8307d188fa | 52,717 |
def srpc(*params, **kparams):
"""Method decorator to tag a method as a remote procedure call. See
:func:`spyne.decorator.rpc` for detailed information.
The initial "s" stands for "static". In Spyne terms, that means no implicit
first argument is passed to the user callable, which really means the
m... | 2f03d3b53359d19ec2fa76ece08e95a972afc087 | 52,718 |
from typing import Any
from typing import Tuple
def get_block_header_munger(module: Any, block_hash: Hash32) -> Tuple[HexStr]:
"""
Normalizes the inputs JSON-RPC endpoints that take a 2-tuple of
`(ContentKey, bytes)`
"""
return (encode_hex(b"\x01" + block_hash),) | 8f71406ba6517e4ecab8e5759d9b67f5bb272cb1 | 52,719 |
def latlng_to_region(latlng_str):
"""Get region from latlng."""
lat, _, lng = latlng_str.partition(',')
lat_lng = (float)(lat), (float)(lng)
return geodata.get_latlng_regions(lat_lng) | 4826e44485a21eb0781ba5f24d76f857158b11bc | 52,720 |
import types
def truncated_normal(shape, mean=0.0, stddev=1.0, dtype=types.float32,
seed=None, name=None):
"""Outputs random values from a truncated normal distribution.
The generated values follow a normal distribution with specified mean and
standard deviation, except that values whose m... | d68103b50a2785a2cccd90fdd96cb2f890626628 | 52,721 |
import glob
def task_pot():
"""Re-create .pot ."""
return {
"actions": ['pybabel extract -F locales/babel-mapping.ini -o jackalify.pot jackalify'],
"file_dep": glob.glob('**/*.py', recursive=True),
"targets": ['jackalify.pot'],
"clean": True,
} | 7b6996691535f0468887e61942deb1415cc09ca1 | 52,722 |
def track_timing(collector):
"""Decorator to track statistics on a function's execution time.
Parameters
----------
collector : TimerStatsCollector
"""
def wrap(func):
def timed_(*args, **kwargs):
return _timed_func(collector, func, *args, **kwargs)
return timed_
... | 0d6fee74271f40d5fb355a136a2a0a29e41f6edd | 52,723 |
import os
def UrlsPath()->str:
"""根路由的路径"""
PROJECT_CONFIG = get_configs(CONFIG_PATH)
PROJECT_BASE_DIR = PROJECT_CONFIG['dirname']
return os.path.join(PROJECT_BASE_DIR, PROJECT_CONFIG['project_name'], 'urls.py') | 6e257f3c8d3bdbfbba1d19fe2c71263d537f5562 | 52,724 |
def aic(L, k):
"""
Akaike information criterion.
:param L: maximized value of the negative log likelihood function
:param k: number of free parameters
:return: AIC
"""
return 2*(k + L) | 159a02cc19d2b4eab30dd13c1cd2b802777277ad | 52,725 |
def hanging_node_threshold_comparison(pred_tactics, predprob_tactics, pred_techniques, predprob_techniques, known_pred_techniques, permutations):
"""
Using different combinations of thresholds retrieve all the F0.5 score macro-averaged between the
post-processed predictions and the true labels.
"""
f05list = []
f... | 727cc90fe2da1b6f9df8de83e7854efd2dd39470 | 52,726 |
def build_score_matched_bins(target_scores, full_scores, num_increments=21):
"""build bins
"""
# TODO ideally build intervals for both GC and scores...
# then to build bins, do a nested loop?
# for score interval, for gc interval:
# collect all target that match <- track count as num_target
... | ad486e714a3e2125f5bcfcee312f192954872529 | 52,727 |
def identity(x):
"""Return x."""
return x | 260605c9434bb3a1de37b019b998a1cbd7e581d6 | 52,728 |
def chunkReadPoints(chunk_id=None, chunk_layout=None, chunk_arr=None,
point_arr=None):
"""
Read points from given chunk
"""
log.debug(f"chunkReadPoints - chunk_id: {chunk_id}")
dims = chunk_arr.shape
chunk_coord = getChunkCoordinate(chunk_id, dims)
log.debug(f"chunk_coor... | 88028f457befb08cf8a2c2f362f9738cf6afc1e6 | 52,729 |
def get_columns(invoice_list):
"""return columns based on filters"""
columns = [
_("Company") + ":Company:120",
_("Trans. Group") + ":Data:180",
_("Invoice Type") + ":Data:90",
_("Acct. Head") + ":Data:160",
_("Stock No.") + ":Link/Item:120",
_("Vim Number") + ":Data:150",
_("Details") ... | 033c8249e2bed97c52155764257e407f31c22afb | 52,730 |
import re
def contains_domain(address, domain):
"""Returns True if the email address contains the given domain in the domain position, false if not."""
domain = r'[\w\.-]+@'+domain+'$'
if re.match(domain,address):
return True
return False | 10181053b162701546b9c8e775812022f1572b43 | 52,731 |
def pycond(cond, *a, **cfg):
""" condition function - for those who don't need meta infos """
return parse_cond(cond, *a, **cfg)[0] | e0b78e939f5391fbdc0e6f868481d2986fe4999d | 52,732 |
def list_dir(path):
"""列出某个目录下的文件
:param path: 相对于resources目录的路径,用于查找文件夹
:type path: str
:returns :返回一个包含资源目录下所有文件或者文件下的绝对路径的list
"""
return _current_resmgr_session().list_dir(path) | 2c023cb106af58a8928f6bf210af9ef8969f2842 | 52,733 |
def prepare_update_sql(list_columns, list_values, data_code=100):
"""
Creates a string for the update query
:param list_columns: columns that are in need of an update
:param list_values: values where the columns should be updated with
:param data_code: data code to add to the columns
:return: st... | cc3f3c548623bdeb4d2e4e12cc3205baf0a9e9ba | 52,734 |
from typing import Any
from typing import List
from pathlib import Path
async def enum_coercer(
result: Any,
info: "ResolveInfo",
execution_context: "ExecutionContext",
field_nodes: List["FieldNode"],
path: "Path",
enum_type: "GraphQLEnumType",
) -> Any:
"""
Computes the value of an en... | 75bf091fc360de34bf22f1043d1ca62b1a2c2e70 | 52,735 |
def db(request):
"""Session-wide test database."""
# create a SQLite DB in memory
_db.engine = create_engine("sqlite://")
# setup models in DB
Base.metadata.create_all(_db.engine)
return _db | 2678a6e147d6bf56b497f6821b8b76ab5ca703e6 | 52,736 |
import torch
def inference_detector_with_probs(model, img, score_thresh = None):
"""Inference image with the detector.
Args:
model (nn.Module): The loaded detector.
img (str): image file.
Returns:
"""
cfg = model.cfg
cfg.model.test_cfg.rcnn.max_per_img = 50
device = n... | 615d63b0bd515757c3815b0cd4c451d1169847f8 | 52,737 |
import os
def read_test_txt(txt_file):
""" read single-modality txt file
:param txt_file: image list txt file path
:return: a list of image path list, list of image case names
"""
lines = readlines(txt_file)
case_num = int(lines[0])
if len(lines) - 1 != case_num:
raise ValueError('case num do not e... | 936adcc1d88076fd1f3596486265857d1ca39feb | 52,738 |
from matplotlib import pyplot as plt
import numpy
def plot_hist_prop(data, plot_it=False, **histogram_kwargs):
"""Create histogram data (and maybe plot it) which is normalize to be an empirical mass distribution.
:param data: all the relevant solving times that we have observed the mouse take
:type data:... | 9009089427f6e39ff39c5a1ac926e8f5b2cad9e4 | 52,739 |
def translate(points, x, y, z):
"""Takes a set of coordinates and translates them in three dimensional
space.
The points must be a list (or tuple, or any collection really) of
coordinates in the form ``(x, y, z)``, *or* a list (etc.) of objects with
x(), y() and z() methods.
An example would b... | 8dc16aeb28f5b292daf375249bf600e5d2a641ca | 52,740 |
import os
def read_rttm_lines(rttm_file_path):
"""
Read rttm files and return the rttm information lines.
Args:
rttm_file_path (str):
Returns:
lines (list):
List containing the strings from the RTTM file.
"""
if rttm_file_path and os.path.exists(rttm_file_path):
... | 1d47b8470ee56bc752aa70fa7d436e0587603c4b | 52,741 |
def tversky_index(y_true, y_pred, smooth = 1, alpha = 0.7):
"""
Links
1. https://arxiv.org/pdf/1810.07842.pdf
"""
y_true, y_pred = y_cast(y_true, y_pred)
tp = reduce_sum(y_true * y_pred)
fn = reduce_sum(y_true * (1 - y_pred))
fp = reduce_sum((1 - y_true) * y_pred)
return reduce... | 20dc0e960441635139f1ce959e1dc6fca3d3ab7a | 52,742 |
def resnet51q(pretrained=False, **kwargs):
"""
"""
return _create_byobnet('resnet51q', pretrained=pretrained, **kwargs) | 5a08258ea9f63c7e2ede41e55731b9e39ed610aa | 52,743 |
def _feature_correlation_num(X, y, feature, n_bins=-1, return_prob=False, model=None):
"""Calculate proportion of true label and distribution predicted probability for a numerical feature using binning
"""
bin_avg = []
probs = []
# Calculating average prob requires model
if return_prob and mode... | c5c915b28fc88006082f6985913a1da965a87afa | 52,744 |
async def list_logs(
hub, ctx, name, container_group, resource_group, tail=None, **kwargs
):
"""
.. versionadded:: 3.0.0
Get the logs for a specified container instance in a specified resource group and container group.
:param name: The name of the container instance.
:param container_group: ... | 863676ceae0a1affd9ef60019afe2836069a7c8a | 52,745 |
def en(s):
"""Returns `s` as an English location string."""
return owlready2.locstr(s, lang='en') | b5627034be8e5aa3ba0956a3bc9cbcad05d99adb | 52,746 |
import time
import copy
def davidsonliu_fqe(
hmat: Hamiltonian,
nroots: int,
guess_vecs,
nele,
sz,
norb,
epsilon: float = 1.0e-8,
verbose=False,
):
"""TODO: Add docstring."""
if nroots < 1 or nroots > 2**(hmat.dim() - 1):
raise ValueError... | ccb9e35536380c2695bdb98ce2a842555c37b36e | 52,747 |
import os
def generate_log_filename() -> str:
"""Generates log filename using time.
Returns:
str: log filename with time.
"""
filename = generate_filename('log-{}.pickle')
return os.path.join(MODELS_DIR, filename) | 0f2fd71fab984fc962c1eceddbd92a15caae6b2d | 52,748 |
def onBoard(top, left=0):
"""Simplifies a lot of logic to tell if the coords are within the board"""
return 0 <= top <= 9 and 0 <= left <= 9 | 2b2007ae2e3acdbb9c04c3df1397cffce97c6717 | 52,749 |
import copy
import os
def guess_first_nonoption(gparser, subcmds_map):
"""Given a global options parser, try to guess the first non-option without
generating an exception. This is used for scripts that implement a
subcommand syntax, so that we can generate the appropriate completions for
the subcomma... | bfaa02cda400d83a29329197fb4ea37d577a2230 | 52,750 |
def _plot_enn_samples_2d(sample_df: pd.DataFrame,
train_df: pd.DataFrame) -> gg.ggplot:
"""Plot realizations of enn samples."""
p = (gg.ggplot(sample_df)
+ gg.aes(x='x0', y='x1', fill='y')
+ gg.geom_tile()
+ gg.geom_point(data=train_df, size=3, stroke=1.5)
+ gg.s... | 975dd8d3ee0a6ce7f13c351915a15a4d95a2722b | 52,751 |
def square2vec(rdm):
"""map 2D distance matrix to [n,1] vector of unique distances. Returns distances in
same order as scipy.spatial.distance.squareform."""
return rdm[np.triu_indices_from(rdm, k=1)][:, None] | 830a91f5890017f035383d1c728be3048deed44a | 52,752 |
from datetime import datetime
import pytz
def parse_date_string(dt_string, alexa=False):
"""Parse the date string from the database into a `datetime` object.
:param date_string: the raw date string to parse
:returns: the `datetime` version of the given date string
"""
if(alexa):
return da... | 3deb8558d84cd28e2eca5b575587fe8315f6de0c | 52,753 |
from typing import Union
from typing import ContextManager
from pathlib import Path
def _get_filepath(
dataset_name: str, dir_path: Union[None, str], filename: str
) -> Union[str, ContextManager[Path]]:
"""
Returns the path to a decay dataset file (located either within a sub-package of
``radioactived... | a4e7d480bf0abf209f3fc094452d6e38d4334741 | 52,754 |
import json
def get_frequent_queries(**kwargs):
"""
Gets the most frequent queries
Kwargs:
db: global database instance
redis: global redis instance
"""
db = kwargs["db"]
with db.scoped_session() as session:
q = sqlalchemy.text(
"SELECT query, calls FROM pg... | 2b0a58aeb4ef228bcf230030d1d2b5f02e49452e | 52,755 |
def Bellman_exp_inplace_prt(Qsa, S, action, action_list, ff=0.9, N_A=9, N_Symbols=3, disp_flag=False):
"""Evaluate q(s,a) using ``S`` and ``action``.
Returns q(s,a).
Parameters
----------
S : numpy.ndarray, shape=(N_A,)
State matrix <--> state index, ``S_Idx``
action : int
... | 77c371749d5cbc0c7162ecf2a4916d34143ce7fd | 52,756 |
def beh_idx_to_2p_idx(beh_indices, cam_line, frame_counter):
"""
This functions converts behaviour frame numbers into the corresponding
2p frame numbers.
Parameters
----------
beh_indices : numpy array
Indices of the behaviour frames to be converted.
cam_line : numpy array
P... | 1521f29eaf0fed628dd8dedd3cc0ce5f8223c7ca | 52,757 |
def num2julian(num):
"""
Convert a Julian days to a matplotlib date.
Parameters
----------
num : numpy.ndarray : int32
Number of days since 0001-01-01 00:00:00 UTC *plus* *one*.
Returns
-------
jd : numpy.ndarray : int32
Julian days.
"""
return num + 1721424.5 | c3d4815ef316062065109ebb7c52290ca13c01fe | 52,758 |
import logging
def get_logger(module_name: str) -> logging.Logger:
"""
Gets a namespaced logger based on the project name and module name
"""
if "" == LOGGING_PROJECT_NAME:
return get_fqn_logger(module_name)
return get_fqn_logger("{}.{}".format(
LOGGING_PROJECT_NAME,
modul... | 4543e7fafb5788607664de0749dff5456dc63c6f | 52,759 |
def crop_and_resize_instance_masks(masks, boxes, mask_size):
"""Crop and resize each mask according to the given boxes.
Args:
masks: A [N, H, W] float tensor.
boxes: A [N, 4] float tensor of normalized boxes.
mask_size: int, the size of the output masks.
Returns:
masks: A [N, mask_size, mask_siz... | 81f06b34499ec8c51c5635e4c79a5943179b3108 | 52,760 |
def compute_source_flags(tod=None, P=None, mask=None, wrap=None,
center_on=None, res=None):
"""Process masking instructions and create RangesMatrix that flags
samples in the TOD that are within the masked region. This
masking makes use of a map with the footprint encoded in P, so
... | 857eb7db8bd8490695a8198714d3675c2ea5940d | 52,761 |
def _split(df, keepvars, force_numeric=False):
"""
Splits a dataframe into a list of arrays based on a key variable. Pass keepvars
to keep variables other than the key variable
"""
# df = df.sort_values('__key_var__') #now done outside of function
small_df = df[['__key_var__'] + keepvars]
ar... | 0a93671b0348a3e8d288485733bba1befa93445a | 52,762 |
import functools
def pmg_serialize(method):
"""
Decorator for methods that add MSON serializations keys
to the dictionary. See documentation of MSON for more details
"""
@functools.wraps(method)
def wrapper(*args, **kwargs):
self = args[0]
d = method(*args, **kwargs)
#... | bbe2ed20bf563d97c5cfc920e9ad226e096f5cba | 52,763 |
def normalize_dataframes(grouped_df, year):
""" Takes a dataframe which has been grouped by phrase and aggregated, and normalizes the
total_occurrences and total_docs columns by dividing them by the total no. of phrases or total no. of
docs in the relevant year and multiplying by 100 to create percentages.
... | 4a4ca38c13b8a18b0b72f86ae9610882314bac74 | 52,764 |
async def setup_file(config_file, cmd_args):
"""Set up control center from config file and command line args.
Parameters
----------
config_file : str
The path to the configuration YAML file.
cmd_args : dict
The dict with the command line arguments.
Returns
-------
Cente... | 912b8c044fdfce07f0d2fdad141feb548ea8c5fb | 52,765 |
def egd_get_user_lang(user=None) -> str:
"""If user logged use gessed language on session beginning or resumption"""
if is_app_for_actual_site():
return frappe.local.lang
else:
return frappe_get_user_lang(user) | 2fe52f7259dc2cb5fa33dd883e475960ef7040a3 | 52,766 |
def oldest_youngest():
"""Get JSON Data.
Compile a dictionary of all billionaires' names and ages.
Find the oldest billionaire under 80, and youngest living billionaire."""
data = get_json()
age_dict = {}
for item in data['billionaires']:
if item['age'] >= 80 or item['age'] < 0:
... | 25e04edac9fb7ba7f4fa7b399dd28403c1ffffe0 | 52,767 |
import pickle
def read_narr_mask(pickle_file_name):
"""Reads NARR mask from Pickle file.
:param pickle_file_name: Path to input file.
:return: mask_matrix: See doc for `check_narr_mask`.
"""
pickle_file_handle = open(pickle_file_name, 'rb')
mask_matrix = pickle.load(pickle_file_handle)
p... | ad78202ef4cf136647ad51d4e558fe3de58ef9d0 | 52,768 |
from typing import Dict
from typing import Optional
def get_imported(context: dict) -> Dict[str, Optional[version_types]]:
"""Create list of imported modules in given context.
Only outputs modules from given context that have
conventional version attributes.
Context is typically globals() or locals()... | 1a1e2a84db5de4490f2adbe677fc08315a99de2f | 52,769 |
from typing import Callable
def mpi_reduce(x: np.ndarray, op: Callable) -> np.ndarray:
"""Apply reduce operation over MPI processes."""
buffer = np.zeros_like(x)
MPI.COMM_WORLD.Allreduce(x, buffer, op=op)
return buffer | 7c048c5f3fdcd19b436e45cdbab17ad02255bdbf | 52,770 |
import os
def extract_columns_from_table_definition_file(xmltag, table_definition_file):
"""
Extract all columns mentioned in the result tag of a table definition file.
"""
def handle_path(path):
"""Convert path from a path relative to table-definition file."""
if not path or path.sta... | f3a8e0f952bdbb35d2eaf7be09300a82996541fb | 52,771 |
def get_det_bbox_with_cls_of_img(all_boxes, img_idx):
"""get_det_bbox_with_cls_of_img
:param all_boxes: det result
:param img_idx: img idx in imageset.txt
:return bboxes: N*6-dim matrix, N is number of bbox, 6 is [x1,y1,x2,y2,score,cls], the cls is the addtion information we get from this function
... | b4c2023c385712675b99b944a179614dbac9e1f5 | 52,772 |
def _multiply_calculate(a, b): # pragma: no cover
"""
a in GF(2^m), can be represented as a degree m-1 polynomial in GF(2)[x]
b in GF(2^m), can be represented as a degree m-1 polynomial in GF(2)[x]
p(x) in GF(2)[x] with degree m is the primitive polynomial of GF(2^m)
a * b = c
= (a(x) * ... | 7cb631ceed1c635eca26c105f82c43301bc158b0 | 52,773 |
def hugoniot_rho(p, rho0, c0, s, min_strain=0.01):
"""
calculate density in g/cm^3 from a hugoniot curve
:param p: pressure in GPa
:param rho0: density at 1 bar in g/cm^3
:param c0: velocity at 1 bar in km/s
:param s: slope of the velocity change
:param min_strain: defining minimum v/v0 val... | c8afd51030c9b7c8c1353bab0ac7199b349aa77d | 52,774 |
import platform
import time
import os
import re
def scan_with_arp():
"""Komut satırından veriyi çeker. Hızlı yöntemdir. Sadece Linux'da çalışır.
:return: dict --> { "MAC":"IP", "MAC":"IP",. .. }
"""
if platform not in ["linux", "linux2"]:
rapor.warning(scan_with_arp.__name__, "Stopped: This... | 00621f6feb8a2afbf21989c68ef9f0aa75c7ec9d | 52,775 |
from pathlib import Path
import shutil
import os
def no_pipegraph(request):
"""No pipegraph, but seperate directory per test"""
if request.cls is None:
target_path = Path(request.fspath).parent / "run" / ("." + request.node.name)
else:
target_path = (
Path(request.fspath).paren... | 91bf7f9957af93648350a1100faab81e42151e09 | 52,776 |
def name( path ):
"""Extracts the resource name."""
return path[1+path.rfind('/'):] | 7e8448e5b1c62c30e7ae28c80580731aa9f6f9fb | 52,777 |
def report_dfa(q_0, dfa, g):
"""
Give a complete description of the DFA as a string
"""
output = ""
output += "----------- DFA ----------- " + "Goal: " + g + " ----------- \n"
transitions = [(i,dfa[(i,sigma)],sigma) for i,sigma in dfa]
transitions.sort()
for i,j,sigma in transitions:
output += (f"delta({i},{s... | 99d86557b9e1aede93f46e1ef78ecb1fe6cdbf30 | 52,778 |
def get_page_response(query, page, per_page, itemskey, return_method=None,
replaceobj=None, replaceobj_key_only=False, **kwargs):
""" 获取一个多页响应对象
:param query: 查询对象,或者直接返回的对象
:param page: 当前页
:param per_page: 每页项目数
:param itemskey: 对应 items 的键名
:param return_method: 若值不为 Non... | fb15af91981ff057ed75a633a9012ab68d5653e3 | 52,779 |
def decrypted(data, password=None, is_user=True):
"""Decrypt to any Python object
:param data: a byte string previously encrypted using :func:`encrypted`
:param passowrd: the optional password originally used to encrypt
:param is_user: optionally indicate whether user or machine
:returns: a Python ... | d3924de10aaa4b0918205373cf2e4f7744a0bc7c | 52,780 |
def on_pad_pressed(pad_n=None, pad_ij=None):
"""Shortcut for registering handlers for ACTION_PAD_PRESSED events.
Optional "pad_n" or "pad_ij" arguments are to link the handler to a specific pad.
Functions decorated with this decorator will be called with the following positional
arguments:
* Pus... | 458be38bacca5347370bb9526a7603d0d6455f85 | 52,781 |
def score(n):
"""根据成绩,计算成绩的级别,级别有:A、B、C、D
成绩>=90 ——A
成绩>=80 ——B
成绩>=70 ——C
成绩>=60 ——D
参数:
- n-:成绩
返回值:返回‘A’或‘B’或者'C'或者'D'
"""
if n >= 90:
return 'A'
if n >= 80:
return 'B'
if n >= 70:
return 'C'
if n >= 60:
return 'D' | fb854dbdb77e31b75a70eddf6d001814100c44d3 | 52,782 |
import os
def normalize_path(p):
"""Normalize filesystem path (case and origin). If two paths are identical, they should be equal when normalized."""
return os.path.normcase(os.path.abspath(p)) | 747948440eeebd99fca79ec413a616eaaba4dbdd | 52,783 |
def handle_cron_reacts():
"""Check for new reactions - if any, run through and react to them"""
# Check emojis uploaded (every 60 mins)
# This url is hit in crontab as such:
# 0 * * * * /usr/bin/curl -X POST https://YOUR_APP/cron/reacts
logg.debug('Handling recent reacts...')
reacts = Bot.... | e7087257e7b11cb15a416cfc17443fddeb6075a5 | 52,784 |
def get_linked_clusters():
"""
Get linked clusters.
:returns: list of linked clusters
:rtype: [LinkedCluster]
"""
current_cluster = get_attached_cluster()
if not current_cluster:
return []
links = get_cluster_links(current_cluster.get_url()).get('links')
linked_clusters = ... | 524d231676d1db77cf1804d626f7aeb2ff69a228 | 52,785 |
from unittest.mock import Mock
def cube_mesh():
""" cube mesh """
mesh = Mock()
mesh.vertices = cube_vertices()
mesh.loop_triangles = [
triangle(0, 2, 1),
triangle(0, 3, 2),
triangle(2, 3, 4),
triangle(2, 4, 5),
triangle(1, 2, 5),
triangle(1, 5, 6),
... | 3a572fd73fe5a2aca2f59517ba19f8b7d6b214f9 | 52,786 |
def algo_options():
"""
Return the list of default options for supported algorithms.
"""
return {"grid": "",
"hubbard": "",
"medial": "-merge -burst -expand",
"octree": "",
"spawn": ""} | f52c12efe477bd50a49e7053cca97fc9e4072433 | 52,787 |
import os
def dyld_framework(filename, framework_name, version=None):
"""Find a framework using dyld semantics"""
filename = ensure_unicode(filename)
framework_name = ensure_unicode(framework_name)
version = ensure_unicode(version)
def _search():
spath = ensure_unicode(os.environ.get("DYL... | 54896f20d750f572cfceead89d67dd90061b728d | 52,788 |
def fill_matrix(X: np.ndarray, mixture: GaussianMixture) -> np.ndarray:
"""Fills an incomplete matrix according to a mixture model
Args:
X: (n, d) array of incomplete data (incomplete entries =0)
mixture: a mixture of gaussians
Returns
np.ndarray: a (n, d) array with completed data... | c7001e668a04a3221f9db48038815abfcdbb1575 | 52,789 |
def detect(agent, fill_none=False):
"""
fill_none: if name/version is not detected respective key is still added to the result with value None
"""
result = dict(platform=dict(name=None, version=None))
_suggested_detectors = []
for info_type in detectorshub:
detectors = _suggested_detect... | bef47ccbff4bbf09d0195a6f9e71f8ed675f04ef | 52,790 |
def shutting_down(globals=globals):
"""
Whether the interpreter is currently shutting down.
For use in finalizers, __del__ methods, and similar; it is advised
to early bind this function rather than look it up when calling it,
since at shutdown module globals may be cleared.
"""
# At shutdow... | 01f601b989611b06a438a3be3e15937eff389038 | 52,791 |
def _err(msg=None):
"""To return a string to signal "error" in output table"""
if msg is None:
msg = 'error'
return '!' + msg | 029fae3786df61160867696fb71cc94b2edf0506 | 52,792 |
from datetime import datetime
import pickle
def run_qpe(
unitary,
precision_qubits,
query_qubits,
query_circuit,
device,
items_to_keep=1,
shots=1000,
save_to_pck=False,
):
"""
Function to run QPE algorithm end-to-end and return measurement counts.
Args:
precision_q... | 04e6cecd3a28c50f635a0a42f1ee24f6ac8c0b70 | 52,793 |
def LNETF(N,loc_rad,taper='GC',infl=1.0,Rs=1.0,rot=False,**kwargs):
"""
The Nonlinear-Ensemble-Transform-Filter (localized).
Ref: Julian Tödter and Bodo Ahrens (2014):
"A Second-Order Exact Ensemble Square Root Filter for Nonlinear Data Assimilation"
It is (supposedly) a deterministic upgrade of the NLEAF ... | e1f3beb387371d3178598b724cc08c0a0e3f53b8 | 52,794 |
def alert_unmanaged_error(request_id, error, sys_exc_info):
"""Compose error on unmanaged error."""
return UNMANAGED_TEXT_MESSAGE.format(
date=get_date(),
request_id=request_id,
error=error,
traceback=format_traceback(sys_exc_info),
locals=format_locals(sys_exc_info)
... | 53c504a2bef9f7c7593988b63238a95c753fbbde | 52,795 |
def load_transcript(transcript_path):
""""
Load transcript from *.srt file
"""
transcript = []
subs = pysrt.open(transcript_path)
for sub in subs:
transcript.append((sub.text, time2second(tuple(sub.start)[:4]), time2second(tuple(sub.end)[:4])))
return transcript | ff4725e0f2ec68b16bd750b28066a4446280c866 | 52,796 |
async def get_attachment_obj(ctx: commands.Context):
"""Gets the attachment object from a message"""
# switch to the replied message if it's there
if ctx.message.attachments:
msg = ctx.message
elif ctx.message.reference:
msg = ctx.message.reference.resolved
else:
return False... | 176a7e2c9dcc27dff9586440c23486dc7d273301 | 52,797 |
def day_wind_chart(qs_list, unit, plot_func, width, height, colors):
"""
Returns a URL which produces one line for each queryset.
"""
data_list = [] # list of value lists
for date_qs in qs_list:
if date_qs: # only work on this if the queryset is not empty
data_list.append(conv... | eda14897fec89f14b340c7dc5234b7a91f4ca59d | 52,798 |
from operator import eq
def conso(h, t, l):
""" Logical cons -- l[0], l[1:] == h, t """
if isinstance(l, (tuple, list)):
if len(l) == 0:
return fail
else:
return (conde, [(eq, h, l[0]), (eq, t, l[1:])])
elif isinstance(t, (tuple, list)):
return eq((h, ) + tu... | cb576eeeb8de5a2a71a8843a4d81b3933af6d64a | 52,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.