text string | label_name string | labels int64 |
|---|---|---|
rs[..]")
.run();
ws.cargo("build -v --example ex1")
.with_stderr_contains("[RUNNING] `rustc [..]a/examples/ex1.rs[..]")
.run();
}
#[cargo_test]
fn target_filters_workspace_not_found() {
let ws = project()
.at("ws")
.file(
"Cargo.toml",
r#"
... | Rust | 0 |
rface.vder(u, v);
let vder1 = processor.vder(u, v);
assert_near!(vder0, vder1);
let uuder0 = surface.uuder(u, v);
let uuder1 = processor.uuder(u, v);
assert_near!(uuder0, uuder1);
let uvder0 = surface.uvder(u, v);
... | Rust | 0 |
# print(round(8/3))
# print(round(8/3,2))
# print(8 // 3)
# result = 4 / 2
# result /= 2
# print(result)
score = 0
height = 1.8
isWinning = True
# f string
print(f"your score is {score},your height is {height},your winning is {isWinning}") | Python | 1 |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
class LogisticRegression:
def __init__(self, learning_rate=0.01, n_iterations=1000):
self.learning_rate = learn... | Python | 1 |
vent_type (str, optional): 事件類型
stock_id (str, optional): 股票代號
start_time (datetime, optional): 開始時間
end_time (datetime, optional): 結束時間
Returns:
list: 事件列表
"""
filtered_events = self.events
# 過濾事件類型
if event_type:
fil... | Python | 1 |
(),
error_message: None,
data: vec![],
}
}
pub fn parse_wrk_output(&self) -> ToolsetResult<BenchmarkResults> {
lazy_static! {
static ref THREADS_CONNECTIONS: Regex = Regex::new(r"([0-9]+) threads and ([0-9]+) connections").unwrap();
static ref LATE... | Rust | 0 |
0x69, 0x6F, 0x6E,
0x20, 0x31, 0x39, 0x2E, 0x35, 0x2E, 0x30, 0x3A, 0x20, 0x54, 0x75, 0x65, 0x20, 0x4D, 0x61,
0x79, 0x20, 0x32, 0x36, 0x20, 0x32, 0x30, 0x3A, 0x34, 0x31, 0x3A, 0x34, 0x34, 0x20, 0x50,
0x44, 0x54, 0x20, 0x32, 0x30, 0x32, 0x30, 0x3B, 0x20, 0x72, 0x6F, 0x6F, 0x74, 0x3A, 0x78,
... | Rust | 0 |
t.addWidget(widget)
return widget
def test_initialization(self, numeric_edit):
assert numeric_edit._minimum == 10
assert numeric_edit._maximum == 50
assert numeric_edit._decimals == 2
assert numeric_edit.text() == "10.00"
assert numeric_edit.get_value() == 10.0
... | Python | 1 |
ign_down(&self, align: usize) -> VirtAddr {
VirtAddr(rt::align_down(self.0, align))
}
}
impl Add<usize> for VirtAddr {
type Output = VirtAddr;
#[inline(always)]
fn add(self, rhs: usize) -> VirtAddr {
VirtAddr(self.0 + rhs)
}
}
impl AddAssign<usize> for VirtAddr {
#[inline(alwa... | Rust | 0 |
# Train models and save the model. The model will be saved in the pretrained folder.
# Can't train large models with this script. Use train_large.py instead.
# Large models are trained with NeighborLoader, which is not supported in this script.
# The trained model is used for benchmarking explanation methods.
import ... | Python | 1 |
}
#[allow(unused_mut)]
let mut scope_328 = writer.prefix("DefaultRouteTablePropagation");
if let Some(var_329) = &input.default_route_table_propagation {
scope_328.string(var_329.as_str());
}
#[allow(unused_mut)]
let mut scope_330 = writer.prefix("VpnEcmpSupport");
if let Some(var_33... | Rust | 0 |
_cx_auge.astype(np.float32)
item['cam_cy'] = cy.astype(np.float32)
###### bbox params
item['box_center'] = np.array([center_x_auge, center_y]).astype(np.float32)
item['box_size'] = (bbox_size * auge_scale).astype(np.float32)
###### scene verts
scene_pcd_verts_full_auge =... | Python | 1 |
(prev.mult)
.filter(|t| (t + bus.delay) % bus.id == 0)
.take(2)
.collect();
Candidate {
first: valid[0],
mult: valid[1] - valid[0],
}
}
fn solve_part2(busses: &[Bus]) -> usize {
busses
.iter()
.fold(Candidate { first: 1, mult: 1 }, step)
.fir... | Rust | 0 |
ta>>,
render_layer_queue: VecDeque<Arc<SceneGraph>>,
model_data: Vec<ModelData>,
// Enable vulkan debug layers? - need to install the vulkan sdk to get them
#[allow(dead_code)]
debug_callback: Option<vulkano::instance::debug::DebugCallback>,
previous_frame_end: Box<dyn GpuFuture>,
recreat... | Rust | 0 |
import re
from unittest import SkipTest
import pytest
import moto.server as server
from moto import mock_aws, settings
FILE_SYSTEMS = "/2015-02-01/file-systems"
MOUNT_TARGETS = "/2015-02-01/mount-targets"
@pytest.fixture(scope="function", name="aws_credentials")
def fixture_aws_credentials(monkeypatch):
"""Moc... | Python | 1 |
let a: i16x4 = i16x4::new(1, 0, 2, 0);
let b: i16x4 = i16x4::new(2, 0, 3, 0);
let e: i16x4 = i16x4::new(1, 2, 2, 3);
let r: i16x4 = transmute(vuzp1_p16(transmute(a), transmute(b)));
assert_eq!(r, e);
}
#[simd_test(enable = "neon")]
unsafe fn test_vuzp1q_p16() {
let a... | Rust | 0 |
r c @ s, e Zd ZdZdZdd Zdd Zdd Zd S )
r a Interface for stream protocol with manual buffer control.
Important: this has been added to asyncio in Python 3.7
*on a provisional basis*! Consider it as an experimental API that
might be changed or removed in Python... | Python | 1 |
template.vis.clone();
}
if let Some(ref mut template) = template.variants.iter().next() {
for variant in item.variants.iter_mut() {
variant.attrs.extend(template.attrs.clone());
}
... | Rust | 0 |
= 1_u16;
for c in &self.cmd_infos {
let entry_w = UnicodeWidthStr::width(c.text.name);
if line_width + entry_w > width as usize {
self.draw_list.push(DrawListEntry::LineBreak);
line_width = 0;
lines += 1;
} else if line_width... | Rust | 0 |
= TchTensorBuffer<f32, ObsShape, Obs>;
type ActBuffer = TchTensorBuffer<i64, ActShape, Act>;
mod dqn_model {
use anyhow::Result;
use border_tch_agent::{
dqn::{DQNModel, DQNModelBuilder},
model::SubModel,
util::OutDim,
};
use serde::{Deserialize, Serialize};
use tch::{nn, nn... | Rust | 0 |
.collect::<Vec<_>>();
queries.sort_by_key(|ref t| t.0);
// Start at highest zoom level and find first match
let query = queries
.iter()
.rev()
.find(|ref q| level >= q.0 && level <= q.1 && check(q.2));
query.map(|q| q.2)
}
/// SQL query ... | Rust | 0 |
"""
Car model for Hybrid A* path planning
author: Zheng Zh (@Zhengzh)
"""
import sys
import pathlib
root_dir = pathlib.Path(__file__).parent.parent.parent
sys.path.append(str(root_dir))
from math import cos, sin, tan, pi
import matplotlib.pyplot as plt
import numpy as np
from utils.angle import rot_mat_2d
WB = ... | Python | 1 |
_range()
.set_end(keys::data_end_key(end.as_encoded()));
}
ctx.spawn(
self.threads
.spawn_with_handle(
async move {
let client =
Client::new(req.get_pd_addr(), 1, min_available_ratio, sec... | Rust | 0 |
ive() {
let hash = hash_files_recursive_from(vfat_from_resource!("mock3.fat32.img"), "/");
assert_hash_eq!("mock 3 file hashes", hash, hash_for!("files-2-3-4"));
}
#[test]
fn test_mock4_files_recursive() {
let hash = hash_files_recursive_from(vfat_from_resource!("mock4.fat32.img"), "/");
assert_hash_eq... | Rust | 0 |
, 't>(
_context: &ParserContext,
input: &mut Parser<'i, 't>,
) -> Result<PropertyDeclaration, ParseError<'i>> {
BoxShadow::parse(input).map(PropertyDeclaration::BoxShadow)
}
net.sf.jasperreports.data.ClasspathAwareDataAdapter
<filename>pokemon_rust/src/battle/tests/moves/meditate.rs
use crate::battle::backend::{Batt... | Rust | 0 |
ite!(f, "{}", e),
InputParseErr::Fatal(e) => write!(f, "{}", e),
}
}
}
#[non_exhaustive]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Expectation {
/// A string tag was expected.
Tag(&'static str),
/// A specific character was expected.
Char(char),
/// One of the ... | Rust | 0 |
(Rc::new(r1 / r2))
},
},
NumberPair::Rational(r1, r2) =>
Number::Rational(Rc::new(&*r1 / &*r2))
}
}
}
impl Neg for Number {
type Output = Number;
fn neg(self) -> Self::Output {
match self {
Number::Integer(n) => Nu... | Rust | 0 |
"""Test .dist-info style distributions.
"""
import os
import shutil
import tempfile
import unittest
import textwrap
try:
import ast
except:
pass
import pkg_resources
from setuptools.tests.py26compat import skipIf
def DALS(s):
"dedent and left-strip"
return textwrap.dedent(s).lstrip()
class TestDist... | Python | 1 |
ityAnalyzer::new();
let response: Vec<VaderScores> = req_text
.text
.iter()
.map(|text| analyzer.polarity_scores(text))
.collect();
HttpResponse::Ok().json(response)
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
std::env::set_var("RUST_LOG", "actix_web=info")... | Rust | 0 |
from django.db import migrations
def alter_charset_mysql(apps, schema_editor):
if schema_editor.connection.vendor != "mysql":
return
# Convert the table to utf8mb4
schema_editor.execute("ALTER TABLE web_blogpost CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci")
# Modify the title ... | Python | 1 |
}
func TestStartLineAnchor(t *testing.T) {
b := testIndexBuilder(t, nil,
Document{
Name: "f1",
Content: []byte(
`hello
start of middle of line
`),
})
q, err := query.Parse("^start")
if err != nil {
t.Errorf("parse: %v", err)
}
res := searchForTest(t, b, q)
if len(res.Files) != 1 {
t.Errorf("g... | Rust | 0 |
(|v| v * &recip).collect::<Vec<_>>();
Ok((value, cart_grad))
}
}
// ---------------
/// A test Potential that creates a chain along the first lattice vector.
#[derive(Debug, Clone)]
pub struct Chainify;
impl<Meta: Clone + 'static> PotentialBuilder<Meta> for Chainify {
fn initialize_diff_fn(&self, ini... | Rust | 0 |
rt dist12 > 0
assert dist13 == 0.0
assert dist14 > dist12
assert dist15 == float('inf')
print(f"\n--- Testing Novelty Search Components ---")
archive = NoveltyArchive(capacity=5)
pop_behaviors = [
[1.0, 1.0], # 0
[1.1, 1.1], # 1
[5.0, 5.0], # 2
[5.1, 5.0], # 3
... | Python | 1 |
from typing import Union
import numpy as np
from ... import operations
from ...graph import OperationGraph
from .base import Simplifier
class ConvertMatMulToGemm(Simplifier):
def visit_MatMul(
self, operation: operations.MatMul
) -> Union[operations.MatMul, operations.Gemm]:
a = operation.a
... | Python | 1 |
= "SVGSVGElement" , js_name = suspendRedraw)]
#[doc = "The `suspendRedraw()` method."]
#[doc = ""]
#[doc = "[MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/SVGSVGElement/suspendRedraw)"]
#[doc = ""]
#[doc = "*This API requires the following crate features to be activated: `Svgs... | Rust | 0 |
(feature.webpmux, "WEBPMUX"),
]
all = 1
for option in options:
if option[0]:
version = ''
if len(option) >= 3 and option[2]:
version = ' (%s)' % option[2]
print("--- %s support available%s" % (option[1], versio... | Python | 1 |
# Python Program to implement
# Odd-Even / Brick Sort
def oddEvenSort(arr, n):
# Initially array is unsorted
isSorted = 0
while isSorted == 0:
isSorted = 1
temp = 0
for i in range(1, n - 1, 2):
if arr[i] > arr[i + 1]:
arr[i], arr[i + 1] = arr[i + 1], arr... | Python | 1 |
#[test(tokio::test)]
async fn empty_query_plan_should_be_a_planner_error() {
insta::assert_debug_snapshot!(
"empty_query_plan_should_be_a_planner_error",
BridgeQueryPlanner::new(Arc::new(example_schema()))
.await
.unwrap()
.get(
... | Rust | 0 |
from django.db import models
# from users.models import Users2
# Create your models here.
class Coach(models.Model):
image = models.ImageField(
upload_to="coach_images", blank=True, null=True, verbose_name="Picture"
)
# user = models.OneToOneField(
# to=Users2, verbose_name="User_id", on_... | Python | 1 |
PrimitiveDateTime::parse(
string,
format_description!(
"[year repr:full base:calendar]-[month repr:numerical]-[day]T[hour]:[minute]:[second]"
),
).map(|datetime| datetime.assume_utc())
})
.or_else... | Rust | 0 |
contains many traits which often follow naming patterns,
//! sets of these items are sometimes referred to by parts of their name.
//! In particular, in order of descending precedence:
//!
//! - `Part` traits -> traits with "Part" in their name
//! - <code><s>Part</s></code> traits -> traits that do *not* have "Part" ... | Rust | 0 |
import os
import socket
def find_open_port():
"""
Find an open port
"""
sock = socket.socket()
sock.bind(("", 0))
_, port = sock.getsockname()
return port
def is_docker():
path = "/proc/self/cgroup"
return (
os.path.exists("/.dockerenv")
or os.path.isfile(path)
... | Python | 1 |
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
# routers
from routers import ingredients
from routers import ingredientbatches
app = FastAPI(title="Ingredients Service")
# include routers
app.includ... | Python | 1 |
Shape,
}
impl fmt::Display for ToolType {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
use ToolType::*;
let name = match_variant_name!(match (self) {
Select,
Crop,
Navigate,
Eyedropper,
Text,
Fill,
Gradient,
Brush,
Heal,
Clone,
Patch,
BlurSharpen,
Relight,... | Rust | 0 |
f.get_aref().percent(other, heap)
}
pub fn floor_div(self, other: Value<'v>, heap: &'v Heap) -> anyhow::Result<Value<'v>> {
self.get_aref().floor_div(other, heap)
}
pub fn bit_and(self, other: Value<'v>) -> anyhow::Result<Value<'v>> {
self.get_aref().bit_and(other)
}
pub fn bit... | Rust | 0 |
ct_definition: &'a ContractDefinition,
pub definition_node: &'a ContractDefinitionNode,
pub blocks: &'b mut Vec<&'a Block>,
pub statement: Option<&'a Statement>,
pub assignment: &'a Assignment,
}
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, PartialOrd, Eq, Ord, Hash)]
#[serde(rename_all = ... | Rust | 0 |
let col_name = &table.columns[1];
assert_that!(col_name.name).is_equal_to("name".to_string());
assert_that!(col_name.sql_type).is_equal_to(SqlType::Simple(SimpleSqlType::VariableLengthString(50), None));
assert_that!(col_name.constraints)
.named(&"col_name.constraints")
.... | Rust | 0 |
mport STMemory
from ai.cognitive_control import CognitiveControl
cognitive_control = CognitiveControl(robot, config, {}, False)
lt_memory = LTMemory(robot, config)
st_memory = STMemory(robot, config)
nerves = Nerves(robot)
with open(config.DATA_PATH + robot + "/settin... | Python | 1 |
nterrater.CMINIOU}, "
f"{apstr}constrained)",
)
# now save everything
plt.savefig(savename)
plt.close()
def _get_fov_anchor_counts(dbcon, evalset, whoistruth):
"""get no of anchors."""
anchor_counts = DataFrame()
for constrained, dbc in dbcon.items():
acnt = ... | Python | 1 |
let n_rows = self.num_rows();
valid_row_ids.reserve(n_rows);
const STEP: RowId = 64;
let mut start = 0;
let mut buffer = [0; STEP];
while start < n_rows {
let step = cmp::min(STEP, n_ro... | Rust | 0 |
(tokenstream::TokenTree::Token(span, tok)) => match kleene_op(&tok) {
Some(op) => return (None, op),
None => match input.next() {
Some(tokenstream::TokenTree::Token(span, tok2)) => match kleene_op(&tok2) {
Some(op) => return (Some(tok), op),
... | Rust | 0 |
from fastapi import Header, HTTPException
from pymongo import MongoClient
import os
from dotenv import load_dotenv
# Load env variables
load_dotenv()
MONGO_URI = os.getenv("MONGO_URI")
client = MongoClient(MONGO_URI)
db = client.get_default_database()
user_collection = db.devices
async def verify_api_key_user(x_api_... | Python | 1 |
tches(needle, haystack) {
Some((haystack, scorer::score(needle, haystack)))
} else {
None
}
}
pub fn match_and_score_with_positions<'a>(needle: &str, haystack: &'a str) -> Option<MatchWithPositions<'a>> {
if matcher::matches(needle, haystack) {
let (score, positions) = scorer::score... | Rust | 0 |
"nearest": cv2.INTER_NEAREST,
"area": cv2.INTER_AREA
}
def func(x):
x = cv2.resize(x, output_size, interpolation=name_to_filter[filter])
x = x.clip(0, 255)
if quantize_after:
x = x.astype(np.uint8)
return x
else:
r... | Python | 1 |
dators_times().get(pub_key), Some(time0));
}
fn get_current_time(api: &TestKitApi) -> Option<DateTime<Utc>> {
api.get(ApiKind::Service("exonum_time"), "v1/current_time")
}
fn get_current_validators_times(api: &TestKitApi) -> Vec<ValidatorTime> {
api.get_private(ApiKind::Service("exonum_time"), "v1/validators_... | Rust | 0 |
ns, NatsConfigError> {
let nats_options = match &auth_config {
None => nats::asynk::Options::new(),
Some(auth) => auth.to_nats_options()?,
};
let nats_options = nats_options
.with_name(connection_name)
// Set reconnect_buffer_size on the nats client to 0 bytes so that the
... | Rust | 0 |
# Generated by Django 5.1.1 on 2024-09-29 07:28
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... | Python | 1 |
tream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
match codegen::generate(&input) {
Ok(code) => {
generate_derive(input, code)
}
Err(err) => {
let error = match err {
CompileError::SpanError(span_err) => {
... | Rust | 0 |
# input = [(1,2),(3,1),(5,4)]
# output = [(3,1),(1,2),(5,4)]
a = [(1,2),(3,1),(5,4)]
n = len(a)
for i in range(n):
min = i
for j in range(i+1,n):
if a[j][1] < a[min][1]:
min = j
a[i],a[min] = a[min],a[i]
print(a)
a.sort(key = lambda x : x[1])
print(a)
| Python | 1 |
import copy
import pickle
import ecole
def test_RandomGenerator():
"""Test bindings of the RandomGenerator."""
assert ecole.RandomGenerator.min_seed < ecole.RandomGenerator.max_seed
rng = ecole.RandomGenerator(42)
rand_val_1 = rng()
assert isinstance(rand_val_1, int)
rng.seed(42)
rand_va... | Python | 1 |
ess at 0.
read_progress(progress_value, progress_event)
schedule(is_done, progress_value, progress_event, allocate_gpus_num, allocated_gpus_num)
print(f"Starting Deadline Control at deadline {desired_deadline}s with alpha = {alpha}.")
start_time = time.time()
time.sleep(T_SAMPLE_SECONDS)
#This... | Python | 1 |
:from_args();
// Set the verbosity level of the logger.
let level = match opt.verbose {
0 => LevelFilter::Error,
1 => LevelFilter::Warn,
2 => LevelFilter::Info,
_ => LevelFilter::Debug,
};
SimpleLogger::init(level, Config::default()).unwrap();
}
<gh_stars>1-10
use super:... | Rust | 0 |
expected_shape = (batch_size * num_beam_groups, seq_len, config.hidden_size)
# check hidden size
self.assertListEqual(
[layer_hidden_states.shape for layer_hidden_states in iter_hidden_states],
[expected_shape] * len(iter_hidden_states),
)
... | Python | 1 |
#[structopt(name="ruche-server", author, about)]
struct Opt {
#[structopt(
long,
help = "Sets the listening address",
value_name = "IP:PORT",
default_value(DEFAULT_LISTENING_ADDRESS),
parse(try_from_str)
)]
addr: SocketAddr
}
#[tokio::main]
async fn main() {
env_... | Rust | 0 |
# encoding=utf-8
from __future__ import unicode_literals
from whoosh.analysis import RegexAnalyzer, LowercaseFilter, StopFilter, StemFilter
from whoosh.analysis import Tokenizer, Token
from whoosh.lang.porter import stem
import jieba
import re
STOP_WORDS = frozenset(('a', 'an', 'and', 'are', 'as', 'at', 'be', 'by', '... | Python | 1 |
() };
let targeted = 1.0 / 60.0;
egui.tick_accum += dt;
if egui.tick_accum > targeted {
egui.tick_accum -= targeted;
egui.tick = Some(targeted);
}
})
.display(|| {
let egui: &mut Egui = unsafe { Engine::module_mut().unwrap() };
let dt = egui.tick.take().unwrap_or_default();
... | Rust | 0 |
turnpoint C record, the 9th character is the N/S of the latitutde
// In a declaration type C record, it is a number (part of the declaration time)
if line.len() < 9 {
return Err(ParseError::SyntaxError);
}
match line.as_bytes()[8] {
... | Rust | 0 |
.keys()
.map(|referent| referent.clone())
.into_iter()
.collect::<HashSet<String>>();
let received_attrs = received_revealed_attrs
.union(&received_unrevealed_attrs)
.map(|attr| attr.clone())
.collect::<HashSet<String>>()
... | Rust | 0 |
a = self;
let b = other;
let result_1 = a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3] +
a[4] * b[4] + a[5] * b[5] + a[6] * b[6] + a[7] * b[7];
EuclideanMultivector3::from_scalar(result_1)
}
}
impl<S> ops::BitOr<S> for EuclideanMultivector3<S>
where
S: Scala... | Rust | 0 |
_get(
context, rule['parent_group_id'],
columns_to_join=['instances'])
security_groups.add(security_group)
# ..then we find the instances that are members of these groups..
instances = {}
for security_group in security_groups:
for instance... | Python | 1 |
0px;
background: white;
box-sizing: border-box;
text-align: center;
font-size: 12px
}
h1 {
font-size: 24px;
font-family: helvetica;
text-align: center;
}
h2 {
font-size: large;
font-family: helvetica;
text-align: center;
}
.table-container-summary {
position: relative;
max-hei... | Python | 1 |
from setuptools.command.register import register
from setuptools.dist import Distribution
from setuptools.errors import RemovedCommandError
from unittest import mock
import pytest
class TestRegister:
def test_register_exception(self):
"""Ensure that the register command has been properly removed."""
... | Python | 1 |
n_ub};
infer::can_mk_assignty(self.infcx, anmnt, sub, sup)
}
fn mk_eqty(sub: ty::t, sup: ty::t) -> result<(), ty::type_err> {
infer::mk_eqty(self.infcx, sub, sup)
}
fn mk_subr(sub: ty::region, sup: ty::region) -> result<(), ty::type_err> {
infer::mk_subr(self.infcx, sub, sup)
... | Rust | 0 |
t[str, Any]:
"""轮询检查设备授权状态
Args:
device_code: 设备码
interval: 轮询间隔(秒)
timeout: 总超时时间(秒)
Returns:
授权结果,包含 access_token
Raises:
AuthTimeoutError: 授权超时
BaiduDriveError: 授权失败
"""
self.logger.info(f"开始轮询设... | Python | 1 |
Returns a list of all source files in the project's `src` directory
pub fn list_source_files(&self) -> Vec<PathBuf> {
utils::source_files(self.project().sources_path())
}
}
impl<T: ArtifactOutput + Default> TempProject<T> {
/// Creates a new temp project inside a tempdir with a prefixed directory
... | Rust | 0 |
und_no=round_no,
snapshot_id=snapshot_id,
llm_reply=llm_reply,
items=final_items,
logs=result.logs,
metrics=result.metrics,
state_snapshot=state_snapshot,
round_status=round_status_str,
)
# --- Additional models and endpoints for status / reroll / branch ---
... | Python | 1 |
span.in_scope(|| {
db_cross_section_leaves(db, xs)
.enumerate()
.map(|(i, (aabb, _, level))| {
min_level = min_level.min(level);
(i.try_into().unwrap(), aabb)
})
.collect()
});
(qbvh_from_leaves_with_splitter(leaves), min_l... | Rust | 0 |
);
self.velocities[i] = (vel_x, vel_y);
self.rotations[i] = rot;
}
}
}
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
_reserved0: [u8; 1usize],
#[doc = "0x01 - Port 2 Input"]
pub p2in: P2IN,
_reserved1: [u8; 1usize],
#[doc = "0x03 - Port 2 Output... | Rust | 0 |
]
)
actual = DatetimeIndex(shift_months(dti.asi8, years * 12 + months))
raw = [x + pd.offsets.DateOffset(years=years, months=months) for x in dti]
expected = DatetimeIndex(raw)
tm.assert_index_equal(actual, expected)
def test_dt64arr_addsub_object_dtype_2d():
# block-wise DataFrame o... | Python | 1 |
s be using `mitosis`
std::env::remove_var(ENV_NAME);
bootstrap_ipc(token);
}
}
static IN_TEST_ENV: AtomicBool = AtomicBool::new(false);
/// Initialize `mitosis` within a `#[test]`. You need to also have
/// ```rust
/// #[test]
/// fn mitosis() {
/// init_test()
/// }
/// ```
/// in your crate ... | Rust | 0 |
.collect::<Vec<String>>()
.join("\n")
}
}
//mutates cur_ind to sit on previous char
//it is better to use external crates for this I guess
fn prev(str: &str, cur_ind: &mut usize) {
// if *cur_ind == 0 {
// return;
// }
// if let Some((ind, _)) = str.get(..*cur_ind).unwra... | Rust | 0 |
import math
import csv
from sklearn.metrics import roc_auc_score, roc_curve
import numpy as np
import argparse
parser = argparse.ArgumentParser(description='Calculate toggle-based uncertainty and AUROC for LALM.')
parser.add_argument('--model', type=str, required=True, help='Name of the model (e.g., salmonn, qwen).')... | Python | 1 |
#!/usr/bin/env python
from setuptools import setup
from setuptools.command.develop import develop
import distutils.log
from distutils.command.build import build
from distutils.cmd import Command
def read_text_file(path):
import os
with open(os.path.join(os.path.dirname(__file__), path)) as f:
return f... | Python | 1 |
> {
if self.current_frame.is_none() || num + 1 != self.next_frame {
self.load_frame(num)
} else {
self.current_frame.as_ref()
}
}
fn setup_decoder(&mut self) -> Result<(), gif::DecodingError> {
use gif::{ColorOutput, SetParameter};
let mut dec... | Rust | 0 |
lease/test_wasm_random_bytes.wasm")
}
TestWasm::SerRegression => {
get_code("wasm32-unknown-unknown/release/test_wasm_ser_regression.wasm")
}
TestWasm::Sign => get_code("wasm32-unknown-unknown/release/test_wasm_sign.wasm"),
TestWasm::SysTime =>... | Rust | 0 |
𝁣', '\u{e01df}', '𐠒', '𝕬', '𐊶', '𐘬', 'ȸ', '𘳔',
'\u{e0157}', '𐒊', '⠺', 'ꅡ', '꤯', '🎜', 'ᧉ', '꯵', 'ឆ', '⊻', '𛇽',
'𓊚', '💀', '\u{e01c8}', '\u{1da2d}', '𑿗', '律', '𛀘', '𖨯', '𝞭', '𘭃',
'𞟣', '෮', 'Р', '▃', '🕝', '𒎒', '൯', 'ꏳ', 'ണ', '𐺄', '㍭', '🐢',
'𔐣', '𘳆', 'ﲀ', '⡢', 'ꭕ', 'ﱈ', '𤠔', '㈣', '🠭'... | Rust | 0 |
Self) {
for (addr, byte) in other.diffs() {
self.write_u8(addr, u32::from(byte));
}
}
fn read_byte(&self, _address_space: AddressSpace, address: u32) -> u32 {
self.read_u8(address)
}
fn read_word(&self, _address_space: AddressSpace, address: u32) -> u32 {
(s... | Rust | 0 |
**************************************************80
#
## BURGERS_VISCOUS_TIME_EXACT1_TEST02 tests sets up a finer test case.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 24 September 2015
#
# Author:
#
# John Burkardt
#
import numpy as np
import platform
f... | Python | 1 |
ocimientos.top_herramientas_por_mes])
# ───────────────────────── PREFERENCIAS ──────────────────────
elements.append(Paragraph("📌 Estadísticas de Preferencias", styles["Heading2"]))
# Anuales
add_section("Top disponibilidad de inicio (anual)", [(i.label, i.count) for i in preferencias.top_disponibilidad... | Python | 1 |
# Copyright (C) 2020 Red Hat, Inc.
#
# 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 writ... | Python | 1 |
constant_pool.class(slice.read_u16::<BigEndian>()?)?.name_index)?.str.clone());
}
Ok(ExceptionsAttribute {
exceptions
})
}
pub fn write<T: Write>(&self, wtr: &mut T, constant_pool: &mut ConstantPoolWriter) -> Result<()> {
let num_exceptions = self.exceptions.len();
wtr.write_u16::<BigEndian>(num_except... | Rust | 0 |
import reflex as rx
config = rx.Config(
app_name="resuelvesistema",
) | Python | 1 |
ition, self.dimension),
});
for mut child in self.children_mut() {
child.process_get_primitives(primitives, env);
}
primitives.push(Primitive {
kind: PrimitiveKind::UnClip,
rect: Rect::new(self.position, self.dimension),
});
}
}
impl Wid... | Rust | 0 |
ROR": "FrontMatter 파싱 오류: {}",
"GET_ADVANCED_SETTINGS_FAILED": "고급 설정 가져오기 오류: {}",
"GET_CUSTOM_FAILED": "사용자 정의 필드 가져오기 오류: {}",
"GET_PAGE_SCAFFOLD_FAILED": "페이지 템플릿 가져오기 실패, 오류 메시지: {}",
"GET_POST_SCAFFOLD_FAILED": "게시물 템플릿 가져오기 실패, 오류 메시지: {}",
"GET_SCRIPTS... | Python | 1 |
ame>query-engine/core/src/schema_builder/output_types/mutation_type.rs
use crate::constants::inputs::args;
use super::*;
use datamodel_connector::ConnectorCapability;
use input_types::input_fields;
use prisma_models::{dml, PrismaValue};
/// Builds the root `Mutation` type.
#[tracing::instrument(skip(ctx))]
pub(crate)... | Rust | 0 |
u" \u251c\u25cb axle",
u" \u251c\u25cb wheel_left",
u" \u2514\u25cb wheel_right\n",
]))
def test_prefix(self):
obj = CubeStack()
tree_str = obj.tree_str(name='cubestack', prefix="--")
self.assertEqual(tree_str, '\n'.join([
u"--cubesta... | Python | 1 |
f):
import torch
feature_extractor = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict())
np_speech_inputs = np.random.rand(100).astype(np.float64)
py_speech_inputs = np_speech_inputs.tolist()
for inputs in [py_speech_inputs, np_speech_inputs]:
... | Python | 1 |
gpio_pin.write(self.value)?;
Ok(None)
}
}
#[derive(Debug, StructOpt)]
/// Set the I/O mode of a GPIO pin (Input/OpenDrain/PushPull).
pub struct GpioSetMode {
#[structopt(name = "PIN", help = "The GPIO pin to modify")]
pub pin: String,
#[structopt(
name = "MODE",
possible_... | Rust | 0 |
dir = -dir;
}
let rot = UnitQuaternion::rotation_between(&Vector3::x(), &dir);
local_pose *= Translation3::from(center.coords) * rot.unwrap_or(UnitQuaternion::identity());
ColliderDesc::Capsule(capsule.radius, capsule.height())
} else if let Some(trimesh) = shape.as_trim... | Rust | 0 |
{
let mut hasher = std::collections::hash_map::DefaultHasher::new();
self.value.hash(&mut hasher);
hasher.finish()
}
}
impl<T: Hash> Deref for Hashed<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.value
}
}
impl<T: Hash> DerefMut for Hashed<T> {
fn ... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.