text string | label_name string | labels int64 |
|---|---|---|
rgs)
model.apply(weight_init)
model.to(device)
if args.optimizer == 'SGD':
optimizer = optim.SGD(model.parameters(), lr=args.learning_rate, momentum=0.9, weight_decay=1e-4)
scheduler = optim.lr_scheduler.StepLR(optimizer, args.lr_decay_step, args.lr_decay_ratio)
elif args.optimizer == ... | Python | 1 |
# Alice and Bob want to exchange messages over an insecure channel. They decide to do so
# using the One-Time Pad (OTP) encryption algorithm. However, they do not share a secret key,
# so they must first exchange it. Mallory is listening.
#
# Allow Mallory to:
# 1. Eavesdrop on the communication between Alice and Bob.
... | Python | 1 |
"""Usage utilities."""
from typing import Callable
def _dict_int_op(
left: dict,
right: dict,
op: Callable[[int, int], int],
*,
default: int = 0,
depth: int = 0,
max_depth: int = 100,
) -> dict:
if depth >= max_depth:
msg = f"{max_depth=} exceeded, unable to combine dicts."
... | Python | 1 |
from datetime import timedelta
from pydantic import BaseModel
class TimeDeltaInfo(BaseModel):
days: int
hours: int
minutes: int
def to_timedelta(self) -> timedelta:
return timedelta(days=self.days, hours=self.hours, minutes=self.minutes)
| Python | 1 |
if user.get('email'):
message += f"📧 *Email:* {escape_markdown(str(user['email']))}\n"
if user.get('hwidDeviceLimit'):
message += f"📱 *Лимит устройств:* {user['hwidDeviceLimit']}\n"
message += f"\n⏱️ *Создан:* {user['createdAt'][:10]}\n"
mes... | Python | 1 |
.bits & !(0x3f << 8)) | ((value as u32 & 0x3f) << 8);
self.w
}
}
#[doc = "Field `FILTSCL` reader - Glitch Filter SCL"]
pub struct FILTSCL_R(crate::FieldReader<u8, u8>);
impl FILTSCL_R {
#[inline(always)]
pub(crate) fn new(bits: u8) -> Self {
FILTSCL_R(crate::FieldReader::new(bits))
}
}
i... | Rust | 0 |
Table<'a> {
pub sfnt_version: u32,
pub search_range: u16,
pub entry_selector: u16,
pub range_shift: u16,
pub table_records: ReadArray<'a, TableRecord>,
}
pub struct OffsetTableFontProvider<'a> {
scope: ReadScope<'a>,
offset_table: Cow<'a, OffsetTable<'a>>,
}
/// An entry in the Offset Tabl... | Rust | 0 |
f {
UnaryOp::Pos => "unary `+` operator",
UnaryOp::Neg => "unary `-` operator",
UnaryOp::BitNot => "`~` operator",
UnaryOp::LogicNot => "`!` operator",
UnaryOp::PreInc => "`++` prefix operator",
UnaryOp::PreDec => "`--` prefix operator",
... | Rust | 0 |
_player if is_valid else current_player
else:
# 记录未质疑的情况
self.game_record.record_challenge(
was_challenged=False,
reason=challenge_result["challenge_reason"],
result=None,
challenge_thinking=reasoning
)
... | Python | 1 |
bind_mount(&Path::new("/sys"), &Path::new("/vagga/root/sys")));
try!(mount_proc(&Path::new("/vagga/root/proc")));
try!(bind_mount(&Path::new("/work"), &Path::new("/vagga/root/work")));
return Ok(());
}
pub fn mount_dev(dev_dir: &Path) -> Result<(), String> {
try!(bind_mount(&Path::new("/dev"), &dev_dir... | Rust | 0 |
Model", property="author"))
self.db.create_index(gq.MemgraphIndex("Model", property="merge_method"))
self.db.create_index(gq.MemgraphIndex("Model", property="architecture"))
self.db.create_index(gq.MemgraphIndex("Model", property="private"))
self.db.create_index(gq.MemgraphIndex("Model",... | Python | 1 |
class Solution:
def splitArraySameAverage(self, nums: List[int]) -> bool:
n = len(nums)
summ = sum(nums)
if not any(i * summ % n == 0 for i in range(1, n // 2 + 1)):
return False
sums = [set() for _ in range(n // 2 + 1)]
sums[0].add(0)
for num in nums:
for i in range(n // 2, 0, -... | Python | 1 |
eq
).\
must_next()
pkts.filter_wpan_src64(ROUTER_1).\
filter_wpan_dst64(ROUTER_2).\
filter_mle_cmd(MLE_CHILD_ID_RESPONSE).\
filter(lambda p: {
ADDRESS16_TLV,
LEADER_DATA_TLV,
... | Python | 1 |
irectory.")
print()
"""
############ Password generator section #######################################
def genpassx():
print("\033[1;92m\n \033[1;91m[*]\033[1;97m Password generator launching...")
sleep(0.7)
MAX_LEN = int(input(' \033[1;91m[?]\033[1;97m Password length: '))
cot = int(input(' \03... | Python | 1 |
enderer, call_axes_locator=True):
bb0 = super(Axes, self).get_tightbbox(renderer, call_axes_locator)
if not self._axisline_on:
return bb0
bb = [bb0]
for axisline in list(six.itervalues(self._axislines)):
if not axisline.get_visible():
continue
... | Python | 1 |
ogic, similar to JavaScript's if-else.
# 7. Script Execution Entry Point:
# Python's 'if __name__ == "__main__":' is a unique way to define the starting point of a script.
# 8. Importing Modules:
# Python's 'import' statement is used to include modules, somewhat similar to JavaScript's import, but with different synt... | Python | 1 |
#!/usr/bin/env python3
"""Takeoff-hover-land for one CF. Useful to validate hardware config."""
from sdf import box, sphere
import functions.pawn as ex
from cf_show_node import SwarmControllerNode
RATE = 10
TAKEOFF_DURATION = 2.5
HOVER_DURATION = 5.0
def main():
# cost = ex.get_pawn()
cost = [sphere(0.... | Python | 1 |
.upgrade().unwrap();
app.log.append("Disconnecting...");
}
self.set_disconnected();
{
let app = self.app.lock().unwrap();
let app = app.upgrade().unwrap();
let mut openvpn = app.openvpn.borrow_mut();
if let Some(ref srv) = openvpn.... | Rust | 0 |
from glob import glob
import torchaudio
import os
from torchaudio.functional import highpass_biquad
from pathlib import Path
import torch
from scipy.signal import resample
from tqdm import tqdm
import math
def preprocess_segments(path, out, sr_to=48000):
wav, sr = torchaudio.load(path)
# Stereo to mono
if ... | Python | 1 |
# coding: utf-8
"""
Utilities for dealing with text encodings
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-2012 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part... | Python | 1 |
message, tag = "5")]
Bytes(super::BytesConstraintV2),
}
}
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct IntConstraintV2 {
#[prost(oneof = "int_constraint_v2::Constraint", tags = "1, 2, 3, 4, 5, 6, 7")]
pub constraint: ::core::option::Option<int_constraint_v2::Constraint>,
}
/// Nested mes... | Rust | 0 |
accessor: an alias for `Reg<ALI_REQ0_SPEC>`"]
pub type ALI_REQ0 = crate::Reg<ali_req0::ALI_REQ0_SPEC>;
#[doc = "Analog Input Request Register 0 (P0/P1/P2/P3)"]
pub mod ali_req0;
#[doc = "ALI_REQ1 register accessor: an alias for `Reg<ALI_REQ1_SPEC>`"]
pub type ALI_REQ1 = crate::Reg<ali_req1::ALI_REQ1_SPEC>;
#[doc = "An... | Rust | 0 |
# Simple Number Triangle
rows = 6
for i in range (1, rows):
print(str(i) * i)
# Output:
# 1
# 22
# 333
# 4444
# 55555 | Python | 1 |
tr peering_mode: Type of Network peeringMode Default value: "PRIVATE_SERVICE_ACCESS" Possible values: ["PRIVATE_SERVICE_ACCESS"]
"""
pulumi.set(__self__, "network", network)
pulumi.set(__self__, "peering_mode", peering_mode)
@_builtins.property
@pulumi.getter
def network(self) -> _b... | Python | 1 |
org/docs/reference/functions#trace-str)
#[link_name = "traceUtf8"]
pub fn trace(text: *const u8, len: usize);
}
}
/// Debug prints text to the terminal.
///
/// [WASM-4 Docs](https://wasm4.org/docs/reference/functions#trace-str)
#[inline]
pub fn trace<T: AsRef<str>>(text: T) {
let text = text.as_ref();
u... | Rust | 0 |
body(circle_body);
world.add_body(ground);
world.add_joint((box_id, circle_id), SpringJoint::new(box_anchor, circle_anchor, distance, 1.5, 0.7).into_joint());
SpringsTestbed {
world,
box_id,
circle_id,
}
}
}
impl testbed... | Rust | 0 |
class Solution:
def zeroFilledSubarray(self, nums: List[int]) -> int:
ans = 0
indexBeforeZero = -1
for i, num in enumerate(nums):
if num:
indexBeforeZero = i
else:
ans += i - indexBeforeZero
return ans
| Python | 1 |
}
}
impl Eq for ClassInner {}
<filename>2016/day14/day14.rs
//! [Day 14: One-Time Pad](https://adventofcode.com/2016/day/14)
use std::collections::HashMap;
use std::time::Instant;
/// Solve the day 14 puzzle.
fn main() {
let data = std::fs::read_to_string("input.txt").unwrap();
let data = data.trim();
... | Rust | 0 |
<'ctx> {
self.build_bool_type().const_zero()
}
// 构建存储指针类型 (i64),当做 64 位系统处理
pub fn build_store_ptr_type(&self) -> IntType<'ctx> {
self.context.i64_type()
}
pub fn build_call_fn(
&self,
fn_value: &FunctionValue<'ctx>,
args: &[BasicMetadataValueEnum<'ctx>],
... | Rust | 0 |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.hitbtc import hitbtc
from ccxt.abstract.bequant import ImplicitAPI
from ccxt.base.types import Any
class bequant(hitbtc, Implic... | Python | 1 |
hould be close to 1 for normalized vectors)
norm = np.linalg.norm(embedding)
if abs(norm - 1.0) > 0.01:
issues.append(f"Not properly normalized: norm={norm}")
# Check for zero vector
if np.allclose(embedding, 0):
issues.append("Zero vector detected")
... | Python | 1 |
if len(architectures) > 1:
res['kernelmodulearchitecturemismatch'] = True
# check for each module if its version can be found in any
# of the found Linux kernel versions.
# If there are no kernel versions in the firmware, then assume a kernel
# (or multiple kernels) are already on the device an... | Python | 1 |
er_ref = metadata.make_owner_reference::<ServiceSpec>();
let svc_name = format!("fluvio-spu-{}", spu_name);
let input_service: InputK8Obj<ServiceSpec> = InputK8Obj {
api_version: ServiceSpec::api_version(),
kind: ServiceSpec::kind(),
metadata: InputObjectMeta {
... | Rust | 0 |
" fn(
arg1: *mut elina_manager_t,
arg2: bool_,
arg3: *mut ::std::os::raw::c_void,
arg4: *mut elina_lincons0_array_t,
) -> *mut ::std::os::raw::c_void,
>,
) -> *mut ::std::os::raw::c_void;
}
extern "C" {
pub fn elina_generic_meet... | Rust | 0 |
args.value_of("upload");
let manifest_path = args.value_of("manifest-path").map(Path::new);
let package_args = package_args(args)?;
let reg_pkg = match (manifest_path, krate) {
(Some(_), None) | (None, None) => reg_index::add(
index_path,
index_url,
manifest_path... | Rust | 0 |
okru0g6qno, k0s7dnztnu8, u8pbdrq28w7
ul6932odofd = 0j
'# kites_gallows_deputies -> wiggles_thicknesses_contempt'
del lgt1ca1ts33
raise o5_6ncp1z_6
'# kites_gallows_deputies -> wiggles_thicknesses_contempt'
gpx3pz1k64i.yb24y6ahfdt: False = e1i_vn1bc96
pass
return
global r2if3fnno7u
... | Python | 1 |
#[derive(Copy, Clone)]
pub struct Features<'a> {
chains: Chains<'a>,
features: Option<morx::Features<'a>>,
kern: bool,
seen: SeenFeatures,
}
impl<'a> Features<'a> {
pub fn new(chains: Chains<'a>, kern: bool) -> Self {
Self {
chains,
features: None,
kern,... | Rust | 0 |
отправились в путь, направившись на Луну, где находится вопрошатель!"
}
]
}
"""
assert (
anime.viewing_order[0].get_anime_url_full()
== get_anime_by_url("doktor-stoun").get_anime_url_full()
)
assert anime == get_anime_by_url(
"https://ru.yummyani.me/cata... | Python | 1 |
use ::{CRgbAllocatedArray, libc};
use ::{CRgbAllocatedPtr, CRgbNeededTx};
use c_bitcoin::CRgbBitcoinNetwork;
use c_bitcoin::CRgbOutPoint;
use generics::WrapperOf;
use hashmap::CRgbHashMap;
//#[derive(Debug)]
#[repr(C)]
pub struct CRgbContract {
pub title: [c_char; 256],
pub issuance_utxo: CRgbOutPoint,
pub... | Rust | 0 |
base_name: str
:param provider_key: Provider key e.g. 'ogr'
:type provider_key: str
"""
pass
def addRasterLayer(self, path, base_name):
"""Add a raster layer given a raster layer file name
:param path: Path to layer.
:type path: str
:param base_na... | Python | 1 |
from flask import url_for, render_template, request, Blueprint
from flask_login import current_user
from app.api import search_manga_by_title, Manga
from app.models import UserLibrary
search_bp = Blueprint('search', __name__)
@search_bp.route('/search')
def search():
title = request.args.get('query')
result... | Python | 1 |
rt_almost_equal(metric_dict["f1-measure-ARG2"], 0.0)
numpy.testing.assert_almost_equal(metric_dict["recall-ARG1"], 1.0)
numpy.testing.assert_almost_equal(metric_dict["precision-ARG1"], 0.5)
numpy.testing.assert_almost_equal(metric_dict["f1-measure-ARG1"], 0.666666666)
numpy.testing.asser... | Python | 1 |
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | Python | 1 |
er")
#################################################
model = accelerator.prepare(model)
optimizer, train_loader, val_loader, scheduler = accelerator.prepare(
optimizer,train_loader, val_loader, scheduler)
numel = sum([p.numel() for p in model.parameters()])
logger.info(f'Model with {numel} pa... | Python | 1 |
# $Copyright: (c) 2024 Bentley Systems, Incorporated. All rights reserved. $
from MSPyBentley import *
from MSPyBentleyGeom import *
from MSPyDgnView import *
from MSPyDgnPlatform import *
from MSPyMstnPlatform import *
'''
Sample to demonstrate how to use ScanCriteria to find elements in a range.
'''
def ElementInLe... | Python | 1 |
rate) use A as I; }
}
mod with_crate {
vis_passthru! { crate const A: i32 = 0; }
vis_passthru! { crate enum B {} }
vis_passthru! { crate extern "C" fn c() {} }
vis_passthru! { crate mod d {} }
vis_passthru! { crate static E: i32 = 0; }
vis_passthru! { crate struct F; }
vis_passthru! { crate... | Rust | 0 |
def decode(self, bytes_seq, debug_hint):
# type: (bytes, Dict[str, Any]) -> Optional[str]
try:
string = bytes_seq.decode('utf8')
debug_hint['utf-8'] = 'success'
return string
except Exception as e:
debug_hint['utf-8'] = 'failed: {}'.format(str... | Python | 1 |
PassportId, id_type: IdentityType);
fn check_id_identity(id: PassportId, id_type: IdentityType) -> bool;
fn check_account_indetity(account: T::AccountId, id_type: IdentityType) -> bool;
}
sp_api::decl_runtime_apis! {
pub trait IdentityPalletApi<T: Config> {
fn check_id_identity(id: PassportId, id... | Rust | 0 |
from cx_Oracle import CLOB
from django.contrib.gis.db.backends.base.adapter import WKTAdapter
from django.contrib.gis.geos import GeometryCollection, Polygon
class OracleSpatialAdapter(WKTAdapter):
input_size = CLOB
def __init__(self, geom):
"""
Oracle requires that polygon rings are in prop... | Python | 1 |
ool.acquire() as con:
await con.execute("UPDATE orders SET qty=$2, status='APPROVED', extra=COALESCE(extra,'{}'::jsonb)||$3::jsonb WHERE client_order_id=$1",
o["client_order_id"], qty, json.dumps({"risk":{"qty":qty}}))
APPROVED.in... | Python | 1 |
rc.completed:
completed_this_update.append(arc)
for arc in completed_this_update:
self.active_arcs.remove(arc)
self.completed_arcs.append(arc)
logging.info(f"Story arc '{arc.name}' moved to completed")
def get_arcs_in_phase(self, phase: str) ... | Python | 1 |
"R" => Ok(R(s[1..].parse().unwrap())),
"L" => Ok(L(s[1..].parse().unwrap())),
"F" => Ok(F(s[1..].parse().unwrap())),
_ => Err(ParseErr {})
}
}
}
/// Loads instructions from the given file, panicking if it doesn't exist or can't be loaded.
fn load_instructions(filena... | Rust | 0 |
.0",
"action": "install"
},
{
"name": "collectd",
"version": "5.7",
"url": "https://collectd.org/download/collectd-tarballs/collectd-5.12.0.tar.bz2",
... | Rust | 0 |
e mozjpeg::src::jcprepct;
pub use mozjpeg::src::jcsample;
pub use mozjpeg::src::jctrans;
pub use mozjpeg::src::jdapimin;
pub use mozjpeg::src::jdapistd;
pub use mozjpeg::src::jdatadst;
pub use mozjpeg::src::jdatadst_tj;
pub use mozjpeg::src::jdatasrc;
pub use mozjpeg::src::jdatasrc_tj;
pub use mozjpeg::src::jdcoefct;
p... | Rust | 0 |
*self == HAAR_A::_0
}
#[doc = "Checks if the value of the field is `_1`"]
#[inline(always)]
pub fn is_1(&self) -> bool {
*self == HAAR_A::_1
}
}
#[doc = "Write proxy for field `HAAR`"]
pub struct HAAR_W<'a> {
w: &'a mut W,
}
impl<'a> HAAR_W<'a> {
#[doc = r"Writes `variant` t... | Rust | 0 |
EXT0_SDA);
sda.connect_input_to_peripheral(InputSignal::I2CEXT0_SDA);
}
fn program_i2c_timing(i2c: &mut I2C0, period: u16) {
let half_period = period / 2;
unsafe {
i2c.scl_high_period.write(|w| w.period().bits(half_period));
i2c.scl_low_period.write(|w| w.period().bits(half_period));
... | Rust | 0 |
ool, Self::Error> {
// NOTE(unsafe) atomic read with no side effects
Ok(unsafe { (*$GPIOX::ptr()).pdir.read().bits() & (1 << $i) == 0 })
}
}
)+
}
}
}
gpio!(GPIOA, gpioa, PORTA, porta, PAx, [
PA0: (pa0, 0, In... | Rust | 0 |
.parsemode);
}
*/
//https://core.telegram.org/bots/api#sendmessage
pub fn send_message(&self, text:&str) -> String {
let link:String = format!("https://api.telegram.org/bot{}/sendMessage?chat_id={}&text={}&parse_mode={}",
self.token, self.id, text, self.parsemode);
network::get(&link)
}
/*
//https://cor... | Rust | 0 |
keys.iter().all(|k| first_key == k),
"Not all interned keys for {} were equal: {:?}",
s,
keys,
);
unsafe {
assert_eq!(s, arena.as_str(*first_key));
}
}
}... | Rust | 0 |
C_* environment variables" in errMsg
continue
if not errorIsDetected:
pytest.xfail("All the bad data are processed without errors!")
finally:
__class__.helper__restore_envvar("LANG", prev_LANG)
__class__.helper__restore_envvar("LANGUAGE", pre... | Python | 1 |
from sqlalchemy import Engine, MetaData, Table, Column, String, Text, DateTime, inspect, text
from time import sleep
# feedsnooplyze modules
from .persistence_engine import PersistenceEngineIcon
def _create_structure(engine: Engine):
metadata = MetaData()
page_content = Table(
'page_content', metada... | Python | 1 |
aud: Some(std::iter::once(config.jwt_audience.clone()).collect()),
iss: Some(config.jwt_issuer.clone()),
sub: None,
algorithms: vec![jwt::Algorithm::RS256],
};
let data = jwt::decode(&bearer.token, &key, &validation).context("Failed to validate JWT")?;
Ok(data.claims)
}
#[derive(De... | Rust | 0 |
# Authors:
# Christian F. Baumgartner (c.f.baumgartner@gmail.com)
import os
import socket
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')
### SET THESE PATHS MANUALLY #####################################################
# Full paths are required because otherwise the code wi... | Python | 1 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, models
class Users(models.Model):
_inherit = 'res.users'
def _deactivate_portal_user(self, **post):
"""Blacklist the phone of the user after deleting it."""
numbers_to_black... | Python | 1 |
w_progress(status="Polling")
# TODO: skip occasional failing requests? (e.g. see `SkipIntermittentFailures` from openeo-aggregator)
resp = self._requests.post(url=token_endpoint, data=post_data, timeout=5)
if resp.status_code == 200:
lo... | Python | 1 |
// label the source with (INFINITY, 0)
labels[0] = (f64::INFINITY, 0, false);
// add the source to the empty queue q
let mut q = VecDeque::<usize>::new();
q.push_back(0);
while !q.is_empty() {
let mut i = q.pop_front().unwrap();
// forward edges
for j in 0..n {
... | Rust | 0 |
"""
Calculate and plot daily daytime temperature averages
-----------------------------------------------------
Example of how to read in MET data and plot up daytime
temperature averages using the add_solar_variable function
Author: Adam Theisen
"""
from arm_test_data import DATASETS
import matplotlib.pyplot as plt... | Python | 1 |
'''
#Read PDB
cat_model, cat_model_resnos, cat_model_CA_coords, cat_model_seqs = read_pdb(pdbname)
receptor_pdb, receptor_resnos, receptor_CA_coords, receptor_seq = cat_model[receptor_chain], cat_model_resnos[receptor_chain], cat_model_CA_coords[receptor_chain], cat_model_seqs[receptor_chain]
#Write... | Python | 1 |
_voltage().await.unwrap();
defmt::info!("Batt: {} V", batt.as_volts());
let batt_charge = axp173.batt_charge_current().await.unwrap();
let batt_discharge = axp173.batt_discharge_current().await.unwrap();
defmt::info!(
"Batt: ^ {} mA | v {} mA",
batt_charge.as_milliamps(),
batt_d... | Rust | 0 |
from telegram import Update
from telegram.ext import ContextTypes, MessageHandler
import models
from custom_filters import MainChannel
from jobs import reforward_job
async def relay_main_channel_post(update: Update, context: ContextTypes.DEFAULT_TYPE):
with models.session_scope() as s:
chats = (
... | Python | 1 |
impl Debug for Bytes {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Bytes").field("inner", self.inner.as_ref().unwrap()).field("drops", &self.drops.as_ref().map(|v| v.len()).unwrap_or(0)).finish()
}
}
impl Display for Bytes {
#[inline]
fn fmt(&self, f:... | Rust | 0 |
(quote! {
impl #impl_generics Fold #generics for #name #ty_generics #where_clause {
type Result = Self;
fn fold_with(
&self,
folder: &mut dyn Folder #generics,
binders: usize,
) -> ::chalk_engine::fallible::Fallible<Self::Resul... | Rust | 0 |
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from ..database import get_db
from .. import models, schemas
from ..auth import hash_password, verify_password, create_access_token
router = APIRouter(prefix="/auth", tags=["auth"])
@router.post("/register")
def register(user: sc... | Python | 1 |
OP_26(13)
StopEffect(0x00, 0x02)
PlayEffect(0x00, 0x00, 0x00FF, 5240, 5000, -181320, 0, 0, 0, 700, 700, 700, 0x00FF, 0, 0, 0, 0)
OP_6F(0x0005, 0)
OP_70(0x0005, 50)
OP_73(0x0005)
OP_20(0x00000BB8)
PlaySE(12, 0x00, 0x64)
StopEffect(0x00, 0x02)
LoadEffect(0x01, 'map\\\\mp027_01.eff... | Python | 1 |
EnsureTyped(keys=image_keys),
Orientationd(keys=image_keys, axcodes="RAS"),
CropForegroundd(keys=image_keys, source_key="label", k_divisible=crop_shape),
RandSpatialCropd(keys=image_keys, roi_size=crop_shape, random_size=False),
ConvertBratsLabelToMultiChannel(keys="labe... | Python | 1 |
are a helpful assistant.\nuser\n\nWhat is shown in this image?\nassistant\nThe image shows a radar chart comparing the performance of different models on various visual question answering (VQA) benchmarks. Each colored line represents a different model, and the distance from the center of the chart indicates the score ... | Python | 1 |
from multiprocessing import cpu_count
SEED = 777
TEMP_DIRECTORY = "temp/data"
RESULT_FILE = "result.tsv"
SUBMISSION_FILE = "predictions.txt"
RESULT_IMAGE = "result.jpg"
GOOGLE_DRIVE = False
DRIVE_FILE_ID = None
MODEL_TYPE = "xlmroberta"
MODEL_NAME = "xlm-roberta-large"
monotransquest_config = {
'output_dir': 'tem... | Python | 1 |
calIpTranslationNatRules", params)
response = json.loads(body)
if "Error" not in response["Response"]:
model = models.DescribeLocalIpTranslationNatRulesResponse()
model._deserialize(response["Response"])
return model
else:
... | Python | 1 |
Import data from an uploaded Excel file.
"""
# Only allow managers to perform the upload.
if not request.user.groups.filter(name="managers").exists():
logger.debug("Permission denied: user is not in managers group.")
return Response(
{"detail": "Permission denied."}, status=st... | Python | 1 |
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
# Define the differential equation function
def second_order_ode(y, t):
y1, y2 = y
dydt = [y2, 2*y2 - y1 + np.exp(2*t)]
return dydt
# Initial conditions
y0 = [0, 1] # y(0) = 0, y'(0) = 1
# Time points to solve for
t = ... | Python | 1 |
:
return os.makedirs(path)
def _write_config(self):
domain1 = self.env.domain1
creds1 = self.env.get_credentials(domain1)
self._mkpath(self._docs_dir)
self._mkpath(self._tmp_dir)
with open(os.path.join(self._docs_dir, 'data.json'), 'w') as fd:
data = ... | Python | 1 |
import os
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../')))
import asyncio
from sphero_sdk import SpheroRvrAsync
from sphero_sdk import SerialAsyncDal
from sphero_sdk import RvrStreamingServices
loop = asyncio.get_event_loop()
rvr = SpheroRvrAsync(
dal=SerialAsync... | Python | 1 |
}
if matches!(node, Node::Parent(_)) && i % 2 != 1 {
return Err(TreeIntegrityError::CorruptedTree("parent index is not odd"));
}
}
for (i, node) in nodes.iter().enumerate() {
match node {
Node::Leaf(Some(kp)) => {
... | Rust | 0 |
}) = unwind_codes.last()
{
*size == word_size && offset == *alloc_offset && *stack_offset == 0
} else {
false
};
if push_... | Rust | 0 |
}
fn foo(a: A) { B { bar: a.$0 }; }
"#,
expect![[r#"
fd bar [type+name]
fd baz [type]
fd foo []
"#]],
)
}
#[test]
fn record_field_and_call_relevances() {
check_relevance(
r#"
struct A { foo: i64, bar: u32, ... | Rust | 0 |
マガド ×1"),
Quest("雪鬼獣がやってくる", "ゴシャハギ ×1"),
Quest("方々から迫る脅威", "ヤツカダキ ×1, フルフル ×1"),
Quest("乱暴者たちにご注意を", "ラージャン ×1, 像ジンオウガ ×1"),
Quest("激突・激烈・激励の乱", "ゴシャハギ ×1, ヨツミワドウ ×1"),
Quest("大社跡の大騒動", "オロミドロ ×1, タマミツネ ×1"),
Quest("うさ団子貫く四つの角!の巻", "ディアブロス ×2"),
... | Rust | 0 |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | Python | 1 |
eturn Response(generate(),
direct_passthrough=True,
status=resp.status_code,
content_type=content_type)
else:
# For non-streaming requests, get full response
resp... | Python | 1 |
ssertEqual(
"Week 1 has regular season matchups and playoff/championship matchups in the same week.",
str(context.exception),
)
def test_checkMultiWeekMatchupsWithSameIdAreOnlyInOneMatchupPerWeek_weekHasSameMultiMatchupIdInMultipleMatchups_raisesException(
self,
):
... | Python | 1 |
*b;
i += 1;
}
}
#[test]
fn clear_screen() {
// 0x00E0
let mut test = ::cpu::Cpu::new();
let rom = &[0x00, 0xE0];
test.graphics = [1; 64 * 32];
load_vec(&mut test, rom);
test.run_cycle();
// 12/5/2014 this is probably slower, but slices are unstable
for &x in test.graphics.iter() {
assert!(x ... | Rust | 0 |
"""
Knapsack 0-1 problem using dp (0-1 means we either choose it or we don't, no fractions)
Given weights and their corresponding values,
We fill knapsack of capacity W to obtain maximum possible value in bottom-up manner.
N: Number of (items)weight elements
W: Capacity of knapsack
Time Complexity: O(N*W)(Looping thro... | Python | 1 |
, ly: usize, lz: usize) -> u32 {
LightUtils::extract_blue_light(self.lights[&[lx, ly, lz]])
}
/// Set the blue light value locally.
#[inline]
fn set_local_blue_light(&mut self, lx: usize, ly: usize, lz: usize, level: u32) {
self.lights[&[lx, ly, lz]] =
LightUtils::insert_blu... | Rust | 0 |
reference_points=ref_3d,
reference_points_cam=reference_points_cam,
mask=mask,
attn_mask=attn_masks[attn_index],
key_padding_mask=key_padding_mask,
spatial_shapes=spatial_shapes,
level_st... | Python | 1 |
map from D
x = self.output(x)
return x, cam_logit
class MultiScaleD(nn.Module):
def __init__(self,
num_scale=2,
num_layers=3, channels=64, max_channels=512, act_name='lrelu', in_channels=3
) -> None:
super().__init__()
self.discs = nn.ModuleList([
D... | Python | 1 |
self) -> Option<&String> {
self.domain.as_ref()
}
pub fn reset_domain(&mut self) {
self.domain = None;
}
pub fn set_effect_id(&mut self, effect_id: i32) {
self.effect_id = Some(effect_id);
}
pub fn with_effect_id(mut self, effect_id: i32) -> GetDogmaEffectsEffectIdModifier {
self.effect_i... | Rust | 0 |
eff: motor_params.cfm_coeff,
cfm_gain: motor_params.cfm_gain,
rhs: rhs_wo_bias,
rhs_wo_bias,
writeback_id,
}
}
pub fn limit_angular_ground<const LANES: usize>(
&self,
params: &IntegrationParameters,
joint_id: [JointIndex; LANES],
... | Rust | 0 |
t]
fn transform2_scale_uniform() {
let t = Transform2::scale_uniform(4.0);
assert_eq!(*t.forward, Matrix3x3::scale_uniform(4.0));
assert_eq!(*t.inverse, Matrix3x3::scale_uniform(1.0 / 4.0));
}
#[test]
fn transform2_and_then() {
let angle = 0.39269908169872415480783042290... | Rust | 0 |
secs(3)).await;
local1.alias(x, Some(c2.cid())).await.unwrap();
assert_pinned!(&local1, &a1);
assert_unpinned!(&local1, &b1);
assert_unpinned!(&local1, &c1);
assert_pinned!(&local1, &b2);
assert_pinned!(&local1, &c2);
local2.alias(x, None).await.unwrap();
... | Rust | 0 |
MULTIKEY_V1 = {
"@context": {
"id": "@id",
"type": "@type",
"@protected": True,
"Multikey": {
"@id": "https://w3id.org/security#Multikey",
"@context": {
"@protected": True,
"id": "@id",
"type": "@type",
... | Python | 1 |
0, &mut offsets[..]);
let offsets = offsets;
let views = env
.find_class("net/imglib2/view/Views")
.expect("Failed to load Java class net.imglib2.view.Views");
let flat_iterable = env.call_static_method(
views,
"flatIterable",
"(Lnet/imglib2/RandomAccessibleInterva... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.