text string | label_name string | labels int64 |
|---|---|---|
unsafe {
&(*(::std::ptr::null::<ibv_qp_init_attr_ex>())).send_ops_flags as *const _ as usize
},
128usize,
concat!(
"Offset of field: ",
stringify!(ibv_qp_init_attr_ex),
"::",
stringify!(send_ops_flags)
)
);
}
impl ib... | Rust | 0 |
,
&(entry.generation as i64),
&entry.uid,
],
)
.await?;
log::debug!("Rows deleted: {}", num);
Ok(num > 0)
}
async fn fetch_unread(
&self,
duration: Duration,
) -> Result<Pin<Box<dyn Stream<Item... | Rust | 0 |
"""
Vertex AI Gemini API の基本的な使い方
"""
import os
import sys
import vertexai
from dotenv import load_dotenv
from rich.console import Console
from rich.panel import Panel
from vertexai.generative_models import GenerativeModel
# 環境変数を読み込み
load_dotenv()
# きれいな出力のためのコンソール
console = Console()
def main():
"""メイン処理"""... | Python | 1 |
import pytest
import requests
import allure
@allure.title("Token - Generate Token")
@allure.description("Create new Token")
@pytest.fixture
def create_token():
base_url="https://restful-booker.herokuapp.com"
path_url="/auth"
token_url=base_url+path_url
headers={"content-tpyt":"application/json"}
p... | Python | 1 |
# key : from (n, c2, h2, w2) to (n, key_channels, h2*w2)
key = self.f_object(proxy)
key = paddle.reshape(key, (n, self.key_channels, -1))
# value : from (n, c2, h2, w2) to (n, h2*w2, key_channels)
value = self.f_down(proxy)
value = paddle.reshape(value, (n, self.key_chan... | Python | 1 |
# simulated_data.py
import itertools
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
if __name__ == "__main__":
np.random.seed(1)
# Set the number of samples, the means and
# variances of each of the three simulated clusters
samples = 100
mu = [(7, 5), (8,... | Python | 1 |
r node"
)
parser.add_argument(
"-n", "--num-nodes",
type=int,
default=1,
help="Number of nodes"
)
parser.add_argument(
"--parallel",
action="store_true",
help="Run seeds in parallel"
)
parser.add_argument(
"--max-work... | Python | 1 |
# Copyright (c) 2021 - present / Neuralmagic, Inc. 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 required b... | Python | 1 |
dd_cipher(&self, c1: &Mpz, c2: &Mpz) -> Mpz {
(c1 * c2) % &self.pk.n2
}
pub fn add_const(&self, c: &Mpz, m: &Mpz) -> Mpz {
self.add_cipher(c, &self.pk.g.powm(&m, &self.pk.n2))
}
pub fn mul_const(&self, c: &Mpz, m: &Mpz) -> Mpz {
c.powm(&m, &self.pk.n2)
}
}
<gh_stars>100-100... | Rust | 0 |
{
acc.push(' ');
index = 1;
}
acc.push(x);
acc
})
}
pub fn decode(message: &str) -> String {
message
.chars()
.filter_map(|c| match c {
_ if c.is_ascii_digit() => Some(c),
_ if c.is_ascii_lowercase... | Rust | 0 |
[test]
#[cfg(feature = "std")]
fn from_str() {
// Another simple test. `DnameBuilder` does all the heavy lifting,
// so we don’t need to test all the escape sequence shenanigans here.
// Just check that we’ll always get a name, final dot or not, unless
// the string is empty.
... | Rust | 0 |
stm32_mcu = "stm32f413",
stm32_mcu = "stm32f427",
stm32_mcu = "stm32f429",
stm32_mcu = "stm32f469",
))]
map_uart! {
"Extracts UART7 register tokens.",
periph_uart7,
"UART7 peripheral variant.",
Uart7,
APB1ENR,
APB1RSTR,
APB1LPENR,
UART7EN,
UART7RST,
UART7LPEN,
... | Rust | 0 |
from_json<S: AsRef<str>>(json: S) -> RTDResult<Self> {
Ok(serde_json::from_str(json.as_ref())?)
}
pub fn builder() -> RTDToggleMessageSenderIsBlockedBuilder {
let mut inner = ToggleMessageSenderIsBlocked::default();
inner.extra = Some(Uuid::new_v4().to_string());
inner.td_type ... | Rust | 0 |
import random
import os
import time
import json
"""
Copyright (c) 2024 Aakidul. All rights reserved.
This code is the original work of Aakidul and may not be copied,
modified, or redistributed without permission.
Unauthorized use, including the creation of derivative works or other games based on this code, is stric... | Python | 1 |
ivationPath::from_str("m/44'/0'/0'/1/42")?), &ctx), Some(bip32::DerivationPath::from_str("m/44'/0'/0'/1")?));
/// assert_eq!(xpub.matches(&(bip32::Fingerprint::from_str("ffffffff")?, bip32::DerivationPath::from_str("m/44'/0'/0'/1/42")?), &ctx), None);
/// assert_eq!(xpub.matches(&(bip32::Fingerprint::from_str("... | Rust | 0 |
async def _send_message(self, chat_id: int, text: str):
"""Send a message to Telegram"""
if not self.http_client:
logger.error("HTTP client not initialized")
return
url = f"{TelegramPollingService.API_BASE_URL}/bot{self.bot_token}/sendMessage"
await self.http_cli... | Python | 1 |
SE: Tag = Tag::new_unchecked('V' as u8);
pub const NEGOTIATE_PROTOCOL_VERSION: Tag = Tag::new_unchecked('v' as u8);
pub const NO_DATA: Tag = Tag::new_unchecked('n' as u8);
pub const PARAMETER_DESCRIPTION: Tag = Tag::new_unchecked('t' as u8);
pub const PARSE_COMPLETE: Tag = Tag::new_unchecked('1' as u8);... | Rust | 0 |
# -*- coding: utf-8 -*-
import scrapy
from scrapy import Request
import re
import urllib.parse
from items import TripadvisorItem
class CommentSpider(scrapy.Spider):
name = 'comment'
headers = {
'Accept': 'text/html, */*',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'en-... | Python | 1 |
tlere_hautfarbe:',
'es': ':hombres_de_la_mano_tono_de_piel_oscuro_y_tono_de_piel_medio:',
'fr': ':deux_hommes_se_tenant_la_main_peau_foncée_et_peau_légèrement_mate:',
'ja': ':手をつなぐ男性_濃い肌色_中間の肌色:',
'ko': ':손을_잡고_있는_두_명의_남자_검은색_피부_갈색_피부:',
'pt': ':dois_homens_de_mãos_dadas_pele_esc... | Python | 1 |
println!("getting {} bytes starting at {}", length, start);
let (mut data, _) = bucket
// -1 because ranges are inclusive in `get_object_range`
.get_object_range(&path, start, Some(start + length as u64 - 1))
.await
.map_err(|x| std... | Rust | 0 |
import bpy, os
from pytest import approx
from .. import dynamic_import
from .. import ObjectService
from .. import NodeService
from .. import LocationService
MhMaterial = dynamic_import("mpfb.entities.material.mhmaterial", "MhMaterial")
NodeWrapperGameEngine = dynamic_import("mpfb.entities.nodemodel.v2.materials.nodewr... | Python | 1 |
shers (if they exist) when reservation is canceled or expired
if not self.is_active and not is_new:
self.book.notify_wishers()
class Meta:
verbose_name = _('Reservation')
verbose_name_plural = _('Reservations')
def __str__(self):
return f'{self.user.email} reserved ... | Python | 1 |
Security_Authentication_Identity\"`*"]
pub const KERB_TICKET_FLAGS_enc_pa_rep: u32 = 65536u32;
#[doc = "*Required features: `\"Win32_Security_Authentication_Identity\"`*"]
pub const KERB_TICKET_FLAGS_name_canonicalize: u32 = 65536u32;
#[repr(C)]
#[doc = "*Required features: `\"Win32_Security_Authentication_Identity\"`*... | Rust | 0 |
up 3: literal (e.g. amp, gt, ...) (maybe)
*/
static ref HTML_ENTITIES_REGEX: Regex = Regex::new(r"&(#([0-9]+))?([a-z]+)?;").unwrap();
static ref REPEATED_NEWLINES_REGEX: Regex = Regex::new(r"(\r?\n|\r)\d*(\r?\n|\r)").unwrap();
}
/// ### elide_string_at
///
/// Elide string at `len` and append `
pub fn eli... | Rust | 0 |
import FWCore.ParameterSet.Config as cms
process = cms.Process("TEST")
process.maxEvents.input = 3
process.source = cms.Source("EmptySource",
firstLuminosityBlockForEachRun = cms.untracked.VLuminosityBlockID(
cms.LuminosityBlockID(10,1),
... | Python | 1 |
fn render_scene(
camera: &Camera,
instances: &[ModelInstance],
lights: &[Light],
canvas: &mut Canvas,
depth_buffer: &mut DepthBuffer,
user_choices: &UserChoices,
) {
let camera_matrix = camera.orientation
.transpose()
.multiply_matrix4x4(&Matrix4x4::new_translation_matrix_fr... | Rust | 0 |
words = [input() for _ in range(2)]
dict_1 = {k: words[0].count(k) for k in set(words[0])}
dict_2 = {k: words[1].count(k) for k in set(words[1])}
print(result := 'YES' if dict_1 == dict_2 else 'NO')
| Python | 1 |
# prompt_manager/storage/base.py
from abc import ABC, abstractmethod
from pathlib import Path
from typing import List, Dict
from ..types import PromptVersion
class StorageBackend(ABC):
def __init__(self, root_path: str | Path):
self.root_path = Path(root_path).expanduser()
# ---------- project ------... | Python | 1 |
import pygame as pg
class HealthBar:
def __init__(self, x, y, width, height, max_health):
self.rect = pg.Rect(x, y, width, height)
self.max_health = max_health
self.current_health = 0
def update(self, current_health):
self.current_health = current_health
def draw(self, surf... | Python | 1 |
d_embs.extend(sampled_embs)
all_sampled_embs = np.stack(all_sampled_embs).astype(np.float32)
print ("Training index...")
start_time = time.time()
self._train_index(all_sampled_embs, self.trained_index_path)
print ("Finish training (%ds)" % (time.time()-start_time))
... | Python | 1 |
s().unwrap(), "+0:00:00.300000000");
}
#[test]
fn test_pravega_timestamp_extreme() {
// Limit from chrono-0.4.19/src/naive/datetime.rs:351
let s1 = "2262-04-11T23:47:16.854775804Z";
let pt1 = PravegaTimestamp::try_from(Some(s1)).unwrap();
println!("s1 ={}", s1);
prin... | Rust | 0 |
it(&format!("{}.kalem", codegen.kalem_source_files[i]).to_string());
temp_codegen = read_source(data);
if temp_codegen.kalem_library {
temp_codegen.kalem_generated.push_str(format!("\n#{}", append_codegen::_CPP_ENDIF).as_str());
}
if Path::new(format!("{}.hpp", codegen.kal... | Rust | 0 |
1])
b = int(list_color[2])
self.flashing[dict_payload["led_number"]]["color"] = r << 16 | g << 8 | b # Each 0 - 255
self.timer_flash = time.time() + self.led_flash_period_sec
self.flashing[dict_payload["led_number"]]["enabled"] = True
def flashing_off(self, dict_payload):
... | Python | 1 |
# Decode topic and split off the prefix
topic = message.topic.replace(self.config['mqtt']['prefix'], '').split('/')[1:]
action = message.payload.decode()
LOGGER.info("Command received: %s (%s)" % (topic, message.payload))
if topic[0] == 'cec':
if topic[1] == 'powe... | Python | 1 |
]
extern crate steam_language_gen_derive;
use downcast_rs::{impl_downcast, Downcast};
use enum_dispatch::enum_dispatch;
use serde::Serialize;
use crate::generated::headers::{ExtendedMessageHeader, StandardMessageHeader};
use steam_protobuf::steam::steammessages_base::CMsgProtoBufHeader;
use steam_protobuf::Message;
... | Rust | 0 |
print("""
██▓ ██▓███ █████▒██▓ ███▄ █ ▓█████▄ ▓█████ ██▀███
▓██▒▓██░ ██▒ ▓██ ▒▓██▒ ██ ▀█ █ ▒██▀ ██▌▓█ ▀ ▓██ ▒ ██▒
▒██▒▓██░ ██▓▒ ▒████ ░▒██▒▓██ ▀█ ██▒░██ █▌▒███ ▓██ ░▄█ ▒
░██░▒██▄█▓▒ ▒ ░▓█▒ ░░██░▓██▒ ▐▌██▒░▓█▄ ▌▒▓█ ▄ ▒██▀▀█▄
░██░▒██▒ ░ ░ ░▒█░ ░██░▒██░ ▓██░░▒████▓ ░▒████▒░██▓ ... | Python | 1 |
Sized
{
JoinIter::new(self)
}
/// Open this join by returning the mask and the storages.
fn open(self) -> (Self::Mask, Self::Value);
/// Get a joined component value by a given index.
unsafe fn get(&mut Self::Value, Index) -> Self::Type;
}
/// `JoinIter` is an Iterator over a group ... | Rust | 0 |
#[test]
fn unlinked_key_chown() {
let mut keyring = utils::new_test_keyring();
let payload = "payload".as_bytes();
let mut key = keyring
.add_key::<User, _, _>("unlinked_key_chown", payload)
.unwrap();
keyring.unlink_key(&key).unwrap();
utils::wait_for_key_gc(&key);
let err =... | Rust | 0 |
cm_fig = px.imshow(cm, text_auto=True, color_continuous_scale="Blues",
title="Confusion Matrix", labels={"x": "Predicted", "y": "Actual"})
st.plotly_chart(cm_fig)
except Exception as e:
st.error(f"Terjadi error: {e... | Python | 1 |
}
pub fn keyval (key :&str, val :&str, ck : Rgb, cv : Rgb) -> Cow<'static, str> {
format!("{} {}", ck.fg(&format!("{} :", key)), cv.fg(val)).into()
}
pub fn description(description :&str) {
println!(" {}", CTEXT.fg(description));
}
pub fn usage() {
let space_arg : usize = 11;
let arg1 : &str = "SEAR... | Rust | 0 |
s['filter']
for i in _filter:
if i == 'search':
_x = _filter[i].strip()
if len(_x) == 0:
tmp.append(i)
continue
for i in tmp:
del _filter[i]
sql_filter.update(_filter... | Python | 1 |
import string
import random
import array
# import tkinter
# from tkinter import *
# What this Program does!!!!
# This is an Random password generated program....
# alpha = ["a" ,"b", "c", "d", "e" "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
# nums = [1, 2,... | Python | 1 |
p(|f| f.average_chain_len_pair).sum();
pick_random_follower_with_sum(followers, avg_sum, rng)
}
fn update_follower_averages(
followers: &mut Vec<Vec<Follower>>,
chain: &Vec<u8>,
new_sample: f32) {
for pair in chain.windows(2) {
if let &[a, b] = pair {
let a_follower = follow... | Rust | 0 |
memsz: u64,
pub align: u64,
}
impl ProgramHeader {
pub const fn new() -> ProgramHeader {
ProgramHeader {
types: 0,
flags: 0,
off: 0,
vaddr: 0,
paddr: 0,
filesz: 0,
memsz: 0,
align: 0,
}
}
}
// V... | Rust | 0 |
SLanguage;
}
extern "C" {
#[doc = " Edit the syntax tree to keep it in sync with source code that has been"]
#[doc = " edited."]
#[doc = ""]
#[doc = " You must describe the edit both in terms of byte offsets and in terms of"]
#[doc = " (row, column) coordinates."]
pub fn ts_tree_edit(self_: *mut... | Rust | 0 |
import tiktoken
from langchain_core.tools import tool
from openai import OpenAI
from ..utils.rag_memory import rag_memory
from ..configuracoes.config import API_KEY, TOKENIZER_ENCODING, DEFAULT_TOP_K, DEFAULT_SIMILARITY_THRESHOLD
client = OpenAI(api_key=API_KEY)
tokenizador = tiktoken.get_encoding(TOKENIZER_ENCODING)
... | Python | 1 |
help='produce more log messages(debug log)')
args = parser.parse_args()
# globals
GlobalConfig.qtpath = os.path.normpath(args.qtpath)
GlobalConfig.exepath = args.exepath
GlobalConfig.logger = logging.getLogger()
# configure logging
###################
# create formatter
fo... | Python | 1 |
ialOrd, Ord, Hash)]
struct Obj(usize);
impl ObjectID for Obj {}
pub struct BrowseNeighborhoods {
panel: Panel,
neighborhoods: BTreeMap<Obj, Block>,
world: World<Obj>,
labels: DrawRoadLabels,
}
impl BrowseNeighborhoods {
pub fn new_state(ctx: &mut EventCtx, app: &App) -> Box<dyn State<App>> {
... | Rust | 0 |
ITAL_PAD` writer - "]
pub struct TO_DIGITAL_PAD_W<'a> {
w: &'a mut W,
}
impl<'a> TO_DIGITAL_PAD_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) ... | Rust | 0 |
fn default() -> Self { unsafe { ::core::mem::zeroed() } }
}
pub type ACPI_TABLE_TCPA_HDR = Struct_acpi_table_tcpa_hdr;
#[repr(C, packed)]
#[derive(Copy)]
pub struct Struct_acpi_table_tcpa_client {
pub MinimumLogLength: UINT32,
pub LogAddress: UINT64,
}
impl ::core::clone::Clone for Struct_acpi_table_tcpa_client... | Rust | 0 |
.read_to_end(&mut buf).unwrap();
let data_len = buf.len();
let mut index_reader =
TSMIndexReader::try_new(BufReader::new(Cursor::new(&buf)), data_len).unwrap();
let mut blocks = Vec::new();
for res in &mut index_reader {
let entry = res.unwrap();
let... | Rust | 0 |
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def count_valid_sequences(root: TreeNode) -> int:
"""
Returns the number of valid node value sequences in a binary search tree.
"""
def traverse(node: TreeNod... | Python | 1 |
(*p_j2k).m_specific_param.m_decoder.m_header_data,
2 as libc::c_int as OPJ_SIZE_T,
p_manager,
) != 2 as libc::c_int as libc::c_ulong
{
opj_event_msg(
p_manager,
1 as libc::c_int,
b"Stream too short\n\x00" as *const u8 as *const libc::c_char,
);
return 0 ... | Rust | 0 |
import os
import time
import random
import numpy as np
import torch
import torch.nn as nn
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data.distributed import DistributedSampler
from tensorboardX import SummaryWriter
from validate import validate
from d... | Python | 1 |
patch.make_nop(locals_use.first_use.unwrap());
}
patch.make_nop(candidate);
let size = opt_size.unwrap() as u32;
patch.add_assign(candidate,
dst_place.clone(),
Rvalue::Use(
... | Rust | 0 |
turn
confirm = input("Επιβεβαιώνετε τη δωρεά; (ν/ο): ")
if confirm.lower() != 'ν':
print("Η δωρεά ακυρώθηκε.")
return
if target_type == "action":
donation = Donation(amount, datetime.now(), payment_system.get_name(), user, action=selected)
else:
donation = Donation(amou... | Python | 1 |
@TemplateId.setter
def TemplateId(self, TemplateId):
self._TemplateId = TemplateId
def _deserialize(self, params):
self._TemplateId = params.get("TemplateId")
memeber_set = set(params.keys())
for name, value in vars(self).items():
property_name = name[1:]
... | Python | 1 |
# coding=utf-8
# Copyright 2021 The HuggingFace Inc. team. 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 r... | Python | 1 |
et('impropers',[]))
))
print("Output written to: {}".format(output_path))
except Exception as e:
print("Error during MD data modification: {}".format(e))
traceback.print_exc()
finally:
print("="*70)
input("Process complete. Press Enter to close this window...")
... | Python | 1 |
__version__ = "2.18.2"
| Python | 1 |
note_id: T::NoteIndex) -> DispatchResult {
let sender = ensure_signed(origin)?;
Notes::<T>::try_mutate_exists(sender.clone(), note_id, |note| -> DispatchResult {
// Test the user owns this note
let _n = note.take().ok_or(Error::<T>::InvalidNoteId)?;
... | Rust | 0 |
Some(Model {
vertices: modified_vertices,
triangles: triangles.to_vec(),
bounds_center: transformed_center,
bounds_radius: model.bounds_radius,
})
}
/// Renders the `Model` passed by iterating through the list of triangles and vertices
/// that it contains, using the `transform`... | Rust | 0 |
},
"zh": {
"label": "LoRA 秩",
"info": "LoRA 矩阵的秩大小。",
},
"ko": {
"label": "LoRA 랭크",
"info": "LoRA 행렬의 랭크.",
},
},
"lora_alpha": {
"en": {
"label": "LoRA alpha",
"info": "Lora scaling coefficient.",
... | Python | 1 |
# coding=utf-8
import requests
from core import printmodels
r = '\033[31m'
g = '\033[32m'
y = '\033[33m'
b = '\033[34m'
m = '\033[35m'
c = '\033[36m'
w = '\033[37m'
Headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:28.0) Gecko/20100101 Firefox/28.0'}
Jce_Deface_image = 'files/pwn.gif'
ShellPresta = 'f... | Python | 1 |
AssetId = <Self as DeFiComposableConfig>::MayBeAssetId,
> + Mutate<
Self::AccountId,
Balance = Self::Balance,
AssetId = <Self as DeFiComposableConfig>::MayBeAssetId,
> + MutateHold<
Self::AccountId,
Balance = Self::Balance,
AssetId = <Self as DeFiComposableConfig>::MayBeAssetId,
> + ... | Rust | 0 |
pes can be used in associated type constraints
};
const _: () = {
fn f1<'a>(arg : Box<dyn X< 'a = u32 >>) {}
//~^ ERROR: only types can be used in associated type constraints
};
fn main() {}
<reponame>polyfractal/playground<filename>hotcloud/src/main.rs
#![feature(custom_derive, plugin)]
#[macro_use] extern ... | Rust | 0 |
# 9095 1,2,3 더하기
# 목표 : n을 1,2,3의 합으로 나타내는 방법의 수 구하기
# 제한 : 0 < n < 11, 1000ms 이내
# 방법 : 이전의 수를 활용하여 다음 수를 예측 -> DP
DP = [0, 1, 2, 4] + [0] * 7
for c in range(int(input())):
N = int(input())
for i in range(4, N+1):
DP[i] = DP[i-1] + DP[i-2] + DP[i-3]
print(DP[N])
'''
31120KB / 40ms
''' | Python | 1 |
import io
import os
from pyrogram import filters
from tswift import Song
from pyrogram import Client as pbot
# Lel, Didn't Get Time To Make New One So Used Plugin Made br @mrconfused and @sandy1709 dont edit credits
@pbot.on_message(filters.command(["lyric", "lyrics"]))
async def _(client, message):
lel = a... | Python | 1 |
from pr_agent.config_loader import get_settings
def get_secret_provider():
if not get_settings().get("CONFIG.SECRET_PROVIDER"):
return None
provider_id = get_settings().config.secret_provider
if provider_id == 'google_cloud_storage':
try:
from pr_agent.secret_providers.google_... | Python | 1 |
, min_samples=1)
assert_array_equal(core_samples, np.arange(n_samples))
assert_array_equal(labels, [0, 1, 1, 1, 2, 3, 4])
# With eps=1 and min_samples=2 only the 3 samples from the denser area
# are core samples. All other points are isolated and considered noise.
core_samples, labels = dbscan(X, a... | Python | 1 |
}
/// Stores the low lane value to the reference given.
/// ```
/// # use safe_arch::*;
/// let a = m128d::from_array([10.0, 12.0]);
/// let mut f = 0.0;
/// store_m128d_s(&mut f, a);
/// assert_eq!(f, 10.0);
/// ```
#[inline(always)]
#[cfg_attr(docs_rs, doc(cfg(target_feature = "sse2")))]
pub fn store_m128d_s(r: &mut... | Rust | 0 |
import os
import csv
width = 0
height = 0
bg_map = []
fg0_map = []
fg1_map = []
fg2_map = []
npc_map = []
collision_map = []
def get_map_text(map):
map_text = " "
for y in range(0, height):
if y > len(map) - 1:
map_text += "-1, " * width
else:
for x in range(0, width... | Python | 1 |
from typing import Literal
from safety_schemas.models.events import Event, EventType
from safety_schemas.models.events.payloads import (
AuthCompletedPayload,
AuthStartedPayload,
CodebaseSetupCompletedPayload,
CodebaseSetupResponseCreatedPayload,
FirewallConfiguredPayload,
FirewallDisabledPaylo... | Python | 1 |
import torch
def high_quality_nodes(logits: torch.tensor, normal_th: float = 0.05, fraud_th: float = 0.85, high_quality_node: bool = True):
# prediction of the model
#u_pred_log.shape = (192, 2)
u_pred_log = logits.log_softmax(dim=-1)
#u_pred[i]: probability that node i-th is an abnormal node
u_pr... | Python | 1 |
import mysql.connector
from src.config.database import staging_connector
from src.config.procedure import get_log_load_staging, get_script_load_file_by_source
from src.service.controller_service.database_controller import Controller
class LoadStagingController(Controller):
def __init__(self):
super().__i... | Python | 1 |
}
}
impl Core for Polygon {
parent_types![(parametric_path, ParametricPath)];
properties!(
(125, points, set_points),
(126, corner_radius, set_corner_radius),
parametric_path
);
}
impl OnAdded for ObjectRef<'_, Polygon> {
on_added!(ParametricPath);
}
#[naked]
#[no_mangle]
#[li... | Rust | 0 |
_on_bn254::Fq;
use ark_std::vec::Vec;
use ark_ec;
use ark_ff::biginteger::{BigInteger256, BigInteger384};
use ark_ff::bytes::{FromBytes, ToBytes};
use ark_ff::Fp256;
use ark_ff::QuadExtField;
use ark_groth16::{
prepare_inputs, prepare_verifying_key, verify_proof, verify_proof_with_p... | Rust | 0 |
#!/usr/bin/env python3
# Accera Multi-pass Tensor MatMul GPU (with pass fusion)
import accera as acc
import hello_matmul_gpu_generator
import tensor_matmul_gpu_generator
def create_multipass_tensor_matmul_plan(target: acc.Target, mma_shape: acc.MMAShape, num_passes: int):
schedule, A, B, C = hello_matmul_gpu_gener... | Python | 1 |
th.to_string_lossy().into_owned(), output))
},
FileTarget::Highlight(ext) => {
let syntax = client.syntax_set.find_syntax_by_extension(ext)?;
let output = highlighted_html_for_string(
input.as_str(),
... | Rust | 0 |
use solana_core::validator::new_validator_for_tests;
use std::thread::sleep;
use std::time::Duration;
use tempfile::NamedTempFile;
fn make_tmp_file() -> (String, NamedTempFile) {
let tmp_file = NamedTempFile::new().unwrap();
(String::from(tmp_file.path().to_str().unwrap()), tmp_file)
}
fn check_balance(expec... | Rust | 0 |
from openai import OpenAI
from .base import BaseLLMProvider
from typing import Dict, List
from core.logger import logger
import os
class LMStudioProvider(BaseLLMProvider):
def __init__(self):
super().__init__()
self.client = None
self.model_type = os.environ.get("LMSTUDIO_MODEL_TYPE", "")
... | Python | 1 |
* Thêm padding nhỏ */\n"
"}\n"
"")
self.kho_stacked_2.setObjectName("kho_stacked_2")
self.quan_li_danh_muc_2 = QtWidgets.QWidget()
self.quan_li_danh_muc_2.setObjectName("quan_li_danh_muc_2")
self.gridLayout_64 = QtWidgets.QGridLayout(self.quan_li_danh_muc_2)
self.gridLayout_64.se... | Python | 1 |
"""Context variables for all Chimera tools"""
import os
def __get_steam_user_dirs(steam_dir):
base = os.path.join(steam_dir, 'userdata')
user_dirs = []
if os.path.isdir(base):
for d in os.listdir(base):
if d not in ['anonymous', 'ac', '0']:
user_dirs.append(os.path.joi... | Python | 1 |
CString::new(name).unwrap();
let lcpl = hdf5::H5P_DEFAULT;
let dcpl = hdf5::H5P_DEFAULT;
let dapl = hdf5::H5P_DEFAULT;
let dataset = hdf5::H5Dcreate2
(location, cname.as_ptr(), datatype, dataspace, lcpl, dcpl, dapl);
assert!(dataset >= 0);
return dataset;
... | Rust | 0 |
# -*- coding: utf-8 -*-
import pygcb
def CreateDBObject():
dbObj=pygcb.tcMissileDBObject()
dbObj.mzClass='P-20 Rubezh'
dbObj.natoClass='SS-N-2A Styx'
dbObj.mnModelType=5
dbObj.mnType=64
dbObj.cost=0.000000
dbObj.weight_kg=2125.000000
dbObj.volume_m3=3.000000
dbObj.initialYear=1958.00... | Python | 1 |
import json
import requests
import urllib.parse
import os
import time
# File paths
input_file = "cleaned_bird_data.json" # JSON with common bird names
output_file = "gbif_species_ids.json" # JSON to store species IDs
# Function to get GBIF scientific name from a common name
def get_gbif_scientific_name(common_name)... | Python | 1 |
# ## Directives Class
#
# This module manages custom directives for template processing.
# Directives are user-defined handlers that can be registered and processed dynamically.
#
# ### Features:
# - Register custom directives with unique names.
# - Dynamically invoke handlers for registered directives.
# - Maintain a ... | Python | 1 |
data: number & 0x7F,
}
}
pub fn mark(&mut self) {
self.data |= 0x80;
}
pub fn number(&self) -> u8 {
self.data & 0x7F
}
pub fn is_marked(&self) -> bool {
(self.data & 0x80) != 0
}
}
struct BingoBoard {
pub rows: ArrayVec<[ArrayVec<[Square; 5]>; 5]>,... | Rust | 0 |
l":
return [
self.slider,
self.duration,
# self.to_start_button,
self.backwards_button,
self.forward_button,
# self.to_end_button
]
else:
return [
widgets.VBox(
... | Python | 1 |
#!/usr/bin/env python3
"""
Example usage of the application factory pattern
Shows how to create different app configurations
"""
from app_factory import create_app
def main():
print("=== Application Factory Pattern Demo ===\n")
# Create development app
print("1. Creating development app...")
dev_... | Python | 1 |
me[..]);
buf.put_u8(b' ');
let mut wr = buf.writer();
ftoa::write(&mut wr, m.value.value)?;
wr.write(&b" "[..])?;
// in impossible case metric does not have timestamp, use zero
let ts = m.value.timestamp.unwrap_or(0u64);
itoa::write(&mut wr, ts)?;
wr.wri... | Rust | 0 |
applied to this transition. If any, the delay
/// starts exactly `delay_duration` seconds before the next event (visit or
/// vehicle end). See
/// \[TransitionAttributes.delay][google.cloud.optimization.v1.TransitionAttributes.delay\].
#[prost(message, optional, tag="4")]
pub d... | Rust | 0 |
128, i as u128, &shuffles), v);
}
}
#[test]
fn test_deal_into_new_stack_rev() {
let source = vec![9, 8, 7, 6, 5, 4, 3, 2, 1, 0];
let shuffles = "deal into new stack".parse().unwrap();
for (i, &v) in source.iter().enumerate() {
assert_eq!(shuffle_index_rev(source.len() as u128, i as u128, &shuffle... | Rust | 0 |
= {"cleanup": False}
glos.cleanup()
if tmpFpath:
self.assertTrue(
isfile(tmpFpath), msg=f"tmp file does not exist: {tmpFpath}"
)
def addWordsList(
self,
glos: Glossary,
terms: list[str],
newDefiFunc: Callable[[Any], str] = str,
defiFormat: str = "",
) -> list[list[str]]:
wordsList = []
f... | Python | 1 |
conf::EnvConf,
) -> anyhow::Result<()> {
let conf = match conf::parse_cmdopts(prog_name, args) {
Ok(conf) => conf,
Err(errs) => {
for err in errs.iter().take(1) {
if err.is_help() || err.is_version() {
let _r = sioe.pout().lock().write_fmt(format_args!... | Rust | 0 |
# <Copyright 2022, Argo AI, LLC. Released under the MIT license.>
"""Dataset evaluation subpackage."""
from enum import Enum, unique
from typing import Final
NUM_RECALL_SAMPLES: Final = 101
@unique
class SensorCompetitionCategories(str, Enum):
"""Sensor dataset annotation categories."""
ARTICULATED_BUS = ... | Python | 1 |
timer=inference_timer, logger=logger)
# wait for all processes to complete before measuring the time
synchronize()
total_time = total_timer.toc()
total_time_str = get_time_str(total_time)
logger.info(
"Total run time: {} ({} s / img per device, on {} device... | Python | 1 |
!(
"Undo crossed out text (not widely supported).",
NoCrossedOut,
"29m"
);
derive_csi_sequence!("Framed text (not widely supported).", Framed, "51m");
# ! [ doc = "USB device/host/OTG controller" ]
use core::ops::Deref;
use cortex_m::peripheral::Peripheral;
# [ doc = "USB device/host/OTG controller" ]
pub... | Rust | 0 |
_before_insn: &mut c_int,
) -> usize {
*ip_before_insn = unwind_ctx.signal as _;
unwind_ctx.ctx[Arch::RA]
}
#[no_mangle]
pub extern "C" fn _Unwind_SetIP(unwind_ctx: &mut UnwindContext<'_>, value: usize) {
unwind_ctx.ctx[Arch::RA] = value;
}
#[no_mangle]
pub extern "C" fn _Unwind_GetLanguageSpecificData(un... | Rust | 0 |
import pandas as pd
def merge_csv(file1, file2):
# 读取CSV文件
df1 = pd.read_csv(file1)
df2 = pd.read_csv(file2)
# 合并CSV数据
combined_df = pd.concat([df1, df2], ignore_index=True)
# 处理“县级市”重复的数据
combined_df.sort_values(by=["县级市"], inplace=True)
duplicated_rows = combined_df[combined_df.dup... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.