text
string
label_name
string
labels
int64
e_epi32(m3, _MM_SHUFFLE!(0, 1, 3, 2)); let mx2 = _mm_blend_epi16(t0, t1, 0xC3); let my2 = _mm_shuffle_epi32(t0, _MM_SHUFFLE!(2, 3, 0, 1)); ROUND!(va, vb, vc, vd, mx1, mx2, my1, my2); // Round-2 let t0 = _mm_blend_epi16(m1, m2, 0x0C); let t1 = _mm_slli_si128(m3, 4); let t2 = _mm_blend_epi16(...
Rust
0
f, username, permission_group): document = self.users.find_one_and_update({FIELD_LOOKUP_USERNAME: username.lower()}, {"$set": {FIELD_PERMISSION_GROUP: permission_group}}) return document is not None def set_settings(self, username, settings): document = self.users.find_one_and_update({F...
Python
1
import os import platform import sys from scripts.sprint import sprint from scripts.colors import ran, y, r, g, c import time from subprocess import call def clear(): system = platform.system().lower() if system == 'windows': _ = os.system('cls') elif system == 'linux' or system == 'darwin': _ = os.sys...
Python
1
def get_legend_items(colors): return [ {"label": "Start Method", "color": colors["start"]}, {"label": "Method", "color": colors["method"]}, { "label": "Crew Method", "color": colors["bg"], "border": colors["start"], "dashed": False, },...
Python
1
} } <gh_stars>1000+ // Check that an arena (TypedArena) cannot carry elements whose drop // methods might access borrowed data of lifetime that does not // strictly outlive the arena itself. // // Compare against run-pass/dropck_tarena_sound_drop.rs, which shows a // similar setup, but loosens `f` so that the struc...
Rust
0
wif = self._private_key_to_wif(private_key) address = self._private_key_to_address(private_key) return private_key, wif, address class LostBitcoinStrategy(BitcoinSearchStrategy): """Chiến lược tìm kiếm các ví Bitcoin đã mất""" def __init__(self): self.early_patterns = [ ...
Python
1
la.peek(LitStr) { Ok(Literal::Utf8(input.parse()?)) } else if la.peek(LitByteStr) { Ok(Literal::Bytes(input.parse()?)) } else { Err(la.error()) } } } pub fn bytes_to_regex_string(bytes: Vec<u8>) -> String { if bytes.is_ascii() { unsafe { ...
Rust
0
ng=args.enable_access_logging, enable_container_logging=args.enable_container_logging, service_account=args.service_account, traffic_split=args.traffic_split, deployed_model_id=args.deployed_model_id, shared_resources_ref=shared_resources_ref) response_msg = operati...
Python
1
3*num_kp+2) """ feat_stiching = concat_feat(kp_source, kp_driving) with torch.no_grad(): delta = self.stitching_retargeting_module['stitching'](feat_stiching) return delta def stitching(self, kp_source: torch.Tensor, kp_driving: torch.Tensor) -> torch.Tensor: "...
Python
1
s.insert( pubkey, RevaultSignature::PlaintextSig( Signature::from_der(&sig).expect("We input to_der()"), ), ); } } Ok(Sigs { signatures }) } pub async fn store_spend_tx( config: &tokio_postgres::Config, outpoint: O...
Rust
0
Vec3::new(upper_bound_x, upper_bound_y, upper_bound_z), extents: Vec3::new(extent_x, extent_y, extent_z), cell_extents: Vec3::new(cell_extent_x, cell_extent_y, cell_extent_z), coord_derivatives: [up_derivatives, down_derivatives], } } fn shape(&self) -> &In3D<usize> ...
Rust
0
ta.values(row_ids, dst)), Self::I64U16(data) => EncodedValues::I64(data.values(row_ids, dst)), Self::I64I8(data) => EncodedValues::I64(data.values(row_ids, dst)), Self::I64U8(data) => EncodedValues::I64(data.values(row_ids, dst)), _ => unreachable!("encode...
Rust
0
f.encode_metadata( CustomJobMetadata( input_data_path=job_request.input_data_path, output_data_path=job_request.output_data_path, expires_at=expires_at.isoformat(), priority=job_request.priority, labels=j...
Python
1
from django.urls import path from . import views urlpatterns = [ path('', views.add_trip, name='add_trip'), path('trip_list/', views.trip_list, name='trip_list'), path('trips/edit/<int:trip_id>/', views.edit_trip, name='edit_trip'), # Edit a specific trip path('trips/delete/<int:trip_id>/', views.dele...
Python
1
cfg.MODEL.ENCODER_LAYER pre_num = cfg.MODEL.PRENUM bins = cfg.MODEL.BINS range = cfg.MODEL.RANGE num_heads = cfg.MODEL.NUM_HEADS mlp_ratio = cfg.MODEL.MLP_RATIO qkv_bias = cfg.MODEL.QKV_BIAS drop_rate = cfg.MODEL.DROP_RATE attn_drop = cfg.MODEL.ATTN_DROP drop_path = cfg.MODEL.DROP_P...
Python
1
import os from typing import Any from moonshot.src.connectors.connector import Connector, perform_retry from moonshot.src.connectors.connector_response import ConnectorResponse from moonshot.src.connectors_endpoints.connector_endpoint_arguments import ( ConnectorEndpointArguments, ) from h2ogpte import H2OGPTE cl...
Python
1
return True else: connection.close() self.inputs.remove(connection) self.outputs.remove(connection) return False def handle_write(self, connection: socket.socket) -> None: """Writes an HttpResponse to the network buffer Args: conn...
Python
1
} } <reponame>busstoptaktik/geodesy mod cartesians; mod geodesics; pub(crate) mod latitudes; mod meridians; /// Representation of a (potentially triaxial) ellipsoid. #[derive(Clone, Copy, Debug)] pub struct Ellipsoid { a: f64, ay: f64, f: f64, } /// GRS80 is the default ellipsoid. impl Default for Ell...
Rust
0
""" 對手建模服務模組 提供對手行為預測相關的服務,包括招式預測和傷害評估。 """ from ..utils.type_effectiveness_utils import TypeEffectivenessHelper, estimate_damage_score from poke_env.battle import Battle def predict_opponent_damage_candidates( battle: Battle, type_helper: TypeEffectivenessHelper, max_candidates: int = 2, ) -> list[tupl...
Python
1
callback: P, ) { let user_data: Box_<P> = Box_::new(callback); unsafe extern "C" fn domains_with_cookies_trampoline< P: FnOnce(Result<Vec<glib::GString>, glib::Error>) + Send + 'static, >( _source_object: *mut glib::gobject_ffi::GObject, res: *mut gio::ffi...
Rust
0
, is_teammate: true, x: -0.289095425043726, y: rules.ROBOT_RADIUS, z: -19.997910486728827, velocity_x: 0.0, velocity_y: 0.0, velocity_z: 0.0, radius: rules.ROBOT_RADIUS, nitro_amount: if game_type.nitro() { rules.START_NITRO_AMOUNT ...
Rust
0
if line[:length] == keyword: return line[length:] else: if keyword in line: return line[line.index(keyword):] else: return None def parse_cell(cell, rules): """ Applies the rules to the bunch of text describing a cell. @param string cell A network...
Python
1
import numpy as np import redis HOSTS = { "bot1": "172.24.69.149", "bot2": "172.24.69.150", "bot3": "172.24.69.151", "bot4": "172.24.69.155", } PASSWORD = "bohg" class MobileBase(object): def __init__(self, name="bot1", password=PASSWORD): self.name = name self.host = HOSTS[name]...
Python
1
g)) or (slot.playing_status > 0)) self.send_midi((NOTE_ON_STATUS+PLAYING_CH, PLAYING_BASE_NO+index, state and 127)) def _on_visible_tracks_changed(self): self._setup_playing_clips() self.update_playing_buttons() def on_selected_track_bank(self): self._setup_playing_cli...
Python
1
l/dataset/internal/LaSOT_QA/LaSOT_test_v20231020.parquet" # parquet = "hdfs://haruna/home/byte_lab_ocr_cn/proj/video_multi_modal/dataset/VideoChat/vidmm/00000011.parquet" parquet = "hdfs://haruna/home/byte_lab_ocr_cn/proj/video_multi_modal/dataset/internal/LaSOT_General_train_v20240102/00000000.parquet" ds ...
Python
1
# Ficheiro: audio_db.py # Descrição: Funções básicas para manipular a base de dados de áudio from db_config import get_client import mutagen import librosa import os def add_audio_vector(audio_id, vector, metadata=None): """ Adiciona um vetor de áudio à base de dados. Args: audio_id: Identifi...
Python
1
{ ZSort::ByLex => match range.range { ZRangeBound::Lex(_) | ZRangeBound::InfiniteLex | ZRangeBound::NegInfinityLex => Ok(()), _ => new_range_error(kind), }, ZSort::ByScore => match range.range { ZRangeBound::Score(_) | ZRangeBound::InfiniteScore | ZRangeBound::NegInfiniteScore ...
Rust
0
ddchstr.3x.html> pub unsafe fn mvwaddchnstr(win: WINDOW, y: i32, x: i32, chstr: &[chtype], n: i32) -> i32 { assert!(!win.is_null(), "{}mvwaddchnstr() : win.is_null()", MODULE_PATH); assert!(y >= 0, "{}mvwaddchnstr() : y = {}", MODULE_PATH, y); assert!(x >= 0, "{}mvwaddchnstr() : x = {}", MODULE_PATH, x); ...
Rust
0
from PIL import Image import codecs version = [3, 0] def encodeUTF8Text(input:str, avatar:str = ""): textbyte_list = list(bytearray(input.encode('utf-8'))) textbyte_list = [0,0,0,0] + [0] + version + [1] + textbyte_list if avatar != "": avatar = avatar.replace("avtr_", "") avatar = avata...
Python
1
页面 driver.get(login_url) Login() # 切换英文 while True: try: count = count + 1 driver.find_element(By.ID, 'lang_title').click() driver.find_element(By.ID, 'lang_en').click() except E...
Python
1
#----------------------------------------------------------------------------- # Copyright (c) 2014-2023, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License (version 2 # or later) with exception for distributing the bootloader. # # The full license is in the file COPYING.txt...
Python
1
that the user can invoke explicitly which allows /// /// for parsing 0 or more types, rather than the default 1 or more. /// named!(pub parse0 -> Self, do_parse!( /// types: call!(Punctuated::parse_separated) >> /// (CommaSeparatedTypes { types }) /// )); /// } /// # /// # fn main() {} /// ...
Rust
0
TimeStamp(self, StartTimeStamp): self._StartTimeStamp = StartTimeStamp @property def EndTimeStamp(self): """视觉信息终止时间戳,从0开始 关键词在视觉信息中的区间为[StartTimeStamp, EndTimeStamp) :rtype: float """ return self._EndTimeStamp @EndTimeStamp.setter def EndTimeStamp(self, EndTime...
Python
1
{}", Rand::u64()); println!("u64 1 = {}", Rand::u64()); println!("u64 2 = {}", Rand::u64()); println!("u64 3 = {}", Rand::u64()); println!("u64 4 = {}", Rand::u64()); println!("u64 5 = {}", Rand::u64()); println!("u64 6 = {}", Rand::u64()); println!("u64 7 = {}",...
Rust
0
# Copyright HeteroCL authors. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import heterocl as hcl import numpy as np from lenet_main import * batch_size = 50 # f = build_lenet_inf(batch_size, 'vhls_csim') f = build_lenet_inf(batch_size, "sdaccel_sw_emu") mnist = mx.test_utils.get_mnist() correct_sum =...
Python
1
'Dz:', 'y:', 'He:'], # 'res': ['C:'], 'js': ['(Q/(Pi*u*Dy*Dz))*math.exp(-(y**2/(2*Dy**2))-He**2/(2*Dz**2))'], # 'py': ['(Q/(Pi*u*Dy*Dz))*math.exp(-(y**2/(2*Dy**2))-He**2/(2*Dz**2))']} # # 环评公式_83v.doc f017 = { 'keywords': '临界氧亏模型,在线计算', 'desc': '临界氧亏模型在线计算', 'title': '临界氧亏模型在线计算', 'p': [ 'kd:有机...
Python
1
e_many_nonempty(rng, (), dist.max_have_cards, |rng, _| rng.gen()), ), )), 5 => Antecedent::Draw(self.draws.sample(rng), self.sample(rng), rng.gen::<bool>()), 6 => Antecedent::Show(self.sample(rng), self.sample(rng)), //_ => unsafe { unreachable_unchecked()...
Rust
0
ids.filtered(lambda l: l.display_type == 'cogs') self.assertRecordValues(invoice_1_cogs, [ {'debit': 0, 'credit': 40, 'account_id': account_stock_out.id, 'reconciled': True}, {'debit': 40, 'credit': 0, 'account_id': account_expense.id, 'reconciled': False}, ]) self.assert...
Python
1
pth_to_show).clamp(0, 10) output_writers[i].add_image('val target Disparity Normalized', tensor2array(disp_to_show, max_value=None, colormap='magma'), epoch) output_writers[i].add_image('val Dispnet Outp...
Python
1
= 0, #[doc = "1: 24 bits"] _24 = 1, #[doc = "2: 20 bits"] _20 = 2, #[doc = "3: 18 bits"] _18 = 3, #[doc = "4: 16 bits"] _16 = 4, #[doc = "5: 16 bits compact stereo"] _16C = 5, #[doc = "6: 8 bits"] _8 = 6, #[doc = "7: 8 bits compact stereo"] _8C = 7, } impl From<DA...
Rust
0
with open(f"{self.args.saving_path}/rag_docs_writer_rerank.jsonl", 'a') as f: writer = jsonlines.Writer(f) line = { "total_docs": [{doc.metadata['id']: {'title': doc.metadata['title'], 'citation': doc.metadata['citation_count']}} for doc in results[0]], ...
Python
1
, encoding: &str, vm: &VirtualMachine) -> PyResult<Self> { Ok(PyBytes { inner: PyByteInner::from_string(value, encoding, vm)?, }) } pub fn get_value(&self) -> &[u8] { &self.inner.elements } } impl IntoPyObject for Vec<u8> { fn into_pyobject(self, vm: &VirtualMachine...
Rust
0
.await .map_err(|e| DigitalAssetError::FatalError(format!("Error sending request to channel:{}", e)))?; rx.await .map_err(|e| DigitalAssetError::FatalError(format!("Error receiving from wait_for oneshot channel:{}", e))) } async fn wait_for_qc( &self, message_typ...
Rust
0
orm: PlatformSpec, /// The binaries installed by this package pub bins: Vec<String>, } /// Configuration information about an installed binary from a package. /// /// This information will be stored in ~/.volta/tools/user/bins/<bin-name>.json. /// /// For an example, this looks like: /// /// { /// "name": "c...
Rust
0
ents: Punctuated<syn::Ident, syn::Token![,]> = <Punctuated<syn::Ident, syn::Token![,]>>::parse(input)?; punc_idents.iter().cloned().collect() }; let qmd = test_query(&query_pretty); // Parameterized columns equals columns values that are filled with dynamic values ...
Rust
0
num_cls_tokens=12, cls_reduce=2, **kwargs) model.default_cfg = _cfg() if pretrained: checkpoint = torch.hub.load_state_dict_from_url( url="https://huggingface.co/Wangf3014/Mamba-Reg/resolve/main/mambar_small_patch16_224.pth", map_location="cpu", check_hash=True ) ...
Python
1
alPaymentData(self, ExternalPaymentData): self._ExternalPaymentData = ExternalPaymentData @property def GoodsInfos(self): r"""商品信息 :rtype: list of OpenBankGoodsInfo """ return self._GoodsInfos @GoodsInfos.setter def GoodsInfos(self, GoodsInfos): self._Go...
Python
1
} } impl ::std::ops::DerefMut for TxWitness { fn deref_mut(&mut self) -> &mut Vec<TxInWitness> { &mut self.0 } } // normally should be some structure: e.g. indicate a type of signature #[derive(Debug, PartialEq, Eq, Clone)] pub enum TxInWitness { TreeSig(SchnorrSignature, Proof<RawPubkey>), } ...
Rust
0
new=CoroutineMock()) as mock_send: mock_send.side_effect = aioxmpp.XMPPCancelError( aioxmpp.ErrorCondition.REMOTE_SERVER_NOT_FOUND ) res = run_coroutine(self.s.get_vcard(TEST_JID1)) def test_set_vcard(self): with unittest....
Python
1
= base32::decode("em3ags7p").unwrap(); /// println!("{:?}", bytes); /// // Prints 'hello' ///} ///``` #[cfg(any(feature = "alloc", feature = "std", test))] pub fn decode<T: AsRef<[u8]>>(input: T) -> Result<Vec<u8>, DecodeError> { decode_alphabet(input, &ZBASE32) } ///Decode from string reference as octets u...
Rust
0
uncionario() elif mf == "4": excluir_funcionario() elif mf == "0": break else: print("Opção inválida!") # Menu Principal de inicialização de sistema def main(funcionario_ativo): while True: print(f"{10*'-='} L O C A D O R A {10*'=-'}") pri...
Python
1
+" tongue = "[pPd3]+" otherMouths = r"(?:[oO]+|[/\\]+|[vV]+|[Ss]+|[|]+)" # remove forward slash if http://'s aren't cleaned # mouth repetition examples: # @aliciakeys Put it in a love song :-)) # @hellocalyclops =))=))=)) Oh well # myleott: try to be as case insensitive as possible, but still not perfect, e.g., o.O f...
Python
1
ize, SocketAddr)> { Self::recv_from_with_flags(sock, buf, libc::MSG_PEEK as _) .await .map(|(size, sockaddr)| (size, sockaddr.as_std().unwrap())) } async fn recv_from_with_flags<R: AsRawFd>( socket: &R, buf: &mut [u8], flags: u32, ) -> io::Result<(usi...
Rust
0
from selenium.webdriver.common.by import By class ConfirmPage: def __init__(self, driver): self.driver = driver confirmCheckoutBtn = (By.XPATH, "//button[@class='btn btn-success']") countryInputField = (By.ID, "country") countrySearchKey = "united" countryName = "United States of America"...
Python
1
>)>) -> H256 { warn!("trie::blake2_256_root() unimplemented"); H256::default() } /// A trie root formed from the enumerated items. pub fn blake2_256_ordered_root(input: Vec<Vec<u8>>) -> H256 { warn!("trie::blake2_256_ordered_root() unimplemented"); H256::default() } pub fn keccak_256_root(input: Vec<(Vec...
Rust
0
password[x..y + 1].reverse(); } RotL(x) => { let y = x % password.len(); if y > 0 { password[..y].reverse(); password[y..].reverse(); password[..].reverse(); } } ...
Rust
0
Model {} /// ``` mod active_model; mod base_entity; mod column; mod identity; mod link; mod model; /// Re-export common types from the entity pub mod prelude; mod primary_key; mod relation; pub use active_model::*; pub use base_entity::*; pub use column::*; pub use identity::*; pub use link::*; pub use model::*; // pu...
Rust
0
[doc = "*Required features: `\"Win32_NetworkManagement_QoS\"`, `\"Win32_Foundation\"`*"] #[cfg(feature = "Win32_Foundation")] pub fn TcDeregisterClient(clienthandle: super::super::Foundation::HANDLE) -> u32; #[doc = "*Required features: `\"Win32_NetworkManagement_QoS\"`, `\"Win32_Foundation\"`*"] #[cfg(...
Rust
0
if console.sheet_index == 0 { console.cmd_exit(fat); } cmdline = [0; MAX_CMD]; // プロンプト表示 if sheet_index != 0 { console.show_prompt(); ...
Rust
0
} #[inline(always)] fn to_csv<T: Write>(&self, writer: &mut T, delimiter: u8) -> Result<()> { reference_iterator_to_csv(writer, self.iter(), delimiter) } #[inline(always)] fn from_csv<T: Read>(reader: &mut T, delimiter: u8) -> Result<RecordList> { iterator_from_csv(reader, deli...
Rust
0
Box<dyn std::error::Error>> { let bucket = crate::read_test_bucket().await; let obj1 = Object::create(&bucket.name, vec![0, 1], "test-compose-1", "text/plain").await?; let obj2 = Object::create(&bucket.name, vec![2, 3], "test-compose-2", "text/plain").await?; let compose_request = Compo...
Rust
0
from typing import Any import numpy as np from numba import from_dtype, float64, int64 from numba.experimental import jitclass from .types import state_values_dtype class StateValues: arr: from_dtype(state_values_dtype)[:] def __init__(self, arr: np.ndarray[Any, state_values_dtype]): self.arr = arr...
Python
1
-> Result<Pin<Box<impl Stream<Item = serde_json::Value>>>, anyhow::Error> { let sensors = self .stream_char(BOARD_SERVICE_UUID, SENSORS_CHAR_UUID) .await? .map(|data| Self::data_to_json(&data)); Ok(Box::pin(sensors)) } async fn read_char(&mut self, service: ...
Rust
0
AV::Int(Out), ); inp.add( Ident::Connect, vec!["sockfd", "addr", "addrlen"], vec![AV::Int(In), AV::SockAddr(In, 2), AV::Int(In)], // FIXME use struct sockaddr, socklen_t addrlen AV::Int(Out), ); } /// Syscall: Create an endpoint for communication #[derive(Debug, Pa...
Rust
0
tance pointer. #[no_mangle] pub extern fn hl_crypto_cl_sub_proof_request_free(sub_proof_request: *const c_void) -> ErrorCode { trace!("hl_crypto_cl_sub_proof_request_free: >>> sub_proof_request: {:?}", sub_proof_request); check_useful_c_ptr!(sub_proof_request, ErrorCode::CommonInvalidParam1); let sub_proo...
Rust
0
ls.Q(course_module__in=form_data.get('module', [])) ) def get_submitters(form_data: Dict[str, Any]) -> models.QuerySet[UserProfile]: """ Get the submitters that match the input form's `submitter` and `submitter_tag` fields. """ return UserProfile.objects.filter( models.Q(id__in=form_da...
Python
1
pd-353[jowtx] lhkhszqx-fqzcd-cxd-nodqzshnmr-911[dhqzc] fodvvlilhg-fdqgb-xvhu-whvwlqj-725[syfpw] mtzslklcozfd-dnlgpyrpc-sfye-cpdplcns-873[zngtm] rwcnawjcrxwju-yujbcrl-pajbb-jwjuhbrb-459[jbrwc] hcd-gsqfsh-awzwhofm-ufors-suu-twbobqwbu-948[reunt] pwcvonofrcig-pibbm-obozmgwg-688[zgthm] vhehkyne-l...
Rust
0
String::from("2000"), last_update: String::from("2000"), flag_date: Some(String::from("today")), maintainers: vec![String::from("orhun"), String::from("nuhro")], packager: String::from("orhun"), licenses: vec![String::from("MIT"), String::from("GPL")], ...
Rust
0
import requests import socket from transformers import set_seed import sys import requests import os # 获取当前taskid class GetPromptId: """ A custom node for making API requests and processing responses. Attributes and class methods are defined to match the framework's expectations, similar to the provi...
Python
1
pr(C)] #[derive(Copy, Clone, Debug)] struct Cdw0 { opcode: u8, // UINT32 Opcode:8; fused: u8, // UINT32 FusedOperation:2; _res1: u8, // _res2: u8, // UINT32 Reserved:22; } #[repr(C)] #[derive(Debug)] pub struct Command { cdw_0: Cdw0, flags: CdwValidityFlags, pub nsid: u32, pub cdw_2:...
Rust
0
{ assert_eq!(expected_name, name); check(init); } else { panic!("Assign type expected: {:#?}", expr); } } pub fn check_assign<F>(expr: &AST, expected_name: &str, check: F) where F: Fn(&AST) { if let Assign{ ref name, ref init, .. } = *expr { assert_eq!(expected_name, ...
Rust
0
ebracket: bool, pub rightsquarebracket: bool, pub semicolon: bool, pub apostrophe: bool, pub hash: bool, } <filename>test/build_env/tests/manifest_dir.rs #[test] pub fn test_manifest_dir() { let actual = include_str!(concat!( env!("CARGO_MANIFEST_DIR"), "/src/manifest_dir_file.txt" ...
Rust
0
# Faça um programa que use um laço while para exibir os # primeiros 20 termos da sequência de Fibonacci. # 3 - Sequência de Fibonacci: a = 1 b = 1 n = 0 f = 0 cont = 0 while f < 20: n += 1 f = f - (n - 1) + f (n - 2) print(n)
Python
1
lections::HashMap; use gorating::{Rating, RatingSystem}; use rusqlite::types::ToSql; use rusqlite::{Transaction, NO_PARAMS}; use crate::models::GameResult; pub static RATINGS: RatingSystem = RatingSystem::new(); struct PendingRating { rating: Rating, pending: Cell<f64>, } impl PendingRating { fn new(ra...
Rust
0
from torch.utils.checkpoint import checkpoint import ldm.modules.attention import ldm.modules.diffusionmodules.openaimodel def BasicTransformerBlock_forward(self, x, context=None): return checkpoint(self._forward, x, context) def AttentionBlock_forward(self, x): return checkpoint(self._forward, x) def Re...
Python
1
aggregated, global counter. Use this if you don't want any aggregation, /// and just want to expose a value through stats. #[auto_impl(Box)] pub trait SingletonCounter { /// Sets the value of the counter fn set_value(&self, fb: FacebookInit, value: i64); /// Gets the current value of the counter fn get...
Rust
0
# 3. Leetcode 9 - Palindrome Number # https://leetcode.com/problems/palindrome-number/description/ # tc=O(log10 N) # sc=O(1) #Note i have taken org_x to store the orignal value of x for checking whether result==org_x and x is changing as loop is running def ispalin(x:int)->bool: org_x=x res=0 while x>0: ...
Python
1
elf, path, uid, gid): """Change the *owner* of a resource. """ if uid is None or gid is None: info = self.getinfo(path, namespaces=('access',)) uid = uid or info.get('access', 'uid') gid = gid or info.get('access', 'gid') self._sftp.chown(path, uid, gi...
Python
1
import time def countdown(t): while t: mins, secs = divmod(t, 60) timer = '{:02d}:{:02d}'.format(mins,secs) print(timer, end="\r") time.sleep(1) t -= 1 print('Timer completed!') t = input('Enter the time in seconds: ') countdown(int(t))
Python
1
t(); let expected_risk = vec![vec![None; risk[0].len()]; risk.len()]; Ok(Self { risk, expected_risk, }) } } impl Iterator for RiskMap { type Item = i64; fn next(&mut self) -> Option<Self::Item> { let new_expected_risk: Vec<Vec<Option<u64>>> = self ...
Rust
0
#[test] fn encode_connect_request_test() { let mut buf: [u8; 2] = [0x00, 0x00]; let expected: [u8; 2] = [0xca, 0x01]; let result = ConnectRequest.encode(&mut buf); assert_eq!(Ok(2), result); assert_eq!(expected, buf); } #[test] fn parse_get_info_response_se...
Rust
0
Transport<C> where C: Write, { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { if !buf.is_empty() { let mut avail_bytes; loop { avail_bytes = cmp::min(buf.len(), self.cap - self.buf.len()); if avail_bytes == 0 { self.fl...
Rust
0
# SPDX-FileCopyrightText: 2023, 2024 Horus View and Explore B.V. # # SPDX-License-Identifier: MIT from datetime import datetime from sqlalchemy.orm import DeclarativeBase, MappedAsDataclass from sqlalchemy.schema import MetaData from mercaido_client.pb.mercaido import Service as ServiceMessage from .types import Se...
Python
1
id: str, **params: Unpack["InboundTransfer.SucceedParams"] ) -> "InboundTransfer": """ Transitions a test mode created InboundTransfer to the succeeded status. The InboundTransfer must already be in the processing state. """ ... @overload asy...
Python
1
ap, Empty>(&self, n: usize, op: Op, e: E, map: Map, empty: Empty) -> S where S: Clone + Sized, Op: Fn(&S, &S) -> S, E: Fn() -> S, Map: Fn(&S, C) -> S, Empty: Fn() -> S, { let mut dp = HashMap::new(); dp.insert(self.init, (empty)()); for _ in 0 .. n { dp = self.dp_forward(&dp, &...
Rust
0
from datetime import datetime, timedelta class ExpiredDict(dict): def __init__(self, expires_in_seconds): super().__init__() self.expires_in_seconds = expires_in_seconds def __getitem__(self, key): value, expiry_time = super().__getitem__(key) if datetime.now() > expiry_time: ...
Python
1
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.hr_timesheet.tests.test_timesheet import TestCommonTimesheet from odoo.tests import tagged @tagged('post_install', '-at_install') class TestPerformanceTimesheet(TestCommonTimesheet): def test_times...
Python
1
://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ep15_out_control](ep15_out_control) module"] pub type EP15_OUT_CONTROL = crate::Reg<u32, _EP15_OUT_CONTROL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _EP15_OUT_CONTROL; #[doc = "`read()` method returns [ep15_out_contro...
Rust
0
from pydantic import BaseModel from typing import List, Optional import datetime # --- 基础响应模型 --- class MessageResponse(BaseModel): message: str # --- 模板相关的模型 --- class TemplateResponse(BaseModel): id: int name: str filepath: str placeholders: dict class Config: from_attributes = True...
Python
1
an_signals_dataframe(signals_df) signals_df.to_csv(args.output_file, index=False) print(f"Generated {len(signals)} signals") print(f"Cleaned signals count: {len(signals_df)}") print(f"Signals saved to: {args.output_file}") print(f"Final bal...
Python
1
def say_sup(): print(f"SUP! My __name__ is {__name__}") if __name__ == "__main__": say_sup()
Python
1
""" URL configuration for Messenger project. The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/5.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='ho...
Python
1
# -*- coding: utf-8 -*- from odoo import models, fields class SaasK8sClusterNS(models.Model): _name = 'kk_odoo_saas.app.cluster.ns' _description = 'SaaS Cluster NameSpace' name = fields.Char() status = fields.Char() age = fields.Char() all_json = fields.Text('Complete json') class SaasK8sC...
Python
1
# construct a tuple of unpacked data data = () for subfmt in fmt: if subfmt == "S": data += (self.read_string(),) elif subfmt == "Z": data += (self.read_bool(),) else: data += self.read_and_unpack(subfmt) if le...
Python
1
r(f"Invalid key: {key}. Must be one of {', '.join(self.CONFIG_KEYS)}") values = config[key] if isinstance(values, list): for value in values: configs.append(self.get_configentry_obj(key, value, cfile_path)) ...
Python
1
Hash> { match module { Dependency::Hash(hash) => Ok(hash), Dependency::Name(name) => { // resolve module hash by name let map = modules.lock(); let hash = map.get(&name).cloned(); hash.ok_or_else(|| InvalidModuleName(name.clone())) } } } #...
Rust
0
time: float = 0.0 k1: float = 0.693000000000000 k2: float = 0.250000000000000 compartment: float = 10.0000000000000 # Initial assignments dS3 = 0.0005 * k1 dS4 = -0.0005 * k2 S1_amount = 0.0015 * compartment S2_amount = 0.002 * compartment S3_amount = 0.0015 * compartment S4_amount = 0.004 * compartment S1 = S1_amount...
Python
1
ions below: /// /// ``` /// /// My `str` type. /// #[repr(transparent)] /// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] /// pub struct MyStr([u8]); /// /// /// Spec for `MyStr` type. /// enum MyStrSpec {} /// /// impl validated_slice::SliceSpec for MyStrSpec { /// // My `str` type. /// type Custom = ...
Rust
0
educe(lambda total, char:total+ (char.lower() in vowels), string,0) print(result)''' #Laptop_project '''class Laptop: def __init__(self,brand,price,ram,storage): self.brand=brand self.price=price self.ram=ram self.storage=storage def gaming(self): print(f"you are gaming ...
Python
1
8f163db38682925e4491c5e58d4bb3506ef8c14eb78a86e908c5624a67200fe992405f0d785b599a2e3387f6d34d01faccfeb22fb697ef3fd53541241a338c", output.to_hex()); } #[test] fn blake3_256_key_test() { let input = "hello".as_bytes(); let mut output = [0u8; 32]; let key = b"012345678901234567890123456...
Rust
0