content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def truncate_out_cert_raw(origin_raw_str: str):
"""truncate the original ssl certificate raw str like:\n
-----BEGIN CERTIFICATE-----
raw_str_data...
-----END CERTIFICATE-----\n
and split out the raw_str_data"""
if not isinstance(origin_raw_str, str) or origin_raw_str == "":
raise Excepti... | 73,200 |
def addNewUser(db: Connection, userID: int) -> bool:
"""
Add new user to database
:param db: database object instance
:param userID: User ID
:return: Boolean True if no error
"""
if db is None:
return False
now: datetime = datetime.utcnow()
currentTime: str = now.strftime("%Y... | 73,201 |
def dv_dlogdp(dp, n, gm, gsd):
"""The volume weighted PDF of a lognormal distribution as calculated
using equation 8.20 from Seinfeld and Pandis.
.. math::
n_V^o(log D_p)=log(10)*D_p n_V(D_p)
Parameters
----------
dp : float or array of floats
Particle diameter in microns.
... | 73,202 |
def generate_lp_file_borda_owa(owa, lp_file_name, params, votes):
""" this function generates lp file"""
lp_file = open(lp_file_name, 'w')
lp_file.write("Maximize\nobj: ")
pos = 0
first = True
for i in range(params['voters']):
for j in range(params['orders']):
for k in range... | 73,203 |
def auto_pairing(ctx, status):
"""Configure auto-pairing status.
When auto-pairing is enabled, if no known device is available when adapter
is plugged in, a pairing is automatically done with first available device."""
adapter = ctx.obj['adapter']
if status is None:
with hid.Device(adap... | 73,204 |
def cmp_char(a, b):
"""Returns '<', '=', '>' depending on whether a < b, a = b, or a > b
Examples
--------
>>> from misc_utils import cmp_char
>>> cmp_char(1, 2)
'<'
>>> print('%d %s %d' % (1, cmp_char(1,2), 2))
1 < 2
Parameters
----------
a
Value to be compare... | 73,205 |
def retrieve_context_topology_node_owned_node_edge_point_available_capacity_bandwidth_profile_committed_burst_size_committed_burst_size(uuid, node_uuid, owned_node_edge_point_uuid): # noqa: E501
"""Retrieve committed-burst-size
Retrieve operation of resource: committed-burst-size # noqa: E501
:param uuid... | 73,206 |
def get_command_name(cmd, default=''):
"""Extracts command name."""
# Check if command object exists.
# Return the expected name property or replace with default.
if cmd:
return cmd.name
return default | 73,207 |
def ref_ad_factory(path_to_refs):
"""
Read the reference file.
Parameters
----------
path_to_refs : pytest.fixture
Fixture containing the root path to the reference files.
Returns
-------
function : function that loads the reference file.
"""
def _reference_ad(filename... | 73,208 |
def _getText(node):
"""
Obtains the text from the node provided.
@param node Node to obtain the text from.
@retval Text from the node provided.
"""
return " ".join(child.data.strip() for child in node.childNodes
if child.nodeType == child.TEXT_NODE) | 73,209 |
def make_connection_plus_from(conn: Union[sqlite3.Connection, ConnectionPlus]
) -> ConnectionPlus:
"""
Makes a ConnectionPlus connection object out of a given argument.
If the given connection is already a ConnectionPlus, then it is returned
without any changes.
Args:... | 73,210 |
def _update_sensor_geometry(info, fine_cal, ignore_ref):
"""Replace sensor geometry information and reorder cal_chs."""
from ._fine_cal import read_fine_calibration
logger.info(' Using fine calibration %s' % op.basename(fine_cal))
fine_cal = read_fine_calibration(fine_cal) # filename -> dict
ch_... | 73,211 |
def print_reshaped_data_dimension(x_train, y_train, x_val=None, y_val=None):
"""Print dimensions after reshaping data"""
print("\n\nAfter reshaping:\nTraining shape: ")
print(x_train.shape, y_train.shape)
if (x_val is not None) and (y_val is not None):
print("Validation shape: ")
print(... | 73,212 |
def polygonOffsetWithMinimumDistanceToPoint(point, polygon, perpendicular=False):
"""Return the offset from the polygon start where the distance to the point is minimal"""
return polygonOffsetAndDistanceToPoint(point, polygon, perpendicular)[0] | 73,213 |
def closeWindows():
"""
Closes all of the windows derived from QProxyWindow.
:rtype: None
"""
from dcc.userinterface import qproxywindow
qproxywindow.QProxyWindow.closeWindows() | 73,214 |
def get_package_versions(sha1, os_type, package_versions=None):
"""
Will retrieve the package versions for the given sha1 and os_type
from gitbuilder.
Optionally, a package_versions dict can be provided
from previous calls to this function to avoid calling gitbuilder for
information we've alrea... | 73,215 |
def get_configs_from_model_files(state: 'State', model_root = None, ignore_files: list = None) -> List[dict]:
"""
Assumes that all configs are defined within the model files:
models/m_{name}.py
and that each model file has a get_config() option which returns an array of all configs.
Each config... | 73,216 |
def get_arrdepth(arr):
"""
USAGE
-----
arr_depths = get_arrdepth(arr)
Determine number of nested levels in each
element of an array of arrays of arrays...
(or other array-like objects).
"""
arr = np.array(arr) # Make sure first level is an array.
all_nlevs = []
for i in ran... | 73,217 |
def get_ocid(prefix, tenderID):
"""greates unique contracting identifier"""
return "{}-{}".format(prefix, tenderID) | 73,218 |
def verify_soc_board_combination(args):
"""Verifies the given board exists for the SOC."""
soc_file = f"meta/socs/{args.soc}.yaml"
if not os.path.exists(soc_file):
raise SystemExit(f"SOC {args.soc} does not exist.")
all_boards = open_yaml(soc_file).get('boards', [])
if args.board not in all_... | 73,219 |
def main():
"""Make a jazz noise here"""
args = get_args()
str = args.str.upper()
codons = {}
for line in args.codons:
codon, protein = line.upper().split()
codons[codon] = protein
k = 3
proteins = []
for codon in [str[i:i + k] for i in range(0, len(str) - k + 1, k)]:
... | 73,220 |
def md5(fileName):
"""Compute md5 hash of the specified file"""
m = hashlib.md5()
try:
fd = open(fileName,"rb")
except IOError:
print("Reading file has problem:", filename)
return
x = fd.read()
fd.close()
m.update(x)
return m.hexdigest() | 73,221 |
def Kernel(x,f,theta):
"""
build square kernel matrix for inputs x with kernel function f and
parameters theta
Inputs
-------
x : vector
values to evaluate the kenrel function at, pairwise
f: kernel function
function that accepts inputs as (x1,x2,theta)
theta: vector
... | 73,222 |
def drop_duplicated_indices(df: Union[pd.Series, pd.DataFrame]) -> Union[pd.Series, pd.DataFrame]:
"""If one concatenates dataframes there might be duplicated
indices. This can lead to problems, e.g., in interpolation steps.
One easy solution can be to just drop the duplicated row
Args:
df (Uni... | 73,223 |
def report_response(params, runner=None, cache=DEFAULT_CACHE):
"""
This frontend helper function is meant to be used in your
request-processing code to handle all AJAX responses to the Blingalytics
JavaScript frontend.
In its most basic usage, you just pass in the request's GET parameters
as a ... | 73,224 |
def median( y, mask):
"""Return the median of the array y, ignoring masked elements.
Parameters
-----------
y : ndarray
array of values
mask : ndarray
array of (int32) ones or zeros (0 indicates a good value)
Returns
--------
med... | 73,225 |
def train_model(x_train, y_train_e, x_val, y_val_e, num_epochs, learning_rate):
"""
Train the model using the data given, along with the parameters given.
@param x_train is the training dataset.
@param y_train_e is an np.array of the training labels.
@param x_val is the validation... | 73,226 |
def run_forever():
"""Create the server instance using the above create_server method."""
server = create_server()
try:
print(f'Starting server on 127.0.0.1:5000')
server.serve_forever()
except KeyboardInterrupt as error:
print('Thanks for running the server. Shutting down...')
... | 73,227 |
def polynomial(a0,a1,a2,a3,a4,x):
"""
Up to x4
"""
return a0 + x*(a1+x*(a2+x*(a3+x*a4))) | 73,228 |
def fibo(f=1, g=1):
"""Yields Fibonacci numbers."""
while True:
yield f
f, g = g, f + g | 73,229 |
def find_place(word: Word, panel: Panel):
"""
Find a place for a word inside the panel. The position will be written into word.positions.
:param panel: The panel where the word should find a place.
:param word: The word which is looking for a place inside the panel.
:raise PermutationsExceededExce... | 73,230 |
def time_round(time, delta, epoch=None):
"""From https://stackoverflow.com/a/57877961/13775459"""
mod = time_mod(time, delta, epoch)
if mod < (delta / 2):
return time - mod
return time + (delta - mod) | 73,231 |
def resnet(info, depth=28, width=1):
"""Resnets of varying width and depth."""
N = (depth - 4) // 6
inputs = Input(shape=info.features['image'].shape)
x = Conv2D(16, (3, 3), padding='same')(inputs)
x = BatchNormalization()(x)
x = Activation('relu')(x)
for _ in range(N):
x = _residu... | 73,232 |
def get_str_md5(content):
"""
Calculate the MD5 for the str file
:param content:
:return:
"""
m = hashlib.md5(content) # 创建md5对象
return m.hexdigest() | 73,233 |
def cv_personal_info(request):
"""Add information about person to CV requests"""
return {'cv_personal_info': CV_PERSONAL_INFO} | 73,234 |
def make_test(row):
"""
Generate a test method
"""
def row_test(self):
actual = row.get("_actual")
if actual in ("P", "F"):
if actual == "P":
self.assertMeansTest("eligible", row)
else:
self.assertMeansTest("ineligible", row)
... | 73,235 |
def replace_german_umlaute(unicode_string):
"""."""
utf8_string = unicode_string.encode("utf-8")
print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
print("{}".format(utf8_string))
print(u"{}".format(utf8_string))
print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
for k in umlaute_dict.keys():
utf8_string ... | 73,236 |
def audio_conversion():
"""Convert audio file to MP3 and update metadata on mp3.
:return: Converted audio
"""
# For whatever reason temporary file was workable with subprocess.
tmp_path = os.path.join("/tmp", "audio_" + uuid.uuid4().hex + ".mp3")
try:
audio_bytes = request.files["audio_... | 73,237 |
def populate(contents_mgr):
"""
Populate a test directory with a ContentsManager.
"""
dirs_nbs = [
('', 'inroot.ipynb'),
('Directory with spaces in', 'inspace.ipynb'),
('unicodé', 'innonascii.ipynb'),
('foo', 'a.ipynb'),
('foo', 'name with spaces.ipynb'),
... | 73,238 |
def running_mean(clazz=None, batch_size=50, step_size=10, dim=None):
"""The :func:`running_mean` decorator is used to add a :class:`.RunningMean` to the :class:`.MetricTree`. If the
inner class is not a :class:`.MetricTree` then one will be created. The :class:`.RunningMean` will be wrapped in a
:class:`.To... | 73,239 |
def min_value(state, depth, max_depth, alpha, beta, transposition_table):
"""
Acting as the minimizer for the min_max search with alpha beta
"""
state.depth = depth
# checking entry in transposition table
table_check = transposition_table.table_lookup(state)
if(len(table_check) > 0):
... | 73,240 |
def evaluate():
"""
Evaluate the CNN model.
"""
path = 'results/'
eval = EvaluateModel(ConvolutionalNeuralNetwork)
eval.evaluate(path, path) | 73,241 |
def api_client(cluster_name: str, api_class: str) -> k8s.client.apis:
"""
Creates and returns a python k8s api client of the specified class and pointing to the specified cluster.
Usage: Use this function whenever you want a python k8s api client.
Python k8s api documentation: https://github.com/kubernetes-clie... | 73,242 |
def plot_intensity(tc, ax=None, figsize=(10,5), fontsize=15):
"""
Plot the intensity of the given TC.
Parameters
----------
tc: TC
A single TC.
ax: Axe
Axe for plotting
figsize: tuple
Figure size of (12, 6)
fontsize: int
Size of the font (title, label and... | 73,243 |
def fig_2_Image(fig):
"""
Ref: https://panjinquan.blog.csdn.net/article/details/104179723
fig = plt.figure()
image = fig2data(fig)
@brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it
@param fig a matplotlib figure
@return a numpy 3D array of RGBA valu... | 73,244 |
def binary_sigmoid(n: float, lmbda: float = 1.0) -> float:
"""
Binary Sigmoidal (Unipolar Continuous) Activation Function
"""
return 1 / (1 + (math.exp(-lmbda * n))) | 73,245 |
def user_is_valid(data):
"""user error handling"""
from .collections import store
resp = "The username you provided already exists"
body = store.get_by_field(key='username', value=data.get('username')) is not None
errors = {}
if store.get_by_field(key='email', value=data.get('email')) is not No... | 73,246 |
def create_new_ap_hostname(country_code, ap_macs: list(), mgmt_subnet: str) -> dict:
"""
"WAP<COUNTRY_CODE><2nd_OCTET>3rd_OCTET>_<ascending index starting from 001>"
start index will be the lowest management IP address
Args:
mgmt_subnet: IP network portion (without prefix)
ap_macs: list... | 73,247 |
def ldns_tsig_keydata_clone(*args):
"""LDNS buffer."""
return _ldns.ldns_tsig_keydata_clone(*args) | 73,248 |
def then_ros(result: dict, ros_em: float, note: str):
""" check the relative error of the ros """
error = check_metric('ROS',
result['fuel_type'],
result['python'].ros,
result['expected']['ros'],
ros_em,
... | 73,249 |
def capture_output(stream, loglevel=None):
"""Context manager which captures all log and console output to given `stream` while in scope."""
root_logger = logging.getLogger()
old_level = root_logger.getEffectiveLevel()
old_id = getattr(local_context, 'session_id', None)
# Keep using current, or crea... | 73,250 |
def log_variance(locations):
"""
Compute location variance feature from location data.
Logarithm of combined variance of latitude and longitude values.
:param locations: dataframe of location data with columns latitude and longitude.
:return: location variance.
"""
if len(locations) < 2:
... | 73,251 |
def main(cmd_args):
""" Complete Scenario Generator. """
args = get_options(cmd_args)
logging.info('%s', args)
## ======================== PROFILER ======================== ##
if args.profiling:
profiler = cProfile.Profile()
profiler.enable()
## ======... | 73,252 |
def exec_code_in_pi(source, inp=None, out=None, err=None, locals=None):
"""Runs code in a separate context: (thread, PySystemState, PythonInterpreter)"""
def execution_context():
from org.python.core import Py
from org.python.util import PythonInterpreter
from org.python.core import PyS... | 73,253 |
def client(app):
""" Fixture to emulate client"""
return app.test_client() | 73,254 |
def test_wage_nonpecs():
"""Replace constants in reward functions with constants due to observables."""
point_constr = {"n_periods": 3, "n_lagged_choices": 1, "observables": [2]}
params, options = generate_random_model(point_constr=point_constr)
solve = get_solve_func(params, options)
state_space =... | 73,255 |
def menu():
"""Print the menu"""
print '\nWelcome to the Rock-Paper-Scissors Game'
print 'Please select:'
print '1 for rock'
print '2 for paper'
print '3 for scissors' | 73,256 |
def first_discoverable(targets, cat, kwargs):
"""A target chooser: the first target for which discover() succeeds
This may be useful where some drivers are not importable, or some
sources can be available only sometimes.
"""
for t in targets:
try:
if cat:
s = cat... | 73,257 |
def _centralize(shape):
"""Create a shape which is just like the input, but aligned to origin.
The origin is (0; 0) in 2D case.
The input shape stays unchanged. It's expected to be a numpy.array.
"""
centroid = shape.mean(0)
return shape - centroid | 73,258 |
def evaluate_model(Net, seeds, mini_batch_size=100, optimizer = optim.Adam, criterion = nn.CrossEntropyLoss(), n_epochs=40, eta = 1e-3,
lambda_l2 = 0, alpha=0.5, beta=0.5, plot=True,statistics = True ,rotate = False,translate=False,swap_channel = False,
GPU=False):
"""
... | 73,259 |
def factory(_context, request):
"""Return a AuthCookieService instance for the passed context and request."""
cookie = SignedCookieProfile(
# This value is set in `h.auth` at the moment
secret=request.registry.settings["h_auth_cookie_secret"],
salt="authsanity",
cookie_name="aut... | 73,260 |
def get_fcn_resnet50_model_instance(num_classes):
"""
This method gets an instance of FCN-Resnet-50 model given num_classes.
0 < num_classes <= 21
:param num_classes: number of classes
:return: instance of FCN-Resnet-50 model.
"""
# Checks constraint on num_classes
if num_classes <= 0 ... | 73,261 |
def projC(gamma,q):
"""return the KL projection on the column constrints """
return np.multiply(gamma,q/np.maximum(np.sum(gamma,axis=0),1e-10)) | 73,262 |
def read_file(file_name, package_level=True):
"""Get file content given file path.
:param: [package_level] - Wheather the file is in/out side the
`gmail_api_wrapper` package
"""
file_path = get_absolute_path(file_name, package_level=package_level)
with open(file_path) as file_descriptor:
... | 73,263 |
def test_query_into_dictcursor(sn):
"""Verifies passing `as_dcur=True` to snowmobile.query() returns a dictcursor."""
from snowflake.connector import DictCursor
dcur = sn.query("select 1", as_dcur=True)
assert isinstance(dcur, DictCursor) | 73,264 |
def fit_vfa_nonlinear(s, fa_rad, tr):
"""Return T1 based on VFA signals using NLLS fitting.
Parameters
----------
s: ndarray
1D array of signals.
fa_rad: ndarray
1D array of flip angles (rad).
tr: float
Repetition time (s).
Returns
---... | 73,265 |
def GenerateRandomName():
"""Generates a random string.
Returns:
The returned string will be 12 characters long and will begin with
a lowercase letter followed by 10 characters drawn from the set
[-a-z0-9] and finally a character drawn from the set [a-z0-9].
"""
buf = cStringIO.StringIO()
buf.wri... | 73,266 |
def p_fillnull_macro(p):
"""fillnullcmd : FILLNULL MACRO"""
p[0] = ParseTreeNode('COMMAND', raw='fillnull')
p[1] = ParseTreeNode('MACRO', raw=p[1], is_argument=True)
p[0].add_child(p[1]) | 73,267 |
def sign_correct(a_v, a_terms2idx, a_pos, a_neg, a_neut):
"""Fix polarity values of the seed terms in the given vector.
@param a_v - vector of word polarity scores
@param a_terms2idx - mapping from terms to ``a_v`` indices
@param a_pos - set of lexemes with positive polarity
@param a_neg - set of l... | 73,268 |
def get_restoration_targets(message_ids):
"""Given a list of message-ids, return a list of tuples of (message_id, recipient)
suitable for the unremediate_emails command. The values are discovered by
querying the remediation table in the database."""
from saq.database import get_db_connection
... | 73,269 |
def _check_fit_params(x_data, fit_params, indices=None):
"""Check and validate the parameters passed during ``fit``."""
fit_params_validated = {}
for param_key, param_value in fit_params.items():
if (not _is_arraylike(param_value) or
_num_samples(param_value) != _num_samples(x_data))... | 73,270 |
def filter_wrong_poses(
skel_ours_2d, skel_ours_3d,
d_thresh=Conf.get().optimize_path.head_ank_dthresh,
l_torso_thresh=Conf.get().optimize_path.torso_length_thresh,
show=False):
"""Attempts to filter poses, where ankles are too close to the head.
Remember, up is -y, so lower y coordinate means "higher" ... | 73,271 |
def clone_file(in_: Input, out: Output):
"""."""
_out: Path = Path(out)
with _out.open("w") as f:
f.write("Child\n")
f.write(open(in_, "r").read()) | 73,272 |
def read_binary_file(
bbseries, comps, station_names=None, wave_type=None, file_type=None, units="g"
):
"""
read all stations into a list of waveforms
:param input_path:
:param comp:
:param station_names:
:param wave_type:
:param file_type:
:return: [(waveform_acc, waveform_vel])
... | 73,273 |
def _install(package, src_dir, dst_dir, params, prefix_len=None, rec=None):
"""Interpolate source directory into target directory with params.
"""
package_name = package.__name__
_LOGGER.info(
'Installing package: %s %s %s', package_name, src_dir, dst_dir
)
contents = pkg_resources.reso... | 73,274 |
def is_html_needed(user_agent):
"""
Basing on `user_agent`, return whether it needs HTML or ANSI
"""
plaintext_clients = ['curl', 'wget', 'fetch', 'httpie', 'lwp-request', 'python-requests']
if any([x in user_agent for x in plaintext_clients]):
return False
return True | 73,275 |
def open_hansen_biomass_tile(tile_id, version):
"""
Open single tile from the Hansen 2020 dataset and then
massage it into a format for use by the rest of the routines.
Parameters
----------
tile_id : str
The latitude/longitude of the northwest corner of the tile (e.g. 50N_130W)
ver... | 73,276 |
def get_image(max_number=None):
"""
This function returns a iterator of image.
It is used for local test of participating algorithms.
Each iteration provides a tuple of (image_id, image), each image will be in RGB color format with array shape of (height, width, 3)
return: tuple(image_id: str, ... | 73,277 |
def main():
"""
Entrypoint for all 4 command-line tools. Typical usage:
$ djhtml -i file1.html file2.html
"""
Mode = modes.DjHTML
if sys.argv[0].endswith("djtxt"):
Mode = modes.DjTXT
if sys.argv[0].endswith("djcss"):
Mode = modes.DjCSS
if sys.argv[0].endswith("djjs"... | 73,278 |
def process_entry(base_url, i, entry):
"""
Given a base URL, an index, and an entry dictionary,
ensure that the entry is valid,
and return an Apache RedirectMatch directive string.
"""
source = ''
replacement = ''
# Check entry data type
if type(entry) is not dict:
raise ValueError('Entry %d is n... | 73,279 |
def _normalize(string_to_convert, normalize=False):
"""
a utility method for normalizing string
"""
try:
return unicodedata.normalize('NFC', string_to_convert) if normalize else string_to_convert
except TypeError:
return string_to_convert | 73,280 |
def pipe(*args, **kwargs):
"""An aggregator that eagerly sums fields of items in a stream.
Note that this pipe is not lazy if `group_key` is specified.
Args:
items (Iter[dict]): The source.
kwargs (dict): The keyword arguments passed to the wrapper
Kwargs:
conf (dict): The pipe... | 73,281 |
def save_data_list_to_npz(data_list, npz_file):
"""tbd"""
keys = data_list[0].keys()
merged_data = {}
for key in keys:
lens = np.array([len(data[key]) for data in data_list])
values = np.concatenate([data[key] for data in data_list], 0)
merged_data[key] = values
merged_da... | 73,282 |
def __xor_bytes(bytes1, bytes2):
"""xor of a list of bytes"""
assert len(bytes1) == len(bytes2)
return [bytes1[i] ^ bytes2[i] for i in range(len(bytes1))] | 73,283 |
def plugins_help() -> str:
"""
Gets the help text for the 'plugins' sub-command.
"""
return PluginsOptions.get_configured_parser(prog="wai-annotations plugins").format_help() | 73,284 |
def report_issue() -> str: # pragma: no cover
"""Used when errors are really f*cked up"""
return ('Report an issue please? '
'( https://github.com/agamm/comeback/issues )') | 73,285 |
def get_distro():
""" factory to return the right Distro object """
return distro_instance | 73,286 |
def compute_coefficients(temperature_resistance_pairs):
"""Computes Steinhart-Hart model coefficients.
Equations taken from
https://www.dataloggerinc.com/wp-content/uploads/2016/10/self-calibrate-thermistors.pdf.
Args:
temperature_resistance_pairs: sequence of three (temperature, resistance)
tuples.... | 73,287 |
def timed_cache(**timed_cache_kwargs):
"""LRU cache decorator with timeout.
Parameters
----------
days: int
seconds: int
microseconds: int
milliseconds: int
minutes: int
hours: int
weeks: int
maxsise: int [default: 128]
typed: bool [default: False]
"""
def _wrap... | 73,288 |
def _get_orthologous_imodulons(M1, M2, method, cutoff):
"""
Given two M matrices, returns the dot graph and name links of the various
connected ICA components
Parameters
----------
M1 : ~pandas.DataFrame
M matrix from the first organism
M2 : ~pandas.DataFrame
M matrix from t... | 73,289 |
def cont6():
"""
1 cluster (2 shared contours) with 2 subclusters (those from <cont4>).
Contains 3 minima (subclusters contain 1 and 2, resp.).
"""
cont_min = [
cncc(5, (6.00, 3.00), 0.2, (1, 1)),
cncc(2, (7.00, 4.00), 0.1, (4, 1), rmin=0.15),
cncc(2, (6.25, 3.25), 0.3, (6, 1... | 73,290 |
def test_logger_no(caplog):
"""Can we not emit logs."""
util.LOG.debug("hi daryl")
assert "hi daryl" not in caplog.text | 73,291 |
def _get_raw_parts_helper(response, http_response_type):
"""Helper for _get_raw_parts
Assuming this body is multipart, return the iterator or parts.
If parts are application/http use http_response_type or HttpClientTransportResponse
as enveloppe.
"""
body_as_bytes = response.body()
# In or... | 73,292 |
def add_cdb_to_cfg(name, loc, cfg_file):
"""Adds cdb of name `name` and path `loc` to `cfg_file`
Parameters
----------
name : str
Name of cdb (e.g. example_database)
loc : str
path to cdb (e.g. C:\\example_database.cdb)
cfg_file : str
Full filename of an adams drill ... | 73,293 |
def mom2mag_nm(mom):
"""Converts moment to magnitude - newtonmetre"""
return (np.log10(mom) - 9.05) / 1.5 | 73,294 |
def mergeWindows(data, dimOrder, maxWindowSize, overlapPercent, batchSize, transform, progressCallback=None):
"""
Generates sliding windows for the specified dataset and applies the specified
transformation function to each window. Where multiple overlapping windows
include an element of the input datas... | 73,295 |
def UDPOS(*args, **kwargs):
""" Universal Dependencies English Web Treebank
Separately returns the training and test dataset
Arguments:
root: Directory where the datasets are saved. Default: ".data"
Examples:
>>> from torchtext.datasets.raw import UDPOS
>>> train_dataset, vali... | 73,296 |
def _load_global_signal(confounds_raw, global_signal):
"""Load the regressors derived from the global signal."""
global_params = _add_suffix(["global_signal"], global_signal)
_check_params(confounds_raw, global_params)
return confounds_raw[global_params] | 73,297 |
def DictTester(
value_test: Callable[[Any], bool],
) -> Callable[[Any], bool]:
"""
Return a callable that tests whether a given TypeSpec is a DictTypeSpec
with the expected valueSpec.
It is assumed that keySpec must be a ScalarTypeSpec[str], since that is the
only type of Dict we support.
"... | 73,298 |
def isHarmonic(field, sphericalMask, shellMask):
"""Checks if the extrema of the field are in the shell."""
fullField = np.multiply(field, sphericalMask) # [T]
reducedField = np.multiply(field, shellMask)
if int(ptpPPM(fullField)) > int(ptpPPM(reducedField)):
print(
"ptpPPM of field... | 73,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.