content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_get_releases_mine(client: TestClient, session: db.Session):
"""Releases list must mark which releases are in the user's collection"""
master_set = Release(name="Master Set")
master_set.is_public = True
session.add(master_set)
first_expansion = Release(name="First Expansion")
first_expan... | 21,200 |
def UnN(X, Z, N, sampling_type):
"""Computes block-wise complete U-statistic."""
return UN(X, Z, N, Un, sampling_type=sampling_type) | 21,201 |
def view_log_view(request, model_name, object_id):
"""view log view
Arguments:
request {object} -- wsgi request object
content_type {str} -- content type
object_id {int} -- admin_log id
Returns:
retun -- html view
"""
if model_name not in register_form:
re... | 21,202 |
def parse_markdown(source: str) -> Tuple[str, Dict]:
"""Parse a Markdown document using our custom parser.
Args:
source (str): the Markdown source text
Returns:
tuple(str, dict):
1. the converted output as a string
2. any extracted metadata as a dict
"""
# ... | 21,203 |
def flatten_list(nested_list):
# Essentially we want to loop through each element in the list
# and check to see if it is of type integer or list
"""
Flatten a arbitrarily nested list
Args:
nested_list: a nested list with item to be either integer or list
example:
[2,[[... | 21,204 |
def detect_runner():
""" Guess which test runner we're using by traversing the stack and looking
for the first matching module. This *should* be reasonably safe, as
it's done during test discovery where the test runner should be the
stack frame immediately outside. """
if _test_runner_ov... | 21,205 |
def analyze(ss, cfg):
"""
Run job
:param ss: SparkSession
:param cfg: app configuration
:return: None
"""
logger = logging.getLogger(__name__)
logger.info('Python version: {}'.format(sys.version))
logger.info('Finding all papers')
# MAG dataset to use
db_name = cfg['mag_db_... | 21,206 |
def retinanet(
mode,
offsets_mean=None,
offsets_std=None,
architecture='resnet50',
train_bn=False,
channels_fmap=256,
num_anchors_per_pixel=9,
num_object_classes=1,
pi=0.01,
alpha=0.25,
gamma=2.0,
confidence_... | 21,207 |
def default_chap_exec(gallery_or_id: Union[Gallery, int], chap: Chapter, only_values=False) \
-> Union[Tuple[str, dict], Tuple[int, Union[str, List[str]], int, bytes, int, Literal[0, 1]]]:
"""Pass a Gallery object or gallery id and a Chapter object"""
gid: int
if isinstance(gallery_or_id, Gallery):
... | 21,208 |
def merge_closest_groups(groups, special_tokens=None):
""" Finds the two token groups with the best merge score and merges them.
"""
scores = [merge_score(groups[i], groups[i+1], special_tokens) for i in range(len(groups)-1)]
#print(scores)
ind = np.argmax(scores)
groups[ind] = groups[ind] + gro... | 21,209 |
def _list_all(listing_call, output_format='dict', *args, **filters):
"""Helper to handle paged listing requests.
Example usage:
``evaluations = list_all(list_evaluations, "predictive_accuracy", task=mytask)``
Parameters
----------
listing_call : callable
Call listing, e.g. list_evalua... | 21,210 |
def get_matching_based_variables(match_definitions:List[Dict[Literal['name', 'matching'],Any]],
global_dict=None,
local_dict=None,
var_lenght=0):
"""
Function to construct an array with values depending on the con... | 21,211 |
def _AStar_graph(problem: BridgeProblem) -> (list, list):
"""Used for graphing, returns solution as well as all nodes in a list"""
all_nodes = [problem.initial_node]
pq = [(problem.initial_node.path_cost + problem.h(problem.initial_node.state), problem.initial_node)]
closed = set()
while True:
... | 21,212 |
def plot_setup(name, figsize=None, fontsize=9, font='paper', dpi=None):
""" Setup a PDF page for plot.
name: PDF file name. If not ending with .pdf, will automatically append.
figsize: dimension of the plot in inches, should be an array of length two.
fontsize: fontsize for legends and labels.
font... | 21,213 |
def author_endyear(pub2author_df = None, colgroupby = 'AuthorId', datecol = 'Year', show_progress=False):
"""
Calculate the year of last publication for each author.
Parameters
----------
pub2author_df : DataFrame, default None, Optional
A DataFrame with the author2publication information.
... | 21,214 |
def plot_spatial_3d(pos, output_file, box_size):
"""
Plots the 3D spatial distribution of galaxies.
Parameters
==========
pos : ``numpy`` 3D array with length equal to the number of galaxies
The position (in Mpc/h) of the galaxies.
output_file : String
Name of the file the plo... | 21,215 |
def _filter_switch_ip(data):
"""filter switch ip related params to db/api understandable format.
Examples:
{'switchIp': '10.0.0.1'} to {'ip_int': {'eq': int of '10.0.0.1'}}
{'switchIpStart': '10.0.0.1'} to
{'ip_int': {'ge': int of '10.0.0.1'}}
{'switchIpEnd': '10.0.0.1'} to
... | 21,216 |
def to_gif(images, fps):
"""Converts image sequence (4D numpy array) to gif."""
imageio.mimsave('./animation.gif', images, fps=fps)
return embed.embed_file('./animation.gif') | 21,217 |
async def stop_all(consumers):
"""Stop all consumers.
"""
# pylint: disable=expression-not-assigned
[await a.stop() for a in consumers.values()] | 21,218 |
def get_half_max_down(signal, peak):
"""See `get_half_max_up` for explanation.
This is a minor modification of the above function.
"""
if peak['peak'] == 0:
return np.nan
fflag = False
half_max = signal[peak['peak']] / 2
falling_signal = signal[peak['peak']:(peak['right']+1)]
cl... | 21,219 |
def connect2server(env=None, key=None, keyfile=None, logger=None):
"""Sets up credentials for accessing the server. Generates a key using info
from the named keyname in the keyfile and checks that the server can be
reached with that key.
Also handles keyfiles stored in s3 using the env param""... | 21,220 |
def ternary(c):
"""
Encodes the circuit with ternary values
Parameters
----------
c : Circuit
Circuit to encode.
Returns
-------
Circuit
Encoded circuit.
"""
if c.blackboxes:
raise ValueError(f"{c.name} contains a blackbox")
t = copy(c)
... | 21,221 |
def eval_lane_per_frame(
gt_file: str, pred_file: str, bound_ths: List[float]
) -> Dict[str, np.ndarray]:
"""Compute mean,recall and decay from per-frame evaluation."""
task2arr: Dict[str, np.ndarray] = dict() # str -> 2d array
gt_byte = np.asarray(Image.open(gt_file))
pred_byte = np.asarray(Image.... | 21,222 |
def membrane(field, voxel_size=1, bound='dct2', dim=None, weights=None):
"""Precision matrix for the Membrane energy
Note
----
.. This is exactly equivalent to SPM's membrane energy
Parameters
----------
field : (..., *spatial) tensor
voxel_size : float or sequence[float], default=1
... | 21,223 |
def test_can_accept_colormap_dict():
"""Test that we can accept vispy colormaps in a dictionary"""
colors = np.array([[0, 0, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1]])
cmap = ensure_colormap({'colors': colors, 'name': 'special_name'})
assert isinstance(cmap, Colormap)
np.testing.assert_almost_equal(cmap.co... | 21,224 |
def get_uint64(dgram: bytes, start_index: int) -> Tuple[int, int]:
"""Get a 64-bit big-endian unsigned integer from the datagram.
Args:
dgram: A datagram packet.
start_index: An index where the integer starts in the datagram.
Returns:
A tuple containing the integer and the new end index.... | 21,225 |
def fftshift(x: torch.Tensor, dim: Optional[List[int]] = None) -> torch.Tensor:
"""
Similar to np.fft.fftshift but applies to PyTorch Tensors
Args:
x: A PyTorch tensor.
dim: Which dimension to fftshift.
Returns:
fftshifted version of x.
"""
if dim is None:
# thi... | 21,226 |
def flatten(x):
"""Flattens nested list"""
if isinstance(x, list):
return [a for i in x for a in flatten(i)]
else:
return [x] | 21,227 |
def get_capture_points_gazebo(bag, odom_topic='/gazebo/model_states', sync_topic='/mavros/imu/data_raw', camera_freq=20, sync_topic_freq=100, method='every'):
"""
method(string): method for sampling capturing points.
'every': Sample IMU for every n msgs, and then capture odometry msg which has the clos... | 21,228 |
async def test_get_connected_devices_no_ip(event_loop, mocker):
"""Test for get asuswrt_data and not requiring ip."""
mock_run_cmd(mocker, [WL_DATA, ARP_DATA, NEIGH_DATA, LEASES_DATA])
scanner = AsusWrt(host="localhost", port=22, mode="ap", require_ip=False)
data = await scanner.async_get_connected_devi... | 21,229 |
def parse_input():
"""Parse input and return array of calendar
A user can either pass the calendar via the stdin or via one or several
icalendar files. This method will parse the input and return an array
of valid icalendar
"""
input_data = ''
calendars = []
for line in fileinput.input... | 21,230 |
def identity(obj):
"""Returns the ``obj`` parameter itself
:param obj: The parameter to be returned
:return: ``obj`` itself
>>> identity(5)
5
>>> foo = 2
>>> identity(foo) is foo
True
"""
return obj | 21,231 |
def assignCrowdingDist(individuals):
"""Assign a crowding distance to each individual's fitness. The
crowding distance can be retrieve via the :attr:`crowding_dist`
attribute of each individual's fitness.
"""
if len(individuals) == 0:
return
distances = [0.0] * len(individuals)
crow... | 21,232 |
def loadAllProteins(proteinfiles, basefile, chromosomes,
matrixfile,correctmatrix,celltype,resolution,internaloutdir,chromsizefile):
"""
Function for binning ChIP-seq data.
Data must be provided in narrowPeak, broadPeak or bigwig format.
Simultaneous usage of different formats is pos... | 21,233 |
def percent_clipper(x, percentiles):
"""
Takes data as np.ndarray and percentiles as array-like
Returns clipped ndarray
"""
LOWERBOUND, UPPERBOUND = np.percentile(x, [percentiles[0], percentiles[1])
return np.clip(x, LOWERBOUND, UPPERBOUND) | 21,234 |
def check_prob_vector(p):
"""
Check if a vector is a probability vector.
Args:
p, array/list.
"""
assert np.all(p >= 0), p
assert np.isclose(np.sum(p), 1), p
return True | 21,235 |
def relabel_subgraph():
""" This function adapts an existing sampler by relabelling the vertices in the edge list
to have dense index.
Returns
-------
sample: a function, that when invoked, produces a sample for the input function.
"""
def relabel(edge_list, positive_vertices):
sha... | 21,236 |
def get_activation_bytes(input_file=None, checksum=None):
"""
Get the activation bytes from the .aax checksum using rainbow tables.
None is returned if the activation bytes can't be computed.
"""
if (not input_file and not checksum) or (input_file and checksum):
raise ValueError('Ple... | 21,237 |
def init_binary(mocker):
"""Initialize a dummy BinaryDigitalAssetFile for testing."""
mocker.patch.multiple(
houdini_package_runner.items.digital_asset.BinaryDigitalAssetFile,
__init__=lambda x, y, z: None,
)
def _create():
return houdini_package_runner.items.digital_asset.Binar... | 21,238 |
def with_setup_(setup=None, teardown=None):
"""Decorator like `with_setup` of nosetest but which can be applied to any
function"""
def decorated(function):
def app(*args, **kwargs):
if setup:
setup()
try:
function(*args, **kwargs)
f... | 21,239 |
def g_model(padmode, padvalue, interpolation, resource_names,
datasource, binning, output):
"""Derives a model from DATASOURCE with given BINNING.
The model is written to OUTPUT.
BINNING can be a path to a previously created binning, or custom bin edges
in all dimension: dimensions are sepa... | 21,240 |
def post_options():
"""Standard arguments and options for posting timeseries readings.
"""
options = [
click.argument('port'),
click.argument('value', type=JSONParamType()),
click.option('--timestamp', metavar='DATE',
help='the time of the reading'),
]
d... | 21,241 |
def make_filesystem(device, block_device):
"""
Synchronously initialize a device file with an ext4 filesystem.
:param FilePath device: The path to the file onto which to put the
filesystem. Anything accepted by ``mkfs`` is acceptable (including a
regular file instead of a device file).
... | 21,242 |
def _partial_read_stats(
args: argparse.Namespace,
stats: Dict,
input_data: Dict,
):
"""Calculate statistics about partially read files.
:param args: Parsed command line arguments.
:param stats: Statistics data structure.
:param input_data: Input data from registry for partially... | 21,243 |
def add_vcz_parameters(this_flux_lm, which_gate: str = None):
"""
Adds to `this_flux_lm` the necessary parameters used for the VCZ
flux waveform including corrections
"""
this_flux_lm.add_parameter(
"vcz_amp_dac_at_11_02_%s" % which_gate,
docstring="DAC amplitude (in the case of HDAW... | 21,244 |
def bufferSetDefaultAllocMode(defAllocMode, defInitialSize):
"""
Sets new global default allocation mode and minimal intial size.
defAllocMode : the new default buffer allocation mode.
defInitialSize : the new default buffer minimal intial size.
"""
xmlsecmod.bufferSetDefaultAllocMode(defAlloc... | 21,245 |
def test_in_scalar():
""" Testing the in_scalar function
"""
scalar = in_scalar(5)
assert scalar.units == u.dimensionless
assert scalar.magnitude == 5
scalar = in_scalar(5 * u.dimensionless)
assert scalar.units == u.dimensionless
assert scalar.magnitude == 5
with pytest.raises(Val... | 21,246 |
def authenticated(f):
"""Decorator for authenticating with the Hub"""
@wraps(f)
def decorated(*args, **kwargs):
token = request.cookies.get(auth.cookie_name)
if token:
user = auth.user_for_token(token)
else:
user = None
if user:
return f(u... | 21,247 |
def warn(msg):
"""
Print an warning message.
"""
print("WARNING: {}".format(msg), file=sys.stderr) | 21,248 |
def json_complex_hook(dct):
"""
Return an encoded complex number to it's python representation.
:param dct: (dict) json encoded complex number (__complex__)
:return: python complex number
"""
if isinstance(dct, dict):
if '__complex__' in dct:
parts = dct['__complex__']
assert len(parts) == 2
return pa... | 21,249 |
def reg_logLiklihood(x, weights, y, C):
"""Regularizd log-liklihood function (cost function to minimized in logistic
regression classification with L2 regularization)
Parameters
-----------
x : {array-like}, shape = [n_samples, n_features + 1]
feature vectors. Note, first column of x mu... | 21,250 |
def two_dimension_heatmap(data, xmin, xmax, ymin, ymax):
"""
Args:
nparray with two dimensions
"""
# interpolation gaussian
plt.xlabel("Packet size (bit)")
plt.ylabel("bit error rate")
image = plt.imshow(
data,
cmap="Greens",
interpolation="none",
ex... | 21,251 |
def smooth_internal(xyzlist, atom_names, width, allpairs=False, w_morse=0.0, rep=False, anchor=-1, window='hanning', **kwargs):
"""Smooth a trajectory by transforming to redundant, internal coordinates,
running a 1d timeseries smoothing algorithm on each DOF, and then
reconstructing a set of consistent cart... | 21,252 |
def cli():
"""Define the command line interface of the script."""
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument("--output", help="the directory to store the archives")
parser.add_argument("--repeats", type=i... | 21,253 |
def estimate_gridsearch_size(model, params):
""" Compute the total number of parameter combinations in a grid search
Parameters
----------
model: str
name of the model to train. The function currently supports feedforward neural networks (model = 'FNN'),
long-short term memory (model ... | 21,254 |
def softmax_logits_kld(ops, p_logits, q_logits, keepdims=False):
"""
Compute the KL-divergence between two softmax categorical distributions
via logits. The last dimension of `p` and `q` are treated as the
softmax dimension, and will be reduced for computing KL-divergence.
.. math::
\\ope... | 21,255 |
def E_inductive_from_ElectricDipoleWholeSpace(
XYZ,
srcLoc,
sig,
f,
current=1.0,
length=1.0,
orientation="X",
kappa=1.0,
epsr=1.0,
t=0.0,
):
"""
Computing Inductive portion of Electric fields from Electrical Dipole in a Wholespace
TODO:
Add descri... | 21,256 |
def translate_categories_json(n=10):
"""Translate category descriptions in categories.json to the most common n non-english languages"""
language_list = get_language_list()
language_list = language_list[:n]
with open(os.path.join(data_directory, 'categories.json'), 'r') as f:
categories_mapping ... | 21,257 |
def str2posix(timelist):
""" This will take a list of strings with the date along with a start and
end time and make a list with the posix times.
Inputs
timelist - A list of strings with the data followed by two times.
The date for the second time can also be used, it will be... | 21,258 |
def test_spherical_isolation_grid1():
""" Create a regular grid inside the unit box with points on each of the following
nodes: 0.1, 0.3, 0.5, 0.7, 0.9. Demonstrate that all points in such a sample
are isolated if r_max < 0.2, regardless of periodic boundary conditions.
"""
sample1 = generate_3d_reg... | 21,259 |
def iterate_by_type(objs, typelist):
"""
collects a sequence of objs into buckets by type, then re-emits
objs from the buckets, sorting through the buckets in the order
specified by typelist. Any objects of a type not specified in
typelist will be emitted last in no guaranteed order (but still
g... | 21,260 |
def keys_verif(verif: bool = True):
"""
Used to verify existence of private or/and public keys of ElGamal.
"""
print("\nChecking the presence of keys in the system....")
if isFileHere("public_key.kpk", config.DIRECTORY_PROCESSING):
# from cipher.asymmetric import elGamal as elG
p... | 21,261 |
def r2(ground_truth, simulation, join='inner', fill_value=0):
"""
R-squared value between ground truth and simulation
Inputs:
ground_truth - ground truth measurement (data frame) with measurement in the "value" column
simulation - simulation measurement (data frame) with measurement in the "value" ... | 21,262 |
def atualiza_pontos(lista_jogadores, indece, pontos_carregados):
"""
-> Funcão que ao ser chamada atualiza os pontos dos jogadores.
:param lista_jogadores: é a lista que contem todos os dados dos jogadores cadastados, seus respectivos
nomes e pontos.
:param indece: é o índece do jogador que está jog... | 21,263 |
def add_team_batting_stats(df, years, batter_metrics):
"""
"""
gids = list(set(df['gameId']))
bat_saber_paths = [
CONFIG.get('paths').get('batter_saber') + gid + \
"/batter_saber_team.parquet" for gid in
os.listdir(CONFIG.get('paths').get('batter_saber'))
]
curr_gids = li... | 21,264 |
def depth_analysis_transform_1(rgb_tensor, depth_tensor, num_filters):
"""Builds the analysis transform."""
with tf.variable_scope("analysis"):
# --------------------------------------- rgb branch
with tf.variable_scope("layer_0"):
layer = tfc.SignalConv2D(
num_filters, (9, 9), corr=True, s... | 21,265 |
def boxPlot(med, quartiles, minmax, mean=None, outliers=None, name='boxplot', horiz=True, offset=0,
legendGroup='boxplot', showleg=False, plot=False, col='blue', width=8):
"""
Makes very light plotly boxplot. Unlike theirs, this can take externally calc'd values rather than just data to make it go m... | 21,266 |
def hub_quantile_prediction_dict_validator(target_group_dict, prediction_dict):
"""
Does hub prediction_dict validation as documented in `json_io_dict_from_quantile_csv_file()`
"""
error_messages = [] # return value. filled next
valid_quantiles = target_group_dict['quantiles']
prediction_quanti... | 21,267 |
def allclose_periodical(x, y, a, b, atol=1e-10):
"""
Checks np.allclose(x,y), but assumes both x and y are periodical with respect to interval (a,b)
"""
assert(len(x) == len(y))
period = b-a
x_p = np.remainder(x-a,period) # now in 0, b-a
y_p = np.remainder(y-a,period)
return all(np.isclo... | 21,268 |
def get_categories_to_rows_ratio(df):
"""
Gets ratio of unique categories to number of rows
in the categorical variable; do this for each categorical
variable
:param df: pd.DataFrame
:return: array of tuples
"""
cat_columns = get_categorical_variable_names(df)
ratios = {col:len(df[c... | 21,269 |
def _width_left_set(size: int, lsize: int, value: list, fmt: str, meta: dict) -> dict:
"""Width setting of paragraph with left repositioning."""
return Plain([RawInline(fmt, '<p style="text-align:left !important;'
'text-indent:0 !important;'
'position:rela... | 21,270 |
def GetMappingKeyName(run, user):
"""Returns a str used to uniquely identify a mapping."""
return 'RunTesterMap_%s_%s' % (run.key().name(), str(user.user_id())) | 21,271 |
def get_invitee_from_table(invite_code: str, table):
"""
Get a dictionary of the stored information for this invite code.
Args:
invite_code: The invitation code to search for
table: A DynamoDB table for querying
Returns:
A dictionary of information stored under the invite code
... | 21,272 |
def load_game(filename: str):
"""
Deserialise the game data from a file. Filename does not include path to save folder.
"""
# read from json
with open(SAVE_PATH + filename + ".json", "r") as file:
save = json.load(file)
# check the version
if save["version"] != VERSION:
logg... | 21,273 |
def minter(pid_type, pid_field, record):
"""Mint the given PID for the given record."""
if pid_field not in record.keys():
record[pid_field] = create_pid()
pid = PersistentIdentifier.get(
pid_type="recid",
pid_value=record[pid_field]
)
pid.status = PIDStatus.REGISTERED
p... | 21,274 |
def export_to_labelbox(
sample_collection,
ndjson_path,
video_labels_dir=None,
labelbox_id_field="labelbox_id",
label_field=None,
frame_labels_field=None,
):
"""Exports labels from the FiftyOne samples to Labelbox format.
This function is useful for loading predictions into Labelbox for... | 21,275 |
def zip_minibatch_iterate_info(arrays, minibatch_size, n_epochs=None, test_epochs = None):
"""
Iterate through minibatches of arrays and yield info about the state of iteration though training.
:param arrays:
:param arrays: A collection of arrays, all of which must have the same shape[0]
:param min... | 21,276 |
def d_beta_dr(radius, beta, mass_r, epsilon, pressure, h_r):
""" d_beta_dr """
return 2. * (1 - 2 * (mass_r/radius)) ** (-1.) * h_r * \
( -2. * math.pi * (5*epsilon + 9*pressure + f(epsilon, pressure)) + (3/radius**2.) + 2*(1 - 2 * mass_r / radius)**(-1) * \
((mass_r/radius) + 4 * math.pi*radius... | 21,277 |
def main(args=None):
"""Main function called by the `MPfspec` command line script."""
import argparse
description = ('Create frequency spectra (PDS, CPDS, cospectrum) '
'starting from well-defined input ligthcurves')
parser = argparse.ArgumentParser(description=description)
parse... | 21,278 |
def handle_signals():
"""
typing the interrupt character (probably Ctrl-C) causes SIGINT to be sent
typing the quit character (probably Ctrl-\) sends SIGQUIT.
hanging up the phone (modem) sends SIGHUP
typing the stop character (probably Ctrl-Z) sends SIGSTOP.
"""
LOG.info('Setting up signal ... | 21,279 |
def test_ndcg_after_2_perfect():
"""
ndcg with top 2 classes removed
"""
y_true = np.array([[1, 1, 1, 0, 0, 0],
[1, 1, 0, 1, 0, 1],
[0, 1, 1, 1, 1, 1],
[0, 1, 1, 0, 1, 1],
[0, 0, 1, 1, 1, 1]])
y_prob = np.ar... | 21,280 |
def score(capstone, student_api):
"""
Calculates the score of the students' API model
:param student_api: StudentApi object
:return: score as a float
"""
# Check which simulators have datapoints with outcomes outcomes
simulator_ids = []
for simulator in capstone.simulators.all():
... | 21,281 |
def clean_lhdf(df: pd.DataFrame):
"""
Removes unneccessary columms from the location history data frame and computes new required columns
Parameters
----------
df : pandas.DataFrame
DataFrame to process
Returns
-------
Copy of `df`, altered the following way:
* Colums remov... | 21,282 |
def year_from_operating_datetime(df):
"""Add a 'year' column based on the year in the operating_datetime.
Args:
df (pandas.DataFrame): A DataFrame containing EPA CEMS data.
Returns:
pandas.DataFrame: A DataFrame containing EPA CEMS data with a 'year'
column.
"""
df['year']... | 21,283 |
def is_thrift(target):
"""Returns True if the target has thrift IDL sources."""
return isinstance(target, JavaThriftLibrary) | 21,284 |
def print_events_unified(success_result: dict):
"""Print the results of `getevents`, in one table"""
elist = success_result["events"]
for event in elist:
event["time"] = datetime.datetime.fromisoformat(event["time"])
lowest_time = min(event["time"] for event in elist)
for event in elist:
... | 21,285 |
def get_instance(value, model):
"""Returns a model instance from value. If value is a string, gets by key
name, if value is an integer, gets by id and if value is an instance,
returns the instance.
"""
if not issubclass(model, db.Model):
raise TypeError('Invalid type (model); expected subcla... | 21,286 |
def add_badfit_estimates(results, base_estimate_label="default", estimate_types=('wildcard',),
badFitThreshold=None, opt_args=None, evaltree_cache=None,
comm=None, memLimit=None, verbosity=0):
"""
Add any and all "bad fit" estimates to `results`.
TODO: docst... | 21,287 |
def clean_infix(token, INFIX):
"""
Checks token for infixes. (ex. bumalik = balik)
token: word to be stemmed for infixes
returns STRING
"""
if check_validation(token):
return token
for infix in INFIX_SET:
if len(token) - len(infix) >= 3 and count_vowel(token[len(infix):]) >= 2:
if token[0] == token[... | 21,288 |
def test_catalog_size(test_catalog):
"""Passes if catalog.size matches the length of data"""
assert test_catalog.size == len(test_catalog.data) | 21,289 |
def seq_to_encoder(input_seq):
"""从输入空格分隔的数字id串,转成预测用的encoder、decoder、target_weight等
"""
input_seq_array = [int(v) for v in input_seq.split()]
encoder_input = [PAD_ID] * \
(input_seq_len - len(input_seq_array)) + input_seq_array
decoder_input = [GO_ID] + [PAD_ID] * (output_seq_len - 1)
e... | 21,290 |
def SendEmailNotificationSuccess():
""" Sends a successful email notification to the EmailNotice attribute"""
global gVoOutput
global gSitesMissingData
subject = "GRATIA-APEL interface for %s - SUCCESS (%s)" % (gDateFilter,gRunTime)
contents = """The interface from Gratia to the APEL (WLCG) database was suc... | 21,291 |
def getMergers(tree, map_strain2species, options):
"""merge strains to species.
returns the new tree with species merged and
a dictionary of genes including the genes that have been merged.
Currently, only binary merges are supported.
"""
n = TreeTools.GetSize(tree) + 1
all_strains = map_... | 21,292 |
def convolve_with_gaussian(
data: np.ndarray, kernel_width: int = 21
) -> np.ndarray:
"""
Convolves a 1D array with a gaussian kernel of given width
"""
# create kernel and normalize area under curve
norm = stats.norm(0, kernel_width)
X = np.linspace(norm.ppf(0.0001), norm.ppf(0.9999), k... | 21,293 |
def post_netspeed(event, context):
"""
Speed test data ingestion handler
"""
return process_reading(event['query'], NETSPEED_SQL) | 21,294 |
def notify_host_disabled(token, host_name):
"""
Notify OpenStack Nova that a host is disabled
"""
url = token.get_service_url(OPENSTACK_SERVICE.NOVA, strip_version=True)
if url is None:
raise ValueError("OpenStack Nova URL is invalid")
# Get the service ID for the nova-compute service.
... | 21,295 |
def compute_moments_weights_slow(mu, x2, neighbors, weights):
"""
This version exaustively iterates over all |E|^2 terms
to compute the expected moments exactly. Used to test
the more optimized formulations that follow
"""
N = neighbors.shape[0]
K = neighbors.shape[1]
# Calculate E[G]... | 21,296 |
def sum_fn(fun, ndims=0):
"""Higher order helper for summing the result of fun."""
@functools.wraps(fun)
def wrapped(*args):
batch_loglik = fun(*args)
return jnp.sum(
batch_loglik.reshape((-1,) +
batch_loglik.shape[-ndims +
... | 21,297 |
def p_value_analysis(data, opts):
"""
p-value analysis with cumulative freq.
Only positive signals.
Negative ctools ts => 0
"""
# photometrics analysis
total = len(data)
positive_signals = [d for d in data if d['phm_excess'] > 0]
log.info(f' considered data: {len(data)}')
lo... | 21,298 |
def get_control_policy_attachments(language: Optional[str] = None,
output_file: Optional[str] = None,
policy_type: Optional[str] = None,
target_id: Optional[str] = None,
opts: Opti... | 21,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.