text
string
label_name
string
labels
int64
inches="tight", dpi=300) plt.show() import pandas as pd import numpy as np import matplotlib.pyplot as plt def extract_wall_boundary_numpy(field, threshold=1e-6): """ 对每一列,从上往下找第一个大于 threshold 的值的索引 """ wall_y = [] height, width = field.shape for x in range(width): col = field[:, x...
Python
1
Error> where W: io::Write, { match self { Balance::Zero => write!(writer, "0"), Balance::Amount(ref balance) => balance.write(writer, settings), } } } impl Serializer for CommodityPrice { fn write<W>(&self, writer: &mut W, settings: &SerializerSettings) -...
Rust
0
new()); let res = &data.db.add_post(&post).await; match res { Err(_) => { return HttpResponse::InternalServerError().json(general::Error { status_code: "500".to_string(), error: "Error when adding to database.".to_string(), }); } ...
Rust
0
ue` and `false`. :param _builtins.str name: The name of the project. :param _builtins.str parent_id: The parent of this project. :param _builtins.str project_id: The id of the project. Conflicts with any of the above arguments. :param _builtins.str region: The region in which to obtain the V3...
Python
1
pending: Command::None, } } fn new_state_ok(&mut self, state: DFUState) { self.new_state_status(state, DFUStatusCode::OK); } fn new_state_status(&mut self, state: DFUState, status: DFUStatusCode) { self.status = status; self.state = state; } fn stat...
Rust
0
ruff.set_instance_parameter(inst, SynthParameter::Attack, 0.0); ruff.set_instance_parameter(inst, SynthParameter::Sustain, 1.0); ruff.set_instance_parameter(inst, SynthParameter::Release, 0.0); ruff.trigger(inst); let out_1 = ruff.process(0.0, true); let mut comp_1 = [0.0; 128]...
Rust
0
} } } <reponame>hyperswine/novusk<gh_stars>1-10 #![no_std] #[macro_use] extern crate tock_registers; pub mod board; pub use board::RaspberryPi; pub mod common; pub use common::*; #[macro_use] #[path = "../../../kernel/irq.rs"] pub mod irq; pub mod rpi2; pub mod rpi3; pub use rpi2::Rpi2; pub use rpi3::Rp...
Rust
0
state[5] = (state.Gamepad.sThumbRY as i32 + 32768) as f32 / 65535.0 * 2.0 - 1.0; } fn update_info(&mut self, index: usize, capabilities: &XCapabilities) { let mut name = String::from("XBOX360"); match capabilities.SubType { xinput::XINPUT_DEVSUBTYPE_GAMEPAD => name.push_s...
Rust
0
eturn concat_str # 4 def string_methods(value, metod, *args): if metod == 'upper': return value.upper() elif metod == 'lower': return value.lower() elif metod == 'startswith': return value.startswith(*args) elif metod == 'endswith': return value.endswith(*args) else:...
Python
1
import glob from pathlib import Path import re import os import datetime def increment_path(path, exist_ok=True, sep=''): # Increment path, i.e. runs/exp --> runs/exp{sep}0, runs/exp{sep}1 etc. path = Path(path) # os-agnostic if (path.exists() and exist_ok) or (not path.exists()): return str(path)...
Python
1
ped = win32file.OVERLAPPED() overlapped.hEvent = win32event.CreateEvent(None, 1, 0, None) err, n = win32file.WriteFile(self.hComPort, s, overlapped) if err: #will be ERROR_IO_PENDING: # Wait for the write to complete. win32event.WaitForSingleObject(overlapped.hEvent, win3...
Python
1
# Common training-related configs that are designed for "tools/train_net.py" # You can use your own instead, together with your own train_net.py train = dict( # Directory where output files are written to output_dir="./output", # The initialize checkpoint to be loaded init_checkpoint="", # The total...
Python
1
tive to the top-left /// corner of the decorations pub(crate) fn subsurface_offset() -> (i32, i32) { (DECORATION_SIZE, DECORATION_TOP_SIZE) } /// Subtracts the border dimensions from the given dimensions. pub fn subtract_borders(width: i32, height: i32) -> (i32, i32) { ( width - 2 * (DECORATION_SIZE as...
Rust
0
('123456789') def _printResults(fn=_callCalcString123456789): import sys d = sys.modules[__name__].__dict__ algorithms = sorted( (v for (k, v) in d.iteritems() if isinstance(v, CrcAlgorithm)), key=lambda v: (v.width, v.name)) for a in algorithms: format = ("%%0%dX" % ((a.width +...
Python
1
# https://leetcode.com/problems/count-subarrays-with-median-k/ # https://youtu.be/QZzDioqkRhU class Solution: def countSubarrays(self, nums: List[int], k: int) -> int: pos = nums.index(k) cnt = defaultdict(int) cnt[0] = 1 c = 0 for i in range(pos + 1, len(nums)): ...
Python
1
d::time::Duration; use subprocess::{Exec, Popen}; const POST_DTRACE_WAIT: Duration = Duration::from_secs(2); const SUBPROC_WAIT: Duration = Duration::from_secs(5); fn root_command() -> OsString { if cfg!(target_os = "illumos") { "pfexec".parse().unwrap() } else { ...
Rust
0
rivation: &Path) -> Result<(), anyhow::Error> { let mut cmd = self.session.command("sudo"); let flake_base_name = derivation .file_name() .ok_or_else(|| anyhow::anyhow!("Built path has a weird format: {:?}", derivation))? .to_str() .expect("Nix path must b...
Rust
0
); let body = client.torrent_add(add_args).await; assert!(body.is_err()); } #[tokio::test] async fn test_torrent_add_without_file_and_meta() { let uri = dotenv::var("TRPC_TARGET").expect("not set TRPC_TARGET"); let mut client = Client::new(&uri); let mut add_args = TorrentAddArgs::from_meta("tests...
Rust
0
z - v) >> 3) as i16; lp1[3] = ((x + u) >> 3) as i16; lp1[4] = ((x - u) >> 3) as i16; lp1 = &mut lp1[8..]; } } #[allow(clippy::too_many_arguments)] fn ycc2rgb( mut dc: usize, mut ac: usize, dct_y: &[i16], dct_cb: &[i16], dct_cr: &[i16], mut cbcr_src: usize, m_out...
Rust
0
#!/usr/bin/env python3 import tensorflow as tf import numpy as np import os flags = tf.app.flags flags.DEFINE_string("input", "", "The model checkpoint") flags.DEFINE_string("output", "", "The output numpy file") FLAGS = flags.FLAGS def main(_): if FLAGS.input == '': print('You must specify --input valu...
Python
1
(Foo::<Runtime>::hashed_key().to_vec(), true, true); b.whitelist(Value::<Runtime>::hashed_key().to_vec(), true, true); b.bench(|| { let _ = Test::set_foo(); }); } benches!(whitelist, set_value, set_foo, remove_all_bar); <reponame>mxpv/hypervisor-framework // Apple Silicon example. // Adapted from https://github.c...
Rust
0
from collections import deque from typing import List, Tuple from collections import deque def find_minimum_cost(n, cost, k, m): """ This function finds the minimum cost and path for a given set of costs and constraints. Args: - n (int): The number of elements in the cost list. - cost (List[int]...
Python
1
alizer.serialize_bool(x), Self::Int8(x) => serializer.serialize_i8(x), Self::Int16(x) => serializer.serialize_i16(x), Self::Int32(x) => serializer.serialize_i32(x), Self::Int64(x) => serializer.serialize_i64(x), Self::UInt8(x) => serializer.serialize_u8(x), Self::UInt16(x) => seriali...
Rust
0
#!/usr/bin/env python3 import rospy import threading from std_msgs.msg import Bool, Int32, String from geometry_msgs.msg import Point, PoseStamped from sensor_msgs.msg import JointState from moveit_ctrl.srv import JointMoveitCtrl, JointMoveitCtrlRequest import math class FruitPicker: def __init__(self): r...
Python
1
&'a [Piece<'a>]), } pub struct PluralArm<'a> { selector: Either<parse::PluralKeyword, uint>, result: &'a [Piece<'a>], } pub struct SelectArm<'a> { selector: &'a str, result: &'a [Piece<'a>], } <gh_stars>0 // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or http://www.apache.org/li...
Rust
0
isable loopback. ); //Set gain. self.cs4265.reg.PGAA.write(cs4265::PGAA::GAIN.val(params.adcgaina as u8)); self.cs4265.reg.PGAB.write(cs4265::PGAB::GAIN.val(params.adcgainb as u8)); //Set soft ramp, zero crossing detection and line level. self.cs4265.reg.AICTL.modify ( cs42...
Rust
0
output_tensor = self._build_tensor( src + 1, value=-1, device=device ) dist.recv(output_tensor, src) self.assertEqual(output_tensor, expected_tensor) def test_send_recv_crosscard(self): self._test_send_recv_crosscard() def ...
Python
1
eds) Y_pred = KMeans(nb_classes, random_state=42).fit(embeds)#.predict(embeds) Y_pred = Y_pred.labels_ # 可视化 label_to_color = {0: '#FF9671', 1: '#008E9B', 2: '#B39CD0', 3: 'red', 4:'blue'} # 标签到颜色的映射关系 colors = [label_to_color[l] for l in label] # 根据标签获取颜色 plt.scatter(reduced_features[:, 0], ...
Python
1
from collections import OrderedDict import torch import numpy as np import matplotlib.pyplot as plt from scipy.spatial import cKDTree from torch.nn.utils.rnn import pad_sequence import time # 定义子网络列表 def NN_list(layers): depth = len(layers) - 1 activation = torch.nn.Tanh layer_list = list() for i in ra...
Python
1
name="teja" #print("Hello"+name) print(name.capitalize()) #--only first letter is capitalized print(name.find("a")) print(name.upper()) #--ALL CAPITALS print(name.lower()) #--All lower print(name.isdigit()) #--checks is it a number or not print(name.isalpha()) #Checks it consists of only string letters then the out...
Python
1
let (_, result) = parse_p(CompleteByteSlice( b"#complex-assign-command !prompt 'Test this function' [0:'Ok', 1:'No'] >> ${0} == 0 ? $foo = !roll 1d20 : $foo = ${0} | !roll 1d8" )).unwrap(); assert_eq!(result, program); } #[test] fn test_function_parser() { let (_, result) = parse_p(CompleteByte...
Rust
0
# Variables are used to store data values. A variable is a name given to a memory location where the data is stored. It is the basic unit of storage in a program. The value stored in a variable can be changed during program execution. A variable is created the moment you first assign a value to it. Variables do not nee...
Python
1
play.handle_event(timer, &mut MicrobitGpio(gpio)); } <filename>crates/simplexpr/src/ast.rs use crate::dynval::DynVal; use eww_shared_util::{Span, Spanned}; use itertools::Itertools; use serde::{Deserialize, Serialize}; use eww_shared_util::VarName; #[rustfmt::skip] #[derive(Clone, PartialEq, Eq, Serialize, Deserializ...
Rust
0
)] #[doc(hidden)] pub struct _BB_AESCNTL; #[doc = "`read()` method returns [bb_aescntl::R](bb_aescntl::R) reader structure"] impl crate::Readable for BB_AESCNTL {} #[doc = "`write(|w| ..)` method takes [bb_aescntl::W](bb_aescntl::W) writer structure"] impl crate::Writable for BB_AESCNTL {} #[doc = "AES-128 ciphering co...
Rust
0
ethod sets ADC14CLRIFGR1 to value 0"] impl crate::Resettable for ADC14CLRIFGR1_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } } <filename>src/max_flow.rs use std::sync::{atomic::AtomicI32, Arc}; use crate::graph::NodeID; use bitvec::vec::BitVec; #[derive(Copy, Clone, Debug, PartialEq,...
Rust
0
_id) { self.material.replace(mat.clone_loaded()); } } if let Some(mesh) = self.mesh.take() { self.mesh_handle = Some(loader.load_from_data(mesh.clone().into(), &mut *progress, meshes_storage)); ret = true; } if let Some(...
Rust
0
import os import sys root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))) sys.path.append(root) # ---------------------------------------------------------------------------- # PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN: # ht...
Python
1
pub fn set_alphabet(&mut self, alphabet: String) { let mut alphabet = alphabet; alphabet.push('*'); self.alphabet = alphabet; } }use crate::graphics::ShaderDescription; #[derive(Debug, Clone)] pub struct ShaderSet { pub vertex: ShaderDescription, pub hull: Option<ShaderDes...
Rust
0
ata, pos=index) if not m: return None, index, False else: id = m.group(1).lower() end = m.end(0) if not id: id = text.lower() return id, end, True def makeTag(self, href, title, text): el = etree.Element('a') e...
Python
1
@mcp.tool() def optimize_sd_parameters( ctx: Context, goal: str = "quality", hardware: str = "medium", image_type: str = "general", time_budget: int = 60, quality_preference: float = 0.7 ) -> str: """ 智能优化Stable Diffusion参数 Args: goal: 优化目标 (speed/quality/balanced) ...
Python
1
from typing import Final, Generic, Type, TypeVar from PySide6.QtCore import QObject from PySide6.QtWidgets import QComboBox from eon_timer.util.enum import EnhancedEnum from eon_timer.util.properties.property import EnumProperty, PropertyChangeEvent EnhancedEnumT = TypeVar('EnhancedEnumT', bound=EnhancedEnum) clas...
Python
1
result = sw_df.loc[result, 'max_'] print(f'max: {result}') print(f'-----------------------------------------') inHistory = True break if not inHistory: ...
Python
1
_pre(x) if g is not None: x = x + self.cond(g) for i in range(self.num_upsamples): x = F.leaky_relu(x, LRELU_SLOPE) x = self.ups[i](x) xs = None for j in range(self.num_kernels): if xs is None: xs = self.res...
Python
1
from streamlit import session_state from backend.core import run_llm import streamlit as st from typing import Set # Configure the theme to match LangChain's style st.set_page_config( page_title="Documentation Helper Bot", page_icon="🔗", layout="wide" ) # Custom CSS to match LangChain's theme st.markdow...
Python
1
# 1957. Delete Characters to Make Fancy String # Easy # A fancy string is a string where no three consecutive characters are equal. # Given a string s, delete the minimum possible number of characters from s to make it fancy. # Return the final string after the deletion. It can be shown that the answer will always be...
Python
1
FieldData::FitUint64(_) => Err("Bad cast!"),// Needs try_into. FitFieldData::FitUint64z(_) => Err("Bad cast!"), } } } fn contains_invalid_f32(x: &Vec<f32>) -> bool { for item in x { let bitpattern = unsafe { std::mem::transmute::<f32, u32>(*item) }; if b...
Rust
0
) { unsafe { oslog_sys::oslog_sys_signpost_interval_begin(log.inner, spid.inner, msg.as_ptr()); } } #[inline] pub fn os_signpost_interval_end(log: &OSLog, spid: OSSignpostID, msg: &CStr) { unsafe { oslog_sys::oslog_sys_signpost_interval_end(log.inner, spid.inner, msg.as_ptr()); } } pub...
Rust
0
(Average): """ Fifo averager that allows usage of custom accessor function. Does not support custom boolean collapsation. Example: lambdas = (lambda item: item['x'], lambda item: item['y']) averager = AverageCustom(lambdas, 2) averager({'x': 0, 'y': 0}) # returns (0.0, 0.0) averager...
Python
1
ar1::R) reader structure"] impl crate::Readable for INTISAR1 {} #[doc = "`write(|w| ..)` method takes [intisar1::W](intisar1::W) writer structure"] impl crate::Writable for INTISAR1 {} #[doc = "ISA Feature Register 1"] pub mod intisar1; #[doc = "ISA Feature Register 2\n\nThis register you can [`read`](crate::generic::R...
Rust
0
from flask import Flask, request, jsonify from flask_sqlalchemy import SQLAlchemy from collections import defaultdict from flasgger import Swagger from flask_cors import CORS from os import environ app = Flask(__name__) CORS(app) # app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+mysqlconnector://root:@localhost:3306/w...
Python
1
coda_category = { 1: {'supercategory': 'pedestrian', 'id': 1, 'name': 'pedestrian'}, 2: {'supercategory': 'cyclist', 'id': 2, 'name': 'cyclist'}, 3: {'supercategory': 'vehicle', 'id': 3, 'name': 'car'}, 4: {'supercategory': 'vehicle', 'id': 4, 'name': 'truck'}, 6: {'supercategory': 'vehicle', 'id': 6, 'name': 'tric...
Python
1
) while performing the command or during a self test. HardwareError =0x4, /// Indicates that: /// a) the command was addressed to an incorrect logical unit number (see SAM-4); /// b) the command had an invalid task attribute (see SAM-4); /// c) the command was addressed to a logical unit whose curre...
Rust
0
#!/usr/bin/env python3 # Copyright (c) Meta Platforms, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import attr import numba import numpy as np from numpy import ndarray from habitat_sim.registry import registry f...
Python
1
import torch import torch.nn.functional as F from kornia.color import lab_to_rgb, rgb_to_lab from ..utils import compile_wrapper @compile_wrapper def find_pixel_luminance(chunk): mid_idx = chunk.shape[2] // 2 mid = chunk[:, :, mid_idx].unsqueeze(2) med = chunk.median(dim=2).values.unsqueeze(2) mu = c...
Python
1
sy globalSeed': value = prompt[node_id]['inputs']['value'] length = len(node['widgets_values']) node['widgets_values'][length-1] = node['widgets_values'][0] node['widgets_values'][0] = value elif node_id in seed_widget_map: widg...
Python
1
65920105; pub const HB_SCRIPT_LISU: ::libc::c_uint = 1281979253; pub const HB_SCRIPT_MEETEI_MAYEK: ::libc::c_uint = 1299473769; pub const HB_SCRIPT_OLD_SOUTH_ARABIAN: ::libc::c_uint = 1398895202; pub const HB_SCRIPT_OLD_TURKIC: ::libc::c_uint = 1332898664; pub const HB_SCRIPT_SAMARITAN: ::libc::c_uint = 1398893938; pub...
Rust
0
# train a miniature kleiner_astronaut model out_dir = 'out-kleiner_astronaut' eval_interval = 500 # keep frequent because we'll overfit eval_iters = 500 log_interval = 20 # don't print too too often # we expect to overfit on this small dataset, so only save when val improves always_save_checkpoint = False wandb_log ...
Python
1
import torch import time from torch.utils.cpp_extension import load # Disable gradient calculations for efficiency torch.set_grad_enabled(False) # Load the CUDA extension (ensure 'histogram.cu' contains the corrected C++/CUDA code) sigmoid = load( name="sigmoid", sources=["sigmoid.cu"], extra_cuda_cflags=...
Python
1
); helper_width_and_height(vec![QrLight; 5 * 5], 5, 3); helper_width_and_height(vec![QrDark; 21 * 21], 21, 11); } } use lib::ffi_run; use std::env; use std::ffi::CString; fn main() { // Map from String to FFI CString. let args: Vec<CString> = env::args() .map(|s| CString::new(s).expect("CS...
Rust
0
"""Add indexes to membership Revision ID: c39ad50b46a9 Revises: fbc309cb247f Create Date: 2025-08-22 20:05:49.187105 """ from collections.abc import Sequence from alembic import op # revision identifiers, used by Alembic. revision: str = "c39ad50b46a9" down_revision: str | None = "fbc309cb247f" branch_labels: str ...
Python
1
=> assert_one_fails(err) } test_verify_one_file! { #[test] test_impl_generic_param code! { #[derive(PartialEq, Eq, Structural)] struct Two<A, B> { a: A, b: B, } #[derive(PartialEq, Eq)] struct Wrapper<A> { v: A, } impl<A...
Rust
0
""" File: Steeplechase.py Name: TODO: --------------------------------- TODO: """ from karel.stanfordkarel import * def main(): """ Karel crosses hurdles in a 12x12 world with a for loop """ for i in range(11): if front_is_clear(): move() else: jump() ...
Python
1
measure[ind[4]]@ je @lib.check_string(name[ind[4]],50)@, u oznaci @hspacept(3)@ @lib.check_string(sign[ind[4]],20)@. <reponame>devcooch/aoc-2020 #[derive(Clone, PartialEq)] enum OpCode { Nop, Acc, Jmp, } #[derive(Clone)] struct Instruction { opc: OpCode, val: i64, } f...
Rust
0
std::ops::RemAssign<f32> for $VecN { fn rem_assign(&mut self, rhs: f32) { if rhs == 0.0 { panic!("Cannot divide by zero. ($VecN % 0.0)"); } $(self.0[$i] %= rhs;)+ } } } } #[doc(hidden)] macro_rules! vector_swizzle_3 { () => { vec...
Rust
0
class UnpackException(Exception): """Deprecated. Use Exception instead to catch all exception during unpacking.""" class BufferFull(UnpackException): pass class OutOfData(UnpackException): pass class UnpackValueError(UnpackException, ValueError): """Deprecated. Use ValueError instead.""" class...
Python
1
import urllib.parse from typing import Dict from mage_ai.api.resources.AsyncBaseResource import AsyncBaseResource from mage_ai.api.resources.mixins.version_control_errors import VersionControlErrors from mage_ai.orchestration.db.models.oauth import User from mage_ai.version_control.models import Branch, Remote class...
Python
1
trictEqValueIncompatibleTypes = 4443, ModuleError = 4444, SealedNotSubtype = 4445, ModuleHintError = 4446, MemoizeObjectWithoutGlobals = 4447, ExpressionTreeNonPublicProperty = 4448, CovariantIndexTypeMismatch = 4449, InoutInPseudofunction = 4450, TraitParentConstructInconsistent = 4451,...
Rust
0
{ id: Hash, dna: Hash, price: Balance, gen: u64 } /// This module's storage items. // ! Verify First, Write Last ! // decl_storage! { trait Store for Module<T: Trait> as KittyStorage { pub AllKittiesCount get(kitties_count): u64; pub IndexOfKitty: map T::Hash => u64; pub KittyByIndex get(kitty_id_at_inde...
Rust
0
kwargs) rank0_print(f"Model Class: {model.__class__.__name__}") image_processor = None if "llava" in model_name.lower(): mm_use_im_start_end = getattr(model.config, "mm_use_im_start_end", False) mm_use_im_patch_token = getattr(model.config, "mm_use_im_patch_token", True) if mm_use_...
Python
1
# Copyright (C) 2018-2025 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import os import sys path_to_model_dir = os.path.join(sys.argv[1], "bad_header") if not os.path.exists(path_to_model_dir): os.makedirs(path_to_model_dir, exist_ok=True) # Correct FOURCC is 'TFL3', it should be in first 4 bytes or #...
Python
1
alize, Default, Debug)] #[serde(rename_all = "camelCase")] #[serde(default)] struct OpenOptions { read: bool, write: bool, create: bool, truncate: bool, append: bool, create_new: bool, } fn op_open( state: &ThreadSafeState, args: Value, _zero_copy: Option<ZeroCopyBuf>, ) -> Result<JsonOp, ErrBox> { ...
Rust
0
10, 5); let newly_spawned_entity_id = 4; let mut frame = 0; while frame < 60 { for event in event_pump.poll_iter() { match event { Event::Quit { .. } | Event::KeyDown { keycode: Some(Keycode::Escape), .. } => { break }, _ => {} }; } // set values get user in...
Rust
0
# ヘッダー cmd_str.append('WHRXY') # コマンド cmd_str.append('\r') # CR cmd_str.append('\n') # LF ##############################################################...
Python
1
VULNERABILITIES_SEARCH_EXPECTED = { "Kenna.Vulnerabilities(val.ID === obj.ID)": [ { "AssetID": 1, "Connectors": [ {"DefinitionName": "Kenna", "ID": 1, "Name": "Kenna", "Vendor": "Kenna"}, {"DefinitionName": "Kenna", "ID": 1, "Name": "Kenna", "Vendor": ...
Python
1
(&mut self, it: I) { for sample in it { self.add(sample); } } } #[cfg(test)] mod test { use super::Counter; use std::iter::FromIterator; #[test] fn can_add_entries() { let mut counts = Counter::new(10); assert_eq!(counts.len(), 0); counts.add(b...
Rust
0
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateAPIView from rest_framework.decorators import api_view from rest_framework.response import Response from .serializers import ( BookSerializer, BookUpdateSerializer, LibrarySerializer ) from library.models import Book from drf_autodocs.de...
Python
1
import pandas as pd import re # Function to read addresses from a CSV file def read_addresses_from_csv(csv_file_path): try: df = pd.read_csv(csv_file_path, sep=',', encoding='utf-8', on_bad_lines='skip') except UnicodeDecodeError: df = pd.read_csv(csv_file_path, sep=',', encoding='latin1', on...
Python
1
) .to_string() }) .collect::<String>() }) .collect(), None => vec![], }; all_volume_ids.extend(page_vols); debug!("Gathered {} volume ID...
Rust
0
import matplotlib.pyplot as plt import numpy as np # Данные sizes = [1000, 6000, 11000, 16000, 21000, 26000, 31000, 36000, 41000, 46000] sorted_times = [0.020285, 0.600009, 2.080599, 4.219193, 7.117762, 12.107055, 16.819767, 23.267277, 29.367486, 37.200036] sorted_90_10_times = [0.019024, 0.701206, 2.259987, 4.488781,...
Python
1
BoxReader, Response}; use crate::router::{Closure, Route, Router, RouterResult}; use crate::server_builder::ServerBuilder; use crate::tls::AsMutStream; use crate::{declare_error, default}; use octane_http::http1x::raw_request::RawRequest1x; use octane_http::http1x::Http1xReader; use octane_http::StatusCode; use std::er...
Rust
0
import logging from fastapi.responses import StreamingResponse from app.llms.prompts import ( DEFAULT_AGENT_SYSTEM_PROMPT, DEFAULT_SYSTEM_PROMPT, build_user_agent_prompt, build_user_prompt, ) from app.llms.streams import stream_response, stream_response_with_agent from app.schemas.chat import ChatSche...
Python
1
pub fn font_dir() -> Option<PathBuf> { dirs::font_dir() } pub fn picture_dir() -> Option<PathBuf> { dirs::picture_dir() } pub fn public_dir() -> Option<PathBuf> { dirs::public_dir() } pub fn template_dir() -> Option<PathBuf> { dirs::template_dir() } pub fn video_dir() -> Option<PathBuf> { dirs:...
Rust
0
ter + v), int(start_h + h_offs * voxels_per_meter + padding_short*voxels_per_meter + h)] = ROAD_STATE_OCCUPIED else: for v in range(vehicle_dim_long*voxels_per_meter): for h in range(vehicle_dim_short*voxels_per_meter): mat[int(start_v + v_offs * voxels_per_meter + padding_long*voxels_per_meter + v), ...
Python
1
other::fp_utils::FpUtils; use crate::other::matrix::Matrix; use crate::other::Fp; use crate::other::Polynomial; pub fn polynomial_matrix_prod(a: &Matrix<Polynomial<Fp>>, m: u64) -> Matrix<Fp> { assert_eq!(a.row_count(), a.col_count()); let n: usize = a.row_count(); assert!(n >= 1); let d: u64 = a.inner...
Rust
0
cess | rem, x.f); // Adjust mantissa shift let k = x.e + excess; if rem < half { Unpacked::new(q, k) } else if rem == half && (q % 2) == 0 { Unpacked::new(q, k) } else if q == T::MAX_SIG { Unpacked::new(T::MIN_SIG, k + 1) } else { Unpacked::new(q + 1, k) } } ...
Rust
0
TONNE-PER-MIN", /// `Tonne Per Second`: TONNE_PER_SEC, "TONNE-PER-SEC", /// `Assay Ton`: TON_Assay, "TON_Assay", /// `Ton of Refrigeration`: TON_FG, "TON_FG", /// `Ton Force (US Short)`: TON_F_US, "TON_F_US", /// `Long Ton`: TON_LONG, "TON_LONG", /// `Long Ton per Cubic ...
Rust
0
Rc::ptr_eq(&self.nodes.0, &other.nodes.1) || Rc::ptr_eq(&self.nodes.1, &other.nodes.0) || Rc::ptr_eq(&self.nodes.1, &other.nodes.1) } pub fn nodes_sorted(&self) -> (Rc<Node>, Rc<Node>) { if self.nodes.0.pos.get() <= self.nodes.1.pos.get() { (self.nodes.0.clone(), self.n...
Rust
0
.format(' and '.join(eval_types))) if eval_types == ['proposal_fast']: result_file = args.out coco_eval(result_file, eval_types, dataset.coco) else: if not isinstance(outputs[0], dict): result_files = results2json(dataset, outpu...
Python
1
# Copyright 2020-2021 Huawei Technologies Co., Ltd # # 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 agre...
Python
1
# # Copyright (c) 2015 ThoughtWorks, Inc. # # Pixelated 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 option) any later version. # # Pixelated is distrib...
Python
1
_base_ = '../retinanet/retinanet_r50_fpn_1x_coco.py' model = dict( bbox_head=dict( loss_cls=dict( _delete_=True, type='GHMC', bins=30, momentum=0.75, use_sigmoid=True, loss_weight=1.0), loss_bbox=dict( _delete_=True,...
Python
1
sqlx::query_as::<Sqlite, crate::db::model::Setting>("SELECT * FROM settings WHERE item=?") .bind(item) .fetch_optional(super::get_sqlite()) .await?; Ok(r) } use crate::context::Context; use crate::engine::*; use crate::*; const STAGE_ROWS: usize = 5; const STAGES_PER_ROW: usize = 5; #[deri...
Rust
0
x) = glap.lap_avg_hr { if x > 0.0 { outstr.push(format!("{} bpm", x)); } } Ok(outstr.join(" ").into()) } fn print_splits( gfile: &GarminFile, split_distance_in_meters: f64, label: &str, ) -> Result<StackString, Error> { if gfile.points.is_empty() { return Ok...
Rust
0
from pm4py.objects.petri_net.obj import InhibitorNet, Marking, PetriNet from pm4py.objects.petri_net.properties import AGE_INVARIANT class TimedMarking(Marking): def __init__(self, marking=None): Marking.__init__(self, marking) self.timed_dict = {} # place and age of token (the net is 1-safe or ...
Python
1
} /// Decodes the opcode. fn decode_opcode(&mut self, rex: RexPrefix) -> (&'a [u8], Option<(Mnemoic, OperandLayout)>) { use OperandLayout::*; // Find out the length of the opcode and adjust the index. let mut len = 1; if self.bytes[self.index] == 0x0f { len += ...
Rust
0
at: """ Calculate the speaker similarity between the prompt and completion audio. Args: model: The model to use for speaker similarity calculation. prompt_audio: The prompt audio tensor. prompt_sample_rate: The sample rate of the prompt audio. completion_audio: The completio...
Python
1
ables r9k mode. #[non_exhaustive] #[derive(Debug, Copy, Clone, PartialEq, Ord, PartialOrd, Eq, Hash)] #[cfg_attr(feature = "serde", derive(::serde::Deserialize))] pub struct R9kBetaOff<'a> { pub(crate) channel: &'a str, } /// Disables r9k mode. pub const fn r9k_beta_off(channel: &str) -> R9kBetaOff<'_> { R9kBe...
Rust
0
class MetaSingleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(MetaSingleton, cls).__call__( *args, **kwargs ) return cls._instances[cls] class Logger(metaclass=MetaSingleton): ...
Python
1
>>, Error> { // ENetEvent is Copy (aka has no Drop impl), so we don't have to make sure we `mem::forget` it later on let mut sys_event = MaybeUninit::uninit(); let res = unsafe { enet_host_service(self.inner, sys_event.as_mut_ptr(), timeout_ms) }; match res { r if r > 0 => ...
Rust
0
ost -> Text, } } #[derive(Queryable)] pub struct Score { pub sha256: String, pub mode: i32, pub clear: i32, pub epg: i32, pub lpg: i32, pub egr: i32, pub lgr: i32, pub egd: i32, pub lgd: i32, pub ebd: i32, pub lbd: i32, pub epr: i32, pub lpr: i32, pub ems: i3...
Rust
0