content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
async def validate_login(opp, provider, args):
"""Validate a login."""
try:
provider.data.validate_login(args.username, args.password)
print("Auth valid")
except opp_auth.InvalidAuth:
print("Auth invalid") | 29,400 |
def call(stoptime, seconds, method=None):
"""
Returns a dict with route, direction, stop, call time and source.
Call time is in UTC.
"""
result = dict(stoptime._asdict(), call_time=toutc(seconds), source=method or "I")
result["deviation"] = result["call_time"] - stoptime.datetime
return resu... | 29,401 |
def sanitize_value(val):
"""Remove crap from val string and then convert it into float"""
val = re.sub(u"(\xa0|\s)", '', val)
val = val.replace(',', '.')
# positive or negative multiplier
mult = 1
if '-' in val and len(val) > 1:
mult = -1
val = val.replace('-', '')
elif '-'... | 29,402 |
def getObjectInfo(fluiddb, about):
"""
Gets object info for an object with the given about tag.
"""
return fluiddb.about[about].get() | 29,403 |
def extract_tar_images():
"""extract tarfiles in data directory to image directory"""
tarfiles = glob(os.path.join(data_directory, '*.tar.gz'))
for t in tqdm(tarfiles):
tf = tarfile.open(t)
if not os.path.isdir(output_dir):
os.makedirs(output_dir, exist_ok=True)
tf.extrac... | 29,404 |
def __getattr__(name):
"""Get attribute."""
deprecated = __deprecated__.get(name)
if deprecated:
warnings.warn(
"'{}' is deprecated. Use '{}' instead.".format(name, deprecated[0]),
category=DeprecationWarning,
stacklevel=(3 if PY37 else 4)
)
retur... | 29,405 |
def get_model_and_assets():
"""Returns a tuple containing the model XML string and a dict of assets."""
return common.read_model('finger.xml'), common.ASSETS | 29,406 |
def open_random_port(limit):
"""Open random ports."""
command = '''
netstat -plutn |
grep "LISTEN" |
grep -oh ":[0-9]*" |
grep -v -e "^:$" | tr -d ":"'''
ports_list = os.popen(command).read().split('\n')[:-1]
ports_list = [int(i) for i in ports_list]
for i in range(li... | 29,407 |
async def process_logout():
"""
Purge the login information from the users session/cookie data
:return: Redirect to main body
"""
# Simply destroy the cookies in this session and get rid of the creds, redirect to landing
response = RedirectResponse("/") # Process the destruction from main app... | 29,408 |
def test_association(factory):
"""Testing Association elements in the meta-model."""
element = factory.create(UML.Association)
property1 = factory.create(UML.Property)
property2 = factory.create(UML.Property)
element.memberEnd = property1
element.memberEnd = property2
element.ownedEnd = p... | 29,409 |
def _lex_label(label: str) -> _LexedLabel:
"""Splits the label into packages and target."""
match = _LABEL_LEXER.match(label)
if match is None:
raise ValueError(f'{label} is not an absolute Bazel label')
groups = match.groupdict()
packages: Optional[str] = groups['packages']
target: Optional[str] = grou... | 29,410 |
def generate_extra(candidate: tuple, expansion_set, murder_list=None, attempted=None) -> list:
"""
Special routine for graph based algorithm
:param candidate:
:param expansion_set:
:param murder_list:
:param attempted:
:return:
"""
check = manufacture_lambda(attempted, murder_list)
... | 29,411 |
def extract_oe_stereochemistry(
molecule: Molecule, oe_mol: "OEMol"
) -> Tuple[Dict[int, AtomStereochemistry], Dict[int, BondStereochemistry]]:
"""Extracts the CIP stereochemistry of each atom and bond in a OE molecule."""
atom_stereo = {
oe_atom.GetIdx(): atom_cip_stereochemistry(oe_mol, oe_atom)
... | 29,412 |
def nlmeans_proxy(in_file, settings,
snr=None,
smask=None,
nmask=None,
out_file=None):
"""
Uses non-local means to denoise 4D datasets
"""
from dipy.denoise.nlmeans import nlmeans
from scipy.ndimage.morphology import binary_eros... | 29,413 |
def dissolve(
input_path: Union[str, 'os.PathLike[Any]'],
output_path: Union[str, 'os.PathLike[Any]'],
explodecollections: bool,
groupby_columns: Optional[List[str]] = None,
columns: Optional[List[str]] = [],
aggfunc: str = 'first',
tiles_path: Union[str, 'os.Pa... | 29,414 |
def jointImgTo3D(sample):
"""
Normalize sample to metric 3D
:param sample: joints in (x,y,z) with x,y in image coordinates and z in mm
:return: normalized joints in mm
"""
ret = np.zeros((3,), np.float32)
# convert to metric using f
ret[0] = (sample[0]-centerX)*sample[2]/focalLengthX
... | 29,415 |
def _find_registered_loggers(
source_logger: Logger, loggers: Set[str], filter_func: Callable[[Set[str]], List[logging.Logger]]
) -> List[logging.Logger]:
"""Filter root loggers based on provided parameters."""
root_loggers = filter_func(loggers)
source_logger.debug(f"Filtered root loggers: {root_logger... | 29,416 |
def build_param_obj(key, val, delim=''):
"""Creates a Parameter object from key and value, surrounding key with delim
Parameters
----------
key : str
* key to use for parameter
value : str
* value to use for parameter
delim : str
* str to surround key with when adding to... | 29,417 |
def copy_fixtures_to_matrixstore(cls):
"""
Decorator for TestCase classes which copies data from Postgres into an
in-memory MatrixStore instance. This allows us to re-use database fixtures,
and the tests designed to work with those fixtures, to test
MatrixStore-powered code.
"""
# These meth... | 29,418 |
def test_ext_to_int_sample_map(
map_mock,
):
"""
fetch method using a mocked API endpoint
:param map_mock:
:return:
"""
with open(LOOKUP_PED, 'r', encoding='utf-8') as handle:
payload = json.load(handle)
map_mock.return_value = payload
result = ext_to_int_sample_map(project... | 29,419 |
def intersect_description(first, second):
"""
Intersect two description objects.
:param first: First object to intersect with.
:param second: Other object to intersect with.
:return: New object.
"""
# Check that none of the object is None before processing
if first is None:
retur... | 29,420 |
def smooth_correlation_matrix(cor, sigma, exclude_diagonal=True):
"""Apply a simple gaussian filter on a correlation matrix.
Parameters
----------
cor : numpy array
Correlation matrix.
sigma : int, optional
Scale of the gaussian filter.
exclude_diagonal : boolean, optional
... | 29,421 |
def quantize_iir_filter(filter_dict, n_bits):
"""
Quantize the iir filter tuple for sos_filt funcitons
Parameters:
- filter_dict: dict, contains the quantized filter dictionary with the following keys:
- coeff: np.array(size=(M, 6)), float representation of the coefficients
- coeff_scale: n... | 29,422 |
def add_goods(request, openid, store_id, store_name, dsr,
specification, brand, favorable_rate, pic_path, live_recording_screen_path, daily_price, commission_rate,
pos_price, preferential_way, goods_url, hand_card,
storage_condition, shelf_life, unsuitable_people, ability_to_de... | 29,423 |
def cli_to_args():
"""
converts the command line interface to a series of args
"""
cli = argparse.ArgumentParser(description="")
cli.add_argument('-input_dir',
type=str, required=True,
help='The input directory that contains pngs and svgs of cowboys with Uni... | 29,424 |
def main():
"""
Run the generator
"""
util.display(globals()['__banner'], color=random.choice(list(filter(lambda x: bool(str.isupper(x) and 'BLACK' not in x), dir(colorama.Fore)))), style='normal')
parser = argparse.ArgumentParser(
prog='client.py',
description="Generator (Build Yo... | 29,425 |
def _get_metadata_from_configuration(
path, name, config,
fields, **kwargs
):
"""Recursively get metadata from configuration.
Args:
path: used to indicate the path to the root element.
mainly for trouble shooting.
name: the key of the metadata section.
config: the valu... | 29,426 |
def test_get_events(lora):
"""Test _get_events."""
# Successful command
lora._serial.receive.return_value = [
'at+recv=0,-68,7,0',
'at+recv=1,-65,6,2:4865',
]
events = lora._get_events()
assert events.pop() == '1,-65,6,2:4865'
assert events.pop() == '0,-68,7,0' | 29,427 |
def calcOneFeatureEa(dataSet: list, feature_idx: int):
"""
获取一个特征的E(A)值
:param dataSet: 数据集
:param feature_idx: 指定的一个特征(这里是用下标0,1,2..表示)
:return:
"""
attrs = getOneFeatureAttrs(dataSet, feature_idx)
# 获取数据集的p, n值
p, n = getDatasetPN(dataSet)
ea = 0.0
for attr in attrs:
... | 29,428 |
def translate_mapping(mapping: list, reference: SimpleNamespace, templ: bool=True, nontempl: bool=True,
correctframe: bool=True, filterframe: bool=True, filternonsense: bool=True):
"""
creates a protein mapping from a dna mapping.
:param mapping: a list/tuple of ops.
:param referen... | 29,429 |
def try_download_file():
"""
Function that try to download required files from github (pcm-dpc/COVID-19)
If some errors happen during download, like "connection lost", it waits for 5 seconds.
Print info about error in case no internet connection
don't :return:
"""
connection = True
while... | 29,430 |
def trainModel(label,bestModel,obs,trainSet,testSet,modelgrid,cv,optMetric='auc'):
""" Train a message classification model """
from copy import copy
from numpy import zeros, unique
from itertools import product
pred = zeros(len(obs))
fullpred = zeros((len(obs),len(unique(obs))))
model = cop... | 29,431 |
def get_device_state():
"""Return the device status."""
state_cmd = get_adb_command_line('get-state')
return execute_command(
state_cmd, timeout=RECOVERY_CMD_TIMEOUT, log_error=True) | 29,432 |
def character_state(combat, character):
"""
Get the combat status of a single character, as a tuple of
current_hp, max_hp, total healing
"""
max_hp = Max_hp(character.base_hp)
total_h = 0
for effect in StatusEffect.objects.filter(character=character, combat=combat, effect_typ__typ='M... | 29,433 |
def load_textfile(path) :
"""Returns text file as a str object
"""
f=open(path, 'r')
recs = f.read() # f.readlines()
f.close()
return recs | 29,434 |
def interp1d_to_uniform(x, y, axis=None):
"""Resample array to uniformly sampled axis.
Has some limitations due to use of scipy interp1d.
Args:
x (vector): independent variable
y (array): dependent variable, must broadcast with x
axis (int): axis along which to resample
Return... | 29,435 |
def get_walkthrought_dir(dm_path):
""" return 3 parameter:
file_index[0]: total path infomation
file_index[1]: file path directory
file_index[2]: file name
"""
file_index = []
for dirPath, dirName, fileName in os.walk(dm_path):
for file... | 29,436 |
def flatten_dict(d: Dict):
"""Recursively flatten dictionaries, ordered by keys in ascending order"""
s = ""
for k in sorted(d.keys()):
if d[k] is not None:
if isinstance(d[k], dict):
s += f"{k}|{flatten_dict(d[k])}|"
else:
s += f"{k}|{d[k]}|"
... | 29,437 |
def get_tokens(s):
"""
Given a string containing xonsh code, generates a stream of relevant PLY
tokens using ``handle_token``.
"""
state = {'indents': [0], 'last': None,
'pymode': [(True, '', '', (0, 0))],
'stream': tokenize(io.BytesIO(s.encode('utf-8')).readline)}
whil... | 29,438 |
def getPVvecs(fname):
"""
Generates an ensemble of day long PV activities, sampled 3 different
days for each complete pv data set
"""
datmat = np.zeros((18,48))
df = dd.read_csv(fname)
i = 0
for unique_value in df.Substation.unique():
ttemp, ptemp = PVgettimesandpower("2014-06", unique_value, fname)
t, ... | 29,439 |
def test_fqdn_url_without_domain_name():
""" Test with invalid fully qualified domain name URL """
schema = Schema({"url": FqdnUrl()})
try:
schema({"url": "http://localhost/"})
except MultipleInvalid as e:
assert_equal(str(e),
"expected a fully qualified domain name ... | 29,440 |
def vis9(n): # DONE
"""
O OO OOO
OO OOO OOOO
OOO OOOO OOOOO
Number of Os:
6 9 12"""
result = 'O' * (n - 1) + 'O\n'
result += 'O' * (n - 1) + 'OO\n'
result += 'O' * (n - 1) + 'OOO\n'
return result | 29,441 |
def derivative_circ_dist(x, p):
"""
Derivative of circumferential distance and derivative function, w.r.t. p
d/dp d(x, p) = d/dp min_{z in [-1, 0, 1]} (|z + p - x|)
Args:
x (float): first angle
p (float): second angle
Returns:
float: d/dp d(x, p)
"""
# pylin... | 29,442 |
async def test_temp_change_ac_trigger_on_not_long_enough_2(hass, setup_comp_5):
"""Test if temperature change turn ac on."""
calls = _setup_switch(hass, False)
await common.async_set_temperature(hass, 25)
_setup_sensor(hass, 30)
await hass.async_block_till_done()
assert 0 == len(calls) | 29,443 |
def get_MB_compatible_list(OpClass, lhs, rhs):
""" return a list of metablock instance implementing an operation of
type OpClass and compatible with format descriptor @p lhs and @p rhs
"""
fct_map = {
Addition: get_Addition_MB_compatible_list,
Multiplication: get_Multiplication_M... | 29,444 |
def create_mock_target(number_of_nodes, number_of_classes):
"""
Creating a mock target vector.
"""
return torch.LongTensor([random.randint(0, number_of_classes-1) for node in range(number_of_nodes)]) | 29,445 |
def is_iterable(obj):
"""
Return true if object has iterator but is not a string
:param object obj: Any object
:return: True if object is iterable but not a string.
:rtype: bool
"""
return hasattr(obj, '__iter__') and not isinstance(obj, str) | 29,446 |
def convert_loglevstr_to_loglevint(loglevstr):
""" returns logging.NOTSET if we fail to match string """
if loglevstr.lower() == "critical":
return logging.CRITICAL
if loglevstr.lower() == "error":
return logging.ERROR
if loglevstr.lower() == "warning":
return logging.WARNING
if loglevstr.lower() == "info":... | 29,447 |
def get_operator_module(operator_string):
"""
Get module name
"""
# the module, for when the operator is not a local operator
operator_path = ".".join(operator_string.split(".")[:-1])
assert len(operator_path) != 0, (
"Please specify a format like 'package.operator' to specify your opera... | 29,448 |
def is_fraction(obj):
"""Test whether the object is a valid fraction.
"""
return isinstance(obj, Fraction) | 29,449 |
def getExtrusion(matrix):
"""calculates DXF-Extrusion = Arbitrary Xaxis and Zaxis vectors
"""
AZaxis = matrix[2].copy().resize3D().normalize() # = ArbitraryZvector
Extrusion = [AZaxis[0],AZaxis[1],AZaxis[2]]
if AZaxis[2]==1.0:
Extrusion = None
AXaxis = matrix[0].copy().resize3D() # = ArbitraryXvector
else:... | 29,450 |
def _build_class_include(env, class_name):
"""
If parentns::classname is included and fabric
properties such as puppet_parentns__classname_prop = val1
are set, the class included in puppet will be something like
class { 'parentns::classname':
prop => 'val1',
}
"""
include_def = ... | 29,451 |
async def mention_html(user_id, name):
"""
The function is designed to output a link to a telegram.
"""
return f'<a href="tg://user?id={user_id}">{escape(name)}</a>' | 29,452 |
def blaze_loader(alias):
"""
Loader for BlazeDS framework compatibility classes, specifically
implementing ISmallMessage.
.. seealso:: `BlazeDS (external)
<http://opensource.adobe.com/wiki/display/blazeds/BlazeDS>`_
:since: 0.1
"""
if alias not in ['DSC', 'DSK', 'DSA']:
retur... | 29,453 |
def get_user_pic(user_id, table):
"""[summary]
Gets users profile picture
Args:
user_id ([int]): [User id]
table ([string]): [Table target]
Returns:
[string]: [Filename]
"""
try:
connection = database_cred()
cursor = connection.cursor()
curso... | 29,454 |
def convert_file_format(files,size):
"""
Takes filename queue and returns an example from it
using the TF Reader structure
"""
filename_queue = tf.train.string_input_producer(files,shuffle=True)
image_reader = tf.WholeFileReader()
_,image_file = image_reader.read(filename_queue)
image =... | 29,455 |
def validate_access_rule(supported_access_types, supported_access_levels,
access_rule, abort=False):
"""Validate an access rule.
:param access_rule: Access rules to be validated.
:param supported_access_types: List of access types that are regarded
valid.
:param sup... | 29,456 |
def track_viou_video(video_path, detections, sigma_l, sigma_h, sigma_iou, t_min, ttl, tracker_type, keep_upper_height_ratio):
""" V-IOU Tracker.
See "Extending IOU Based Multi-Object Tracking by Visual Information by E. Bochinski, T. Senst, T. Sikora" for
more information.
Args:
frames_path (s... | 29,457 |
def deduplicate(inp: SHAPE) -> SHAPE:
"""
Remove duplicates from any iterable while retaining the order of elements.
:param inp: iterable to deduplicate
:return: new, unique iterable of same type as input
"""
return type(inp)(dict.fromkeys(list(inp))) | 29,458 |
def access_rules_synchronized(f):
"""Decorator for synchronizing share access rule modification methods."""
def wrapped_func(self, *args, **kwargs):
# The first argument is always a share, which has an ID
key = "share-access-%s" % args[0]['id']
@utils.synchronized(key)
def sou... | 29,459 |
def import_python(path, package=None):
"""Get python module or object.
Parameters
----------
path : str
Fully-qualified python path, i.e. `package.module:object`.
package : str or None
Package name to use as an anchor if `path` is relative.
"""
parts = path.split(':')
if ... | 29,460 |
async def feature_flags_scope_per_request(
request: Request, call_next: Callable[[Request], Awaitable[Response]]
) -> Response:
"""Use new feature flags copy for each request."""
# Create new copy of the feature flags, as we'll be modifying them later
# and do not want to change our system-wide feature... | 29,461 |
def test_md034_good_http_url_in_inline_link():
"""
Test to make sure this rule does not trigger with a document that
contains http urls in inline links.
"""
# Arrange
scanner = MarkdownScanner()
supplied_arguments = [
"scan",
"test/resources/rules/md034/good_http_url_in_inli... | 29,462 |
def fakepulsar(parfile, obstimes, toaerr, freq=1440.0, observatory="AXIS", flags="", iters=3):
"""Returns a libstempo tempopulsar object corresponding to a noiseless set
of observations for the pulsar specified in 'parfile', with observations
happening at times (MJD) given in the array (or list) 'obstimes',... | 29,463 |
def get_scenes_need_processing(config_file, sensors):
"""
A function which finds all the processing steps for all the scenes which haven't yet been undertaken.
This is per scene processing rather than per step processing in the functions above.
Steps include:
* Download
* ARD Production
... | 29,464 |
def Double_DQN(env, memory, q_net, t_net, optim, steps = 10000, eps = 1, disc_factor = 0.99, loss = torch.nn.MSELoss(), batch_sz = 128, tgt_update = 10, early = True,
eps_decay = lambda eps, steps, step: eps - eps/steps,
act = lambda s, eps, env, q_net: torch.tensor(env.action_space.sample()) if torch.r... | 29,465 |
def startingStateDistribution(env, N=100000):
"""
This function samples initial states for the environment and computes
an empirical estimator for the starting distribution mu_0
"""
rdInit = []
sample = {}
# Computing the starting state distribution
mu_0 =... | 29,466 |
def get_shapley(csv_filename, modalities = ["t1", "t1ce", "t2", "flair"]):
"""
calculate modality shapeley value
CSV with column: t1, t1c, t2, flair, of 0 / 1. and perforamnce value.
:param csv:
:return:
"""
# convert csv to dict: {(0, 0, 1, 0): 10} {tuple: performance}
df = pd.read_csv(... | 29,467 |
def reload_all():
"""
Resets all modules to the state they were in right after import_all
returned.
"""
import renpy.style
import renpy.display
# Clear all pending exceptions.
sys.exc_clear()
# Reset the styles.
renpy.style.reset() # @UndefinedVariable
# Shut down the cac... | 29,468 |
def quest_13(_x):
"""
Sample data for 1000 cells, with 200 genes, and 8 cell types. Cluster the data with k-means (k = 8)
"""
plt.subplot(121)
plt.imshow(np.log(_x), cmap="binary", interpolation="nearest")
plt.ylabel('Genes')
plt.xlabel('Cells')
plt.xlim(0,200)
plt.ylim(0,200)
pl... | 29,469 |
def demo_eval(chunkparser, text):
"""
Demonstration code for evaluating a chunk parser, using a
``ChunkScore``. This function assumes that ``text`` contains one
sentence per line, and that each sentence has the form expected by
``tree.chunk``. It runs the given chunk parser on each sentence in
... | 29,470 |
def get_changepoint_values_from_config(
changepoints_dict,
time_features_df,
time_col=cst.TIME_COL):
"""Applies the changepoint method specified in `changepoints_dict` to return the changepoint values
:param changepoints_dict: Optional[Dict[str, any]]
Specifies the changepoint c... | 29,471 |
def jitChol(A, maxTries=10, warning=True):
"""Do a Cholesky decomposition with jitter.
Description:
U, jitter = jitChol(A, maxTries, warning) attempts a Cholesky
decomposition on the given matrix, if matrix isn't positive
definite the function adds 'jitter' and tries again. Thereaf... | 29,472 |
def stock_individual_info_em(symbol: str = "603777") -> pd.DataFrame:
"""
东方财富-个股-股票信息
http://quote.eastmoney.com/concept/sh603777.html?from=classic
:param symbol: 股票代码
:type symbol: str
:return: 股票信息
:rtype: pandas.DataFrame
"""
code_id_dict = code_id_map_em()
url = "http://push... | 29,473 |
def InverseDynamicsTool_safeDownCast(obj):
"""
InverseDynamicsTool_safeDownCast(OpenSimObject obj) -> InverseDynamicsTool
Parameters
----------
obj: OpenSim::Object *
"""
return _tools.InverseDynamicsTool_safeDownCast(obj) | 29,474 |
def in_incident_root(current_dir_path):
"""
Helper function to determine if a sub directory is a child of an incident directory. This is useful for setting
default params in tools that has an incident directory as an input
:param current_dir_path: String of the path being evaluated
:return: tuple of... | 29,475 |
def build_decoder(encoding_dim,sparse):
""""build and return the decoder linked with the encoder"""
input_img = Input(shape=(28*28,))
encoder = build_encoder(encoding_dim,sparse)
input_encoded = encoder(input_img)
decoded = Dense(64, activation='relu')(input_encoded)
decoded = Dense(128, activ... | 29,476 |
def find_usable_exits(room, stuff):
"""
Given a room, and the player's stuff, find a list of exits that they can use right now.
That means the exits must not be hidden, and if they require a key, the player has it.
RETURNS
- a list of exits that are visible (not hidden) and don't require a key!
... | 29,477 |
def test_1_1_1_4_file_mode(host):
"""
CIS Ubuntu 20.04 v1.0.0 - Rule # 1.1.1.4
Tests if /etc/modprobe.d/1.1.1.4_hfs.conf has 0644 mode
"""
assert host.file(HFS_MOD_FILE).mode == 0o644 | 29,478 |
def get_normal_map(x, area_weighted=False):
"""
x: [bs, h, w, 3] (x,y,z) -> (nx,ny,nz)
"""
nn = 6
p11 = x
p = tf.pad(x, tf.constant([[0,0], [1,1], [1,1], [0,0]]))
p11 = p[:, 1:-1, 1:-1, :]
p10 = p[:, 1:-1, 0:-2, :]
p01 = p[:, 0:-2, 1:-1, :]
p02 = p[:, 0:-2, 2:, :]
p12 = p... | 29,479 |
def get_example_models():
"""Generator that yields the model objects for all example models"""
example_dir = os.path.join(os.path.dirname(__file__), '..', 'examples')
for filename in os.listdir(example_dir):
if filename.endswith('.py') and not filename.startswith('run_') \
and not fil... | 29,480 |
def check_dtype(array, allowed):
"""Raises TypeError if the array is not of an allowed dtype.
:param array: array whose dtype is to be checked
:param allowed: instance or list of allowed dtypes
:raises: TypeError
"""
if not hasattr(allowed, "__iter__"):
allowed = [allowed, ]
if arra... | 29,481 |
def initPeaksFromControlPoints(peakSelectionModel, controlPoints, context=None):
"""Initialize peak selection model using control points object
:rtype: pyFAI.control_points.ControlPoints
"""
if not isinstance(peakSelectionModel, PeakSelectionModel):
raise TypeError("Unexpected model type")
... | 29,482 |
def _ros_group_rank(df, dl_idx, censorship):
"""
Ranks each observation within the data groups.
In this case, the groups are defined by the record's detection
limit index and censorship status.
Parameters
----------
df : pandas.DataFrame
dl_idx : str
Name of the column in the ... | 29,483 |
def f_all(predicate, iterable):
"""Return whether predicate(i) is True for all i in iterable
>>> is_odd = lambda num: (num % 2 == 1)
>>> f_all(is_odd, [])
True
>>> f_all(is_odd, [1, 3, 5, 7, 9])
True
>>> f_all(is_odd, [2, 1, 3, 5, 7, 9])
False
"""
return all(predicate(i) for i i... | 29,484 |
def vcpu_affinity_output(vm_info, i, config):
"""
Output the vcpu affinity
:param vminfo: the data structure have all the xml items values
:param i: the index of vm id
:param config: file pointor to store the information
"""
if vm_info.load_order[i] == "SOS_VM":
return
cpu_bits ... | 29,485 |
def _recursive_replace(data):
"""Searches data structure and replaces 'nan' and 'inf' with respective float values"""
if isinstance(data, str):
if data == "nan":
return float("nan")
if data == "inf":
return float("inf")
if isinstance(data, List):
return [_recu... | 29,486 |
def m3_change_emotion(rosebot, emotionnum):
"""
This is a callable function to change the emotion of the robot from an entry without crashing if the number is too
large
:type rosebot: rb.RoseBot
:param emotionnum:
:return:
"""
if emotionnum < 7:
rosebot.m3_emotion_system.change... | 29,487 |
def user(request, user_id):
"""Displays a User and various information about them."""
raise NotImplementedError | 29,488 |
def test_add_alternative_cds():
"""Test get_alternative_cds from CDS class"""
cds_list[0].add_alternative_cds(cds_list[1])
assert len(cds_list[0].alternative_cds) == 1 | 29,489 |
def trans_text_ch_to_vector(txt_file, word_num_map, txt_label=None):
""" Trans chinese chars to vector
:param txt_file:
:param word_num_map:
:param txt_label:
:return:
"""
words_size = len(word_num_map)
to_num = lambda word: word_num_map.get(word.encode('utf-8'), words_size)
i... | 29,490 |
def adjust_bag(request, item_id):
""" Adjust the quantity of a product to the specified amount"""
quantity = int('0'+request.POST.get('quantity'))
bag = request.session.get('bag', {})
if quantity > 0:
bag[item_id] = quantity
else:
messages.error(request, 'Value must greather than o... | 29,491 |
def get_file_paths_in_dir(idp,
ext=None,
target_str_or_list=None,
ignore_str_or_list=None,
base_name_only=False,
without_ext=False,
sort_result=True,
... | 29,492 |
def touch(filename):
"""
Creates an empty file if it does not already exist
"""
open(filename, 'a').close() | 29,493 |
def test_connected_taskflow(ctx, proxy):
"""Test a connected taskflow"""
# Now try a workflow that is the two connected together
logging.info('Running taskflow that connects to parts together ...')
taskflow_id = create_taskflow(
proxy, 'cumulus.taskflow.core.test.mytaskflows.ConnectTwoTaskFlow')... | 29,494 |
def _condexpr_value(e):
"""Evaluate the value of the input expression.
"""
assert type(e) == tuple
assert len(e) in [2, 3]
if len(e) == 3:
if e[0] in ARITH_SET:
return _expr_value(e)
left = _condexpr_value(e[1])
right = _condexpr_value(e[2])
if type(left... | 29,495 |
def in6_isincluded(addr, prefix, plen):
"""
Returns True when 'addr' belongs to prefix/plen. False otherwise.
"""
temp = inet_pton(socket.AF_INET6, addr)
pref = in6_cidr2mask(plen)
zero = inet_pton(socket.AF_INET6, prefix)
return zero == in6_and(temp, pref) | 29,496 |
def check_datepaths(record):
"""
Asserts that the given date paths return the same number of files,
otherwise raises an informative error.
"""
from .utils import make_date_path_pairs
import pandas as pd
random_dates = pd.DatetimeIndex(
['2010-04-03', '2010-03-23', '2014-01-01', '201... | 29,497 |
def vis_channel(model, layer, channel_n):
"""
This function creates a visualization for a single channel in a layer
:param model: model we are visualizing
:type model: lucid.modelzoo
:param layer: the name of the layer we are visualizing
:type layer: string
:param channel_n: The channel ... | 29,498 |
def _validate_fft_input(array: numpy.ndarray) -> None:
"""
Validate the fft input.
Parameters
----------
array : numpy.ndarray
Returns
-------
None
"""
if not isinstance(array, numpy.ndarray):
raise TypeError('array must be a numpy array')
if not numpy.iscomplexobj... | 29,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.