text
string
label_name
string
labels
int64
import tkinter as tk import re # Create the main function to handle the password testing def check_password_strength(password): if len(password) < 8: return "Weak: Password should be at least 8 characters long." if not re.search(r'[A-Z]', password): return "Weak: Password should contain at leas...
Python
1
rged labelmap of all visible segments, as the filter expects a single labelmap with all the labels. mergedLabelmapNode = slicer.vtkMRMLLabelMapVolumeNode() slicer.mrmlScene.AddNode(mergedLabelmapNode) slicer.vtkSlicerSegmentationsModuleLogic.ExportSegmentsToLabelmapNode(segmentationNode, visibleSegmentIds, ...
Python
1
ctNV", [(HANDLE, "hDevice"), (OpaquePointer(Void), "dxObject"), (GLuint, "name"), (GLenum, "type"), (GLenum, "access")]), StdFunction(BOOL, "wglDXUnregisterObjectNV", [(HANDLE, "hDevice"), (HANDLE, "hObject")]), StdFunction(BOOL, "wglDXObjectAccessNV", [(HANDLE, "hObject"), (GLenum, "access")]), StdFunction...
Python
1
#!/usr/bin/env python # Copyright (C) 2014-2015 Thomas Huang # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 2 of the License. # # This program is distributed in the hope that it will ...
Python
1
self.download_file(url, file_path) except (urllib.error.URLError, IOError) as e: if url.startswith("https"): url = url.replace("https", "http") try: self.download_file(url, file_path) except (urllib.error.URLError, IOEr...
Python
1
EvalCoord2d(u: f64, v: f64) { unsafe { glu_sys::glEvalCoord2d(u, v) } } pub fn EvalCoord2f(u: f32, v: f32) { unsafe { glu_sys::glEvalCoord2f(u, v) } } pub fn EvalCoord2dv(u: &[f64]) { unsafe { glu_sys::glEvalCoord2dv(u.as_ptr()) } } pub fn EvalCoord2fv(u: &[f32]) { unsafe { glu_sys::glEvalCoord2fv(u...
Rust
0
n = rmp::decode::read_bin_len(&mut reader).map_err(|_| CowRpcError::CowRpcFailure(CowRpcErrorCode::Payload))?; #ident = msgpack_decode_binary(&mut reader, len as usize)?; } }); wr...
Rust
0
.resolve_type(type_id) .ok_or(MetadataError::TypeNotFound(type_id))?; let mut decode_compact_primitive = |primitive: &TypeDefPrimitive| match primitive { TypeDefPrimitive::U8 => decode_raw::<Compact<u8>>(input, output), TypeDefPrimitive::U16 =>...
Rust
0
# Copyright (c) Alibaba, Inc. and its affiliates. import os import subprocess import sys import time from typing import Dict, List, Tuple, Type import gradio as gr import psutil from packaging import version from swift.ui.base import BaseUI from swift.ui.llm_infer.runtime import Runtime from swift.utils import get_lo...
Python
1
naive; #[cfg(all(target_arch = "x86_64", memchr_runtime_simd, feature = "use_std"))] mod x86; #[cfg(test)] mod tests; /// An iterator over all occurrences of the needle in a haystack. #[inline] pub fn memchr_iter(needle: u8, haystack: &[u8]) -> Memchr { Memchr::new(needle, haystack) } /// An iterator over all oc...
Rust
0
>, #[prost(string, optional, tag="4")] pub trailing_comments: ::core::option::Option<::prost::alloc::string::String>, #[prost(string, repeated, tag="6")] pub leading_detached_comments: ::prost::alloc::vec::Vec<::prost::alloc::string::String>, } } /// Describes the relationship betwee...
Rust
0
import streamlit as st import matplotlib.pyplot as plt from streamlit_option_menu import option_menu import apartment as apartment import multigen import solo import office # 좌측 메인메뉴 with st.sidebar: selected = option_menu( menu_title = "Main Menu", options = ["Home", "아파트", "연립/다세대", "단독/다가구", "오피스텔", ], ...
Python
1
qWqWdS(NR%(Rtjointitertext(RRRR(R R((s+D:\Python27_64\lib\xml\etree\ElementPath.pyRs  s-()s-()-tlastsunsupported functionisunsupported expressionc3syt|}xf|D]^}y>||}t|...
Python
1
import logging import base64 import json def reverse(file_path): logging.debug(f'reverse compile {file_path}') with open(file_path, mode='rb') as f: base64_bytes = base64.b64decode(f.read()) raw_json = str(base64_bytes[42:], encoding='utf-8').encode('utf-8').decode('unicode-escape') if raw...
Python
1
from ipaddress import ip_network, ip_address for a in range(256): net_ip = f'127.63.{67&a}.0' try: net = ip_network(f'{net_ip}/255.255.{a}.0', False) cnt = 0 for ip in net: ip = f'{int(ip):032b}' if ip[:16].count('1') >= ip[16:].count('1'): cnt +=...
Python
1
era_index_max: EraIndex, ) -> Result<f32, SyncError> { let mut conn = self .cache_pool .get() .await .map_err(CacheError::RedisPoolError)?; let count: f32 = redis::cmd("ZCOUNT") .arg(Key::ActiveErasByValidator(stash.clone())) ...
Rust
0
closest_hit_opt } } //! //! Algebraic _field_ traits and implementations. //! //! The `field` module provides support for types that form algebraic //! _fields_, including their "numeric" counterparts. //! pub mod field; #[inline(always)] pub(crate) fn unreachable() -> ! { debug_assert!(false, "unreachabl...
Rust
0
from fastapi import HTTPException from sqlalchemy.ext.asyncio import AsyncSession from app.database.repo.subscribe_repository import SubscribeRepository class SubscribeService: def __init__(self, session: AsyncSession) -> None: self._session = session self._repo = SubscribeRepository(session) ...
Python
1
of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or d...
Rust
0
::std::mem::size_of::<std___allocator_traits_base>(), 1usize, concat!("Size of: ", stringify!(std___allocator_traits_base)) ); assert_eq!( ::std::mem::align_of::<std___allocator_traits_base>(), 1usize, concat!("Alignment of ", stringify!(std___allocator_traits_base)) ...
Rust
0
from utils import _obtain_avel_label import platform from tqdm import tqdm import numpy as np import torch import os def get_vggsound(rootpath): root = rootpath + 'VGGS50K/' if platform.system() == 'Linux' else 'D:/Gray/Database/VGGS50K/' vf_list, af_list, labels = [], [], [] with open(root + 'VGGS50k_meta...
Python
1
ature and value for a split""" subset = np.random.choice(X.shape[1], max_features, replace = False) max_col, max_val, max_gain = None, None, None parent_entropy = _compute_entropy(y) for column in subset: split_values = _find_splits(X, column) for value in split_values: spli...
Python
1
_1.material().with_ambient(1.0)); let mut inner = DEFAULT_SPHERE_2.clone(); inner.set_material(DEFAULT_SPHERE_2.material().with_ambient(1.0)); w.objects = vec![&outer, &inner]; let r = Ray::new( Tuple::new_point(0.0, 0.0, 0.75), Tuple::new_vector(0, 0, -1), ); let c = w.color_...
Rust
0
import json from pathlib import Path from helpers import CONSOLE_SEPARATOR from brownie import ( config, network, AutomatedVaultERC4626, AutomatedVaultsFactory, ) PATH_TO_DATA = str(Path("./scripts/data/script_data.json").resolve()) FACTORY_ADDRESS = config["networks"][network.show_active()]["vaults_f...
Python
1
from embit.descriptor import Descriptor from embit.networks import NETWORKS from .rpc import prepare_rpc def create_wallet(wname, d1: str, d2: str, rpc=None): if rpc is None: rpc = prepare_rpc() wdefault = rpc.wallet("") # to derive addresses desc1 = Descriptor.from_string(d1) # recv addr ...
Python
1
.new_doc("Customer Gift Point Details") # gift_point_details.customer_id = order.customer_id # gift_point_details.customer_name = order.full_name # gift_point_details.gift_id = order.product_id # gift_point_details.gift_product_name = order.product_name # gift...
Python
1
tool_lints))] #[deny(bad_style)] #[deny(future_incompatible)] #[deny(missing_docs)] #[deny(nonstandard_style)] #[deny(rust_2018_compatibility)] #[deny(rust_2018_idioms)] #[deny(unused)] #[deny(warnings)] extern crate clap; use clap::ArgMatches; use std::{env, process}; /// The Bughunt project type, root pub struct B...
Rust
0
bit value at that index. This allows the predicate to have more than one /// bit of information about the bit-slice being traversed. /// /// ## Sibling Methods /// /// - [`.splitn()`] has the same splitting logic, but each yielded bit-slice /// is immutable. /// - [`.rsplitn_mut()`] iterates from the back of ...
Rust
0
mut self) -> Result<(), FtStatus> { trace!("FT_ClrtDtr({:?})", self.handle()); let status: FT_STATUS = unsafe { FT_ClrDtr(self.handle()) }; ft_result((), status) } /// Set the Request to Send (RTS) control signal. /// /// # Example /// /// ```no_run /// use libftd2xx...
Rust
0
pub const mask: u32 = 0xff << offset; /// Read-only values (empty) pub mod R {} /// Write-only values (empty) pub mod W {} /// Read-write values (empty) pub mod RW {} } } /// SAI version register pub mod SAI_VERR { /// MINREV pub mod MINREV { /...
Rust
0
wner: &mut S, task_name: &'static str, subsystem_name: &'static str, future: BoxFuture<'static, ()>); } #[allow(missing_docs)] struct Regular; impl TaskKind for Regular { fn launch_task<S: SpawnNamed>(spawner: &mut S, task_name: &'static str, subsystem_name: &'static str, future: BoxFuture<'static, ()>) { ...
Rust
0
*bs/100.0, *bl/100.0, 1.0)); Color::from(p1.over(b)) }, }; values_chosen.insert(section.to_string(), (variant.to_string(), color)); } } fn rgb_to_svg(rgb: &LinSrgb) -> String { let mut rgb_int = (rgb.red * 256.0) as u32; rgb_int = (rgb_int << 8) + (rgb.green * ...
Rust
0
// We can save nine multiplications, nine additions, and one matrix // construction by only applying the nonzero elements // c0r0, c1r1, c2r3, c3r0, c3r1, c3r2, and c3r3 to the input vector. let one = S::one(); let two = one + one; let near = self.near; let far = self....
Rust
0
); let intersection = mesh.intersect_half_space(&half_space); let base_path = "data/polymesh_intersection/halfspace"; let original_mesh_file_name = format!("{}/{}.vtk", base_path, name); let intersection_file_name = format!("{}/{}_intersection.vtk", base_path, name); write_v...
Rust
0
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from datetime import date, datetime import pytest from kylinpy.exceptions import KylinUnsupportedType from kylinpy.utils.kylin_types import kyli...
Python
1
jump = True if event.key == pygame.K_ESCAPE: run = False # Keys released if event.type == pygame.KEYUP: if event.key == pygame.K_a: moving_left = False if event.key == pygame.K_d: moving_right = False if event.key == pygame.K_w: shoot = False if event.key == pygame.K_q: grenade =...
Python
1
.val(pke as u32) + SW_PAD_CTL_PAD_PMIC_STBY_REQ::ODE.val(ode as u32) + SW_PAD_CTL_PAD_PMIC_STBY_REQ::SPEED.val(speed as u32) + SW_PAD_CTL_PAD_PMIC_STBY_REQ::DSE.val(dse as u32), ); } _ => {} } } }...
Rust
0
stance(m, Bottleneck2d) and m.bn3.weight is not None: nn.init.constant_(m.bn3.weight, 0) elif isinstance(m, BasicBlock2d) and m.bn2.weight is not None: nn.init.constant_(m.bn2.weight, 0) def forward(self, image_dict: dict[str, torch.Tensor]) -> torch.Tensor: ...
Python
1
import numpy as np import matplotlib.pyplot as plt # Parameters rho = 0.9 # Autoregressive coefficient sigma_L = 0.1 # Low uncertainty standard deviation sigma_H = 0.2 # High uncertainty standard deviation num_individuals = 1000 # Number of individuals num_periods = 21 # Number of time periods # Poisson-distribu...
Python
1
} } lines } struct SearchArgs { dir: Direction, skip: bool, } #[derive(Clone)] enum Direction { Next, Prev, } pub struct Bk<'a> { quit: bool, chapters: Vec<epub::Chapter>, // position in the book chapter: usize, line: usize, mark: HashMap<char, (usize, usize)>...
Rust
0
*/, &info.1 /*station*/).unwrap().iter()) } //#[get("/sncf/dest/<station>", format = "text/html")] fn rt_sncf_dest(info: Path<(String)>) -> String { get_time_lines_html(sncf(&info, true).unwrap().iter()) } //#[get("/sncf/arriv/<station>", format = "text/html")] fn rt_sncf_arriv(req: HttpRequest) -> impl Responder...
Rust
0
ainer(self) -> Output: r"""Allows to get fields_container output of the operator The computed result fields container (elemental nodal). Returns ------- output: An Output instance for this pin. Examples -------- >>> from ansys.dpf import cor...
Python
1
sw': 'Kimedumba', 'th': 'เมดุมบา', 'to': 'lea fakametūmipa', 'tr': 'Medumba', 'ug': 'مېدۇمباچە', 'uk': 'медумба', 'vi': 'Tiếng Medumba', 'yrl': 'medũba', 'yue': '梅敦巴文', 'yue-Hans': '梅敦巴文', 'yue-Hant': '梅敦巴文', 'zh': '梅敦巴语', 'zh-Hans': '梅敦巴语', 'zh-Hant': '梅敦巴文'}, 'byw': {'en': 'Belhariya'}, 'byx': {'en': 'Qaqet'}...
Python
1
continue; } low_points.push((x, y)); } } low_points } fn get_basin( values: &[Vec<u32>], x: usize, y: usize, visited: &mut Vec<(usize, usize)>, ) -> Vec<(usize, usize)> { let mut basin = Vec::new(); if values[x][y] == 9 { retur...
Rust
0
import cv2 import mediapipe as mp import keyboard import time # Camera setup cap = cv2.VideoCapture(0, cv2.CAP_DSHOW) cap.set(3, 640) cap.set(4, 360) cv2.namedWindow("Safe Hand Gaming Control", cv2.WINDOW_NORMAL) cv2.resizeWindow("Safe Hand Gaming Control", 1000, 600) hands = mp.solutions.hands.Hands( max_num_ha...
Python
1
llow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { OTG_CLK_ENW::DISABLE_THE_OTG_CLOC => false, OTG_CLK_ENW::ENABLE_THE_OTG_CLOCK => true, } } } #[doc = r" Proxy"] pub struct _OTG_CLK_ENW<'a> { w: &'a mut W, } impl<'a> _OTG...
Rust
0
.1; let sq_distance = square(diff.x >> (ONE_BIT / 2)) + square(diff.y >> (ONE_BIT / 2)); if sq_distance > square(*spd >> (ONE_BIT / 2)) { let dlimit: i32 = *spd * 5 / 3; let target_angle = atan2_lut(-diff.y, diff.x); let d = diff_angle(target_angle, *angle); *angle += clamp(d, ...
Rust
0
import random random.seed(42) def generate_existing_data(): random.seed(42) """ Her sektör için sıcaklık ve hacim değerleri üretir. Returns: dict: {sector_id: (temp, vol)} """ from Sector import sector_positions data = {} for sector in sector_positions: sector_id = str...
Python
1
_h", "C_h", "C_H", "Cabovedot", "cabovedot", "Cacute", "cacute", "Cancel", "Caps_Lock", "careof", "caret", "caron", "Ccaron", "ccaron", "Ccedilla", "ccedilla", "Ccircumflex", "ccircumflex", "cedilla", "cent", "ch", "Ch", "CH", "...
Rust
0
BadgeType.AVAILABILITY_PUBLIC) else self._availability( is_private=is_private, needs_premium=( self._has_badge(badges, BadgeType.AVAILABILITY_PREMIUM) or False if initial_data and is_private is not None else None), needs...
Python
1
### 시뮬레이션 메인 부분 ### simulator.draw_background(white) #시뮬레이션 배경화면 그리기 simulator.draw_grid(100) #격자그리기 #simulator.atom_atom_collision() #원자와 원자 사이의 충돌 고려 #simulator.atom_atom_fusion() #원자와 원자의 병합 고려 simulator.main() #원자의 위치와 속력을 업데이트 하는 함수 simulator.draw_atom() # 원자 그리기 ### 시뮬레이션 메인 부분 ### ...
Python
1
import streamlit as st from PIL import Image st.set_page_config(layout="centered") image_1 = Image.open('./data/image_1.JPG') resize_image_1 = image_1.resize((1000,500)) image_2 = Image.open('./data/image_2.JPG') resize_image_2 = image_2.resize((1000,500)) image_3 = Image.open('./data/image_3.JPG') resize_image_3 = i...
Python
1
class Hissi: def __init__(self,alin_kerros,ylin_kerros): self.alin_kerros = alin_kerros self.ylin_kerros = ylin_kerros self.nykyinen_kerros = alin_kerros def kerros_ylös(self): self.nykyinen_kerros +=1 print(f"-Hissi nousi kerroksen. Olet nyt kerroksessa {self.nykyinen_k...
Python
1
import json from experiments.consts import * from parsers.parser import Parser import os dir_path = os.path.dirname(os.path.realpath(__file__)) dist_path = os.path.join(dir_path, 'datasets', 'data_distributions.json') boost_env = os.environ.get('BOOST', None) if boost_env is not None: general_boost = dict() f...
Python
1
lone(), term3.clone()).unwrap(); let lit = ast::basic_literal_from_comparison(&loc, Sign::NoSign, comp).unwrap(); assert_eq!(format!("{}", lit), "\"test\" > fun1(42,\"test\")"); // TODO: activate these test when the bug in libclingo is fixed // let sym4 = Symbol::create_supremum(); // let term4 = s...
Rust
0
_for_rgb!([$t; 4], v, { let [r, g, b, a] = *v; Rgb::new(r as f64, g as f64, b as f64, Some(a as f64)) }); }; } from_for_rgb_all!(f32); from_for_rgb_all!(f64); from_for_rgb_all_with_alpha!(f32); from_for_rgb_all_with_alpha!(f64); from_for_rgb_all!(i16); from_for_rgb_all!(i32); from_for_rgb_all!(i64); ...
Rust
0
import tkinter as tk # creating the main window root = tk.Tk() root.title("Tkinter Entry Widget") def on_button_click(): name_input = name_entry.get() age_input = age_entry.get() print(f"User name: {name_input}") print(f"Age: {age_input}") def validate_input(value): return value.isdigit() or...
Python
1
println!("{:padding$}PartUUID: {}", partuuid, padding = padding); } if let Some(partlabel) = &partition.partlabel { println!("{:padding$}PartLabel: {}", partlabel, padding = padding); } if let Some((vg, pv)) = entity.pv() { println!("{:padding$}PV: {}", pv.path.display(),...
Rust
0
ow_type { ArrowTip::Cone => "Translation", ArrowTip::Sphere => "Look", ArrowTip::Cube => "Scale", ArrowTip::None => "", }; let x = create_arrow(scene, [0.8, 0., 0., 1.], arrow_type, "XAxis", true, true); let y = create_arrow(scene, [0., 0.8, 0., 1.], arrow_type, "YAxis", true...
Rust
0
} /// Returns an iterator over all chunk checksums. pub fn checksums(&self) -> Iter<'_, Digest> { self.chunks.iter() } /// Returns an iterator over all `DifChunk`s. pub fn chunks(&self) -> DifChunks<'_> { DifChunks { checksums: self.checksums(), iter: self.d...
Rust
0
'SET', 'SETOF', 'SETS', 'SHARE', 'SHOW', 'SIMILAR', 'SIMPLE', 'SIZE', 'SOME', 'SOURCE', 'SPACE', 'SPECIFIC', 'SPECIFICTYPE', 'SPECIFIC_NAME', 'SQL', 'SQLCODE', 'SQLERROR', 'SQLEXCEPTION', 'SQLSTATE', 'SQLWARNINIG', 'STABLE', 'START', 'STATE', 'STATEMENT', 'STA...
Python
1
class FenwickTree: def __init__(self, n: int): self.sums = [0] * (n + 1) def update(self, i: int, delta: int) -> None: while i < len(self.sums): self.sums[i] += delta i += FenwickTree.lowbit(i) def get(self, i: int) -> int: summ = 0 while i > 0: summ += self.sums[i] i -= ...
Python
1
vot optimisation..."); while !frontier.is_empty() { if discovered.as_bdd().size() > 10_000 { println!("{}/{} ({:+e}%, nodes result({}))", discovered.cardinality(), universe.cardinality(), (discovered.cardinality() / universe.cardinal...
Rust
0
l_ref = 0.026581603224742834 self.assertAlmostEqual(x_vel, x_vel_ref, delta=tol) dem_pressure_ref = 21598.828562997718 self.assertAlmostEqual(dem_pressure, dem_pressure_ref, delta=tol) class DEM3D_SymplecticTestSolution(DEM3D_ForwardEulerTestSolution): def CheckValues(self, x_vel, dem_pre...
Python
1
angle - angle.0).abs(); assert!(diff < EPS, "{} != {}", expected_angle, angle.0); } } } use crate::{addon::Addon, config::Flavor, error::ClientError, network::request_async, Result}; use isahc::config::RedirectPolicy; use isahc::prelude::*; use serde::Deserialize; use std::path::PathBuf; #[deri...
Rust
0
); lock.push(Rc::new(op)); drop(name_lock); drop(lock); op_id } fn json_map(&self) -> Buf { let lock = self.name_to_id.read().unwrap(); let op_map_json = serde_json::to_string(&*lock).unwrap(); op_map_json.as_bytes().to_owned().into_boxed_slice() } /// This function returns N...
Rust
0
,0|\ A@5708,0|\ Y@6538,0|\ Y@6870,0|\ A@7202,0|\ Z@8032,0|\ Z@8354,0" ); } #[test] fn morx_31_002() { assert_eq!( shape( "text-rendering-tests/fonts/TestMORXThirtyone.ttf", "\u{0058}\u{0058}\u{0041}\u{0059}\u{0059}\u{0042}\u{...
Rust
0
uted_ref_changed) self.default_mic.connect("notify::volume", self.on_mic_volume_changed) self.default_mic.connect("notify::mute", self.on_mic_muted_changed) self.default_mic.connect("notify::description", self.update_mic_name) self.default_mic.connect("notify::name", self.update_mic_name...
Python
1
# synapse_bond_manager.py """ Synapse Bond Manager – NeuroBase v1.3 (Theophilus-Axon) Purpose: Manage the formation and retrieval of symbolic memory bonds between NeuronMemoryNodes. Scientific Support: - Hebbian Learning (Hebb, 1949): "Neurons that fire together wire together." - Memory Encoding via Assoc...
Python
1
fElement::Right(hex!( "394927388eb0a8ad4fa2abee5774e0a76978c34e0991d5dbfd8d57c9c63fc3a3" )), ProofElement::Right(hex!( "c53ab8ae5cd3402147acd585cf82273f354669bb0fbb7017ffb1a2d4e96a1fb9" )), ]; let leaf = hex!("4741a0e50f977e1deffd81f392...
Rust
0
import arrow from django.db import models from django.utils.translation import gettext_lazy as _ from common.models import Org, Profile from common.base import BaseModel from contacts.models import Contact from teams.models import Teams # Create your models here. class Event(BaseModel): EVENT_TYPE = ( (...
Python
1
StatsPreparation<'a> { pub base: GameFightMinimalStats<'a>, #[protocol(var)] pub initiative: u32, } #[derive(Clone, PartialEq, Debug, Encode, Decode)] #[protocol(id = 413)] pub struct GameFightFighterLightInformations<'a> { #[protocol(flag)] pub sex: bool, #[protocol(flag)] pub alive: bool,...
Rust
0
await self.set_file_datetime(media_item, media_item.complete_file) self.attempt_task_removal(media_item) self.manager.progress_manager.download_progress.add_completed() log(f"Download finished: {media_item.url}", 20) return downloaded...
Python
1
YPE:usize=SHA256; pub struct RsaPrivateKey { p:FF, q:FF, dp:FF, dq:FF, c:FF } pub struct RsaPublicKey { e: isize, n: FF } pub fn new_private_key(n: usize) -> RsaPrivateKey { RsaPrivateKey {p:FF::new_int(n),q:FF::new_int(n),dp:FF::new_int(n),dq:FF::new_int(n),c:FF::new_int(n)} } pub fn new_public_key(m: usiz...
Rust
0
is_none")] pub user_id: Option<String>, #[serde(rename = "userEmail")] #[serde(skip_serializing_if = "Option::is_none")] pub user_email: Option<String>, #[serde(rename = "userName")] #[serde(skip_serializing_if = "Option::is_none")] pub user_name: Option<String>, #[serde(rename = "userPr...
Rust
0
pub normal: Vect, /// Feature at the intersection point. pub feature: FeatureId, } impl RayIntersection { pub(crate) fn from_rapier( inter: rapier::parry::query::RayIntersection, unscaled_origin: Vect, unscaled_dir: Vect, ) -> Self { Self { toi: inter.toi...
Rust
0
# app/db/session.py from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker from sqlalchemy.orm import declarative_base from sqlalchemy.pool import NullPool from app.core.config import conf from app.core.logger import get_logger logger = get_logger() Base = declarative_base() if conf...
Python
1
ErrorHandlers, Logger}; use actix_web::{dev::Resource, fs, http, server, App}; use dotenv::dotenv; use std::env; use tera::Tera; mod api; mod db; mod model; mod schema; mod session; static SESSION_SIGNING_KEY: &[u8] = &[0; 32]; const NUM_DB_THREADS: usize = 3; fn main() { dotenv().ok(); std::env::set_var("R...
Rust
0
# Code generated by Lark OpenAPI. import lark_oapi as lark from lark_oapi.api.wiki.v2 import * def main(): # 创建client client = lark.Client.builder() \ .app_id(lark.APP_ID) \ .app_secret(lark.APP_SECRET) \ .log_level(lark.LogLevel.DEBUG) \ .build() # 构造请求对象 request: Cr...
Python
1
""" Convert the preprocessed .npz files to .npy files for training """ # %% import packages import numpy as np import os join = os.path.join listdir = os.listdir makedirs = os.makedirs from tqdm import tqdm import multiprocessing as mp import argparse parser = argparse.ArgumentParser() parser.add_argument("-npz_dir", ...
Python
1
u64; match (*master).pass_type as libc::c_uint { 0 => { /* Initial pass: will collect input data, and do either Huffman * optimization or data output for the first scan. */ select_scan_parameters(cinfo); per_scan_setup(cinfo); if (*ci...
Rust
0
f"{self.agent_id}: {new_policy_id} softly loaded from a pretrained model {policy_id}:{policy_dir}" ) return new_policy_id, policy def init_from_random(self, algorithm_conf, new_policy_ctr): env_agent_id = self.agent_id policy_cls = registry.get(registry.POLICY, algorithm...
Python
1
x = input_int() y = input_int() if x == y: print(42) else: print(0)
Python
1
means that the coupling has not converged and this was not the last coupling iteration self.__CommunicateIfTimeStepNeedsToBeRepeated(True) # do relaxation only if this iteration is not the last iteration of this timestep for conv_acc in self.convergence_accelerators_list: ...
Python
1
orientation: usize) { if level == LOOKUP_BITS { let ij = (i << LOOKUP_BITS) + j; lookup_pos[(ij << 2) + orig_orientation] = ((pos << 2) + orientation) as u16; lookup_ij[(pos << 2) + orig_orientation] = ((ij << 2) + orientation) as u16; return; } let (nlevel, ni, nj, npos) = ...
Rust
0
ctx .db .get_usage(ctx.app_id, ts - c_in_window.window_size.seconds, ts)?; Ok(usage < c_in_window.limit.seconds) } Condition::AtMostInThis(c_in_current) => { let start_of_window = match c_in_current.time_unit { TimeUnit::Second => c...
Rust
0
MAX as usize { error!("Too many tagged fields to encode ({} fields)", num_tagged_fields); return Err(EncodeError); } total_size += types::UnsignedVarInt.compute_size(num_tagged_fields as u32)?; total_size += compute_unknown_tagged_fields_size(&self.un...
Rust
0
633, -85.1893615723, -105.872497559, -105.871124268}}, {"v2g8jh1", Box{49.2407226562, 49.2420959473, 61.3929748535, 61.3943481445}}, {"84umeh3gmupk", Box{16.45947285, 16.4594730176, -173.888941817, -173.888941482}}, {"s4g900", Box{15.64453125, 15.6500244141, 4.921875, 4.93286132812}}, {"0b313fz2", Box{-88.358917236...
Rust
0
ding=1) self.bn2 = BatchNorm2d(num_filters) self.conv3 = Conv2d(num_filters, num_filters, 3, padding=1) self.bn3 = BatchNorm2d(num_filters) self.conv4 = Conv2d(num_filters, num_filters, 3, padding=1) self.bn4 = BatchNorm2d(num_filters) self.conv5 = Conv2d(num_filters, ...
Python
1
"} addTLSLocal("127.0.0.1:%s", "%s", "%s", { provider="openssl" }) lastKey = "" lastKeyLen = 0 function keyAddedCallback(key, keyLen) lastKey = key lastKeyLen = keyLen end setTicketsKeyAddedHook(keyAddedCallback) """ def testSetTicketsKey(self): """ TLSTick...
Python
1
(11)); } /** * Generates a sequence of type T and compares values to an externally generated * reference sequence (see 'test/data/ref_seq_*.tsv.gz') */ fn validate<T>(ref_seq: &Vec<Vec<f32>>, resolution: Option<usize>) where T: SobolType + ToFloat + Display, T::IT: LossyFrom<u32>, { let dims: usize = ref_...
Rust
0
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ @File : __init__.py.py @Contact : haoheliu@gmail.com @License : (C)Copyright 2020-2100 @Modify Time @Author @Version @Desciption ------------ ------- -------- ----------- 9/14/21 12:28 AM Haohe Liu 1.0 None """
Python
1
from sympy.matrices.expressions import MatrixExpr from sympy.assumptions.ask import Q class Factorization(MatrixExpr): arg = property(lambda self: self.args[0]) shape = property(lambda self: self.arg.shape) # type: ignore class LofLU(Factorization): @property def predicates(self): return (Q.l...
Python
1
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from typing import Optional import os def send_email( to_email: str, subject: str, body: str, html_body: Optional[str] = None ) -> bool: """ Send an email using SMTP. Returns True if successful, False ot...
Python
1
od_line_gdf = gpd.GeoDataFrame(od_line_gdf, geometry=geometry_field, crs='EPSG:4326') od_line_gdf.rename(columns={agent_field: od_id_field}, inplace=True) # od try: res_df['str_xy'] = res_df[geometry_field].apply(lambda geo: list(map(str, (geo.x, geo.y)))) except Attribu...
Python
1
import numpy as np import pickle, os import matplotlib.pyplot as plt def avg_return_curve(x, y, stride, total_steps): """ Author: Rupam Mahmood (armahmood@ualberta.ca) :param x: A list of list of termination steps for each episode. len(x) == total number of runs :param y: A list of list of episodic ret...
Python
1
winners.iter()) { let replica = replicas .get(&winner.sector_id) .with_context(|| format!("Missing replica for sector: {}", winner.sector_id))?; let comm_r = replica.safe_comm_r()?; if !election_post::is_valid_sector_challenge_index( challenge_count, ...
Rust
0
if acc_neg_mon == 0: acc_neg_mon = -1 acc_neg = -1 else: acc_neg = acc_neg_son / acc_neg_mon # 计算 F1 分值 if acc + recall == 0: acc = recall = acc_neg = f1 = 0 else: f1 = (2 * acc * recall) / (acc + recall) sql_predic...
Python
1
def __init__(self, config: Blip2Config): super().__init__(config) self.config = config self.embeddings = Blip2TextEmbeddings(config.qformer_config) self.visual_encoder = Blip2VisionModel(config.vision_config) self.query_tokens = nn.Parameter(torch.zeros(1, config.num_query_tokens, config.qfo...
Python
1
as f32) / (2. * (FOV / 2.).tan()); if let Some(hit) = sphere_trace( Vec3f::new(0., 0., 3.), // the camera is placed to (0,0,3) and it looks along the -z axis Vec3f::new(dir_x, dir_y, dir_z).normalize(), ) { let noise_level = (SPHERE_RADIUS - hit.ma...
Rust
0