content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def birth(sim):
"""Similar to create agent, but just one individual"""
age = 0
qualification = int(sim.seed.gammavariate(3, 3))
qualification = [qualification if qualification < 21 else 20][0]
money = sim.seed.randrange(20, 40)
month = sim.seed.randrange(1, 13, 1)
gender = sim.seed.choice(['... | 23,200 |
def offer_better_greeting():
"""Give player optional compliments."""
player = request.args["person"]
# if they didn't tick box, `wants_compliments` won't be
# in query args -- so let's use safe `.get()` method of
# dict-like things
wants = request.args.get("wants_compliments")
nice_things... | 23,201 |
def get_trip_length(grouped_counts):
"""
Gets the frequency of the length of a trip for a customer
Args:
grouped_counts (Pandas.DataFrame): The grouped dataframe returned from
a get_trips method call
Returns:
Pandas.DataFrame: the dataframe co... | 23,202 |
def extract_begin_end(data):
""" Finds nif:beginIndex and nif:endIndex values.
:param data: Data sent by the client.
:return: Begin index and end index, -1 if error.
"""
try:
begin = data.split("nif:beginIndex")[1].split("\"")[1]
end = data.split("nif:endIndex")[1].split("\"")[1]
... | 23,203 |
def setup_parameters():
"""
Helper routine to fill in all relevant parameters
Note that this file will be used for all versions of SDC, containing more than necessary for each individual run
Returns:
description (dict)
controller_params (dict)
"""
# initialize level parameters... | 23,204 |
def create_scope(api_client, scope, initial_manage_principal):
"""
Creates a new secret scope with given name.
"""
SecretApi(api_client).create_scope(scope, initial_manage_principal) | 23,205 |
def add_quick_closing(request_id, days, date, tz_name, content):
"""Create and store an acknowledgement-determination response followed by a closing-determination response for
the specified request and update the request accordingly.
Args:
request_id: FOIL request ID
days: days until reques... | 23,206 |
def get_operation(op, inplanes, outplanes, stride, conv_type):
"""Set up conv and pool operations."""
kernel_size = Ops.ops_to_kernel_size[op]
padding = [(k - 1) // 2 for k in kernel_size]
if op in Ops.pooling_ops:
if inplanes == outplanes:
return nn.AvgPool2d(kernel_size, stride=str... | 23,207 |
def test_create_subscription_metadata(
caplog, auth_client, user, session, mock_stripe_customer
):
"""Successful checkout session updates metadata on Stripe Customer"""
mock_stripe_customer.retrieve.return_value.metadata = {}
mock_stripe_customer.retrieve.return_value.email = user.email
url = revers... | 23,208 |
def encode(
structure_klifs_ids, fingerprints_filepath=None, local_klifs_download_path=None, n_cores=1
):
"""
Encode structures.
Parameters
----------
structure_klifs_ids : list of int
Structure KLIFS IDs.
fingerprints_filepath : str or pathlib.Path
Path to output json file.... | 23,209 |
def log_like_repressed(params, data_rep):
"""Conv wrapper for log likelihood for 2-state promoter w/
transcription bursts and repression.
data_rep: a list of arrays, each of which is n x 2, of form
data[:, 0] = SORTED unique mRNA counts
data[:, 1] = frequency of each mRNA count
Not... | 23,210 |
def test_wrapper_calls_of_on_non_wrapper():
"""
The ExtensionClass protocol is respected even for non-Acquisition
objects.
>>> class MyBase(ExtensionClass.Base):
... def __of__(self, other):
... print("Of called")
... return 42
>>> class Impl(Acquisition.Implicit):
... | 23,211 |
def selectBroadcastData(request):
"""
检索黑广播
:param request:
:return:
"""
pass | 23,212 |
def freq_mask(spec, F=30, num_masks=1, pad_value=0.):
"""Frequency masking
Args:
spec (torch.Tensor): input tensor of shape `(dim, T)`
F (int): maximum width of each mask
num_masks (int): number of masks
pad_value (float): value for padding
Returns:
freq masked te... | 23,213 |
def prepare_file_hierarchy(path):
"""
Create a temporary folder structure like the following:
test_find_dotenv0/
└── child1
├── child2
│ └── child3
│ └── child4
└── .env
Then try to automatically `find_dotenv` starting in `child4`
... | 23,214 |
def test_config_rule_errors(): # pylint: disable=too-many-statements
"""Test various error conditions in ConfigRule instantiation."""
client = boto3.client("config", region_name=TEST_REGION)
# Missing fields (ParamValidationError) caught by botocore and not
# tested here: ConfigRule.Source, ConfigRul... | 23,215 |
def collateReadCounts(inputs, outputs):
"""
Collate read counts from samtools flagstat output into a table.
"""
# Note expected input and output directories are effectively hard-coded
in_dir = sambam_dir
out_dir = results_dir
flag_file = outputs[-1]
print "Collating read counts"
r... | 23,216 |
def cmd2dict(cmd):
"""Returns a dictionary of what to replace each value by."""
pixel_count = cmd[cmd.shape[0] - 1, cmd.shape[1] - 1]
scaling_dict = dict()
for i in range(0, cmd.shape[0]):
scaling_dict[cmd[i, 0]] = round(
((cmd[i, 1] - cmd[0, 1]) / (pixel_count - cmd[0, 1])) * 255
... | 23,217 |
def cached_part(query, cache=None):
"""Get cached part of the query.
Use either supplied cache object or global cache object (default).
In the process, query is into two parts: the beginning of the query
and the remainder. Function tries to find longest possible beginning of the query
which is cache... | 23,218 |
def exist_key(bucket: str, key: str) -> bool:
"""Exist key or not.
Args:
bucket (str): S3 bucket name.
key (str): Object key.
Returns:
bool: Exist or not.
"""
try:
s3.Object(bucket, key).get()
except s3.meta.client.exceptions.NoSuchKey:
return False
... | 23,219 |
def load_all_files(dir):
"""Returns all of the csharp source files."""
result = []
for root, dirnames, filenames in os.walk(dir):
if 'obj\\' not in root and 'bin\\' not in root:
for name in fnmatch.filter(filenames, '*.cs'):
result.append(SourceFile(os.path.join(root, nam... | 23,220 |
def glove4gensim(file_dir):
"""
A function that modifies the pretrained GloVe file so it could be integrated with this framework
[Note] You can download the vectors used in this code at
https://nlp.stanford.edu/projects/glove/ (make sure to unzip the files)
:param file_dir: file directory of th... | 23,221 |
def calculate_bleu_score(candidate_file: str, reference_file: str) -> float:
"""
Calculates the average BLEU score of the given files, interpreting each line as a sentence.
Partially taken from https://stackoverflow.com/a/49886758/3918865.
Args:
candidate_file: the name of the file that contain... | 23,222 |
def _read_id_not_in_dict(read_ids, read_dict):
"""Return True if all read_ids in a list are not in the read_dict keys, otherwise False"""
for read_id in read_ids:
if read_id not in read_dict.keys():
return True
return False | 23,223 |
def generate_spectra_products(dataset, prdcfg):
"""
generates spectra products. Accepted product types:
'AMPLITUDE_PHASE_ANGLE_DOPPLER': Makes an angle Doppler plot of
complex spectra or IQ data. The plot can be along azimuth or along
range. It is plotted separately the module an... | 23,224 |
def odds_or_evens(my_bool, nums):
"""Returns all of the odd or
even numbers from a list"""
return_list = []
for num in nums:
if my_bool:
if num % 2 == 0:
return_list.append(num)
else:
if num % 2 != 0:
return_list.append(num)
re... | 23,225 |
def configure_db():
"""Configure database.
Establish the database, create an engine if needed, and register
the models.
"""
global _DB_ENGINE
if not _DB_ENGINE:
_DB_ENGINE = session.get_engine(sqlite_fk=True)
register_models() | 23,226 |
def p_ir_header(p):
# type: (YaccProduction) -> None
"""
ir-header : ir-header-decl ir-header
"""
p[0] = [p[1]] + p[2] | 23,227 |
def demo(event=None, context=None):
"""Shows how to use the role functions."""
logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
print('-'*80)
print("AWS Identity and Account Management role cleanup.")
print('-'*80)
role = list_roles()
print("Roles which have not b... | 23,228 |
def load_tas_lookup():
"""Load/update the TAS table to reflect the latest list."""
logger.info('Loading TAS')
loadTas() | 23,229 |
def local_mass_diagonal(quad_data, basis):
"""Constructs the elemental mass matrix, diagonal version
Arguments:
quad_data - Quadrature points and weights
basis - Basis and respective derivatives
Returns:
Mass matrix M, where m_ii = \int_k psi_i psi_i
"""
return numpy.sum(qu... | 23,230 |
def xtrct_grid(
input_path: Path,
output_path: Path,
xmin: float,
xmax: float,
ymin: float,
ymax: float,
n_levels: int = None,
):
"""Export a cropped spatial subdomain from an ARL packed file."""
# Requires >=0.4 degree padding between the parent domain extent and crop domain
# e... | 23,231 |
def create_saved_group(uuid=None):
"""Create and save a Sample Group with all the fixings (plus gravy)."""
if uuid is None:
uuid = uuid4()
analysis_result = AnalysisResultMeta().save()
group_description = 'Includes factory-produced analysis results from all display_modules'
sample_group = Sa... | 23,232 |
def words_to_indexes(tree):
"""Return a new tree based on the original tree, such that the leaf values
are replaced by their indexs."""
out = copy.deepcopy(tree)
leaves = out.leaves()
for index in range(0, len(leaves)):
path = out.leaf_treeposition(index)
out[path] = index + 1
r... | 23,233 |
def get_stoplist_names():
"""Return list of stoplist names"""
config = configuration()
return [name for name, value in config.items('stoplists')] | 23,234 |
def any_(criterions):
"""Return a stop criterion that given a list `criterions` of stop criterions
only returns True, if any of the criterions returns True.
This basically implements a logical OR for stop criterions.
"""
def inner(info):
return any(c(info) for c in criterions)
return in... | 23,235 |
def make_movie_noah(imgname, movname, indexsz='05', framerate=10, imgdir=None, rm_images=False,
save_into_subdir=False, start_number=0, framestep=1):
"""Create a movie from a sequence of images using the ffmpeg supplied with ilpm.
Options allow for deleting folder automatically after making movie... | 23,236 |
def validate_basic(params, length, allow_infnan=False, title=None):
"""
Validate parameter vector for basic correctness.
Parameters
----------
params : array_like
Array of parameters to validate.
length : int
Expected length of the parameter vector.
allow_infnan : bool, opti... | 23,237 |
def unsorted_segment_sum(data, segment_ids, num_segments):
"""
Computes the sum along segments of a tensor. Analogous to tf.unsorted_segment_sum.
:param data: A tensor whose segments are to be summed.
:param segment_ids: The segment indices tensor.
:param num_segments: The number of segments.... | 23,238 |
def plot_classmap(VGGCAM_weight_path, img_path, label,
nb_classes, num_input_channels=1024, ratio=16):
"""
Plot class activation map of trained VGGCAM model
args: VGGCAM_weight_path (str) path to trained keras VGGCAM weights
img_path (str) path to the image for which we get the a... | 23,239 |
def create_parameters(address: str) -> dict:
"""Create parameters for address.
this function create parameters for having request from geocoder
and than return dictionary of parameters
Args:
address (str): the address for create parameters
Returns:
dict: takes the api key and Geoc... | 23,240 |
def test_remove_connected_item():
"""Test adding canvas constraint."""
canvas = Canvas()
from gaphas.aspect import ConnectionSink, Connector
l1 = Line(canvas.connections)
canvas.add(l1)
b1 = Box(canvas.connections)
canvas.add(b1)
number_cons1 = len(canvas.solver.constraints)
b2 ... | 23,241 |
def make_default_storage_backend_connected_handler():
"""Set the default storage-backend.connected state so that the default
handler in layer-openstack can run.
Convoluted, because charms.reactive will only run handlers in the reactive
or hooks directory.
"""
reactive.set_state('charms.openstack... | 23,242 |
def convert_upsample(builder, layer, input_names, output_names, keras_layer):
"""Convert convolution layer from keras to coreml.
Parameters
----------
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
# Get input and... | 23,243 |
def standardizeName(name):
"""
Remove stuff not used by bngl
"""
name2 = name
sbml2BnglTranslationDict = {
"^": "",
"'": "",
"*": "m",
" ": "_",
"#": "sh",
":": "_",
"α": "a",
"β": "b",
"γ": "g",
" ": "",
"+": "... | 23,244 |
def _learning_rate_decay(hparams, warmup_steps=0):
"""Learning rate decay multiplier."""
scheme = hparams.learning_rate_decay_scheme
warmup_steps = tf.to_float(warmup_steps)
global_step = tf.to_float(tf.train.get_or_create_global_step())
if not scheme or scheme == "none":
return tf.constant(1.)
tf.log... | 23,245 |
def nextjs_build_action(ctx, srcs, out):
"""Run a production build of the vite project
Args:
ctx: arguments description, can be
multiline with additional indentation.
srcs: source files
out: output directory
"""
# setup the args passed to vite
launcher_args = ctx.ac... | 23,246 |
def new_model(save_dir, integer_tokens, batch_size=128,
vocab_size=50000, embedding_size=128,
num_negative=64, num_steps=100001,
num_skips=2, skip_window=1):
"""
Create a new Word2Vec model with token
vectors generated in the 'tokens' step.
Parameters
---... | 23,247 |
def read_junction_report(filename: Union[str, Path]) -> Tuple[str, List[str]]:
"""
tab-delimited with header:
chr left right strand num_transcript num_sample genome annotation label
return: dict of label --> records with that label
"""
with open(filename, "r") as fi:
... | 23,248 |
def Register_User():
"""Validates register form data and saves it to the database"""
# Check if the fields are filled out
if not (request.form['username'] and request.form['email'] and request.form['password'] and request.form['passwordConf']):
return redirect(url_for('Register', message = "Please ... | 23,249 |
def check_events(ai_settings, screen, ship, bullets):
"""响应按键和鼠标事件"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
check_keydown_events(event, ai_settings, screen, ship, bullets)
elif event.type == py... | 23,250 |
def test_x_wrong_ndims():
"""Test that a runtime error is thrown when x has the wrong shape."""
z = np.zeros((0, 2))
x = [[np.array([0., 0.]), np.array([[1., 0.]]), np.array([[0., 1.]]), np.array([[1., 1.]])],
[z, z, z, z], [z], []]
assert_failure(x=x) | 23,251 |
def extreme_rank(df, col, n, bottom=True, keep=[]):
"""
Calculate the n top or bottom of a given series
"""
t = df[list(keep)+[col]].sort_values(col, ascending=bottom).iloc[:30]
count = t['NO_MUNICIPIO'].value_counts()
count.name = '#'
perc = t['NO_MUNICIPIO'].value_counts(nor... | 23,252 |
def ss_octile(y):
"""Obtain the octile summary statistic.
The statistic reaches the optimal performance upon a high number of
observations. According to Allingham et al. (2009), it is more stable than ss_robust.
Parameters
----------
y : array_like
Yielded points.
Returns
----... | 23,253 |
def englishToFrench(englishText):
"""Translates English to French"""
model_id='en-fr'
fr_text = language_translator.translate(
text=englishText,
model_id=model_id).get_result()
return(fr_text['translations'][0]['translation']) | 23,254 |
def calc_out_of_plane_angle(a, b, c, d):
"""
Calculate the out of plane angle of the A-D vector
to the A-B-C plane
Returns the value in radians and a boolean telling if b-a-c are near-collinear
"""
collinear_cutoff = 175./180.
collinear = 0
if abs(calc_angle(b, a, c)) > np.pi ... | 23,255 |
async def median(ctx, *args):
"""
Generate median from given dataset.
Returns the median for the given array or a dataframe containing means for every column
"""
param_def = {"fcai": "False", "tpose": "False", "dataframe": ""}
argchecked = check_args(param_rec=args, param_def=param_def)
if... | 23,256 |
def compute_distances(X, Y):
"""
Computes the Mahalanobis distances between X and Y, for the special case
where covariance between components is 0.
Args:
X (np.ndarray):
3D array that represents our population of gaussians. It is
assumed that X[0] is the 2D matrix contai... | 23,257 |
def third_level_command_3():
"""Third level command under 2nd level 2""" | 23,258 |
def test_assure_valid_device_configuration():
"""Test if invalid configurations are updated correctly"""
conf = {
CONF_USERNAME: "bbbrrrqqq@exa@mple.com",
CONF_PASSWORD: "PasswordPassword",
"test": "test2",
CONF_DEVICES: [
{CONF_TOKEN: "ABCDEF"},
{CONF_TOK... | 23,259 |
def op_item_info():
"""Helper that compiles item info spec and all common module specs
:return dict
"""
item_spec = dict(
item=dict(
type="str",
required=True
),
flatten_fields_by_label=dict(
type="bool",
default=True
),
... | 23,260 |
def unpack_condition(tup):
"""
Convert a condition to a list of values.
Notes
-----
Rules for keys of conditions dicts:
(1) If it's numeric, treat as a point value
(2) If it's a tuple with one element, treat as a point value
(3) If it's a tuple with two elements, treat as lower/upper li... | 23,261 |
def run(doc, preset_mc: bool):
"""Create Graph through classfication values."""
mc = doc._.MajorClaim
adus = doc._.ADU_Sents
if isinstance(mc, list):
mc = mc[0]
if mc == []:
mc = adus.pop(0)
elif not mc:
mc = adus.pop(0)
relations = compare_all(adus, mc)
... | 23,262 |
def get_wfs_with_parameter(parameter, wf_class='Workflow'):
"""
Find workflows of a given class, with a given parameter (which must be a
node)
:param parameter: an AiiDA node
:param wf_class: the name of the workflow class
:return: an AiiDA query set with all workflows that have this parameter
... | 23,263 |
def find_checkpoint_in_dir(model_dir):
"""tf.train.latest_checkpoint will find checkpoints if
'checkpoint' file is present in the directory.
"""
checkpoint_path = tf.train.latest_checkpoint(model_dir)
if checkpoint_path:
return checkpoint_path
# tf.train.latest_checkpoint did not find a... | 23,264 |
def map_iou(boxes_true, boxes_pred, scores, thresholds = [0.4, 0.45, 0.5, 0.55, 0.6, 0.65, 0.7, 0.75]):
"""
Mean average precision at differnet intersection over union (IoU) threshold
input:
boxes_true: Mx4 numpy array of ground true bounding boxes of one image.
bbox format: (x1... | 23,265 |
def draw_output_summary(model):
""" reads the data saved in the model class and depending on this data
chooses a visualization method to present the results with the help
of draw_optimization_overview """
if 'time_series' in model.log:
# no optimization has happend.
# hence... | 23,266 |
def _Userinfo(args):
"""Print the userinfo for this token, if possible."""
userinfo = apitools_base.GetUserinfo(
oauth2client.client.AccessTokenCredentials(args.access_token,
'oauth2l/1.0'))
if args.format == 'json':
print(_PrettyJson(userin... | 23,267 |
def ShowSkmemArena(cmd_args=None) :
""" Show the global list of skmem arenas
"""
i = 1
arhead = kern.globals.skmem_arena_head
for ar in IterateTAILQ_HEAD(arhead, "ar_link") :
format_string = "{:>4d}: 0x{:<08x} {:<6s} {:>5d} KB \"{:<s}\""
print format_string.format(i, ar, SkmemArena... | 23,268 |
def general_spline_interpolation(xs, ys, p, knots=None):
"""
NOTE: SLOW SINCE IT USES B()
xs,ys: interpolation points
p: degree
knots: If None, use p+1-regular from xs[0] to slightly past x[1]
returns cs, knots
"""
# number of interpolation points (and also control point... | 23,269 |
def number_from_string(s):
"""
Parse and return number from string.
Return float only if number is not an int. Assume number can be parsed from
string.
"""
try:
return int(s)
except ValueError:
return float(s) | 23,270 |
def ennAvgPool(inplanes,
kernel_size=1,
stride=None,
padding=0,
ceil_mode=False):
"""enn Average Pooling."""
in_type = build_enn_divide_feature(inplanes)
return enn.PointwiseAvgPool(
in_type,
kernel_size,
stride=stride,
... | 23,271 |
def acceptable(*args, acceptables):
"""
If the characters in StringVars passed as arguments are in acceptables return True, else returns False
"""
for arg in args:
for char in arg:
if char.lower() not in acceptables:
return False
return True | 23,272 |
def get_confusion_matrix(
ground_truth: np.ndarray,
predictions: np.ndarray,
labels: Optional[List[Union[str, float]]] = None) -> np.ndarray:
"""
Computes a confusion matrix based on predictions and ground truth vectors.
The confusion matrix (a.k.a. contingency table) has prediction... | 23,273 |
def atom_explicit_hydrogen_valences(gra):
""" explicit hydrogen valences, by atom
"""
return dict_.transform_values(atom_explicit_hydrogen_keys(gra), len) | 23,274 |
def get_average(pixels):
"""
Given a list of pixels, finds the average red, blue, and green values
Input:
pixels (List[Pixel]): list of pixels to be averaged
Returns:
rgb (List[int]): list of average red, green, blue values across pixels respectively
Assumes you are returning in th... | 23,275 |
def send_transaction(to, value, token):
"""Sends transaction."""
password = getpass.getpass('Password from keystore: ') # Prompt the user for a password of keystore file
configuration = Configuration().load_configuration()
api = get_api()
try:
if token is None:
# send ETH tran... | 23,276 |
def _leading_space_count(line):
"""Return number of leading spaces in line."""
i = 0
while i < len(line) and line[i] == ' ':
i += 1
return i | 23,277 |
def _get_marker_indices(marker, line):
""" method to find the start and end parameter markers
on a template file line. Used by write_to_template()
"""
indices = [i for i, ltr in enumerate(line) if ltr == marker]
start = indices[0:-1:2]
end = [i + 1 for i in indices[1::2]]
assert len(start)... | 23,278 |
def get_number_of_images(dir):
"""
Returns number of files in given directory
Input:
dir - full path of directory
Output:
number of files in directory
"""
return len([name for name in os.listdir(dir) if os.path.isfile(os.path.join(dir, name))]) | 23,279 |
def seg_liver_train(config, train_df, val_df,
gpu_id, number_slices, batch_size, iter_mean_grad, max_training_iters_1,
max_training_iters_2, max_training_iters_3, save_step, display_step,
ini_learning_rate, boundaries, values):
"""
train_file: Training... | 23,280 |
def test_keywords_and_flat_sections(keywords_and_flat_sections):
"""Test an input made of keywords and two unnested sections, interspersed."""
ref_dict = dict(reference)
ref_dict["topsect"] = dict(reference)
ref_dict["foo<bar>"] = dict(reference)
grammar = getkw.grammar()
tokens = lexer.parse_st... | 23,281 |
def get_wrapper_depth(wrapper):
"""Return depth of wrapper function.
.. versionadded:: 3.0
"""
return wrapper.__wrapped__.__wrappers__ + (1 - wrapper.__depth__) | 23,282 |
def apiTest():
"""Tests the API connection to lmessage. Returns true if it is connected."""
try:
result = api.add(2, 3)
except:
return False
return result == 5 | 23,283 |
def generations(pots, notes):
"""Return next generation of pots after rules in notes."""
next_gen = []
for pot in pots.keys():
pattern = ''
for i in range(-2, 3):
pattern += pots.get(pot + i, '.')
next_gen.append((pot, notes[pattern]))
# Check edges for new pots
... | 23,284 |
def signal_handler(sig, frame):
"""Handle ctrl+c interrupt.
Without this handler, everytime a ctrl+c interrupt is received, the server shutdowns and
proceeds to the next iteration in the loop rather than exiting the program altogether.
"""
print("************Received CTRL-C. Will exit in 1 second**... | 23,285 |
def get_distribution(dist_name):
"""Fetches a scipy distribution class by name"""
from scipy import stats as dists
if dist_name not in dists.__all__:
return None
cls = getattr(dists, dist_name)
return cls | 23,286 |
async def async_remove_entry(hass, config_entry):
"""Handle removal of an entry."""
# remove persistent data
config = config_entry.data
name = config.get(CONF_NAME)
filenames = give_persistent_filename(hass, name)
if os.path.isfile(filenames.get("curve_filename")):
os.remove(filenames... | 23,287 |
async def handle_countdown_reminders():
""" Handle countdowns after starting.
Countdowns created afterwards are handled by the cd create command.
"""
reminders = []
for tag, cd in dict(time_cfg.data["countdown"]).items():
dt = pendulum.parse(cd["time"], tz=cd["tz"])
cd = dict(cd)
... | 23,288 |
def ece(y_probs, y_preds, y_true, balanced=False, bins="fd", **bin_args):
"""Compute the expected calibration error (ECE).
Parameters:
y_probs (np.array): predicted class probabilities
y_preds (np.array): predicted class labels
y_true (np.array): true class labels
Returns:
exp_ce (float): ... | 23,289 |
def _call_or_get(value, menu=None, choice=None, string=None, obj=None, caller=None):
"""
Call the value, if appropriate, or just return it.
Args:
value (any): the value to obtain. It might be a callable (see note).
Keyword Args:
menu (BuildingMenu, optional): the building menu to pass... | 23,290 |
def div(a, b, num_threads=None, direction='left'):
"""Divide multithreaded
Args
a (np.ndarray or scalar): Numpy array or scalar
b (np.ndarray or scalar): Numpy array or scalar
num_threads : Number of threads to be used, overrides threads as set by
... | 23,291 |
def is_shared_object(s):
"""
Return True if s looks like a shared object file.
Example: librt.so.1
"""
so = re.compile('^[\w_\-]+\.so\.[0-9]+\.*.[0-9]*$', re.IGNORECASE).match
return so(s) | 23,292 |
def get_name(properties, lang):
"""Return the Place name from the properties field of the elastic response
Here 'name' corresponds to the POI name in the language of the user request (i.e. 'name:{lang}' field).
If lang is None or if name:lang is not in the properties
Then name receives the local name v... | 23,293 |
def get_task(name):
"""Return the chosen task."""
tasks_json = load_json('tasks.json')
return tasks_json[name] | 23,294 |
def exportToXml(stations):
"""
Export subRoutes data to XML
"""
root = ET.Element("stations")
for aStation in stations:
station = ET.SubElement(root, "station")
station.set('lat', aStation['lat'])
station.set('lon', aStation['lon'])
station.set('name', aStation[... | 23,295 |
def aws_credentials(request: pytest.fixture, aws_utils: pytest.fixture, profile_name: str):
"""
Fixture for setting up temporary AWS credentials from assume role.
:param request: _pytest.fixtures.SubRequest class that handles getting
a pytest fixture from a pytest function/fixture.
:param aws_u... | 23,296 |
def mean_predictions(predicted):
"""
Calculate the mean of predictions that overlaps. This is donne mostly to be able to plot what the model is doing.
-------------------------------------------------------
Args:
predicted : numpy array
Numpy array with shape (Number points to predic... | 23,297 |
def test_serverspec_binary_file(host):
"""
Tests if shellcheck binary is file type.
"""
assert host.file(PACKAGE_BINARY).is_file | 23,298 |
def update_diskspace(dmfilestat, cached=None):
"""Update diskspace field in dmfilestat object"""
try:
# search both results directory and raw data directory
search_dirs = [
dmfilestat.result.get_report_dir(),
dmfilestat.result.experiment.expDir,
]
if not ... | 23,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.