text
string
label_name
string
labels
int64
""" Archivo de configuración WSGI para el proyecto Django 'mi_proyecto'. Este archivo expone la aplicación WSGI como una variable llamada 'application'. Es utilizado por servidores compatibles con WSGI (como Gunicorn o uWSGI) para servir tu proyecto en producción. """ import os from django.core.wsgi import get_wsgi_a...
Python
1
coverage results. By treating calls without try `?` operators as non-branching (assumed to // return normally and continue) the coverage graph can be simplified, producing smaller, // faster binaries, and cleaner coverage results. // 5. The reason the coverage results actually show `panic!()` was called is ...
Rust
0
Option<&users::User>, ) -> Result<JobDetails, Box<dyn Error>> { let api_resp = match super::api::job_info(&owner, &job_id, super_admin) { Ok(body) => body, Err(e) => { // eprintln!("Problem getting the Job via API: {}", e); return Err(format!("Problem...
Rust
0
f old == Status::Ok || old == status { if self.status_cas(old.into(), Status::Lock) { *self.wakers[status as usize - 1].borrow_mut() = Some(cx.waker().clone()); let _cas = self.status_cas(Status::Lock, status); debug_assert!(_cas); ...
Rust
0
data, row, col, B, spinfo=spinfo, transpose=transpose) return [coo_matmat_hlo(data, row, col, B, shape=shape, transpose=transpose, x_dtype=B_aval.dtype, data_dtype=data_aval.dtype, ...
Python
1
r<Item = &'a str>>(messages: I) -> Increment { let increment = messages.fold(Increment::NONE, |acc, message| { let increment = semantic_increment(message); // return the biggest increment type return cmp::max(acc, increment); }); increment } fn semantic_increment(message: &str) -> ...
Rust
0
from apis.tourism_api import TourismAPI from apis.weather_api import WeatherAPI from sklearn.cluster import KMeans import numpy as np from collections import defaultdict class Itinerary: """ A system for generating optimized travel itineraries based on destination, duration, and available activities. Now e...
Python
1
0; for cube maps, one of the 6 cube"] #[doc = " faces in the order +X, -X, +Y, -Y, +Z, -Z,"] #[doc = " 0 to 5."] #[doc = " @param [in] width width of the image."] #[doc = " @param [in] height height of the image or, for 1D textures"] #[doc = " ...
Rust
0
itemsPerPage": 10, "totalItems": 100, "totalPages": 10, "pageIndex": 1, // Start from 1 } } Failure: { "apiVersion": "2.0", "error": { "code": 404, "message": "File Not Found", } } */ use crate::CONFIG; use poem_openapi::Object; #[derive(Debug, Serialize, Deseri...
Rust
0
# 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 writing, software # d...
Python
1
= "main =\n println \"Hello World!\""; let mut data = crate::test::mock::Unified::new(); data.set_code(initial_code); let test = |runner: &mut Runner| { let edit_handler = LsClientSetup::new_for_mock_data(&data); let mut fixture = data.fixture_customize(|data, client...
Rust
0
# -*- coding: utf-8 -*- import pytest import irc3 import irc3d from irc3.compat import asyncio @irc3.plugin class P: connections_made = [] def __init__(self, bot): self.bot = bot def connection_made(self, *args, **kwargs): self.bot.log.info('P.connection_made') self.ready.set_re...
Python
1
import transformers from ..functions import helium_rms_norm_forward, nn_linear_forward, llama_mlp_forward from ..patch import _checkpoint_module, _patch_module def apply_patch_to_helium_model( model: "transformers.models.helium.modeling_helium.HeliumPreTrainedModel", norm: bool = False, attn_in: bool = F...
Python
1
self.assertIs(result[-1], None) def test_multi_moment(self): # Test gen.multi with moment # now that it's not a real Future @gen.coroutine def wait_a_moment(): result = yield gen.multi([gen.moment, gen.moment]) raise gen.Return(result) l...
Python
1
> BitAnd for Value<'ir> { type Output = Result<Value<'ir>, ()>; fn bitand(self, other: Value) -> Result<Value<'ir>, ()> { use Value::*; match (self, other) { (U8(a), U8(b)) => Ok(U8(a & b)), (U16(a), U16(b)) => Ok(U16(a & b)), (U32(a), U32(b)) => Ok(U32(a & b...
Rust
0
// // Common queries can be reused with a typedef like this but it is not necessary. type PosVelQuery = (Write<Position>, Read<Velocity>); // Retrieves all entities that have a Position and Velocity component as an iterator. world .matcher::<(&mut Position, &Velocity)>() .for_each(|(pos, _v...
Rust
0
Data::Sparse(data)) .zip(labels) .map(|(data, label)| LabeledData {data, label}) .collect::<Vec<LabeledData>>(); let dtype = DType::Sparse; let sample = Sample { sample, dtype }; Ok(sample) } /// The function `read_csv` reads file with CSV format. /// Each row (data) must hav...
Rust
0
else { self.animation_player.speed_up = 1.0; } } } // The entity is in the air, so it must be jumping or falling else { if self.velocity().y > 0.0 { self.animation_player.play(self.animations.fall.clone()); ...
Rust
0
from collections import namedtuple import psutil import pytest from pysisyphus.helpers_pure import check_mem from pysisyphus.init_logging import init_logging from pysisyphus.calculators.Calculator import Calculator init_logging() def get_mock_mv(available_mb): # kbytes bytes avail...
Python
1
WaitLoadingPlugin) .add_plugin(ShoppingTimerPlugin) .add_plugin(BattlePlugin) .add_plugin(ResultPlugin) .add_plugin(PrintStateNamesPlugin); } } fn check_init_system(mut app_state: ResMut<State<ServerState>>) { app_state .set(ServerState::Lobby) .expect("Can not c...
Rust
0
let mut mint = Mint::new("tests/sql/mutation"); let mut f = mint.new_goldenfile(stringify!($name))?; write!(f, "Query: {}\n", $query.trim())?; match engine.session()?.execute($query) { Ok(resultset) => { write!...
Rust
0
s_sys::{ client_acg, server_acg, ClientACG, ClientFHE, SealClientACG, SealServerACG, ServerACG, ServerFHE, }; pub struct NNProtocol<P: FixedPointParameters> { _share: PhantomData<P>, } pub const CLIENT: usize = 1; pub const SERVER: usize = 2; pub struct ServerState<P: FixedPointParameters> where P::F...
Rust
0
proportion(), "chroma: {:?}", chroma); if chroma == F::ONE { ( (F::ONE + self.second).min(F::TWO), (F::ONE + self.second).min(F::TWO), ) } else { let temp = self.second * chroma; ( (chroma + temp).min(F::THRE...
Rust
0
pub const USER_SERVER_TRUST_ACCOUNT: u32 = 256u32; #[repr(C)] #[doc = "*Required features: `\"Win32_Security_Authentication_Identity\"`, `\"Win32_Foundation\"`, `\"Win32_System_PasswordManagement\"`*"] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_PasswordManagement"))] pub struct USER_SESSION_KEY { ...
Rust
0
-smol")] /// # fn main() { /// # smol::block_on(main_async()) /// # } /// ``` fn par_map<P, T, F, Func>(self, config: P, f: F) -> ParMap<T> where T: 'static + Send, F: 'static + FnMut(Self::Item) -> Func + Send, Func: 'static + FnOnce() -> T + Send, P: IntoPar...
Rust
0
for k in splits: assert all([t in dataset.track_ids for t in splits[k]]) this_split = set(splits[k]) assert not used_tracks.intersection(this_split) used_tracks.update(this_split) except (AttributeError, NotImplementedError): ...
Python
1
ance() sshkey = SSHKeyFingerprintInstance(instance) assert not sshkey.match(SSHKeyFingerprint('7b:0d:a3:0d:9e:fc:f3:97:bb:a8:d2:1d:05:3f:d5:f9')) def test_sshkeyfingerprintinstance_get_fingerprint(): from ploy.common import SSHKeyFingerprint from ploy.common import SSHKeyFingerprintInstance class...
Python
1
ours(), test_fut.as_mut()); let info = fake_disconnect_info(); test_helper .telemetry_sender .send(TelemetryEvent::Disconnected { track_subsequent_downtime: true, info }); test_helper.advance_by(22.hours(), test_fut.as_mut()); let metrics = test_helper.get_logged...
Rust
0
le_dict(instance.__class__, instance) event = BulkUpdateEvent(broadcastable_dict) publish_events([event]) @receiver(post_delete) def post_delete_broadcast(sender, instance, **kwargs): if (in_test_environment() or not isinstance(instance, Broadcasted) or type(instance).__module__ ...
Python
1
ng()) })?; if !Path::new(PUBLIC_KEY_DIR).exists() { create_dir(PUBLIC_KEY_DIR).context("Cannot create directory to save public key")?; } let key_path = Path::new(PUBLIC_KEY_DIR).join(PUBLIC_KEY_NAME); info!("Saving public key to {}", key_path.display()); let...
Rust
0
samples(); let texture = TextureBuilder::new() .size(file_dimensions) .usage(TextureUsage::RENDER_ATTACHMENT | TextureUsage::SAMPLED) .sample_count(sample_count) .format(TextureFormat::Rgba16Float) .build(wgpu_device); let renderer = ...
Rust
0
""" Copyright 2017-2024 SensiML Corporation This file is part of SensiML™ Piccolo AI™. SensiML Piccolo AI 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 optio...
Python
1
# IfcOpenShell - IFC toolkit and geometry engine # Copyright (C) 2024 Dion Moult <dion@thinkmoult.com> # # This file is part of IfcOpenShell. # # IfcOpenShell is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundat...
Python
1
import re patterns = [ (r'\b(?:\w*ed|ing)\b', 'Verb'), (r'\b(?:\w*\'s)\b', 'Noun'), (r'\b(?:The|A|An)\b', 'Determiner'), (r'\b(?:\d+[\.,]?\d*)\b', 'Number'), (r'\b(?:\w+ly)\b', 'Adverb'), (r'\b(?:\w+est)\b', 'Adjective'), (r'\b(?:\w+er)\b', 'Adjective'), ...
Python
1
// before it starts the time. let elapsed = start_time.elapsed(); let elapsed_seconds = elapsed.as_secs() as f64 + elapsed.subsec_nanos() as f64 * 1e-9; eprintln!("vspipe time: {:.2} seconds", elapsed_seconds); } Ok(()) } } #[cfg(not(all( feature = "vssc...
Rust
0
""" WebSocket collectors package for market data collection. """ from .base import BaseWebSocketCollector from .bybit_collector import BybitCollector from .binance_collector import BinanceCollector from .collector_manager import CollectorManager __all__ = [ "BaseWebSocketCollector", "BybitCollector", "Bi...
Python
1
) { if account_meta.is_signer { signed_keys.push(account_meta.pubkey); } else { unsigned_keys.push(account_meta.pubkey); } } (signed_keys, unsigned_keys) } /// Return program ids referenced by all instructions. No duplicates and order is preserved. fn get_progra...
Rust
0
#[test] fn test_ip_value_display() { #[cfg(feature = "host-name")] assert_eq!(IpValue::HostName.to_string(), "test-host-name"); #[cfg(feature = "host-ip")] assert_eq!(IpValue::HostIp.to_string(), "10.2.0.1"); #[cfg(feature = "host-ip")] assert_eq!( ...
Rust
0
let (request, s) = s.recv()?; let s = s.send(-request)?; recurs_storage(s) }, Branching0fromCtoS::Down(s) => { let (_failure, s) = s.recv()?; recurs_storage(s) }, Branching0fromCtoS::Close(s) => { let (_close,...
Rust
0
er.setup(&mut world.res); world.add_resource(LastFrame(Instant::now())); let mut runtime = Runtime::new().unwrap(); runtime.spawn(futures::lazy(move || { timers::start_timer_events(timer.send.unwrap()); Ok(()) })); runtime.spawn(timeloop( move |now| { if Instant::now() - now > Duration::from...
Rust
0
t = t + redis.call('zscore', terms[j], ids[i]) * weights[j] end table.insert(tfidf,t) end -- normal query else -- to much code to call a single zintersore local args = {'zinterstore', query_key, size, unpack(terms) } args[#args + 1] = 'WEIGHTS' for i=1, #weights ...
Python
1
model=("contour_value", contour_value), change=commit_changes, min=("data_range[0]",), max=("data_range[1]",), hide_details=True, dense=True, style="max-width: 300px", ) vuetify.VSwitch( v_model="$vuetify.theme.dark", ...
Python
1
import time from typing import Callable from unilabos.device_comms.modbus_plc.client import TCPClient, ModbusWorkflow, WorkflowAction, load_csv from unilabos.device_comms.modbus_plc.node.modbus import Base as ModbusNodeBase ############ 第一种写法 ############## # modbus_tcp_client_test1 = TCPClient('192.168.3.2', 502) #...
Python
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 🔧 简单命令发送脚本 向WebSocket服务器发送机器人命令 """ import asyncio import websockets import json import time import sys async def send_command(server_url, robot_id, command): """发送命令到WebSocket服务器""" try: # 连接到WebSocket服务器 async with websockets.connect(serve...
Python
1
udozhestvennaya-literatura'>Художественная литература</a><ul><li><a href='https://www.wildberries.ru/catalog/knigi/hudozhestvennaya-literatura/aforizmy-folklor-mify'>Афоризмы, фольклор и мифы</a></li><li><a href='https://www.wildberries.ru/catalog/knigi/hudozhestvennaya-literatura/detektivy'>Детективы</a></li><li><a hr...
Python
1
_THREAD.Wakeup(shareSpace); } pub fn SharespaceReady(&mut self) -> &mut AtomicU32 { return &mut self.sharespaceReady; } pub fn WaitShareSpaceReady() -> i32 { let addr = super::SYNC_MGR.lock().SharespaceReady().get_mut() as *const _ as u64; let ret = Self::Futex(addr, FUTEX_WAI...
Rust
0
rx_bytes), rx_packets: self.rx_packets.wrapping_add(rhs.rx_packets), tx_bytes: self.tx_bytes.wrapping_add(rhs.tx_bytes), tx_packets: self.tx_packets.wrapping_add(rhs.tx_packets), } } } impl<'a> Sum<&'a Entry> for Entry { fn sum<I: Iterator<Item = &'a Entry>>(iter: I)...
Rust
0
gateways(deps.storage).save(sender_bytes, &bond)?; Ok(HandleResponse { messages: vec![], attributes, data: None, }) } pub(crate) fn try_remove_gateway( deps: DepsMut, info: MessageInfo, env: Env, ) -> Result<HandleResponse, ContractError> { let sender_bytes = info.se...
Rust
0
import numpy as np import matplotlib.pyplot as plt def sigmoid(x): return 1 / (1 + np.exp(-x)) def compute_energy(v, h, W, b, c): return -np.dot(v, b) - np.dot(h, c) - np.dot(np.dot(v, W), h) def sample_bernoulli(probs): return (probs > np.random.random(probs.shape)).astype(float) def entree_sortie_RBM(...
Python
1
n(filename)?; Ok(joined) } /// Download a file from a base url. pub fn curl_url(url: &str, output_directory: &std::path::Path) { // Generate url to get file let mut easy = Easy::new(); let file_url = url.to_string(); easy.url(&file_url).unwrap(); let file_name = Path::new(&file_url).file_name()...
Rust
0
way of assigning UVs to voxel quads. It assumes that each material has a /// single tile texture with wrapping coordinates, and each voxel face should show the entire /// texture. It also assumes a particular orientation for the texture. This should be sufficient /// for minecraft-style meshing. /// ...
Rust
0
for (_, angle_points) in builder { flat_map.push(angle_points.into_vec()) } RadialMap { origin, points: flat_map, } } pub fn visable(&self) -> usize { self.points.len() } pub fn sweep(&...
Rust
0
et_expire(key: &[u8], expire: u64) -> (); /// Get a value from the local cache. /// /// Only for query functions. Always returns `None` if it is called from a command context. #[ink(extension = 0xff000008, handle_status = false, returns_result = false)] fn cache_get(key: &[u8]) -> Option<Vec<u8>>; ...
Rust
0
Some("375"), Some("400"))); assert!(s.overlaps(Some("450"), Some("450"))); assert!(s.overlaps(Some("450"), Some("500"))); } #[test] fn test_multiple_null_boundaries() { let mut s = VersionManagerTest::new(); s.add("150", "200", 100, 100); s.add("200", "250", 100, 100...
Rust
0
import pytest try: from postal.parser import parse_address postal_available = True except ImportError: postal_available = False parse_address = lambda x: x skip_if_no_postal = pytest.mark.skipif( not postal_available, reason="postal package is not installed" ) @skip_if_no_postal def test_us_add...
Python
1
ization) video = factories.VideoFactory(playlist=playlist) factories.OrganizationAccessFactory( user=user, organization=organization, role=models.INSTRUCTOR ) jwt_token = UserAccessTokenFactory(user=user) response = self.client.post( self._post_url(video...
Python
1
# database/classes_db.py文件中 # 从数据库模块中导入基础数据库管理类 DatabaseManage import random from DataBase.base_db import DataBaseManage # 定义一个类 ClassDB,继承自 DatabaseManage class ParishDb(DataBaseManage): # 定义一个方法 fetch_classes,用于从数据库中获取班级信息 def fetch_parish(self): # 定义 SQL 查询语句,用于选择 CLASSES 表中的所有数据 query = "...
Python
1
} #[inline] fn cvt_from_bytes(src: [u8; 8]) -> u64 { #[cfg(target_endian = "little")] { u64::from_le_bytes(src) } #[cfg(target_endian = "big")] { u64::from_be_bytes(src) } } fn crypt_block(&self, dst: &mu...
Rust
0
::Visitor for CollectionVisitor { type Value = Collection; fn expecting() -> &'static str { "a Collection" } async fn visit_map<A: de::MapAccess>(self, mut map: A) -> Result<Self::Value, A::Error> { let classpath = map .next_key::<TCPathBuf>(()) .await? ...
Rust
0
kage::default().raw).unwrap(), bench::Signature::from_base64_str(bench::Signature::INVALID_SAMPLE), )), }; self.requests += 1; Ok(res) } } #[async_trait::async_trait(?Send)] impl bench::AppImpl for App { type Err = Err; type RemoteClient = RemoteClient; ...
Rust
0
import torch import numpy as np import torch.nn as nn from torch.utils.data import DataLoader from torchvision import transforms import torchvision.models as models from torchvision.models import ResNet18_Weights from CustomDataset import CustomDataset from train_evaluate import train_model, evaluate_model from upload...
Python
1
JITTER: *mut *mut c_void, layout: u32, transa: u32, transb: u32, m: usize, n: usize, k: usize, alpha: f32, lda: usize, ldb: usize, beta: f32, ldc: usize, ) -> u32; fn mkl_jit_get_sgemm_ptr(JITTER: *const c_void) -> SgemmJitK...
Rust
0
from core import start, register_plugin, set_bounds, add_initialization_hook
Python
1
command: ISO7816Command) -> ISO7816Response: """Sends a plain command and expects a secure response""" decrypted_response, self.counter = self.decrypt_response( self.tag.transceive(command) ) return decrypted_response def transceive_secure_secure(self, command: ISO7816C...
Python
1
State::Waiting(ref mut func) => { // if !func(self) { // self.state = mut_state; // false // } else { // true // } // } // ...
Rust
0
import sys from collections import deque input = sys.stdin.readline #상자의 가로 칸의 수, 세로 칸의 수 입력받기 M, N = map(int, input().split()) #그래프 초기화 graph = [[] for _ in range(N)] #토마토 정보 세팅 #익은 토마토 1 #익지않은 토마토 0 #토마토가 들어있지 않은 칸 -1 for i in range(N): graph[i] = list(map(int, input().split())) q = deque([]) for i in ra...
Python
1
import pandas as pd from sqlalchemy import create_engine def csv_to_database(csv_file): df = pd.read_csv(csv_file, index_col=0) engine = create_engine(f'sqlite:///ncaa_game_stats.db') df.to_sql( csv_file[csv_file.index("/")+1:csv_file.index(".")], engine, if_exists='replace', index=False ...
Python
1
logging.info(f"Method: {method_name}, " f"Spearman: {result['mean_spearman']:.2f}") except Exception as e: logging.error(f"Error evaluating method {method_name}: {str(e)}") continue # Save results if results: s...
Python
1
RE) def check_update_info_github(self): """ 从 GitHub 获取最新发布版本的信息。 返回: 最新发布版本的信息(JSON 格式) """ if not cfg.update_prerelease_enable: response = requests.get( f"https://api.github.com/repos/{self.user}/{self.repo}/releases/latest", ...
Python
1
st _spinLogicBlockLUTInputActivationEnums_LogicBlockLUTInputActivation_RisingEdge: _spinLogicBlockLUTInputActivationEnums = 3; #[doc = "<"] pub const _spinLogicBlockLUTInputActivationEnums_LogicBlockLUTInputActivation_AnyEdge: _spinLogicBlockLUTInputActivationEnums = 4; pub const _spinLogicBlockLUTInputActivati...
Rust
0
import secrets from Crypto.Util import Counter from Crypto.Cipher import AES def encrypt(plaintext: str, key: str | bytes) -> (bytes, bytes): """Encrypts the given plaintext using the given 32-byte key. (The underlying cipher is AES in counter mode.) Returns a randomly-generated initialisation vector alo...
Python
1
ns.index(token) vllm_logprob = vllm_logprob_values[vllm_idx].logprob print( f" Token {token}: HF={hf_logprob:.4f}, vLLM={vllm_logprob:.4f}, diff={abs(hf_logprob - vllm_logprob):.4f}" ) else: print("❌ No common tokens in top 5") ...
Python
1
_ = 1 + 1
Python
1
constructor; let object = constructor(); let boxed: Box<dyn PathRewritePlugin + Sync> = Box::new(object); Box::into_raw(boxed) } }; } /// Plugin manager to handle multiple plugins #[derive(Default)] pub struct PathRewritePluginManager { plugins: Vec<Box<dyn PathRewr...
Rust
0
error!(logger, "GraphQLService call failed: {}", err); Ok(Response::builder() .status(500) .header("Content-Type", "text/plain") .body(Body::from(format!("Query error: {}", err))) .u...
Rust
0
import torch import math import numpy as np def truncated_normal_(tensor, mean=0, std=1): size = tensor.shape tmp = tensor.new_empty(size + (4,)).normal_() valid = (tmp < 2) & (tmp > -2) ind = valid.max(-1, keepdim=True)[1] tensor.data.copy_(tmp.gather(-1, ind).squeeze(-1)) tensor.data.mul_(std...
Python
1
print({x: 0 for x in [1, 2, 3]})
Python
1
了 return true; } path[start_row as usize][start_column as usize - 1] = true; return true; } if check( // 往右边找 &word_vec, board, start_row, start_column + 1, index + 1, &mut path.clone(), ) { if word_vec[inde...
Rust
0
[`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields ...
Rust
0
# Step 3: Fetch the updated certificate new_cert_data = self.fetcher.fetch_certificate(update_url) new_cert_info = self.parser.parse_certificate_data(new_cert_data) # Step 4: Verify the new certificate is_valid, reason = self.verifier.verify_c...
Python
1
level: level, server: addr, sock: sock, hostname: hostname.trim().to_string(), }) })); Ok(()) } impl Gelf { fn message_id(&self) -> u64 { use chrono::Timelike; let mut s = DefaultHasher::new(); self.host.hash(&mut s); sel...
Rust
0
nFactory.rs net.sf.jasperreports.engine.util.SingleProtectionDomainFactory <reponame>kitsonk/swc<filename>macros/enum_kind/src/input.rs use syn::*; /// Parsed input. #[derive(Debug)] pub struct Input { pub attrs: EnumAttrs, /// Name of enum. pub name: Ident, pub vis: Visibility, pub generics: Gener...
Rust
0
x21,0x46,0x01,0x34,0x21]); // Validate the average case yielded the anticipated result. let ihex_rep_disjoint = ihex_representation_of_data_ranges(&[range_a, range_b]); let expected_ihex_rep_disjoint = String::new() + &":10010000214601360121470136007EFE09D2190140\n" + &":100130003F0156702B5E71...
Rust
0
""" Classifies: CHEBI:33303 chalcogen """ from rdkit import Chem def is_chalcogen(smiles: str): """ Determines if a SMILES string represents a chalcogen atom. Args: smiles (str): SMILES string of a chemical entity Returns: bool: True if the SMILES represents a chalcogen atom, False ot...
Python
1
children = struct_elem['/K'] except KeyError: return # if there's only one child, /K need not be an array if not isinstance(children, generic.ArrayObject): children = (children,) for child in children: child_ref = None ...
Python
1
import torch import torch.nn.functional as F def naively_compute_sequentially(coeffs, values, init): x = [init] # x_0 for a, b in zip(coeffs, values): x.append(a * x[-1] + b) return torch.stack(x) device = "cuda:0" # change as necessary seq_len = 10000 # change as you wish # Generate some ra...
Python
1
Type: *const SLchar, pub containerType: SLuint32, } pub type SLDataFormat_MIME = SLDataFormat_MIME_; #[doc = " PCM-type-based data format definition where formatType must be SL_DATAFORMAT_PCM"] #[repr(C)] pub struct SLDataFormat_PCM_ { pub formatType: SLuint32, pub numChannels: SLuint32, pub samplesPerS...
Rust
0
&salt, 8192, 8, 1).unwrap(); /// assert_eq!(key.len(), 32); /// ``` pub fn derive_key_from_password( algo: &str, out_len: usize, passphrase: &str, salt: &[u8], param1: usize, param2: usize, param3: usize) -> Result<Vec<u8>> { let algo = make_cstr(algo)?; let passphrase = make_cstr(p...
Rust
0
e above two methods for more information. """ return self.tokenizer.batch_decode( token_ids=token_ids, feature_extractor_output=feature_extractor_output, return_midi=return_midi ) @property def model_input_names(self): tokenizer_input_names = self.tokenizer.model_in...
Python
1
u32; } #[doc = "`read()` method returns [rsr::R](R) reader structure"] impl crate::Readable for RSR_SPEC { type Reader = R; } #[doc = "`reset()` method sets RSR to value 0x02"] impl crate::Resettable for RSR_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0x02 } } <filename>src/before_s...
Rust
0
Reader::new(bits)) } } impl core::ops::Deref for ADPLL_LF_BETA_BASE_RX_R { type Target = crate::FieldReader<u8, u8>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `adpll_lf_beta_base_rx` writer - "] pub struct ADPLL_LF_BETA_BASE_RX_W<'a> { w: &'a mut W, ...
Rust
0
# from http://coreygoldberg.blogspot.com/2013/01/python-verify-png-file-and-get-image.html import struct def is_png(data): return (data[:8] == '\211PNG\r\n\032\n'and (data[12:16] == 'IHDR')) def get_image_info(data): if is_png(data): w, h = struct.unpack('>LL', data[16:24]) width = int(w) ...
Python
1
""" Tests automatic loading of ip adapter """ import os import PIL from enfugue.util import logger, image_from_uri, fit_image from enfugue.diffusion.engine import DiffusionEngine from pibble.util.log import DebugUnifiedLoggingContext BASE_IMAGE = "https://huggingface.co/lllyasviel/control_v11p_sd15_openpose/resolve/m...
Python
1
use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; let mut hasher = DefaultHasher::new(); a.0.hash(&mut hasher); hasher.finish() as i32 }, title: common::str_to_wchar(&a.0), c...
Rust
0
# removeLineBreaks.py # # Demonstration of the pyparsing module, converting text files # with hard line-breaks to text files with line breaks only # between paragraphs. (Helps when converting downloads from Project # Gutenberg - https://www.gutenberg.org/ - to import to word processing apps # that can reformat paragra...
Python
1
al(status, 200) def test_download_ImageNetES(self): status = urlopen("https://drive.google.com/uc?id=" + ImageNetES.gdrive_id).getcode() self.assertEqual(status, 200) def test_download_SSBHard(self): status = urlopen("https://drive.google.com/uc?id=" + SSBHard.gdrive_id).getcode() ...
Python
1
rogram expects /// a single account that is owned by the program as an argument and /// no instructions. /// /// The account passed in ought to contain a `CandidateAccount`. This /// program will increment the `age` value in the /// `CandidateAccount` when executed. pub fn process_instruction( program_id: &Pubkey, ...
Rust
0
s html_text = call_args[1]['html_text'] # 祝福の効果説明が含まれる assert "攻撃力・防御力が上昇" in html_text assert "クリティカル率が向上" in html_text assert "効果は1回の戦闘まで持続" in html_text class TestBlessingPanelActions: """BlessingPanelのアクション機能テスト(基...
Python
1
0x23, 0x45, 0x67]),Ok((empty,0x1234567))); assert_eq!(parse_der_u32(&[0x02, 0x04, 0xff, 0xff, 0xff, 0xff]),Ok((empty,0xffffffff))); let s = &[0x02, 0x05, 0x01, 0x23, 0x45, 0x67, 0x89]; assert_eq!(parse_der_u32(s),Err(Err::Error(error_position!(&s[2..],ErrorKind::Custom(DER_INTEGER_TOO_LARGE))))); let s...
Rust
0
_from_extern(r) } ) } /// Performs object detection without a multi-scale window. /// /// ## Parameters /// * img: Source image. CV_8UC1 and CV_8UC4 types are supported for now. /// * found_locations: Left-top corner points of detected objects boundaries. /// * confidences: Optional output array for confidenc...
Rust
0