text string | label_name string | labels int64 |
|---|---|---|
from django.contrib.auth.models import AbstractUser
from django.db import models
NULLABLE = {'blank': True, 'null': True}
class User(AbstractUser):
"""Модель пользователя"""
username = None
email = models.EmailField(unique=True, verbose_name='email')
phone = models.CharField(max_length=35, verbose_na... | Python | 1 |
14.pdf>.
let k = r0.wrapping_mul(P::INV);
let mut carry = 0;
fa::mac_with_carry(r0, k, P::MODULUS.0[0], &mut carry);
r1 = fa::mac_with_carry(r1, k, P::MODULUS.0[1], &mut carry);
r2 = fa::mac_with_carry(r2, k, P::MODULUS.0[2], &mut carry);
r3 = fa::mac_with_carry(r3, k, P... | Rust | 0 |
.iter()
.zip(chunk.sections.iter())
.map(|(mesh, chunk_section)| {
Self::build_texture_atlas_for_mesh(
mesh,
chunk_section,
&*asset_server,
... | Rust | 0 |
# pygame.Surface object
# https://www.pygame.org/docs/ref/surface.html
#
# How do I focus light or how do I only draw certain circular parts of the window in pygame?
# https://stackoverflow.com/questions/61657481/how-do-i-focus-light-or-how-do-i-only-draw-certain-circular-parts-of-the-window/61658124#61658124
#
# GitHu... | Python | 1 |
try:
menu = int(input("Choose an option: \n 1. Decimal to binary \n 2. Binary to decimal\n Option: "))
if menu < 1 or menu > 2:
raise ValueError
if menu == 1:
dec = int(input("Input your decimal number:\nDecimal: "))
print("Binary: {}".format(bin(dec)[2:]))
elif menu == 2:
... | Python | 1 |
ot(X, beta_[1:, 0])
y2 = -1 + 2 * y[:, 0]
pp *= y2
np.exp(pp, out=pp)
pp += 1
np.reciprocal(pp, out=pp)
np.square(pp, out=pp)
del y2
def hessp(v):
pp0 = pp * (v[0] + np.dot(X, v[1:]))
res = np.empty_like(v)
res[0] = pp0... | Python | 1 |
Get => "get",
HttpMethod::Post => "post",
HttpMethod::Put => "put",
HttpMethod::Patch => "patch",
HttpMethod::Delete => "delete",
},
url = url,
request_data = request_data.unwrap_or_default(),
return_type = emit_type_name(return_type.to_own... | Rust | 0 |
// reset our card offset
prev_card_id = 0;
for card in &deck.cards {
add_card_to_buffer(card.count, card.id - prev_card_id, &mut bytes);
prev_card_id = card.id;
}
// save off pre string bytes for checksum
let pre_string_byte_count = bytes.len();
// write the string
l... | Rust | 0 |
6,
#[doc = "7: Generic clock generator 7"]
GCLK7 = 7,
#[doc = "8: Generic clock generator 8"]
GCLK8 = 8,
#[doc = "9: Generic clock generator 9"]
GCLK9 = 9,
#[doc = "10: Generic clock generator 10"]
GCLK10 = 10,
#[doc = "11: Generic clock generator 11"]
GCLK11 = 11,
}
impl From<G... | Rust | 0 |
nst STOP: u8 = 0x00;
const PUSH1: u8 = 0x60;
const PUSH32: u8 = 0x7f;
let mut pos = 0;
while pos + 1 < deploy_code.len() {
let op = deploy_code[pos];
if op == RETURN && deploy_code[pos + 1] == STOP {
return &deploy_code[pos + 2..];
}
if op >= PUSH1 && op <= ... | Rust | 0 |
sep}deps/libfoo{hash1}.rlib`
{compiling} foo v0.0.0 (file:{dir})
{compiling} test v0.0.0 (file:{dir})\n",
running = RUNNING,
compiling = COMPILING,
dir = p.root().display(),
sep = path::SEP,
hash1 = hash1,
... | Rust | 0 |
args, get the second arg */
# else if (NATIVE_GET_NUM_ARGS() == 2)
# {
# po = NATIVE_GET_LOCAL(1);
# }
#
# /* Raise TypeError if wrong number of args */
# else
# {
# PM_RAISE(retval, PM_RET_EX_TYPE);
# return retval;
# }
# pself = ... | Python | 1 |
<((), ())>()
.finish(),
)
.unwrap();
// Create an array with the data for the 3 vertices we'll use to draw our triangle.
let vertex_data = [
Vertex {
position: [0.0, 0.5],
color: [255, 0, 0],
},
Vertex {
position: [-0.5... | Rust | 0 |
[f"{k}:{v}⭐" for k, v in resto.ingredient_choices.items()]
)
print(f" Ingrédients: {ingredients_desc}")
def test_market_allocation():
"""Test de l'allocation de marché avec qualité."""
print("\n\n📊 TEST ALLOCATION DE MARCHÉ")
print("=" * 60)
scenario = create_... | Python | 1 |
from typing import List
from paragon.core.dialogue import quick_script_parser
from paragon.core.dialogue.pretty_script_parser import PrettyScriptParser
from paragon.core.dialogue.commands import (
Command,
NewlineCommand,
SetSpeakerCommand,
LoadAssetsCommand,
SetEmotionsCommand,
)
from paragon.cor... | Python | 1 |
from app.db.base_class import Base
from app.models.championship import Championship
from app.models.examination import Examination
from app.models.question import Question
from app.models.queschoice import QuesChoice
from app.models.answer import Answer
from app.models.profile import Profile
from app.models.admit_ca... | Python | 1 |
alignment,
area,
} => {
let resolved = area.resolve(parent_area);
if text.has_changed() {
let surface = self
.font_body
.as_ref()
.unwrap()
... | Rust | 0 |
(out_footprint, layer="merged_lines_original")
# trim lines and footprints
lg.run_cleanup(buffer_gdf)
lg.save_file(out_footprint)
# perpendicular lines
layer = "perp_lines"
out_footprint = Path(out_footprint)
out_aux_gpkg = out_footprint.with_stem(out_footprint.stem + "_aux").with_suffix(
... | Python | 1 |
KNeighborsClassifier in this function.
"""
model = KNeighborsClassifier(n_neighbors=1)
model.fit(evidence, labels)
return model
def evaluate(labels, predictions):
"""
Given a list of actual labels and a list of predicted labels,
return a tuple (sensitivity, specificity).
Assume each ... | Python | 1 |
(
company_info=self.company_info, keywords=keywords, titles=titles
)
prediction = self.llm.generate_content(prompt_template).text
return prediction
class KeywordExtractor(object):
def __init__(self, count=5):
"""
Initializes the KeywordExtractor class.
... | Python | 1 |
>examples/0054.cross_language/rust_f64.rs<gh_stars>0
extern "C"
{
/*void cxx_fast_io_bufferred_release(void* deviceptr) CXX_FAST_IO_NOEXCEPT;
int cxx_fast_io_bufferred_acquire_file(void** generated_device,char const* filename,char const* open_mode) CXX_FAST_IO_NOEXCEPT;
int cxx_fast_io_bufferred_print_c_str(void* devic... | Rust | 0 |
DepA {
const MIN_LEN: usize = <f32 as WireFormat>::MIN_LEN
+ <f32 as WireFormat>::MIN_LEN
+ <f32 as WireFormat>::MIN_LEN
+ <u8 as WireFormat>::MIN_LEN;
fn len(&self) -> usize {
WireFormat::len(&self.snr)
+ WireFormat::len(&self.cp)
+ WireFormat::len(&self.... | Rust | 0 |
result_list.previous_file()
}),
"gg" => consume_buffer_and_execute(&mut self.input_buffer, &mut || result_list.top()),
"G" => consume_buffer_and_execute(&mut self.input_buffer, &mut || result_list.bottom()),
"dd" => consume_buffer_and_execute(&mut self.input_buffer, ... | Rust | 0 |
# Do Not Repeat Repeated Work
#
# Focus: Units 5 and 6: Interpreting and Optimization
#
#
# In class we studied many approaches to optimizing away redundant
# computation. For example, "X * 0" can be replaced with "0", because we
# know in advance that the result will always be 0. However, even if we do
# not know the ... | Python | 1 |
# Iternables dundermethod - __itr__() -> iter(obj)
# Iterators dundermethod - __next__() -> next(obj)
nums = [4,5,6,7]
# Ex- List,dictonary,string,tupes ect are iterables
# Iterables - something that can be looped over for example
for num in nums: # This means iterables
print(num)
# How to find if something i... | Python | 1 |
T: ToSave,
{
type Save = Weiche<Richtung, T::Save>;
fn to_save(&self) -> Weiche<Richtung, T::Save> {
Weiche {
name: self.name.clone(),
aktuelle_richtung: self.aktuelle_richtung.clone(),
letzte_richtung: self.letzte_richtung.clone(),
anschlüsse: self.a... | Rust | 0 |
2%80%99Europe+centrale)&version=202310.2.0&browserGpcFlag=0&isIABGlobal=False&hosts=&landingPath=NotLandingPage&groups=C0001%3A1%2CC0003%3A1%2CC0002%3A1%2CC0004%3A1"
},
{
"domain": "orcid.org",
"hostOnly": True,
"httpOnly": False,
"name": "XSRF-TOKEN",
"path": "/",
... | Python | 1 |
{FieldCharacterIndex, SpecialAbility, SkillAbility, CharacterAbility, NoopAbility, CharacterData, CharacterRecord, Enemy};
use crate::sim1::action::{Attack, AttackEvent, ICDTimer, ElementalAbsorption, NaLoop, SimpleSkill, SimpleSkillDot, SkillDamage2Dot, SimpleBurst, SimpleBurstDot, BurstDamage2Dot, NTimer, DurationTim... | Rust | 0 |
}
}
#[allow(dead_code)]
fn uniform_heating(lattice: &mut Vec<f64>, rank: i32, procs: i32, world: &SystemCommunicator) -> Result<(), Box<dyn std::error::Error>> {
let h = 0.2;
let q = 1.0;
let mut index = 0;
let mut orig = lattice.clone();
let root_process = world.process_at_rank(0);
let mut gl... | Rust | 0 |
, c_char),
('EvtChar', c_char),
('wReserved1', WORD),
]
_COMMTIMEOUTS._fields_ = [
('ReadIntervalTimeout', DWORD),
('ReadTotalTimeoutMultiplier', DWORD),
('ReadTotalTimeoutConstant', DWORD),
('WriteTotalTimeoutMultiplier', DWORD),
('WriteTotalTimeoutConstant', DWORD),
]
__all__ = ['GetLastEr... | Python | 1 |
0.0, 0.0));
let target =
camera_matrix_inv.transform_point3(macroquad::math::Vec3::new(x, y, 0.999));
let direction = target - origin;
let focus = -origin.y / direction.y;
let x = direction * focus + origin;
let target = Point::from(Vector::f... | Rust | 0 |
import os
import sys
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
sys.path.insert(0, ROOT)
import pytest # noqa: E402
from app.services import sigilmesh # noqa: E402
@pytest.mark.asyncio
async def test_mint_reputation_nft():
nft = await sigilmesh.mint_reputation_nft({"score": 900})
... | Python | 1 |
#!/usr/bin/python
#
# this will generate a random frsky compatible
# hop table and a random txid
#
import random
import textwrap
random.seed()
#get a random number for the txid
txid = random.randint(513, 65000)
hoptable_ok = 0
#generate hoptable
hoptable_ok = 0
while (hoptable_ok == 0):
#get random numbers for ... | Python | 1 |
self.critic(sampled_batch['obs'], sampled_batch['actions'])
critic_loss = F.mse_loss(q, q_target.repeat(1, q.shape[-1]))
abs_critic_error = torch.abs(q - q_target.repeat(1, q.shape[-1]))
self.critic_optim.zero_grad()
critic_loss.backward()
self.critic_optim.step()
if up... | Python | 1 |
# "max_obj_inds": object index of the object with the highest score at each location
max_obj_inds = torch.argmax(pred_masks, dim=0, keepdim=True)
# "batch_obj_inds": object index of each object slice (along dim 0) in `pred_masks`
batch_obj_inds = torch.arange(batch_size, device=device)[:, No... | Python | 1 |
fn add_row(&self, lhs: &Matrix<T>, rhs: &Matrix<T>) -> Matrix<T> {
switch_to_cpu_help_lr(self, lhs, rhs, |device, lhs, rhs| device.add_row(lhs, rhs))
}
}
// influxdb.rs
use super::sensordata::MyData;
use super::startup;
use anyhow::anyhow;
use chrono::*;
use log::*;
use std::{ffi::OsString, io::Write, pro... | Rust | 0 |
from enum import Enum
class UserRole(Enum):
ADMIN = "admin"
USER = "user"
| Python | 1 |
from project.services.base_service import BaseService
class MainService(BaseService):
CAPACITY = 30
def __init__(self, name: str):
super().__init__(name, capacity=self.CAPACITY)
# NB!!!
def details(self):
result = f"{self.name} Main Service:\n"
if len(self.robots) <= 0:
... | Python | 1 |
next,
LogEntry::Data(b"foobar".to_vec().into())))
.wait_future()
.expect("append_entry");
let (off, val) = task::spawn(store.fetch_next(current)).wait_future().expect("fetch");
assert_eq!((off, val),
(next, LogEntry::Data(b"foobar".to_vec().... | Rust | 0 |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from .dino_clstoken_loss import DINOLoss
from .ibot_patch_loss import iBOTPatchLoss
from .koleo_loss import KoLeoLoss
| Python | 1 |
'''
a=101
while a < 100:
print('*', end ='')
print()
Phân tích:
Biến a khởi tạo = 0.
Trong vòng lặp while a < 100: → điều kiện đúng (0 < 100).
Nhưng trong thân vòng lặp không hề có câu lệnh a = a + 1 để tăng giá trị của a.
Kết quả:
a luôn bằng 0 → điều kiện a < 100 luôn đúng → vòng lặp chạy vô hạn.
Nghĩa là chươn... | Python | 1 |
o on the stderr.
:param adv_object: Parameters of the adversarial object, printed out to the stderr.
"""
self.logger.info(adv_object)
def save_image(self, image: np.ndarray) -> None:
"""
Saves images generated during lasting process to the artifacts directory.
:par... | Python | 1 |
"""Common methods for NAS."""
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2021 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.o... | Python | 1 |
Result<Env> {
let token_distribution = TokenDistribution::generate();
let inital_contracts = if let Some(path) = &cfg.inital_bytecode_path {
let (addr, _) = token_distribution.addr_to_amount.iter().next().c(d!())?;
let salt = cfg
.inital_salt
.c... | Rust | 0 |
as(engine: &mut Engine) -> Status {
engine.load_instruction(Instruction::new("GRAMTOGAS"))?;
fetch_stack(engine, 1)?;
let nanograms_input = engine.cmd.var(0);
let gas = if nanograms_input.as_integer()?.is_neg() {
0
} else {
let nanograms = nanograms_input.as_integer()?.take_value_of(... | Rust | 0 |
ked::<u16>(start_codes_offset + i2) };
if codepoint < start {
hi = i;
} else if codepoint > unsafe { b.read_unchecked::<u16>(end_codes_offset + i2) } {
lo = i + 1;
} else {
let deltas_offset = start_codes_offset + segcount_x2;
let ranges_offset = d... | Rust | 0 |
ailable():
inlier_device = torch.device('cpu')
else:
inlier_device = torch.device('cuda', int(opt.inlier_gpu))
return fitting_device, consac_device, depth_device, inlier_device
def get_depth_model(opt, devices):
depth_device = devices[2]
if opt.depth_model == "bts":
depth_d... | Python | 1 |
self.point_color = point_color
self.bbox_color = bbox_color
self.points_in_box_color = points_in_box_color
self.rot_axis = rot_axis
self.center_mode = center_mode
self.mode = mode
# draw points
if points is not None:
self.pcd, self.points_colors = _... | Python | 1 |
")
# ⑤ BlastBerry Override を上書き
bb_override_meta = read_datatable_json(BLASTBERRY_OVERRIDE_PATH)
rep_bb_ov, add_bb_ov = merge_rows(rows, bb_override_meta["Rows"])
print(f"[MERGE] (BB Base) <- BlastBerryOverride : replaced={rep_bb_ov}, added={add_bb_ov}")
# ⑥ Hotfix: BlastBerryOverride
if HOTFI... | Python | 1 |
DF: HKDF-SHA256
MAC: HMAC-SHA256
Group: P256_XMD:SHA-256_SSWU_RO_
Context: 4f50415155452d504f43
Nh: 32
Npk: 33
Nsk: 32
Nm: 32
Nx: 32
Nok: 32
~~~
#### Input Values
~~~
client_identity: 616c696365
server_identity: 626f62
oprf_seed: f7664fae89be455ee3350b04a85eab390b2dc63256fbd311d8de944b45
b859e6
credential_identifier:... | Rust | 0 |
ize(
anti_rug.reserve_bp,
snapshot,
)?)
.ok_or(ErrorCode::NumericalOverflowError)?;
msg!(
"calculated reserve size total is {} dividing by number tickets punched {}",
reserve_size,
fair_l... | Rust | 0 |
red = true;
}
}
}
if just_triggered {
if let Some((status_index, _)) = sim.get_first_status_for_pos(x, y) {
actions.push(Action::SetStatusParam1{value: 9, status_index});
}
} else {
actions.push(Action::MoveTile{
from_x: x,
from_y: y,
to_x: x + push_off_x,
to_y: y + push_off_y... | 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 under the Apache License, Version 2.0
# (the "License"); you may not us... | Python | 1 |
GCP_TEST_MACHINE_LIST = {
"europe-west1-c": [
"sshkeys-11",
"sshkeys-12",
"hadoop-2",
"hadoop-3",
"mssql-16",
"mimikatz-14",
"mimikatz-15",
"tunneling-9",
"tunneling-10",
"tunneling-11",
"tunneling-12",
"tunneling-13",
... | Python | 1 |
append('-DVERSION_INFO="%s"' % self.distribution.get_version())
opts.append(cpp_flag(self.compiler))
# if has_flag(self.compiler, '-fvisibility=hidden'):
# opts.append('-fvisibility=hidden')
elif ct == 'msvc':
opts.append('/DVERSION_INFO=\\"%s\\"' % self.distr... | Python | 1 |
import pandas as pd
import numpy as np
# Membaca data dari file CSV
data = pd.read_csv('allkumhamsma2018.csv') # Gantilah dengan nama file yang sesuai
rules = pd.read_csv('data_asli.csv')
# Mengambil variabel yang diperlukan dari rules
results = []
# Mengambil data dari setiap baris dalam rules
for index, row in ru... | Python | 1 |
# Uses python3
DEFAULT_READS_NUMBER = 1618
DEFAULT_MIN_OVERLAP_LENGTH = 70
LENGTH_OF_READ = 100
class TrieNode(object):
def __init__(self):
self.children = {}
self.indexes = []
class PrefixTrie(object):
def __init__(self):
self.root = TrieNode()
def addPrefix(self, string, index):
for end in range(DEFAULT... | Python | 1 |
_00_08 != 0 {
all.insert(MethodAccessFlags::Static);
}
if value & 0x_00_10 != 0 {
all.insert(MethodAccessFlags::Final);
}
if value & 0x_00_20 != 0 {
all.insert(MethodAccessFlags::Synchronized);
}
if value & 0x_00_40 != 0 {
... | Rust | 0 |
import torch
try:
import triton
import triton.language as tl
except ImportError as e:
print('triton is not installed, please install by running `pip install triton -U --pre`')
exit()
@triton.autotune(configs = [
triton.Config({'BLOCK_SIZE': 128}, num_warps = 4),
triton.Config({'BLOCK_SIZE': 1... | Python | 1 |
son::CombinedJson;
use self::standard_json::input::Input as StandardJsonInput;
use self::standard_json::output::Output as StandardJsonOutput;
///
/// The Solidity compiler.
///
pub struct Compiler {
/// The binary executable name.
pub executable: String,
}
impl Compiler {
/// The default executable name.
... | Rust | 0 |
let builder = MessageBuilder::new().error("Stop trying to break the bot.");
return command.create_message(&ctx, builder).await;
}
if let Some(call) = ctx.songbird.get(SERVER_ID) {
let call = call.lock().await;
if call.queue().is_empty() {
let builder = MessageBuild... | Rust | 0 |
Option<u8> {
#[inline]
fn from(input: Grab) -> Self {
Some(input.0)
}
}
impl From<Grab> for u16 {
#[inline]
fn from(input: Grab) -> Self {
u16::from(input.0)
}
}
impl From<Grab> for Option<u16> {
#[inline]
fn from(input: Grab) -> Self {
Some(u16::from(input.0))
... | Rust | 0 |
mentValue::String(value),
ArgType::Path => ArgumentValue::PathVal(value.into()),
}
}
}
/// Binary search for a `key` in a sorted array of items, given a comparison
/// function. This implementation is tweaked to handle the case where the
/// comparison function does prefix matching, where multi... | Rust | 0 |
is_too_small_to_be_represented_as_8_bit_signed() {
let mut cpu = create_test_cpu();
cpu.status_flags = 0x03;
cpu.a = 208; // - 48
cpu.do_subtract(112);
assert_eq!(0x40, cpu.status_flags & 0x40);
}
#[test]
fn do_subtract_sets_overflow_flag_if_subtraction_is_too_big_to... | Rust | 0 |
ize);
let mut rng = ChaChaRng::from_seed(SEED.using_encoded(blake2_256));
// Create validators
for i in 0..validators {
let balance_factor = if randomize_stake {
rng.next_u32() % 255 + 10
} else {
100u32
};
let (v_stash, v_controller) =
cr... | Rust | 0 |
{line_num}: {action} - Verification failed")
summary.append(f" Expected: {failure.get('expected', '').strip()}")
summary.append(f" Actual: {failure.get('actual', '').strip()}")
summary.append("")
if "message" in results:
summa... | Python | 1 |
#!/usr/bin/env python
import os,sys
PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(PROJECT_ROOT, '../lib'))
sys.path.insert(0, os.path.join(PROJECT_ROOT, '../'))
import settings
for m in settings.app:
try:
exec "from %s.models import *" % m
except ImportEr... | Python | 1 |
s) = {metric_sum / num_ranked_queries}")
os.makedirs(dirname(args.output_filepath), exist_ok=True)
with open(args.output_filepath, "w", encoding="utf-8") as f:
json.dump(results, f, indent=2, ensure_ascii=False)
if args.annotate:
args.output = f'{args.ranking}.annotated'
assert not... | Python | 1 |
services_dir = '/etc/init.d'
services_ignored = [
'boot', 'coredump', 'done', 'led', 'silentboot', 'bluetoothd',
'dlnainit', 'dnsmasq', 'gpio_switch', 'linein', 'logrotate',
'mdplay', 'mediaplayer', 'messagingagent', 'mibrain_service',
'mibt_mesh', 'mibt_mesh_proxy', 'mico_ai_crontab', 'mico_aivs_lab',
'mico_... | Python | 1 |
from transformers import GPT2LMHeadModel, GPT2Tokenizer
import torch
import config
# Load the locally saved tokenizer
tokenizer = GPT2Tokenizer.from_pretrained(config.TOKENIZER_PATH)
# Load the pre-trained model
model = torch.load(config.MODEL_PATH, map_location=torch.device('cpu'))
# Function to generate text from ... | Python | 1 |
with st.expander(f"Box #{i + 1} (Displayed Coords)", expanded=False):
cols = st.columns(2)
coords_display = [f"Top-Left: ({bbox_display[0][0]}, {bbox_display[0][1]})",
f"Top-Right: ({bbox_display[1][0]}, {bbox_display[1][1]})",
... | Python | 1 |
#############################################################################
# Copyright (C) 2020-2025 MEmilio
#
# Authors:
#
# Contact: Martin J. Kuehn <Martin.Kuehn@DLR.de>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may... | Python | 1 |
"\n{str(manifest)}"
logger.info(summary)
def _create_entity_dir(self, start_manifest: Manifest) -> None:
def create_entity_dir(entity: t.Union[Orchestrator, Model, Ensemble]) -> None:
if not os.path.isdir(entity.path):
os.makedirs(entity.path)
for model in star... | Python | 1 |
cc = CNN.evaluate(x_test, label_test)
print('test_loss: ',test_loss)
print('test_accuracy: ',test_acc)
#Epoch당 loss / accuracy plot
loss = hist.history['loss']
acc = hist.history['accuracy']
val_loss = hist.history['val_loss']
val_acc = hist.history['val_accuracy']
epochs = range(1, len(loss)+1)
plt.figure(figsi... | Python | 1 |
the PollingPlaceID is not the Vote Collection Point ID
// The only consistent identifier is {Division}_{Booth}
let mut booths: HashMap<DivBooth, BoothRecord> = HashMap::new();
// but here we use Serde
// OK, let's figure out polling places
let mut pp_rdr = csv::ReaderBuilder::new()
.flexi... | Rust | 0 |
(MetadataUpdateType::META_TYPE_TIMES),
1 => ::std::option::Option::Some(MetadataUpdateType::META_TYPE_REPLICATION),
2 => ::std::option::Option::Some(MetadataUpdateType::META_TYPE_OWNER),
3 => ::std::option::Option::Some(MetadataUpdateType::META_TYPE_PERMS),
4 => ::std::op... | Rust | 0 |
import traceback
import time
from src.DragonValeHack import DragonValeHack
from src.DragonValeHack_Util import *
"""
Item Hack Script:
This script automates the process of buying a item for free in DragonVale. Supports 1080p resolution.
Prerequisites:
- Ensure Nox is fullscreen windowed (for accurate coordina... | Python | 1 |
es);
assert_eq!(val, from_lsb);
}
#[test]
fn test_roundtrip_u24() {
let val = 0xCCBBAA;
let num: Integer<u32, Bits::<24>> = val.into();
let msb_bytes = num.to_msb_bytes().unwrap();
assert_eq!([0xCC, 0xBB, 0xAA], msb_bytes);
let from_msb = <Integer<u32, Bits::<24>>>::from_msb_bytes(&msb_bytes).u... | Rust | 0 |
import numpy as np
import matplotlib.pyplot as plt
import random
from tqdm import tqdm
import time
plt.rcParams['savefig.bbox'] = 'tight'
plt.rcParams['savefig.pad_inches'] = 0
PATH = "../latex/pdfs/"
def fft(y): #dx je (sampling period)/(number of data points)
N = len(y)
H = []
for n in range(N):
... | Python | 1 |
# SPDX-License-Identifier: MIT
#
# MIT License
#
# Copyright (c) 2024 Ericsson
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
#... | Python | 1 |
truct-MLX model not found"
)
def test_task_2_embedding_as_linear():
mlx_model, _ = load("Qwen/Qwen2-0.5B-Instruct-MLX")
embedding = Embedding(
mlx_model.args.vocab_size,
mlx_model.args.hidden_size,
dequantize_linear(mlx_model.model.embed_tokens).astype(mx.float16),
)
for _ in ran... | Python | 1 |
_trait]
impl FromConfig<MqttPublisherConfig> for MqttPublisher {
async fn from_config(config: MqttPublisherConfig) -> anyhow::Result<Self> {
let qos = to_qos(config.qos);
let topic = config.topic;
let retain = config.retain;
let (client, mut event) = new_client(&config.base);
... | Rust | 0 |
pub struct BytesBenchStr(Bytes);
impl BenchStr for BytesBenchStr {
fn from_str(slice: &str) -> Self {
Self(Bytes::copy_from_slice(slice.as_bytes()))
}
fn from_static(slice: &'static str) -> Self {
Self(Bytes::from_static(slice.as_bytes()))
}
fn from_bin_iter(iter: impl Iterator<I... | Rust | 0 |
def validar_lista_numeros():
while True:
try:
numeros = input("Ingrese una lista de números enteros separados por espacios: ")
numeros = numeros.split()
numeros = [int(num) for num in numeros]
return numeros
except ValueError:
print("Erro... | Python | 1 |
mber(1);
create_space_and_post();
assert_ok!(_report_default_post());
SpaceById::<Test>::remove(SPACE1);
});
ext
}
pub fn build_with_report_then_grant_role_to_suggest_entity_status() -> TestExternalities {
let mut ext = Self::build_with_space_and_p... | Rust | 0 |
queue(Goto(5,5)).queue(Clear(ClearType::All))`.
//!
//! Macros:
//!
//! ```no_run
//! use std::io::Write;
//! use crossterm::{queue, QueueableCommand, cursor};
//!
//! let mut stdout = std::io::stdout();
//! queue!(stdout, cursor::MoveTo(5, 5));
//!
//! // some other code ...
//!
//! stdout.flush();
//! ```
//!
//! Yo... | Rust | 0 |
import numpy as np
import bpy
from bpy.props import FloatProperty, EnumProperty, BoolProperty, IntProperty, FloatVectorProperty
from sverchok.node_tree import SverchCustomTreeNode
from sverchok.data_structure import updateNode, zip_long_repeat, ensure_nesting_level, get_data_nesting_level
from sverchok.utils.field.sc... | Python | 1 |
"""OWASP module GraphQL queries."""
import logging
import strawberry
from django.core.exceptions import ObjectDoesNotExist
from apps.mentorship.api.internal.nodes.module import ModuleNode
from apps.mentorship.models import Module
logger = logging.getLogger(__name__)
@strawberry.type
class ModuleQuery:
"""Modu... | Python | 1 |
rive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, FromXmlStream)]
#[serde()]
pub struct Summary {
pub TotalOfferCount: i32,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub NumberOfOffers: Vec<OfferCount>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub LowestPrices: Vec<... | Rust | 0 |
_base_ = '../faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py'
model = dict(
backbone=dict(plugins=[
dict(
cfg=dict(
type='GeneralizedAttention',
spatial_range=-1,
num_heads=8,
attention_type='1111',
kv_stride=2),
... | Python | 1 |
息
user = await context.bot.get_chat(user_id_target)
user_display = f'@{user.username}' if user.username else f"ID:{user_id_target}"
anonymous_status = "匿名投稿" if is_anonymous else "署名投稿"
review_text = f"\u2728 <b>投稿审核</b>\n用户: {user_display... | Python | 1 |
#!/usr/bin/env python
# Run this in your pygmt environment
import elastic_stresses_py.PyCoulomb.fault_slip_object as fso
import tectonic_utils.seismo.moment_calculations as seismo_mo
import elastic_stresses_py.PyCoulomb as PyCoulomb
filedict = {"usgs_slip_file": "../../_Data/files_MTMOD_WS/Kaikoura_usgs_finite_fault.... | Python | 1 |
# Alice and Bob want to exchange messages over an insecure channel.
# They decide to use a Message Authentication Code (MAC) to ensure their authenticity and integrity.
# Mallory is an attacker who has access to the communication channel between Alice and Bob.
#
# Implement message authenticity checking using a combina... | Python | 1 |
raise exceptions.UserAlreadyVerified(
_("This user has been already verified.")
)
except ObjectDoesNotExist:
pass
def __check(self, token):
self._validate_already_verified()
if self.attempts > app_settings.SMS_TOKEN_MAX_ATTEMPTS:
... | Python | 1 |
the `Material Incos Font` project.
pub const MATERIAL_ICONS_BASELINE_FONT: &[u8] =
include_bytes!("../../../assets/fonts/material/MaterialIcons-Baseline.woff2");
/// The 'outlined' variant of the woff2 encoded font, offering glyphs maintained in the `Material Incos Font` project.
pub const MATERIAL_ICONS_OUTLINED... | Rust | 0 |
MOD = 998244353
def dfs(node, parent):
# Initialize the DP for the current node
dp = [1]
size = 0
for child in tree[node]:
if child == parent:
continue
# Recursively calculate for the children
child_dp = dfs(child, node)
# Combine the DP values ... | Python | 1 |
async operation to get a snapshot from the storage engine, then posts a
/// `SnapshotFinished` message back to the event loop when it finishes.
fn get_snapshot(&mut self, cid: u64) {
let task = self.dequeue_task(cid);
let tag = task.tag;
let ctx = task.context().clone();
let exe... | Rust | 0 |
InvalidPadding,
/// `out` size was too small for the conversion
OutputBufferTooSmall {
expected: usize,
},
}
/// Perform bits conversion
pub fn convert_bits<const FROM: u8, const TO: u8>(
input: &[u8],
out: &mut [u8],
pad: bool,
) -> Result<(), ConvertBitsError> {
if FROM > 8 ||... | Rust | 0 |
#[test]
fn it_should_find_all_the_required_passport_keys() {
let snippet = "ecl:gry pid:860033327 eyr:2020 hcl:#fffffd
byr:1937 iyr:2017 cid:147 hgt:183cm";
let expected = vec!["ecl", "pid", "eyr", "hcl", "byr", "iyr", "hgt"];
assert_eq!(find_passport_keys(snippet), expected);
}
... | Rust | 0 |
import pytest
import sys
from unittest.mock import MagicMock
# 这行在导入 local_llm_api.py 前模拟掉 ollama,以防报 ModuleNotFoundError
sys.modules["ollama"] = MagicMock()
from modules.local_llm_api import OllamaModelHandler
@pytest.fixture
def local_llm():
"""Fixture 初始化 OllamaModelHandler 类"""
return OllamaModelHandle... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.