text string | label_name string | labels int64 |
|---|---|---|
from rich.console import Console
from rich.theme import Theme
from typing import List, Union
from asyncio import sleep
import discord
import dotenv
import os
dotenv.load_dotenv()
console_theme = Theme({
"mag": "magenta"
})
console = Console(theme=console_theme)
command_pref = ':'
the_speech = "a ser ya trikt lkhera... | Python | 1 |
TestModel":{"id":1}}}"#
);
assert_query!(
runner,
"query { findFirstTestModel(where: { field: { not: null }}) { id }}",
r#"{"data":{"findFirstTestModel":{"id":1}}}"#
);
assert_query!(
runner,
"query { findFirstTestModel(where:... | Rust | 0 |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
plt.rcParams.update({'legend.fontsize': 9,
'axes.labelsize': 9,
'xtick.labelsize': 8,
'ytick.labelsize': 8})
path = "stochheat"
names = ["stochheat_SV_NN",
... | Python | 1 |
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
ENVIRONMENT: str = "development"
DEBUG: bool = False
POSTGRES_USER: str
POSTGRES_PASSWORD: str
POSTGRES_DB_NAME: str
POSTGRES_HOST: str = "localhost"
POSTGRES_PORT: int = 5432
BOT_TOKEN: str = "... | Python | 1 |
import pytest
import numpy as np
from numpy.testing import assert_allclose, assert_almost_equal
from minimc.autograd_interface import AutogradPotential
from minimc import (
leapfrog,
hamiltonian_monte_carlo,
neg_log_normal,
neg_log_mvnormal,
)
from minimc.integrators import leapfrog_twostage, leapfrog... | Python | 1 |
0] == 0.01
assert src[1]["dist_limit"][0] == 0.01
# If we want smaller distances, no need to re-compute.
dist = _get_distance_matrix(src, dist_lim=0.005)
assert dist.shape == (nuse, nuse)
assert src[0]["dist_limit"][0] == 0.01
# But if we want greater distances, we will need to re-compute.
... | Python | 1 |
");
let a_position = program.attrib_location(b"a_position\0").unwrap() as _;
let a_color = program.attrib_location(b"a_color\0").unwrap() as _;
let u_mvp = program.uniform_location(b"u_mvp\0").unwrap();
Self {
program, u_mvp, a_position, a_color,
}
}
pub fn ... | Rust | 0 |
import csv
from migrations.utils.utils import api_post, drop_indexes_and_constraints
from neo4j_mdr_db.db_schema import build_schema_queries
REGEX_SNAKE_CASE = r"^[a-z]+(_[a-z]+)*$"
REGEX_SNAKE_CASE_WITH_DOT = r"^[a-z.]+(_[a-z.]+)*$"
def migrate_indexes_and_constraints(db_connection, logger):
logger.info("Re-cr... | Python | 1 |
@classmethod
def convert_box(cls, box, height, width):
x_min, y_min = box[0] / width, box[1] / height
w_box, h_box = box[2] / width, box[3] / height
x_max, y_max = x_min + w_box, y_min + h_box
return x_min, y_min, x_max, y_max
| Python | 1 |
= 0
for x, bands_list, group_key in zip(
[landscan, latlon], [LANDSCAN_BANDS, LOCATION_BANDS], ["LS", "location"]
):
if x is not None:
if group_key == "location":
# transform latlon to cartesian
x = cast(torch.Tensor, to_cartesian(x[0], x[1]))
... | Python | 1 |
import ollama
SYSTEM_PROMPT = "You will get a quiz to solve. You will output just the name of the correct option like A, B, C, D, etc. If no option matches the correct answer choose something randomly."
def solve(question, model="llama3"):
answer = ollama.chat(
model=model,
messages=[
... | Python | 1 |
import os
# Path to ffmpeg directory (must contain both ffmpeg and ffprobe)
FFMPEG_PATH = "/opt/homebrew/bin" # Change this path as per your OS
# Output paths
# TEMP_AUDIO_PATH = os.path.join("temp", "audio.wav")
TRANSCRIPT_DIR = os.path.join("data", "transcripts")
TEMP_AUDIO_PATH = os.path.join("temp", "audio")
#... | Python | 1 |
# WARNING: Please don't edit this file. It was generated by Python/WinRT v0.9.210202.1
import typing, winrt
_ns_module = winrt._import_ns_module("Windows.ApplicationModel.Payments.Provider")
try:
import winrt.windows.applicationmodel.payments
except:
pass
try:
import winrt.windows.foundation
except:
... | Python | 1 |
rt_position - 20 == part_cid:
return 1
return 0
# 前指令的单独计算
elif premise_all_value_list[1][0] == "I":
if "Instruct" in premise_all_value_list[1]:
len_pre_behavior = len(cache.pl_pre_behavior_instruce)
behavior_id_str = "_".join(premise_all_value_li... | Python | 1 |
s::vk_to_wrapped(&src.purposes),
description: new_string(&src.description[0] as *const c_char),
layer: new_string(&src.layer[0] as *const c_char),
}
}
}
impl VkSetup for VkPhysicalDeviceToolProperties {
fn vk_setup(&mut self, fn_table: *mut VkFunctionTable) {
}
}
i... | Rust | 0 |
_extent()
#bbax = ax.patch.get_window_extent()
#l1 = bbax1.x1 - bbax1.x0
#l2 = bbax.x1 - bbax.x0
# You can use the ax.transData instance to transform from your data to your display coordinate system,
# either a single point or a sequence of points as shown below:
#print( ax1.transData.transform((left1, bottom1)),
# ... | Python | 1 |
import itertools
l_2d_5 = [[0, 1, 2] for i in range(5)]
print(l_2d_5)
# [[0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]]
%%timeit
list(itertools.chain.from_iterable(l_2d_5))
# 537 ns ± 4.59 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
%%timeit
sum(l_2d_5, [])
# 319 ns ± 1.85 ns per loop (mean ... | Python | 1 |
= self.eols.partition_point(|&eol_idx| eol_idx < idx);
let col_idx = if line_idx == 0 { idx } else { idx - self.eols[line_idx-1] };
(line_idx + 1, col_idx + 1)
}
pub fn idx_to_location(&self, idx: usize) -> Location {
let (line_no, col_no) = self.idx_to_line_col_no(idx);
Locati... | Rust | 0 |
# -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Lic... | Python | 1 |
import os
import tempfile
from mock import Mock, patch
from dusty.systems.nfs import server
from dusty import constants
from ....testcases import DustyTestCase
class TestNFSServer(DustyTestCase):
def setUp(self):
super(TestNFSServer, self).setUp()
def tearDown(self):
super(TestNFSServer, sel... | Python | 1 |
ateTimeField(auto_now_add=True)
is_read = models.BooleanField(default=False)
class Wallet(models.Model):
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
wallet = models.IntegerField(default=0)
def __str__(self):
return f"{self.user.username}'s Wallet: {self.wallet}"
clas... | Python | 1 |
.field("self_mute", &self.self_mute)
.field("self_stream", &self.self_stream)
.field("session_id", &self.session_id)
.field("suppress", &self.suppress)
.field("user_id", &self.user_id)
.finish()
}
}
// From SafariMonkey and jhpratt in https://githu... | Rust | 0 |
if let Some(w) = fst_iter_data.final_weight {
unsafe { ofst.set_final_unchecked(fst_iter_data.state_id, w) };
}
}
}
ofst
}
<reponame>Dr-Electron/identity.rs<filename>bindings/wasm/src/common/utils.rs
// Copyright 2020-2022 <NAME>
// SPDX-License-Identifier: Apache-2.0
use... | Rust | 0 |
match event {
Event::MouseClick { state, button, handled, .. } => {
if !handled {
rotating = *button == MouseButton::Left && *state == State::Pressed;
}
},
Event::MouseMotion { d... | Rust | 0 |
# Copyright (C) 2017-2025 Pier Carlo Chiodi
#
# 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, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distri... | Python | 1 |
) -> Self { *self }
}
impl ::core::default::Default for Struct_acpi_grt_info {
fn default() -> Self { unsafe { ::core::mem::zeroed() } }
}
pub type ACPI_GRT_INFO = Struct_acpi_grt_info;
#[repr(C, packed)]
#[derive(Copy)]
pub struct Struct_acpi_gtm_info {
pub PioSpeed0: UINT32,
pub DmaSpeed0: UINT32,
pub... | Rust | 0 |
# Problem: Longest Nice Substring - https://leetcode.com/problems/longest-nice-substring/
class Solution:
def longestNiceSubstring(self, s: str) -> str:
answer = ""
for i in range(len(s)):
lower = upper = 0
for j in range(i,len(s)):
word = s[i:j+1]
... | Python | 1 |
import torch
import torch.nn as nn
class Autoencoder(nn.Module):
def __init__(self):
super(Autoencoder, self).__init__()
self.encoder = nn.Sequential(
nn.Linear(5, 1024), # Adjusted input size to 5
nn.ReLU(),
nn.Linear(1024, 512),
nn.ReLU(),
... | Python | 1 |
flag = readable.read_u8()?;
Ok(FrameHeaderV3 {
id: id,
size: size,
status_flag: status_flag,
encoding_flag: encoding_flag,
})
}
pub fn write(&self, writable: &mut Cursor<Vec<u8>>, version: u8) -> Result<()> {
let _ = version;
let... | Rust | 0 |
a: typing.MutableMapping[tuple[str, str], spec.DataFrame] = {}
for token_in, token_out in trade_pairs:
mask = (swaps['arg__tokenIn'] == token_in) & (
swaps['arg__tokenOut'] == token_out
)
pair_swaps = swaps[mask]
pair_weights = weights[mask.values]
in_amounts = pa... | Python | 1 |
lt<Option<RamBundleModule>> {
match self.repr {
RamBundleImpl::Indexed(ref indexed) => indexed.get_module(id),
RamBundleImpl::Unbundle(ref file) => file.get_module(id),
}
}
/// Returns the number of modules in the bundle
pub fn module_count(&self) -> usize {
... | Rust | 0 |
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 18)) | (((value as u32) & 0x07) << 18);
self.w
}
}
#[doc = "Field `INT4IS` reader - "]
pub struct INT4IS_R(crate::FieldReader<u8, u8>);
impl INT4IS_R {
pub(crate) fn new(bits: u8) -... | Rust | 0 |
urce.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use prelude::v1::*;
use cell::Cell;
use rt;
use sync::{StaticMutex, Arc};
pub struct Lazy<T> {
lock: StaticMutex,
ptr: Cell<*mut Arc<T>>,
init: fn() -> Arc<T>,
}
unsafe im... | Rust | 0 |
array_201.value().string(item_202.as_str());
}
}
array_201.finish();
}
if let Some(var_203) = &input.max_results {
object.key("MaxResults").number(
#[allow(clippy::useless_conversion)]
aws_smithy_types::Number::NegInt((*var_203).into()... | Rust | 0 |
204, 123, 52, 230, 234, 32, 170, 15, 129, 0, 45, 37, 241,
184, 213, 12, 91, 31, 138, 194,
]);
let part = Participant::<Awaiting>::new(state);
let eligible_update_seed = &[
138, 154, 233, 12, 24, 151, 168, 241, 106, 193, 49, 13, 179, 26, 193, 253, 32, 197, 62,
... | Rust | 0 |
client_socket.sendall("Ingrese contraseña: ".encode("utf-8"))
password = client_socket.recv(1024).decode().strip()
resultado = verificar_credenciales(username, password)
if resultado == "Inicio de sesión exitoso.":
active_sessions[username] = client_socket
... | Python | 1 |
# -*- coding: utf-8 -*-
import pygcb
def CreateDBObject():
dbObj=pygcb.tcAcousticModel()
dbObj.databaseClass='BN215'
dbObj.xSpeed_kts=[0.000000,9.160000,32.060001,45.799999]
dbObj.ySL_dB=[76.199997,80.356842,109.454758,117.768448]
dbObj.speedMinNL_kts=10.640000
dbObj.NL_min=43.520000
dbObj.s... | Python | 1 |
ials_create_from_plugin(
plugin: grpc_metadata_credentials_plugin,
min_security_level: grpc_security_level,
reserved: *mut ::std::os::raw::c_void,
) -> *mut grpc_call_credentials;
}
extern "C" {
#[doc = " Creates a secure channel using the passed-in credentials. Additional"]
#[doc = ... | Rust | 0 |
::Bool(true)),
("false", Value::Bool(false)),
("\"mystr\"", Value::String("mystr".into())),
(
"\"string with spaces\"",
Value::String("string with spaces".into()),
),
("\"äççéñt\"", Value::String("äççéñt".into())),
("\"😂\"", Value::String("😂".into())),
("x <- y <- 0", Value::Int(0)),
("0 -> y ->... | Rust | 0 |
cxcywh_to_xyxy(src_boxes.detach()), box_cxcywh_to_xyxy(target_boxes)))
else:
raise AttributeError()
if loss in ('boxes', ):
meta = {'boxes_weight': iou}
elif loss in ('vfl', 'mal'):
meta = {'values': iou}
else:
meta = {}
return me... | Python | 1 |
ype {
None = 0,
View = 1,
SecCtx = 2,
Thread = 3,
Root = 4,
Device = 5,
Directory = 6,
Data = 7,
Max = 8,
}
const KSO_NAME_MAXLEN: usize = 1024;
#[repr(C)]
#[derive(Debug)]
pub struct KSOAttachment {
pub(crate) id: ObjID,
pub(crate) info: u64,
pub(crate) attype: u32,
pub(crate) flags: u32,
}
#[derive(De... | Rust | 0 |
rams": {}
}
)
for hit_group in res:
print("Results:")
for rank, hit in enumerate(hit_group, start=1):
entity = hit["entity"]
print(
f"Title: {entity.get('title', '')}\t"
f"Rank: {rank} Score: {hit['distance']:}\t"
f... | Python | 1 |
import mujoco
import numpy as np
import open3d as o3d
from gymnasium.envs.mujoco.mujoco_rendering import MujocoRenderer
from scipy.spatial.transform import Rotation
from lift3d.helpers.graphics import HomogeneousCoordinates
def camera_name_to_id(mujoco_model, camera_name):
camera_id = mujoco.mj_name2id(
... | Python | 1 |
import telebot
import json
def get_token():
token = ''
with open('token.jsons') as file:
json_answer = json.load(file)
token = json_answer['config']
return token
TOKEN = get_token()
bot = telebot.TeleBot(TOKEN)
@bot.message_handler(commands=['start'])
def send_start(message):
bot.send... | Python | 1 |
iter, "c:cat", vec![], false);
// c:strRef
&self.string_reference.write_to(writer);
write_end_tag(writer, "c:cat");
}
}
<reponame>museun/blaise
use std::sync::Arc;
use std::io::Write;
use termcolor::{WriteColor, Buffer, BufferWriter, ColorSpec};
pub enum Color {
Black,
Blue,
... | Rust | 0 |
import torch.nn as nn
import torch
class Head(nn.Module):
def __init__(self, nC, stride):
super(Head, self).__init__()
self.__nC = nC
self.__stride = stride
def forward(self, p):
bs, nG = p.shape[0], p.shape[-1]
p = p.view(bs, 4 + self.__nC + 1, nG, nG).permute(0, 2, 3,... | Python | 1 |
pub const CLUSREG_NAME_CLUS_DEFAULT_NETWORK_ROLE: &str = "DefaultNetworkRole";
#[doc = "*Required features: `\"Win32_Networking_Clustering\"`*"]
pub const CLUSREG_NAME_CLUS_DESC: &str = "Description";
#[doc = "*Required features: `\"Win32_Networking_Clustering\"`*"]
pub const CLUSREG_NAME_CLUS_SD: &str = "Security Des... | Rust | 0 |
tern "C" {
pub fn nztific_FreeIdentityContent(ossctx: *mut nzctx, identity: *mut nzttIdentity) -> nzerror;
}
extern "C" {
pub fn nztSign(
arg1: *mut nzctx,
arg2: *mut nzttPersona,
arg3: nzttces,
arg4: ub4,
arg5: *mut ub1,
arg6: *mut nzttBufferBlock,
) -> nzerr... | Rust | 0 |
tr::*;
/// #[refcounted(local)]
/// struct HeapInt { value: i32 }
///
/// let ptr = make_refptr!(HeapInt { value: 10 });
/// ```
#[macro_export]
macro_rules! make_refptr {
($($seg:ident $(::<$($t:ty),*>)?)::+ { $($f:tt)* }) => {
{
let value = $crate::__rt::ManuallyDrop::new($($seg $(::<$($t),*>)... | Rust | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""\
Permutation rank
christoph dürr - 2016-2019
"""
# pylint: disable=line-too-long
def permutation_rank(p):
"""Given a permutation of {0,..,n-1} find its rank according to
lexicographical order
:param p: list of length n containing all integers from 0 ... | Python | 1 |
# pylint: disable=unused-argument, redefined-outer-name, too-many-arguments, line-too-long, too-many-statements
# pytest fixture functions have other fixture functions as arguments,
# which pylint interprets as unused arguments
import pytest
from fastapi.testclient import TestClient
from neomodel import db
from clin... | Python | 1 |
};
/// Extrinsic signer.
pub trait Signer<T: System, S: Encode, E: SignedExtra<T>>
where
<<E as SignedExtra<T>>::Extra as SignedExtension>::AdditionalSigned: Send + Sync,
{
/// Returns the account id.
fn account_id(&self) -> &T::AccountId;
/// Optionally returns a nonce.
fn nonce(&self) -> Option... | Rust | 0 |
ext, spk_id)
# in instruct mode, we remove spk_embedding in llm due to information leakage
del model_input['llm_embedding']
instruct_text_token, instruct_text_token_len = self._extract_text_token(instruct_text + '<endofprompt>')
model_input['prompt_text'] = instruct_text_token
mo... | Python | 1 |
# Other tests can not work on the abstract base.
if self.protocol.__class__ == Protocol:
return
self.doConnect()
self.assertEqual('unknown', self.protocol.guess_os())
self.protocol.login(self.account)
self.assertTrue(self.protocol.is_protocol_authenticated())
... | Python | 1 |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# File : test-utils-debug.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 09/11/2019
#
# This file is part of Jacinle.
# Distributed under terms of the MIT license.
from jacinle.utils.debug import decorate_exception_hook
@decorate_exception_hook
... | Python | 1 |
nt=("Segoe UI", 16, "bold"), text_color="white").pack(anchor="w", padx=10, pady=5)
CTkLabel(display_frame, text=year, font=("Segoe UI", 16), text_color="white").pack(anchor="w", padx=10)
CTkLabel(display_frame, text="Instructor Name:", font=("Segoe UI", 16, "bold"), text_color="white").pack(anchor="w",... | Python | 1 |
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Generic, TypeVar
from jaxtyping import Float
from torch import Tensor
from spatialreasoners.denoising_model.flow import Flow
@dataclass
class LossCfg:
weight: float | int = 1
apply_after_step: int = 0
T = TypeVar("T",... | Python | 1 |
sarus_std_lib::append_std_funcs(ast);
jit.translate(ast.clone())?;
let func_ptr = jit.get_func("main")?;
let func = unsafe { mem::transmute::<_, extern "C" fn(f64, f64) -> f64>(func_ptr) };
assert_eq!(2048.0, func(a, b));
Ok(())
}
#[test]
fn int_to_float() -> anyhow::Result<()> {
let code = r#... | Rust | 0 |
var".to_owned()), env.get_write_style());
}
#[test]
fn env_get_write_style_reads_from_default_if_var_not_set() {
env::remove_var("env_get_write_style_reads_from_default_if_var_not_set");
let env = Env::new().write_style_or("env_get_write_style_reads_from_default_if_var_not_set", "from def... | Rust | 0 |
row["status_code"] < 300 else "failure"
record = {
"timestamp": row["timestamp"].isoformat(),
"key": row["key"],
"model": row["model"],
"status": status,
"status_code": row["status_code"],
... | Python | 1 |
stream(&mut plaintext)
.map_err(|_| operation_error("tried to decrypt too much data"))?;
Ok(plaintext)
}
fn decrypt_aes_gcm_gen<B>(
key: &[u8],
tag: &GenericArray<u8, <B as AeadCore>::TagSize>,
nonce: &GenericArray<u8, <B as AeadCore>::NonceSize>,
additional_data: Vec<u8>,
plaintext: &mut [u8],
) -> R... | Rust | 0 |
(error) = device.detach().await {
return Err(failure!(
Code::Internal,
"Failed to unstage volume {}: failed to detach device {}: {}",
volume_id,
device_path,
error
... | Rust | 0 |
= 0x02000000; /* Gen Purpose Interrupt on SDP1 */
pub const IXGBE_EICR_GPI_SDP2: u32 = 0x04000000; /* Gen Purpose Interrupt on SDP2 */
pub const IXGBE_EICR_ECC: u32 = 0x10000000; /* ECC Error */
pub const IXGBE_EICR_GPI_SDP0_X540: u32 ... | Rust | 0 |
assert!(!rate_limiter.try_acquire(), "Must not grant a permit");
assert!(rate_limiter.try_acquire(), "Must grant a permit");
}
#[test]
fn test_twice_per_minute() {
let rate_limiter =
UltraLightRateLimiter::new(2. / 60 as f64, get_ticker(vec![0, 30_000, 50_000, 60_000]));
... | Rust | 0 |
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
file_path = '/mnt/data/Financial Analytics data.csv'
data = pd.read_csv(file_path)
print("First few rows of the dataset:")
print(data.head())
print("\nBasic information about the dataset:")
print(data.info())
print("\nSummary statistics of the... | Python | 1 |
.')
cmc, mAP = metrics.evaluate_rank(
distmat,
q_pids,
g_pids,
q_camids,
g_camids,
use_metric_cuhk03=use_metric_cuhk03
)
print('** Results **')
print('mAP: {:.1%}'.format(mAP))
print('CMC curve')
fo... | Python | 1 |
definite, val),
};
Ok(val)
}
}
impl SimpleValue {
pub fn to_type_order(&self) -> usize {
use SimpleValue::*;
match self {
Unassigned => 4,
True => 8,
False => 12,
Null => 16,
Undefined => 20,
Reserved24(_)... | Rust | 0 |
get").join("aarch64-apple-ios").join("debug").join("libSDL2.a")).expect("Cannot copy libSDL2 for iPhone OS");
fs::copy(Path::new(¤t_dir).join(SDL2_PATH).join("Xcode-iOS").join("SDL").join("build").join("Release-iphonesimulator").join("libSDL2.a"), Path::new(¤t_dir).join("target").join("x86_64-apple-... | Rust | 0 |
f the example returned
:param seed: the seed for random generator
:return: a tensor for the adversarial example
"""
with tf.name_scope(scope, "virtual_adversarial_perturbation"):
d = tf.random_normal(tf.shape(x), dtype=tf_dtype)
for _ in range(num_iterations):
d = xi * utils_... | Python | 1 |
let NonNull { inner, marker } = data;
let inner = std::ptr::NonNull::slice_from_raw_parts(inner, len);
Self { inner, marker }
}
}
<filename>jinshu-database/src/model/block.rs
//! SeaORM Entity. Generated by sea-orm-codegen 0.7.0
use sea_orm::entity::prelude::*;
use serde::{Deserialize, Serialize};... | Rust | 0 |
let ret1 = get_time_from_code(wrong1);
let ret2 = get_time_from_code(wrong2);
assert_eq!(time, 114514);
assert!(ret1.is_err());
assert!(ret2.is_err());
}
}
<gh_stars>1-10
use http::HeaderValue;
use serde::Deserialize;
use serde::Deserializer;
use std::ops::Deref;
pub(super)... | Rust | 0 |
::c_int,
}
#[test]
fn bindgen_test_layout_CollateClause() {
assert_eq!(
::std::mem::size_of::<CollateClause>(),
32usize,
concat!("Size of: ", stringify!(CollateClause))
);
assert_eq!(
::std::mem::align_of::<CollateClause>(),
8usize,
concat!("Alignment of ", st... | Rust | 0 |
to check ce certif/pfx
## Read certificate info (.cer)
### openssl x509 -inform der -in {certif} -text -noout
## Read pfx info (ask to another password to encrypt Private key before print/export)
### openssl pkcs12 -info -in {pfx} -nokeys
## Read pfx info !!!! PRINT PRIVATE KEY !!!!
### openssl pkcs12 -info -in {pfx... | Python | 1 |
# Copyright (c) 2025 Intel Corporation
# 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 agreed to in writ... | Python | 1 |
import argparse
import asyncio
import json
import os
from typing import Dict
import aiohttp
from pydantic import BaseModel, ValidationError
class Response(BaseModel):
result: str
error: str
stdout: str
class HumanPrompt(BaseModel):
prompt: str
def parse_args():
parser = argparse.ArgumentParse... | Python | 1 |
#Realizar un programa que pida al usuario que ingrese varios números y
# que devuelva la suma del cuadrado de esos números
#num = int(input('Digite um número (para finalizar digite 0): '))
soma = 0
cont = 0
while True:
num = int(input('Digite um número (para finalizar digite 0): '))
cont += 1
quad = num *... | Python | 1 |
import json
import yaml
import pandas as pd
from pathlib import Path
from typing import Dict, Any, Union
from django.core.files.uploadedfile import UploadedFile
def load_rules_from_file(file_or_path: Union[str, UploadedFile, Path]) -> Dict[str, Any]:
if isinstance(file_or_path, (str, Path)):
p = Path(str(... | Python | 1 |
n-bd" style="height: 379px;">
<div class="mui-mbar-plugin-load"></div>
</div>
</div>
</div>
<div class="mui-mbar-tabs mui-mbar-tabs-shadow" style="height: 414px; left: 0px;">
<div class="mui-mbar-tab-bubble mui-mbar-tab-bubble-prof" style="top: 82px;">
<div class="mui-mbar-tab-bubble-bd"></div>
</div>
<div class="mui-m... | Python | 1 |
box):
enhancement_decision = random.randint(1, 2)
if enhancement_decision == 1:
crop_x = random.randint(-10, 10)
crop_y = random.randint(-10, 10)
img = crop_and_pad_image(img, [crop_x, crop_y])
bbox = crop_boxes(bbox, [crop_x, crop_y])
elif enhancement_decision == 2:
... | Python | 1 |
Target = crate::W<EF_IF_CFG_0_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl core::convert::From<crate::W<EF_IF_CFG_0_SPEC>> for W {
... | Rust | 0 |
a total of 32 bytes, repeating the sequence twice.
/// #
/// # Ok(()) }
/// ```
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Display, LowerHex, UpperHex)]
pub struct Offset(pub u16);
/// The number of chunks sent in [`SendData`](Message::SendData) messages, reported by [`DataChunksSent`](Message::DataChunksSent)... | Rust | 0 |
# Copyright (c) 2024, Nirali and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class GemstoneMultiplier(Document):
pass
| Python | 1 |
import prince
import pandas as pd
import matplotlib.pyplot as plt
# --- Step 1: Load the Dataset ---
url = "https://raw.githubusercontent.com/vincentarelbundock/Rdatasets/master/csv/datasets/USArrests.csv"
df = pd.read_csv(url, index_col=0)
# --- Step 2: Perform Correspondence Analysis ---
ca = prince.CA(
n_comp... | Python | 1 |
(0, 0)),
("Ac", (0, 0)),
("rfisht", (0, 0)),
("ExponentialE", (0, 0)),
("kjcy", (0, 0)),
("nrar", (0, 0)),
("ratail", (0, 0)),
("lurdsh", (0, 0)),
("ccedil;", (231, 0)),
("zwn", (0, 0)),
("UnderBar", (0, 0)),
("strns", (0, 0)),
... | Rust | 0 |
from abc import ABC, abstractmethod
from dataclasses import dataclass
from domain.entities.library import Book
@dataclass
class BaseBookRepository(ABC):
@abstractmethod
async def add(self, book: Book) -> Book: ...
@abstractmethod
async def get_by_id(self, book_id: int) -> Book | None: ...
@abst... | Python | 1 |
rng, _rng = jax.random.split(rng)
runner_state = (
(actor_train_state, critic_train_state),
env_state,
obsv,
jnp.zeros((config["NUM_ACTORS"]), dtype=bool),
(ac_init_hstate, cr_init_hstate),
_rng,
)
runner_state, metric = jax... | Python | 1 |
idx, = np.where( (x_chunk >= xmin-buff) & (x_chunk <= xmax+buff) &
(y_chunk >= ymin-buff) & (y_chunk <= ymax+buff) )
# Leave chunk if outside tile
if len(idx) == 0: continue
# Get chunk of data in-memory, and
# Query chunk in-memory
points_chu... | Python | 1 |
blend_mode: BlendMode) -> vk::PipelineColorBlendAttachmentState {
match blend_mode {
BlendMode::AlphaBlend => vk::PipelineColorBlendAttachmentState {
blend_enable: vk::TRUE,
src_color_blend_factor: vk::BlendFactor::SRC_ALPHA,
dst_color_blend_factor: vk::BlendFactor::ONE_M... | Rust | 0 |
3,
AttentionSignal = 6,
BulkLoadData = 7,
FederatedAuthToken = 8,
TransactionManagerRequest = 14,
Tds7Login = 16,
Sspi = 17,
TabularResult = 4,
}
impl PacketType {
pub fn get(value: u8) -> Result<Self, Error> {
Ok(match value {
1 => PacketType::SqlBatch,
... | Rust | 0 |
std::sync::Arc;
/// Owned RAII structure used to release the exclusive write access of a lock when
/// dropped.
///
/// This structure is created by [mapping] an [`OwnedRwLockWriteGuard`]. It is a
/// separate type from `OwnedRwLockWriteGuard` to disallow downgrading a mapped
/// guard, since doing so can cause undef... | Rust | 0 |
coco_labels with sets=val2014
"""
from pycocotools.coco import COCO
opt = MapConfig(_config)
if sets not in ['train2014', 'val2014']:
raise ValueError(f'Not supported sets: {sets}. [train2014, val2014]')
save_dir = DATA_DIR['COCO'] / f'{sets}_label'
annFile = DATA_DIR['COCO'] / f'annot... | Python | 1 |
let href = match community {
Some(c) => format!("/community_node/{}/{}", c, n.slug),
None => format!("/node/{}", n.slug),
};
let node = GNode {
id: format!("{}", &n.node_name),
node_type: String::from("Node"),
text: vec![n.domain_token.to_owne... | Rust | 0 |
&'a mut W {
self.w.bits = value as u32;
self.w
}
}
impl R {
#[doc = "Bits 0:31 - RAMFIFO0 Address: ARM firmware/software Access these registers to Read/Write the RAMFIFO0. From 0x8000 to 0x8FFC."]
#[inline(always)]
pub fn ramfifo0(&self) -> RAMFIFO0_R {
RAMFIFO0_R::new(self.bits... | Rust | 0 |
"""
Tailwind UI Components code snippets RAG
""" | Python | 1 |
en(train_loader), 2)
def test():
model.eval()
test_loss = 0
test_acc = 0
for data, target in test_loader:
if args.cuda:
data, target = data.cuda(), target.cuda()
data, target = Variable(data, volatile=True), Variable(target)
output = model(data)
test_loss += ... | Python | 1 |
: DWORD = 0x4;
pub const fPCD_MEM2_A: DWORD = 0x8;
pub const fPCD_IO_ZW_8: DWORD = 0x10;
pub const fPCD_IO_SRC_16: DWORD = 0x20;
pub const fPCD_IO_WS_16: DWORD = 0x40;
pub const mPCD_MEM_WS: DWORD = 0x300;
pub const fPCD_MEM_WS_ONE: DWORD = 0x100;
pub const fPCD_MEM_WS_TWO: DWORD = 0x200;
pub const fPCD_MEM_WS_THREE: D... | Rust | 0 |
他'} # 目标字符集
with open(vocab_path, "r", encoding="utf8") as f:
vocab = json.load(f) # 加载字符表
model = build_model(vocab, char_dim, sentence_length)
model.load_state_dict(torch.load(model_path))
model.eval()
predictions = []
for input_string in input_strings:
x = [vocab[char] fo... | Python | 1 |
vatedEventArgs = _ns_module.IProtocolForResultsActivatedEventArgs
IRestrictedLaunchActivatedEventArgs = _ns_module.IRestrictedLaunchActivatedEventArgs
ISearchActivatedEventArgs = _ns_module.ISearchActivatedEventArgs
ISearchActivatedEventArgsWithLinguisticDetails = _ns_module.ISearchActivatedEventArgsWithLinguisticDetai... | Python | 1 |
rs2_extension = 40;
pub const rs2_extension_RS2_EXTENSION_AUTO_CALIBRATED_DEVICE: rs2_extension = 41;
pub const rs2_extension_RS2_EXTENSION_COLOR_SENSOR: rs2_extension = 42;
pub const rs2_extension_RS2_EXTENSION_MOTION_SENSOR: rs2_extension = 43;
pub const rs2_extension_RS2_EXTENSION_FISHEYE_SENSOR: rs2_extension = 44... | Rust | 0 |
import torch
def get_tokenizer(args):
from transformers import AutoTokenizer
if args.dataset == 'rxr' or args.tokenizer == 'xlm':
cfg_name = 'bert_config/xlm-roberta-base'
else:
cfg_name = 'bert_config/bert-base-uncased'
tokenizer = AutoTokenizer.from_pretrained(cfg_name)
return to... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.