content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def resize_image(ratio, path, image_format=None):
"""
thumbnail est une imagette
:param ratio:entier : Taux de réduction
:param path: string : chemin du fichier image à réduire .
:param image_format: string : extension indiquant le type de l'image (PPM, PNG, JPEG, GIF, TIFF and BMP etc )
:r... | 50,000 |
def test_tuple_list_to_dataframe(
grammer_instance: Grammer, mock_terms_to_cols: Mock
) -> None:
"""It returns Pandas dataframe from tuple list."""
mock_terms_to_cols.return_value = ["snacks low", "low calorie"], [2, 1]
test_tuple_list = [(("test", "thing"), 3)]
df = grammer_instance.df_from_terms(t... | 50,001 |
def test_expand_node_with_all_actions(o, actions, init_stats):
"""tests :func:~online_pomdp_planning.mcts.expand_node_with_all_actions"""
parent = ObservationNode()
stats = 0
node = ActionNode(stats, parent)
info = {}
expand_node_with_all_actions(actions, init_stats, o, node, info)
expansi... | 50,002 |
def json_serializer(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, datetime):
# Serialize datetime as the ISO formatted string
serial = obj.isoformat()
return serial
raise TypeError("Type not serializable") | 50,003 |
def save_as_pt(input_img):
"""
This function is to transfer nii.gz file into .pt format, in order to train the classifiers model more efficient when loading the data.
:param input_img:
:return:
"""
import torch
import os
import nibabel as nib
image_array = nib.load(input_img).get_f... | 50,004 |
def leaves_f(prog, typ):
"""Doc."""
return list(filter(lambda it: type(it), leaves(prog))) | 50,005 |
def imshow_xy(axes, coord, data,
xy_limits=None, xy_pad=0.02, add_lines=False,
step_kw=None, line_kw=None, **kwargs):
""" Show data as an image in ax, with slices at x and y in
the subplots axy and axx.
img = ax.imshow(data)
step_x = axx.step(data[coord[1], :... | 50,006 |
def test_decimal_scale_is_a_positive_int():
"""https://github.com/fastavro/fastavro/issues/457"""
schema = {
"type": "record",
"name": "test_scale_is_an_int",
"fields": [
{
"name": "field",
"type": {
"logicalType": "decimal"... | 50,007 |
def create_endpoint(project_id: str, region: str, endpoint_name: str) -> str:
"""
Create an endpoint on Vertex AI
:param project_id:
:param region:
:param endpoint_name:
:return:
"""
try:
endpoint = aiplatform.Endpoint.create(display_name=endpoint_name, project=project_id, locat... | 50,008 |
def get_warning_logger() -> logging.Logger:
"""
Set up a logger to capture warnings and log them
"""
logging.captureWarnings(True)
warning_logger = logging.getLogger('py.warnings')
if warning_logger.handlers: warning_logger.handlers = []
return warning_logger | 50,009 |
def main():
"""
-This photo is created based on the idea of
attempting to distract focus from my self image xD,
as well as providing fun looking for Wally with MASK!
-The way to do it is to combine two images in one
and display the combined image.
"""
selfie = SimpleImage('image_cont... | 50,010 |
def generate_us_zipcode_data():
"""Generate a list of US zipcode data from the txt file in the latest
Geonames.org database and save it as a JSON file.
"""
us_zipcode_data = []
us_zipcode_txt_file_data = _get_latest_us_zipcode_data()
for line in us_zipcode_txt_file_data:
zip = line.decod... | 50,011 |
def check_connection_ntuple(conn):
"""Check validity of a connection namedtuple."""
valid_conn_states = [getattr(psutil, x) for x in dir(psutil) if
x.startswith('CONN_')]
assert conn[0] == conn.fd
assert conn[1] == conn.family
assert conn[2] == conn.type
assert conn[3] =... | 50,012 |
def check_type_match(actual_val, expected_val) -> bool:
"""Check actual_val matches type of expected_val
The exception here is that expected_val can be
float, and in that case actual_val can be either
int or float
Args:
actual_val (Any): Actual type
expected_val (Any): Expe... | 50,013 |
async def test_task_raises():
"""Raise an exception from a task"""
async def raiser():
await asyncio.sleep(0.01)
raise ValueError('boom')
with pytest.raises(ValueError):
async with Scope() as n:
n << raiser() | 50,014 |
def test_affine_transformer_round_trip(batch_size, n_features):
"""Make sure the forward + inverse conposition of affine transformers is equal to the identity."""
x, coefficients = create_random_input(batch_size, n_features, dtype=torch.double,
n_parameters=2, seed=0)
... | 50,015 |
def _single_step_smart_generalized_leapfrog(
grad_log_posterior: Callable,
metric: Callable,
grad_metric: Callable,
grad_log_posterior_and_metric_and_grad_metric: Callable,
zo: Tuple[np.ndarray],
step_size: float,
thresh: float,
max_iters: int,
cac... | 50,016 |
def real_sph_harm(l, zero_m_only=True, spherical_coordinates=True):
"""
Computes formula strings of the the real part of the spherical harmonics up to order l (excluded).
Variables are either cartesian coordinates x,y,z on the unit sphere or spherical coordinates phi and theta.
"""
if not zero_m_onl... | 50,017 |
def plot_mean_interval(ax, x, y,
ma_type='sliding',
window_size=100,
resolution=10,
nbootstraps=1000,
confidence=95,
color='grey',
alpha=0.25,
... | 50,018 |
def drsky(x, ecc, omega, inc):
"""Function whose roots we wish to find to obtain time of secondary
(and primary) eclipse(s)
When one takes the derivative of equation (5) in Winn
(2010; https://arxiv.org/abs/1001.2010v5), and equates that to zero
(to find the minimum/maximum of said function), one g... | 50,019 |
def test_web_layout_url_src():
"""Test image URLs with $ssWeblayoutUrl directives."""
md_converter = learning_importer.MHRAMarkdownConverter(
content_prefix="/content/", asset_prefix="/asset/"
)
result = md_converter.convert(
"<img src=\"[!--$ssWeblayoutUrl('ab/cd/abc123.jpg')--]\" "
... | 50,020 |
def preserve_selection(tree_view,
column=0,
role=QtCore.Qt.DisplayRole,
current_index=True):
"""Preserves row selection in QTreeView by column's data role.
This function is created to maintain the selection status of
the model items. When... | 50,021 |
def ComputeQueryBasedMetrics( # pylint: disable=invalid-name
extracts: beam.pvalue.PCollection,
prediction_key: str,
query_id: str,
combine_fns: List[beam.CombineFn],
) -> beam.pvalue.PCollection:
"""Computes metrics and plots using the EvalSavedModel.
Args:
extracts: PCollection of Extracts. ... | 50,022 |
def get_brier_scores(at_time_intervals, censored_indicator=1.0):
"""Construct Brier score metrics for survival probability predictions."""
metrics = []
for t in at_time_intervals:
metric = partial(
brier_score, t=t, censored_indicator=censored_indicator)
metric.__name__ = 'bs_at_... | 50,023 |
def create_id_maps(session):
"""
Create a large universal map of maps that carries common items like
"Allegiance" or "Government" onto the id expected to be inserted into the db.
Returns: A adict of dicts that ultimately points to integer ids in the db.
"""
maps = {
'Allegiance': {x.edd... | 50,024 |
def _box_without_row_and_column_of(row, col, width, height):
"""Return some coordinates in the square of (col, row) as a list.
The coordinates in the same row and column are removed.
This is an internal function and should not be used
outside of the coordinates module.
"""
grid_x = col - (col ... | 50,025 |
def print_failure(string):
""" Print but sad. """
print(f"\033[91m\033[4m{string}\033[0m") | 50,026 |
def csv_out(filename, labels, datas):
"""
データをcsvで出力する.
Parameters
----------
filename : str
出力ファイル名
labels : tuple str
ラベル文字列のタプル
datas : tuple list
データのリストのタプル
"""
data = list(zip(*datas))
with open(filename, 'w') as f:
writer = csv.writer(f)
... | 50,027 |
def fieldtype(field):
"""Get the type of a django form field (thus helps you know what class to apply to it)"""
return field.field.widget.__class__.__name__ | 50,028 |
def options(parser, help_menu=False):
"""
Summary.
parse cli parameter options
Returns:
TYPE: argparse object, parser argument set
"""
parser.add_argument("-b", "--build", dest='build', default=False, action='store_true', required=False)
parser.add_argument("-D", "--debug", de... | 50,029 |
def test_glm_family_argument(f, fam, y, X):
"""Test GLM family argument set as string."""
glm = GeneralizedLinearRegressor(family=f, alpha=0).fit(X, y)
assert isinstance(glm._family_instance, fam.__class__) | 50,030 |
def fitToIntervals(areas: list, num_of_bins: int):
"""
fitting the area of each contour to the suitable interval.
:param areas: a list of contour areas.
:param num_of_bins: the number of intervals.
:return: a list containing each suitable interval for a given area.
"""
intervals = findInter... | 50,031 |
def parse_cmd_line():
""" Return True if a commnd-line option was run, else False """
HelpInformation = "kjv.py: Search, bookmark & browse the Bible."
parse = argparse.ArgumentParser(usage="", description=HelpInformation)
parse.add_argument(
"-s", "--Sierra",type = int,metavar="", help="Fin... | 50,032 |
def compute_reduced_reciprocal(init_approx, vy, num_iteration):
""" Compute the correctly rounded approximation of 1.0 / vy
using @p init_approx as starting point and execution
@p num_iteration Newton-Raphson iteration(s) """
current_approx = init_approx
inv_iteration_list = []
# comput... | 50,033 |
def topology_deployment_locations_name_get(name):
"""
get details of a deployment location
Returns information for the specified deployment location
:param name: Unique name for the location requested
:type name: str
:rtype: InlineResponse20010
"""
osmVim = OsmClient().getVim()
vim... | 50,034 |
def get_team_repo(remote_url):
"""
Takes remote URL (e.g., `git@github.com:mozilla/fireplace.git`) and
returns team/repo pair (e.g., `mozilla/fireplace`).
"""
if ':' not in remote_url:
return remote_url
return remote_url.split(':')[1].replace('.git', '') | 50,035 |
def ajax_request(func):
"""
If view returned serializable dict, returns JSONResponse with this dict as content.
example:
@ajax_request
def my_view(request):
news = News.objects.all()
news_titles = [entry.title for entry in news]
return {'news_tit... | 50,036 |
def nsi_op_list2(ctx, name):
"""shows the history of operations over a Network Slice Instance (NSI)
NAME: name or ID of the Network Slice Instance
"""
nsi_op_list(ctx, name) | 50,037 |
def load_collection_from_file(resource, filename, content_type=None):
"""
Creates a new collection for the registered resource and calls
`load_into_collection_from_file` with it.
"""
coll = create_staging_collection(resource)
load_into_collection_from_file(coll, filename,
... | 50,038 |
def test_write_data_fails():
"""
Check that write data raises an exception for non-zero return codes.
"""
# It's hard to make the C API function fail without causing a Segmentation
# Fault. Can't test this if by giving a bad file name because if
# output=='', GMT will just write to stdout and sp... | 50,039 |
def test_data_folder(request):
"""
This fixture returns path to folder with shared test resources among asr tests
"""
data_dir = os.path.join(script_dir, "testdata")
if not os.path.exists(data_dir):
os.mkdir(data_dir)
return data_dir | 50,040 |
def scan_eddystone(on_data=None):
"""
Provide a callback for 'on_data'. The callback will be run whenever
an Eddystone URL packet is detected.
:param on_data: A function to be called on Eddystone packet
:return: None
"""
try:
Scanner.start_beacon_scan(on_eddystone_url=on_data)
e... | 50,041 |
def get_fxa_token(*, code=None, refresh_token=None, config=None):
"""Given an FxA access code or refresh token, return dict from FxA /token endpoint
(https://git.io/JJZww). Should at least contain `access_token` and
`id_token` keys.
"""
assert config, 'config dict must be provided to get_fxa_token'
... | 50,042 |
def set_slice_sagittal_callback(attr, old, new):
"""
Called if the slice_slider_sagittal has been modified (directly by user or or indirectly via click event)
Usually re-plots the sagittal figure (and the others if region outline is active). Also relocates the cross hairs
indicating the selected sagitt... | 50,043 |
def merge_connected_components(conn_components, ingoing, outgoing):
"""
Merge the unconnected connected components
Parameters
-------------
conn_components
Connected components
ingoing
Ingoing dictionary
outgoing
Outgoing dictionary
Returns
-------------
... | 50,044 |
def split_indices_with_unseen_target_geo_in_test(loads, geo_ids, labels,
bias_train=False, seed=None,
debug=True):
""" Args:
loads: (list) train-test-val split percentages strictly positive and must sum to... | 50,045 |
def create_doc_index(ui_mat_rdd,
export=False):
"""
Indexes the docs and saves the index in a dictionary. The indexes are
then saved to disk. The indexing allows us to use internal integer IDs
for the users and documents instead of real IDs. The internal IDs are used
to index the different model matrices efficie... | 50,046 |
def _multiple_backends_not_enabled():
"""Throw exception indicating multiple backends support is not enabled."""
pecan.abort(404, u._('Not Found. Multiple backends support is not enabled '
'in service configuration.')) | 50,047 |
def read_markers_from_file(filepath, ext=None):
"""
Read a cell marker file from accepted file formats.
Currently supported: csv, tsv.
See doc for formatting.
"""
# Get extension
if ext is None:
ext = filepath.split('.')[-1]
dict_format = {"csv":read_markers_csv, "tsv":read_marke... | 50,048 |
def check_if_cube_is_there():
"""Verify that the cube is still inside the arena."""
camera_data = tricamera.SingleProcessData(history_size=5)
camera_driver = tricamera.TriCameraObjectTrackerDriver(
"camera60", "camera180", "camera300"
)
camera_backend = tricamera.Backend(camera_driver, camer... | 50,049 |
def get_user_id_from_email(email):
""" Pulls the user from the MDB (or dies trying). Returns its email. """
u = utils.mdb.users.find_one({'login': email.lower().strip()})
if u is None:
raise AttributeError("Could not find user data for %s" % email)
return u['_id'] | 50,050 |
def test_set_parameters_bad_input():
"""
check the set_parameters function with wrong input type
"""
r=sheep_client.set_parameters("a")
assert(r["status_code"] == 550) | 50,051 |
def _object_exists(key):
"""Verify if a given key (path) exists, using the S3 API."""
try:
app.s3.head_object(Bucket=app.config.get("AWS_S3_BUCKET_NAME"),
Key=key)
except ClientError as e:
if e.response["Error"]["Code"] == "404":
return False
ra... | 50,052 |
def dpgmm_predict(data:pd.DataFrame,
code=None,
indices:pd.DataFrame=None,) -> np.ndarray:
"""
(假设)我们对这条行情的走势一无所知,使用机器学习可以快速的识别出走势,划分出波浪。
DPGMM聚类 将整条行情大致分块,这个随着时间变化会有轻微抖动。
所以不适合做精确买卖点控制。但是作为趋势判断已经足够了。
"""
sub_offest = 0
nextsub_first = sub_first = 0
... | 50,053 |
def list_ep(server: Server, path: str, r_type: OT = OT.DOMAIN, scope: EPScope = None) -> List[str]:
"""
List elements under an object fitting a type.
:param Server server: server object
:param str path: path to object
:param OT r_type: type of ep to return (default is domain)
:param EPScope sco... | 50,054 |
def check_if_partial(comments):
"""
Checks if comments contain info about Dat being a part of a series of dats (i.e. two part entropy scans where first
part is wide and second part is narrow with more repeats)
Args:
comments (string): Sweeplogs comments (where info on part#of# should be found)
... | 50,055 |
def add_parser_arguments(parser: Parser, arguments: Arguments) -> None:
"""Add arguments to parser
:param Parser parser: Parser to add arguments to
:param Arguments arguments: Arguments to add to parser
"""
for argument in arguments:
parser.add_argument(*argument[0], **argument[1]) | 50,056 |
def create_v1_session(): # noqa: E501
"""POST /v1/session
Creates a new boot session. # noqa: E501
:param session: A JSON object for creating sessions
:type session: dict | bytes
:rtype: Session
"""
if connexion.request.is_json:
LOGGER.debug("connexion.request.is_json")
LOG... | 50,057 |
def cardChunk(key, chunk):
"""
Parse Card Chunk Method
"""
for line in chunk:
values = []
sline = line.strip().split()
for idx in range(1, len(sline)):
values.append(sline[idx])
return {'card': sline[0],
'values': values} | 50,058 |
def init_module(filesystem):
"""Initializes the fake module with the fake file system."""
# pylint: disable=protected-access
FakePath.filesystem = filesystem
FakePathlibModule.PureWindowsPath._flavour = _FakeWindowsFlavour(
filesystem)
FakePathlibModule.PurePosixPath._flavour = _FakePosixFla... | 50,059 |
def update_outline(outline, filename=None, message=None):
"""
Updates the the outline from active instances in the workspace
"""
if not message:
message = "Automated update via presalytics.lib.tools.workflows.update_outline()"
update_components(filename=filename)
for p in range(0, ... | 50,060 |
def slave_hub_factory(config, comm_class, comm_config):
"""Factory of management bus slave hub instances
Args:
config (dict): management bus master config
comm_class (string): communication backend.
Unused, ZMQRedis is always used
comm_config (dict): config of the communicat... | 50,061 |
def morepath_modules(cls):
""" Returns all morepath modules which should be scanned for the given
morepath application class.
We can't reliably know the actual morepath modules that
need to be scanned, which is why we assume that each module has
one namespace (like 'more.transaction' or 'onegov.cor... | 50,062 |
def rgb565_to_rgb(arr, out=None):
"""
Convert a numpy :class:`~numpy.ndarray` in RGB565 format (unsigned 16-bit
values with 5 bits for red and blue, and 6 bits for green laid out
RRRRRGGGGGGBBBBB) to RGB format (structured floating-point type with 3
values each between 0 and 1).
"""
check_r... | 50,063 |
def run_highstate_tests(saltenv="base"):
"""
Lookup top files for minion, pass results to wrapped run_state_tests for copy and run
"""
top_states = __salt__["state.show_top"]().get(saltenv)
state_string = ",".join(top_states)
ret = run_state_tests(state_string, saltenv)
return ret | 50,064 |
def varianceOfLaplacian(img):
""" Compute the Laplacian of the image and then return the focus measure,
which is simply the variance of the Laplacian.
Source: A.Rosebrock, https://www.pyimagesearch.com/2015/09/07/blur-detection-with-opencv/
"""
return cv2.Laplacian(img, cv2.CV_64F).var() | 50,065 |
def main():
""" Parses the command-line args, and calls run. """
parser = argparse.ArgumentParser(
description='A pipeline that generates analysis pipelines.')
parser.add_argument('input', nargs='?',
help='A valid metapipe configuration file.')
parser.add_argument('-o', '--out... | 50,066 |
def show(tournament, participant_id, **params):
"""Retrieve a single participant record for a tournament."""
return api.fetch_and_parse(
"GET", "tournaments/%s/participants/%s" % (tournament, participant_id), **params
) | 50,067 |
def logsubexp(A, B):
"""
Numerically stable log(exp(A) - exp(B))
"""
# Just adding an epsilon here does not work: the optimizer moves it out
result = A + tt.log(1 - tt.clip(tt.exp(B - A), epsilon, 1-epsilon))
return result | 50,068 |
def sort_dict(d: dict, by: str = 'key',
allow_duplicates: bool = True) -> collections.OrderedDict:
"""
Sort a dictionary by key or value.
The function relies on
https://docs.python.org/3/library/collections.html#collections.OrderedDict .
The dulicated are determined based on
https... | 50,069 |
def main(argv):
"""
Creates a parquet file with provider type data.
:param list argv: the list elements should be:
[1]: Parquet file path with raw expression data
[2]: Output file
"""
molecular_characterization_path = argv[1]
raw_expression_parquet_path = ... | 50,070 |
def read_file_info(filename):
"""
Read an info file.
Parameters
----------
filename : string
The name of file with cross-sectional area and length information.
Returns
-------
info : dict
The values of cross-sectional area and length of the specimens,
"""
fd = o... | 50,071 |
def search_to_new_ids(index, query, k):
"""
this function maps the result ids to the ones ordered by the ivf clusters
to be used along with a re-ordered metadata
"""
distances, indices = index.search(query, k)
opq2 = faiss.downcast_VectorTransform(index.chain.at(0))
xq = opq2.apply(query)
... | 50,072 |
def build_simplex_lattice(factor_count, model_order = ModelOrder.quadratic):
"""Builds a Simplex Lattice mixture design.
This design can be used for 2 to 30 components. A simplex-lattice mixture
design of degree m consists of m+1 points of equally spaced values between
0 and 1 for each component. If m ... | 50,073 |
def position_specializations(position_block):
"""
:param bs4.Tag position_block: position block
:return: list
"""
position_block = position_block.find("div", {"class": "bloko-gap bloko-gap_bottom"})
profarea_name = position_block.find("span", {"data-qa": "resume-block-specialization-category"})... | 50,074 |
def test_center_crop_op(height=375, width=375, plot=False):
"""
Test CenterCrop
"""
logger.info("Test CenterCrop")
# First dataset
data1 = ds.TFRecordDataset(DATA_DIR, SCHEMA_DIR, columns_list=["image"])
decode_op = vision.Decode()
# 3 images [375, 500] [600, 500] [512, 512]
center_... | 50,075 |
def GetElement(layers, locations):
"""
Return the node(s) at the location(s) in the given layer(s).
This function works for fixed grid layers only.
* If layers contains a single GID and locations is a single 2-element
array giving a grid location, return a list of GIDs of layer elements
at... | 50,076 |
def create_sampling_strategy(param_variation_model,
sampling_strategy_configuration):
"""
A factory method that creates a
memosampler.strategies.SamplingStrategy object from a
memosampler.sampler.ParameterVariationModel and a
memomodel.SamplingStrategy configuratio... | 50,077 |
def assert_warning(model, guide, elbo):
"""
Assert that inference works but with a warning.
"""
pyro.clear_param_store()
inference = SVI(model, guide, Adam({"lr": 1e-6}), elbo)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
inference.step()
... | 50,078 |
def json_to_hps(dct):
"""Translate the params dict to HyperparameterSpace object.
:param dict dct: params dict.
:return: HyperparameterSpace.
:rtype: HyperparameterSpace or None
"""
if "hyperparameters" in dct:
hps = HyperparameterSpace()
for hp_dict in dct["hyperparameters"]:
... | 50,079 |
def phone_number(update: Update, context: CallbackContext):
"""Добавляет номер телефона в контекст пользователя и предлагает ввести ИНН"""
logger.info(f"User with chat_id {update.effective_user.id} sent phone number [{update.message.text}]")
context.user_data[State.PHONE_NUMBER] = update.message.text
... | 50,080 |
def db_available(test):
"""Decorator for detecting if OpenCV/Python bindings are available"""
from bob.io.base.test_utils import datafile
from nose.plugins.skip import SkipTest
import functools
@functools.wraps(test)
def wrapper(*args, **kwargs):
dbfile = datafile("db.sql3", __name__, None)
if os.p... | 50,081 |
def _print_cfg(d, indent=0) -> None:
"""Print an Isaac Gym environment configuration
:param d: The dictionary to print
:type d: dict
:param indent: The indentation level (default: 0)
:type indent: int, optional
"""
for key, value in d.items():
if isinstance(value, dict):
... | 50,082 |
def test_privacy_accepted(app, combatant, privileged_user):
"""Test accepted privacy policy."""
with Mockmail('emol.models.privacy_acceptance', True):
resolution = combatant.privacy_acceptance.resolve(True)
assert combatant.card_url is not None
assert resolution.get('card_url') == combatant.car... | 50,083 |
def downsample_adata(adata: AnnData,
mode: str = 'total',
n_cells: Optional[int] = None,
by: Optional[str] = None,
balance_cell_type: bool = False,
random_state: int = 0,
return_index: bool = Tr... | 50,084 |
def parse_blob(value, offset=0, **kwargs):
"""Return a blob from offset in value."""
size = calcsize('>i')
length = unpack_from('>i', value, offset)[0]
data = unpack_from('>%iQ' % length, value, offset + size)
return data, padded(length, 8) | 50,085 |
def test_oncv_default(fixture_sandbox, generate_calc_job, generate_inputs_oncv, file_regression):
"""Test a default `opsp.pseudo.oncv`."""
entry_point_name = 'opsp.pseudo.oncv'
inputs = generate_inputs_oncv()
calc_info = generate_calc_job(fixture_sandbox, entry_point_name, inputs)
# Check the attr... | 50,086 |
def send_emails__evaluation_and_rebuttal():
"""
Send emails for the Evaluation step: i.e. when two reviews are returned,
are ready to be evaluated.
"""
subject = 'Interactive Peer Review: start evaluating ...'
import time
from basic.models import EntryPoint
from interactive.models import... | 50,087 |
def _get_now(utc: bool = False) -> datetime.datetime: # pragma: nocover
"""Workaround over datetime C module to be able to mock & patch in tests.
"""
if utc:
return datetime.datetime.utcnow()
return datetime.datetime.now() | 50,088 |
def save_to_csv_mat(name, values, path):
"""
Basic saver to .csv and .mat, only used by metadata
Parameters
----------
name : name to save to
values : values to save
path : path to save
Returns
-------
None.
"""
with open(path + "/" + name + '.csv', mode='w') as csv_fi... | 50,089 |
def dilation(image, selem, out=None, shift_x=False, shift_y=False):
"""Return greyscale morphological dilation of an image.
Morphological dilation sets a pixel at (i,j) to the maximum over all pixels
in the neighborhood centered at (i,j). Dilation enlarges bright regions
and shrinks dark regions.
... | 50,090 |
def randn(*args):
"""Returns samples from a normal distribution.
Uses `tf.random_normal`.
Args:
*args: The shape of the output array.
Returns:
An ndarray with shape `args` and dtype `float64`.
"""
# TODO(wangpeng): Use new stateful RNG
if utils.isscalar(args):
args = (args,)
return utils.... | 50,091 |
def circuit19(params, wires):
"""Circuit template #19 in 1905.10876
Args:
params (array): An array of shapes (3N, ).
wires (Iterable): Wires that the template acts on.
"""
# Input Checks
wires, size = Wires(wires), len(wires)
check_shape(params, target_shape=(3 * size,),
... | 50,092 |
def nice_layer_name(weight_key):
"""Takes a tuple like ('weights', 2) and returns a nice string like "2nd layer weights"
for use in plots and legends."""
return "Layer {num} {name}".format(num=weight_key[1] + 1, name=weight_key[0]) | 50,093 |
def categories(request, structure_slug, structure):
"""
Retrieves structure categories list
:type structure_slug: String
:type structure: OrganizationalStructure (from @is_manager)
:param structure_slug: structure slug
:param structure: structure object (from @is_manager)
:return: render
... | 50,094 |
def test_dlmmp(lmax=3, nbeta=10):
"""
Compare our expression to the one in `sympy` up to degree `lmax`
for a few different values of `beta`.
"""
np.random.seed(0)
for n in tqdm(range(nbeta), disable=bool(int(os.getenv("NOTQDM", "0")))):
beta = np.random.uniform(-np.pi, np.pi)
for... | 50,095 |
def checaDiagonal3D4(
tabuleiro
):
"""
Checa se todos os elementos da diagonal 3D 4 (decrescente|crescente)
são iguais a 'X' ou 'O', retornando o caractere em caso
afirmativo e retornando '' caso contrário
"""
if tabuleiro[0][3][0] == 'X' and tabuleiro[1][2][1] == 'X' and ... | 50,096 |
def setup_environment():
"""Setup the pygame environment"""
logging.debug('setup pygame environment')
os.environ['SDL_VIDEODRIVER'] = 'dummy'
pygame.init()
pygame.display.init()
pygame.display.set_mode((1, 1))
signal.signal(signal.SIGINT, signal_handler) | 50,097 |
def parse_contigs(locations, gdir, odir):
"""
Parse the contigs file and print non-prophage regions
:param locations: the locations hash from the phispy directory
:param gdir: the genome directory that contains the contigs file
:param odir: the output directory
:return: None
"""
p = re... | 50,098 |
def do_quantize_training_on_graphdef(input_graph, num_bits):
"""A general quantization scheme is being developed in `tf.contrib.quantize`.
Consider using that instead, though since it is in the tf.contrib namespace,
it is not subject to backward compatibility guarantees.
Args:
input_graph: A `GraphDef`.
... | 50,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.