text
string
label_name
string
labels
int64
pyrender.Mesh.from_points(self.points)) pyrender.Viewer(scene, use_raymond_lighting=True, point_size=2) def is_outside(self, points): # project points to camera view RT = np.linalg.inv(self.camera_pose) pc = points.T pc_camera = RT[:3, :3] @ pc + RT[:3, 3].reshape((3, 1)) ...
Python
1
# -*- coding: utf-8 -*- # Copyright 2025 Google LLC # # 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...
Python
1
N in app's .env file custom_subdomain = get_custom_subdomain_from_env(app_name) if custom_subdomain: subdomain = custom_subdomain # Create app entry app_entry = { "name": app_info.get("name", app_name.capitalize()), ...
Python
1
0)], cpsr: CPSR::default(), cycles: 0, } ) ]; for (i, (in_data, out_data)) in data.iter().enumerate() { in_data.run_test(i, out_data); } } #[test] fn test_msr() { let data = vec![ ( // MSR CPSR_flg, R1 TestIn {...
Rust
0
tsec.FALCON_DMATRFCMD.set(TSEC_FALCON_DMATRFCMD_IMEM); tsec_dma_wait_idle(tsec)?; } Ok(()) } fn execute_tsec_fw( firmware: &[u8], boot_vector_address: u32, argument0: &mut u32, argument1: &mut u32, ) -> Result<(), FalconError> { let mut res; Clock::SE.enable(); Clock::H...
Rust
0
def place(self, num_bytes): node_edges = {} tensor_shapes = {} for node in self.nodes: for x in node.inputs: if x.name in node_edges: node_edges[x.name] += 1 else: node_edges[x.name] = 1 tensor_shapes[x.name] = x.shape active_te...
Python
1
} // Just panic if we get a poisoned/other error. This shouldn't // happen, and indicates a run-time bug. e @ Err(_) => e.unwrap(), }; return Ok(_dev); } } impl<D, C> Manager for DeviceManager<D, C> where D: Device + Send + 'static, C: governor::cl...
Rust
0
:Env::from_ptr(self.0.env); let (class, field) = env.require_class_field("android/net/wifi/WifiConfiguration\0", "wepKeys\0", "[Ljava/lang/String;\0"); env.get_object_field(class, field) } } /// **set** public [wepKeys](https://developer.android.com/reference...
Rust
0
# if width or height > 2000 pixels, don't enlarge the image if pm.width > 2000 or pm.height > 2000: pm = page.get_pixmap(matrix=fitz.Matrix(1, 1), alpha=False) img = Image.frombytes("RGB", [pm.width, pm.height], pm.samples) img = cv2.cvtColor(...
Python
1
_loc = player_locs .iter() .min_by_key(|player_loc| { let diff = position - **player_loc; (diff.x * diff.x + diff.y * diff.y).round() as i64 })?; let displacement = *closest_player_loc - position; let distance = displacemen...
Rust
0
carriage. let x_origin = x; for ch in se.chars() { if ch == '\n' { y += 8; x = x_origin; continue; } self.draw_char(ch, x, y, color, self.cur_page_idx1); x += 1; ...
Rust
0
from django_components import component @component.register("flat_example") class FlatExample(component.Component): template_name = "flat_example_component.html" def get_context_data(self): return {}
Python
1
ess # ----------------------------- # We visualize the network's community prediction on one training example, # together with the ground truth. pmpd1 = sparse2th(pmpd1) LG1 = G1.line_graph(backtracking=False) z = model(G1, LG1, pmpd1) _, pred = th.max(z, 1) visualize(pred, nx_G1) ####################################...
Python
1
k(Trace([]))) if (code_width_support or attr != "code_width") ] ) tb.__rich_console__.return_value = "for Python 3.8 compatibility" with mock.patch.object( dev.Traceback, "from_exception", return_value=tb ) as factory: try: ...
Python
1
import json import os import re from pandas.util._print_versions import ( _get_dependency_info, _get_sys_info, ) import pandas as pd def test_show_versions(tmpdir): # GH39701 as_json = os.path.join(tmpdir, "test_output.json") pd.show_versions(as_json=as_json) with open(as_json, encoding="u...
Python
1
= board.generate_moves(); if moves.is_empty() { if board.in_check() { return ScoringMove::blank(MATE_V + (board.depth() as i16)); } else { return ScoringMove::blank(DRAW_V); } } let mut best_move: BitMove = BitMove::null(); for mov in moves { ...
Rust
0
import NssMPC.application.neural_network as nn from NssMPC.crypto.protocols.replicated_secret_sharing.honest_majority_functional import * from data.AlexNet.Alexnet import AlexNet # 测试恶意乘法 secure_model = 0 if secure_model == 0: from NssMPC.application.neural_network.party.neural_network_party import HonestMajority...
Python
1
acc" if has_top1 else DEFAULT_LOSS_KEY).item() print( f"Saving model for epoch {epoch} and {metric_name} " f"{metric} to {save_dir} for {save_name}" ) exporter = ModuleExporter(model, save_dir) exporter.export_pytorch(optim, epoch, f"{save_name}.pth") exporter.export_onnx( to...
Python
1
respond(format!( "You are setting this channel to be a verification channel. This will cause \ the bot to:\n\ • Delete all messages currently in in this channel.\n\ • Delete any messages sent by other users in this channel immediately \ ...
Rust
0
= "Norway")] Nor, #[strum(serialize = "Oman")] Omn, #[strum(serialize = "Pakistan")] Pak, #[strum(serialize = "Palau")] Plw, #[strum(serialize = "Palestine")] Pse, #[strum(serialize = "Panama")] Pan, #[strum(serialize = "Papua New Guinea")] Png, #[strum(serialize...
Rust
0
# print(15+4) # print(3-2) # print(3*2) # print(15%4) x = 4 y = -4 print(x / y)
Python
1
state_dict = fairseq_model.lm.state_dict() decoder_state_dict, enc_dec_proj_state_dict = rename_state_dict( decoder_state_dict, hidden_size=decoder_config.hidden_size ) text_encoder = T5EncoderModel.from_pretrained("t5-base") audio_encoder = EncodecModel.from_pretrained("facebook/encodec_32khz"...
Python
1
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Guidance algorithms. Reference: T. I. Fossen (2021). Handbook of Marine Craft Hydrodynamics and Motion Control. 2nd. Edition, Wiley. URL: www.fossen.biz/wiley Author: Thor I. Fossen """ import numpy as np import math # [x_d,v_d,a_d] = refModel3(x_d,v_d,a_d,r,w...
Python
1
atrix pub fn generate_random_symmetric(dim: usize, magnitude: f64) -> Array2<f64> { let arr: Array2<f64> = random((dim, dim)) * magnitude; arr.dot(&arr.t()) } pub fn sort_vector<T: PartialOrd>(vs: &mut Vec<T>, ascending: bool) { if ascending { vs.sort_unstable_by(|a, b| a.partial_cmp(b).unwrap()); ...
Rust
0
import json from PySide6.QtCore import QObject, Signal CONFIG_FILE = "sakura-launcher_config.json" class Setting(QObject): llamacpp_path = "" model_search_paths = "" model_sort_option = "修改时间" remember_window_state = False remember_advanced_state = False no_gpu_ability_check = False windo...
Python
1
from .augmenter import Augmenter from .categorical_mlp import CategoricalMLP from .clip import CLIPForImageText from .document_transformer import DocumentTransformer from .ft_transformer import FT_Transformer from .fusion import ( AbstractMultimodalFusionModel, MultimodalFusionMLP, MultimodalFusionNER, ...
Python
1
| { debug!("{}", show_proc_maps(e)); }); } <reponame>teythoon/rustneat extern crate rustneat; #[cfg(test)] mod test { use rustneat::{Environment, Organism, Population}; struct MyEnvironment; impl Environment for MyEnvironment { fn test(&self, _: &mut Organism) -> f64 { ...
Rust
0
k::{env, near_bindgen}; // Podemos usar "as" para dar apelidos a funções ou módulos importados. use a_module::hello as hello; use a_module::specific_module::hello as hello1; // pub use torna a função disponível para crates externos. pub use another_module::hello as hello2; pub use yet_another_module::hello as hello3;...
Rust
0
failover_peers=config.failover_peers_v6, shared_networks=config.shared_networks_v6, hosts=config.hosts_v6, omapi_key=config.omapi_key, ).encode("utf-8") ).decode("utf-8") result["dhcpd6_interfaces"] = base64.b64encode( interfaces_v6.encode("utf-8") )...
Python
1
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright 2014-2025 by Alexis Pietak & Cecil Curry. # See "LICENSE" for further details. ''' Blast-proof utilities. ''' #FIXME: Consider offshoring this entire subpackage into a new independent #Python project co...
Python
1
Per Square Inch`: KiloLB_F_PER_IN2, "KiloLB_F-PER-IN2", /// `Kilometre `: KiloM, "KiloM", /// `Kilometres per day`: KiloM_PER_DAY, "KiloM-PER-DAY", /// `Kilometre per Hour`: KiloM_PER_HR, "KiloM-PER-HR", /// `Kilometre per Second`: KiloM_PER_SEC, "KiloM-PER-SEC", /// `Cubic...
Rust
0
car_TA_StartNewGame(self.addr()); } } fn reset_game(&self) { unsafe { GameEvent_Soccar_TA_ResetGame(self.addr()); } } fn clear_replicated_stat_event(&self) { unsafe { GameEvent_Soccar_TA_ClearReplicatedStatEvent(self.addr()); } } fn...
Rust
0
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
Python
1
ing::format(file.clone())?); let wear_leveling = Rc::new(WearLeveling::new(file)?); (Some(wear_leveling.clone()), wear_leveling) } else { (None, file) }; let save = Rc::new(AesCtrFile::new(file, key, [0; 16], repeat_ctr)); SaveData::format(save, Save...
Rust
0
{ assert_eq!( shape( "tests/fonts/in-house/4d4206e30b2dbf1c1ef492a8eae1c9e7829ebad8.ttf", "\u{182D}\u{182D}\u{180B}", "", ), "uni182D.E8E2_g.init=0+1000|\ uni182D.E8E8_g.fina1=1+1250" ); } #[test] fn mongolian_variation_selector_006() { ...
Rust
0
mod addressing_mode; use crate::addressing; use crate::Emitter; use addressing_mode::AddressingModeOrReference; use isa_mos6502::{addressing_mode::AddressingMode, mnemonic::Mnemonic}; use std::fmt; #[cfg(test)] mod tests; /// OpCode represents an unsigned 8bit value. pub type OpCode = u8; impl addressing::SizeOf for...
Rust
0
on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use futures::future::join_all; use serde::{Deserialize, Serialize}; use crate::{ ipc_connect_with_path, ipc_rec...
Rust
0
_namespace3); assert_eq!(prefix3.len(), 0xFFFF + 2); assert_eq!(&prefix3[0..2], b"\xFF\xFF"); } #[test] #[should_panic(expected = "only supports namespaces up to length 0xFFFF")] fn key_prefix_panics_for_too_long_prefix() { let limit = 0xFFFF; let long_namespace = vec![0...
Rust
0
import numpy as np import tifffile from pathlib import Path from sklearn.decomposition import NMF from skimage.filters import threshold_otsu from imageio.v2 import imwrite import pandas as pd import re from tkinter import filedialog, Tk def nmf_remove_background(img, n_components=2, keep_component=1): h, w = img....
Python
1
self.queue.pop_front(); if let Some(waiting_customer) = next_to_be_served { let customer = Customer::start_service(waiting_customer, self.time); self.in_service.push(customer); } } else { let arriving_customer = self.next_customer; ...
Rust
0
hkrnsana tmfeymay tcnogxpv lnlrpnzt vavbgplk kjymlakj tmlseyul zfowvrum yzvwvrmw qntgqett vwwqkqdt xlfedyzg ehxpxwjn wmijbqgj idftxkgo mymigedt bmouaruq bxnbmvxz jqmgqwta idawdbub opxennsn jeotjdhx sojzqnpa xouarvap yjuoninr vqjogzjl khzkueji ndoiuxtm wifnoizv afzkeddd pfyyvihg pcsrligt xnsxcyrz gzququlr vihfqqdo lsbs...
Rust
0
lo); let c = proptest::collection::size_range((1, 100)); // This crashes because of bounds error // let c = proptest::collection::size_range((lo, hi)); let v: Vec<Repo> = (lo..=(hi)) .map(|i| i.to_string()) .map(Repo::new) .collect_vec(); let ...
Rust
0
<'a, T: ?Sized + Writer<'a, C>>( &'a self, writer: &mut T, ) -> Result<(), std::io::Error> { writer.write_bytes(&self.0).map(|_| ()) } } #[derive( BorshSerialize, BorshDeserialize, Debug, Clone, Eq, PartialEq, SerdeSerialize, SerdeDeserialize, )] pub struct Signature([u8; 32]); impl...
Rust
0
ports["mz_system"] = c.port("materialized", 6877) if scenario == Scenario.ZeroDowntimeDeploy: ports["materialized2"] = 7075 ports["http2"] = 7076 ports["mz_system2"] = 7077 # try: run( "127.0.0.1", ports, args.seed, ...
Python
1
_cmpxchg(oldval: u32, newval: u32, ptr: *mut u32) -> bool { let f: extern "C" fn(u32, u32, *mut u32) -> u32 = mem::transmute(0xffff0fc0u32); f(oldval, newval, ptr) == 0 } unsafe fn __kuser_memory_barrier() { let f: extern "C" fn() = mem::transmute(0xffff0fa0u32); f(); } // Word-align a pointer fn align...
Rust
0
risultati = [] def area_triangolo(): base = float(input("Inserire base del triangolo: ")) altezza = float(input("Inserire altezza del triangolo: ")) return (base * altezza) / 2 def area_quadrato(): lato = float(input("Inserire il lato del quadrato: ")) return (lato * lato) def area_rettangolo...
Python
1
() -> Self::Ux { 0 } } <gh_stars>0 #![cfg_attr(all(feature = "no-std", not(test)), no_std)] #![warn( missing_copy_implementations, missing_debug_implementations, clippy::dbg_macro, clippy::missing_safety_doc, clippy::wildcard_imports, clippy::shadow_unrelated )] extern crate alloc; ...
Rust
0
import socra from socra.utils.decorators import throttle from socra.utils.spinner import Spinner import typing from socra.nodes import Node class Inputs(socra.Schema): node: Node prompt: str class NodeContentUpdate(socra.Action[Inputs, str]): """ Node content update action. """ Inputs: ty...
Python
1
#!/usr/bin/env python # Test vtkRenderLargeImage with a renderer that uses a gradient background from vtkmodules.vtkFiltersHybrid import vtkRenderLargeImage from vtkmodules.vtkIOImport import vtk3DSImporter from vtkmodules.vtkInteractionImage import vtkImageViewer from vtkmodules.vtkRenderingCore import ( vtkRend...
Python
1
mut_str()), ctx)?; Ok(Owned { data: Pin::new(data), value: Some(inner), }) } } use crate::{utils, wire_msg::WireMsg, Config, QuicP2p}; use anyhow::{anyhow, Error, Result}; #[tokio::test] async fn echo_service() -> Result<()> { utils::init_logging(); // Endpoint buil...
Rust
0
that ought to be fine, right? And, in my testing, /// it does seem to work. /// /// But thinking more carefully about it it seems that this is not *guaranteed* to /// be the case. This is supported by the fact that the rust API appears to avoid what /// would otherwise be obvious additions, such as a method to return ...
Rust
0
, 648518346341351424u64, ]); } #[allow(dead_code)] pub const FQ_ONE: Fq = Fq::new(FqParameters::R); #[allow(dead_code)] pub const FQ_ZERO: Fq = Fq::new(BigInteger([0, 0, 0, 0, 0, 0, 0])); #[allow(dead_code)] pub const FQ_TWO: Fq = field_new!(Fq, "2"); <filename>cli/src/commands/cheqd_keys.rs extern crate r...
Rust
0
upper_left_y = row * 3; let upper_left_x = col * 3; match *x { DIAG_UNEXPLORED => {} DIAG_GENERATED => { writeln!( dest, "<rect x=\"{}\" y=\"{}\" width=\"3\" height=\"3\" style=\"stroke-width:0.1px;stroke:#ffff00;fill:#ffff00\"/>", ...
Rust
0
self: &mut Self) -> u8 { let dd = self.fetch_byte(); self.registers.program_counter += dd as i32; 12 } fn cp_n(self: &mut Self) -> u8 { let n = self.fetch_byte(); let ret = self.registers.a - n; // self.registers.flags.evaluate_effect( // self.registers.a...
Rust
0
32, path_bbox_alloc: path_bbox_alloc as u32, drawmonoid_alloc: drawmonoid_alloc as u32, clip_bic_alloc: clip_bic_alloc as u32, clip_stack_alloc: clip_stack_alloc as u32, clip_bbox_alloc: clip_bbox_alloc as u32, n_clip: n_clip as u32, .....
Rust
0
last_tag = content['tag'] font = ImageFont.truetype(params[f'font_{last_tag}'], params[f'font_{last_tag}_size']) # 在循环之前进行判断返回,避免过多处理字段 if y > y_limit - (font.getbbox('的')[3] - font.getbbox('的')[1]) and ellipsis: return {'canvas': canvas, 'canvas_bottom': y} if should...
Python
1
&ChangeSet| { &m.checksum }, |m: &mut ChangeSet| { &mut m.checksum }, )); fields.push(::protobuf::reflect::accessor::make_simple_field_accessor::<_, ::protobuf::types::ProtobufTypeString>( "format", |m: &ChangeSet| { &m.format }, |...
Rust
0
None => None, Some(shm) => Some(shm.clone()), } } fn dissociateKey(&self, shm: &Shm) { let mut me = self.lock(); let mut s = shm.lock(); if s.key != IPC_PRIVATE { me.keysToShms.remove(&s.key); s.key = IPC_PRIVATE; } }...
Rust
0
import os import numpy as np import torch import torchvision.datasets as datasets from .imagenet import ImageNetSubsample, ImageNetSubsampleValClasses CLASS_SUBLIST = [ 6, 11, 13, 15, 17, 22, 23, 27, 30, 37, 39, 42, 47, 50, 57, 70, 71, 76, 79, 89, 90, 94, 96, 97, 99, 105, 107, 108, 110, 113, 124, 125, 13...
Python
1
self.client.request(r).await } /// 说明 : 歌单能看到歌单名字, 但看不到具体歌单内容 , 调用此接口 , 传入歌单 id, /// 可以获取对应歌单内的所有的音乐(未登录状态只能获取不完整的歌单,登录后是完整的), /// 但是返回的trackIds是完整的,tracks 则是不完整的, /// 可拿全部 trackIds 请求一次 song/detail 接口获取所有歌曲的详情 /// /// required /// 必选参数 : id : 歌单 id /// /// optional ...
Rust
0
collect_types(types); E::collect_types(types); } } impl Serializable for String { fn ident() -> TypeIdent { TypeIdent::from("String") } fn ty() -> Type { Type::String } } impl<T> Serializable for Vec<T> where T: Serializable, { fn ident() -> TypeIdent { Typ...
Rust
0
n = 0 cont = 0 while n <= 10: n =
Python
1
# [Grand Athenaeum] Ariant : Near the Castle sm.removeEscapeButton() sm.setSpeakerID(2510001) sm.sendNext("Hatsar is struggling with the monsters that have been hounding his trade route.") sm.flipDialoguePlayerAsSpeaker() sm.sendSay("(The monsters were definitely peculiar... Felt like something ghoulish.)") sm.setSp...
Python
1
# Copyright (C) 2022-2025 Intel Corporation # LIMITED EDGE SOFTWARE DISTRIBUTION LICENSE from unittest.mock import patch from testfixtures import compare from communication.rest_views.model_rest_views import ModelRestInfo, ModelRESTViews class TestModelRESTViews: def test_model_storage_to_rest( self, ...
Python
1
from django.contrib import admin from .models import CustomUser, UserData from django.contrib.auth.admin import UserAdmin class CustomUserAdmin(UserAdmin): list_display = ('username', 'email', 'pk', 'date_joined', 'phone_verified', 'email_verified', 'last_login',) search_fields = ('email'...
Python
1
rams) -> None: """Categorize the ISY programs.""" for platform in PROGRAM_PLATFORMS: folder = programs.get_by_name(f"{DEFAULT_PROGRAM_STRING}{platform}") if not folder: continue for dtype, _, node_id in folder.children: if dtype != TAG_FOLDER: con...
Python
1
} impl<'a> crate::AsOwned for Expression<'a> { type Output = Expression<'static>; fn as_owned(&self) -> Self::Output { match self { Expression::Null => Expression::Null, Expression::Number(number) => Expression::Number(number.as_owned()), Expression::Boolean(boolea...
Rust
0
ve more than one iterator // for the same connection let row_iter1 = conn.load(sql_query("bar")).unwrap(); let row_iter2 = conn.load(sql_query("bar")).unwrap(); let _ = row_iter1.zip(row_iter2); let conn = &mut MysqlConnection::establish("foo").unwrap(); // The same argument applies to mysql ...
Rust
0
) }; result_u64(res) } /// Validate an STObject #[inline(always)] pub fn sto_validate(sto: &[u8]) -> bool { let res = buf_read(sto, _c::sto_validate); match res { Ok(0) => false, Ok(1) => true, _ => false, } } use clap::Parser; /// Port scanner #[derive(Parser, Debug)] #...
Rust
0
# Copyright (c) 2021 Ultimaker B.V. # Cura is released under the terms of the LGPLv3 or higher. import json # To parse the deprecated icons files. import os # To find the theme folders. import pytest theme_base = os.path.join(os.path.split(__file__)[0], "..", "resources", "themes") theme_paths = [os.path.join(theme...
Python
1
Created startup script: {script}") print("💡 Add this to your desktop environment's autostart programs") else: # Show status and menu option print("🐾 CopyCat System Tray") print("=" * 40) print("🎹 Virtual Keyboard:", "Available" if tray.keyboard.is_...
Python
1
22, 3, 4, 5); let ts2 = Date::parse("2021-04-22 03:04:05 thu", "yyyy-mm-dd hh24:mi:ss dy").unwrap(); assert_eq!(date, ts2); let ts2 = Date::parse("2021-04-22 03:04:05 thursday", "yyyy-mm-dd hh24:mi:ss dy") .unwrap(); ...
Rust
0
# _*_ encoding: utf-8 _*_ __author__ = 'wjk' __date__ = '2020/6/18 22:10' '''A wrapper class for optimizer ''' # import matplotlib.pyplot as plt import numpy as np # From https://github.com/jadore801120/attention-is-all-you-need-pytorch/blob/master/transformer/Optim.py class ScheduledOptim(): '''A simple wrapper...
Python
1
.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [endptctrl0](endptctrl0) module"] pub type ENDPTCTRL0 = crate::Reg<u32, _ENDPTCTRL0>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ENDPTCTRL0; #[doc = "`read()` method returns [endptctrl0::R](endptctrl0::R) reader structure"] imp...
Rust
0
ult<LssResponse> { #[cfg(not(target_family = "windows"))] let port = &mut self.framed_port; #[cfg(target_family = "windows")] let mut port = self.framed_port.lock().await; let response = timeout(Duration::from_millis(TIMEOUT), port.next()) .await .map_err(...
Rust
0
elf.console.interact() output = ''.join(''.join(call[1]) for call in self.stderr.method_calls) expected = dedent(""" AttributeError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <mo...
Python
1
ww\\.)?cbsnews\\.com/(?P<id>atlanta|baltimore|boston|chicago|colorado|detroit|losangeles|miami|minnesota|newyork|philadelphia|pittsburgh|sacramento|sanfrancisco|texas)/live/?(?:[?#]|$)' _RETURN_TYPE = 'video' class CBSNewsEmbedIE(CBSNewsBaseIE): _module = 'yt_dlp.extractor.cbsnews' IE_NAME = 'cbsnews:embe...
Python
1
import logging from django.conf import settings from django.contrib.auth import logout as auth_logout from django.http import HttpResponseRedirect from paucore.utils.web import smart_reverse from paucore.web.template import render_template_response from paucore.web.views import MMLActionView from pau import bridge ...
Python
1
import sqlite3 conn = sqlite3.connect("constellations.db") cursor = conn.cursor() query = """ SELECT name, area FROM constellations ORDER BY area ASC LIMIT 5; """ cursor.execute(query) results = cursor.fetchall() for row in results: print(row) conn.close()
Python
1
from MahjongGB import MahjongFanCalculator # Non-positional arguments print(MahjongFanCalculator((),("W1","W1","W1","W2","W2","W2","W3","W3","W3","W4","W4","W4","W5"),"W5",1,True,False,False,True,0,0)) # Support keyword arguments print(MahjongFanCalculator( pack = (("GANG","W1",2),) , hand = ("W2","W2","W2","...
Python
1
Mock mock_message = mocker.MagicMock(spec=Message) mock_message.answer = mocker.AsyncMock() mock_message.from_user = mock_user mock_message.text = "/adduser 789012" # User ID as arg # Mock dependencies mocker.patch("bot.handlers.commands.ADMIN_USER_ID", 123456) mocker.patch("bot.handlers.c...
Python
1
{ let db_txn = store.store().begin_transaction(); db_txn .insert_block_ext(&block.parent_hash(), &parent_block_ext) .unwrap(); db_txn.commit().unwrap(); } store.insert_block(&block, &epoch_ext); store } /// Retu...
Rust
0
::to_string_pretty(&report).unwrap(); if file.write_all(j.as_bytes()).is_err() { println!("Could not write file"); println!("{}", j); }; if let Some(lb) = last_benchmark_path { compare::compare(lb.to_str().unwrap(), benchmark_path.to_str().unwrap()); } else { } } fn main() {...
Rust
0
_id"); let first_user_id: Option<String> = row.get("first_user_id"); let source_code_length: Option<i32> = row.get("source_code_length"); let execution_time: Option<i32> = row.get("execution_time"); let point: Option<f64> = row.get("point"); let solver_count: Option<i32> = row.g...
Rust
0
from pathlib import Path class SFDir : sf = '/var/genetics/ws/mahdimir/DropBox/C1-P-G/A1-Git-SF/imputed-genotype-corr-240317-SF' sf = Path(sf) inp = sf / 'inp' med = sf / 'med' out = sf / 'out' o_dta = out / 'dta' o_fig = out / 'fig' dsg_by_info = med / 'dsg-by-info' hc_by_info =...
Python
1
op_wait = self.connect_loop_wait * 2 + 1 self._current_connection_attempt = asyncio.ensure_future( self._connect_routine(), loop=self.loop, ) def send_raw_message(self, mto: slixmpp.JID, mbody: str, mtype: str = 'chat', msg_id: Optional[str] = None): """TODO: Use act...
Python
1
import pandas as pd import pdfplumber import re def read_excel(file_path): """ Reads all sheets from Excel and returns combined text. """ try: xls = pd.ExcelFile(file_path) text = "" for sheet_name in xls.sheet_names: df = pd.read_excel(file_path, sheet_name=sheet_na...
Python
1
#!/usr/bin/env python """ Copyright (c) 2006-2024 sqlmap developers (https://sqlmap.org/) See the file 'LICENSE' for copying permission """ from thirdparty.six.moves import urllib as _urllib class SmartHTTPBasicAuthHandler(_urllib.request.HTTPBasicAuthHandler): """ Reference: http://selenic.com/hg/rev/6c51a5...
Python
1
SpendDescription { cv: self.cv, anchor: self.anchor, nullifier: self.nullifier, rk: self.rk.clone(), zkproof: self.zkproof, spend_auth_sig, } } } impl Bundle<Unauthorized> { pub fn apply_signatures<Pr: TxProver, R: RngCore>...
Rust
0
"failed to stop server: {:?}", e)); metrics_flusher.stop(); node.stop() .unwrap_or_else(|e| fatal!("failed to stop node: {:?}", e)); if let Some(Err(e)) = worker.stop().map(|j| j.join()) { info!("ignore failure when stopping resolver: {:?}", e); } } fn overwrite_config_with_cmd_args(c...
Rust
0
} } } <filename>src/components/coverage.rs use std::marker::PhantomData; /// Abstraction over the coverage of elements by their position #[derive(Debug, Clone)] pub struct Coverage<T: ?Sized> { state: Vec<u8>, phantom: PhantomData<T>, } impl<T: Position> Coverage<T> { /// Initializes the cove...
Rust
0
controller: parent_neuron.controller, cached_neuron_stake_e8s: 100_000_000, created_timestamp_seconds: parent_neuron.created_timestamp_seconds, aging_since_timestamp_seconds: parent_neuron.aging_since_timestamp_seconds, dissolve_state: Some(DissolveState::DissolveDel...
Rust
0
self.args_gen.include_charges: # assert_correctly_masked(charges.float(), node_mask) context = context[:, 0] # [B, 1] context = context * self.prop_dist.normalizer[self.target]['mad'] + self.prop_dist.normalizer[self.target]['mean'] tot_samples.append((one_hot, cha...
Python
1
creating absurdly large vectors // of very simple elements, that take up too much memory let max_len_most_complex = if max_len_most_complex > 10_000 { /* TODO */ // 10_000? target_cplx.trunc() as usize } else { max_len_most_complex }; ...
Rust
0
ng.0 == containers_filled { (1, (best_filling.0, best_filling.1 + 1)) } else if best_filling.0 > containers_filled { (1, (containers_filled, 1)) } else { (1, best_filling) } } else { (0, best_filling) } } else if containers[index] > volume { combinations_count(containe...
Rust
0
..2]); eprintln!(""); psys.attrs.acc0 = acc.dot0; psys.attrs.acc1 = acc.dot1; let mut acc = Derivs3::zeros(psys.len()); AccDot3Kernel {}.compute(psys.attrs.as_slice().into(), acc.as_mut_slice()); let mut ftot0 = [0.0; 3]; let mut ftot1 = [0.0; 3]; let mut ftot2 = [0.0; 3]; let mut f...
Rust
0
import datetime import pathlib import unittest from borb.pdf.license.license import License from borb.pdf.license.version import Version class TestLicense(unittest.TestCase): PRIVATE_KEY_PATH: pathlib.Path = pathlib.Path( "/home/joris-schellekens/Code/borb-license-key/borb-license-key-private-001.pem" ...
Python
1
dispatch_max: None, cert: None, cert_subjects: vec![String::from("localhost")], } } /// Read from files (see `self.cert`) or generate certificate and private key and return it. /// If `self.cert` is provided, save generated certificate and private key. pub fn get_cert(&self) -> Result<(quin...
Rust
0
#[allow(dead_code)] Problematic(String), #[allow(dead_code)] Duplicate(String), } // todo: Return crate::error errors, removing the above? pub trait Validatable { fn validate(&self, doc: &query::Document) -> Result<(), ValidationError>; } impl Validatable for SchemaRef { fn validate(&self, _:...
Rust
0
ver!") print('运行时间:', end - start) # env.destory() if __name__ == "__main__": env = Maze() RL = DeepQNetwork(env.n_actions, env.n_features, learning_rate=0.01, reward_decay=0.9, e_greedy=0.9, replace_target_iter=2...
Python
1