content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def mvg_all_joints(jLs, face_keypoints=True, upper_sternum=True, upper_body=True, lower_body=True, wsize=6):
"""
:param jLs: list of lists with length 54 derived from text file
including x,y,z coordinates for each joint as separately list.
:type jLs: list
:param face_keypoints... | 50,200 |
def test_panelist_utility_id_not_exists(panelist_id: int):
"""Negative testing for :py:meth:`wwdtm.panelist.PanelistUtility.id_exists`
:param panelist_id: Panelist ID to test if a panelist does not exist
"""
utility = PanelistUtility(get_connect_dict())
result = utility.id_exists(panelist_id)
... | 50,201 |
def check_in_all_models(models_per_expt):
"""
Check intersection of which models are in all experiments
:param models_per_expt: an ordered dictionary of expts as keys with a list of valid models
:return: list of models that appear in all experiments
"""
in_all = None
for key, items in mod... | 50,202 |
def _translate_x(video: torch.Tensor, factor: float, **kwargs):
"""
Translate the video along the vertical axis.
Args:
video (torch.Tensor): Video tensor with shape (T, C, H, W).
factor (float): How much (relative to the image size) to translate along the
vertical axis.
"""
... | 50,203 |
def get_volume_pixeldata(sorted_slices):
"""
the slice and intercept calculation can cause the slices to have different dtypes
we should get the correct dtype that can cover all of them
:type sorted_slices: list of slices
:param sorted_slices: sliced sored in the correct order to create volume
... | 50,204 |
def read_val_dataframe_from_hdf5(input_pattern, val_fold=0):
"""Reads the hdf5 tables for the validation fold only.
Args:
input_pattern: String with the path for the hdf5 with a '%d' for the fold.
val_fold: Integer. The zero-based validation fold num.
Returns:
A pandas dataframe containing the valida... | 50,205 |
def debug_print(*args):
""" Print if in debugging mode """
if (IS_DEBUG):
print(*args) | 50,206 |
def hash_file(hash_obj, fout: Path):
"""Create a hash of the file.
Parameters
hash_obj () The hash object
fout (Path) : Path to file to be written.
Return
str : If fout was found.
None : If fout was not found.
"""
try:
with fout.open('rb') as f:
buf =... | 50,207 |
def start_worker_reactor(appname, config):
""" Run the reactor in the main process
Daemonizes if necessary, and then configures some resources, before starting
the reactor. Pulls configuration from the 'worker' settings in 'config'.
Args:
appname (str): application name which will be sent to s... | 50,208 |
def main(project_name, dataset_name, item_path):
"""
Add any metadata to item
:return:
"""
# import Dataloop SDK
import dtlpy as dl
# get dataset
dataset = dl.projects.get(project_name=project_name).datasets.get(dataset_name=dataset_name)
# upload and claim item
item = dataset.... | 50,209 |
def Get_Wav_EMA_PerFile(EMA_file, Wav_file, F, EmaDir, MFCCpath, BeginEnd, XvectorPath, cfg):
"""Return mean and variance normalised ema, mfcc, and x-vectors if required (of the cross-corpus).
Parameters
----------
EMA_file: str
path to ema file
Wav_file: str
path to mfcc file
... | 50,210 |
def is_class_name(class_name):
"""
Check if the given string is a python class.
The criteria to use is the convention that Python classes start with uppercase
:param class_name: The name of class candidate
:type class_name: str
:return: True whether the class_name is a python class otherwise Fa... | 50,211 |
def is_pesummary_json_file_deprecated(path):
"""Determine if the results file is a deprecated pesummary json file
Parameters
----------
path: str
path to results file
"""
return _is_pesummary_json_file(path, _check_pesummary_file_deprecated) | 50,212 |
def popart(image_array):
"""
Applique la fonction popart 4 fois avec des paramètres un peu différents
:return: une image avec moins de couleurs.
"""
h = get_image_height(image_array)
w = get_image_width(image_array)
small_height = h // 2
small_width = w // 2
small_image = im... | 50,213 |
def random_wait():
"""
Randomly wait some time
:return: None
"""
wait_time = random.uniform(0.5, 1.5)
time.sleep(wait_time) | 50,214 |
def test_issue_95():
"""test file reader when failed on file write."""
writer = FileWriter(__file__, FILES_NUM)
data_raw = get_data("../data/mindrecord/testImageNetData/")
schema_json = {"file_name": {"type": "number"},
"label": {"type": "number"},
"data": {"type": ... | 50,215 |
def _get_image_blob(roidb, coco):
"""Builds an input blob from the images in the roidb at the specified
scales.
"""
num_images = len(roidb)
# Sample random scales to use for each image in this batch
scale_inds = np.random.randint(
0, high=len(cfg.TRAIN.SCALES), size=num_images)
proce... | 50,216 |
def plot_light_spectrum_comparison():
"""
This function creates a plot comparing the normalized light spectra of different light sources
:return: None
"""
led_file = "/home/eiscar/PyCharm_Projects/UWOpticalSystemDesigner/LightData/LightMeasurements/LEDBENCH_002_02゚_5407K.csv"
fluorescent_file = ... | 50,217 |
def set_burst_mode_off(pulse_gen, channel=1, both=False):
"""
Set the pulse generator to off of burst (most commonly to cont.)
args:
pulse_gen (pyvisa.resources.gpib.GPIBInstrument): Tektronix AFG 3252
channel (int): 1 or 2. Which channel
both (bool): Set both channels to burst
... | 50,218 |
def solve_lu(A, P, B, options=MATPROP.NONE):
"""
Solve a system of linear equations, using LU decomposition.
Parameters
----------
A: af.Array
- A 2 dimensional arrayfire array representing the coefficients of the system.
- This matrix should be decomposed previously using `lu_inplac... | 50,219 |
def guess_type(filename, strict=False, default="application/octet-stream"):
""" Wrap std mimetypes.guess_type to assign a default type """
content_type, encoding = mimetypes.guess_type(filename, strict=strict)
if content_type is None:
content_type = default
return content_type, encoding | 50,220 |
def _lookup_alias(aliases, value):
"""
Translate to a common name if our value is an alias.
:type aliases: dict of (str, [str])
:type value: str
:rtype: str
>>> _lookup_alias({'name1': ['alias1']}, 'name1')
'name1'
>>> _lookup_alias({'name1': ['alias1', 'alias2']}, 'alias1')
'name1... | 50,221 |
def triplet_loss(anchor, positive, negative, alpha):
"""Calculate the triplet loss according to the FaceNet paper
Args:
anchor: the embeddings for the anchor images.
positive: the embeddings for the positive images.
negative: the embeddings for the negative images.
Returns:
t... | 50,222 |
def write_csv_file(output_filepath, dict_to_write, header):
"""
Writes a .csv file using the "csv" module. The file will contain the information
from <dict_to_write>, where each row of the new .csv file is one of the key/value
pairs. In other words, the output file should have two columns.
The ... | 50,223 |
def writeConstraints(constraints,file):
"""
Writes constraints to file in CSV format
file: a file object or a filepath
"""
file = nx.utils._get_fh(file, mode='w')
writer = csv.writer(file)
writer.writerow(["Node","Constraint","C-Size","C-Density","C-Hierarchy"])
for i in constraints:
writer.writerow([i,con... | 50,224 |
def loadConfig() -> list:
"""Loads configuration from CONFIG_PATH
Returns:
[list] -- the CONFIG_VARS as loaded from CONFIG_PATH
"""
configData = json.load(open(CONFIG_PATH, 'r', encoding='utf-8'))
returnValue = []
# make sure we're not missing anything
for configItem in CONFIG_VARS:... | 50,225 |
async def get_corrected_name_api(keyphrase: str) -> str:
"""
Get corrected artist name via Last.fm API method
artist.getCorrection. See: https://last.fm/api/show/artist.getCorrection
:param keyphrase: Name of an artist or a band.
:return: Corrected artist name.
"""
async with httpx.AsyncClie... | 50,226 |
def missing_columns(df, missing_threshold=0.6):
"""Find missing features
Parameters
----------
df : pd.DataFrame, shape (n_samples, n_features)
Training data, where n_samples is the number of samples and n_features is the number of features.
missing_threshold : float, default=0.6... | 50,227 |
def plot_fom_base(ax, rhist, stats, label, pos, color, spec):
"""
Plot relative energy resolution histogram and draw textbox with stat info.
"""
plot_rhist1d(ax, rhist, histtype = 'step', label = label, color = color)
plot_gauss_fit(ax, rhist.bins_x, stats, color = color)
add_stats_text(ax, st... | 50,228 |
def extract() -> Tuple[int, int, int, int, int, int]:
""" """
global args
global data_to_stdout
data: InfoData = read_info_file(args.extract)
# Need perlreg expressions instead of shell pattern
pattern_list: List[str] = [transform_pattern(elem) for elem in args.ARGV]
# Filter out files wh... | 50,229 |
def read_message(raw_data: bytes):
"""Reads a UDP raw message, split the metadata, and decode data.
:param raw_data: Raw UDP packet
:type raw_data: bytes
:return: Metadata and decoded data required for packet reassembly.
:rtype: tuple
"""
header, data = read_raw_message(raw_data)
#'devi... | 50,230 |
def test_slack_callback_user_dms_bot_reply(
mocker, client, session, patched_slack, create_slack_headers
):
"""Bot get notified of its own DM replies to users... ignore"""
# Arrange
slack = patched_slack(mocker.MagicMock())
channel_id = 5
# TODO find out how messages are really sent and make the... | 50,231 |
def chunk_worker(packed_args):
""" Accumulate sample by sample and filter population SNPs """
global pool_of_samples
global dict_of_species
species_id, chunk_id, contig_id = packed_args[:3]
sp = dict_of_species[species_id]
total_samples_count = sp.samples_count
list_of_samples_depth = sp.l... | 50,232 |
def test():
"""Intended for debugging/unit test."""
locals().update(**common_config.COMMON_CONFIGS["point_mass"])
data_root = os.path.join("tests/data")
vals_path = "aggregated/aggregated.pkl"
# Do not include "tex" in styles here: this will break on CI.
styles = ["paper", "heatmap-1col"]
_ ... | 50,233 |
def _get_nagios_macros():
"""Read all ENV vars then save and rename the Nagios Macros in a dictionary."""
MACROS=dict()
for k, v in sorted(os.environ.items()):
if k.startswith('NAGIOS_'):
k = k.replace('NAGIOS_', '')
MACROS[k] = v
# Inject Nagios location for template bas... | 50,234 |
def is_ordered(treap):
""" Utility to check that every node in the given Treap satisfies the following:
Rules:
- if v is a child of u, then v.priority <= u.priority
- if v is a left child of u, then v.key < u.key
- if v is a right child of u, then v.key > u.key
"""
# iterate through all n... | 50,235 |
def test_kudu_lookup_data_types(sdc_builder, sdc_executor, cluster):
"""
Tests if outgoing records have correct data types and values.
This test uses a table with a compound key.
dev_raw_data_source >> record_deduplicator >> kudu >> trash
record_deduplicator >> to_error
"""
if not hasattr(c... | 50,236 |
def find_disulphide_bonds(input_file, output_file):
"""
Find the probable Di-Sulphide Bonds in the given Domain sequences.
:param input_file: Name of the input file which contains list of Domains (IRDs).
:type input_file: string
:param output_file: Name of the output file in which Domains along with Di-Su... | 50,237 |
def async_detect_document(gcs_source_uri, gcs_destination_uri):
"""OCR with PDF/TIFF as source files on GCS"""
import json
import re
from google.cloud import vision
from google.cloud import storage
# Supported mime_types are: 'application/pdf' and 'image/tiff'
mime_type = 'application/pdf'
... | 50,238 |
def graph_data(stock, mov_avg_1, mov_avg_2):
"""
Parameters:
stock
mov_avg_1: moving average 1
mov_avg_2: moving average 2
Definitions:
av1 - average 1
av2 - average 2
ax0 - axis 0
ax1 - axis 1
ax2 - axis 2
ax1vol - axis 1 volume
... | 50,239 |
def log_prob(x, df, loc, scale):
"""Compute log probability of Student T distribution.
Note that scale can be negative.
Args:
x: Floating-point `Tensor`. Where to compute the log probabilities.
df: Floating-point `Tensor`. The degrees of freedom of the
distribution(s). `df` must contain only posit... | 50,240 |
def setup_channel_set(channel_set):
"""Configures an amfast.remoting.channel.ChannelSet object."""
# Setup database
schema = persistent.Schema()
schema.createSchema()
schema.createMappers()
# Setup DB based connection_manager and subscription_manager
channel_set.connection_manager = SaConn... | 50,241 |
def ext_handler(directory, files_info, use_def):
"""
Move files into subfolder based on extension of files
"""
# Get all files and folders
all_entities = os.listdir(directory)
for entity in all_entities:
entity_path = os.path.join(directory,entity)
if os.path.isfile( entity_path ):
is_sane,extension... | 50,242 |
def startup():
"""
Create working directory for workers
:return:
"""
# TODO: move to configure file
if os.path.exists('tmp'):
shutil.rmtree('tmp')
os.mkdir('tmp')
Sandbox.generate_profile()
if not os.path.exists('logs'):
os.mkdir('logs') | 50,243 |
def find_files(t):
"""
Find the files to move, return a list of tuples - location & name
"""
walked_path = quick_join(os.environ['HOME'], t.source)
files = []
for dirpath, _, filenames in os.walk(walked_path):
location = dirpath.replace(walked_path, '').strip('/')
for f in filena... | 50,244 |
def get_cleaned_query_data_http_error(handler, *args):
"""
同上
:param handler:
:param args:
:return:
"""
data = {}
for k in args:
try:
data[k] = clean_data(handler.get_query_argument(k))
except MissingArgumentError:
raise HTTPError(400)
return d... | 50,245 |
def CreateOrUpdateActivity(request, program, activity=None):
"""Creates or updates an activity.
Caller must provide the program. Activity is optional when creating a new one.
Args:
request: A request.
program: A models.Program under which we are either creating or updating
the activity.
activi... | 50,246 |
def dowork(lon, lat):
""" Actually do stuff"""
pgconn = get_dbconn('postgis')
cursor = pgconn.cursor()
res = dict(mcds=[])
cursor.execute("""
SELECT issue at time zone 'UTC' as i,
expire at time zone 'UTC' as e,
product_num,
product_id
from text_products WHERE pil = 'SWOMCD'
... | 50,247 |
def run_interpolation(
A, D,
cell_state,
kernel='Linear',
num_inducing=800,
maxiter=2000,
return_prior_mean=False,
n_cores=1):
"""Run scDALI interpolation of allelic rates for each region.
A, D are assumed to be n-by-d, where n is the number of cells and ... | 50,248 |
def get_event_locations(tour_dates, location='building'):
"""Returns list of event locations, filtering out duplicates.
Format location strings by calling format_event_location() passing
location and string constant that sets the location scope (i.e.,
building, city, country).
Parameters:
t... | 50,249 |
def extended_knapsack_dp(value_set, weight_set, total_allowed_weight, max_number_of_elements):
"""Knapsack with limited number of elements allowed.
Notes
-----
The rows are the number of elements in value_set
Columns are the number of weights, ranging from 0 to weight_set.
The third dimension ... | 50,250 |
def parse_arguments(version: str = "?") -> Tuple[argparse.ArgumentParser, argparse.Namespace]:
"""Build the argument parser and parse the command line arguments."""
# Ensure that the help info is printed using all columns available
os.environ['COLUMNS'] = str(shutil.get_terminal_size().columns)
parser =... | 50,251 |
def test_create_update_and_read_datetime_property_auto_update(config_props):
"""Tests creating, updating, and reading datetime property with auto update.
"""
dt_utc = datetime(2020, 8, 24, 10, 50).astimezone(UTC)
config_props.prop_attr_auto = dt_utc
props = config_props.props
assert config_props... | 50,252 |
def get_matrix_rbf(X, var, have_var=True):
"""e^-||(x_i - x_j)||/ 2*var^2 RBF"""
(rows, _) = X.shape
K = np.empty((rows, rows))
for i in range(rows):
c = np.sum(np.abs(X - X[i]) ** 2, axis=-1) ** (1. / 2) # norm
if (have_var):
c = c / (2 * (var ** 2))
K[i] = c
w ... | 50,253 |
def AddReference(name, use_clr, verbose=True):
"""
Imports a :epkg:`C#` dll.
@param name assembly name
@param use_clr use :epkg:`pythonnet` or not
(native bridge)
@param verbose verbose
This function only works if :epkg:`pythonnet` is i... | 50,254 |
def buildDict(filterKeys=None, mapColumns=False, targetDatasets=None):
""" Maps the dataset names, contained tables, and contained
columns in the projects BigQuery.
Args:
filterKeys (LIST of STRING): A list of substrings,
one of which must be included in
the table name for the table to be
... | 50,255 |
def build_gaussian_pyramid(im, max_levels, filter_size):
"""
Construct a Gaussian pyramid for a given image
:param im: a grayscale image with double values in [0,1]
:param max_levels: the maximal number of levels in the resulting pyramid.
:param filter_size: the size of the Gaussian filter (an odd s... | 50,256 |
def main():
"""Runs bigqueries and writes results."""
sql, stublib, tables = sys.argv[1], sys.argv[2], sys.argv[3:]
sqlpath = Path(sql)
sqltext = sqlpath.read_text(encoding='utf8')
def make_fields(dbc, petopia):
trie = pygtrie.StringTrie(separator='.')
for path, data in zip(tables,... | 50,257 |
def broadcast_weeks(start, end):
"""return broadcast weeks with start, end for date range"""
starts = broadcast_week_starts(start, end)
return [(start, start+timedelta(days=6)) for start in starts] | 50,258 |
def _aix_iqn():
"""
Return iSCSI IQN from an AIX host.
"""
ret = []
aix_cmd = "lsattr -E -l iscsi0 | grep initiator_name"
aix_ret = salt.modules.cmdmod.run(aix_cmd)
if aix_ret[0].isalpha():
try:
ret.append(aix_ret.split()[1].rstrip())
except IndexError:
... | 50,259 |
def generate_token(user):
""" Currently this is workaround
since the latest version that already has this function
is not published on PyPI yet and we don't want
to install the package directly from GitHub.
See: https://github.com/mattupstate/flask-jwt/blob/9f4f3bc8dce9da5dd8a567dfada0854e0cf656ae/f... | 50,260 |
def _make_replica_groups(parameters):
"""Construct local nearest-neighbor rings given the JAX device assignment."""
if 'bn_group_size' not in parameters or parameters['bn_group_size'] <= 1:
return None
inner_group_size = parameters['bn_group_size']
world_size = parameters['num_replicas']
if parameters['n... | 50,261 |
def calculate_lines_per_gloss(lines):
"""
Calculates lines per gloss of lines
Parameters
----------
lines : list
lines in the corpus
Returns
-------
number : int
the count of lines per gloss
"""
line_counts = [len(x[1]) for x in lines]
equaled = list()
... | 50,262 |
def random_selection(population: np.ndarray, mut_p: float) -> np.ndarray:
"""Randomly select genes to mutate
Args:
population (np.ndarray): Population of chromosomes
chromosome_size (int): Number of genes per chromosome
mut_p (float): Mutation probability
Returns:
np.ndarra... | 50,263 |
def rls(ctx, name, info, humanize, encrypted, tags, sort, size, descending):
"""List documents."""
yew = ctx.obj["YEW"]
docs = yew.remote.list_docs()
print(json.dumps(docs, indent=4)) | 50,264 |
def _combo_runner(fn, combos, constants, split=False, parallel=False,
num_workers=None, executor=None, verbosity=1, pool=None):
"""Core combo runner, i.e. no parsing of arguments.
"""
executor = _choose_executor_depr_pool(executor, pool)
n = prod(len(x) for _, x in combos)
ndim = ... | 50,265 |
def p_structure(p):
"""structure : STRUCTURE IDENTIFIER '{' field_list '}'"""
p[0] = ArsStructure(name=p[2])
for field in p[4]:
p[0].add_field(field)
p.parser.interface.types.append(p[0]) | 50,266 |
def recover_volume(module, array):
""" Recover Deleted Volume"""
changed = True
volfact = []
if not module.check_mode:
try:
array.recover_volume(module.params['name'])
except Exception:
module.fail_json(msg='Recovery of volume {0} failed'.format(module.params['nam... | 50,267 |
def push_to_hub_keras(
model,
repo_path_or_name: Optional[str] = None,
repo_url: Optional[str] = None,
log_dir: Optional[str] = None,
commit_message: Optional[str] = "Add model",
organization: Optional[str] = None,
private: Optional[bool] = None,
api_endpoint: Optional[str] = None,
u... | 50,268 |
def _should_ignore(fd_name: str, patterns: Sequence[str]) -> bool:
"""Return whether `fd_name` should be ignored according to `patterns`.
Examples
--------
>>> fd_name = "google/protobuf/empty.proto"
>>> pattern = "google/protobuf/*"
>>> _should_ignore(fd_name, [pattern])
True
>>> fd_na... | 50,269 |
def main(
recipes_dir: (
"Directory of the recipes to patch",
"option",
"r",
) = "nerdpool/nerdpool_recipes",
nerdpool_template: (
"Template file used to patch the recipes",
"option",
"t",
) = "nerdpool_recipe_patch_template.py",
recipes_list: ("List o... | 50,270 |
def unc_inertia_eval(awg, afg, bout, bi, mw, ed, out_xml):
""" Unconventional aircraft Moment of Inertia analysis main function.
It dvides the cases defined and evaluates them calling the
function in the with_fuse_geom subfolder.
Source: An introduction to mechanics, 2nd ed., D. Kleppner
... | 50,271 |
def str2body(v):
"""
convert str to json data or keep original string
:param v:
:return:
"""
try:
return json.loads(v)
except:
return v | 50,272 |
def get_default_law_key():
""" Default key needs to be unique timestamp until changed """
x = str(datetime.now())
key = x[5:25]
return key | 50,273 |
def _evaluate_Delaunay_component(
subgraph_RE_comp: nx.Graph,
subgraph_R_comp: nx.Graph,
subgraph_E_comp: nx.Graph,
num_R: int,
):
"""
Phase 3
Evaluates given graph-connected component.
:param subgraph_RE_comp: Delaunay graph of the component containing R and E points..
:param subgra... | 50,274 |
def calculate_fees(sat_per_vbyte: int, num_p2wkh_inputs: int, num_np2wkh_inputs,
num_channels: int, has_change=False) -> int:
"""Calculates the size (in vbytes) of a transaction and determines the fee."""
# see also https://github.com/btcsuite/btcwallet/tree/master/wallet/txsizes/size.go
... | 50,275 |
def load_module(path, module_name=None):
"""Load python module from file
Args:
path: python file path
module_name: import as `module_name` name. If none, use `path[:-3]`
"""
assert path.endswith(".py")
if module_name is None:
module_name = os.path.basename(path)[:-3] # omit .... | 50,276 |
def test_atomic_float_white_space_nistxml_sv_iv_atomic_float_white_space_1_3(mode, save_output, output_format):
"""
Type atomic/float is restricted by facet whiteSpace with value
collapse.
"""
assert_bindings(
schema="nistData/atomic/float/Schema+Instance/NISTSchema-SV-IV-atomic-float-whiteS... | 50,277 |
def abcd_normalize(A=None, B=None, C=None, D=None):
"""Check state-space matrices and ensure they are two-dimensional.
If enough information on the system is provided, that is, enough
properly-shaped arrays are passed to the function, the missing ones
are built from this information, ensuring the corre... | 50,278 |
def RunGetOutput(cmd, chk_err=True, log_cmd=True):
"""
Wrapper for subprocess.check_output.
Execute 'cmd'. Returns return code and STDOUT, trapping expected exceptions.
Reports exceptions to Error if chk_err parameter is True
"""
if log_cmd:
LogIfVerbose(cmd)
try:
output = s... | 50,279 |
def test_derived_component_identifier() -> None:
"""Test that derived components do not have an identifier."""
mdc = MyDerivedComponent()
with pytest.raises(NotSupportedByComponentError):
mdc.identifier | 50,280 |
def extract_full_symbol(full_symbol: str):
"""
:return: (symbol, exchange)
"""
tmp = full_symbol.split(' ')
if len(tmp) < 4:
return "unknwonsymbol", Exchange.SHFE
symbol = tmp[2] + tmp[3]
exchange_str = tmp[0]
ex = Exchange(exchange_str)
if ex in [Exchange.SHFE, Exchange.DCE,... | 50,281 |
def remove(user_id):
"""User removing"""
user = User.query.get(user_id)
db.session.delete(user)
db.session.commit()
flash('User "%s" successfully remove' % user.name, 'success')
return redirect(url_for('backend.index')) | 50,282 |
def phonemes_to_sentences(
arpabet: Dict[str, List[List[str]]],
data: Tuple[List[list], ...],
print_every: int,
of: int,
) -> Tuple[str, ...]:
"""Convert list of phoneme lists to sentences."""
data = [
(
" ".join([phonetic_to_word(arpabet, [p]) for p in d]),
(prin... | 50,283 |
def submit():
"""
Submit one name.
"""
# TODO captcha
try:
if request.form.get('name'):
# egg
name = _process_name(request.form.get('name'))
database.add_name(name)
elif request.form.get('fullname'):
name = _process_name(request.form.ge... | 50,284 |
def butter_bandpass_filter(flux, lowcut, fs, order=3):
"""
Apply a Butterworth high-pass filter.
Args:
flux (array): The flux array.
lowcut (float): The frequency cut off.
fs (array): The frequency array.
order (Optional[int]): The order of the Butterworth filter. Default
... | 50,285 |
def main(filepath=None):
"""execution starts here"""
# print("main():")
if filepath==None:
filepath = r"C:\Program Files\7-Zip\7z.exe"
print("Getting Metadata From File: " + filepath)
parser = hachoir.parser.createParser(str(filepath))
metadata = hachoir.metadata.extractMetadata(parser)... | 50,286 |
def calculate_background_gradient(u, v, w, weights, u_back, v_back, Cb=0.01):
"""
Calculates the gradient of the background cost function. For each u, v
this is given as 2*coefficent*(analysis wind - background wind).
Parameters
----------
u: Float array
Float array with u component of ... | 50,287 |
def recreate_directory(directory_path):
"""Delete directory if exists, create empty directory. Throw an exception if
either fails."""
if not shell.remove_directory(directory_path, recreate=True):
raise Exception('Failed to recreate directory: ' + directory_path) | 50,288 |
def read_embedding_vocabularies(filenames):
"""
Reads every vector embedding file in the given collection of
filenames, and returns the union of their vocabularies. (The
files are assumed to be hdf5 files containing dataframes, and
the vocabularies are their indices.
"""
result = pd.Inde... | 50,289 |
def sorted_keys(lut: dict) -> list:
"""returns sorted lut keys if env_flags[sorted] is set to True"""
if env_flags['sorted'] is True or str(env_flags['sorted']).lower() == 'true':
return sorted(lut.keys(), key=lambda x: x)
return lut.keys() | 50,290 |
def run_pivot_report(property_id="YOUR-GA4-PROPERTY-ID"):
"""Runs a pivot query to build a report of session counts by country,
pivoted by the browser dimension.."""
client = BetaAnalyticsDataClient()
request = RunPivotReportRequest(
property=f"properties/{property_id}",
date_ranges=[
... | 50,291 |
def sigmax(dim=2):
"""Qiskit wrapper of sigma-X operator.
"""
if dim == 2:
return ops.sigmax()
else:
raise Exception('Invalid level specification of the qubit subspace') | 50,292 |
def is_relative_path(p):
""" Return True if path is relative """
p = p.replace('\\', '/')
if p and p[0] == '/':
return False
if sabnzbd.WIN32 and p and len(p) > 2:
if p[0].isalpha() and p[1] == ':' and p[2] == '/':
return False
return True | 50,293 |
def setting_keybord(
is_admin: bool, language: str, session_timeout: int
) -> types.InlineKeyboardMarkup:
"""انشاء كيبورد الاعدادات
المعطيات:
is_admin (bool): هل الكيبورد مرسل لادمن
language (str): لغة االكيبورد
session_timeout (int): وقت الجلسة
المخرجات:
types.InlineKe... | 50,294 |
def IoU(bbox1, bbox2):
"""Compute IoU of two bounding boxes
Args:
bbox1 - 4-tuple (x, y, w, h) where (x, y) is the top left corner of
the bounding box, and (w, h) are width and height of the box.
bbox2 - 4-tuple (x, y, w, h) where (x, y) is the top left corner of
the bou... | 50,295 |
def query_GTEx_service(
snps,
genes,
to_query,
p_values,
num_processes,
output_dir):
"""Queries GTEx for eQTL association between SNP and gene.
Args:
snps: The dictionary of SNP fragments returned from process_inputs
genes: The dictionary of genes... | 50,296 |
def filter_red_pen(rgb, output_type="bool"):
"""
Create a mask to filter out red pen marks from a slide.
Args:
rgb: RGB image as a NumPy array.
output_type: Type of array to return (bool, float, or uint8).
Returns:
NumPy array representing the mask.
"""
result = (
... | 50,297 |
def start():
"""
Start a new instance of Bewaarbot.
"""
print("Bewaarbot initializing")
start_bot() | 50,298 |
def project_delete(request, project_slug):
"""
Make a project as deleted on POST, otherwise show a form asking for
confirmation of delete.
"""
project = get_object_or_404(request.user.projects.live(),
slug=project_slug)
if request.method == 'POST':
# Remo... | 50,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.