text string | label_name string | labels int64 |
|---|---|---|
(NixErrno::ENODEV)) =>
return Ok (None),
Err (NixError::Sys (errno)) =>
return Err (
format! (
"Os error {} getting device info",
errno)),
Err (error) =>
return Err (
format! (
"Unknown error getting device info: {}",
error)),
_ => (),
};
Ok (Some (
DeviceInfo {
d... | Rust | 0 |
IAL>;
#[doc = "Register RF_CRC_POLYNOMIAL `reset()`'s with value 0"]
impl crate::ResetValue for super::RF_CRC_POLYNOMIAL {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "CRC polynomial. It is coded using the Koopman notation, i.e. the nth bit codes the (n+1) c... | Rust | 0 |
_LEN: u32 = 4096;
/**< Number of maximum resolution level authorized */
pub const OPJ_J2K_MAXRLVLS: u32 = 33;
/**< Number of maximum sub-band linked to number of resolution level */
pub const OPJ_J2K_MAXBANDS: u32 = (3*OPJ_J2K_MAXRLVLS-2);
pub const OPJ_J2K_DEFAULT_NB_SEGS: u32 = 10;
/** 1 m... | Rust | 0 |
import time
from multiprocessing import Queue
from queue import Empty
from typing import Optional
from voice_dialogue.audio.player import play_audio
from voice_dialogue.core.base import BaseThread
from voice_dialogue.core.constants import voice_state_manager, silence_over_threshold_event
from voice_dialogue.models.voi... | Python | 1 |
# metrics.py
from typing import Dict
import re
DISALLOWED = {"hate", "kill", "bomb"} # simple example
def keyword_coverage(output: str, keywords: set) -> float:
hits = sum(1 for kw in keywords if re.search(rf"\b{re.escape(kw)}\b", output, re.IGNORECASE))
return hits / len(keywords) if keywords else 1.0
def ... | Python | 1 |
as"])
if start_lat is not None and start_lon is not None:
hits = _sort_by_distance(hits, start_lat, start_lon)
if wants_near:
hits = _filter_by_radius_km(hits, start_lat, start_lon, radius_km=1.5)
n_target = _target_count_for_intent(intent, bootstrap) # 6
... | Python | 1 |
startswith('backbone.'):
# state_dict[k[9:]] = v
# else:
# state_dict[k] = v
# # load state_dict
# load_state_dict(model, state_dict, strict, logger)
# return checkpoint
#
#
# def get_state_dict(filename, map_location='cpu'):
# """Get state_dict from a file or URI.
#
# ... | Python | 1 |
# Ahora destruyo tu funcion ekisde
def sumar(*n, i = 10) :
i = 1000 + i
return i - sum(n)
print(sumar(1,22,100))
| Python | 1 |
import torch
import timm
import numpy as np
from torch import nn
# from . import losses
from .point_encoder import PointcloudEncoder
class Uni3D(nn.Module):
def __init__(self, point_encoder):
super().__init__()
self.logit_scale = nn.Parameter(torch.ones([]) * np.log(1 / 0.07))
self.point_e... | Python | 1 |
ugalos::client::config::Client as ConfigRpcClient;
use libfrugalos::entity::bucket::{Bucket, BucketSummary};
use libfrugalos::entity::device::{Device, DeviceSummary};
use libfrugalos::entity::server::{Server, ServerSummary};
use std::net::SocketAddr;
use url::Url;
use crate::daemon::FrugalosDaemonHandle;
use crate::de... | Rust | 0 |
import pandas as pd
import massbalancemachine as mbm
def test_dataloader():
data = pd.read_csv(
"./notebooks/example_data/iceland/files/iceland_monthly_dataset.csv"
)
cfg = mbm.Config(seed=30)
# Create a new DataLoader object with the monthly stake data measurements
dataloader = mbm.data... | Python | 1 |
ction_cutter.cut_coords_downsampled[i, 2:]))
mask.append(TF.crop(_[2], *self.prediction_cutter.cut_coords_downsampled[i, 2:]))
pred = torch.cat(pred, dim=2)
mask = torch.cat(mask, dim=2)
elif self.predict_mode == self.prediction_cutter.PredictMode.PATCH:
orig_... | Python | 1 |
SULT,
pub pszInformation: ::windows_sys::core::PCWSTR,
}
impl ::core::marker::Copy for LOGGING_PARAMETERS {}
impl ::core::clone::Clone for LOGGING_PARAMETERS {
fn clone(&self) -> Self {
*self
}
}
#[doc = "*Required features: `\"Win32_System_Iis\"`*"]
pub const MB_DONT_IMPERSONATE: u32 = 9033u32;
#[d... | Rust | 0 |
e
//! vertex attributes from its [`Geometry`].
//!
//! The range of graphics pipelines available range from simple sprite rendering to
//! physically based rendering.
//!
//! ## 3D format loading
//!
//! ### glTF 2.0
//!
//! `three` comes equipped with support for rendering and animating glTF scenes.
//!
//! See [`Fact... | Rust | 0 |
}
}
impl LaneEntry {
pub fn new_entries(v: Vec<Arc<ModelEntry>>, lane: &Weak<BarLane>) -> Vec<Arc<LaneEntry>> {
let mut pos = 0.0;
v.into_iter()
.enumerate()
.map(|(index, entry)| {
let in_bar_pos = pos;
pos += Units::from(entry.as_ref().du... | Rust | 0 |
}
cups
}
fn get_data(input: &str) -> Result<Vec<usize>> {
let data: Vec<_> = input
.lines()
.next()
.ok_or_else(|| Error::from(ErrorKind::InvalidData))?
.chars()
.map(|c| {
c.to_digit(10)
.map(|d| d as usize)
.ok_or_else(|| Er... | Rust | 0 |
mmon::paste())
}
fn build_interpreter() -> Menu<AppState> {
Menu::new(LocalizedString::new("Interpreter"))
.entry(
MenuItem::new(LocalizedString::new("Go"))
.enabled_if(|data: &AppState, _env| data.input.len() > 0)
.hotkey(SysMods::Cmd, "g")
.comm... | Rust | 0 |
",
"INVALID_DEBIT_BALANCE_SIGNATURE",
"INVALID_CREDIT_BALANCE_SIGNATURE",
"INVALID_FUTURE_CREDIT_SIGNATURE",
"INVALID_CREDIT_SIGNATURE",
"INVALID_FUTURE_DEBIT_SIGNATURE",
"INVALID_DEBIT_SIGNATURE",
"INVALID_FUTURE_CREDIT_FULFILLMENT_SIGNATURE",
"INVALID_CREDIT_FULFILLMENT_SIGNATURE",
];
... | Rust | 0 |
dd_china_map_2cartopy_public(
ax_inset, name='province', edgecolor='black', lw=0.8, zorder=105)
# Set the titles and axes labels
ax_inset.set_title('')
ax.set_title('相当位温, 绝对湿度, 沿剖面风', loc='right', fontsize=25)
ax.set_ylabel('Pressure (hPa)')
ax.set_xlabel('Longitude')
Qv_colorbar.s... | Python | 1 |
"""
Telegram integration: Listener and signal parser with detailed logging.
Supports Anna, Precisiontrike, and OTC signal formats.
Handles multiple timezones and prepares signals for core.py trading.
"""
from telethon import TelegramClient, events
import re
from datetime import datetime, timedelta
import logging
# ==... | Python | 1 |
import matplotlib.pyplot as plt
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, avg
import pandas as pd
import os
os.environ['JAVA_HOME'] = "/opt/bitnami/java" # 根据实际情况修改
# 初始化 Spark Session
spark = SparkSession.builder \
.appName("SerenGPUUsageHistogram") \
.master("spark://localh... | Python | 1 |
from typing import Tuple, List
import pandas as pd
import pytest
from autorag.evaluation import evaluate_retrieval_contents
from autorag.schema.metricinput import MetricInput
gt = [
[["Enough for drinking water", "Just looking for a water bottle"]],
[["Do you want to buy some?"]],
]
pred = [
[
"Enough for mixin... | Python | 1 |
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
import geatpy as ea # import geatpy
if __name__ == '__main__':
# 实例化问题对象
problem = ea.benchmarks.TSP('att48')
# 构建算法
algorithm = ea.soea_studGA_templet(
problem,
ea.Population(Encoding='P', NIND=100),
... | Python | 1 |
}
}
// check if the hashmap already contains the given id.k
match map.contains_key(id) {
true => AxialError::KeyDuplicateError(id.to_string()),
false => AxialError::KeyMissingError(id.to_string()),
}
}
// functions takes a vector containing the real coordinates, and the vector... | Rust | 0 |
#!/usr/bin/env python3
"""
Test the PEM formatting fix for v2 JSON responses.
"""
import asyncio
import logging
from src.pytak.crypto_classes import CertificateEnrollment
from cryptography.hazmat.primitives.asymmetric import rsa
import pytest
@pytest.mark.asyncio
async def test_pem_formatting_fix():
"""Test PEM f... | Python | 1 |
) {
// Ditto
}
fn trace(&self, gc: &mut Gc) {
self.trace_fields_except_stack(gc);
self.context.lock().unwrap().stack.trace(gc);
}
}
impl PartialEq for Thread {
fn eq(&self, other: &Thread) -> bool {
self as *const _ == other as *const _
}
}
impl VmType for RootedThr... | Rust | 0 |
import time # for benchmarking
import numpy as np # to optimize the calculations for arrays
from matplotlib import pyplot as plt # to visualize the data
from collections import Counter # to count the most common class
def euclidean_distance(p1, p2):
"""
To calculate the Euclidean distance between 2 points tha... | Python | 1 |
fid, num_bytes=24, format_char_sequence="iiQQ")
camera_id = camera_properties[0]
model_id = camera_properties[1]
model_name = CAMERA_MODEL_IDS[camera_properties[1]].model_name
width = camera_properties[2]
height = camera_properties[3]
n... | Python | 1 |
(alloc)]
#![feature(arc_counts)]
#![feature(asm)]
#![feature(collections)]
#![feature(const_fn)]
#![feature(core_intrinsics)]
#![feature(drop_types_in_const)]
#![feature(heap_api)]
#![feature(integer_atomics)]
#![feature(never_type)]
#![feature(thread_local)]
#![no_std]
use arch::interrupt;
/// Architecture specific ... | Rust | 0 |
c>>,
ambient_light: AmbientLight,
background: Option<SkyBox>,
root: Box<Traceable + Send + Sync>) -> Scene {
let mut scene = Scene::new();
scene.ambient_light = ambient_light;
for light in lights.into_iter() {
scene.add_light(light);
... | Rust | 0 |
class Matcher:
def __init__(self, routes):
self._routes = routes
def match_request(self, request):
for route in self._routes:
match_dict = {}
rest = request.path
value = True
for typ, data in route.segments:
if typ == 'exact':
... | Python | 1 |
id_list = []
direction = False
add_down_step = False
for i in range(count - 1):
if add_down_step == True:
add_down_step = False
grid_list.append((3, True))
elif direction == True:
if (row_counter % 2) == 0:
... | Python | 1 |
), x).doit())
def test_sympyissue_23562():
assert dsolve(f(x).diff(x) + g(y), f(x)) == Eq(f(x), C1 - x*g(y))
assert dsolve(f(x).diff(x) + g(y).diff(y),
f(x)) == Eq(f(x), C1 - x*g(y).diff(y))
def test_sympyissue_23702():
assert dsolve(f(x).diff(x) - f(x), f(x),
init={f... | Python | 1 |
ncident_role_id"],
["incident_role.id"],
),
sa.ForeignKeyConstraint(
["tag_id"],
["tag.id"],
),
sa.PrimaryKeyConstraint("incident_role_id", "tag_id"),
)
op.create_table(
"incident_role_incident_type",
sa.Column("incident_role_id... | Python | 1 |
lf.intra_module)):
description_encodings = self.intra_module[idx](
description_encodings)
description_encodings = description_encodings.permute(
1, 0, 2).contiguous()
description_encodings = description_encodings.max(dim=1)[0]
description_encodings = self... | Python | 1 |
from django.urls import path
from . import views
app_name = "account"
urlpatterns = [
# account
path("", views.view_user, name="view_user"),
path("<int:user_pk>/", views.view_user, name="view_user"),
path("<int:user_pk>/edit/", views.edit_user, name="edit_user"),
path("<int:user_pk>/delete/", view... | Python | 1 |
{
pub fn new(timer: &dyn Timer) -> Self {
let t0 = timer.seconds();
TimerStopwatch { t0 }
}
}
impl Stopwatch for TimerStopwatch {
fn reset<T>(&mut self, timer: &T)
where T: Timer {
self.t0 = timer.seconds();
}
fn elapsed<T>(&self, timer: &T) -> Seconds
where T: Timer {
timer.seconds() - self.t0
}
}
... | Rust | 0 |
"""Settings for the API service."""
from pydantic import BaseModel
import os
_SYMPTOM_REGISTRY_DEFAULT = os.path.abspath(
os.path.join(os.path.dirname(__file__), "..", "registry", "symptoms.yml")
)
class Settings(BaseModel):
app_env: str = os.getenv("APP_ENV", "dev")
host: str = os.getenv("HOST", "0.0.0... | Python | 1 |
: usize) {
if vec.capacity() < len {
vec.reserve(len - vec.capacity());
}
if vec.len() < len {
vec.set_len(len);
}
}
let lines = builder.build(|_| None);
let len = lines.lengths.iter().copied().sum::<usize>();
unsafe {
reserve_if_required(... | Rust | 0 |
Err(_) => {
always_error(MshParserErrorKind::ValueOutOfRange(ValueType::UnsignedInt))(i)
}
},
Err(e) => Err(e),
}) as for<'a> fn(&'a [u8]) -> IResult<&'a [u8], T, MshParserError<&'a [u8]>>
}
}
}
pub... | Rust | 0 |
log_nx = torch.zeros(N) #needs to be implemented, this is the noise samples
log_ny = torch.zeros(N) # maybe just noise
log_J1_denom = torch.logsumexp(torch.stack([torch.log(torch.tensor(N))+log_prob_data,torch.log(torch.tensor(M))+log_nx],dim=-1), dim=-1)
log_J2_denom = torch.logsume... | Python | 1 |
on("sphere-ray", |b| {
b.iter(|| {
let ray = Ray {
origin: Vec3::from_single(0.0),
direction: Vec3::new(0.0, 0.0, 1.0),
};
sphere.intersect(ray).unwrap();
})
});
}
pub fn rendering(c: &mut Criterion) {
c.bench_function("renderi... | Rust | 0 |
x_min = agent_x.min()
num_steps = 20
step_dist = (x_max - x_min) / num_steps
line_x = np.arange(x_min, x_max, step_dist)[:, np.newaxis]
line_y_ransac = ransac.predict(line_x)
y_min = line_y_ransac.min()
y_max = line_y_ransac.max()
plt.scatter(
... | Python | 1 |
funBody = _jsToPy(funBody)
return '\n' + funBody + '\n'
return funBody
def play_video(url):
if 'watch?v=' in url:
a, b = url.split('?')
find = b.split('&')
for item in find:
if item.startswith('v='):
url = item[2:]
break
... | Python | 1 |
se std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::sync::Arc;
use std::time::Duration;
use tokio::time::delay_for;
#[tokio::test]
async fn test_await() {
let count = Arc::new(AtomicUsize::new(0));
let wg = WaitGroup::new();
for _ in 0..10 {
let wg = wg.clone();
wg... | Rust | 0 |
time,
stream.start_time,
stream.end_time,
)
.execute(&pool)
.await
.map_err(Error::Database)?;
}
Ok(StatusCode::OK)
}
fn parse_xml(xml: &str) -> Option<(String, String, String)> {
let doc = roxmltree::Document::parse(xml).ok()?;
let video_id = d... | Rust | 0 |
simulation time per simulation (slope).
//!
//! Many small benchmarks on toy examples are tracked to guide the
//! development. To compare the performance with other software,
//! we used a real-world model of low-medium size (9 species and 16
//! reactions): the Vilar oscillator (*Mechanisms of noise-resistance
//! ... | Rust | 0 |
# import streamlit as st
# import google.generativeai as genai
# genai.configure(api_key=st.secrets["GEMINI_API_KEY"])
# for model in genai.list_models():
# print(model.name)
# # def generate_resume_summary(name, email, phone, skills, experience , linkedin , github , projects, education, ):
# # prompt = f"""
... | Python | 1 |
'''OpenGL extension ANDROID.framebuffer_target
This module customises the behaviour of the
OpenGL.raw.EGL.ANDROID.framebuffer_target to provide a more
Python-friendly API
The official definition of this extension is available here:
http://www.opengl.org/registry/specs/ANDROID/framebuffer_target.txt
'''
from OpenGL ... | Python | 1 |
from socket import *
serverPort = 12000
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind(('', serverPort))
print("UDP Server Socket binded to " + str(serverPort))
while True:
message, clientAddress = serverSocket.recvfrom(2048)
print(message)
modifiedMessage = message.decode().upper()
serve... | Python | 1 |
FR, FC, LFE, BL, BR, FLC, FRC, BC,
* SL, SR, TC, TFL, TFC, TFR, TBL, TBC, TBR, DL, DR);
* - a number of channels, in decimal, optionally followed by 'c', yielding
* the default channel layout for that number of channels (@see
* av_get_default_channel_layout);
* - a channel layout mask, in hexadecimal starti... | Rust | 0 |
new_copy(&S.getpy());
let mut A = ECP2::new();
let mut B = ECP2::new();
let mut r = FP12::new_int(1);
A.copy(&P);
B.copy(&R);
let mut NP = ECP2::new();
NP.copy(&P);
NP.neg();
let mut NR = ECP2::new();
NR.copy(&R);
NR.neg();
let nb=lbits(&mut n3,&mut n);
for i in ... | Rust | 0 |
EPOCH))
.add_file("board", "x64")
.add_file("zbi", "fake zbi")
.add_file("bootloader", "new bootloader");
env.run_update().await.expect("success");
assert_eq!(resolved_urls(Arc::clone(&env.interactions)), vec![UPDATE_PKG_URL]);
}
#[fasync::run_singlethreaded(test)]
async fn rejects_mi... | Rust | 0 |
pub const GPUREG_0288: u32 = 648;
pub const GPUREG_GSH_INPUTBUFFER_CONFIG: u32 = 649;
pub const GPUREG_GSH_ENTRYPOINT: u32 = 650;
pub const GPUREG_GSH_ATTRIBUTES_PERMUTATION_LOW: u32 = 651;
pub const GPUREG_GSH_ATTRIBUTES_PERMUTATION_HIGH: u32 = 652;
pub const GPUREG_GSH_OUTMAP_MASK: u32 = 653;
pub const GPUREG_028E: u... | Rust | 0 |
: types::GLenum = 0x82CD;
pub const VIEW_CLASS_S3TC_DXT3_RGBA: types::GLenum = 0x82CE;
pub const VIEW_CLASS_S3TC_DXT5_RGBA: types::GLenum = 0x82CF;
pub const VIEW_COMPATIBILITY_CLASS: types::GLenum = 0x82B6;
pub const WAIT_FAILED: types::GLenum = 0x911D;
pub const WRITE_ONLY: types::GLenum = 0x88B9;
pub const XOR: type... | Rust | 0 |
unsafe {
instance.get(GetAclStatusRequestProto::new)
}
}
// required string src = 1;
pub fn clear_src(&mut self) {
self.src.clear();
}
pub fn has_src(&self) -> bool {
self.src.is_some()
}
// Param is passed by value, moved
pub fn set_src(&... | Rust | 0 |
reate a session
config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth = True
config.allow_soft_placement = True
config.log_device_placement = False
sess = tf.compat.v1.Session(config=config)
# Add summary writers
merged = tf.summary.merge_all()
... | Python | 1 |
import logging
from discord.ext import commands
logger = logging.getLogger(__name__)
async def is_admin(ctx) -> bool:
"""
Only an admin can sync guild commands.
Doing this too much will cause a ratelimit
"""
return ctx.message.author.guild_permissions.administrator
class CommandSync(commands.C... | Python | 1 |
import numpy as np
import matplotlib.pyplot as plt
#M_r = 0.5e6 (A/m)
#H_c (coercivity) = 25000 - 30000 A/m (Jiles book)
# Langevin with AA
def L_AA (x, x_1):
if (abs (x - x_1) > 10 ** -2):
return (L_I (x) - L_I (x_1)) / (x - x_1)
else:
return L (0.5 * x + 0.5 * x_1)
# Langevin derivative wit... | Python | 1 |
import os
import requests
import argparse
from common import download_image
def fetch_spacex_image_urls(api_url, flight_id=None):
url = f"{api_url}/{flight_id}" if flight_id else api_url
response = requests.get(url)
response.raise_for_status()
launch_data = response.json()
image_urls = launch_data... | Python | 1 |
"""
ip:-
hello:5438,car:214,book:8799,apple:2187
length of word in number then place that character if length of word not in number then take next small number near to length and keep that character if it is not their then place x
hello length=5 5 in 5438 so o
car length=3 3 not in 214 next small is 2 2... | Python | 1 |
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
j = 0
i = 1
while i < len(nums):
if nums[i] == nums[j]:
del nums[i]
else:
i += 1
j += 1 | Python | 1 |
dog { name }
}
"#,
);
}
#[test]
fn list_variables_with_invalid_item() {
expect_fails_rule!(
factory,
r#"
query InvalidItem($a: [String] = ["one", 2]) {
dog { name }
}
"#,
);
}
}
<gh_stars>0... | Rust | 0 |
es = ["cockroachdb"]
}
model NativeTypesTest {
id Int @db.Int4 @id @default(autoincrement())
bitcol String @db.Bit
boolcol Boolean @db.Bool
bytescol Bytes @db.Bytes
charcol String @db.Char(5)
datecol DateTime @db.Date
... | Rust | 0 |
lass or interface, ty list are the arguments
/// If exact=Exact, then this represents instances of *exactly* this class
/// If exact=Nonexact, this also includes subclasses
Tclass(Positioned<TypeName, R::Pos>, Exact, Vec<TY>),
Tvar(Tyvar),
}
walkable!(impl<R: Reason, TY> for Ty_<R, TY> => {
Ty_::... | Rust | 0 |
help = "Organize by language",
long_help = "Organizes line counts by language instead of filename"
)]
by_lang: bool,
#[clap(
long,
short = 'A',
help = "Sort alphabetically",
long_help = "Sorts line counts alphabetically, instead of by line count"
)]
alphabetical: bool,
#[clap(
long,
short = 'R',
h... | Rust | 0 |
``"1"`` is equivalent to ``"qBde"``.
:q: Educates normal quote characters: (") and (').
:b: Educates \`\`backticks'' -style double quotes.
:B: Educates \`\`backticks'' -style double quotes and \`single' quotes.
:d: Educates em-dashes.
:D: Educates em-dashes and en-dashes, using old-school typew... | Python | 1 |
I) { self.body = Some(body.clone()); }
fn set_id(&mut self, id: u64) { self.id = id; }
}
pub fn __decode_and_call<Request, Response, F, C>(ctx: Context, codec: &C, body: &[u8], mut f: F, res: &mut TransportResponse)
-> Result<(), ServeRequestError>
where F: FnMut(Context, <<C as Codec<Request>>::M as Messa... | Rust | 0 |
: i32) -> &'static str {
return RANK_DESCRIPTION[rank as usize][1];
}
pub const fn describe_sample_hand(rank: i32) -> &'static str {
return RANK_DESCRIPTION[rank as usize][0];
}
pub const fn is_flush(rank: i32) -> bool {
let return_val: bool = match get_rank_category(rank) {
RankCategory::Straight... | Rust | 0 |
dc = pre_im[2] + cart_im[[k, 2]];
d = da * da + db * db + dc * dc;
if d < best {
best = d;
}
}
distances[[i, j]] = best.sqrt();
}
}
Ok(distances)
}
#[inline]
fn _gram_schmidt_process(basis: &Array2<Fl... | Rust | 0 |
#!/usr/bin/env python3
"""
Test script for enhanced trading system with API-first, database-fallback price fetching
"""
import sys
import os
# Add the backend directory to the Python path
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, project_root)
sys.path.insert(0, os.... | Python | 1 |
status_code=status.HTTP_400_BAD_REQUEST,
detail={"error": err.message},
)
return ApiResponse(data=OutAuthorSchema.from_entity(author))
@router.delete(
"/{author_id}/",
status_code=status.HTTP_204_NO_CONTENT,
description="Delete author",
responses={
status.HTTP_400_BAD_... | Python | 1 |
{
let env = __jni_bindgen::Env::from_ptr(self.0.env);
let (class, field) = env.require_class_field("android/view/animation/LayoutAnimationController$AnimationParameters\0", "count\0", "I\0");
env.set_int_field(class, field, value)
}
}
/// **ge... | Rust | 0 |
_closure {
($x:expr) => {
($x & Flags::TE_CLOSURE0).bits() != 0
};
}
macro_rules! arity {
($x:expr) => {
if ($x & (Flags::TE_FUNCTION0 | Flags::TE_CLOSURE0)).bits() != 0 {
$x.bits() & 0x00000007
} else {
0
}
};
}
#[derive(Debug, Copy, Clone, Part... | Rust | 0 |
lf._original_backstory = self.backstory
if inputs:
self.role = interpolate_only(
input_string=self._original_role, inputs=inputs
)
self.goal = interpolate_only(
input_string=self._original_goal, inputs=inputs
)
self.bac... | Python | 1 |
e)
if flag >= 1:
assert (len(value) == len(label))
all_text.append(value)
all_label.append(label)
else:
label, flag = build_ner_data.make_text_label(text)
... | Python | 1 |
self.result = ""
def run(self):
try:
# 构建system提示词和用户提示词
system_prompt = """你是一个专业的茶园环境数据分析专家。你需要分析茶园的环境监测数据,并提供专业、详细的分析报告。
你的分析应该:
1. 基于科学依据和茶叶种植的最佳实践
2. 重点关注影响茶叶生长质量的关键环境因素
3. 及时发现潜在的环境风险
4. 提供具体可行的改进建议
5. 基于MarkDown格式输出结果,确保格式清晰易读且美观,不要使用表格"""
user_prompt = f""... | Python | 1 |
status}, Banner: {banner}")
# Write data to the file
with open(file_path, "w") as file:
file.write("\n".join(data))
# Notify the user that the file has been saved
tk.messagebox.showinfo("Success", f"Work saved to {file_path}")
except Exception as e:
tk.m... | Python | 1 |
# This file was auto-generated by Fern from our API Definition.
import typing
import typing_extensions
from .customer_segment import CustomerSegmentParams
from .error import ErrorParams
class ListCustomerSegmentsResponseParams(typing_extensions.TypedDict):
"""
Defines the fields that are included in the res... | Python | 1 |
load routine,
# which probably corresponds to a correct CRC
# if self.last_success_event and (self.last_success_event + 1) != packet_event_ctr:
# internalblue.logger.debug(" ^----------------------------- MISSED -------------------------------")
# TODO example for setting... | Python | 1 |
Err(err)
}
},
#[cfg(unix)]
ManagerDatagram::UnixDatagram(ref mut unix) => match *target {
ManagerSocketAddr::UnixSocketAddr(ref saddr) => match saddr.as_pathname() {
Some(paddr) => unix.send_to(buf, paddr).await,... | Rust | 0 |
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2014 Grupo de Sistemas Inteligentes (GSI) DIT, UPM
#
# 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://... | Python | 1 |
let mut instruction = Instruction { ..Default::default() };
while let Some((key, value)) = access.next_entry::<String, String>()? {
match key.as_str() {
"@type" => continue, // TODO: handle @type
"text" => instruction.text = value,
... | Rust | 0 |
, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Value::Null => write!(f, "null"),
Value::Bool(b) => write!(f, "{}", b),
Value::Number(n) => write!(f, "{}", n),
Value::Str(ref s) => write!(f, "{}", s),
Value::NativeFun... | Rust | 0 |
MORPHER_PHONEME_AO: i32 = 8;
pub const AL_VOCAL_MORPHER_PHONEME_EH: i32 = 9;
pub const AL_VOCAL_MORPHER_PHONEME_ER: i32 = 10;
pub const AL_VOCAL_MORPHER_PHONEME_IH: i32 = 11;
pub const AL_VOCAL_MORPHER_PHONEME_IY: i32 = 12;
pub const AL_VOCAL_MORPHER_PHONEME_UH: i32 = 13;
pub const AL_VOCAL_MORPHER_PHONEME_UW: i32 = 14... | Rust | 0 |
2, "MinPositionLimit", 52, Word, RW),
Reg::new("XH540-V150", V2, "ExternalPortMode1", 56, Byte, RW),
Reg::new("XH540-V150", V2, "ExternalPortMode2", 57, Byte, RW),
Reg::new("XH540-V150", V2, "ExternalPortMode3", 58, Byte, RW),
Reg::new("XH540-V150", V2, "StartupConfiguration", 60, Byte, RW),
Reg::ne... | Rust | 0 |
ize> = std::env::args()
.skip(1)
.map(|s| s.parse().unwrap())
.collect();
let n = ns[0];
let r = ns[1] as usize;
let mut a: Vec<isize> = (0..n).collect();
shuffle(&mut a, r);
let na = a.len();
quicksort(&mut a, 0, na - 1);
println!("{}", a[0]);
}
<reponame>ddimaria/ru... | Rust | 0 |
from django.apps import AppConfig
class AlertaresultadoConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'AlertaResultado'
| Python | 1 |
import _plotly_utils.basevalidators
class VisibleValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(
self, plotly_name="visible", parent_name="scatter3d.error_x", **kwargs
):
super(VisibleValidator, self).__init__(
plotly_name=plotly_name,
parent_nam... | Python | 1 |
straintField<CF>,
PC::Commitment: ToConstraintField<CF>,
PCG::VerifierKeyVar: ToConstraintFieldGadget<CF>,
PCG::CommitmentVar: ToConstraintFieldGadget<CF>,
{
#[tracing::instrument(target = "r1cs", skip(cs, f))]
fn new_variable<T>(
cs: impl Into<Namespace<CF>>,
f: impl FnOnce() -> Res... | Rust | 0 |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from fairseq.data.legacy.masked_lm_dictionary import MaskedLMDictionary
from fairseq.tasks.translation import TranslationTask
from . import r... | Python | 1 |
debug_assert!(j < self.nr_columns());
// TODO(ARCHITECTURE): Can the +/- F::one() constants be avoided? They might be large and
// require an allocation.
match self.column_type(j) {
ColumnType::Normal(j) => {
Column::Sparse {
// TODO(ENHA... | Rust | 0 |
#
# SPDX-License-Identifier: MIT
#
# Copyright (c) 2025 Carsten Igel.
#
# This file is part of simplepycons
# (see https://github.com/carstencodes/simplepycons).
#
# This file is published using the MIT license.
# Refer to LICENSE for more information
#
""""""
# pylint: disable=C0302
# Justification: Code is generated
... | Python | 1 |
greeks = ('alpha', 'beta', 'gamma', 'delta', 'epsilon', 'zeta',
'eta', 'theta', 'iota', 'kappa', 'lambda', 'mu', 'nu',
'xi', 'omicron', 'pi', 'rho', 'sigma', 'tau', 'upsilon',
'phi', 'chi', 'psi', 'omega')
| Python | 1 |
#!/usr/bin/python
#
# parse-uploadstream.py
#
# Copyright (C) Wolfgang Sourdeau 2011
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any ... | Python | 1 |
# Should have basic health rules
assert "health-baseline" in rule_ids
assert "health-smoking-signage" in rule_ids
# Should have delivery rules
assert "delivery-rules" in rule_ids
# Should have gas rules
assert "gas-cert" in rule_ids
assert "hood-suppression" in rule_ids
... | Python | 1 |
val, Lookahead<Adamax>>
{
/// Shortcut for ES::new(...) using Lookahead with Adamax:
/// Create a new ES-Optimizer using Lookahead with Adamax (create Lookahead and Adamax object with the given parameters, rest left to default).
/// Change these paramters using method get_opt_mut().set_<...>(...) and get_op... | Rust | 0 |
cartridge: &'a mut dyn Cartridge,
}
impl<'a> Mmu<'a> {
pub fn new(
cartridge: &'a mut dyn Cartridge,
gpu: &'a mut Gpu,
apu: &'a mut Apu<'a>,
) -> Mmu<'a> {
Mmu {
gpu,
timer: Timer::new(),
interrupts: InterruptState::new(),
apu... | Rust | 0 |
ten to multiple variants at once:
dispatcher.add_listener(EventEnum::EventVariantB, &listener);
// Dispatches our events to all listeners.
dispatcher.dispatch_event(&EventEnum::EventVariantA);
dispatcher.dispatch_event(&EventEnum::EventVariantB);
// If you want to work with a closure, you can do t... | Rust | 0 |
xtent = initial_extent + 100; // n_iterations = 100
let size = extent as usize;
let map = Array2::zeros((2 * size + 1, 2 * size + 1));
let mut this = Self {
map,
ref_q: extent,
ref_r: extent,
};
for &(x, y, _) in counts
.distinct_el... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.