text
string
label_name
string
labels
int64
# SPDX-License-Identifier: Apache-2.0 from typing import Optional, List import torch from vllm.attention import AttentionMetadata from vllm.sequence import IntermediateTensors from vllm.model_executor.models.gemma3_mm import Gemma3ForConditionalGeneration class Gemma3ForConditionalGeneration(Gemma3ForConditionalGene...
Python
1
25_retriever"] faiss_retriever.search_kwargs.update({"k": top_k, "fetch_k": max(4 * top_k, 20)}) bm25_retriever.k = max(3 * top_k, 15) retriever_input = merge_chat_history(query, chat_history) candidates = retriever.invoke(retriever_input) if not candidates: return [] scored = zip(can...
Python
1
ofiling') parser.add_argument('-registry', action='store', default='xr.xml', help='Use specified registry file instead of xr.xml') parser.add_argument('-time', action='store_true', help='Enable timing') parser.add_argument('-genpath', a...
Python
1
handle is HWND (HWND__*) on Windows #[cfg(target_os = "windows")] pub type sfWindowHandle = *mut c_void; // Window handle is Window (unsigned long) on Unix - X11 #[cfg(any(target_os = "linux", target_os = "freebsd"))] pub type sfWindowHandle = c_ulong; // Window handle is NSWindow (void*) on Mac OS X - Cocoa #[cfg(tar...
Rust
0
from __future__ import annotations from cupy import _core erf = _core.create_ufunc( 'cupyx_scipy_special_erf', ('e->d', 'f->f', 'd->d'), 'out0 = erf(in0)', doc='''Error function. .. seealso:: :meth:`scipy.special.erf` ''') erfc = _core.create_ufunc( 'cupyx_scipy_special_erfc', ('e->d', 'f...
Python
1
application::build(&config, false)?; // NOTE: enable linting in future if memserver_is_enabled { memserver::build(&config, false)?; // NOTE: enable linting in future default_asset_map.as_object_mut().unwrap().insert( "assets/memserver.js".to_string(), Value::String("assets/m...
Rust
0
); Ok((self.0)(r)) } } /// A plumbing type for [`PerConnection`]. #[cfg(feature = "net")] #[pin_project] pub struct Acceptor<A, F, C> { #[pin] accept: A, f: F, cfg: C, name: &'static str, } #[cfg(feature = "net")] impl<A, F, C, Fut> Future for Acceptor<A, F, C> where A: Accept, ...
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
, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5, 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd, 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f, ]; pub const S7: [u32; 256] = [ 0x85e04019, 0x332bf567, 0x662dbff...
Rust
0
ate::R<u32, u32>; impl R { #[doc = "Bits 0:23"] #[inline(always)] pub fn rpt4_reserved4_err(&self) -> RPT4_RESERVED4_ERR_R { RPT4_RESERVED4_ERR_R::new((self.bits & 0x00ff_ffff) as u32) } } <reponame>whtcorpsinc/einsteindb-prod // Copyright 2020 WHTCORPS INC // // Licensed under the Apache Licens...
Rust
0
r the `AccessPoint` resource. #[derive(Debug, Default)] pub struct AccessPointProperties { /// Property [`AccessPointTags`](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-efs-accesspoint.html#cfn-efs-accesspoint-accesspointtags). /// /// Update type: _Mutable_. /// AWS CloudF...
Rust
0
#!/usr/bin/env python3 """Show how slow-sync clients work.""" import time import jack slow = jack.Client('Slow') slow.pos = 0 slow.ready_at = None slow.seek_time = 0.1 @slow.set_sync_callback def slow_sync_callback(state, pos): now = time.time() print(jack.TransportState(state), pos.frame, end=' ') if ...
Python
1
arange(0, 1.01, 1 / (control_points_v - degree_v)).tolist() + [1.0] * degree_v nu = [] nu = np.zeros((u.shape[0], control_points_u)) for i in range(u.shape[0]): for j in range(0, control_points_u): nu[i, j] = basis_function_one(degree_u, knots_u, j, u[i]) nv = np.zeros((v.shape[0],...
Python
1
>src/curl/mod.rs extern crate curl_sys; extern crate libc; pub mod easy; pub struct Response { pub header: String, pub body: String, } #[derive(Debug)] pub struct Time { pub namelookup: f64, pub connect: f64, pub pretransfer: f64, pub starttransfer: f64, pub total: f64, } pub use self::easy::Easy; use...
Rust
0
ryFrom<String> for Timestamp { type Error = TimestampError; fn try_from(t: String) -> Result<Self, Self::Error> { Timestamp::from_str(t.as_ref()) } } impl TryFrom<&String> for Timestamp { type Error = TimestampError; fn try_from(t: &String) -> Result<Self, Self::Error> { Timestamp...
Rust
0
', "xì"), ('餽', "kuì"), ('餾', "liù,liú"), ('餿', "sōu"), ('饀', "táo,tāo,xiàn"), ('饁', "yè"), ('饂', "wēn"), ('饃', "mó"), ('饄', "táng"), ('饅', "mán"), ('饆', "bì"), ('饇', "yù"), ('饈', "xiū"), ('饉', "jǐn"), ('饊', "sǎn"), ('饋', "kuì,tuí"), ('饌', "zhuàn,xuǎn"), ...
Rust
0
Ok(x) = self.uart.read() { if !self.sync { if x == 0xFF { self.sync = true; } else { continue; } } else if x == 0xFF { self.current = self.next.take(); } else if x < 39 { ...
Rust
0
_file, weights_file=args.weights_file, cuda_device=args.cuda_device, overrides=args.overrides, ) config = archive.config prepare_environment(config) model = archive.model model.eval() # Load the evaluation data # Try to use the validation dataset reader if there is ...
Python
1
_offset: binemit::CodeOffset, _reloc: binemit::Reloc, _jt: ir::JumpTable, ) { panic!("trampoline compilation should not produce jump table relocs"); } } <reponame>vstroebel/d10<filename>d10-python/src/lib.rs<gh_stars>0 mod color; mod image; use pyo3::prelude::*; use pyo3::exceptions:...
Rust
0
def f(num): res = set() for i in range(2, int(num**0.5) + 1): if num%i==0: res |= {i, num // i} res = sorted(res) if len(res): M = res[0] + res[-1] if M%10 == 4: return M return 0 cnt = 0 for i in range(800001, 10**20): u = f(i) if u: ...
Python
1
"""SCons.Tool.ilink Tool-specific initialization for the OS/2 ilink linker. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Tool.Tool() selection method. """ # # Copyright (c) 2001 - 2016 The SCons Foundation # # Permission is hereby granted...
Python
1
nistic_signcCs@td}|j|}|t|d||jj||dS)N r) osurandomrVrr$lenrrwrr*msgrr r r!&test_deterministic_sign_random_messages  z7TestTrivialCurve.test_deterministic_sign_random_messagecCs6...
Python
1
; Ok(()) } pub fn test_pda_mut_zero_copy(ctx: Context<TestPdaMutZeroCopy>) -> ProgramResult { let mut acc = ctx.accounts.my_pda.load_mut()?; acc.data = 1234; Ok(()) } pub fn test_token_seeds_init( _ctx: Context<TestTokenSeedsInit>, _token_bump: u8, ...
Rust
0
_serial::{Serial, SerialPortSettings}; use std::time::Duration; let settings = SerialPortSettings { baud_rate: 57600, data_bits: tokio_serial::DataBits::Eight, parity: tokio_serial::Parity::None, stop_bits: tokio_serial::StopBits::One, flow_control: tokio_serial::FlowCon...
Rust
0
PKH([u8; 20]); #[allow(dead_code)] pub fn get_pkh(key: [u8; 33]) -> Result<PKH, SyscallError> { let mut temp = [0; 32]; unsafe { let _len: size_t = cx_hash_sha256( key.as_ptr(), 33, temp.as_mut_ptr(), temp.len() as u32, ); } let mut ripem...
Rust
0
the handler self.keybinding_handler: TemporaryKeybindingHandler = ( TemporaryKeybindingHandler(callbacks=callbacks) ) def create_window(self): x: int y: int w: int h: int x, y, w, h = calculate_window_position_dimensions(640, 540) self.wi...
Python
1
feature_flags(4)); assert_eq!(route.paths[0][2].pubkey, nodes[4]); assert_eq!(route.paths[0][2].short_channel_id, 6); assert_eq!(route.paths[0][2].fee_msat, 0); assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1); assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags(5)); a...
Rust
0
from django.core.management.base import BaseCommand from django.contrib.auth import get_user_model from django.utils import timezone from subscription.models import Plan, Subscription User = get_user_model() class Command(BaseCommand): help = 'Creates subscription plans and assigns free subscriptions to users wh...
Python
1
""" AOL OpenId backend, docs at: https://python-social-auth.readthedocs.io/en/latest/backends/aol.html """ from .open_id import OpenIdAuth class AOLOpenId(OpenIdAuth): name = "aol" URL = "http://openid.aol.com"
Python
1
let Some(optional_header) = pe.header.optional_header { let entry_point = optional_header.standard_fields.address_of_entry_point; if entry_point == 0 { return Ok(vec![]); } Ok(vec![optional_header.windows_fields.image_base + entry_point]) } else { Ok(vec![]) ...
Rust
0
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # NO CHECKED-IN PROTOBUF GENCODE # source: swim.proto # Protobuf Python Version: 5.29.0 """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descripto...
Python
1
, cx: &mut task::Context) -> Poll<(), io::Error> { let state = match self.state { Some(ref state) => state, None => return Err(io::Error::new(io::ErrorKind::Other, "timer has gone away")), }; if state.state.load(SeqCst) & 1 !=...
Rust
0
import random import json import pickle import numpy as np import tensorflow as tf import os dir_path = os.path.dirname(os.path.realpath(__file__)) os.chdir(dir_path) import nltk from nltk.stem import WordNetLemmatizer lemmatizer = WordNetLemmatizer() nltk.download('punkt') nltk.download('wordnet') intents = json...
Python
1
import os import azure.cognitiveservices.speech as speechsdk # Creates an instance of a speech config with specified subscription key and service region. speech_key = os.getenv("SPEECH_KEY") service_region = os.getenv("SERVICE_REGION") endpoint_id = os.getenv("ENDPOINT_ID") speech_config = speechsdk.SpeechConfig(subs...
Python
1
#!/usr/bin/env python3 import sys from itertools import combinations from os import uname from multiprocessing import cpu_count from subprocess import call # Later, we want to test extended vaddr support. Apparently, the "real" way of # checking this is flaky on OS X. bits_64 = sys.maxsize > 2**32 nparallel = cpu_c...
Python
1
from data.database import Repository, TeamMember, User def fix_ident(ident): return str(ident).translate(None, "-/.") with open("outfile.dot", "w") as outfile: outfile.write("digraph relationships {\n") for repo in Repository.select(): ns = fix_ident(repo.namespace_user.username) outfil...
Python
1
test_ping() { const ALICE_IP: [u8; 4] = [192, 168, 0, 1]; const BOB_IP: [u8; 4] = [192, 168, 0, 2]; // simple test to ping between two stacks: let mut t = TestSetupBuilder::new() .add_named_endpoint("bob") .add_named_endpoint("alice") .add_stack( StackSetupBuilder::n...
Rust
0
pub postal: Option<&'a str>, pub email: Option<&'a str>, pub phone: Option<&'a str>, pub last4: Option<&'a str>, pub payment_method: Option<&'a str>, pub amount_int: i32, pub amount_frac: i32, pub currency: &'a str, pub uuid: &'a [u8], } // ts-fmt-lite // Copyright (C) SOFe // // Licens...
Rust
0
default="../bsldict/bsldict_v1.pkl", help="Path to bsldict metadata", ) p.add_argument( "--bsldict_features_path", type=Path, default="/users/gul/checkpoint/bobsl/c2281_16f_pad10sec_m8_-15_4_d0.8_-3_22_anon/test_025_sdict_all/vid_features.mat", help="Path to bsldict...
Python
1
= pair.into_inner(); let ident = pair.next().unwrap().as_str().to_string(); let argc = pair.count(); CtorDef { ident, argc } } pub fn parse_expr(pair: pest::iterators::Pair<Rule>) -> Expr { match pair.as_rule() { Rule::app => { let exprs: Vec<Box<Expr>> = pair.into_inner().map(|x| ...
Rust
0
EsmGroup { One = 0, Two = 1, Three = 2, Four = 3, } #[derive(Copy, Clone)] pub enum EsmError { /// MibADC2 - RAM parity error MibADC2Ram = map_ch_group!(EsmGroup::One, 1), /// DMA - MPU configuration violation DmaMpu = map_ch_group!(EsmGroup::One, 2), /// DMA - control packet RAM p...
Rust
0
#Write a function to find the ration of positive numbers in an array of integers. from array import array def positive_count(nums): n = len(nums) n1 = 0 for x in nums: if x > 0: n1 += 1 else: None return round(n1/n,2)
Python
1
message: RouterSolicitation, code: IcmpUnusedCode, ) { let dummy_config = get_dummy_config::<Ipv6Addr>(); assert_eq!(src_mac, dummy_config.local_mac); assert_eq!(src_ip, dummy_config.local_mac.to_ipv6_link_local().get()); assert_eq!(message, RouterSoli...
Rust
0
lf, options: Option<&crate::EventOptions>, descriptor: &EventDescriptor, data: &[EventDataDescriptor<'_>], ) { match self { Some(p) => p.write(options, descriptor, data), None => {} } } fn is_enabled(&self, level: u8, keyword: u64) -> bool { ...
Rust
0
/// precomputed hash. #[derive(Clone, Debug, PartialEq)] pub enum RecoveryMessage { /// Message bytes Data(Vec<u8>), /// Message hash Hash(H256), } #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)] /// An ECDSA signature pub struct Signature { /// R value pub r: H256, /// S Val...
Rust
0
import mlx.core as mx import mlx.nn as nn def absolute_embeddings(max_length: int, emb_dim: int) -> mx.array: return mx.random.normal((max_length, emb_dim)) def sinusoidal_embeddings(max_length: int, emb_dim: int) -> mx.array: assert emb_dim % 2 == 0 positions = mx.expand_dims(mx.arange(start=0, stop=max...
Python
1
'''Escreva um programa que pergunte a qunatidade de km percorridos por um carro alugado e a quantidade de dias pelos quais ele foi alugado. Calcule o preço a pagar, sabendo que o carro custa R$60 por dia e R$ 0,15 por km rodado ''' km = float(input("Digite a quantidade de km percorridos: "))*0.15 day = int(input("Digi...
Python
1
ng; use std::io::Read; use arrayvec::ArrayString; use crate::{Error, Result}; #[derive(Debug)] pub struct DebianBinaryVersion { pub major: u32, pub minor: u32, } pub fn parse_debian_binary_contents<R: Read>(stream: &mut R) -> Result<DebianBinaryVersion> { let mut first_two_bytes: [u8; 2] = [0, 0]; s...
Rust
0
from django.db import models from usuario.models import Usuario from livraria.models import Livro class Compra(models.Model): class StatusCompra(models.IntegerChoices): CARRINHO = 1, "Carrinho" REALIZADO = 2, "Realizado" PAGO = 3, "Pago" ENTREGUE = 4, "Entregue" usuario = model...
Python
1
eled = next(target_labeled_loader_iter) except: print('Loading data error') break # 获取源域数据 images_source = batch_source['image'].to(device, torch.float) labels_source = batch_source['mask'].to(device, torch.long) ...
Python
1
ContentView::SlidersAndKnobs, ), (String::from("Buttons"), ContentView::Buttons), (String::from("Dropdowns"), ContentView::Dropdowns), (String::from("Tree view"), ContentView::TreeView), ], Some(0), ...
Rust
0
of buffer a BufferObject is bound too. /// /// [more](https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glBindBuffer.xhtml) from OpenGL API #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum BufferKind { /// Vertex Array Object Array, /// Element Array Object ElementArrayBuffer, } imp...
Rust
0
impl ShowWithRRU for ExtendOp { fn show_rru(&self, _mb_rru: Option<&RealRegUniverse>) -> String { format!("{:?}", self) } } impl ShowWithRRU for MemLabel { fn show_rru(&self, _mb_rru: Option<&RealRegUniverse>) -> String { match self { &MemLabel::PCRel(off) => format!("pc+{}", of...
Rust
0
. Molec. Biol._ **162**: 705-708.](https://doi.org/10.1016/0022-2836(82)90398-9) use crate::alignment::*; use std::cmp::max; pub struct GotohSpaceEfficientAligner<'s, F: MatchFunc> { scoring: &'s Scoring<F>, } impl<'s, F: MatchFunc> GotohSpaceEfficientAligner<'s, F> { pub fn new(scoring: &'s Scoring<F>) -> S...
Rust
0
: LPVOID, }} pub type LPOFNOTIFYEXA = *mut OFNOTIFYEXA; STRUCT!{struct OFNOTIFYEXW { hdr: NMHDR, lpOFN: LPOPENFILENAMEW, psf: LPVOID, pidl: LPVOID, }} pub type LPOFNOTIFYEXW = *mut OFNOTIFYEXW; pub const CDN_FIRST: UINT = -601i32 as UINT; pub const CDN_LAST: UINT = -699i32 as UINT; pub const CDN_INITDON...
Rust
0
arse::InvalidCountryCode.into()); } // Try to find the first available country code. for len in 1 .. consts::MAX_LENGTH_FOR_COUNTRY_CODE + 1 { let code = number.national[.. len].parse().unwrap(); if database.by_code(&code).is_some() { number.national = trim(number.national, len); num...
Rust
0
session, image_batch_dict) # 最后重新统计一下数量 self.total_images = get_image_count(session) self.total_videos = get_video_count(session) self.total_video_frames = get_video_frame_count(session) self.scanning_files = 0 self.scanned_files = 0 os.remove(self...
Python
1
CfgManager.singlestepStrFormat( tmpJSON['appCmd'], 'model', model ) ) logPathList.append( CfgManager.singlestepStrFormat( "{workPath}/log/sublog/{model}", '...
Python
1
from twilio.rest import Client import keys import requests import time from bs4 import BeautifulSoup import string import smtplib def pushNotif(phoneNumber, messageBody): keys.target_number = phoneNumber client = Client(keys.account_sid, keys.auth_token) try: message = client.messages.create( ...
Python
1
CHUẨN - CHỈ CÁC CỘT CÓ TRONG BẢNG: { "students": [ { "stt": "1", "lop": "CNTT 17-02", "msv": "1771020073", "ho": "Nguyễn Văn", "ten": "Anh", "cc": "8.5", "kt1": "7.0" } ] } 🎯 QUY TẮC PHÂN CHIA TÊN CHÍNH XÁC: - "ho": Họ + tên đệm (VD: "Bùi Tiến", "Nguyễn Văn", "Trầ...
Python
1
}', '--n_epochs_stop', f'{args.n_epochs_stop}', '--train_batch', f'{args.train_batch}', '--val_batch', f'{args.val_batch}', '--win_stride', f'{args.win_stride}'] if args.fill is not None: command.extend(['--fill', f'{args.fill}']) elif args.bi: command.extend(['--bi', 'True']) if args.input_type == 'rgb': if 'in...
Python
1
2 | # this is the 1st bug-related op get analyzed. sub_i32 NF,r2,tmp5 ----------------|-----> # here, NF is an output operand, it's flagged dead mov_i32 ZF,NF | # and the InMemory bit is clear, tell the previous(above) ops setcond_i32 CF,r2,tmp5,geu | # if it is used as output operand again, do not sync it ...
Python
1
def length_of_string(n): if n == "": return 0 else: return 1 + length_of_string(n[1:]) print(length_of_string("Hello"))
Python
1
ss() { if version().hardware_revision() > 0 { unsafe { let tmss_code: *const u32 = core::mem::transmute(&TMSS_CODE[0]); write_volatile(TMSS_REG, *tmss_code); } } } <gh_stars>0 use std::any::Any; use std::cell::UnsafeCell; use std::marker::PhantomData; use std::mem::Manual...
Rust
0
use router::Router; use mysql as my; use rustc_serialize::json; #[derive(Debug, PartialEq, Eq, RustcEncodable)] struct Produk { nama: String, harga: i32, deskripsi: String, } fn main() { let mut router = Router::new(); router.get("/", hello_world, "index"); router.get("/data", get_table_data,...
Rust
0
sarily in the // list. if let Some(n) = self.nodes_info.get_mut(&peer_id) { n.client_version = Some(info.agent_version); } } Ok(Async::Ready(Some(BehaviourOut::PingSuccess { peer_id, ping_time }))) => { // Contrary to the other events, this one can happen even on nodes which don't ...
Rust
0
from pynq import Overlay from aerpawFPGAController import * class objTest(): def __init__(self): self.bitStreamAERPAW = 'aerpawFPGA_v46_8_128_1536_D1.bit' self.lmk = "_8_128_v2" self.lmx = "_128_1536_v0" self.bitStreamAERPAW = 'aerpawFPGA_v46_8_192_1536_D1.bit' s...
Python
1
HEADLESS,", " \"executable_path\": BROWSER_EXECUTABLE_PATH", " }", " }", "", " # 加载URL配置", " config[\"urls\"] = {}" ]) # 添加URL配置加载 if urls: for i, url in enumerate(urls): ...
Python
1
e, skip_exprs) continue if conv_pattern in matched_exprs: self.reset_expr_message_to_none(expr, scale_message, skip_exprs) mem_conv_scale_message[expr] = const continue scale_message[expr] = const self.scale_message.updat...
Python
1
me(var_2877) = &input.storage_class { object.key("StorageClass").string(var_2877); } Ok(()) } pub fn serialize_structure_crate_model_aws_s3_bucket_website_configuration_routing_rule_condition( object: &mut aws_smithy_json::serialize::JsonObjectWriter, input: &crate::model::AwsS3BucketWebsiteCon...
Rust
0
_leisure_geo_tile(properties, line_string) } else if properties.contains_key("man_made") { get_man_made_geo_tile(properties, line_string) } else if properties.contains_key("military") { get_military_geo_tile(properties, line_string) } else if properties.contains_key("natural") { get_...
Rust
0
# Exercise №1 try: lst = [] while True: lst.append(int(input())) except: print(lst) max = 0 for i in range(len(lst)): if lst[i] > lst[i-1]: max = lst[i] print(max) # Exercise №2 try: lst = [] while True: lst.append(int(input())) except: print(len(lst)) # Exercis...
Python
1
# -*- coding: utf-8 -*- """股票技术指标计算工具模块""" from venv import logger import pandas as pd import pandas_ta as ta import numpy as np import matplotlib.pyplot as plt from typing import Dict, List, Optional, Union, Any, Tuple def calculate_technical_indicators(df: pd.DataFrame, ma_periods: List[int] = [5, 10, 20, 30, 60], ...
Python
1
find the root /// /// `tol` tolerance for error between iterations of Newton's method /// /// `n_max` Maximum number of iterations /// /// # Examples /// ``` /// use nalgebra::{VectorN, U1}; /// use bacon_sci::roots::secant; /// fn cubic(x: &[f64]) -> VectorN<f64, U1> { /// VectorN::<f64, U1>::from_iterator(x.iter()...
Rust
0
} else { *normal = Vector3::new(intersection_point.x, 0.0f32, intersection_point.z); let u = normal.x.atan2(normal.z) / f32::consts::PI + 2.0; //atan2(n.x, n.z) / (2*pi) + 0.5; let v = intersection_point.y; //atan2(n.x, n.z) / (2*pi) + 0.5; ...
Rust
0
m_rt::function; pub use tvm_rt::module; pub use tvm_rt::ndarray; #[cfg(feature = "python")] pub mod compiler; pub mod ir; #[cfg(feature = "python")] pub mod python; pub mod runtime; pub mod transform; pub use runtime::version; #[macro_export] macro_rules! export { ($($fn_name:expr),*) => { pub fn tvm_exp...
Rust
0
ids)) maybe_rejsample_metrics = ( self._metrics.maybe_collect_rejsample_metrics(k)) if maybe_rejsample_metrics is not None: sampler_output_list[ 0].spec_decode_worker_metrics = maybe_rejsample_metrics return sampler_output_list @cached_property ...
Python
1
ass__.__name__} : reset_record: {e}")) raise Exception(f"{self.__class__.__name__} : reset_record: {e}") def record(self, output_filename: str): try: self.start_recording(output_filename) while self.is_recording: print("is_recording") time...
Python
1
from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker import logging # Configure logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # Database configuration DATABASE_URL = "mysql+pymysql://root:costincnva2...
Python
1
pub static ref FILE_ATTRIBUTE_UNIX_NLINK: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_UNIX_NLINK).to_str().unwrap()}; } lazy_static! { pub static ref FILE_ATTRIBUTE_UNIX_RDEV: &'static str = unsafe{CStr::from_ptr(ffi::G_FILE_ATTRIBUTE_UNIX_RDEV).to_str().unwrap()}; } lazy_static! { pub static...
Rust
0
let b = vec![1u8, 3]; assert_eq!(compute_hash(&a), compute_hash(&b)); /// ------------------- fn compute_hash<T: Hash>(value: &T) -> u64 { let mut hasher = DefaultHasher::new(); value.hash(&mut hasher); hasher.finish() } ...
Rust
0
.imbue(::capnp::private::layout::CapTableBuilder::Plain(cap_table)) } } impl <'a,> ::capnp::traits::FromPointerBuilder<'a> for Builder<'a,> { fn init_pointer(builder: ::capnp::private::layout::PointerBuilder<'a>, _size: u32) -> Builder<'a,> { ::capnp::traits::FromStructBuilder::new(builder.init_stru...
Rust
0
import os import sys from .ctk_font import CTkFont from .font_manager import FontManager # import DrawEngine to set preferred_drawing_method if loading shapes font fails from ..core_rendering import DrawEngine FontManager.init_font_manager() # load Roboto fonts (used on Windows/Linux) customtkinter_directory = os.p...
Python
1
import requests import json import logging from time import sleep # Set up logging logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) def test_streaming(): """Test streaming response from the API endpoint""" url = "https://api.canalavi.com/chat/team/67b499b13f5dd757352a9b2f" hea...
Python
1
from typing import List,Set def unions(arr1:List[int], arr2:List[int] ) -> Set[int]: return set(arr1+arr2) if __name__ == "__main__": arr2 = list(map(int,input("enter the elements of tht e array 2 : ").strip().split())) arr1 = list(map(int,input("enter the emelemtnsof the first array1 ").strip().split...
Python
1
frutas = ('laranja', 'banana', '')
Python
1
assert_feed_ok!(d, [], [], ""); assert_feed_err!(d, [], [0xa0], [], ""); assert_finish_ok!(d, ""); } } use crate::io::Name; use serde::Serialize; use std::fmt::{Display, Formatter}; use super::Properties; #[derive(Debug, Serialize)] pub enum Value { ArrayOfF32(Vec<f32>), ArrayOfF6...
Rust
0
x.2).0 { if !s.walk(path, on_node) { return false; } } } Self::Assignment(x, _) => { if !x.0.walk(path, on_node) { return false; } if !x.2.walk(path...
Rust
0
></p></td> <td><p><code class="inline-code">Boolean</code></p></td> <td><p>定位成功后,是否把定位得到的坐标设置为地图中心点坐标</p><p>默认值:true</p></td> </tr> <tr> <td style="white-space: nowrap;"><p><code class="inline-code">zoomToAccuracy</code></p></td> <td><p><code class="inline-code">Boolean</code></p></td> ...
Python
1
ng, log_level: Level, } impl GridConfig { pub fn validator_endpoint(&self) -> &str { &self.validator_endpoint } pub fn log_level(&self) -> Level { self.log_level } } pub struct GridConfigBuilder { validator_endpoint: Option<String>, log_level: Option<Level>, } impl Defaul...
Rust
0
daily_trade_count: int = 0 total_return: float = 0 annual_return: float = 0 daily_return: float = 0 return_std: float = 0 sharpe_ratio: float = 0 return_drawdown_ratio: float = 0 else: # Calculate balance related time series...
Python
1
json(); } if arg.path.is_none() { arg.path = Some("".to_string()); } let res = SysRes { id: new_snowflake_id().to_string().into(), parent_id: arg.parent_id.clone(), name: arg.name.clone(), permission: arg.permission.clone(), path: arg.path.clone(), ...
Rust
0
s considered the termination //! event of the stream. As such, `Receiver::poll` returns `Ok(Ready(None))`. //! //! If the [`Receiver`] handle is dropped, then messages can no longer //! be read out of the channel. In this case, all further attempts to send will //! result in an error. //! //! # Clean Shutdown //! //! W...
Rust
0
pub fn with_new<F>(f: F) where F: FnOnce(&mut State), { f(&mut State::new()) } /// Instantiate a new `State` for a given `Request`. This is primarily useful if you're calling /// Gotham from your own Hyper service. pub fn from_request(req: Request<Body>, client_addr: SocketAddr...
Rust
0
#!/usr/bin/env python3 # -*-coding:utf8-*- from typing_extensions import ( Literal, ) class ArmMsgSearchMotorMaxAngleSpdAccLimit: ''' msg_v1_transmit 查询电机角度/最大速度/最大加速度限制指令 CAN ID: 0x472 Args: motor_num: 关节电机序号,1-6 search_content: 查询内容,0x01-查询电机角度/最大速度,0x02-查询电机最大加...
Python
1
:LE, Wb::LE, Wb::LE, Wb::LE, Wb::LE, Wb::LE, Wb::LE, Wb::LE, Wb::LE, Wb::LE, Wb::LE, Wb::LE, Wb::XX, Wb::XX, Wb::XX, Wb::XX, Wb::XX, Wb::LE, Wb::LE, Wb::LE, Wb::XX, Wb::LE, Wb::LE, Wb::LE, Wb::LE, Wb::LE, Wb::LE, Wb::LE, Wb::XX, Wb::XX, Wb::XX, ], &[ // Block 53 Wb::WSegS...
Rust
0
_, virtio_net_queues = features.get("mq", (False, 1)) ifreq_name = name.encode('ascii') for _ in range(virtio_net_queues): try: tapfd = os.open("/dev/net/tun", os.O_RDWR) except EnvironmentError: raise errors.HypervisorError("Failed to open /dev/net/tun") flags = IFF_TAP | IFF_NO_PI ...
Python
1
, dst: &mut [u8]) { msg!("Write debt data"); let dst = array_mut_ref![dst, 0, 113]; let (dst_stake_pool, dst_owner, dst_account, dst_debt, dst_is_initialized) = mut_array_refs![dst, 32, 32, 32, 16, 1]; let &Debt { ref stake_pool, ref owner, ref account, debt, is_initi...
Rust
0
raAddress, TerraValidatorOperatorAddress}; use crate::canonical_json::to_canonical_json; use crate::coin::Coin; use failure::Error; use rust_decimal::Decimal; use serde::Serialize; use sha2::{digest::Digest, Sha256}; use subtle_encoding::hex; /// Sends Coins between accounts #[derive(Serialize, Debug, Clone)] pub stru...
Rust
0
}", file, e); std::process::exit(1) } } } pub fn read_config_file(buffer: BufReader<File>) -> HashMap<String, u16> { let mut data: HashMap<String, u16> = HashMap::new(); for line in buffer.lines() { let line_str = line.expect("Error"); let data_vec = line_str.split(':')....
Rust
0