text string | label_name string | labels int64 |
|---|---|---|
import datetime
from django.conf import settings
from django.utils import formats, timezone
from django.utils.dateparse import parse_datetime
def ensure_utc(value):
"""
Similar to how django-modelcluster stores the revision's data and similar to how
django stores dates in the database, this converts the ... | Python | 1 |
from django.core.validators import FileExtensionValidator
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("admin_interface", "0020_module_selected_colors"),
]
operations = [
migrations.AlterField(
model_name="theme",
... | Python | 1 |
# Copyright (c) 2023 - 2025, AG2ai, Inc., AG2ai open-source projects maintainers and core contributors
#
# SPDX-License-Identifier: Apache-2.0
#
# Portions derived from https://github.com/https://github.com/Lancetnik/FastDepends are under the MIT License.
# SPDX-License-Identifier: MIT
from __future__ import annotati... | Python | 1 |
rallel_mode
def forward(self, z):
# z = (batch, n_bands, n_time, emb_dim)
if self.parallel_mode:
for sbm_pair in self.seqband:
# z: (batch, n_bands, n_time, emb_dim)
sbm_t, sbm_f = sbm_pair[0], sbm_pair[1]
zt = sbm_t(z) # (batch, n_bands,... | Python | 1 |
driver.pnext()
self.assertTrue(True)
def test_ping(self):
driver=APIMOTE(os.environ['APIMOTE_DEVSTRING'])
self.assertRaises(Exception, driver.ping)
def test_jammer_on_off(self):
driver=APIMOTE(os.environ['APIMOTE_DEVSTRING'])
#driver.jammer_on(None, 0... | Python | 1 |
#[doc = "Checks if the value of the field is `AVG_2_MSRMTS`"]
#[inline]
pub fn is_avg_2_msrmts(&self) -> bool {
*self == ADSEL2R::AVG_2_MSRMTS
}
#[doc = "Checks if the value of the field is `AVG_4_MSRMTS`"]
#[inline]
pub fn is_avg_4_msrmts(&self) -> bool {
*self == ADSEL2R::AV... | Rust | 0 |
xpect("should create user");
create_user(&conn, site_id, name).expect("should create user");
let new = retrieve_users(&conn, site_id, 0, 100).expect("should retrieve users");
assert_eq!(old.len() + 2, new.len());
}
#[test]
fn create_one_user_and_delete() {
let conn = establish_in_memory();
use dies... | Rust | 0 |
{
let g = generate_verifiable_generator(&p, &q, &ev, idx)?;
Ok(DSAParameters{ size: ps, p: p, q: q, g: g })
}
/// Given the provided evidence, validate that the domain parameters
/// were appropriately constructed.
pub fn verify(&self, ev: &DSAGenEvidence, idx: u8) -> bool {
let... | Rust | 0 |
gregorian, Gregorian};
pub const EPOCH: i32 = 227015;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Islamic {
pub year: i32,
pub month: i32,
pub day: i32
}
pub fn is_islamic_leap_year(year: i32) -> bool {
divide(14 + 11 * year, 30).1 < 11
}
/// birashk has the 15th year instead of the 16t... | Rust | 0 |
{
'name': 'Certificate',
'version': '0.1',
'category': 'Hidden/Tools',
'summary': 'Manage certificate',
'installable': True,
'data': [
'security/ir.model.access.csv',
'security/certificate_security.xml',
'views/certificate_views.xml',
'views/key_views.xml',
... | Python | 1 |
port::NB_MAX_FIELDS); input.len() / 2],
|mut res, &s| {
if s.is_empty() {
idx += 1;
} else {
res[idx].extend(s.split(' '));
}
res
},
)
.into_iter()
.filter(|v| v.len() ... | Rust | 0 |
+ "_train.npy"
).shape[0]
config.batch_size = find_nearest(batch_size_buffer, data_len / config.win_size)
config.use_gpu = True if torch.cuda.is_available() and config.use_gpu else False
# if config.use_gpu and config.use_multi_gpu:
# config.devices = config.devices.replace(" ", ... | Python | 1 |
2, if2_gateway.clone())]
.iter()
.cloned()
.collect::<HashMap<_, _>>(),
system: IpVersions { ipv4: Some(ID2), ipv6: Some(ID2) },
};
assert_eq!(state, want_state);
let if2_removed_event = StateEvent::construct(State::Removed);
l... | Rust | 0 |
movies = [
["The Grand Adventure", 8.5, "2021-07-15"],
["Mystery of the Blue", 7.8, "2019-11-22"],
["Lost in the Wild", 8.2, "2020-03-05"],
["Rise of a Hero", 9.1, "2022-05-30"],
["A Night in Paris", 7.6, "2018-12-14"],
["The Last Stand", 8.9, "2021-09-10"],
["Beyond the Horizon", 7.4, "2019-06-18"],
["... | Python | 1 |
for style_manifest in speaker_manifest.styles:
# AIVM マニフェスト内の話者スタイル ID を VOICEVOX ENGINE 互換の StyleId に変換
style_id = cls.local_style_id_to_style_id(style_manifest.local_id, speaker_uuid) # fmt: skip
# SpeakerStyle の作成
speaker_style = ... | Python | 1 |
TheEternalGrove = [
(14380.2, -674.562),
(12437.5, -1727.91),
(9123.92, 729.996),
(4736.91, 5926.64),
(481.706, 4060.73),
(-4227.9, 7190.21),
(-666.852, 9355.51),
(6694.72, 13251.7),
(4043.05, 8245.06),
(-6433.92, 7347.38),
(-5590.98, 5023.76),
(-8564.03, 4743.28),
(-... | Python | 1 |
ap()
}
}
unsafe impl<T> DistinctStorage for HashMapStorage<T> {}
/// Dense vector storage. Has a redirection 2-way table
/// between entities and components, allowing to leave
/// no gaps within the data.
#[derive(Derivative)]
#[derivative(Default(bound = ""))]
pub struct DenseVecStorage<T> {
data: Vec<T>,
... | Rust | 0 |
trace), $source)
};
}
#[macro_export]
macro_rules! throw {
($reason:expr) => {
$crate::erts::exception::throw($reason, $crate::location!(), None)
};
($reason:expr, $stacktrace:expr) => {
$crate::erts::exception::throw($reason, $crate::location!(), Some($stacktrace))
};
}
<gh_stars>1... | Rust | 0 |
224 => "rsa_oaep_2048_sha224_mgf1sha224",
Rsa2048Sha256Mgf1Sha1 => "rsa_oaep_2048_sha256_mgf1sha1",
Rsa2048Sha256Mgf1Sha256 => "rsa_oaep_2048_sha256_mgf1sha256",
Rsa2048Sha384Mgf1Sha1 => "rsa_oaep_2048_sha384_mgf1sha1",
Rsa2048Sha384Mgf1Sha384 => "rsa_oaep_2048_sha384_mgf1sha384",
Rsa2048Sha512Mgf1S... | Rust | 0 |
ult_image, (x, y), (x + w, y + h), (0, 255, 0), 2)
# Draw landmarks
result_image = detector.draw_landmarks(result_image, landmarks)
# Draw landmark connections
result_image = detector.draw_landmark_connections(result_image, landmarks)
... | Python | 1 |
0x181B))
TalkEnd(0x00FF)
Jump('loc_1109')
def _loc_10C9(): pass
label('loc_10C9')
FadeOut(300, 0, 100)
SetMessageWindowPos(72, 320, 56, 3)
TalkSetChrName('')
Talk(
(
(TxtCtl.SetColor, 0x5),
'床还是温热的。',
TxtCtl.Enter,
),
)
C... | Python | 1 |
cent": "N/A",
"pe_ratio": "N/A",
"pb_ratio": "N/A",
"market_cap": "N/A",
"market": "香港股市",
"exchange": "香港交易所"
}
# 方法1: 获取港股实时行情
try:
# 使用akshare获取港股实时数据
realt... | Python | 1 |
key = 'Sagittal T2/STIR Patch'
channels = self.channels_sag
patch_size = self.patch_size_sag
x = data[key]
x = x.transpose(2, 3, 0, 1).reshape(patch_size, patch_size, 5*channels)
x = self.transform(image=x)['image'].reshape(patch_size, patch_size, 5, cha... | Python | 1 |
i]"#,
encoding,
&[
("<div fOo='bar㕦1\nbar2 bar3\tbar4'>", true),
("<div foo='bar㕦'>", true),
("<div foo='BaR㕦'>", true),
("<div foo='bazbar㕦'>", false),
("<div foo='42'>", false),
... | Rust | 0 |
#
# Copyright (c) 2023 Airbyte, Inc., all rights reserved.
#
from setuptools import find_packages, setup
MAIN_REQUIREMENTS = [
"airbyte-cdk",
]
TEST_REQUIREMENTS = [
"pytest~=6.2",
"pytest-mock~=3.6.1",
"requests-mock~=1.9.3",
]
setup(
entry_points={
"console_scripts": [
"so... | Python | 1 |
from dataclasses import dataclass, field
from typing import Optional
import peft
import torch
from peft import PeftConfig, PeftModel
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
from transformers import LlamaForCausalLM, LlamaTokenizer
def merge_peft_adapter(
mo... | Python | 1 |
に変換して保存
df = pd.DataFrame(sales_data)
df.to_csv('data/excel/sales_data.csv', index=False, encoding='utf-8-sig')
df.to_excel('data/excel/sales_data.xlsx', index=False, engine='openpyxl')
print(f"✓ 商品購入データ生成完了: {len(sales_data)}件")
return df
def generate_meeting_transcript():
"""会議文字起こしデータを生... | Python | 1 |
import os
import google.generativeai as genai
class AICodeDetector:
def __init__(self, api_key):
os.environ["GEMINI_API_KEY"] = api_key
genai.configure(api_key=api_key)
self.generation_config = {
"temperature": 0.5,
"top_p": 0.9,
"top_k": 40,
... | Python | 1 |
hed_llm_groups = set(fetched_llm_provider.groups)
llm_provider_groups = set(llm_provider.groups)
# NOTE: returned api keys are sanitized and should not match
if (
fetched_llm_groups == llm_provider_groups
and llm_provider.provider ... | Python | 1 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
AI分析功能测试
验证各种LLM提供商的分析功能
"""
import sys
import os
import time
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from app import create_app
from app.services.ai.analysis_service import AnalysisService
from app.services.ai.llm_provider import... | Python | 1 |
TIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*!
# bacon-cipher
An implementation of the [Bacon's cipher](https://en.wikipedia.org/wiki/Bacon%27s_cipher).
The crate offers codecs that _encode / deco... | Rust | 0 |
Ok(BlockLimits::with_limits(
parse_param_limits(¶m.get_obj("bytes")?)?,
parse_param_limits(¶m.get_obj("gas")?)?,
parse_param_limits(¶m.get_obj("lt_delta")?)?,
))
}
fn parse_msg_forward_prices(param: &PathMap) -> Result<MsgForwardPrices> {
Ok(MsgForwardPrices {
lump_p... | Rust | 0 |
# coding: utf-8
"""
Graphiant APIs
**To use the APIs:** 1) Login using `/api/v1/auth/login` 2) Copy the value of \"token\" in the response 3) Click the \"Authorize\" button 4) In the \"Value\" text field enter: `Bearer <your token>` 5) Click \"Authorize\" 6) All requests are now authorized. **Toke... | Python | 1 |
ormatTag: u16,
pub nChannels: u16,
pub nSamplesPerSec: u32,
pub nAvgBytesPerSec: u32,
pub nBlockAlign: u16,
pub wBitsPerSample: u16,
pub cbSize: u16,
}
impl ::core::marker::Copy for _WAVEFORMATEX {}
impl ::core::clone::Clone for _WAVEFORMATEX {
fn clone(&self) -> Self {
*self
}
}... | Rust | 0 |
8 * 1024,
16 * 1024,
64 * 1024,
128 * 1024,
];
#[rustfmt::skip]
pub static FILE_SIZES_SMALL: &[usize] = &[
1024,
2 * 1024,
4 * 1024,
8 * 1024,
16 * 1024,
64 * 1024,
128 * 1024,
256 * 1024,
512 * 1024,
1024 * 1024,
2 * 1024 * 1024,
];
#[rustfmt::skip]
pub st... | Rust | 0 |
def forward(self, x: torch.Tensor) ->torch.Tensor:
x = self.depthwise_conv(x)
x = self.pointwise_conv(x)
return x
| Python | 1 |
# Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-present Dan <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the F... | Python | 1 |
# -*- coding:utf-8 -*-
# !/usr/bin/env python
"""
Date: 2025/4/11 22:00
Desc: 上海黄金交易所-数据资讯-行情走势
https://www.sge.com.cn/sjzx/mrhq
上海黄金交易所-数据资讯-上海金基准价-历史数据
上海黄金交易所-数据资讯-上海银基准价-历史数据
"""
import pandas as pd
import requests
from akshare.utils.cons import headers
def spot_symbol_table_sge() -> pd.DataFrame:
"""
上... | Python | 1 |
#!/usr/bin/env python3
"""
🎯 EXTRATOR OMIE V3 - MENU PRINCIPAL DE UTILITÁRIOS
==================================================
Script master para navegação e execução dos utilitários organizados.
Oferece interface interativa para acesso rápido a todas as funcionalidades.
"""
import os
import sys
import subprocess
... | Python | 1 |
def f(x, s):
if x >= 313: return s % 2 == 0
if s == 0: return False
h = [
f(x + 2, s - 1),
f(x + 3, s - 1),
f(x * 3, s - 1)
]
return any(h) if (s - 1) % 2 == 0 else all(h)
print(sum([s for s in range(1, 313) if f(s, 2)]))
print([s for s in range(1, 313) if f(s, 3) and not f(... | Python | 1 |
from fastapi import APIRouter
from .admin import admin_router
router = APIRouter()
router.include_router(admin_router, tags=["Admin"]) | Python | 1 |
import pygame as pg
from assets import *
from GUI import Text
def kill(death_message):
global run
backgroundMusic.stop()
background = pg.Surface((window_width, window_height))
background.blit(window, (0, 0))
heading = Text("You Died.", window_width/2, window_height/2, (255, 255, 255), 80, "Arial... | Python | 1 |
s";
pub const TEXTURE_DIRECTORY: &str = "textures";
pub const SHADER_CACHE_DIRECTORY: &str = "shader_caches";
pub const SHADER_DIRECTORY: &str = "shaders";
pub const EXT_AUDIO_SOURCE: [&str; 2] = ["wav", "mp3"];
pub const EXT_AUDIO_BANK: &str = "bank";
pub const EXT_EFFECT: &str = "effect";
pub const EXT_FONT_SOURCE: ... | Rust | 0 |
if self.mat.is_number_matrix(){
let mat = self.mat.number_mat.as_ref().unwrap();
let mat_f64 = mat.map(|f| f.to_f64().unwrap()); // temporarily converts decimal to f64
let lu = mat_f64.lu();
let data = lu.unpack();
let l:DecimalMatrix = data.1.map(|f| Deci... | Rust | 0 |
def reverseVowels(s: str) -> str:
# Convert the string to a list of characters
s_list = list(s)
# Initialize left and right pointers
left, right = 0, len(s) - 1
# Define set of vowels
vowels = set(['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'])
# Loop until left pointer meets or passes t... | Python | 1 |
Some(self.jsx_fragment_factory.clone()),
import_not_used_as_values: match self.imports_not_used_as_values {
ImportsNotUsedAsValues::Remove => {
typescript::strip::ImportsNotUsedAsValues::Remove
}
ImportsNotUsedAsValues::Preserve => {
typescript::strip::ImportsNotUsedAs... | Rust | 0 |
dGadget<P::BasePrimeField> for QuadExtVar<BF, P>
where
BF: FieldVar<P::BaseField, P::BasePrimeField>,
for<'a> &'a BF: FieldOpsBounds<'a, P::BaseField, BF>,
P: QuadExtVarParams<BF>,
BF: ToConstraintFieldGadget<P::BasePrimeField>,
{
#[tracing::instrument(target = "r1cs")]
fn to_constraint_field(&s... | Rust | 0 |
Nama = input("masukan nama :")
Tempatlahir = input("masukan tempat lahir : ")
tanggallahir = float(input("masukan tanggal lahir : "))
tahunlahir = float(input("masukan tahun lahir : "))
jeniskelamin = input("masukan jenis kelamin : ")
nilaimatapelajaranInggris = float(input("masukan nilai pelajaran Inggris : "))
nilaim... | Python | 1 |
>
<li>Az első fázis lezárási kritériumai: az összes különböző csontot tartalmazó régióból, legalább két nézetből, normál és törött röntgenképeket gyüjts felnőttektől, kombinációnként legalább 50 darabot.</li>
<li>A második fázis a különböző alrégiók feltöltése lesz előreláthatólag.</li>
... | Python | 1 |
_task = run_mempool_task(
connection_pool.clone(),
mempool_request_receiver,
eth_watch_req_sender,
&config_opts,
&main_runtime,
);
let proposer_task = run_block_proposer_task(
mempool_request_sender,
state_keeper_req_sender.clone(),
&main_runtime,
... | Rust | 0 |
(expectedOutput);
}
#[test]
fn shouldFail_whenRowHasGuardWithConjunctionAndOneInnerTypeAndComma_ButNoSecondType()
{
let transitionTable = "
#include <boost/msm/back/state_machine.hpp>
#include <boost/msm/front/state_machine_def.hpp>
#include <boost/msm/front/euml/operator.hpp>
struct State1 : public boost::msm::f... | Rust | 0 |
#[cfg(feature = "full")]
#[cfg_attr(doc_cfg, doc(cfg(feature = "clone-impls")))]
impl Clone for MethodTurbofish {
fn clone(&self) -> Self {
MethodTurbofish {
colon2_token: self.colon2_token.clone(),
lt_token: self.lt_token.clone(),
args: self.args.clone(),
gt_... | Rust | 0 |
== 2:
s0, s1 = status.split(' ')
self.status = '%s'%s0.rjust(status_len//2) + ' '\
'%s'%s1.ljust(status_len//2)
else:
sp = status_len - len(status)
self.status = ''.ljust(sp//2) + status + ''.ljust((sp+1)//2)
def summary(self):
... | Python | 1 |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright (C) 2019-2021 Megvii Inc. All rights reserved.
from .base_detection_config import BaseDetectionConfig
_config_dict = dict(
MODEL=dict(
PIXEL_MEAN=[123.675, 116.28, 103.53], # RGB FORMAT
PIXEL_STD=[1.0, 1.0, 1.0],
VGG=dict(
... | Python | 1 |
_fetch_string(&self.client, &url).await?,
)?);
}
Ok(h)
}
async fn get_raw_header(&self, digest: BlockHash) -> Result<Option<RawHeader>, ProviderError> {
let header = esplora_if_found!(
EsploraBlock::fetch_by_digest(&self.client, &self.api_root, digest).await
... | Rust | 0 |
ArgsType,
pub EventId: i32,
pub StructureChangeType: StructureChangeType,
pub pRuntimeId: *mut i32,
pub cRuntimeIdLen: i32,
}
impl ::core::marker::Copy for UiaStructureChangedEventArgs {}
impl ::core::clone::Clone for UiaStructureChangedEventArgs {
fn clone(&self) -> Self {
*self
}
}
#[r... | Rust | 0 |
{"5", Box{-90.0, -45.0, -45.0, 0.0}},
{"red", Box{-25.3125, -23.90625, 160.3125, 161.71875}},
{"r2", Box{-45.0, -39.375, 146.25, 157.5}},
{"v7qptt2u5k", Box{64.6291565895, 64.6291619539, 64.9303686619, 64.9303793907}},
{"pey", Box{-68.90625, -67.5, 165.9375, 167.34375}},
{"r7cg5cz8", Box{-23.3692932129, -23.369121... | Rust | 0 |
def calculate_sgpa():
num_subjects = int(input("Enter number of subjects: "))
total_marks = 0
total_credits = 0
for i in range(num_subjects):
marks = float(input(f"Enter marks obtained in subject {i+1}: "))
credits = float(input(f"Enter credits for subject {i+1}: "))
total_marks... | Python | 1 |
b"gry", b"grn", b"hzl", b"oth"];
if !eye_colors.contains(&p.eye_color) {
continue;
}
if !(p.pass_id.len() == 9 && p.pass_id.iter().all(u8::is_ascii_digit)) {
continue;
}
count += 1;
}
count
}
}
#[cfg(tes... | Rust | 0 |
dd_size(mgr: *mut BddManager, bdd: u64) -> usize {
let mgr = unsafe { &mut *mgr };
mgr.count_nodes(BddPtr::from_raw(bdd))
}
#[no_mangle]
#[cfg(not(target_family="wasm"))]
pub extern "C" fn rsdd_false(mgr: *mut BddManager) -> u64 {
let mgr = unsafe { &mut *mgr };
mgr.false_ptr().raw()
}
#[no_mangle]
#[... | Rust | 0 |
# -------------------------------------------------------------
#
# 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 unde... | Python | 1 |
, column=0, end_column=0)
if (major_version, minor_version) >= (3, 8)
else LocationInfo(lineno=21, end_lineno=21, column=0, end_column=0)
),
LocationInfo(lineno=29, end_lineno=29, column=0, end_column=0),
]
@ALL_PYTHONS
def test_no_frames_at_shutdown(pyt... | Python | 1 |
text_projection")
if "self_attn" in diffusers_name or "text_projection" in diffusers_name:
pass
elif "mlp" in diffusers_name:
# Be aware that this is the new diffusers convention and the rest of the code might
# not utilize it yet.
diffusers_name = diffusers_name.replace(".lora.... | Python | 1 |
Option<std::string::String>,
}
impl std::fmt::Debug for TagError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("TagError");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl TagError {
pub fn message(&se... | Rust | 0 |
class Node:
def __init__(self):
self.count = 0
self.list = [None] * 26
def containKey(self, ch):
return self.list[ord(ch) - ord('a')] is not None
def get(self, ch):
return self.list[ord(ch) - ord('a')]
def put(self, ch, new_node):
self.list[ord(ch) - ord('a')] ... | Python | 1 |
ready for Wasm.
#![cfg_attr(not(feature = "std"), no_std)]
// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
#![recursion_limit = "256"]
use pallet_transaction_payment::CurrencyAdapter;
use sp_std::prelude::*;
use sp_std::collections::btree_map::BTreeMap;
use parity_scale_... | Rust | 0 |
alize_operation_crate_operation_set_queue_attributes(
input: &crate::input::SetQueueAttributesInput,
) -> Result<smithy_http::body::SdkBody, std::convert::Infallible> {
let mut out = String::new();
#[allow(unused_mut)]
let mut writer = smithy_query::QueryWriter::new(&mut out, "SetQueueAttributes", "2012... | Rust | 0 |
.contains(expected), "Error did not contain expected! error: {}", stderr);
snapshot(&stderr);
}
macro_rules! _check_compile_fail_output {
($stderr:expr, expected: $expected:expr) => {{
crate::integration_impl::_check_compile_fail_output(&$stderr, $expected, |stderr| {
insta::with_settings!{... | Rust | 0 |
LightBinningOutputBuffer = LightBinningOutputStd430;
#[derive(Copy, Clone, Debug)]
#[repr(C)]
pub struct ClusterMetaStd430 {
pub count: u32, // +0 (size: 4)
pub first_light: u32, // +4 (size: 4)
} // 8 bytes
pub type ClusterMetaBuffer = ClusterMetaStd430;
pub const INPUT_DATA_DESCRIPTOR_SET_INDEX: usi... | Rust | 0 |
from sklearn.ensemble.tforest import TForestClassifier, StablePathBundle
from .retrain import get_poisoned_loss
import numpy as np
from ..logger import LOGGER_NAME
from logging import getLogger
LOGGER = getLogger(LOGGER_NAME)
MINIMUM_VALID_LOSS = 0
def find_candidate(
xtrain: np.ndarray,
ytrain: np.ndarray,... | Python | 1 |
po.get_cpu_location(CPUBIND_PROCESS));
}
/// Find the last core
fn last_core(topo: &mut Topology) -> &TopologyObject {
let core_depth = topo.depth_or_below_for_type(&ObjectType::Core).unwrap();
let all_cores = topo.objects_at_depth(core_depth);
all_cores.last().unwrap()
}
/*!
RON is a simple config format ... | Rust | 0 |
import argparse
import importlib
from v_diffusion import make_beta_schedule
from moving_average import init_ema_model
from torch.utils.tensorboard import SummaryWriter
from copy import deepcopy
import torch
import os
from train_utils import make_visualization
import cv2
def make_argument_parser():
parser = argpars... | Python | 1 |
t_ok=True)
with open(temp_dir / "dataset.json") as f:
dataset = json.load(f)
results = pd.read_csv("temp/result.csv")
results.loc[:, (results.columns != "x_axis")] *= 1000 * 1000
ax = results.plot(x="x_axis")
# plt.xticks(list(range(0, 64*20+1, 64)))
plt.title("Performance compariso... | Python | 1 |
import torch
from samexporter.mobile_encoder.tiny_vit_sam import TinyViT
from segment_anything.modeling import (
ImageEncoderViT,
MaskDecoder,
PromptEncoder,
Sam,
TwoWayTransformer,
)
def setup_model():
prompt_embed_dim = 256
image_size = 1024
vit_patch_size = 16
image_embedding_si... | Python | 1 |
har('\'') {
self.consume_until_any("<&'");
self.consume_char('\'')
} else if self.consume_char('"') {
self.consume_until_any("<&\"");
self.consume_char('"')
} else {
false
}
}
pub fn consume_char(&mut self, target: char) -> boo... | Rust | 0 |
"""
Configuration components for pretraining.
"""
| Python | 1 |
from typing import Any, Dict, List, Optional
from corbado_python_sdk.exceptions.standard_exception import StandardException
from corbado_python_sdk.generated import ApiException
from ..utils.util import Util
class ServerException(Exception):
"""Custom exception class for server-related errors."""
def __ini... | Python | 1 |
{
Interval::new((self.into_byte() as i8 - rhs.into_byte() as i8).abs() as _)
}
}
impl From<u8> for MidiNote {
fn from(byte: u8) -> Self {
Self::from_byte(byte)
}
}
impl From<MidiNote> for u8 {
fn from(midi: MidiNote) -> Self {
midi.into_byte()
}
}
impl fmt::Display for Mi... | Rust | 0 |
('/').last().unwrap().to_string();
//let tarpath = &dir.path().join(&fname.strip_suffix(".xz").unwrap());
let tarpath = dir.join(&fname.strip_suffix(".xz").unwrap());
// Decompress the tarball
let mut tarball = File::create... | Rust | 0 |
from django.db import models
from django.contrib.auth import get_user_model
from django.utils.translation import gettext_lazy as _
from core_apps.common.models import TimeStampedModel
from core_apps.accounts.models import BankAccount
User = get_user_model()
class VirtualCard(TimeStampedModel):
class CardStatus(m... | Python | 1 |
"""Test the rcv1 loader, if the data is available,
or if specifically requested via environment variable
(e.g. for CI jobs)."""
from functools import partial
import numpy as np
import scipy.sparse as sp
from sklearn.datasets.tests.test_common import check_return_X_y
from sklearn.utils._testing import assert_almost_e... | Python | 1 |
4 - Comparator match"]
#[inline(always)]
pub fn matched(&self) -> MATCHED_R {
MATCHED_R::new(((self.bits >> 24) & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 0:3 - Function"]
#[inline(always)]
pub fn function(&mut self) -> FUNCTION_W {
FUNCTION_W { w: self }
}
}
<reponame>dvc94ch/... | Rust | 0 |
rgv):
parser = OptionParser()
parser.add_option("-b", "--binary", dest="bb", help="path to BusyBox binary", metavar="FILE")
parser.add_option("-c", "--config", dest="bbconfigs", help="path to extracted BusyBox configs", metavar="DIR")
parser.add_option("-f", "--found", dest="found", action="store_true", help="print... | Python | 1 |
7/site-packages/future/backports/http/cookiejar.pyt offset_from_tz_string s
c
C` s y t j | j d } Wn_ t k
r~ y t | } Wn t k
rQ d SXd | k oi d k n rw | } q d Sn X| d k r d } n | d k r d } n | d k r d } n t | }... | Python | 1 |
from typing import List
def solve(grid: List[List[int]]) -> List[List[int]]:
h, w = len(grid), len(grid[0])
out = [[0]*w for _ in range(h)]
if h == 5 and w == 5:
for y in range(1, h):
for x in range(w-1):
if grid[y][x] == 1:
out[y][x] = 2
... | Python | 1 |
on_bounds: bounds.projection_bounds.fold_with(this),
}
}
pub fn super_fold_autoref<'tcx, T: TypeFolder<'tcx>>(this: &mut T,
autoref: &adjustment::AutoRef<'tcx>)
-> adjustment::AutoRef<'tcx>
{
match *autore... | Rust | 0 |
y'
#[inline(always)]
pub fn spr2<V: ?Sized, U: ?Sized, M: ?Sized>(alpha: V::Element, a: &mut M, x: &V, y: &U) where V: Vector, U: Vector<Element = V::Element>, M: PackedMatrix<Element = V::Element>, V::Element: Real {
let (m, n) = a.dim();
debug_assert_eq!(m, n);
debug_assert_eq!(m, x.len());
debug_ass... | Rust | 0 |
def test_model_reduction(method, kwargs, nstates, noutputs, ninputs):
sys = ct.rss(5, 3, 3)
if nstates is None:
# Arguments should generate an error
with pytest.raises(ValueError, match="can't provide both"):
red = ct.model_reduction(sys, **kwargs, method=method)
return
... | Python | 1 |
ist;
mod show;
mod stop;
mod watch;
#[derive(Debug, StructOpt)]
pub enum ExperimentCommand {
Delete {
id: PExperimentId,
},
Launch {
#[structopt(short = "w", long = "watch")]
watch: bool,
#[structopt(flatten)]
definition: DefinitionArg,
},
Show {
i... | Rust | 0 |
erate over the arguments and add any new argument value from the `new_option`.
for arg in option.get_args() {
let mut values = Vec::new();
values.extend_from_slice(arg.get_values());
let new_option_args = new_option.get_args()
.get(arg.get_name())
... | Rust | 0 |
running it in no_std
// environment, specifically, on an STM32F3 Discovery development board.
//
// Copyright © 2017 <NAME>
//
// Licensed under the MIT/X11 license, see the included file 'LICENSE' for
// details.
// This uses the DWT cycle counter, clocked at 72MHz using the external 8MHz HSE
// clock from the ST-Lin... | Rust | 0 |
from whad.zigbee import Sniffer
from whad.device import WhadDevice
from whad.exceptions import WhadDeviceNotFound
from whad.common.monitors import PcapWriterMonitor, WiresharkMonitor
from time import time,sleep
import sys
if __name__ == '__main__':
if len(sys.argv) >= 2:
# Retrieve target interface
... | Python | 1 |
from PyObjCTools.TestSupport import TestCase, min_os_level, min_sdk_level, cast_uint
import WebKit
import objc
class TestDOMNodeFilterHelper(WebKit.NSObject):
def acceptNode_(self, n):
return 1
class TestDOMNodeFilter(TestCase):
@min_sdk_level("10.11")
def testProtocols(self):
self.asser... | Python | 1 |
_arithmetic!(series_div_f64, f64, /);
impl_arithmetic!(series_mul_u8, u8, *);
impl_arithmetic!(series_mul_u16, u16, *);
impl_arithmetic!(series_mul_u32, u32, *);
impl_arithmetic!(series_mul_u64, u64, *);
impl_arithmetic!(series_mul_i8, i8, *);
impl_arithmetic!(series_mul_i16, i16, *);
impl_arithmetic!(series_mul_i32, i... | Rust | 0 |
4+2] = gt_prob[:,:,:,2+k*2:2+k*2+2]
gt_imagegraph[:,:,:,2+k*4+2:2+k*4+4] = gt_vector[:,:,:,k*2:k*2+2]
_test_loss, output = model.Evaluate(input_sat, gt_prob, gt_vector, gt_seg)
test_loss += _test_loss
if step == 1000 or step % 2000 == 0 or (step < 1000 and step % 200 == 0):
for k in range(... | Python | 1 |
from pathlib import Path
from src.csp.instance import CspInstance
from src.csp.evaluator import CspEvaluator
from src.csp.solver import TabuSearchCSP
def run_solver():
"""
Loads an instance, configures the Tabu Search solver, runs it,
and prints the best solution found.
"""
# --- Configuration ---
... | Python | 1 |
# Copyright 2024 Canonical, Ltd.
#
# This program 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.
#
# This program is distribute... | Python | 1 |
);
let trace_id = rng
.sample_iter(&Alphanumeric)
.map(char::from)
.take(8)
.collect::<String>();
// the trace should move across hosts, which in this setup would be nodes
// and pods.
let normal = Normal::new(10.0, 5.0).unwrap();
let node_id_prefix = format!("{... | Rust | 0 |
s traversed and queried again, revisiting the
// same tokens to recompute their local variance.
.find(|(_, token)| {
token
.variance::<InvariantSize>()
.as_invariance()
.map_or(false, |size| *size >= MAX_INVARIANT_SIZE)
})
{
... | Rust | 0 |
ro_en_u7(&mut self) -> THR_ZERO_EN_U7_W {
THR_ZERO_EN_U7_W { w: self }
}
#[doc = "Bit 12 - This is the enable bit for comparing unit7's count with thr_h_lim value."]
#[inline(always)]
pub fn thr_h_lim_en_u7(&mut self) -> THR_H_LIM_EN_U7_W {
THR_H_LIM_EN_U7_W { w: self }
}
#[doc =... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.