text string | label_name string | labels int64 |
|---|---|---|
from heapq import *
def prim(start):
# 시작 정점을 포함한 연결된 정점들
connected = {start}
# 아직 연결되지 않은 간선들을 저장할 힙
unconnected = [(w, e) for e, w in graph[start]]
heapify(unconnected) # 힙 속성 유지
sum_ = 0 # MST의 가중치 합
while unconnected:
weight, vertex = heappop(unconnected) # 최소 가중치 간선 선택
... | Python | 1 |
T_SEPARATOR);
check_subsequent_flags!(INTEGER_TRAILING_DIGIT_SEPARATOR, INTEGER_CONSECUTIVE_DIGIT_SEPARATOR);
check_subsequent_flags!(INTEGER_CONSECUTIVE_DIGIT_SEPARATOR, FRACTION_INTERNAL_DIGIT_SEPARATOR);
check_subsequent_flags!(FRACTION_INTERNAL_DIGIT_SEPARATOR, FRACTION_LEADING_DIGIT_SEPARATOR);
check_subsequent_fl... | Rust | 0 |
import os
# 运行模式: LOCAL 为用户本地运行, CLOUD 为 PandAaI 官网运行
RUN_MODE = os.getenv("RUN_MODE", "LOCAL")
SERVER_ROLE = os.getenv("SERVER_ROLE", "ALL") # API, CONSUMER, ALL
# 日志配置
LOG_LEVEL = os.getenv("LOG_LEVEL", "DEBUG")
LOG_CONSOLE = os.getenv("LOG_CONSOLE", "true")
LOG_FILE = os.getenv("LOG_FILE", "true")
LOG_FORMAT = os... | Python | 1 |
, chain.height());
}
#[test]
fn cannot_forge_difficulty() {
let min_difficulty = Difficulty::min_difficulty();
let (_nonce, mut block, chain) = init_decapitated_chain();
block.difficulty = Arc::new(min_difficulty.clone());
assert!(Chain::expand(&chain, block).is_err());
... | Rust | 0 |
Ok(suitable_vaults[idx].clone())
}
}
/// Get all vaults below the premium redeem threshold
/// Checks three conditions:
/// 1. the vault must have tokens issued
/// 2. the vault must be available to redeem tokens (not all issued tokens currently bein part of redeem/replace proce... | Rust | 0 |
d_pool_size = updated_round.pool_size;
updated_round.pool_size = Uint128(0);
}
tier1_rounds_store.set_at(tier1_rounds_store.len()-1,&updated_round);
//send trigger fee to triggerer
transfer_result = transfer_msg(
triggerer_address.clone(),... | Rust | 0 |
import click
import subprocess
import os
@click.command('test', help="Runs pytest on the blueprints directory or a specific module.")
@click.argument('module_name', required=False)
@click.option('-k', 'keyword', help="Only run tests that match the given substring expression.")
def test(module_name, keyword):
base... | Python | 1 |
ester::{Module, Storage, Call, Event},
// EXCHANGE
Exchange: module_exchange::{Module, Storage, Call, Event<T>},
// Mintx
AuctionManager: module_auction_manager::{Module, Storage, Call, Event<T>, ValidateUnsigned},
Lend: module_lend::{Module, Storage, Call, Event<T>},
Mintx: module_mintx::{Module, Storage... | Rust | 0 |
line chunks.
use crate::{
consts::{CYCLE_MARKER, ONCE_ONLY_MARKER, SEQUENCE_SEPARATOR, SHUFFLE_MARKER},
error::parse::line::LineErrorKind,
line::{
parse::{parse_chunk, split_line_at_separator_braces},
Alternative, AlternativeBuilder, AlternativeKind,
},
};
/// Parse an `Alternative` o... | Rust | 0 |
n"]
pub mod pcr;
#[doc = "GPCLR register accessor: an alias for `Reg<GPCLR_SPEC>`"]
pub type GPCLR = crate::Reg<gpclr::GPCLR_SPEC>;
#[doc = "Global Pin Control Low Register"]
pub mod gpclr;
#[doc = "GPCHR register accessor: an alias for `Reg<GPCHR_SPEC>`"]
pub type GPCHR = crate::Reg<gpchr::GPCHR_SPEC>;
#[doc = "Globa... | Rust | 0 |
32 = 101;
pub const DEFAULT_REPORT_LATENCY: u32 = 1000;
pub trait Trait: SystemTrait {
/// Something which can be notified when the timestamp is set. Set this to `()`
/// if not needed.
type OnFinalizationStalled: OnFinalizationStalled<Self::BlockNumber>;
/// The number of recent samples to keep from this chain. D... | Rust | 0 |
main()
{
let cave = parse_cave(include_str!("../input.txt"));
// a cache of the cave's erosion levels
let mut cache = HashMap::new();
// force the caching of the rectangle from (0, 0) to the target
// (0, 0) and the target won't be present in the cache, but they don't change the result
let (tx... | Rust | 0 |
h S SK Jr S SKJr S SKJrJ r
S SKJr
S SKJr / SQr\\" \5 :X d eg) MapperMapDataPipeShufflerIterDataPipeConcaterMapDataPipeZipperMapDataPipeBatcherMapDataPipeSequenceWrapperMapDataPipeBatcherConcaterMapperSequenceWrapperShu... | Python | 1 |
_mix(agg_noise, speech, i)
return agg_noise
@register_audio_waveform_transform("sporadicnoiseaugment")
class SporadicNoiseAugmentTransform(NoiseAugmentTransform):
@classmethod
def from_config_dict(cls, config=None):
_config = {} if config is None else config
return cls(
_co... | Python | 1 |
from fastapi import APIRouter, Depends
from loguru import logger
from sqlalchemy.orm import Session
from starlette.responses import RedirectResponse
from telegram_bot.database import crud
from telegram_bot.database.database import get_db, get_db_session
from telegram_bot.settings import aio_lru_cache_1h, settings
rou... | Python | 1 |
ing.DEBUG)
component = os.getenv('INSTANCE', 'triggerflow-controller')
# Make sure we log to the console
stream_handler = logging.StreamHandler()
formatter = logging.Formatter('[%(asctime)s.%(msecs)03dZ][%(levelname)s][triggerflow] %(message)s',
datefmt="%Y-%m-%dT%H:%... | Python | 1 |
rice / 500, 2) # Увеличен срок окупаемости
user_ids = message.from_user.id
bot.send_message(
message.chat.id,
text=(
"Вы выбрали карту **RTX 3070**\n\n"
"🔹 **Характеристики и стоимость:**\n"
"💰 Доход: 500 вив/мес\n"
f"💵 Стоимость: {price:.3f} вив\n"
f"⏳ Окупае... | Python | 1 |
Device};
<reponame>jamesmahler/knitting_parser<gh_stars>1-10
//! Holds the definition and details for the supported stitches
/// The supported stitches
#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)]
pub enum Stitch {
// Single
K,
P,
K2Tog,
P2Tog,
Ssk,
Ssp,
SlKwise,
SlPwise,
... | Rust | 0 |
d = samplesPerClass
else:
k_corrected = num_samples2select_class
top_clean_class_relative_idx = torch.topk(discrepancy_class, k=int(k_corrected), largest=False, sorted=False)[1]
agreement_measure[idx_class[top_clean_class_relative_idx]] = 1.0
selected_examples=agreement_me... | Python | 1 |
SubCommand::with_name("-encode")
.alias("encode")
.about("Encode (compress)")
.after_help(
"If no input/ output specified reads/ writes from standard input/ output",
)
.arg(
Arg::with_name... | Rust | 0 |
{
/// Gets the first buckets count, used in MinimizerBucketing phase
fn get_second_bucket(
hash: <Self as HashFunctionFactory>::HashTypeUnextendable,
) -> BucketIndexType;
/// Gets the full minimizer
fn get_full_minimizer(
hash: <Self as HashFunctionFactory>::HashTypeUnextendable,
... | Rust | 0 |
> {
return self.local_vars.as_mut();
}
#[inline]
pub fn next_pc(&self) -> i32 {
return self.next_pc;
}
#[inline]
pub fn set_next_pc(&mut self, next_pc: i32) {
self.next_pc = next_pc;
}
#[inline]
pub fn revert_next_pc(&mut self) {
self.next_pc = (*se... | Rust | 0 |
Name::Headphones => self.headphones_muted = muted,
ChannelName::MicMonitor => self.mic_monitor_muted = muted,
ChannelName::LineOut => self.line_out_muted = muted,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UsbProductInformation {
pub manufacturer_name: Stri... | Rust | 0 |
from datetime import datetime
def main():
birthdate = input("Enter your Birthdate Y-m-d: ")
def compute_age(birthdate):
birth = datetime.strptime(birthdate, "%Y-%m-%d")
today = datetime.now()
return today.year - birth.year - ((today.month, today.day) < (birth.month, birth.day))
main... | Python | 1 |
__doc__ = """ Cosserat rod module import test"""
# System imports
if __name__ == "__main__":
from pytest import main
main([__file__])
| Python | 1 |
_stocks['last_purchase'][idx] = last_purchase[idx]
idx += 1
return _stocks
def change_screen(self, instance):
if instance.text == 'Manage Products':
self.ids.scrn_mngr.current = 'scrn_product_content'
elif instance.text == 'Manage User... | Python | 1 |
[7:0]` to `bit signed [31:0]`.
// TODO: Add SBVT
SignExtend(usize, &'a Rvalue<'a>),
/// Constructor for an array.
ConstructArray(HashMap<usize, &'a Rvalue<'a>>),
/// Constructor for a struct.
ConstructStruct(Vec<&'a Rvalue<'a>>),
/// A constant value.
Const(value::Value<'a>),
... | Rust | 0 |
EPERM = 1 # Operation not permitted
ENOENT = 2 # No such file or directory
ESRCH = 3 # No such process
EINTR = 4 # Interrupted system call
EIO = 5 # I/O error
ENXIO = 6 # No such device or address
E2BIG = 7 # Argument list too long
ENOEXEC = 8 # Exec format error
EBADF = 9 # Bad file ... | Python | 1 |
**{}%**",
&n.status.description,
&n.probability.unwrap_or(-0)
),
false,
);
e.image(
&n.rocket
.configuration
.image_url
.as_ref()
.unwrap_or(&PLACEHOLDER.to_string()),
);
e.url(&n.vid_urls.get(0).unwrap_or(&V... | Rust | 0 |
eg| fold_digits(digits_trailing_zeros(10), 0i32, 10, neg),
true,
))
.or(value((0, 0, false))),
)
.map(
|((mantissa, count, man_overflowed), (exp, _, exp_overflowed))| {
(
if man_overflowed { u64::MAX } el... | Rust | 0 |
import torch
from torch.nn import functional as F
# copy from https://github.com/LeeSinLiang/microGPT/blob/ed40cf9780dbeb180adfe94c227d4aa97e69250e/gpt.py
def top_k_top_p_filter(logits: torch.Tensor, top_k: int = 0, top_p: float = 0.0):
"""
Args:
logits (torch.Tensorpe_): 2D tensor with shape (batch, ... | Python | 1 |
# def func1():
# print("你好")
# func2() # 不是函数的嵌套. 函数的调用
#
#
# def func2():
# print("你不好")
#
#
# func1()
# def func1():
# print("我是func1")
# def func2():
# print("我是func2")
# print("我是外面")
# func2() # 在func1里面访问func2
#
# func1()
def func1():
print("func1_before")
def fun... | Python | 1 |
th, 'save_weight.pth'))
psnr = calc_psnr(bit_inr_res_temp, gt_bits_out_temp)
bermax = errors
if psnr > psnr_max:
psnr_max = psnr
if args.save:
if args.num_bits == 8:
saving_image = (bit_inr_res_temp.detach().cpu().resha... | Python | 1 |
getenv('ARM64', False), "only test for compiled backends, broken on some")
class TestNonFloatUOps(TestUOps):
def test_neg_int32(self): self._test_uop_fxn(UnaryOps.NEG, lambda a: -a, dtypes.int32)
def test_add_int32(self): self._test_bop_fxn(BinaryOps.ADD, lambda a,b: int(a)+int(b), dtypes.int32)
def test_sub_int3... | Python | 1 |
mut self) {
// CVDisplayLinkStop(_displayLinkRef);
// dispatch_suspend(_source);
unsafe {
CVDisplayLinkStop(self.display_link_ref);
dispatch_suspend(self.source)
}
}
// }
//
//
}
// @end
//
// #pragma mark - Callback
//
// static CVReturn displayL... | Rust | 0 |
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Topic :: Software Development :: Compilers',
],
packages = [
'da',
'da.compiler',
'da.examples',
'da.importer',
... | Python | 1 |
import click
import sys
import mhdata.load as data
import mhdata.repair as repair_functions
from mhdata.io import DataReaderWriter
# Python 3.6 dictionaries preserve insertion order, and python 3.7 added it to the spec officially
# Older versions of python won't maintain order when importing data for the build.
if s... | Python | 1 |
: SingleQubitGateOperation = input_operation.try_into().unwrap();
let alpha_r = gate.alpha_r();
let alpha_r_param: CalculatorFloatWrapper =
CalculatorFloatWrapper::extract(convert_cf_to_pyobject(py, alpha_r)).unwrap();
let method_op = operation.call_method0(py, "alpha_r").unwrap();
let compariso... | Rust | 0 |
import time
import torch
from torch import nn
from d2l import torch as d2l
from torch.utils.tensorboard import SummaryWriter
def evaluate_accuracy_gpu(net, data_iter, device):
if isinstance(net, nn.Module):
net.eval()
if not device:
device = next(iter(net.parameters())).device
metri... | Python | 1 |
# # Sử dụng SHA-256 để băm tin nhắn
hash_object = hashlib.sha256(message_bytes)
# # Lấy giá trị băm dưới dạng chuỗi hex
hashed_message = hash_object.hexdigest()
# # Gửi giá trị vừa băm cho server
prin... | Python | 1 |
from layercake.arithmetic.terms.operations import ProductOfTerms
from layercake.arithmetic.terms.operators import OperatorTerm, ComposedOperatorsTerm
from layercake.arithmetic.symbolic.operators import Laplacian, D
def Jacobian(field1, field2, coordinate_system, sign=1, prefactors=(None, None)):
u = coordinate_... | Python | 1 |
now_value);
}
// 改善してたら必ず採用
if next_value < now_value {
return (next, next_value);
}
// 改善してなくても、tまでは悪化を許容
if (next_value - now_value) < t {
return (next, next_value);
}
(now, now_value)
}
fn main() {
let mut sr = SmallRng::from_entropy();
let unif = Uniform::new... | Rust | 0 |
io::Error> {
let name_bytes: &[u8] = name.as_bytes();
let zero_padding_size = compute_padding_size(name_bytes.len());
let mut num_bytes = 0;
// Write the number of useful bytes
let bytes: [u8; 4] = (name_bytes.len() as i32).to_be_bytes();
num_bytes += out_stream.write(&b... | Rust | 0 |
#[structopt(long, short = "q", default_value = "0", env = "SERVER_GRACE_PERIOD")]
/// Defines a grace period in seconds after a `SIGTERM` signal is caught which will delay the server before to shut it down gracefully. The maximum value is 255 seconds.
pub grace_period: u8,
}
<gh_stars>1-10
use std::cell::... | Rust | 0 |
print('"Nexia", "Tiko",\'Damas\', ko\'rganlar qilar havas ')
print("5 ning 4-darjasi ",5**4)
print("22 ni 4 ga bo\'lganda qoldiq",22%4)
print("S= ",125*125 ,"\nP= ",4*125 )
print("S= ",3.14*12**2/4)
print((6**2+7**2)**(1/2)) | Python | 1 |
UniqueCoveragePoolObservationState;
#[no_coverage]
fn observe(
&mut self,
&(index, _counter): &Self::Observation,
input_complexity: f64,
state: &mut Self::ObservationState,
) {
let feature_index = FeatureIdx::new(index);
let AnalyzedFeatureRef { least_comple... | Rust | 0 |
the driver development service"),
example = "To graph device tree:
$ ffx driver dump --graph | dot -Tpng | display"
)]
pub struct DriverDumpCommand {
/// list all device properties.
#[argh(switch, short = 'v', long = "verbose")]
pub verbose: bool,
/// output device graph in dot language so... | Rust | 0 |
VEC4 => Err(UniformWarning::type_mismatch(name, ty)),
Type::BVec2 if glty != gl::BOOL_VEC2 => Err(UniformWarning::type_mismatch(name, ty)),
Type::BVec3 if glty != gl::BOOL_VEC3 => Err(UniformWarning::type_mismatch(name, ty)),
Type::BVec4 if glty != gl::BOOL_VEC4 => Err(UniformWarning::type_mismatch(name, ty... | Rust | 0 |
from_config(config)
@classmethod
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
warnings.warn(
"The class `AutoModelWithLMHead` is deprecated and will be removed in a future version. Please use "
"`AutoModelForCausalLM` for causal language models... | Python | 1 |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
from odoo import _, api, models, modules
class Users(models.Model):
_inherit = 'res.users'
@api.model
def _get_activity_groups(self):
""" Split To-do and Project activities in systray ... | Python | 1 |
import os
import cv2
import tensorflow as tf
import numpy as np
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
from tensorflow.keras.optim... | Python | 1 |
wrong, it shold be one of ('HumanSegMobile', "
"'HumanSegLite', 'HumanSegServer')".format(args.model_type))
model.train(
num_epochs=args.num_epochs,
train_dataset=train_dataset,
train_batch_size=args.batch_size,
eval_dataset=eval_dataset,
save_interval_epochs=arg... | Python | 1 |
compression options available.
fn get_brotli_size(path: &Path) -> u64 {
let out = Command::new("brotli")
.arg("--best")
.arg("--keep")
.arg("--stdout")
.arg(&path)
.output()
.expect("Error during brotli");
assert!(out.status.success());
assert!(out.stdout.len... | Rust | 0 |
from BFSDemo import BFS
from aStarDemo import aStar
from pyamaze import maze,agent,COLOR,textLabel
from timeit import timeit
###########################
## Comparison One by One ##
# First Run this for BFS:
# m=maze(20,30)
# m.CreateMaze(loadMaze='mazeComparison1.csv')
# bSearch,bfsPath,fwdPath=BFS(m)
# l=textLabel... | Python | 1 |
())?;
}
Format::Toml => {
writer.write_all(toml::to_string(&bundle)?.as_bytes())?;
}
Format::Yaml => {
writer.write_all(serde_yaml::to_string(&bundle)?.as_bytes())?;
}
}
Ok(())
}
pub fn deserialize_from_... | Rust | 0 |
s_style: Style,
pub plus_emph_style: Style,
pub plus_non_emph_style: Style,
pub minus_line_marker: &'a str,
pub plus_line_marker: &'a str,
pub commit_style: Style,
pub file_style: Style,
pub hunk_header_style: Style,
pub syntax_set: SyntaxSet,
pub terminal_width: usize,
pub true_... | Rust | 0 |
g_temp = f'./exps/indoor/evaluation/nvs/evaluation_temp_{lis_name_scenes[0]}.txt'
flog_temp = open(path_log_temp, 'w')
for i in range(len(vec_stem_eval)):
try:
flog_temp.write(f'{psnr_imgs_stem[0][i][9:13]} {psnr_imgs_stem[1][i][9:13]} {psnr_imgs_stem[2][i][9:13]}: {psnr_im... | Python | 1 |
not be locked.
#[allow(clippy::expect_used)]
#[inline]
pub fn evolve(
input: &Input,
voxel_size_sq: &Vec3,
time: f64,
mut dt: f64,
mut values: Array4<f64>,
swap: Array4<f64>,
) -> Result<(Array4<f64>, Array4<f64>), Error> {
debug_assert!(time > 0.0);
debug_assert!(dt > 0.0);
// Con... | Rust | 0 |
004;
pub const WAVE_FORMAT_1S16: ::DWORD = 0x00000008;
pub const WAVE_FORMAT_2M08: ::DWORD = 0x00000010;
pub const WAVE_FORMAT_2S08: ::DWORD = 0x00000020;
pub const WAVE_FORMAT_2M16: ::DWORD = 0x00000040;
pub const WAVE_FORMAT_2S16: ::DWORD = 0x00000080;
pub const WAVE_FORMAT_4M08: ::DWORD = 0x00000100;
pub const WAVE_... | Rust | 0 |
time.sleep(0.5)
update.message.reply_text(f"✅ 语音发送 {success} 人,失败 {fail} 人")
def broadcastfull(update: Update, context: CallbackContext):
if update.effective_user.id != ADMIN_ID: return
if len(context.args) < 2:
return update.message.reply_text("用法:/broadcastfull 图片链接 说明")
url = contex... | Python | 1 |