text
string
label_name
string
labels
int64
# -*- coding: utf-8 -*- from __future__ import absolute_import from django.db import models, migrations class Migration(migrations.Migration): """ Migration to alter email-related fields in the Queue, Ticket, and TicketCC models. This migration modifies the following fields to allow null and blank valu...
Python
1
#!/usr/bin/env python from vtkmodules.vtkIOCore import ( vtkGlobFileNames, vtkSortFileNames, ) from vtkmodules.vtkIOImage import vtkImageReader2 from vtkmodules.vtkInteractionImage import vtkImageViewer import vtkmodules.vtkInteractionStyle import vtkmodules.vtkRenderingFreeType import vtkmodules.vtkRenderingOp...
Python
1
oreignState { log: log.new(slog::o!("smithay_module" => "xdg_foreign_handler")), exports: vec![], shell: xdg_shell_state.clone(), })); // Borrow checking does not like us cloning the state inside the filter's closure so we clone // now and pass the clones into the closure. let e...
Rust
0
lid age. Please return to the inventory and change your response.""" # Save Data if db: responses = " ".join([str(i) for i in Q[1:121]]) db.execute('insert into RESULTS values(?, ?, ?, ?, ?, ?)', (datetime.datetime.now(), Sex, Age, Nick, Country, resp...
Python
1
; } return steps; } #[cfg(test)] mod tests { #[test] fn part1() { assert_eq!(5, super::part1(&mut vec![0, 3, 0, 1, -3])); } #[test] fn part2() { assert_eq!(10, super::part2(&mut vec![0, 3, 0, 1, -3])); } }use std::str::FromStr; use xml::{Element, Eleme...
Rust
0
```Embedded(~BsonDocument)```, i.e. it is represented as a BSON): // insert a document into bar_coll let ins = ~"{ \"_id\":0, \"a\":0, \"msg\":\"first insert!\" }"; bar.insert(ins, None); // no write concern specified---use default // insert a big batch of documents into foo_coll let mut i...
Rust
0
# -*- coding: utf-8 -*- # Copyright (C) 2024 BIRU # # This file is part of Tenzu. # # Tenzu is free software: you can redistribute it and/or modify it # under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or (at your option) any later...
Python
1
and(&mut snes.cpu, &mut snes.abus); // Update cycle count to prevent warping emulated_clock_ticks = time_source.elapsed_ticks(); } DebugState::Step => { // Go through steps snes.run_steps(debugger.steps, |cpu, mut abus| { ...
Rust
0
import pytest from endoc.models.paginated_search import PaginatedSearchData, PaginatedSearchResponseBody, Content, AbstractParsedItem, Author, PublicationDate @pytest.fixture def mock_paginated_search_response(): """Sample response for paginated_search wrapped in 'data'.""" return { "data": { ...
Python
1
T> where T: Ord + FromFlatBuffer<F::Inner>, F: fbrt::Follow<'a> + 'a, { fn from_flatbuf(fb: fbrt::Vector<'a, F>) -> ::std::result::Result<Self, String> { let mut vec = ddlog_std::Vec::with_capacity(fb.len()); for x in FBIter::from_vector(fb) { vec.push(T::from_flatbuf(x)?); ...
Rust
0
) } /// Returns the low-order `u32` of an `u64`. pub const fn LODWORD(v: u64) -> u32 { (v & 0xffff_ffff) as _ } /// [`LOWORD`](https://docs.microsoft.com/en-us/previous-versions/windows/desktop/legacy/ms632659(v=vs.85)) /// function. Originally a macro. pub const fn LOWORD(v: u32) -> u16 { (v & 0xffff) ...
Rust
0
tub { dev: Box::new(devices::virtio::VideoDevice::new( virtio::base_features(cfg.protected_vm), typ, backend, Some(resource_bridge), )), jail, }) } #[cfg(any(feature = "video-decoder", feature = "video-encoder"))] fn register_video_device( ...
Rust
0
serializer, Error as DeserializeError, Visitor}; #[derive(Debug, PartialEq, Eq)] pub(super) enum ExceptionType { Added, Removed, } impl<'de> Deserialize<'de> for ExceptionType { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct Servic...
Rust
0
SubCommand::Prove(o) => { prove(o); } SubCommand::Verify(o) => { verify(o); } SubCommand::Setup(o) => { setup(o); } SubCommand::GenerateVerifier(o) => { generate_verifier(o); } SubCommand::ExportKeys(o...
Rust
0
use super::Parity::{Even, Odd}; use super::*; #[test] fn mul() { assert_eq!(Even * Even, Even); assert_eq!(Even * Odd, Odd); assert_eq!(Odd * Even, Odd); assert_eq!(Odd * Odd, Even); } #[test] fn from_number() { assert_eq!(Parity::from_number(0), Eve...
Rust
0
fmt::Result { f.debug_struct(&format!("GOnce @ {:p}", self)).finish() } } #[repr(C)] pub struct _GOptionContext { _data: [u8; 0], _marker: core::marker::PhantomData<(*mut u8, core::marker::PhantomPinned)>, } pub type GOptionContext = *mut _GOptionContext; #[derive(Copy, Clone)] #[repr(C)] pub str...
Rust
0
self.apply_gate(target, y()); #[cfg(feature = "decoherence")] self.decohere(); } /// Pauli Z Gate /// Shorthand Method /// /// Equivilent to `state.apply_gate(target, z());` pub fn z(&mut self, target: i32) { self.apply_gate(target, z()); #[cfg(feature = "decoher...
Rust
0
r> { let state = State { callers: Vec::new(), }; config(deps.storage).save(&state)?; Ok(InitResponse::default()) } // And declare a custom Error variant for the ones where you will want to make use of it #[entry_point] pub fn handle( deps: DepsMut, _env: Env, info: MessageInfo, ...
Rust
0
ain the current input format for `decoder` and write it into `format`. /// This function can be called at any time since a decoder always have a valid /// input format. /// /// Returns 0 in case of success, -1 if an error occured, in which case `format` /// is not overwritten. /// /// # Safety /// /// `decoder` must be...
Rust
0
from PIL import Image from src.handlers.classifiers_handler.classifier_handler import ( ResnetClassifierModelHandler, ) from ..test_utils import mock_context from ..fixture_utils import ( create_handler_instance, req_input, preprocessed_image, inference_output, create_parametrize_mock_context, ...
Python
1
from mcp.server.fastmcp import FastMCP mcp = FastMCP("ai-image-description-mcp")
Python
1
cf().region().unwrap_or("unknown region".into()) ); } #[event(fetch)] pub async fn main(req: Request, env: Env) -> Result<Response> { log_request(&req); utils::set_panic_hook(); let router = Router::new(); router .get("/", |req, ctx| { let query_pairs: HashMap<_, _> = req.url()?...
Rust
0
# Optional RestAPI end points import datetime import json from flask import Blueprint, g, jsonify, request from ansible_webx.app.ansible_run_command import run_ansible from ansible_webx.prepare_data.get_data import find_servers, find_tags, find_values_extra_vars_sites, find_keys_extra_vars_sites api_app = Blueprint('...
Python
1
unwrap(); (i, *n) })) } pub fn iter_bounded<'b, U: Sym>( &'b self, bound: usize, ) -> Box<dyn Iterator<Item=(U, usize)> + 'b> { Box::new((0..bound) .map(|i| U::cast(i as u32).unwrap()) .map(move |i| (i, self.get_bounded(i, bound)))...
Rust
0
by the id. fn name(&self, id: FileId) -> Option<&str>; /// Returns the source of the file identified by the id. fn source(&self, id: FileId) -> Option<SourceFile<'_>>; } /// A file database that contains only one file. #[derive(Clone, Debug)] pub struct SimpleFile { name: String, source: String, ...
Rust
0
n_samples=n_rows, n_features=n_cols, centers=10, cluster_std=1.0, center_box=(-10.0, 10.0), random_state=42, ) X_host = X_host.astype(np.float32) X_device = device_ndarray(X_host) ivf_pq_params = None nn_descent_params = None if algo == "ivf_pq"...
Python
1
dir_fd, wasi::RIGHTS_FD_READ, wasi::RIGHTS_FD_READ); let (rbase, rinher) = fd_get_rights(dir_fd); assert_eq!( rbase & wasi::RIGHTS_FD_READ, 0, "dir should not have base RIGHTS_FD_READ" ); assert_eq!( rinher & wasi::RIGHTS_FD_READ, 0, "dir should not have ...
Rust
0
{ pub fn new(parts: Vec<Element>) -> Document { Document { parts: Rc::new(RefCell::new(parts)) } } pub fn accept<T: Visitor + 'static>(&mut self, visitor: &mut T) { self.parts.borrow().iter().for_each(move |p| p.accept(visitor)); } } pub trait Visitor { const END_LIN...
Rust
0
from posthog.cdp.templates.hog_function_template import HogFunctionTemplateDC template: HogFunctionTemplateDC = HogFunctionTemplateDC( status="beta", free=False, type="destination", id="template-gleap", name="Gleap", description="Updates a contact in Gleap", icon_url="/static/services/gleap...
Python
1
'processing_timestamp': self._get_timestamp() }, quality_metrics=quality_metrics ) # 记录聚合历史 self._record_aggregation_history(layer_results, result, context) # 更新层级可靠性 self._update_layer_reliabilit...
Python
1
from core.security.roles import Role ROLE_PERMISSIONS = { Role.SOFTWARE_ADMIN: ["create_organization", "manage_admins", "manage_users","list_organizations","ADMIN_ACCESS"], Role.ORGANIZATION_ADMIN: ["update_user_status","ORG_ADMIN", "create_user", "manage_organization","create_org...
Python
1
> where W: Print + PrintHelper, { pub fn new(config: ConfigManager, printer: W) -> Self { Sahih { config, printer } } pub fn generate(mut self) -> io::Result<()> { debug!("Running with options: {:#?}", self.config); self.printer.print_welcome()?; self.printer.print_targ...
Rust
0
print(str(self.optim.get_lr())) iteration += 1 if self.distributed: dist.barrier() # 每一个Epoch结束保存模型 self.save_model(epoch) # 模型验证测试,返回的val仅用于SCST训练过程 val = self.eval(epoch) # 4(SCST...
Python
1
"path")] manifest_path: Option<String>, /// Verbose mode #[clap(short)] verbose: bool, #[clap(subcommand)] subcommand: Subcommand, } #[derive(Debug, Clap)] #[clap( name = "cargo-workspaces", bin_name = "cargo", version, global_setting(AppSettings::ColoredHelp) )] enum Cargo {...
Rust
0
number of words in the width table;\cr //! |nh|&number of words in the height table;\cr //! |nd|&number of words in the depth table;\cr //! |ni|&number of words in the italic correction table;\cr //! |nl|&number of words in the lig/kern table;\cr //! |nk|&number of words in the kern table;\cr //! |ne|&number of words i...
Rust
0
arseError<Span>> { move |i: Span| { let (i, _) = tag("open")(i)?; let (i, _) = parse_space(i)?; let (i, name) = parse_name(i)?; let (i, _) = parse_space(i)?; let (i, alias) = opt(terminated(parse_alias, parse_space))(i)?; let alias = alias.unwrap_or(String::from("")); let (i, with) = opt(t...
Rust
0
cs() metrics.update(knn_metrics) trainer.log_metrics("eval", metrics) trainer.save_metrics("eval", metrics) self.knn_wrapper.break_out() return perplexity def run_eval_codegen_perplexity(self): # Based on storage on train, we do eval on self.val_dataset...
Python
1
import os from bs4 import BeautifulSoup import requests import csv # Target URL url = "https://elvi.lv/elvi-vakances/" # Replace with the actual URL # Send a GET request to the URL response = requests.get(url) # Check response status if response.status_code == 200: # Parse the HTML content soup = BeautifulS...
Python
1
ssoc::<Name, <Self::Mode as WalkMode>::Elt>::new()))) } fn is_positive() -> bool { false } } pub trait NegativeWalkMode : WalkMode { /// What happens if destructuring fails? fn qlit_mismatch_error(l: Self::Elt, r: Self::Elt) -> Self::Err { panic!("match failure unimplemented: {} vs. {}", l, r) ...
Rust
0
::from_utf8_lossy(&data); let mut next_peers = next_peers.split(','); // we pop the first one and keep others let next_peer = String::from(next_peers.next().unwrap()); (next_peer, next_peers.join(",").into_bytes()) } else { (init_user_id.to_string(), ...
Rust
0
self.body.tasks[0].reprcall(self.tasks), chain(self.body.tasks[1:], app=self._app), ), ) return '%' + remove_repeating_from_task( self.body['task'], self.body.reprcall(self.tasks)) return f'<chord without body: {...
Python
1
ount += 1 # the # is 'extreme' # p-value was 0.062 => ~62 extreme values out of 1000 assert 59 < extreme_value_count < 65, f"{extreme_value_count}" two_sided_p_value(531.5, mu_0, sigma_0) # 0.0463 tspv = two_sided_p_value(531.5, mu_0, sigma_0) assert 0.0463 < tspv < 0.0464 upper_p_value =...
Python
1
from typing import List class ContextualRelevancyTemplate: @staticmethod def generate_reason( input: str, irrelevant_statements: List[str], relevant_statements: List[str], score: float, ): return f"""Based on the given input, reasons for why the retrieval context is...
Python
1
print_special( ". Stoesse: ", vecstoss.iter() .map(|stoss| stoss.epi) .collect() ); }) } pub fn account_balance_string(an: &EnumMap<EPlayerIndex, isize>, n_stock: isize) -> String { EPlayerIndex::values() .map(|epi| format!("{}: {} | ...
Rust
0
""" В двумерном списке найти суммы элементов каждой строки и поместить их в новый массив. Выполнить замену элементов третьего столбца исходной матрицы на полученные суммы. """ # Суммы строк матрицы и замена третьего столбца try: matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] # Пример матрицы print("Ис...
Python
1
import os from bs4 import BeautifulSoup def check_xml(): base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) xml_path = os.path.join(base_dir, 'data', 'momo_sms.xml') try: with open(xml_path, 'r') as file: content = file.read() soup = BeautifulSoup(co...
Python
1
.take(); if let Some(mut stream) = inner { loop { match stream.poll() { Ok(Async::Ready(Some(_))) => {} Ok(Async::Ready(None)) => { return Ok(Async::Ready(())); } Ok(Async::NotRead...
Rust
0
import datetime from flask import current_app from flask_jwt_extended import current_user from lin import db, manager from lin.interface import InfoCrud as Base from sqlalchemy import Column, Integer, String, Boolean, text, SmallInteger from app.libs.enums import EmailStrategyEnum from app.libs.init import scheduler ...
Python
1
rMrNrN]6&-HA x  +  )<)<)>> = y  rPSequenceroverload TYPE_CHECKINGUnion_device_dtype_int ProcessGrouprorBrrrcg)Nr)rrrrBs rMemptyrurPcg)N...
Python
1
########################################################################################## # Copyright (c) 2025 Nordic Semiconductor # SPDX-License-Identifier: LicenseRef-Nordic-5-Clause ########################################################################################## import os import pytest import time from ...
Python
1
0, f"ID_AA64DFR0_EL1={PARSE_INTERVAL_DEFAULT}" assert PARSE_INTERVAL_DEFAULT.startswith("0x"), f"ID_AA64DFR0_EL1={PARSE_INTERVAL_DEFAULT}" assert int(PARSE_INTERVAL_DEFAULT, 16) != 0x00, f"ID_AA64DFR0_EL1={PARSE_INTERVAL_DEFAULT}" def test_wperf_test_pmu_version_name(): """ Check if PMU name format is corr...
Python
1
_config={"tags": ["er-description-summarization"]}, ) # Graph Generator graph_generator = GraphGenerator( er_extractor=entity_extractor, graphs_merger=GraphsMerger(), er_description_summarizer=entity_summarizer, ) # Community Detector community_detector = HierarchicalLe...
Python
1
""" Project Lava Tube Mapping, Technical University of Delft. Author: Alexander James Becoy @alexanderjamesbecoy """ import os from ament_index_python.packages import get_package_share_directory from launch import LaunchDescription from launch.actions import DeclareLaunchArgument from launch.substitutions import Launc...
Python
1
"""uncertainty.py 集成不确定性估计模块 ================== • Deep Ensemble: 训练多个独立模型 • MC-Dropout: 蒙特卡洛 Dropout 采样 • Ensemble + MC 混合策略 • 校准不确定性 (Temperature Scaling) """ from __future__ import annotations import copy from typing import List, Tuple, Dict, Any from pathlib import Path import torch import torch.nn as nn import nu...
Python
1
#!/usr/bin/env python3 import argparse import os import glob import urllib import re import requests # Define API Endpoints for Algorithms and Files URL_ALGORITHMS = '/api/algorithms/store' URL_INPUTFILE = '/api/file-inputs/store' def send(file,url): # Check if url is valid (includes http) if not r...
Python
1
import numpy as np from sklearn.cluster import KMeans class DetectorDeAnomalias: def __init__(self, n_clusters): self.n_clusters = n_clusters self.modelo = KMeans(n_clusters=self.n_clusters, random_state=42, n_init=10) self.limiar_anomalia = None self.centroides_aprendidos = Non...
Python
1
{ f.write_str(".0")?; } Ok(()) } } } #[cfg(not(feature = "no_float"))] impl<F: Float> From<F> for FloatWrapper<F> { #[inline(always)] fn from(value: F) -> Self { Self::new(value) } } #[cfg(not(feature = "no_float"))] impl<F: Float + FromStr> Fro...
Rust
0
NP = EncNP_Shape_ENCODING(input_points, num_stages, embed_dim, k_neighbors, alpha, beta, ratio=ratio, device=device) def forward(self, x, colors, seg_mask): # xyz: point coordinates # x: point features xyz = x.permute(0, 2, 1) colors = colors.permute(0, 2, 1) seg_mask = seg_...
Python
1
ring2b.123".to_string(), ]); assert_that!(local_store.get_ring("ring1a")).is_ok_containing((0u64, ZeroingWords::from(ring1a.as_ref()))); assert_that!(local_store.get_ring("ring1b")).is_ok_containing((1u64, ZeroingWords::from(ring1b1.as_ref()))); assert_that!(local_store.get_ring("ring2a")).is_ok_containing((0u...
Rust
0
teForKey(entry.get().0)), } } pub fn with_state( self, button: impl Into<Button>, id: impl Into<StateId>, ) -> Result<Self, InputContextError> { self.with_state_passthrough(button, id, InputPassthrough::Consume) } pub fn with_range_passthrough( mut s...
Rust
0
"" list_of_models = [] model = PretrainedModelInfo( pretrained_model_name="tts_en_fastspeech2", location="https://api.ngc.nvidia.com/v2/models/nvidia/nemo/tts_en_fastspeech_2/versions/1.0.0/files/tts_en_fastspeech2.nemo", description="This model is trained on LJSpeech...
Python
1
7) .p_t(0.05) .with_cliffords() .build(); let mut g: Graph = c.to_graph(); g.plug_inputs(&vec![BasisElem::Z0; qs]); g.plug_output(0, BasisElem::Z1); g.plug(&g.to_adjoint()); println!("g has T-count: {}", g.tcount()/2); quizx::simplify::full_simp(&mut g); println!("g ...
Rust
0
import logging from pathlib import Path import tempfile from urllib.request import urlretrieve import zipfile import click import pandas as pd logging.basicConfig( format="[%(asctime)-15s] %(levelname)s - %(message)s", level=logging.INFO ) @click.command() @click.option("--start_date", default="2019-01-01", typ...
Python
1
on the corpus with cross-validation and returns the mean cross-validation score. :param corpus: target Corpus (must be annotated with pair information using PairedPrediction.transform()) :param selector: a (lambda) function that takes a Corpus object and returns a bool: True if the object is to be inc...
Python
1
tag: &mut VorbisCommentsRef<'a, II, IP>, writer: &mut Cursor<Vec<u8>>, stream_serial: u32, add_framing_bit: bool, ) -> Result<Vec<Page>> where II: Iterator<Item = (&'a str, &'a str)>, IP: Iterator<Item = (&'a crate::picture::Picture, PictureInformation)>, { const PICTURE_KEY: &str = "METADATA_BLOCK_PICTURE="; ...
Rust
0
in range(1): x = self.get_valid_x_position(50) y = random.choice([self.platforms[0].rect.y - 180, self.platforms[2].rect.y - 250]) self.obstacles.append(CircularSaw((x, y), random.randint(100, 180))) # Увеличиваем скорость лифтов for obstacle in self.obstacles: ...
Python
1
#!/usr/bin/env python # -*- coding: utf-8 -*- """Audio playback backend using SoundDevice. These are optional components that can be obtained by installing the `psychopy-sounddevice` extension into the current environment. """ import psychopy.logging as logging from .exceptions import DependencyError try: from...
Python
1
3648; pub const FPU_FPCCR_LSPEN_Pos: u32 = 30; pub const FPU_FPCCR_LSPEN_Msk: u32 = 1073741824; pub const FPU_FPCCR_MONRDY_Pos: u32 = 8; pub const FPU_FPCCR_MONRDY_Msk: u32 = 256; pub const FPU_FPCCR_BFRDY_Pos: u32 = 6; pub const FPU_FPCCR_BFRDY_Msk: u32 = 64; pub const FPU_FPCCR_MMRDY_Pos: u32 = 5; pub const FPU_FPCCR...
Rust
0
, return_tensors="pt").to(torch_device) # forward pass with torch.no_grad(): outputs = model(**inputs) # verify the predicted depth expected_shape = torch.Size([1, 480, 640]) self.assertEqual(outputs.predicted_depth.shape, expected_shape) expected_slice = t...
Python
1
ith open(file_path, "w") as f: f.write(blog_message) subprocess.run(["npm", "run", "build"], cwd=wiki_dir, check=True) # Step 4: Remove existing docs directory if os.path.exists(f"{PROJECT_DIR}/docs"): shutil.rmtree(f"{PROJECT_DIR}/docs") shutil.copytree(f"{wiki_dir}/build", f"{PROJEC...
Python
1
_null()), _ => query }; query.get_results::<models::OrganizationRole>(titan_db) .map_err(db::TitanDatabaseError::from) } /// [deprecated(note = "Use find_org_roles instead.")] pub fn find_unranked_roles( org_id: i32, titan_db: &MysqlConnection, wcf_db: &MysqlConnection, app_con...
Rust
0
def saudacoes(nome1): print(f'Olá, {nome1}!') def pega_sobrenome(nome2): sobrenome = input(f'Por favor {nome2}, digite o seu sobrenome: ') print(f'{nome2} {sobrenome}') nome = input('Digite o seu nome: ') saudacoes(nome) pega_sobrenome(nome)
Python
1
ct_id: str, user_id: str = None, current_document_id: str = None, progress_callback: Any = None, ) -> DocumentOperation: """ Run the agent for conversational document management. Args: user_message: The user's conversational input project_id: ...
Python
1
crate::Move::Place(loc, _) => { let id = self.board.id(loc); let name = self.id_to_name_stack.get_mut(&id).unwrap().pop().unwrap(); self.name_to_id.insert(name, UNASSIGNED); } crate::Move::Movement(start_loc, end_loc) => { let start...
Rust
0
dict1 = { "Ashu":100, "Sarthika":100, "shashank":98, 70:"Remaining students", } # print(dict1) # Methods of dictionary # print(dict1.items()) # Returns a view object that displays a list of a dictionary's key-value tuple pairs # print(dict1.keys()) # Returns a view object that displays a list of al...
Python
1
#!/usr/bin/env python3 # Hacky script to fix an invalid export_cda.xml file # # For some reason, in some cases the Apple Health Export file export_cda.xml # can be in the following format: # # <?xml version="1.0"?> # <?xml-stylesheet type="text/xsl" href="CDA.xsl"?> # <ClinicalDocument ...> # <entry typeCode="DRIV"> ...
Python
1
::FancySlice; use cgmath::Vector3; use crate::resources::Resource; pub(crate) fn vertices(data: FancySlice, resources: Vec<Resource>) -> Vec<Vertices> { let mut vertices = vec!(); for resource in resources { let data = data.relative_fancy_slice(resource.data_offset as usize..); let size ...
Rust
0
s: size, } } fn add(&mut self, d: Datum<T>) { self.q.push_back(d) } fn to_string(&self) -> String { json!(self.q).to_string() } } pub struct MetricGraphics<T> where T: serde::Serialize + serde::Deserialize + Send { inner: Arc<Mutex<MetricGraphicsInner<...
Rust
0
abel_enable_for_facet_search':'true', 'Rewrite':'site:.edu', 'entities':[]}, } # }}} # 这个文件或许手修改更方便, 所以只生成该文件中的标签部分 {{{ def gen_cse_xml(): root = ET.Element('Facet') # 创建根节点 tree = ET.ElementTree(root) # 创建文档 for facet in list(facet_items.values()): FacetItem = ET.E...
Python
1
import os import torch from transformers import AutoTokenizer from mplug_owl_video.modeling_mplug_owl import MplugOwlForConditionalGeneration from mplug_owl_video.processing_mplug_owl import ( MplugOwlImageProcessor, MplugOwlProcessor, ) from .base_model import BaseModel pretrained_ckpt = "MAGAer13/mplug-owl...
Python
1
m info", vec!["object 1", "object 2"], ) .await; t = server.restart(t).await; t.test_exclude( "both are deleted after restart", "room info", vec!["object 1", "object 2"], ) .await; t.test( "prototype still exists", "prototype 1 info", ...
Rust
0
dex(&self, index: ::std::ops::Range<usize>) -> &[$ty] { &self.0[index] } } impl ::std::ops::Index<::std::ops::RangeTo<usize>> for $thing { type Output = [$ty]; #[inline] fn index(&self, index: ::std::ops::RangeTo<usize>) -> &[$ty] { ...
Rust
0
uf.pop(); diff_paths( self.fix_import_url(new_url.as_str()), buf.to_slash().unwrap(), ) .unwrap() } else { if fixed_url.starts_with("/") { let mut buf = PathBuf::from(self.specifier.as_str()); buf.pop(); diff_paths(fixed_url.clone()...
Rust
0
: &mut fmt::Formatter) -> Result<(), fmt::Error> { match *self { GenericType::Any(ref name) => write!(f, "{}", name), GenericType::Restricted(ref constraints) => write!(f, "({})", join(constraints.iter(), " + ")), } } } impl TreePrinter for Type { fn print(&s...
Rust
0
] = None, *args: Any, **kwargs: Any, ) -> Iterator[T_References]: """Equivalent to :meth:`SymbolicReference.iter_items <git.refs.symbolic.SymbolicReference.iter_items>`, but will return non-detached references as well.""" return cls._iter_items(repo, common_path) ...
Python
1
= Timestamp::from(TIME_2021_07_01_10_00_00); assert!(!newer.is_expired(&older)); } #[test] fn timestamp_older_than_one_day_should_expire() { const TIME_2021_07_01_10_00_00: i64 = 1625126400; const TIME_2021_06_01_02_00_00: i64 = 1622505600; let newer = Timestamp::from(TIME...
Rust
0
IT 3", (page_id,) ) result["examples"] = [dict(row) for row in cursor.fetchall()] # Add related links cursor = conn.execute( "SELECT title, url FROM related_links WHERE page_id = ? LIMIT 5", (page_id,) ) result["related_links...
Python
1
# Copyright 2025 AlphaAvatar project # # 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 w...
Python
1
uality::QualityBRISQUE>; ptr_extern! { crate::quality::QualityBRISQUE, cv_PtrOfQualityBRISQUE_delete, cv_PtrOfQualityBRISQUE_get_inner_ptr, cv_PtrOfQualityBRISQUE_get_inner_ptr_mut } ptr_extern_ctor! { crate::quality::QualityBRISQUE, cv_PtrOfQualityBRISQUE_new } impl PtrOfQualityBRISQUE { #[inline] pub fn...
Rust
0
0 # Define mask where a valid depth value is found mask = mask_sign_change & mask_pos_to_neg # (n_rays,) # Get depth values and function values for the interval d_low = starts[torch.arange(n_rays), indices, 0][mask] v_low = sdf[torch.arange(n_rays), indices, 0][mask] ...
Python
1
import numpy as np def determinant(matrix, mode="pure"): """ Computes the determinant of a square matrix. Parameters: - matrix: list of lists or np.array -> Matrix to compute determinant. - mode: str -> "pure" for Python lists, "numpy" for NumPy arrays. Returns: - The determinant value. ...
Python
1
.prog.len() { self.terminated = true; } } else { self.stopped = true; } Ok(self) } } impl Prog { fn parse<'a>(input: &'a str) -> nom::IResult<&'a str, Self, nom::error::VerboseError<&'a str>> { use nom::{ branch::alt, ...
Rust
0
module_name=MODULE_NAME, chat_id=chat_id) # 重新显示配置面板 await show_config(update, None) elif data == f"{CALLBACK_PREFIX}back_to_main": # 返回主菜单 await show_shuo_main_menu(message=update.callback_query.message, ...
Python
1
from llama_index.core import VectorStoreIndex,SummaryIndex from llama_index.experimental.query_engine import PandasQueryEngine from llama_index.core.schema import IndexNode from llama_index.llms.openai import OpenAI from llama_index.core.response.pprint_utils import pprint_response from llama_parse import LlamaParse fr...
Python
1
.find(filter, None) .await .on_err("MongoDB query error")? .next() .await .is_some()) } //Workaround since we can not do impl CPFLat.. since not in the same crate #[async_trait] pub trait TSLitInterpret { fn seval_call0(state: Arc<State>, f: &str) -> Option<CPLiteral>; ...
Rust
0
s["token"].rstrip() token = tok if tok != "" else None directory = values["location"] threads = values["threads"] start_epi = int(values["start_epi"]) if values["start_epi"] != "" else 1 end_epi = int(values["end_epi"]) if values["end_epi"...
Python
1
] ); assert_eq!( update_board( vec2_char![ ['B', '1', 'E', '1', 'B'], ['B', '1', 'M', '1', 'B'], ['B', '1', '1', '1', 'B'], ['B', 'B', 'B', 'B', 'B'] ], vec![1, 2] ), vec2_char![ ...
Rust
0
#[test] fn test_hash() { let h = compute_sha256("hello world".as_bytes()); let res = hex!("b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"); assert_eq!(h[..], res[..]) } #[test] fn test_hex_to_string() { let data = vec![ 185, 77, 39, 1...
Rust
0
, PartialEq, Clone, Serialize, Deserialize, Builder)] pub struct SlackApiUsersLookupByEmailResponse { pub user: SlackUser, } #[skip_serializing_none] #[derive(Debug, PartialEq, Clone, Serialize, Deserialize, Builder)] pub struct SlackApiUsersSetPresenceRequest { pub presence: String, } #[skip_serializing_none...
Rust
0
K: Keychain, { fn drop(&mut self) { self.zeroize(); } } use proconio::input; fn main() { input! { x1: i32, x2: i32, x3: i32, x4: i32, _: i32, } let ans = if x1 == 0 {1} else if x2 == 0 {2} else if x3 == 0 {3} else if x4 == 0 {4} else {5}; println!("{}", ans...
Rust
0