content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _check_supports_private_deps(repository_ctx, swiftc_path, temp_dir):
"""Returns True if `swiftc` supports implementation-only imports."""
source_file = _scratch_file(
repository_ctx,
temp_dir,
"main.swift",
"""\
@_implementationOnly import Foundation
print("Hello")
""",
)... | 4971d84914b957f80e467b6956395806e06117bf | 3,629,653 |
def createNullOperator(context, domain, range, dualToRange, label=None):
"""
Create and return a null (zero-valued) operator.
*Parameters:*
- context (Context)
A Context object to control the assembly of the weak form of the
newly constructed operator.
- domain (Space)... | 149ee689c30f6da1ac47c418de41533dc1706663 | 3,629,655 |
def stsb(dataset):
"""Convert STSB examples to text2text format.
STSB maps two sentences to a floating point number between 1 and 5
representing their semantic similarity. Since we are treating all tasks as
text-to-text tasks we need to convert this floating point number to a string.
The vast majority of the... | a19664d2fd7b24efa132852fbb39dd9300b73f59 | 3,629,656 |
def scatter_matrix(df,theme=None,bins=10,color='grey',size=2):
"""
Displays a matrix with scatter plot for each pair of
Series in the DataFrame.
The diagonal shows a histogram for each of the Series
Parameters:
-----------
df : DataFrame
Pandas DataFrame
theme : string
Theme to be used (if not the defa... | db92ed3b03ecb081364e7f50ddbb9b0a777ce820 | 3,629,659 |
def _gr1_sorted_ ( graph , reverse = False ) :
"""Make sorted graph
>>> graph = ...
>>> s = graph.sorted()
"""
oitems = ( i for i in graph.iteritems() )
sitems = sorted ( oitems , key = lambda s :s[1].value() , reverse = reverse )
new_graph = ROOT.TGraphErrors ( len( g... | 147edad4505c9d7ab5df181d6e731e8c7f6713b3 | 3,629,660 |
def compute_features_paa(filename, with_timebase=False, verbose=False):
"""compute_features_paa
Compute a bag of standard audio features to be used for some
downstream task.
"""
if verbose:
print('compute_features_paa loading from {0}'.format(filename))
[Fs, x_] = audioBasicIO.read_audi... | 2a91c4dfc64bcae6b79c6a5f0bfd5f7fdeac2db6 | 3,629,661 |
def str_match_end(name, strip):
"""
:param name:
:param strip:
:return:
"""
if name is None:
return False
if name[len(name)-len(strip):len(name)] == strip:
return True
return False | ba9c84644d22f0b2ce68f7cb6efb1279209084f8 | 3,629,662 |
def points(start, end):
"""
Bresenham's Line Drawing Algorithm in 2D
"""
l = []
x0, y0 = start
x1, y1 = end
dx = abs(x1 - x0)
dy = abs(y1 - y0)
if x0 < x1:
sx = 1
else:
sx = -1
if y0 < y1:
sy = 1
else:
sy = -1
err = dx - dy
whil... | ffa8be5eb09e2b454242e4095883bfee239e5319 | 3,629,664 |
import re
def ExtractIconReps(icon_file_name):
"""Reads the contents of the given icon file and returns a dictionary of icon
sizes to vector commands for different icon representations stored in that
file.
Args:
icon_file_name: The file path of the icon file to read.
"""
with open(icon_file_n... | 14cbe3a9d8ee107fd60643dc61648cfeba3167ae | 3,629,665 |
def _is_device_list_local(devices):
"""Checks whether the devices list is for local or multi-worker.
Args:
devices: a list of device strings, either local for remote devices.
Returns:
a boolean indicating whether these device strings are for local or for
remote.
Raises:
ValueError: if device ... | adb1c414f8e22ecab3a31a0cd61666d96af1acfd | 3,629,666 |
def ab_from_mv(m, v):
"""
estimate beta parameters (a,b) from given mean and variance;
return (a,b).
Note, for uniform distribution on [0,1], (m,v)=(0.5,1/12)
"""
phi = m*(1-m)/v - 1 # z = 2 for uniform distribution
return (phi*m, phi*(1-m)) | 0326c165e44c1ab9df091e0344f12b9fab8c0e19 | 3,629,667 |
def get_credentials():
"""Get the Google credentials needed to access our services."""
credentials = GoogleCredentials.get_application_default()
if credentials.create_scoped_required():
credentials = credentials.create_scoped(SCOPES)
return credentials | 196013b7e49a87ca43a6824a02cf72db830e5420 | 3,629,668 |
def mtrax_mat_to_big_arrays(data):
"""translation of code sent to me by alice"""
if np.any(~np.isfinite(data['identity'])): # make sure no funny numbers
raise ValueError('cannot handle non-finite data on identity')
identity = np.array( data['identity'], dtype=int ) # cast to int
assert np.allclo... | f7c7b2d9c3e731cf7af05aa771e3739ddc66df95 | 3,629,669 |
from typing import Union
def normalize_class(c:Union[str,int], ensure_scored:bool=False) -> str:
""" finished, checked,
normalize the class name to its abbr.,
facilitating the computation of the `load_weights` function
Parameters
----------
c: str or int,
abbr. or SNOMEDCTCode of the... | 320710e59ba585c1de276be4b0195335127c08c8 | 3,629,670 |
def appearance_kernel(x_1: int, y_1: int, p_1: np.ndarray,
x_2: int, y_2: int, p_2: np.ndarray,
theta_alpha: float, theta_beta: float) -> float:
"""Compute appearance kernel.
Args:
x_1: X coordinate of first pixel.
y_1: Y coordinate of first pixel.
... | 4d9f70268baba752352de5e3c692e0bc2ceaac64 | 3,629,671 |
def update_game_log_tables(player_id, season):
"""
Loads player's game for specific season as pandas DataFrame
:param player_id: string,
:param season: int
:return: column names, table data for 'games-table' object and table title for text object
"""
global df_reg_games, df_po_games, df_ids
... | 0627694434e26118b93587265bde710840f8d4a2 | 3,629,672 |
from datetime import datetime
def _convert_relative_time(relative_time):
"""
Convert a Cb Response relative time boundary (i.e., start:-1440m) to a device_timestamp:
device_timestamp:[2019-06-02T00:00:00Z TO 2019-06-03T23:59:00Z]
"""
time_format = "%Y-%m-%dT%H:%M:%SZ"
minus_minutes = relative_... | 533b2c6b53d9f34754f8d5f1452c9b4caf93108c | 3,629,673 |
def NTFSolve_conv(M, Mmis, Mt0, Mw0, Mb0, nc, tolerance, LogIter, Status0, MaxIterations, NMFFixUserLHE, NMFFixUserRHE, NMFFixUserBHE,
NMFSparseLevel, NTFUnimodal, NTFSmooth, NTFLeftComponents, NTFRightComponents, NTFBlockComponents, NBlocks, NTFNConv, NMFPriors, myStatusBox):
"""Estimate NTF matrices ... | a84e5e561ac692f7996c675a26b0e8eaf791d50c | 3,629,674 |
def fds_remove_crc_gaps(rom):
"""Remove each block's CRC padding so it can be played by FDS
https://wiki.nesdev.org/w/index.php/FDS_disk_format
"""
offset = 0x0
def get_block(size, crc_gap=2):
nonlocal offset
block = rom[offset : offset + size]
offset += size + crc_gap
... | 935ecb4ac01c1256ec074f6888704fdd1db63ea4 | 3,629,675 |
def _apply_categorical_projection_naive(y, y_probs, z):
"""Naively implemented categorical projection for checking results.
See (7) in https://arxiv.org/abs/1802.08163.
"""
batch_size, n_atoms = y.shape
assert z.shape == (n_atoms,)
assert y_probs.shape == (batch_size, n_atoms)
v_min = z[0]
... | 3674e57a75508a22a3b12cda52e4fc06fa947d20 | 3,629,676 |
def truncatewords(base, length, ellipsis="..."):
"""Truncate a string by words"""
# do we need to preserve the whitespaces?
baselist = base.split()
lenbase = len(baselist)
if length >= lenbase:
return base
# instead of collapsing them into just a single space?
return " ".join(baseli... | f6472c7511e7e9abf03d4da3ed10c94ef070f78a | 3,629,678 |
def normalising_general(data,scoreMAX=[20,27,100,21],scoreMIN=[0,0,0,0],cumsum=True):
"""Normalises the data of the patient with missing count.
Parameters
----------
data : numpy data, [number of observations, number of features]
scoreMAX: max scores for asrm and qids
scoreMIN: min scores for a... | 560e63c79777ab3c3cb4550142ee68bd0ea3c621 | 3,629,679 |
import tokenize
import io
import token
def fix_lazy_json(in_text):
"""
This function modifies JS-contained JSON to be valid.
Posted in http://stackoverflow.com/questions/4033633/handling-lazy-json-\
in-python-expecting-property-name by Pau Sánchez (codigomanso.com)
"""
tokengen = toke... | 9d46297d9beb21fc2368322fe69cd9ab266f733b | 3,629,681 |
def get_project_family(repo, namespace=None, username=None):
"""Return the family of projects for the specified project
{
code: 'OK',
family: [
]
}
"""
allows_pr = flask.request.form.get("allows_pr", "").lower().strip() in [
"1",
"true",
]
allows_iss... | 3a208818e3a30911cd58e459de139aceb485ceb0 | 3,629,682 |
import warnings
def transform(
f,
apply_rng=False,
state=False,
) -> Transformed:
"""Transforms a function using Haiku modules into a pair of pure functions.
The first thing to do is to define a `Module`. A module encapsulates some
parameters and a computation on those parameters:
>>> class MyMo... | 422fe9850df87ac3db738e889461405b36443413 | 3,629,683 |
def direct_to_waypoint(aircraft_id, waypoint_name):
"""
Request aircraft to change heading toward a waypoint.
Parameters
----------
aircraft_id : str
A string aircraft identifier. For the BlueSky simulator, this has to be
at least three characters.
waypoint_name : str
A ... | 0c26bc72a994f14dc4df4c56de24b4637dd5f383 | 3,629,684 |
import re
def username_allowed(username):
"""Returns True if the given username is not a blatent bad word."""
if not username:
return False
blacklist = cache.get(USERNAME_CACHE_KEY)
if blacklist is None:
f = open(settings.USERNAME_BLACKLIST, "r")
blacklist = [w.strip() for w i... | 42f856baf3d5e704af0ce0780a9ecbb0984b465b | 3,629,685 |
def satisfiability(p=5, ratio=2.0, pr_edge=0.5, pr_exo=0.3, dsp_scm=True):
"""
Count the number of attempts to generate a linear P-SCM that can be uniquely recovered
(i.e., satisfies the derived conditions).
:param p: Number of observed nodes
:param ratio: Source to observed node ratio. (Num... | 596b8267b915f8b0dcf0e7bc993fa5ff9a62e1b9 | 3,629,686 |
def next_update_time(m):
"""Return the next update time. If the UpdateFrequency or Modified
"""
last_mod = m.doc['Root'].find_first_value('Root.Modified')
if last_mod:
last_mod = parse(last_mod)
else:
return False
uf = m.doc['Root'].find_first_value('Root.UpdateFrequency')
... | 8bd149b95719691a83563111a196e2b8ab900f99 | 3,629,688 |
import random
def random_permutation(iterable, r=None):
"""Random selection from itertools.permutations(iterable, r)"""
pool = tuple(iterable)
if r is None:
r = len(pool)
return list(random.sample(pool, r)) | 09e9f22def2c1125bf0ffc50db73659eaac65105 | 3,629,689 |
def rabin_karp_pattern_set(test_file_text, k):
""" Given a document to detect matches for, creates a set of
for the "rolling" hashcodes of each shingle.
Runtime: O(len(test_file_text)) with a very small constant factor
@param test_file_text: string of file to detect matchse for
@param k: length of shingles
@re... | dda851974207490717f9dcd1449cc83905fe7e83 | 3,629,690 |
def get_hms(t_sec):
"""Converts time in seconds to hours, minutes, and seconds.
:param t_sec: time in seconds
:return: time in hours, minutes, and seconds
:rtype: list
"""
h = t_sec//3600
m = (t_sec - h*3600)//60
s = t_sec%60
return h,m,s | f873ea04905ebcc5b41a394a4dd880a566623c83 | 3,629,691 |
from typing import Dict
def check_model_version_name(model_name: Text, model_version: Dict) -> bool:
"""Check model version name.
Args:
model_name {Text}: model name
model_version {Dict}: model version dictionary
Returns:
True if model names are matches, otherwise false
"""
... | eed0b9a8a9b25fac8c1818ed18fa59a01a55b5f3 | 3,629,692 |
def task_jshat_app_watch():
"""JsHat application - build all on change"""
return {'actions': ['yarn run --silent watch '
'--config webpack.app.config.js'],
'task_dep': ['jshat_deps']} | 96d9d42e5145cfb2aef3cc91362eb3c9da244ff7 | 3,629,694 |
from etools_permissions.models import Realm
def get_realm(request):
"""
Currently not setting realm in session, so using user to get realm
Expect tenant attribute to be set on request in Workspace in use,
if user not set or user is superuser, then no tenant
"""
realm = None
if request.use... | b3c0a678553d2cd1da982a44a8376686a6f0f7af | 3,629,695 |
def _marked_merging(A, criterion_fn, node_weights=None):
""" Method of paper 'Weighted Graph Cuts without Eigenvectors: A Multilevel Approach' """
if node_weights is None:
node_weights = np.ones(A.shape[0])
unmarked_vertices = list(np.arange(A.shape[0]))
edges_to_merge = np.zeros_like(A)
whi... | 11fe427a8cd0697c123a8c503afdde28dba3b824 | 3,629,696 |
def fast_aggregate(X, Y):
"""If X has dims (T, ...) and Y has dims (T, ...), do dot product for each T to get length-T vector.
Identical to np.sum(X*Y, axis=(1,...,X.ndim-1)) but avoids costly creation of intermediates,
useful for speeding up aggregation in td by factor of 4 to 5."""
T = X.shape[0]
... | dfcb15bdb9555fead4d37ab03c5112a13f944f52 | 3,629,697 |
def GroupConv2D(filters,
kernel_size,
strides=(1, 1),
groups=32,
kernel_initializer='he_uniform',
use_bias=True,
activation='linear',
padding='valid',
**kwargs):
"""
Grouped Convolutio... | 16f4162859bd2186f508800fae04b1a493aa7a33 | 3,629,698 |
def shift(seq: Sequent) -> Sequent:
"""
The :math:`\\textbf{Opt${}^?$}` :math:`\\texttt{shift}` rule.
From an :math:`n`-opetope :math:`\\omega`, creates the
globular :math:`(n+1)`-opetope
:math:`\\lbrace []: \\omega`.
"""
n = seq.source.dimension
ctx = Context(n + 1)
for a in seq.sou... | d306604f6f809a2b38fb147e68f76b7d6e733435 | 3,629,699 |
from torchvision.models.vgg import vgg11_bn
from torchvision.models.vgg import vgg11
def vgg_11(batch_norm=True, pretrained=False, fixed_feature=True):
""" VGG 11-layer model from torchvision's vgg model.
:param batch_norm: train model with batch normalization
:param pretrained: if true, return a model pretrained... | 645b79fa96e3bce65e6f0191a78c9cff88c99fb9 | 3,629,700 |
def Wavelet_hardSoft(s, jN, wname, alpha=0.5):
"""
小波折中阈值滤波
:param s:
:param jN:
:param wname:
:param alpha:
:return:
"""
ca, cd = wavedec(s, jN, wname)
for i in range(len(ca)):
thr = np.median(cd[i] * np.sqrt(2 * np.log((i + 2) / (i + 1)))) / 0.6745
di = np.array... | f1f348345151e6dcb3dd347a6e51612341ee4bd3 | 3,629,702 |
def compute_vad(log_energy, energy_mean_scale=0.5, energy_threshold=0.5, frames_context=0, proportion_threshold=0.6):
""" Apply voice activity detection
:param log_energy: Log mel energy.
:param energy_mean_scale: If this is set to s, to get the actual threshold we let m be the mean log-energy of the file,... | 1b9370494892e18447014cc6850ad528b8786304 | 3,629,703 |
def current_velocity(x_new, x_prev, h):
""" returns current velocity of a particle from next
position at timestep. """
"""
parameters
----------
x_new : array
new x-position of particle
x_prev : array
previous x-position of particle
h : float
simulation timestep
... | 33d47f901be44fed20613957459aca1eecd5ea2c | 3,629,704 |
import csv
def csvReadCallback(inputFile, **kw):
"""Read callback for CSV data"""
inputFile.readline() # skip header
reader = csv.reader(inputFile, lineterminator='\n', **kw)
return [row for row in reader] | e36c92e5792e905da22438a58c8ce810c2a22e2a | 3,629,705 |
def get_interface_config_commands(interface, intf, existing):
"""Generates list of commands to configure on device
Args:
interface (str): k/v pairs in the form of a set that should
be configured on the device
intf (str): full name of interface, i.e. Ethernet1/1
Returns:
lis... | 745dd81a3a45de14d8dd9c58a4e64b78b310136e | 3,629,706 |
def load_word():
""" return the sql and values of the insert queuery."""
sql = """
INSERT INTO Spanglish_Test.Word
(
`word`, `language_id`, `category_id`
)
VALUES (%s, %s, %s)
"""
values = [
(
'Ir', 2, 1
),
... | f0d836f5ca912865f9d75a5e6c10c13cf554674b | 3,629,707 |
def AttenLogitsRPE(query, key, abs_pos_emb, is_causal):
"""Attention logits from ...
https://arxiv.org/pdf/1803.02155.pdf with trainable rel position emb.
Notice padding is supposed to be masked by the caller of this function.
B: batch size
T: sequence length
N: num of attention heads.
H: per-head atte... | d7d99c4ad07089e61516dd65b5765568542887a2 | 3,629,708 |
def normalize_answer(s):
"""Lower text and remove punctuation, articles and extra whitespace."""
def remove_articles(text):
return re_art.sub(' ', text)
def white_space_fix(text):
return ' '.join(text.split())
def remove_punc(text):
return re_punc.sub(' ', text) # convert punctu... | 80e30ee45d665fca1c2ebdd20226da249028064e | 3,629,709 |
def qso_template_uv(wa, z):
""" Return a composite UV QSO spectrum at redshift z.
Wavelengths must be in Angstroms.
This is a smoothed version of the HST/COS EUV+FUV AGN composite
spectrum shown in Figure 5 of Shull, Stevans, and Danforth 2012.
Only good between 550 and 1730 Angstroms (rest frame... | 9c70e2f9c88b3d851951cd3e1b77638c21b99227 | 3,629,710 |
def encode_multipart_formdata(fields, files):
"""
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be uploaded as files
Return (headers, body) ready for httplib.HTTP instance
based on http://code.activest... | 7948d8ff0a2785b84c2e9a7e85182fa5db772692 | 3,629,711 |
from datetime import datetime
def get_ppl_experience(log_entries: QuerySet) -> dict:
"""
https://www.easa.europa.eu/sites/default/files/dfu/Part-FCL.pdf
(a) Applicants for a PPL(A) shall have completed at least 45 hours of flight instruction in aeroplanes or TMGs,
5 of which may have been complet... | 1fb2421352954c837b27fa46a47f36029a560ed8 | 3,629,713 |
import torch
def reconstruct_from_patches_2d(patches, img_shape, step=[1.0,1.0], batch_first=False):
"""Given patches generated from extract_patches_2d function, creates the original unpatched image. We keep track of the
overlapped regions and average them in the end.
Parameters:
patches ... | 35b03ee61dd5a2749601e839d7ade75d1b686383 | 3,629,714 |
def _LJ_rminepsilon_to_ab(coeffs):
"""
Convert rmin/epsilon representation to AB representation of the LJ
potential
"""
A = coeffs['epsilon'] * coeffs['Rmin']**12.0
B = 2 * coeffs['epsilon'] * coeffs['Rmin']**6.0
return {"A": A, "B": B} | 0963c0e8b949d35842660a499ce80a388485773f | 3,629,716 |
def get_offset_stars_ps1(df, target_name_column, target_ra_column,
target_dec_column, radius, data_release='dr2',
catalog='mean', quality_query=None, n=3, verbosity=0):
"""Get offset stars for all targets in the input DataFrame for PanSTARRS
using the MAST website.
... | f86390ba3a114934f682169ae82b830002e8a647 | 3,629,717 |
from yaml import load
from yaml import CLoader as Loader
from yaml import Loader
def _from_yaml(stream):
"""Load data form a YAML file or string."""
try:
except ImportError:
data = load(stream, Loader=Loader)
return data | 5fb82419c2705cb14077164b954aac530b5ddefb | 3,629,718 |
def is_unit_by_ten_thousand(text: str) -> bool:
"""
是否是以万为计量单位
@param: text 薪资描述字符串
@rtype: bool
"""
log.info(f'invoke method -> is_unit_by_ten_thousand(), salary unit text: {text}')
try:
unit = NumericUnit(text.strip())
except ValueError as e:
log.error(str(e))
r... | aeeac44391f5d06a181fd22246a510d16b500c9b | 3,629,719 |
def had_cells_north_edge(strmfunc, frac_thresh=0.1, lat_str=LAT_STR,
lev_str=LEV_STR):
"""Latitude of northern edge of northern Hadley cell."""
return had_cell_edge(
strmfunc,
cell="north",
edge="north",
frac_thresh=frac_thresh,
lat_str=lat_str,
... | f764801ef8047169b9138b696e52d24ef340369d | 3,629,720 |
def get_referrers(*objs): # real signature unknown; restored from __doc__
"""
get_referrers(*objs) -> list
Return the list of objects that directly refer to any of objs.
"""
return [] | a16f99e392b66b0b03d3dd298334b0af4d7d1246 | 3,629,721 |
def margAccRepay(asset, amount, isIsolated="", symbol="", recvWindow=""):
"""# Margin Account Repay (MARGIN)
#### `POST /sapi/v1/margin/repay (HMAC SHA256)`
Repay loan for margin account.
### Weight:
1
### Parameters:
Name |Type |Mandatory |Description
--------|--------|--------|--------
asset |STRING |YES |
isIso... | 639c9f33889ee97e1db95dccdb814a1becb79ba5 | 3,629,722 |
def clean_formula(formula: str) -> str:
"""
Translate mongo's syntax to hande columns names containing spaces to pandas syntax.
Example:
>>> clean_formula('colA * `col B` * [col C] * `[col D]`')
'colA * `col B` * `col C` * `[col D]`'
"""
formula_splitted = COLUMN_PATTERN.split(formu... | 522cfe6f5481e665e7cf0df136f6a2f384607eab | 3,629,723 |
def calculate_SI(aggregated_df):
""" calculates suspicion of infection as per Sepsis-3 on aggregated hourly dataframe and saves it under the column `suspicion_of_infection`.
Note:
aggregated_df must contain `antibiotics` and `microbio-sample` columns.
"""
df = aggregated_df[['hadm_id', 'hour', ... | 88f0fb6285c3fc2826168f01416e1e825b2ed4cc | 3,629,724 |
def _get_reduce_batch_axis(axis, x_dim, x_ndim):
"""get batch_axis for reduce* operation."""
if not isinstance(axis, tuple):
axis = (axis,)
batch_axis = ()
if axis:
for index in axis:
if index < x_dim:
batch_axis = batch_axis + (index,)
else:
... | b2a41f5e03c0388c70d2690793329d922f2d3248 | 3,629,725 |
def no_game_no_life(seed, rules, iterations, print_list):
"""
>>> rules = {3 : 1, 4 : 1, 8 : 1, 10 : 1, 11 : 1, 12 : 1, 15 : 1, 21 : 1,
... 23 : 1, 26 : 1, 27 : 1, 28 : 1, 29 : 1, 30 : 1}
>>> current_plants = no_game_no_life('1001010011000000111000111', rules, 20, True)
1000100001000001001001001
... | f8f8ab138a331cd413f3b730afd443c4a3de0e8c | 3,629,726 |
def evalrawexp(context, mapping, arg):
"""Evaluate given argument as a bare template object which may require
further processing (such as folding generator of strings)"""
func, data = arg
return func(context, mapping, data) | dc443da540bef0fe1198b12c0205921f0de66b2e | 3,629,727 |
def _execute_single_config_query(query_name, np1_list, peer_container, output_config):
"""
Runs a query on single set of policies
:param str query_name: the name of the arg.query
:param str np1_list: set of policies
:param PeerContainer peer_container: set of peers
:param OutputConfiguration out... | f49cbe947c952535ea72e0959ab35d9af724c854 | 3,629,728 |
from typing import Tuple
def shape(A: Matrix) -> Tuple[int, int]:
"""returns the shape of a given matrix"""
num_rows = len(A)
num_cols = len(A[0]) if A else 0
return num_rows, num_cols | d0a76a63444d3b5e541d738eca591ff0a868da40 | 3,629,730 |
import functools
def integrity(integrity_func, retry_errors=(ResponseNotValid,)):
"""
Args:
:param integrity_func: couldb callable or string contains name of
method to call
"""
def build_decorator(func):
@functools.wraps(func)
def func_wrapper(self, grab, task):
... | de5ec2e8039919620bb448d8faedd6fe1fcc12fc | 3,629,731 |
def _convert_evaluation_data_to_frame(steps, evals):
"""Convert evaluation data to (tidy) data frame.
Args:
steps (namedtuple): Namedtuple with field names pos and neg. Is generated by
:func:`~estimagic.differentiation.generate_steps.generate_steps`.
evals (namedtuple): Namedtuple w... | 5ac049ed1b2e213e328b883905cf703ab9edde52 | 3,629,733 |
def unsharp_mask(rgb: np.ndarray, sigma: float, alpha=2.0) -> np.ndarray:
"""シャープ化。sigmaは0~1程度、alphaは1~2程度がよい?"""
rgb = ensure_channel_dim(rgb)
blured = blur(rgb, sigma)
rgb = rgb.astype(np.float32)
rgb = rgb + (rgb - blured) * alpha
return to_uint8(rgb) | 5c74995d7e322c1ff432320d8f18232bfcfdf4fb | 3,629,734 |
async def async_get_actions(hass: HomeAssistant, device_id: str) -> list[dict]:
"""List device actions for RFXCOM RFXtrx devices."""
try:
device = async_get_device_object(hass, device_id)
except ValueError:
return []
actions = []
for action_type in ACTION_TYPES:
if hasattr(... | d821c4e17dc4944b9cfe126e6cd959725d0a7b27 | 3,629,735 |
async def initialize_settings(user=Depends(login_required)):
"""
### 세팅값 초기화
- force: True일 경우 기존 값 초기화
"""
SettingModel.initialize(first=False)
return Response('Success', status_code=status.HTTP_200_OK) | 4e95029db3dcad14c7e08400d358b5fd098ad0b9 | 3,629,736 |
def build_generator(z_input: Input, label_input: Input):
"""
Build generator CNN
:param z_input: latent input
:param label_input: conditional label input
"""
model = Sequential([
Dense(128, input_dim=latent_dim),
LeakyReLU(alpha=0.2), BatchNormalization(momentum=0.8),
De... | e809026b7f4e326d8bd7190fa667b14888948688 | 3,629,737 |
import json
def annotate(project_id, document_id):
"""Annotate document with provided ID.
:param project_id: project id
:param document_id: document id
:return: rendered template
"""
current_user = auth.current_user
document_id = str(document_id)
project = services.get_project(current... | dc215edaf0e5d9829451b0e3c0adfe485db24231 | 3,629,738 |
def send_query_search_request(query, page):
"""Send a request to get one page of results for a query."""
logger.info(f'Sending a request for query {query}, page {page}')
return send_request(
query_url,
{'query': query, 'inclusive': True, 'page': page, 'api_key': api_key}) | 1ecfd2af4c61a1ccd811c506d25d6e9648ec9788 | 3,629,739 |
def find_stab(state, xs, zs):
"""
Find a stabilizer in the stabilizer group.
Args:
state:
logical_circuit:
delogical_circuit:
Returns:
"""
stabs = state.stabs
destabs = state.destabs
# Find the destabilizer generators that anticommute with the stabilizer indi... | 07987377192cb4a4fa8cc35bd13d7566a838778c | 3,629,740 |
def get_darwin_memory():
""" Use system-call to extract total memory on macOS """
system_output = sabnzbd.newsunpack.run_simple(['sysctl', 'hw.memsize'])
return float(system_output.split()[1]) | 16329528b4f9ea1ced90446e717f750276026f38 | 3,629,741 |
def normalise_release(release, area):
"""Try to normalise the release name.
None is a valid argument.
Note that the current policy to is accept any release name if an existing
tag is to be used, and only perform the normalisation on tags to be created
by this script.
Arguments:
releas... | 83fe9c7277aacc54b8679ab1f5cc7c5a1d3cebf6 | 3,629,742 |
from typing import Optional
def _pytd_return_type(
name: str,
return_type: Optional[pytd_node.Node],
is_async: bool
) -> pytd_node.Node:
"""Convert function return type to pytd."""
if name == "__init__":
if (return_type is None or
isinstance(return_type, pytd.AnythingType)):
ret = py... | 9e960570fd4064aaf0168b62214b9c0b53288236 | 3,629,743 |
def getvpidx(rate, bdepth):
"""Get the token numbers for indices of value and policy vectors."""
qpm = getqpm(rate, bdepth)
vidx = np.arange(qpm[0], qpm[2]+1, dtype=np.float64)/qpm[1]
pidx = np.arange(qpm[1], qpm[2]+1, dtype=np.float64)/qpm[1]
return vidx, pidx | 93783c23dff9f3122b994be41a084fdc9d63e2d4 | 3,629,744 |
import functools
def apply_on_axis(op, inputs, axis, *args, **kwargs):
"""Applies a differentiable operator on a given axis of the input.
Args:
op: a differentiable operator (can be ranks, quantile, etc.)
inputs: jnp.ndarray<float> of any shape.
axis: the axis (int) or tuple of ints on which to apply... | 2ef84e164acb1f018a5f4e7e7ef3a289f99886d4 | 3,629,745 |
from django.utils.text import normalize_newlines
import re
def clean_html(text):
"""
Clean the given HTML. Specifically, do the following:
* Convert <b> and <i> to <strong> and <em>.
* Encode all ampersands correctly.
* Remove all "target" attributes from <a> tags.
* Remove ex... | 7598a8c18e3cf3fc9bc256c33aed52a11c4bfa88 | 3,629,746 |
def get_report_importer_cls(library_name):
""" Return a ReportImporter class to handle importing a specific library's report information. """
lib_module = find_library_module(library_name)
if lib_module:
try:
return lib_module.REPORT_IMPORTER_CLASS
except AttributeError:
... | 964137420816bfbeb0eb7d22c861633dfd9efb67 | 3,629,747 |
def read_reddened_stars(filename):
"""
Read reddened stars from a text file.
Parameters
----------
filename : str
The name (with a path if neccessary) of the file which
has 5 five columns. The first one with integers, the rest
with floats. Each column represents: star_id, x_... | e9c50f90d9499cfa8544f41c808992ba10899ded | 3,629,748 |
def rotate_pil(image, angle, center=None, scale=1.0):
"""PIL旋转图像
效果比Image.rotate效果要好,调用rotate进行实现
"""
image = np.asarray(image)
rotated = rotate(image, angle)
return Image.fromarray(rotated) | 1ae75ddba68540b3b7b02cdeb11d62b7b9152fe0 | 3,629,749 |
def pobj_len(this):
"""
returns length (of String, List or Dict)
"""
return _new_pobj(Number, len(this.getvalue())) | 071abd1446e6e1d2394b41ccbf3063c6881f3505 | 3,629,750 |
def _compressed_sparse_stack(blocks, axis):
"""Fast path for stacking CSR/CSC matrices
(i) vstack for CSR, (ii) hstack for CSC.
"""
other_axis = 1 if axis == 0 else 0
data = cupy.concatenate([b.data for b in blocks])
constant_dim = blocks[0].shape[other_axis]
idx_dtype = sputils.get_index_dt... | 934ad0b1d1a26da3496b78e4a4c549c32a7923e5 | 3,629,751 |
def _parse_wall_max_height(response: HtmlResponse):
"""Parse max height of wall.
Returns 0 if not available.
"""
return _parse_length(response.css('th:contains("Höhe") + td ::text')) | b38ddbd8b9a6938fc57cf7cbfbb4feb1531b4525 | 3,629,752 |
def compatible(s1: Shape, s2: Shape):
"""Assert that two shapes are compatible shapes.
Args:
s1 (:class:`lab.shape.Shape`): First shape.
s2 (:class:`lab.shape.Shape`): Second shape.
Returns:
bool: Boolean indicating whether the two shapes are compatible.
"""
try:
ex... | 174b32f048fef109bc9383bdd8393f56fb3235b0 | 3,629,754 |
def get_job_service(request_type: RequestType) -> JobServiceInterface:
"""
This is a factory to get a corretly wired job service. Use that function to get any JobServiceInterface instance.
:param request_type: The request type. The JobServiceInterface is chosen and wired based on this type.
:return: Co... | 3ed998fc3ba19822100f7333bf69aa1ad4c6461e | 3,629,755 |
def get_index(repository_path, pkl_fname=PKL_FNAME):
"""
Return the index information for the EMTF repository located at
*repository_path*.
"""
pkl_fname, _ = initialize(repository_path, pkl_fname=pkl_fname)
with open(pkl_fname) as fid:
return cPickle.load(fid) | 1c3e3c333c0925ceeb167a8bfd32b4487c994454 | 3,629,756 |
def CycleTarget_to_c(self):
"""Syntax for a target of a cycle."""
return f"cycle_{self.targetID}: continue;" | 12cc7a57e5a24a62aba43ac99879d5a5d364ee29 | 3,629,757 |
def _run_ic(dataset):
"""Run iterative compression on a dataset."""
# Run
return solve_ic(
str(HUFFNER_DATA_DIR / (dataset + HUFFNER_DATA_EXT)),
timeout=EXACT_TIMEOUT,
preprocessing=2,
htime=min(0.3 * EXACT_TIMEOUT, 1)
) | a2e4bfd12d41720fe40a97f67294cd7234551525 | 3,629,758 |
from typing import Callable
def expect_jwt(
api: Api,
message: str = "JWT token is required and has the format: 'Bearer <token>'",
) -> Callable:
"""
Adds expected header to swagger,
validates JWT token is present,
adds token to g
"""
def decorator(func: Callable) -> Callable:
... | 414fd3339414ddd190b1a7457c14a2791e848353 | 3,629,760 |
def get_pythia_definitions(parsed_file):
"""
Return a dictionary of all Pythia definitions in the input parsed file,
of the form
"PythiaBothParam <NAME>=<LABEL>"
or
"PythiaBothParam <NAME>=<NUMBER>",
as {'NAME1': 'LABEL1', 'NAME2': VALUE2, ...}.
Parameters
----------
parsed_file... | 4363ee6180847e0991b6b4a9ed3a8636ce70725c | 3,629,761 |
def disable_layer_logging():
"""
Disable the shape logging for all layers from this moment on. Can be
useful when creating multiple towers.
"""
class ContainEverything:
def __contains__(self, x):
return True
# can use nonlocal in python3, but how
globals()['_LAYER_LOGGED'... | e05785f1ade46903c2e66efc35d4fc5f0e9d4fbd | 3,629,762 |
def remove_punct(word: Text) -> Text:
"""Removes punctuation from the word. Returns String."""
result = ''.join([char.lower() for char in word if char.isalpha()])
if len(result) > 0 and result != None:
return result | 7ea8282488a6ddb6f01ecf303b5353dbf2848b24 | 3,629,763 |
def onCapability(name, value):
"""
Run test only if capability with `name` equals `value`.
"""
capability = getattr(process_capabilities, name)
def check_capability():
return capability != value
return skipOnCondition(
check_capability, 'Capability "%s" not present.' % name) | 22ec305df57ee8b2c39d82789b2a5badbbb46225 | 3,629,764 |
from re import U
def WGS84ReferenceSystem():
"""
returns the `GeodeticReferenceSystem` for the WGS84 Ellipsoid
"""
return GeodeticReferenceSystem(a=6378137.0 *U.m, f=1/298.257223563, angular_unit=1*U.DEG, height_unit=100.*U.km, name="WGS84") | 05e1ba83b451eebab752bfe018cd2a0d09f434e3 | 3,629,765 |
def _remap_keypoints(keypoints, padded_w, padded_h, expand, data_shape, ratio):
"""
Remap bboxes in (x0, y0, x1, y1) format into the input image space
Parameters
----------
bboxes
padded_w
padded_h
expand
Returns
-------
"""
keypoints[:, 0::2] *= padded_w / (data_shape ... | 1b8d2520f0df1847967e8db9c565598d6b5ee2b6 | 3,629,766 |
def viz_mask(mask):
"""Given a (batch, w, h, 10) array, returns a visualization"""
rgb_palette = np.array([(248, 183, 205), (246, 210, 224), (200, 231, 245), (103, 163, 217), (6, 113, 183),
(249, 200, 14), (248, 102, 36), (234, 53, 70), (102, 46, 155), (67, 188, 205)])
mask =... | e889f7aa630ed6b98074eb26279ab8bd1b157faf | 3,629,767 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.