content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def analyze_images(url_or_path: str, json_keys: Optional[Sequence[str]] = None,
account: Optional[str] = None,
container: Optional[str] = None,
sas_token: Optional[str] = None) -> None:
"""
Args:
url_or_path: str, URL or local path to a file conta... | 34,000 |
def permutacion_matriz(U, fila_i, idx_max, verbose=False, P=None, r=None):
"""Efectua una permutación por filas de una matriz
Args:
U (matriz): MAtriz a permutar
fila_i (int): indice de fila origen
idx_max (int): indice de fila a la que permutar
verbose (bool, optional): verbose... | 34,001 |
def admin_toggle_access(self, *, sender: AdminDashboardUser, task_data: ToggleAccessRequest):
"""
Toggle a user's access to MarinTrace in Auth0 and Neo4j
:param sender: the user that initiated the task
:param task_data: the user identifier to toggle
"""
logger.info(f"Setting block={task_data.blo... | 34,002 |
def get_compliance_by_rules(scan_id):
"""
Lists compliance results by rule for a scan.
"""
items = []
offset = 0
while True:
params = {'offset': offset}
response = get('scans/%s/compliance_by_rules' % scan_id, params)
items.extend(response['items'])
if not respons... | 34,003 |
def tree_command(ctx, source):
"""View the AST for the given source file."""
loader = ctx.obj['loader']
cf = loader[source]
with io.StringIO() as temp:
cf.node.pprint(file=temp)
click.echo_via_pager(temp.getvalue()) | 34,004 |
def QuadRemeshBrep1(brep, parameters, guideCurves, multiple=False):
"""
Create Quad Remesh from a Brep
Args:
brep (Brep): Set Brep Face Mode by setting QuadRemeshParameters.PreserveMeshArrayEdgesMode
guideCurves (IEnumerable<Curve>): A curve array used to influence mesh face layout
... | 34,005 |
def tags2turbo(lon, lat, dist, bdim=155, timeout=60, pretty_print=False, maxsize=None, tags=[]):
""" """
gtypes = ('node', 'way', 'relation',)
turbo = Turbo()
qconditions = [{
"query": filter2query(tags),
"distance": dist,
"gtypes": gtypes, # Optional. Possible values:
# ... | 34,006 |
async def get_people(from_number: int = None, up_to_number: int = None):
"""
Endpoint to get all people from-to given number
:return: list of people from-to numbers
"""
return _people[from_number:up_to_number] | 34,007 |
def stacked_bar(data, series_labels=None, category_labels=None,
show_values=False, value_format="{}", y_label=None,
grid=True, reverse=False, y_limit=None, size_plot=None, use_dataframe=False, throw_zeros=False,dict_colors={}):
"""Plots a stacked bar chart with the data and labels pr... | 34,008 |
def process_results(economy):
"""
Combine OSeMOSYS solution files and write as the result as an Excel file where each result parameter is a tab in the Excel file.
"""
click.echo(click.style('\n-- Preparing results...',fg='cyan'))
tmp_directory = 'tmp/{}'.format(economy)
parent_directory = "./res... | 34,009 |
def window(x, y, width, overlap=0., x_0=None, expansion=None, cap_left=True,
cap_right=True, ret_x=True):
"""Break arrays x and y into slices.
Parameters
----------
x : array_like
Monotonically increasing numbers. If x is not monotonically increasing
then it will be flipped, ... | 34,010 |
def mark_property_purchased(request):
"""
Api to mark a property as purchased by the buyer without page reload using vue or htmx
"""
data = json.loads(request.body)
property = data['property_id']
if not property.property_status == Property.SOLD and property.property_sold:
property.update... | 34,011 |
def save_app(name, executable, description='', envscript='', preprocess='', postprocess=''):
"""
Adds a new app with the given properties to the balsam database.
Parameters
----------
name: str, name of the app
executable: str, path to the executable
description: str, info about the app
... | 34,012 |
def create_checkpoint(weights_and_biases, global_step, model_dir):
"""Create checkpoint file with provided model weights.
Args:
weights_and_biases: Iterable of tuples of weight and bias values.
global_step: Initial global step to save in checkpoint.
model_dir: Directory into which checkpoint is saved.
... | 34,013 |
def file_exists(file: str) -> bool:
"""Accepts path/file or file and tests if it exists (as a file)."""
if os.path.exists(file):
if os.path.isfile(file):
return True
return False | 34,014 |
def test_issue588(en_vocab):
"""Test if empty specs still cause an error when adding patterns"""
matcher = Matcher(en_vocab)
with pytest.raises(ValueError):
matcher.add("TEST", [[]]) | 34,015 |
def argmax_unique(arr, axis):
"""Return a mask so that we can exclude the nonunique maximums, i.e. the nodes that aren't completely resolved"""
arrm = np.argmax(arr, axis)
arrs = np.sum(arr, axis)
nonunique_mask = np.ma.make_mask((arrs == 1) is False)
uni_argmax = np.ma.masked_array(arrm, mask=... | 34,016 |
def main():
"""putting the different functions together"""
while True:
url_list = input("Paste some RSS feed URLs (Separate them using a space or comma): \n\n")
urls = get_url(url_list)
if urls:
for url in urls:
fetch_xml(url)
root = parse_xml(... | 34,017 |
def mod_builtins():
"""
Replaces all builtins by versions wrapped using
DerivableException.wrap.
It is not recommended to do this, and there is pretty much no
benefit.
"""
g = globals()
for builtin in dir(builtins):
if builtin.endswith('Error') or builtin.endswith('Exception'):
... | 34,018 |
def get_json(response: func.HttpResponse) -> Dict:
"""Get JSON from an HttpResponse."""
return json.loads(response.get_body().decode("utf-8")) | 34,019 |
def _float_feature(value):
"""Returns a float_list from a float / double."""
if isinstance(value, list):
return tf.train.Feature(float_list=tf.train.FloatList(value=value))
return tf.train.Feature(float_list=tf.train.FloatList(value=[value])) | 34,020 |
def sendVillasNodeOutput(message, output_mapping_vector, powerflow_results, state_estimation_results, scenario_flag):
"""
to create the payload according to "villas_node_output.json"
@param message: received message from the server (json.loads(msg.payload)[0])
@param output_mapping_vector: according to... | 34,021 |
def find_org_rooms(dbs, user_id, meeting_date):
"""
获取可分配的机构
:param dbs:
:param user_id:
:param meeting_date:
:return:
"""
orgs = dbs.query(SysOrg.id, SysOrg.org_name, SysOrg.parent_id)\
.outerjoin(SysUserOrg, (SysUserOrg.org_id == SysOrg.id))\
.filter(SysUserOrg.user_id ... | 34,022 |
def config_openapi(app: FastAPI, settings: ApiSettings):
"""Config openapi."""
def custom_openapi():
"""Config openapi."""
if app.openapi_schema:
return app.openapi_schema
openapi_schema = get_openapi(
title="Arturo STAC API", version="0.1", routes=app.routes
... | 34,023 |
def test_sorter_factory_returns_bubble_sorter_when_requested():
"""Test sorter factory returns bubble sorter when requested."""
sorter_name = SortType.BUBBLE.value
received_sorter = sorter_factory(sorter_name)
assert isinstance(received_sorter, BubbleSorter) | 34,024 |
def update_anime_info(name, new):
"""
Update information of anime with a dict contains new information
params:
name Name of anime you want to update
new A dict contains new infomation, the value whose key name starts
with new_ will replaces the corresponding item
... | 34,025 |
def twelve_tone_matrix(
row: Sequence,
) -> DataFrame:
""" Returns a twelve-tone matrix in the form of a Pandas DataFrame.
"""
inverted_row = inversion(row)
inv_mat = transposition(inverted_row, row[0]-inverted_row[0])
new = [row]
for i in range(1, 12):
k = transposition(row, (inv_... | 34,026 |
async def upstream_http_exception_handler(request, exc: HTTPError):
"""Handle http exceptions from upstream server"""
logger.warning(f"Upstream HTTP error [{request.query_params['url']}]: {repr(exc)}")
# Convert to FastApi exception
exc = HTTPException(502, f"Upstream server returned: [{exc.status}] {ex... | 34,027 |
def extract_latest_checkpoint_and_epoch(available_files: List[Path]) -> PathAndEpoch:
"""
Checkpoints are saved as recovery_epoch={epoch}.ckpt, find the latest ckpt and epoch number.
:param available_files: all available checkpoints
:return: path the checkpoint from latest epoch and epoch number
""... | 34,028 |
def bark_filter_banks(nfilts=20,
nfft=512,
fs=16000,
low_freq=0,
high_freq=None,
scale="constant"):
"""
Compute Bark-filterbanks. The filters are stored in the rows, the columns
correspond to fft bi... | 34,029 |
def test_appgroup():
"""Test of with_appcontext."""
@click.group(cls=AppGroup)
def cli():
pass
@cli.command(with_appcontext=True)
def test():
click.echo(current_app.name)
@cli.group()
def subgroup():
pass
@subgroup.command(with_appcontext=True)
def test2():... | 34,030 |
def auth_check_response_fixture():
"""Define a fixture to return a successful authorization check."""
return json.loads(load_fixture("auth_check_response.json")) | 34,031 |
def cancel_session(session_id):
"""
Cancel all tasks within a session
Args:
string: session_id
Returns:
dict: results
"""
lambda_response = {}
all_cancelled_tasks = []
for state in task_states_to_cancel:
res = cancel_tasks_by_status(session_id, state)
... | 34,032 |
def tensor2tensor(tensor):
"""Convert a TensorFLow tensor to PyTorch Tensor,
or vice versa
"""
... | 34,033 |
def valid_capture_area(top_left, bottom_right):
"""Check the capture area extents for sanity.
"""
tl_x = top_left['x']
tl_y = top_left['y']
br_x = bottom_right['x']
br_y = bottom_right['y']
if (br_x <= tl_x) or (br_y <= tl_y):
print('The capture area ({},{}) ({},{}) '
... | 34,034 |
def get_cli_args():
"""Gets, parses, and returns CLI arguments"""
parser = ArgumentParser(description='Check modules formatting')
parser.add_argument('filepath', help='path to a file to check')
parser.add_argument('-n', '--fqcn',
dest='fqcn',
metavar='FQ... | 34,035 |
def __virtual__():
"""
Determine whether or not to load this module
"""
return __virtualname__ | 34,036 |
def load_glove_embeddings():
"""
Load the glove embeddings into a array and a dictionary with words as
keys and their associated index as the value. Assumes the glove
embeddings are located in the same directory and named "glove.6B.50d.txt"
RETURN: embeddings: the array containing word vectors
... | 34,037 |
def _f2_rsub_ ( self , other ) :
"""Operator for ``2D-function - other''"""
return _f2_rop_ ( self , other , Ostap.MoreRooFit.Subtraction , "Subtract_" ) | 34,038 |
def attenuate(source, factor=0.01, duration=1.0, srate=None):
"""Exponential attenuation towards target value within 'factor' in time 'duration' for constant signals."""
if srate is None:
srate = get_srate()
return onepole(source, 1.0, -factor ** (srate / duration), 1.0 - factor ** (srate / duration... | 34,039 |
def test_nonindexed_dimensions_restored():
"""When the selection removes a dimension, xarray.expand_dims does not expand the non-indexed
dimensions that were removed. For example, if one selects only a single zplane, it reduce the z
physical coordinate to a coordinate scalar, and not an array of size 1. T... | 34,040 |
def get_parser(name):
""" make default formatted parser """
parser = argparse.ArgumentParser(
name, formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
# print default value always
parser.add_argument = partial(parser.add_argument, help=" ")
return parser | 34,041 |
def IsMultiPanel(hcuts, vcuts) -> bool:
"""
Check if the image is multi-panel or not.
Could have more logic.
"""
return bool(hcuts or vcuts) | 34,042 |
def is_subject_mutable(context, subject):
"""Return True if the subject is mutable in this context."""
if context.is_admin:
return True
if subject.owner is None or context.owner is None:
return False
return subject.owner == context.owner | 34,043 |
def time_filter(df, start_date, end_date):
"""Remove times that are not within the start/end bounds."""
if start_date:
datetime_start = datetime.strptime(start_date, '%Y-%m-%d')
start_selection = df.index >= datetime_start
if end_date:
datetime_end = datetime.strptime(end_date, '%Y... | 34,044 |
def update_post(post_dict):
""" 更新文章 """
category = post_dict.get('category')
category_query_result = Category.query.filter_by(name=category).first()
if category_query_result is None:
category_item = Category(name=category)
db.session.add(category_item)
db.session.commit()
a... | 34,045 |
def notifications():
"""
Fetches the notifications events that occurred between the given block numbers
URL Params:
min_block_number: (int) The start block number for querying for notifications
max_block_number?: (int) The end block number for querying for notifications
track_id?: (... | 34,046 |
def collapse_umi(cells):
"""
Input set of genotypes for each read
Return list with one entry for each UMI, per cell barcode
"""
collapsed_data = {}
for cell_barcode, umi_set in cells.items():
for _, genotypes in umi_set.items():
if len(set(genotypes)) > 1:
pas... | 34,047 |
def get_corrected_PRES(PRES: np.ndarray, ele_gap: float, TMP: np.ndarray) -> np.ndarray:
"""気圧の標高補正
Args:
PRES (np.ndarray): 補正前の気圧 [hPa]
ele_gap (float): 標高差 [m]
TMP (np.ndarray): 気温 [℃]
Returns:
np.ndarray: 標高補正後の気圧 [hPa]
Notes:
気温減率の平均値を0.0065℃/mとする。
... | 34,048 |
def mishra_bird(x, *args):
"""Mishra's Bird constrained function with 2 parameters.
To be used in the constrained optimization examples.
When subject to:
(x[0] + 5) ** 2 + (x[1] + 5) ** 2 < 25
the global minimum is at f(-3.1302, -1.5821) = -106.7645
Bounds: -10 <= x[0] <= 0
-6.... | 34,049 |
def find_target_migration_file(database=DEFAULT_DB_ALIAS, changelog_file=None):
"""Finds best matching target migration file"""
if not database:
database = DEFAULT_DB_ALIAS
if not changelog_file:
changelog_file = get_changelog_file_for_database(database)
try:
doc = minidom.par... | 34,050 |
def encode_message(ctl, addr, src_id, msg_code, data=""):
"""Encode a message for the PIM, assumes data formatted"""
ctl = create_control_word(addr.is_link) if ctl == -1 else ctl
length = 7 + len(data)
ctl = ctl | (length << 8)
msg = bytearray(length)
msg[0:2] = ctl.to_bytes(2, byteorder="big")
... | 34,051 |
def rule_16(l, r):
"""
Rule for "vyaṁjana sandhi - ghośī karaṇaya"
:return:
"""
l_suffix = utils.endswith(l, letters.AGOSHA_LETTERS)
r_prefix = utils.startswith(r, letters.GOSHA_LETTERS)
if l_suffix is not None and r_prefix is not None:
if r_prefix in letters.VOWELS:
ret... | 34,052 |
def look(x: Any, shrink_right: int = 1) -> None:
"""Dumps any object to stdout using the technique in `expose()`.
The parameter `shrink_right` is used to set narrowing of
indentation. (Use `0` to turn off).
"""
print(pformat(expose(x, shrink_right)).replace(' ', shrink_right * ' ')) | 34,053 |
def is_vertex_cover(G, vertex_cover):
"""Determines whether the given set of vertices is a vertex cover of graph G.
A vertex cover is a set of vertices such that each edge of the graph
is incident with at least one vertex in the set.
Parameters
----------
G : NetworkX graph
The graph on... | 34,054 |
def datetimeformat(value, formatstring='%Y-%m-%d %H:%M', nonchar=''):
"""Formates a datetime.
Tries to convert the given ``value`` to a ``datetime`` object and then formats
it according to ``formatstring``::
{{ datetime.now()|datetimeformat }}
{{ "20171224T235959"|datetimeformat('%H:%M') }... | 34,055 |
def get_interface_for_name(protocols, target_interface_name):
# type: (Iterable[Protocol], str) -> Optional[Interface]
"""Given a name string, gets the interface that has that name, or None."""
for protocol in protocols:
for interface in protocol.interfaces:
if interface.name == target_i... | 34,056 |
def __get_out_file(in_file, out_dir):
"""
Get the path of the output file.
Parameters
----------
in_file: str
Path to input file.
out_dir: str
Path to output directory.
Returns
-------
file_no_ext: str
The file name without extension.
out_dir: str
... | 34,057 |
def extract_validation_set(x: ndarray, y: ndarray, size=6000):
"""Will extract a validation set of "size" from given x,y pair
Parameters:
x (ndarray): numpy array
y (ndarray): numpy array
size (int): Size of validation set. Must be smaller than examples count
in x, y and multiple of... | 34,058 |
def check_rpc_reply(response):
"""Checks RPC Reply for string. Notifies user config was saved"""
if response.rfind("Save running-config successful") != -1:
print("\nConfiguration Saved!")
else:
print("\nConfiguration Not Saved!") | 34,059 |
def send_update(peer_ip, attr, nlri, withdraw):
"""
send update message
:param peer_ip: peer ip address
:return:
"""
if cfg.CONF.bgp.running_config['factory'].fsm.protocol.send_update({
'attr': attr, 'nlri': nlri, 'withdraw': withdraw}):
return {
'status': True
... | 34,060 |
def test_struct2vector(source):
"""
(struct posn (x y) #:transparent)
(struct 3d-posn posn ([z #:mutable]))
(let* ([d (3d-posn 1 2 3)]
[v (struct->vector d)]
[v_name (vector-ref v 0)]
[v0 (vector-ref v 1)]
[v2 (vector-ref v 3)])
(and (eq? v_name 'struct:3... | 34,061 |
def generate_basic_blame_experiment_actions(
project: Project,
bc_file_extensions: tp.Optional[tp.List[BCFileExtensions]] = None,
extraction_error_handler: tp.Optional[PEErrorHandler] = None
) -> tp.List[actions.Step]:
"""
Generate the basic actions for a blame experiment.
- handle caching of B... | 34,062 |
def test_validate_by():
"""Test ``modin.core.dataframe.algebra.default2pandas.groupby.GroupBy.validate_by``."""
def compare(obj1, obj2):
assert type(obj1) == type(
obj2
), f"Both objects must be instances of the same type: {type(obj1)} != {type(obj2)}."
if isinstance(obj1, l... | 34,063 |
def is_json_encodable(t: Any) -> bool:
""" Checks whether a type is json encodable. """
# pylint:disable=invalid-name,too-many-return-statements,too-many-branches
if not is_typecheckable(t):
return False
if t in JSON_BASE_TYPES:
return True
if t in (None, type(None)):
return ... | 34,064 |
def test_raise_on_vector_dimension_mismatch(
L: np.ndarray, method_kwargs: Dict[str, Any]
):
"""Tests whether a :class:`ValueError` is raised if the shape of the vector is not
compatible with the shape of the Cholesky factor"""
N = L.shape[0]
# Generate arbitrary v with incompatible length
v_le... | 34,065 |
def request_parse_platform_id(validated_request):
"""Parses the PlatformID from a provided visibility API request.
Args:
validated_request (obj:Request): A Flask request object that has been generated for a
visibility/opportunity endpoint.
Requires:
... | 34,066 |
def view_runner(step, args):
"""
input:
depthfile : path (.depth file)
nodes : text list (a list of node IDs)
mode : text (currently view or view-all)
output:
output_dir : just a link to the output directory
"""
f1 = args["depthfile"]
mode = args["mode"]
node... | 34,067 |
def dataGenerator(data_generator_info, data_dir, target_size, color_mode, folder, batch_size, seed,
sample_weight_flag=False, is_sample_weight=False, sample_weight_dict={}, sample_rescale=1,
is_test_data=False):
"""Generate an image."""
arg_dict = dict(shuffle=not is_t... | 34,068 |
def crear_comentario_submeta(request, pk):
""" Crea y agrega un comentario a una meta identificada por su id """
# meta = get_object_or_404(Meta, pk=pk)
meta = Submeta.objects.get(pk=pk)
# si ya se creo se guarda el comentario y se redirecciona el navegador a
# la meta
if request.method == "POST... | 34,069 |
def printAnswer(part: int, value: any) -> None:
""" Print the solution to Part `part` of the puzzle """
print(f"{Fore.GREEN}Answer (Part {part}):{Style.RESET_ALL} {value}") | 34,070 |
def execute_op(op: AsyncMigrationOperation, query_id: str, rollback: bool = False):
"""
sync execute the migration against the analytics db (ClickHouse) and then
run the side effect if it is defined
"""
sql = op.rollback if rollback else op.sql
if op.database == AnalyticsDBMS.CLICKHOUSE:
... | 34,071 |
def do_two_stage(data, options):
"""
Run the prime-based approach.
"""
ruler = TwoStageApproach(data, options)
covers = ruler.compute()
# save result to a CSV file
if options.rdump:
data.dump_result(primes, covers) | 34,072 |
def load_mask_from_shapefile(filename, shape, transform):
"""Load a mask from a shapefile."""
multipolygon, _ = load_shapefile2multipolygon(filename)
mask = multipolygon2mask(multipolygon, shape, transform)
return mask | 34,073 |
def _spectra_resample(spectra, wvl_orig, wvl_target):
"""
:param spectra:
:param wvl_orig:
:param wvl_target:
:param k:
:return:
"""
idx_finite = np.isfinite(spectra)
min_wvl_s = np.nanmin(wvl_orig[idx_finite])
max_wvl_s = np.nanmax(wvl_orig[idx_finite])
idx_target = np.logi... | 34,074 |
def test_standard_surface():
"""Test to read a standard surface file."""
def dtparse(string):
return datetime.strptime(string, '%y%m%d/%H%M')
skip = ['text']
gsf = GempakSurface(get_test_data('gem_std.sfc'))
gstns = gsf.sfjson()
gempak = pd.read_csv(get_test_data('gem_std.csv'),
... | 34,075 |
def bootstrap_comparison(
molecule: str,
prediction_file: str,
datatype: str,
n_samples=1,
n_bootstrap=1000,
**kwargs,
):
"""Perform a bootstrap analysis on the experimental and the computed titration curve.
Parameters
----------
molecule - SAMPL6 identifier of the molecule.... | 34,076 |
def calc_mu(Rs):
""" Calculates mu for use in LinKK """
neg_sum = sum(abs(x) for x in Rs if x < 0)
pos_sum = sum(abs(x) for x in Rs if x >= 0)
return 1 - neg_sum/pos_sum | 34,077 |
def test_tensorstore_clim_popup():
"""Regression to test, makes sure it works with tensorstore dtype"""
ts = pytest.importorskip('tensorstore')
layer = Image(ts.array(np.random.rand(20, 20)))
QContrastLimitsPopup(layer) | 34,078 |
def computeAnomaly(data):
"""
Remove the seasonality
"""
period = _get_period(data)
meanclim = computeMeanClimatology(data)
anom = data.groupby(f'time.{period}') - meanclim
return anom | 34,079 |
def product(*args):
"""Calculate product of args.
@param args: list of floats to multiply
@type args: list of float
@return: product of args
@rtype: float
"""
r = args[0]
for x in args[1:]:
r *= x
return r | 34,080 |
def unpack_into_tensorarray(value, axis, size=None):
"""
unpacks a given tensor along a given axis into a TensorArray
Parameters:
----------
value: Tensor
the tensor to be unpacked
axis: int
the axis to unpack the tensor along
size: int
the size of the array to be us... | 34,081 |
def create_spider_(spider_name):
"""
Create a Spider for project ,must create project before
"""
CommandSpider().run(spider_name) | 34,082 |
def get_error_page(status_code, message):
"""
获取错误页面
:param status_code:
:param message:
:return:
"""
context = {
'site_web': settings.SITE_TITLE,
'site_url': reverse(settings.SITE_NAME),
'status_code': status_code,
'message': message,
'date': datetime... | 34,083 |
def fits_difference(*args, **keys):
"""Difference two FITS files with parameters specified as Differencer class."""
differ = FitsDifferencer(*args, **keys)
return differ.difference() | 34,084 |
def esta_balanceada(expressao):
"""
Função que calcula se expressão possui parenteses, colchetes e chaves balanceados
O Aluno deverá informar a complexidade de tempo e espaço da função
Deverá ser usada como estrutura de dados apenas a pilha feita na aula anterior
:param expressao: string com express... | 34,085 |
def create_doc(im_src, tag, coords, fea_arr, fea_bin_arr):
"""
Create elasticsearch doc
Params:
im_src: image file name
tag: tag or class for image
coords: list of boxes corresponding to a tag
fea_arr: list of ImFea objects
fea_bin_arr: list of ImFeaBin objects
"... | 34,086 |
def test_uget_package_installed(host):
"""
Tests if uget is installed.
"""
assert host.package(PACKAGE).is_installed | 34,087 |
def scaled_mouse_pos(mouse): # pragma: no cover
"""
Renvoie la position de la souris mise à l'échelle de l'image.
Parameters
----------
mouse : int * int
La position réelle de la souris
Returns
-------
int * int
La position mise à l'échelle
"""
# Récupération d... | 34,088 |
def _send_auto_response_mail(addressee, passwd: bytearray, addressee_subject) -> None:
"""
Utility method, sends auto-response mail to addressee via SMTP
:param addressee: mail address where the mail is sent to
:param passwd: the mail server password (as bytearray)
:param addressee_subject: the sub... | 34,089 |
def is_valid_zcs_image_id(zcs_image_id):
"""
Validates Zadara Container Services (ZCS) image IDs, also known as the ZCS
image "name". A valid ZCS image name should look like: img-00000001 - It
should always start with "img-" and end with 8 hexadecimal characters in
lower case.
:type zcs_image_... | 34,090 |
def get_topology2(gid: int, cfg: Config):
"""
Create a uniformly and randomly sampled genome of fixed topology:
Sigmoid with bias 1.5 --> Actuation default of 95,3%
(key=0, bias=1.5) (key=1, bias=?)
____ / /
/ /
GRU /
... | 34,091 |
def resolve_implicits(implies, opts):
# type: (Dict[str, List[str]], List[str]) -> Set[str]
"""Adds implied logging options recursively so that specifying e.g.
--debug=popenio results in --debug=popenio,popen.
"""
optset = set(opts)
last_num_opts = None
num_opts = len(optset)
while last_... | 34,092 |
def symmetric_key(kms_client):
"""
Create a temporary symmetric key for use in tests that require one.
The key is marked for deletion once the tests have finished.
We don't actually test the creation/deletion process here; it's assumed to work.
:param kms_client:
:return:
"""
code, conte... | 34,093 |
def dry_press(
H,
Pv,
alt_setting=P0,
alt_units=default_alt_units,
press_units=default_press_units,
):
"""
Returns dry air pressure, i.e. the total air pressure, less the water
vapour pressure.
"""
HP = pressure_alt(H, alt_setting, alt_units=alt_units)
P = alt2press(HP, ... | 34,094 |
def InvocationAddCallerAuthid(builder, callerAuthid):
"""This method is deprecated. Please switch to AddCallerAuthid."""
return AddCallerAuthid(builder, callerAuthid) | 34,095 |
def max_pool1d(input, ksize, strides, padding, data_format="NWC", name=None):
"""Performs the max pooling on the input.
Note internally this op reshapes and uses the underlying 2d operation.
Args:
input: A 3-D `Tensor` of the format specified by `data_format`.
ksize: An int or list of `ints` that has length `1` ... | 34,096 |
def DeepLabV3Plus(shape):
""" Inputs """
inputs = Input(shape)
""" Pre-trained ResNet50 """
base_model = ResNet50(weights='imagenet', include_top=False, input_tensor=inputs)
""" Pre-trained ResNet50 Output """
image_features = base_model.get_layer('conv4_block6_out').output
x_a = ASPP(imag... | 34,097 |
def test_get_search_permutations(search_config):
"""Test for the correct construction of GridSearch hyperparamter permutations."""
sets = [[0.0001, 0.01], [32, 512], [1e-05, 0.001]]
assert GridSearch.get_search_permutations(sets) == [
(0.0001, 32, 1e-05),
(0.0001, 32, 0.001),
(0.000... | 34,098 |
def get_parameters():
"""Parse the supplied command line arguments.
Returns:
args: The parsed and validated command line arguments
"""
parser = argparse.ArgumentParser(
description="Start up and shut down ASGs on demand"
)
# Parse command line inputs and set defaults
parse... | 34,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.