text string | label_name string | labels int64 |
|---|---|---|
import logging
import tensorflow as tf
logger = logging.getLogger(__name__)
__all__ = ['is_gpu_available', 'log_memory_usage']
def is_gpu_available() -> bool:
'''
Check if a GPU is available for TensorFlow.
Args:
None
Returns:
bool: True if a GPU is available, False otherwise.
... | Python | 1 |
ThreadsafeFunctionCallMode> for sys::napi_threadsafe_function_call_mode {
fn from(value: ThreadsafeFunctionCallMode) -> Self {
match value {
ThreadsafeFunctionCallMode::Blocking => sys::ThreadsafeFunctionCallMode::blocking,
ThreadsafeFunctionCallMode::NonBlocking => sys::ThreadsafeFunctionCallMode::no... | Rust | 0 |
elapsed_days to unix time (in seconds)
let time_interval = FilterInterval {
end: Self::from_elapsed_days_to_unix_time(self.elapsed_days_interval.start),
start: Self::from_elapsed_days_to_unix_time(self.elapsed_days_interval.end),
};
let mut query = format!(
"... | Rust | 0 |
riter::new();
writer.write(buf);
let mut reader = MemReader::new(writer.inner());
let f = reader.read_be_f32();
assert!(f == 8.1250);
}
#[test]
fn test_read_write_f32() {
let f:f32 = 8.1250;
let mut writer = MemWriter::new();
writer.write_be_f32(f);... | Rust | 0 |
rmatted_number).unwrap();
(p_meta.pfun_add_text)( p_meta.p_textfun_cargo,
plugin_message_c.as_ptr(),
vooPluginTextFlag_AlignCenter,
p_seq_info.width/2, p_seq_info.height-40 );
}
<filename>src/response/user.rs<gh_stars>0
use super::Medium;
use super::Timestamp;
use super::WatchState;
use supe... | Rust | 0 |
"""sPoNgEcAsE, by Al Sweigart al@inventwithpython.com
Translates English messages into sPOnGEcAsE.
This code is available at https://nostarch.com/big-book-small-python-programming
Tags: tiny, beginner, word"""
import random
try:
import pyperclip # pyperclip copies text to the clipboard.
except ImportError:
p... | Python | 1 |
import numpy as np
import torch
from sklearn.model_selection._split import _BaseKFold, indexable, _num_samples
from sklearn.utils.validation import _deprecate_positional_args
from torch.utils.data import TensorDataset
from colorama import Fore, Style
# 设置打印颜色
def PrintColor(text:str, color = Fore.BLUE, style = Style.B... | Python | 1 |
🇮🇨"]
//! );
//!
//! assert_eq!(
//! GraphemeIndices::new("a̐éö̲\r\n").collect::<Vec<(usize, &str)>>(),
//! &[(0, "a̐"), (3, "é"), (6, "ö̲"), (11, "\r\n")]
//! );
//!
//! fn has_alphanumeric(s: &&str) -> bool {
//! s.chars().any(|ch| ch.is_alphanumeric())
//! }
//!
//! assert_eq!(
//! Words::new(
//! ... | Rust | 0 |
'''
Python knows a number of compound data types,
used to group together other values. The most
versitile is a list.
Others include:
tuple
dictionary
set
Lists are written as a list of comma-seperated values (items) between square brackets
Lists are mutable - this means that items can be changed
Lists have a bun... | Python | 1 |
Some(Tuple::from_ptr(result_ptr))
})
}
/// Return a first (minimal) tuple matched the provided key.
///
/// - `key` - encoded key in MsgPack Array format (`[part1, part2, ...]`).
///
/// Returns a tuple or `None` if index is empty
pub fn min<K>(&self, key: &K) -> Result<Option<Tuple... | Rust | 0 |
class Solution:
def executeInstructions(self, n: int, startPos: List[int], s: str) -> List[int]:
moves = {'L': (0, -1), 'R': (0, 1), 'U': (-1, 0), 'D': (1, 0)}
m = len(s)
uMost = startPos[0] + 1
dMost = n - startPos[0]
lMost = startPos[1] + 1
rMost = n - startPos[1]
ans = [0] * m
reac... | Python | 1 |
workspace
))
}
}
<reponame>guerinoni/leetcode
// NOTE: first approach.
// pub fn my_sqrt(x: i32) -> i32 {
// for i in 0..=x {
// let current = i * i;
// if current == x {
// return i;
// } else if current > x {
// return i - 1;
// }
// }
... | Rust | 0 |
ValueError)r. xs r0 r1 _Dependent.check LMMr4 rP rO r: r@ rA rB rC rY rR propertyboolrD intrE rd r1 rF
__classcell__)r9 s @r0 rI rI j h '5
!T ! !
3
'5
HN Nr4 rI c ... | Python | 1 |
import subprocess
class RemoteNode:
def __init__(self, remote_ip: str, identity_file: str, remote_port: int = 22, remote_username: str = "root"):
self.remote_port = remote_port
self.remote_username = remote_username
self.remote_ip = remote_ip
self.identity_file = identity_file
... | Python | 1 |
from pandas.core.groupby.base import transformation_kernels
# There is no Series.cumcount or DataFrame.cumcount
series_transform_kernels = [
x for x in sorted(transformation_kernels) if x != "cumcount"
]
frame_transform_kernels = [x for x in sorted(transformation_kernels) if x != "cumcount"]
| Python | 1 |
from flask_wtf import FlaskForm
from flask_wtf.file import FileAllowed, FileField, FileRequired, FileSize
from govuk_frontend_wtf.wtforms_widgets import GovFileInput, GovSubmitInput, GovTextInput
from wtforms import HiddenField, StringField, SubmitField
from wtforms.validators import DataRequired
class TemplateCreate... | Python | 1 |
if keyed_only {
keyed_only = false;
}
// If there were keyed ones before push them first to maintain order.
if !keyed.is_empty() {
items.push(HtmlItems::Keyed(keyed));
keyed = vec![];
... | Rust | 0 |
(visitor: &mut V, expr: &'a RcExpr) {
match expr.as_ref() {
Expr::Const(k) => visitor.visit_const(k, expr.span),
Expr::Var(v) => visitor.visit_var(v, expr.span),
Expr::BinaryExpr(b) => visitor.visit_binary(b, expr.span),
Expr::UnaryExpr(u) => visitor.visit_unary(u, expr.span),
... | Rust | 0 |
tance: Arc<Instance>,
pub adapter: Arc<Adapter>,
pub device: Arc<Device>,
pub queue: Arc<Queue>,
pub raw_instance: ash::Instance,
pub raw_physical_device: vk::PhysicalDevice,
pub raw_device: ash::Device,
pub queue_family_index: u32,
pub queue_index: u32,
}
pub fn quad_shader(device: &De... | Rust | 0 |
import heapq
import math
def a_star():
# Define the initial state of the city map as a 2d tuple
initial_state = ((7, 'x', 19, 11, 6, 'x', 4, 15, 9, 3),
('x', 'x', 13, 'x', 8, 17, 'x', 'x', 12, 16),
('x', 'x', 2, 'x', 15, 8, 'x', 13, 4, 'x'),
(13,... | Python | 1 |
pub buffer_type: wlr_output_state_buffer_type,
pub buffer: *mut wlr_buffer,
}
pub type wlr_output_state_buffer_type = libc::c_uint;
pub const WLR_OUTPUT_STATE_BUFFER_SCANOUT: wlr_output_state_buffer_type = 1;
pub const WLR_OUTPUT_STATE_BUFFER_RENDER: wlr_output_state_buffer_type = 0;
#[repr(C)]#[derive(Copy, C... | Rust | 0 |
eight + target_image_pil.height + padding
elif axis == 1: # horizontal
width = source_image_pil.width + target_image_pil.width + padding
height = max(source_image_pil.height, target_image_pil.height)
else:
raise ValueError("axis must be 0 or 1")
if resize and axis == 0:
sou... | Python | 1 |
requesting_user_email_address: str,
page_size: int = 10,
filters: Optional[Filters] = None,
) -> str:
"""
Retrieve Clappia form submissions with optional filtering.
Args:
app_id (str): Application identifier (e.g., "ODT537440"). Must be uppercase letters and numbers.
requesting_u... | Python | 1 |
"Offset of field: ",
stringify!(ble_gattc_conn_cfg_t),
"::",
stringify!(write_cmd_tx_queue_size)
)
);
}
#[doc = "@brief Operation Handle Range."]
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct ble_gattc_handle_range_t {
#[doc = "< Start Handle."]
... | Rust | 0 |
eq!(
directive.to_string(),
r#""""Infer field types from field values."""
directive @infer(cat: [SpaceProgram]) on OBJECT
"#
);
}
}
//! Type definition for green node.
//!
//! See <https://github.com/rust-analyzer/rust-analyzer/blob/master/docs/dev/syntax.md>
use anyhow::*;
use iter... | Rust | 0 |
/// Type of the captured binding.
pub ty: Ty<'tcx>,
/// Span of the binding that was captured.
pub span: Span,
/// Span of the scope of the captured binding.
pub scope_span: Option<Span>,
/// Span of `.await` or `yield` expression.
pub yield_span: Span,
/// Expr which the type evalua... | Rust | 0 |
# extern crate reqwest;
/// # fn run() -> Result<(), Box<::std::error::Error>> {
/// let client = reqwest::Client::builder()
/// .proxy(reqwest::Proxy::http("https://my.prox")?)
/// .build()?;
/// # Ok(())
/// # }
/// # fn main() {}
/// ```
pub fn http<U: IntoUrl>(url: U) ->... | Rust | 0 |
class PrintHandler:
@staticmethod
def show_banner(banner: str):
print(f"\n\n====== {banner} ======\n")
@staticmethod
def print_props(obj_or_list):
if isinstance(obj_or_list, list):
for obj in obj_or_list:
for attr, value in vars(obj).items():
... | Python | 1 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
print ''
print '***************************************************************************************'
print '* *'
print '* Advent of code 2017 4/12 ... | Python | 1 |
## Cálculo da Distância
dist = float(input("Digite a distância a percorrer: \n"))
if dist <= 200:
valor = dist * 0.50
else:
valor = dist * 0.35
print(f"O preço da passagem é: R$ {valor:.2f}")
# Aumento salário funcionário
salario = float(input("Informe seu salário: \n"))
if salario <= 1250:
aumento = sal... | Python | 1 |
App::new("UnikeyBruteForcer")
.version("0.1.0")
.author("<NAME> <<EMAIL>>")
.about("https://github.com/LivingInSyn/UnikeyBruteForcer")
.arg(Arg::with_name("upass1")
.help("User password 1")
.required(true))
.arg(Arg::with_name("upass2")
.help(... | Rust | 0 |
inputs):
goal_embedding = inputs['goal_embedding']
state_inputs = inputs['state_input']
projection_mat = tf.tile(self._projection_mat,
[tf.shape(state_inputs)[0], 1, 1])
out = tf.reshape(state_inputs,
(-1, np.prod(self.out_shape[1:-1]), self.out_shape[-1... | Python | 1 |
es.iter() {
let (process, allocation_size) = *allocated_sizes.get(*i).unwrap();
let process = ProcessUid(process);
expected_sum -= allocation_size;
tracker.free_anon_mmap(process, addresses[*i], allocation_size);
expected_memory_usage[*i] -... | Rust | 0 |
pub fn console_in_handle(&self) -> Handle {
(self.console_in_handle)
}
pub fn console_in(&self) -> &'static TextInput {
(self.console_in)
}
pub fn console_out_handle(&self) -> Handle {
(self.console_out_handle)
}
pub fn console_err_handle(&self) -> Handle {
... | Rust | 0 |
------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'Py_xDH', 'Py_xDH Documentation',
author, 'Py_xDH', 'One line description of project.',
'Miscel... | Python | 1 |
= False,
save_file_path: Optional[str] = None,
**kwargs
):
n_columns = len(input_tokens)
n_rows = rankings.shape[0]
fsize = (1 + 0.9 * n_columns, # Make figure wider if more columns
1 + 0.4 * n_rows) #... | Python | 1 |
_QUATERNION_X" => CurveType::RotateQuaternion(0),
"ROTATION_QUATERNION_Y" => CurveType::RotateQuaternion(1),
"ROTATION_QUATERNION_Z" => CurveType::RotateQuaternion(2),
"ROTATION_QUATERNION_W" => CurveType::RotateQuaternion(3),
"SCALE_X" => ... | Rust | 0 |
# Copyright (c) 2025, NVIDIA CORPORATION.
import numpy as np
import pandas as pd
import pytest
import cudf
from cudf.testing import assert_eq
@pytest.mark.parametrize("nulls", ["none", "some"])
def test_interleave_columns(nulls, all_supported_types_as_str):
if (
all_supported_types_as_str not in ["float... | Python | 1 |
et stmt = runtime.block_on(prepare).unwrap();
let query = client.query(&stmt, &[]).collect();
let rows = runtime.block_on(query).unwrap();
let result = rows[0].get(0);
assert_eq!(val, &result);
let prepare = client.prepare(&format!("SELECT $1::{}", sql_type));
let stmt =... | Rust | 0 |
er::Int(val))
}
_ => println!("", )
}
}
pub fn add_val(ni : &mut NestedInteger, val : i32) {
match ni {
NestedInteger::List(vec ) => {
let len = vec.len();
let mut top = vec.as_slice()[len-1];
vec.pop();
... | Rust | 0 |
from typing import TypedDict, Optional
from mathesar.models.base import Server
from mathesar.rpc.decorators import mathesar_rpc_method
class ConfiguredServerInfo(TypedDict):
"""
Information about a database server.
Attributes:
id: the Django ID of the server model instance.
host: The hos... | Python | 1 |
"3.13").await;
get_manifest(&client, "f/docker/library/alpine", "3.13").await;
//This should use same alpine image as base (so partially cached)
get_manifest(&client, "f/docker/library/nginx", "1.21.0-alpine").await;
//Need to special case single name repos
get_manifest(&clien... | Rust | 0 |
#NLTK (Natural Language Toolkit) is a powerful library for working with human language data and Many developers really like using this platform to make chatbots
import nltk
from nltk.chat.util import Chat, reflections
'''This is a list of patterns and their corresponding responses
Each pattern is a tuple containing a r... | Python | 1 |
our host operating system using this command:', file=message)
print(' simple_switch_CLI --thrift-port <switch thrift port>', file=message)
print(file=message)
print('To view a switch log, run this command from your host OS:', file=message)
print(' tail -f %s/<switchname>.log' % log_di... | Python | 1 |
# -*- coding: utf-8 -*-
# vStream https://github.com/Kodi-vStream/venom-xbmc-addons
from operator import itemgetter
import re
class cParser:
def sorted_nicely(self, l, key):
""" Sort the given iterable in the way that humans expect."""
convert = lambda text: int(text) if text.isdigit() else text
... | Python | 1 |
($name{
completion_code
});
};
($name:ident {
$($method:ident),*
})=>{
impl_debug_for_trb!($name{
completion_code,
$($method),*
});
}
}
event!(
PortStatusChange,
"Port Status Change Event TRB",
Type::PortStatusChange
);
res... | Rust | 0 |
2, 0));
// Get the determinant
let mut vTemp: XMVECTOR = XMVector4Dot(C0, MT.r[0]);
if let Some(determinant) = pDeterminant {
*determinant = vTemp;
}
vTemp = _mm_div_ps(g_XMOne.v, vTemp);
let mut mResult: XMMATRIX = crate::undefined();
mResult.r[0] ... | Rust | 0 |
)
elif saas_url and saas_account_id and saas_token:
connection_params = get_connection_params(
host=saas_url,
account_id=saas_account_id,
database_id=saas_database_id,
database_name=saas_database_name,
pat=saas_token,
... | Python | 1 |
SIC_BIST_CS_REG_SPEC>;
#[doc = "CSIC BIST CS Register"]
pub mod csic_bist_cs_reg;
#[doc = "CSIC_BIST_CONTROL_REG register accessor: an alias for `Reg<CSIC_BIST_CONTROL_REG_SPEC>`"]
pub type CSIC_BIST_CONTROL_REG = crate::Reg<csic_bist_control_reg::CSIC_BIST_CONTROL_REG_SPEC>;
#[doc = "CSIC BIST Control Register"]
pub m... | Rust | 0 |
make it equivalent
/// to the public key of our transaction signing scheme.
pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;
/// The type for looking up accounts. We don't expect more than 4 billion of them, but you
/// never know...
pub type AccountIndex = u32;
/// Index of a transa... | Rust | 0 |
# Copyright (C) 2018-2025 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import argparse
import io
import os
import unittest
from contextlib import redirect_stdout
from unittest.mock import patch
from openvino.tools.ovc.main import main
from openvino.tools.ovc.get_ov_update_message import get_compression_mes... | Python | 1 |
_batch
points_batch = position_batch[..., [0, 1, 2, 4, 5, 6, 7]]
valid_batch = valid_depth_batch # * valid_z_p_batch * valid_z_n_batch
return points_batch, valid_batch
import sys
sys.path.append(osp.realpath(osp.join(osp.realpath(__file__), '../../../..')))
from pointnet2_ops import pointnet2_utils
d... | Python | 1 |
Write;
use crate::internal::fixed_bits::{Bits32TypeTag, Bits64TypeTag};
use crate::internal::types::WireType;
use crate::internal::variant::{Variant, VariantTypeTag};
use crate::ErrorKind;
use crate::{tags, Result};
use ::std::convert::TryInto;
use ::std::io::Write;
use ::std::marker::PhantomData;
pub fn write_field_n... | Rust | 0 |
0x2b9;
pub const XK_gbreve: c_uint = 0x2bb;
pub const XK_jcircumflex: c_uint = 0x2bc;
pub const XK_Cabovedot: c_uint = 0x2c5;
pub const XK_Ccircumflex: c_uint = 0x2c6;
pub const XK_Gabovedot: c_uint = 0x2d5;
pub const XK_Gcircumflex: c_uint = 0x2d8;
pub const XK_Ubreve: c_uint = 0x2dd;
pub const XK_Scircumflex: c_uint... | Rust | 0 |
.did_update(&did, &options, &payload)
.await
.map_err(jsify)?;
let err_msg = "could not update DID document";
ensure(results.len() > 0, || format!("{}: '{}'", &err_msg, &did))?;
Ok(())
}
// vc-zkp
#[cfg(feature = "vc-zkp")]
#[wasm_bindgen]
pub async fn create_schema(
issuer: St... | Rust | 0 |
n = int(input())
if n == 1 :
print(1)
exit()
count =1
room = 1
while True:
room += count*6
count+=1
if n <= room:
print(count)
exit() | Python | 1 |
er {
return Driver{c_driver: c_driver};
}
pub unsafe fn _c_ptr(&self) -> *const c_void {
return self.c_driver;
}
pub fn short_name(&self) -> String {
let rv = unsafe { gdal::GDALGetDriverShortName(self.c_driver) };
return _string(rv);
}
pub fn long_name(&self) ... | Rust | 0 |
ers))
}
}
impl Connection for UnixStreamWrapper {
fn peer_address(&self) -> Option<BindableAddr> {
self.0.peer_addr().ok().and_then(|addr| {
addr.as_pathname()
.map(|path| BindableAddr::Unix(path.to_owned()))
})
}
}
}
pub ... | Rust | 0 |
rom(u: U) -> Self {
Self::new(u)
}
}
#[doc(hidden)]
#[macro_export]
macro_rules! internal_pin_stack {
($id:ident) => {
// Shadow the original binding so that it can't directly be accessed ever again.
let $id: $crate::PinStack<_> = unsafe {
let $id = $crate::StackPinned::new(... | Rust | 0 |
def recursion(string, start, end):
global many
if start >= end:
return 1
elif string[start] != string[end]:
return 0
else:
many += 1
return recursion(string, start+1, end-1)
def isPalindrome(string):
global many
many += 1
return recursion(string, 0, len(strin... | Python | 1 |
_rx(rx);
let ry_val = cpu.get_rx(ry);
let result = rx_val.wrapping_add(ry_val);
change_flags_add(cpu, rx_val, ry_val, result);
cpu.set_rx(rz, result)
}
fn change_flags_sub(cpu: &mut Cpu, original: i16, value: i16, result: i16) -> () {
change_flags_add(cpu, original, -value, result); //Except for carry, they're th... | Rust | 0 |
inline] fn opencv_as_extern(&self) -> Self { *self }
#[inline] fn opencv_as_extern_mut(&mut self) -> Self { *self }
#[inline] fn opencv_into_extern(self) -> Self { self }
}
)+
};
}
#[macro_export]
macro_rules! opencv_type_enum {
($type: ty) => {
$crate::opencv_type_copy! { $type }
};
}
#[macro_expor... | Rust | 0 |
#!/usr/bin/env python
# Michael Saunby. April 2013
#
# Read temperature from the TMP006 sensor in the TI SensorTag
# It's a BLE (Bluetooth low energy) device so using gatttool to
# read and write values.
#
# Usage.
# sensortag_test.py BLUETOOTH_ADR
#
# To find the address of your SensorTag run 'sudo hcitool lesca... | Python | 1 |
f field_name:
return st.session_state.validation_errors.get(field_name, {})
return st.session_state.validation_errors
def create_validation_rules_ui(self) -> Dict[str, Any]:
"""Cria interface para configurar regras de validação"""
st.markdown("### ⚙️ Configurar Regras de Val... | Python | 1 |
ot defined for negative values".to_owned()));
} else if *value <= BigInt::one() {
return Ok(BigInt::from(1u64));
}
let ret: BigInt = num_iter::range_inclusive(BigInt::from(1u64), value.clone()).product();
Ok(ret)
}
fn math_modf(x: IntoPyFloat) -> (f64, f64) {
let x = x.to_f64();
if !x.i... | Rust | 0 |
from logicblocks.event.store import conditions
from logicblocks.event.store.types import stream_publish_definition
from logicblocks.event.testing import NewEventBuilder
class TestStreamPublishDefinition:
def test_creates_definition_with_events_only(self):
events = [
NewEventBuilder().with_name... | Python | 1 |
(Debug, Clone, Copy, PartialEq, Default)]
pub struct GradientStop {
/// The percentage of this color step
pub percentage: f32,
/// The color of this step
pub color: Color,
}
//! Utilities for [Addons].
//!
//! [Addons]: crate::xterm::TerminalAddon
use super::disposable::XtermDisposable;
use super::{int... | Rust | 0 |
pub struct DCDC_VBAT_VALUE_W<'a> {
w: &'a mut W,
}
impl<'a> DCDC_VBAT_VALUE_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 2)) | (((value as u32) & 0x07) << 2);
self.w
}
}
#[doc = "Reader of ... | Rust | 0 |
import pytest
import torch
import torch.distributions as dist
import models.bnn as bnn
def bayesian_regression(n, d, data_precision, prior_precision):
x = torch.randn(n, d)
w = torch.randn(d, 1) * prior_precision ** -0.5
y = x.mm(w) + torch.randn(n, 1) * data_precision ** -0.5
posterior_precision =... | Python | 1 |
ꍰe < d Z ddlmZ ddlZ ee j j ZdZdZ g Z
g dZg dZdZ
dZd gZg d
Zdg ddg d
idgZdZddedz diZddiddiddiddigZdZdZdZdZdZdZej ed ... | Python | 1 |
# decompyle3 version 3.9.0
# Python bytecode version base 3.7.0 (3394)
# Decompiled from: Python 3.7.16 (default, Jan 17 2023, 09:28:58)
# [Clang 14.0.6 ]
# Embedded file name: output/Live/mac_universal_64_static/Release/python-bundle/MIDI Remote Scripts/ableton/v3/control_surface/components/view_toggle.py
# Compiled a... | Python | 1 |
# print(prd_fi)
# quantity_result = str(self.lineEdit_quantity.text())
max_id = None
update_flg = None
barcode_num = self.barcode_num
# print(self.barcode)
if str(barcode_num-1) == str(quantity_value) and str(lot_value) != " ":
with psycopg2.connect(host... | Python | 1 |
from pydantic import BaseModel
class UserCreateCommand(BaseModel):
email: str
class UserCreateCommandResult(BaseModel):
id: str
class UserDeleteCommand(BaseModel):
id: str
class UserDeleteCommandResult(BaseModel): ...
| Python | 1 |
Box::new(future::ok(response))
}
}
}
}
}
#[cfg(test)]
mod test {
use super::*;
use futures::Stream;
use hyper::StatusCode;
#[test]
fn test_app_server_resolve_endpoint() {
let mut router = Router::new();
router.get("/", |mut context: Contex... | Rust | 0 |
"stats_count": len(self._stats),
"streaming_config": {
"chunk_size": self._streaming_config.chunk_size,
"adaptive_chunking": self._streaming_config.adaptive_chunking,
},
"recent_metrics": {}
}
... | Python | 1 |
##############################################################################
#
# Copyright (c) 2004 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... | Python | 1 |
dev.read_temperature());
let result = dev.read_temperature().unwrap();
assert_near!(-127.5, result, 0.2);
destroy(dev);
}
write_test!(can_shutdown, shutdown, [], MODE, [BF::SHUTDOWN]);
write_test!(can_wake_up, wake_up, [], MODE, [0]);
write_test!(can_reset, reset, [], MODE, [BF::RESET]);
write_test!(can_cl... | Rust | 0 |
_DATA_SPACE_PHYSICAL: u32 = 1u32;
#[doc = "*Required features: `\"Win32_System_Diagnostics_Debug\"`*"]
pub const DEBUG_DATA_SPACE_VIRTUAL: u32 = 0u32;
#[doc = "*Required features: `\"Win32_System_Diagnostics_Debug\"`*"]
pub const DEBUG_DATA_SavedContextAddr: u32 = 40u32;
#[doc = "*Required features: `\"Win32_System_Dia... | Rust | 0 |
user_group=usergroup,
tenant=tenant,
app=app,
).first()
compress = Compress()
permission_result = ''
if usergroup_permissionresult:
permission_result = compress.decrypt(usergroup_permissionresult.result)
# 对数据进行一次排序
data_dict = co... | Python | 1 |
Edit_SetChildSizing(AObj: usize, AValue: usize);
pub fn RichEdit_GetBorderSpacing(AObj: usize) -> usize;
pub fn RichEdit_SetBorderSpacing(AObj: usize, AValue: usize);
pub fn RichEdit_GetDockClients(AObj: usize, Index: i32) -> usize;
pub fn RichEdit_GetControls(AObj: usize, Index: i32) -> usize;
pub fn RichEdi... | Rust | 0 |
results show that it's 0.5.)
#
constraints.append(WordEmbeddingDistance(min_cos_sim=0.5))
#
# Only replace words with the same part of speech (or nouns with verbs)
#
constraints.append(PartOfSpeech(allow_verb_noun_swap=True))
#
# Universal Sentence Encode... | Python | 1 |
_("初级骚扰"): constant.Behavior.LOW_OBSCENITY_ANUS,
_("道具"): constant.Behavior.LOW_OBSCENITY_ANUS,
_("口交"): constant.Behavior.LOW_OBSCENITY_ANUS,
_("严重骚扰"): constant.Behavior.HIGH_OBSCENITY_ANUS,
_("药物"): constant.Behavior.HIGH_OBSCENITY_ANUS,
... | Python | 1 |
x2name_dict=residue_index2name_dict, protein_atom_index2standard_name_dict=protein_atom_index2standard_name_dict, atom_reisdue2standard_atom_name_dict=atom_reisdue2standard_atom_name_dict)
self.data_list.append(data)
return
def __len__(self):
return 1
def __getitem__(self, idx):
... | Python | 1 |
idatorsThreshold = DisabledValidatorsThreshold;
type WeightInfo = pallet_session::weights::SubstrateWeight<Runtime>;
}
impl pallet_session::historical::Config for Runtime {
type FullIdentification = pallet_staking::Exposure<AccountId, Balance>;
type FullIdentificationOf = pallet_staking::ExposureOf<Runtime... | Rust | 0 |
[24..32].copy_from_slice(ret_value);
}
}
// Update checksum
let checksum = checksum(&slice[..32]);
let raw_checksum = &u32::to_le_bytes(checksum)[..];
slice[32..].copy_from_slice(raw_checksum);
result
}
}
impl Write<UartReply> for UART {
type Error... | Rust | 0 |
import _plotly_utils.basevalidators
class FamilysrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self, plotly_name="familysrc", parent_name="bar.insidetextfont", **kwargs
):
super(FamilysrcValidator, self).__init__(
plotly_name=plotly_name,
parent_... | Python | 1 |
<reponame>Ewpratten/raylib-rs<filename>samples/font.rs
extern crate raylib;
use raylib::prelude::*;
fn main() {
let w = 800;
let h = 450;
let rust_orange = Color::new(222, 165, 132, 255);
let ray_white = Color::new(255, 255, 255, 255);
let (mut rl, thread) = raylib::init().size(w, h).title("Logo").... | Rust | 0 |
"""微信公众平台消息加解密支持"""
from ..core.tools import encrypt
from . import const
class Encrypt:
"""
为微信公众平台封装的消息加解密类
"""
def __repr__(self) -> str:
"""返回 repr 信息"""
return "<Leaf WeiXin.Encrypt>"
def __init__(self, aeskey: str, appid: str, token: str):
"""
加解密类构造函数:
... | Python | 1 |
(raw_input_text),
NewlineStyle::Native => Self::native_newline_style(),
NewlineStyle::Windows => Self::Windows,
NewlineStyle::Unix => Self::Unix,
}
}
pub fn auto_detect_newline_style(raw_input_text: &str) -> Self {
let first_line_feed_pos = raw_input_text.cha... | Rust | 0 |
error: Exception,
task_id: str
) -> AsyncGenerator[StreamingEvent, None]:
"""Handle errors during streaming task execution"""
self.logger.error(
"Streaming task execution error",
task_id=task_id,
error=str(error),
error_type=type(error)... | Python | 1 |
from sklearn.metrics import (
accuracy_score, classification_report, confusion_matrix, roc_curve, roc_auc_score
)
def measure_results(graph):
# Extracting the 'pred' and 'label' attributes
pred = [data['pred'] for _, data in graph.nodes(data=True)]
label = [data['label'] for _, data in graph.nodes(data... | Python | 1 |
"""Make location mandatory
Revision ID: 3d41c209db4d
Revises: 258163e42b29
Create Date: 2025-01-07 07:12:02.609170
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = "3d41c209db4d"
down_revision: Union[str, None] = "258163... | Python | 1 |
with T.init():
Conv_wmma_accumulator[v_n, v_h, v_w, v_o, v_nn, v_oo] = T.float16(0)
Conv_wmma_accumulator[v_n, v_h, v_w, v_o, v_nn, v_oo] = Conv_wmma_accumulator[v_n, v_h, v_w, v_o, v_nn, v_oo] + Apad_shared_wmma_matrix_a[v_n,... | Python | 1 |
from dataclasses import dataclass
from pathlib import Path
from typing import Optional
@dataclass
class PluginManagerProperties:
plugin_dir: Path
enable: bool
plugin_context_path: str
plugin_config_dir: Path
@staticmethod
def from_dict(config: dict) -> 'PluginManagerProperties':
"""
... | Python | 1 |
import kloch
import kloch.launchers
from kloch.launchers import get_available_launchers_classes
from kloch.launchers import is_launcher_plugin
from kloch.launchers._plugins import _check_launcher_serialized_implementation
from kloch.launchers._plugins import _check_launcher_implementation
from kloch.launchers import ge... | Python | 1 |
7' as u8, '~' as u8];
const F7_ES: [u8; 5] = [ESC_CHAR, '[' as u8, '1' as u8, '8' as u8, '~' as u8];
const F8_ES: [u8; 5] = [ESC_CHAR, '[' as u8, '1' as u8, '9' as u8, '~' as u8];
const F9_ES: [u8; 5] = [ESC_CHAR, '[' as u8, '2' as u8, '0' as u8, '~' as u8];
const F10_ES: [u8; 5] = [ESC_CHAR, '[' as ... | Rust | 0 |
from opencompass.openicl.icl_prompt_template import PromptTemplate
from opencompass.openicl.icl_retriever import ZeroRetriever
from opencompass.openicl.icl_inferencer import GenInferencer
from opencompass.datasets import SanitizedMBPPDataset, MBPPPassKEvaluator
sanitized_mbpp_reader_cfg = dict(input_columns=["text", "... | Python | 1 |
_to_idx(&self, &ground_truth, &classes);
// count each index tuple in the confusion matrix
let mut confusion_matrix = Array2::zeros((classes.len(), classes.len()));
for (i1, i2) in indices.into_iter().filter_map(|x| x) {
confusion_matrix[(i1, i2)] += 1.0;
}
Confusio... | Rust | 0 |
sc_light::Backend<
sc_client_db::light::LightStorage<TBl>,
HashFor<TBl>
>,
crate::client::LocalCallExecutor<
sc_light::Backend<
sc_client_db::light::LightStorage<TBl>,
HashFor<TBl>
>,
NativeExecutor<TExecDisp>
>,
>;
type TFullParts<TBl, TRtApi, TExecDisp> = (
TFullClient<TBl, TRtApi, TExecDisp>,
... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2024/7/3 9:30
@Author : thezehui@gmail.com
@File : 1.问答转换器示例.py
"""
import dotenv
from doctran import Doctran
from langchain_community.document_transformers import DoctranQATransformer
from langchain_core.documents import Document
_ = Doctran
dotenv.loa... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.