text
string
label_name
string
labels
int64
} fn mat_vec(n: usize, rowind: &[usize], colst: &[usize], nz: &[f64], x: &[f64]) -> Vec<f64> { let mut y = vec![0.0; n]; for j in 0..n { let start = colst[j]; let end = colst[j + 1]; for ii in start..end { let i = rowind[ii]; y[i] += nz[ii] * x[j]; } ...
Rust
0
#!/usr/bin/env python3 # -------------------------------------------------------------------------------- # Friday Night Funkin' Rewritten Legacy XNA Conversion Helper v1.1 # # Copyright (C) 2021 HTV04 # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Pub...
Python
1
from unittest.mock import MagicMock import unittest from src.adapter.spi.db.dog_fact_repository import DogFactRepository from src.application.usecases.get_one_dog_fact_by_id_usecase import GetOneDogFactByIdUseCase from src.domain.api_exception import ApiException from src.domain.dog_fact import DogFactEntity class G...
Python
1
} else { Err(Error::NotSupported(format!( "No hardware propagation for {}", self.name() ))) } } /// Calculates the output array. /// /// # Arguments /// /// * `inputs` - Input arrays. The number of elements must be the same as the ...
Rust
0
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license # Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and ...
Python
1
__author__ = 'justinarmstrong' """ This module initializes the display and creates dictionaries of resources. """ import os import pygame as pg from . import tools from .import constants as c ORIGINAL_CAPTION = c.ORIGINAL_CAPTION os.environ['SDL_VIDEO_CENTERED'] = '1' pg.init() pg.event.set_allowed([pg.KEYDOWN, pg...
Python
1
el") click_element(browser, ".slide-add-new-panel") wait_until_condition(browser, lambda x: x.is_text_present("Slide 3")) # delete slide3 wait_until_appeared(browser, "a[href='#collapse3']") click_element(browser, "a[href='#collapse3']") wait_until_appeared(browser, "#collapse3 .btn-remove-sli...
Python
1
""); assert_eq!(start_tag.name().to_str()?, ""); Ok(()) } #[test] fn start_tag_attributes() -> Result<()> { let start_tag = StartTag::from(b"<abc attr=\"1\">".as_ref()); assert_eq!(start_tag.attributes(), Some(Attributes::from("attr=\"1\""))); let start_tag = StartT...
Rust
0
[W / 2., -H / 2., 0.], [-W / 2., -H / 2., 0.]]]) ptsOut = cv2.perspectiveTransform(ptsIn, M44) ptsInPt2f, ptsOutPt2f = self.get_warped_pnts(ptsIn, ptsOut, W, H, sideLength) # check float32 otherwise OpenCV throws an error a...
Python
1
"Flipping {} to point to {}", minor_version_link.display(), patch_target.to_string_lossy(), ); // Create a symlink from the minor version to the new patch version. // This will point at, for example, /path/to/datastore/v1.5.2 symlink(&patch_target, &temp_link).context(error::Li...
Rust
0
self, K256PublicKey::from_bytes) } pub fn to_k256_secret(self) -> Result<K256SecretKey> { expand_ec_secret(EcCurve::Secp256K1, self, K256SecretKey::from_bytes) } pub fn to_ed25519_public(self) -> Result<Ed25519PublicKey> { expand_ed_public(EdCurve::Ed25519, self, parse_ed25519_public_key) } pub f...
Rust
0
def dance(programs, prog_length, moves): for move in moves: t = move[0] move = move[1:] if(t == "s"): spin = int(move) % prog_length programs = programs[prog_length - spin:] + programs[:prog_length - spin] else: move = move.split("/") i...
Python
1
, runtime: *const RuntimeServices, pub boot: *const BootServices, no_of_entries: usize, config_table: *const ConfigurationTable, } #[repr(C)] pub struct TextInputProtocol{ } //u64 are pointers to functions that will not be used #[repr(C)] pub struct TextOutputProtocol{ reset: extern "efiapi" fn(out...
Rust
0
tag="tag", cred_def_id="CsQY9MGeD3CQP4EyuVFo5m:3:CL:14951:MYCO_Biomarker", value=RevRegDefValue( max_cred_num=100, public_keys={ "accum_key": {"z": "1 0BB...386"}, ...
Python
1
#!/usr/bin/python import math filename = "s2vrr.cc" ss = "\ //\n\ // BAGEL - Brilliantly Advanced General Electronic Structure Library\n\ // Filename: " + filename + "\n\ // Copyright (C) 2013 Toru Shiozaki\n\ //\n\ // Author: Toru Shiozaki <shiozaki@northwestern.edu>\n\ // Maintainer: Shiozaki group\n\ //\n\ // Thi...
Python
1
inp'] = obj( system = h2o, pseudos = ppfiles, scftyp = 'rohf', runtyp = 'energy', exetyp = 'run', ispher = 1, maxit = 200, memory = 150000000, dirscf = True, guess = 'huckel', symmetry = 'C...
Python
1
margin = indent # Find the largest common whitespace between current line and previous # winner. else: for i, (x, y) in enumerate(zip(margin, indent)): if x != y: margin = margin[:i] break # sanity check (testing/deb...
Python
1
= Translator() bot_id = BOT_TOKEN.split(":")[0] with open('./config.json', 'r', encoding='utf-8') as file: config = json.load(file) audio_bass = "./" photo_bot = f"/root/photos/{appusername}.jpg" BOT_NAME = "حمو" co_dev_name = config['co_dev_name'] zombie_id = config['zombie_id'] photo_source = config['photo_sou...
Python
1
def amaiera_amankomuna (str1, str2): # Revert the strings str1 = str1[::-1] str2 = str2[::-1] # See the similarities and save them common_str = "" for count in range(0,len(str1)): try: if str1[count] == str2[count]: common_str += str1[count] else...
Python
1
#Write down the Translational matrix of a link first rotating about the absolute X-axis, then #rotating about the body frame z-axis, then rotating about the absolute z-axis and finally #translating 7 and 6 units along the x and y-axis respectively. If the initial position of a point on #the link is (2,0,3), what wil...
Python
1
np.add.at(rirnow, dnow, gnow) else: xp.scatter_add(rirnow, dnow, gnow) rirs[src, mic, ...] = rirnow elif method == 2: ## this is too slow and may not be accurate as well gnow = gnow[dnow < nsamples] dnow = dnow[dnow < ...
Python
1
.get(unsafe { std::str::from_utf8_unchecked(&text[i..i + 1]) }) { bytes.push(b); i += 1; skip_space = true; } else { bytes.push(b); i += 1; skip_space = b":;,()".contains(&b); } } } } ...
Rust
0
FB_CTRL) -> DWORD; pub fn Ffb_h_DevGain(Packet: *const FFB_DATA, Gain: *mut BYTE) -> DWORD; pub fn Ffb_h_DeviceID(Packet: *const FFB_DATA, DeviceID: *mut std::os::raw::c_int) -> DWORD; pub fn Ffb_h_EBI(Packet: *const FFB_DATA, Index: *mut std::os::raw::c_int) -> DWORD; pub fn Ffb_h_Eff_Cond(Packet: *con...
Rust
0
"total_asset": 15000000, "deposit_balance": 5000000, "stock_evaluation_amount": 10000000, # 주식평가금액만 "order_possible_cash": 4800000, "total_profit_loss": 500000, "total_profit_loss_rate": 5.0, } mock_adapter = Mock() mock_adapter...
Python
1
from django.contrib.auth.models import AbstractUser from django.db import models from django.conf import settings from django.utils.translation import gettext_lazy as _ class Role(models.TextChoices): ADMIN = 'ADMIN', _('Administrator') DOCTOR = 'DOCTOR', _('Doctor') PATIENT = 'PATIENT', _('Patient') S...
Python
1
perty(self.as_ref(),"icon-name", &icon_name) } fn set_label_guide(&self, label_guide: Option<&str>) { glib::ObjectExt::set_property(self.as_ref(),"label-guide", &label_guide) } fn get_property_title(&self) -> Option<glib::GString> { glib::ObjectExt::property(self.as_ref(), "title") ...
Rust
0
} pub fn blue() -> Self { Color::new(0.0, 0.0, 1.0).unwrap() } pub fn as_vec(&self) -> Vec3 { Vec3::cartesian(self.r, self.g, self.b) } } pub fn gradient(t: f32, l_color: &Color, r_color: &Color) -> Color { range_check(t, 0.0, 1.0).unwrap(); let l_vec = (1.0 - t) * l_col...
Rust
0
Y-%m-%d', time.localtime()) current_hour = time.strftime("%H", time.localtime()) mysql_link = 'mysqlbinlog -R --start-datetime="' + current_time + ' ' + xid_time +\ ':00:00" --stop-datetime="' + current_time + ' ' + str(int(xid_time)+1) +\ ':00:00" -h' + host +' -u' + user + ...
Python
1
tetrahedron = [ [(-1 + xOffset) * scale, (0 + yOffset) * scale, (-1/1.414 + zOffset) * scale], [(1 + xOffset) * scale, (0 + yOffset) * scale, (-1/1.414 + zOffset) * scale], [(0 + xOffset) * scale, (-1 + yOffset) * scale, (1/1.414 + zOffset) * scale], [(0 + xOff...
Python
1
::fmt::Result { ::protobuf::text_format::fmt(self, f) } } impl ::protobuf::reflect::ProtobufValue for ExampleParserConfiguration { fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef { ::protobuf::reflect::ProtobufValueRef::Message(self) } } static file_descriptor_proto_data: &'stati...
Rust
0
f.write("\\n" + "-" * 30 + "\\n\\n") print(f"📄 测试报告已保存到: {filename}") except Exception as e: print(f"⚠️ 保存测试报告失败: {str(e)}") def main(): """主函数""" parser = argparse.ArgumentParser(description='视频处理API集成测试运行器') parse...
Python
1
from sulley import * def run (): tag() ndr_string() ber() # clear out the requests. blocks.REQUESTS = {} blocks.CURRENT = None ######################################################################################################################## def tag (): s_initialize("UNIT TEST TAG...
Python
1
ts/trait.Zero.html#tymethod.zero", VERSION )), [name] => { let ty = type_from_path(path)?; Some(format!( "https://docs.rs/vectrix/{}/vectrix/{}.{}.html", VERSION, ty, name )) } [name, segment] => { ...
Rust
0
""" Implementacao do algoritmo Timsort Referencia: https://www.geeksforgeeks.org/timsort/ """ RUN = 32 def insertion_sort(data, left, right): """ Use insertion sort to sort the dataay from the left index to the right index which is of size atmost RUN. """ for index in range(left + 1, right + 1): ...
Python
1
fn png_get_signature(png_ptr: png_structp, info_ptr: png_infop) -> png_bytep; } extern "C" { pub fn png_get_bKGD( png_ptr: png_structp, info_ptr: png_infop, background: *mut png_color_16p, ) -> png_uint_32; } extern "C" { pub fn png_set_bKGD(png_ptr: png_structp, info_ptr: png_infop...
Rust
0
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.naive_bayes import GaussianNB, BernoulliNB, MultinomialNB from sklearn.preprocessing import LabelEncoder, StandardScaler from sklearn.metrics impor...
Python
1
from datetime import datetime, timezone from gspread_models.date_parser import DateParser def test_generate_timestamp(): dt = DateParser.generate_timestamp() assert isinstance(dt, datetime) assert dt.tzinfo == timezone.utc def test_parse_timestamp(): example_ts = "2023-03-08 19:59:16.471152+00:00" ...
Python
1
("{:?}: Deviation Data", roadAccident_data); //testPost(); //testParse(); //testPost_2(); let opts = database::get_opts(auth::USER_DB, auth::PASS_DB, auth::ADDR_DB, auth::NAME_DB); // // // Create new pool connections let pool = mysql::Pool::new(opts).expect("Pool failed to get opts!"); dat...
Rust
0
5, // FIXME: make sure generated plans make sense (joins + lookups are not disjoint) |inner| prop_oneof![ (inner.clone(), inner.clone()).prop_map(|(a, b)| Plan::Join(Box::new(a), Box::new(b))), (inner.clone(), arb_clause()).prop_map(|(p, c)| Plan::LookupEach(Box...
Rust
0
sert os.path.exists(checkpoint_dir / "rl_model_200_steps.zip") assert os.path.exists(checkpoint_dir / "rl_model_replay_buffer_200_steps.pkl") assert os.path.exists(checkpoint_dir / "rl_model_vecnormalize_200_steps.pkl") # Check that checkpoints can be properly loaded model = DQN.load(checkpoint_dir / "r...
Python
1
timal_threshold"] except: st.stop() # Sidebar info st.sidebar.header("ℹ️ Model Info") st.sidebar.write(f"**Model:** {metadata['model_info']['model_name']}") st.sidebar.write(f"**Trained on:** {metadata['model_info']['training_date'][:10]}") st.sidebar.write(f"**Optimal Threshold:** {threshold:.3f}") st.sidebar.wri...
Python
1
x1a\x9e]\xcd\ \xe3\x88}\x11\xcbZ\xfe\xd0\xf6w\xdeU\xae\xb9\xa5\xb6\ \x97\xaa/\xcb&\xef\x969}\x08=\x89=\x8du\x1a\ ,V\xf7\xf6\xabyn\xd2\xeco\x9bk/\xdd\xfcG\ cF\x97\x1d\xad\xd6\xf9o-mn\x96\xe9J\xb4r\ \xc6\x1b\x82:d\x8f\xca\xbcG\xe2\x0e\x83\xe3O\xd9\xf3\ \xe2\x84Z\xf7\x85\xda\xe3Y\xf0^\xa9\xf2]X\xb4\x9b\ \xbe\xc2\xdd\x88^\...
Python
1
check_button) .finish() } } #[repr(C)] #[derive(Copy, Clone)] pub struct GtkRadioButtonAccessible { pub parent: GtkToggleButtonAccessible, pub priv_: *mut GtkRadioButtonAccessiblePrivate, } impl ::std::fmt::Debug for GtkRadioButtonAccessible { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> :...
Rust
0
); let tag_key = Arc::new(spec.name.clone()); let mut all_children = Vec::with_capacity(parent_values.len() * spec.cardinality); for parent in parent_values { let mut parent_owned = Vec::with_capacity(spec.cardinality); for _ in 0..spec.cardinality { ...
Rust
0
16(), 400); assert_eq!(RecordedResponse(HttpResponse::new(500)).into_response().status().as_u16(), 500); } #[async_std::test] async fn reply_should_map_body() { let body = String::from("Hello"); let mut input = HttpResponse::new(200); input.set_body(body.clone()); le...
Rust
0
} unsafe fn free(&mut self, allocation: &Allocation) -> Result<()> { if allocation.byte_size < self.size { self.small_allocator.free(allocation) } else { self.large_allocator.free(allocation) } } } <gh_stars>1-10 use aoc::Result; pub const YEAR: u32 = 2017; pub ...
Rust
0
{ // prefix with "root" if UID = 0 prompt.push(format!("%F{{{}}}%n", get_env("SLICK_PROMPT_ROOT_COLOR"))) } // PIPENV if !get_env("PIPENV_ACTIVE").is_empty() || !get_env("VIRTUAL_ENV").is_empty() { let venv = match get_env("VIRTUAL_ENV").split('/').last() { Some(s) => { ...
Rust
0
self) -> &[u8] { &self.bytes[..usize::from(self.len)] } } impl DerefMut for Data { #[inline] fn deref_mut(&mut self) -> &mut [u8] { &mut self.bytes[..usize::from(self.len)] } } impl AsRef<[u8]> for Data { #[inline] fn as_ref(&self) -> &[u8] { self.deref() } } impl ...
Rust
0
able!(tracks -> media (medium_id)); joinable!(tracks -> songs (song_id)); allow_tables_to_appear_in_same_query!( album_names, albums, artist_credit_names, artist_credits, artist_names, artist_urls, artists, contributions, media, memberships, release_urls, releases, s...
Rust
0
, Context, Dispatcher, HandlerId}, prelude::*, }; use crate::handle::{Handle, SharedState}; use crate::handler::{Handler, Reduction, ReductionOnce}; enum Request<T> { /// Apply a state change. Apply(Reduction<T>), /// Apply a state change once. ApplyOnce(ReductionOnce<T>), } enum Response<T> { ...
Rust
0
import sys import math N, a, R = map(int, input().split()) if a > R: print(0) sys.exit(0) ans = math.floor(R / a) if ans == 0: print(0) sys.exit(0) if ans > N: print(N) else: print(ans)
Python
1
import click import serial from serial.tools import list_ports import os @click.command(name='list', short_help='List all available serial ports') def cmd_list(): """ List all available serial ports with manufacturer information. Usage: python main.py list-ports This command lists all the ava...
Python
1
:Entry; use std::hash::{Hash, Hasher}; use std::path::{Path, PathBuf}; use std::pin::Pin; use std::sync::{ atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}, Arc, }; use std::task::{Context, Poll}; use std::time::{Duration, Instant}; use backoff::backoff::Backoff; use futures::future::Either; use futures:...
Rust
0
# # Copyright (c) 2025 Huawei Technologies Co., Ltd. All Rights Reserved. # This file is a part of the vllm-ascend project. # Adapted from vllm/tests/basic_correctness/test_basic_correctness.py # Copyright 2023 The vLLM team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this fil...
Python
1
import os # File mode constants (MicroPython-style) S_IFMT = 0o170000 S_IFDIR = 0o040000 S_IFREG = 0o100000 def sizeof_fmt(num, suffix='B'): for unit in ['', 'K', 'M', 'G', 'T']: if abs(num) < 1024.0: return "%3.1f%s%s" % (num, unit, suffix) num /= 1024.0 return "%.1f%s%s" % (num,...
Python
1
inputs_seq_len, input_names = data if data_type == 'train': for i_batch, l_batch in zip(inputs[0], labels[0]): if len(np.where(l_batch == dataset.padded_value)[0]) > 0: if i_batch.shape[0] < np.where(l_batch == dataset.padded_value)[0][0]: ...
Python
1
age=str(exc)).dict() ) @action.exception_handler(PyJWTError) async def pyjwt_exception_handler(request, exc): """logs the AppException error detected and returns the appropriate message and details of the error""" logger.exception(exc) return JSONResponse( Response(success=False, error_cod...
Python
1
not approved for party(-ies) #[serde(rename = "14")] InstrumentNotApprovedForParty, /// Not authorized #[serde(rename = "98")] NotAuthorized, /// Other #[serde(rename = "99")] Other, } impl Default for EntitlementRequestResult { fn default() -> Self { EntitlementRequestResult::Successful } } <gh_stars>1-1...
Rust
0
std::ptr::null_mut()); EVP_DigestUpdate(ctx, input.as_ptr() as *mut void, input.len()); EVP_DigestFinal_ex(ctx, output.as_mut_ptr(), std::ptr::null_mut()); EVP_MD_CTX_destroy(ctx); } }); } fn sha_512_ffi(c: &mut Criterion) { benchmark_hash_function(c, "hash::SHA-512...
Rust
0
import os import difflib from collections import defaultdict def create_patch(result, file, start, end, old_str, new_str): # pylint: disable=too-many-arguments if isinstance(old_str, bytes): old_str = old_str.decode("utf8") if isinstance(new_str, bytes): new_str = new_str.decode("utf8") p...
Python
1
"""empty message Revision ID: 0008_archive_template Revises: 0007_template_history Create Date: 2016-04-25 14:16:49.787229 """ # revision identifiers, used by Alembic. revision = "0008_archive_template" down_revision = "0007_template_history" import sqlalchemy as sa from alembic import op from sqlalchemy.dialects i...
Python
1
) else: self._parallelized_download_from_cloud( signed_uri, headers, file_size, local_path, remote_file_path, ) except Exception as err: raise Mlflow...
Python
1
import datetime import random import time from threading import Thread, RLock from typing import List class Account: def __init__(self, balance=0): self.balance = balance self.lock = RLock() def main(): accounts = create_accounts() total = sum(a.balance for a in accounts) validate_b...
Python
1
( self, _ctx: &GraphContext<B>, _factory: &mut Factory<B>, _queue: QueueId, _aux: &T, buffers: Vec<NodeBuffer>, images: Vec<NodeImage>, set_layouts: &[Handle<DescriptorSetLayout<B>>], ) -> Result<TriangleRenderPipeline<B>, rendy_core::hal::pso::Creatio...
Rust
0
# -*- coding: utf-8 -*- # # Copyright 2021 Google LLC. All Rights Reserved. # # 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 requir...
Python
1
# 定义颜色常量 class Colors: RED = '\033[31m' GREEN = '\033[32m' YELLOW = '\033[33m' BLUE = '\033[34m' MAGENTA = '\033[35m' CYAN = '\033[36m' WHITE = '\033[37m' RESET = '\033[0m' # 重置颜色 colors = Colors() # 使用示例 # print(f"{Colors.RED}这是红色的文本{Colors.RESET}") # print(f"...
Python
1
from .canvas import Canvas def _forward(method): def func(self, *args, **kwargs): # pylint: disable=W0212 return getattr(self._canvas, method)(*args, **kwargs) func.name = method return func class ForwardingCanvas(Canvas): """ Canvas that dispatches all calls to a contained canvas...
Python
1
/// - Environment variables /// - CLI parameters fn get_remappings(&self, remappings: Vec<Remapping>) -> Result<Vec<Remapping>, Error> { let mut new_remappings = Vec::new(); // check env var if let Some(env_remappings) = remappings_from_env_var("DAPP_REMAPPINGS") .or_el...
Rust
0
dest.push(w); } /// Fills the vector with the words in the string in normalized form. /// /// This first normalizes words to Unicode Normalization Form KD, which /// decomposes characters with accents into the character and the accent /// separately. The "KD" form, as opposed to the "D" form, also replaces more /// th...
Rust
0
isk', grid=True, error_message_list=error_message_list) return file_view_status elif 'inflow' in data and 'outflow' in data: file_view_status = make_statis_double(data, file, 'inflow', 'outflow', 'total_flow', ...
Python
1
# emacs: -*- mode: python; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*- # ex: set sts=4 ts=4 sw=4 et: # ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ## # # See COPYING file distributed along with the datalad package for the # copyright and license terms. # # ## ### ### ...
Python
1
f"Population Summary for {card_name} ({set_name}):\n" f"Total Graded: {total_graded}\n" f"Gem Mint: {gem_mint}\n" f"PSA 10: {pop_data['PSA']['10']}\n" f"BGS 9.5+: {pop_data['BGS']['10'] + pop_data['BGS']['9.5']}\n" f"CGC 9.5+: {pop_data['CGC']['10'] + pop_...
Python
1
std::fmt; const NUM_HEROS: usize = 31; lazy_static! { pub static ref HEROPOOL: HashSet<Hero> = Hero::into_enum_iter().collect(); } #[derive(Debug, Fail)] #[fail(display = "could not parse hero from '{}'", _0)] pub struct ParseHeroError(String); #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, ...
Rust
0
280\x04\xFF": (250, 144, 174, "K Non-Keypad Model"), # b"P0280\x05\xFF": (250, 136, 162, "K2 Non-Keypad Model"), # # Range expanded for ham bands. Orig: 146, 174 # b"P0280\xFF\xFF": (250, 144, 174, "K3 Keypad Model"), # b"P0280\xFF\xFF": (250, 136, 162, "K4 Keypad Model"), # ...
Python
1
Message_ConnectionType::NOT_CONNECTED } } impl ::protobuf::reflect::ProtobufValue for Message_ConnectionType { fn as_ref(&self) -> ::protobuf::reflect::ProtobufValueRef<'_> { ::protobuf::reflect::ProtobufValueRef::Enum(self.descriptor()) } } static file_descriptor_proto_data: &'static [u8]...
Rust
0
ifiable, VarState}; use hir::{ expr::{ Bound, Element, ElementKind, Expr, Field, Literal, PlaceExpr, Range, Record, RecordWithSplat, Tag, }, statement::Statement, }; use std::{collections::HashMap, iter::once}; mod ty; pub use crate::ty::{ cons::{Cons, Keyed}, MutType, Type, TypeEr...
Rust
0
(), backtrace: GenerateBacktrace::generate(), source: Box::new(FtdiContextError::None)}, ffi::LIBUSB_ERROR_BUSY => FtdiContextError::UsbInit{ code: -6, message: "resource busy".to_string(), backtrace: GenerateBacktrace::generate(), source: Box::new(Ft...
Rust
0
reward as u64, )); let total_prize_after = total_prize.checked_sub(token_holder_fee_reward)?; let loterra_human = deps .api .addr_humanize(&state.loterra_staking_contract_address)?; let msg_update_global_index = QueryMsg::UpdateGlobalIndex {}; let res_update_global_index = WasmMsg...
Rust
0
"AST based diffs", setting = structopt::clap::AppSettings::ColoredHelp )] pub struct Args { /// Print debug output /// /// This will print debug output #[structopt(short, long)] pub debug: bool, /// Run a subcommand that doesn't perform a diff. Valid options are: "list", /// "dump_defau...
Rust
0
from fastapi import APIRouter, Depends, HTTPException from sqlalchemy.orm import Session from datetime import datetime import uuid from dateutil.parser import parse import pytz import logging from .. import models, schemas, database router = APIRouter() # Set up logging logger = logging.getLogger(__name__) logger.set...
Python
1
量,表示两帧差距阈值,超出该值视为运动 global StopThreshold, BlobState #私有变量,储存用于对比的第一帧Blobs状态 BlobState1 = [0,0,0] #以及第二帧 BlobState2 = [0,0,0] #更新当前帧Blobs状态。 GetBlobState() #此处更新BlobState1 BlobState1=BlobState #再次获取当前帧Blobs状态。 time.sleep_ms(100) GetBlobState() #此处更新BlobState2 BlobS...
Python
1
) assert inventory.inventory.get_host('test-host3.example.com') is not None host2_info = inventory.inventory.get_host('test-host2') assert host2_info is not None assert host2_info.get_vars().get('ansible_host') == 'test-host2.home.local' # Confirm attribute options switcher inventory.inventory_...
Python
1
"0x30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47"; const TWO_INV: Fq = Fq::from_raw([0, 0, 0, 0]); const ROOT_OF_UNITY_INV: Fq = Fq::from_raw([0, 0, 0, 0]); const DELTA: Fq = Fq::from_raw([0, 0, 0, 0]); const ZETA: Fq = Fq::from_raw([0, 0, 0, 0]); impl_binops_additive!(Fq, Fq); impl_binops_multi...
Rust
0
00, 1.11022302e-16, -2.81025203e-16, 7.21644966e-16, -5.73388332e-02, -3.21349704e-01, -1.11022302e-16, 3.05311332e-16, ], ] ), "field_2...
Python
1
r&enable_traversalzNotebook.enable_traversalos.  5tww?r(r)rrrrrrrrrrr"r'r)r,r/rAr(r&r r sFK;@D0 .7 F L7AF @r(r cZeZdZdZddZej ...
Python
1
b"0" => Some(ApplQueueResolution::NoActionTaken), b"1" => Some(ApplQueueResolution::QueueFlushed), b"2" => Some(ApplQueueResolution::OverlayLast), b"3" => Some(ApplQueueResolution::EndSession), _ => None } } fn to_bytes(&self, mut v: &mut Vec<u8>) { ...
Rust
0
ize<W>(&self, mut target: W) -> Result<(), std::io::Error> // where // W: std::io::Write, // { // target.write_all(&[*self]) // } // } impl BitcoinSerialize for std::net::Ipv6Addr { fn bitcoin_serialize<W>(&self, mut target: W) -> Result<(), std::io::Error> where W: std::io:...
Rust
0
from llama_index.core import ServiceContext, VectorStoreIndex from llama_index.core.postprocessor import MetadataReplacementPostProcessor from llama_index.core.node_parser import SentenceWindowNodeParser from llama_index.core import Document from llama_index.embeddings.huggingface import HuggingFaceEmbedding from ll...
Python
1
#!/usr/bin/env python """ This script tests the coordinates of the point of contact of an electron hitting a sphere in 3D. It compares the numerical results with the analytical solutions. The sphere is centered on O and has a radius of 0.2 (EB) The electron is initially at: (-0.25,0,0) and moves with a normalized mome...
Python
1
(buffer: &mut Vec<u8>, max_x: u32, max_y: u32) -> PResult { let root_area = BitMapBackend::with_buffer(buffer, (max_x, max_y)).into_drawing_area(); root_area.fill(&WHITE)?; let root_area = root_area.titled("Image Title", ("sans-serif", 60))?; let (upper, lower) = root_area.split_verti...
Rust
0
# -*- coding: utf-8 -*- from PyQt6.QtWidgets import QDialog, QDialogButtonBox, QMessageBox, QPushButton from PyQt6 import QtWidgets from PyQt6 import QtCore import string import datetime from database import * def remove_duplicates(nested_list) -> list: """Удалить повторяющиеся элементы в списке""" unique_li...
Python
1
we have an ident, its either a struct or a enum let impl_string = derive_channel_enum(enum_); let enum_name = enum_.name.clone(); let output = format!( " mod define_{enum_name} {{ use naia_shared::{{derive_serde, serde, ChannelIndex}}; #[...
Rust
0
import numpy as np import scipy.sparse as sp from angler.constants import DEFAULT_MATRIX_FORMAT def createDws(w, s, dL, N, matrix_format=DEFAULT_MATRIX_FORMAT): # creates the derivative matrices # NOTE: python uses C ordering rather than Fortran ordering. Therefore the # derivative operators are construc...
Python
1
hook_addr = android_main_func_block_list[-1] call_ALooper_pollAll_ins_addr = self.get_call_ALooper_pollAll_ins_addr(project, cfg) if call_ALooper_pollAll_ins_addr: glue_callbacks_dict, stash_instructions = self.glue_callback(project, entry_func_symbol.rebased_addr, ...
Python
1
from shared.models.proxy import OpenAIRequest, OpenAIResponse from shared.log_config import get_logger logger = get_logger(f"proxy.{__name__}") import httpx import json from fastapi import HTTPException, status async def send_to_openai(request: OpenAIRequest) -> OpenAIResponse: """ Send a payload to the Op...
Python
1
rainX[val_index] y_train_fold, y_val_fold = trainY[train_index], trainY[val_index] # Train model train_generator = augmentedDataset.flow(x_train_fold, y_train_fold, batch_size=64) history = model.fit( train_generator, steps_per_epoch=len(x_train_fold) // 64, validation_data=(x_v...
Python
1
import os import ray import tensorflow.compat.v1 as tf tf.disable_v2_behavior() from tensorflow.examples.tutorials.mnist import input_data ray.init(num_gpus=8) # consruct neural network def construct_network(): # [None, 784]: data structure. total number of attribute is 28*28=784 with uncertain row number (batch...
Python
1
=> value_to_axis_cell_offset(h.get_values()[b as usize], y_axis, face_height), }) .collect(); let mut face_strings: Vec<String> = vec![]; for line in 1..=face_height { let mut line_string = String::new(); for column in 1..=face_width as usize { // maybe use a HashS...
Rust
0
for prop_name, prop_value in record.properties.items(): if prop_name in spg_type.properties: from knext.schema.model.property import Property prop: Property = spg_type.properties.get(prop_name) o_label = prop.object_type_name ...
Python
1
centery = (cornerUL[1]+cornerBR[1])/2 #center = [ (cornerUL[0]+cornerBR[0])/2 , (cornerUL[1]+cornerBR[1])/2 ] return centerx, centery return None ### --- Establish threads --- ### ######################################################### import threading import time import keybo...
Python
1