text string | label_name string | labels int64 |
|---|---|---|
| run_test() );
}
}
fn run_test() {
println!("Starting benchmark thread");
// pick 3 keys
}
use super::super::common;
#[tokio::test]
async fn it_adds_files() {
let client = common::get_client();
let result = client.add_file("/does/not/exist").await;
assert!(result.is_err()); // because the pa... | Rust | 0 |
use boolinator::Boolinator;
println!("--output--");
println!("{:?}", true.as_some(1));
// Copyright 2021 TiKV Project Authors. Licensed under Apache-2.0.
//! Key prefix definistions and utils for API V2.
use codec::number::NumberDecoder;
pub const TIDB_RANGES: &[(&[u8], &[u8])] = &[(&[b'm'], &[b'm' + 1]), (&[b't']... | Rust | 0 |
_left_pt = left_pt;
}
let right_pt = (pt
+ Vector2 {
x: tangent.y * width / 2.0,
y: -tangent.x * width / 2.0,
})
.cast()
.unwrap();
if right_pt != prev_right_pt {
right_edge.push(right_pt);
prev_right... | Rust | 0 |
Ok(Self { kind, copyright })
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
enum LicenseKind {
Mit,
Apache2_0,
Bsd3Clause,
Mpl2_0,
Isc,
CC0_1_0,
Unlicense,
Wtfpl,
}
impl LicenseKind {
fn try_from_short_identifiers(identifiers: &str) -> Option<Sel... | Rust | 0 |
fn get_type(&self) -> FieldType {
FieldType::UInt16
}
fn serialize(&self) -> Option<Vec<u8>> {
let mut buf = Vec::new();
match buf.write_u16::<LittleEndian>(*self) {
Ok(_) => Some(buf),
Err(_) => None
}
}
fn deserialize(d: &Vec<u8>) -> Option<... | Rust | 0 |
from ..models.grid import Grid
from ..models.frontier import StackFrontier
from ..models.solution import NoSolution, Solution
from ..models.node import Node
class DepthFirstSearch:
@staticmethod
def search(grid: Grid) -> Solution:
"""
Encuentra la ruta entre dos puntos en una cuadrícula usando... | Python | 1 |
from .BaseWarmupScheduler import BaseWarmupScheduler
from .build import WARMUP_REGISTRY
@WARMUP_REGISTRY.register()
class ConstantWarmupScheduler(BaseWarmupScheduler):
"""
常数 学习率预热包装器
在预热期间,学习率保持不变,等于 cons_lr
预热结束后,学习率由后续调度器 successor 控制
"""
# 初始化方法
def __init__(self, cfg, successor, last_e... | Python | 1 |
e { AccessorMutator::Accessor => "Get",
AccessorMutator::Mutator => "Set" };
if let Some((_, endianness, end_specified)) = parse_ty(ty) {
if end_specified == EndiannessSpecified::Yes {
let return_or_want = match op_type { AccessorMutator::Accessor => "access... | Rust | 0 |
assert_eq! { index, 1 }
/// }
/// }
/// ```
#[inline]
pub fn try_app(op: Op, mut args: Vec<Term>) -> Result<Term, term::TypError> {
let typ = op.type_check(&mut args)?;
Ok(normalize(op, args, typ))
}
/// Creates a less than or equal to.
///
/// Currently rewritten as a greater than or eq... | Rust | 0 |
&Movement(Move::X, Turn::Single)),
_ => {}
};
let v: Vec<Sticker> = c
.stickers
.iter()
.cloned()
.filter(|s| self.get_face(s.current) == Face::F)
.collect();
// guaranteed to be 9 sticker... | Rust | 0 |
cast_octets: i64,
pub in_csum_errors: i64,
pub in_no_ect_pkts: i64,
pub in_ect1_pkts: i64,
pub in_ect0_pkts: i64,
pub in_ce_pkts: i64,
}
#[derive(Debug, PartialEq, Eq, Clone)]
pub struct LinkInet6StatsBuffer<T> {
buffer: T,
}
impl<T: AsRef<[u8]>> LinkInet6StatsBuffer<T> {
pub fn new(buffer... | Rust | 0 |
::write_u16(&mut disk_number_start, self.disk_number_start);
cdfh_bin.append(&mut signature);
cdfh_bin.append(&mut version_needed_to_extract);
cdfh_bin.append(&mut min_version_to_extract);
cdfh_bin.append(&mut general_purpose_bit_flag);
cdfh_bin.append(&mut compression_met... | Rust | 0 |
_SIZE]; BLOCK_SIZE];
for k in k_start..k_end {
let k_offs = k - k_start;
let col_slice = unsafe {
slice::from_raw_parts(pa.offset(lhs.cell_to_offset(row_start, k)), row_end - row_start)
};
for (row_o... | Rust | 0 |
mation_table(self,threshold):
# print("origin deformation point nums:",self._deformation_table.sum())
self._deformation_table = torch.gt(self._deformation_accum.max(dim=-1).values/100,threshold)
def print_deformation_weight_grad(self):
for name, weight in self._deformation.named_parameters()... | Python | 1 |
ng(E_ERROR);
if(isset($_POST['data'])){{
$data = json_decode($_POST['data'],1);
}}else{{
$s = getopt('',array('post:'));
$data = json_decode($s['post'],1);
}}
$url = $data['url'];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER,$data['headers']);
curl_setopt($ch,... | Python | 1 |
{
panic!("getting first line in file failed: {}! {}", filepath, err);
})
}
/*
String manipulation
*/
// Very bad function -- leaks the string memory :)
// Only use for e.g. command line arguments where it won't happen repeatedly.
pub fn string_to_static_str(s: String) -> &'static str {
Box::leak(s... | Rust | 0 |
from collections import defaultdict, deque
from solution import Solution
class Day22(Solution):
parseLinesAsInt = True
seqMap = defaultdict(int)
pruneVal = 16777216
@classmethod
def ProcessNum(cls, num: int) -> dict[tuple[int, int, int, int], int]:
lastPrice = num % 10
lastChanges... | Python | 1 |
if is_valid:
print(f"{Fore.GREEN}✅ Plan approved{Style.RESET_ALL}")
else:
print(f"{Fore.RED}❌ Plan rejected{Style.RESET_ALL}")
return is_valid
def main():
"""Main entry point for the demo."""
# Parse arguments
parser = argparse.ArgumentParser(
description="Run plan-lin... | Python | 1 |
self.0 {
Some(Either::Left(ref conn_like)) => conn_like,
_ => unreachable!(),
}
}
fn conn_like_mut(&mut self) -> &mut Self::ConnLike {
match self.0 {
Some(Either::Left(ref mut conn_like)) => conn_like,
_ => unreachable!(),
}
}
}
use sy... | Rust | 0 |
as *mut _;
let mut x = sys::FrameState::out(&mut secondary as *mut _ as *mut _);
cvt((self.session.instance.fp().wait_frame)(
self.session.handle,
ptr::null(),
x.as_mut_ptr(),
))?;
x.assume_init()
};
let sta... | Rust | 0 |
# Copyright (c) 2025 Intel Corporation
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writ... | Python | 1 |
size = 5.0
rect = QtCore.QRectF(start_pt.x() - (size / 2),
start_pt.y() - (size / 2),
size, size)
painter.setBrush(color)
painter.drawEllipse(rect)
# draw middle circle
size = 10.0
if dist < 50.0:
... | Python | 1 |
nilai = float(input("masukan nilai disini : "))
if nilai < 50:
print("nilai anda E")
elif nilai >= 50 and nilai <= 60:
print("nilai anda D")
elif nilai >= 60 and nilai <= 70:
print("nilai anda C")
elif nilai >= 70 and nilai <= 80:
print("nilai anda B")
elif nilai >= 80 and nilai <= 100:
print ("nil... | Python | 1 |
import logging
from federatedscope.core.configs.config import CN
from federatedscope.register import register_config
logger = logging.getLogger(__name__)
def extend_compression_cfg(cfg):
# ---------------------------------------------------------------------- #
# Compression (for communication efficiency) r... | Python | 1 |
from __future__ import annotations
import collections.abc
from collections.abc import Generator
from dataclasses import dataclass
@dataclass
class DocstringAttribute:
"""class docstring
Attributes:
x (integer): attribute X
y: attribute Y
"""
x: int
"""attribute x"""
y: int
... | Python | 1 |
ray(y_pred_all)
acc = classification_report(y_true, y_pred, digits=4, output_dict=True)
# 將每個類別的召回率寫入 "recall-baseline.csv" 檔案
RecordRecall = ()
RecordAccuracy = ()
start_time = time.time()
for i in range(len(acc) - 3): # -3 因為 classification_report 會多出 'accuracy', 'macro avg', 'weigh... | Python | 1 |
from pwn import *
import sys
if len(sys.argv) > 1 and sys.argv[1]=="debug":
p = process("./saferrrust")
else:
HOST = os.environ.get("HOST", 'localhost')
PORT = int(os.environ.get("PORT",5555))
TICKET = os.environ.get("TICKET")
p = remote(HOST, PORT)
if TICKET:
p.readuntil('Ticket please... | Python | 1 |
r: *mut libc::c_void,
// TODO: It should be a pointer to `struct session`
// but since we are not using it and it's declaration kinda big,
// it was skipped. Same goes to `e_tsess` field below.
pub e_sess: *mut libc::c_void,
pub e_pcred: pcred,
pub e_ucred: libc::xucred,
pub e_vm: vmspace,
pub e_ppid: libc::pid... | Rust | 0 |
= Mask::default();
for (i, c) in s.chars().rev().enumerate() {
let bit = 1u64 << i;
match c {
'0' => mask.and &= !bit,
'1' => mask.or |= bit,
'X' => (),
_ => return Err("Invalid character in mask string"),
};
... | Rust | 0 |
r, 8);
println!("Got version {}.{}", maj, min);
}
"_pin" => {
let pin = string_at(&chunk, 6, None);
println!("Got pin >{}<", pin);
}
"_top" => {
let me_count = chunk[6];
... | Rust | 0 |
import gzip
import os
import unittest
from glossary_v2_test import TestGlossaryBase
class TestGlossaryKobo(TestGlossaryBase):
def setUp(self):
if os.getenv("SKIP_MISSING"):
try:
import marisa_trie # noqa: F401
except ImportError:
self.skipTest("skipping module due to missing dependency: marisa_trie... | Python | 1 |
# pygame.time module
# https://www.pygame.org/docs/ref/time.html
#
# Pygame "pop up" text - How to show an image only for a period of time?
# https://stackoverflow.com/questions/70996802/pygame-pop-up-text-how-to-show-an-image-only-for-a-period-of-time/70996856#70996856
#
# GitHub - PyGameExamplesAndAnswers - Time, tim... | Python | 1 |
n GH104_ERROR_MSG + "\n\n".join(errors)
return ""
class GH200(GitHub):
"Maintained by Dependabot"
requires = {"GH100"}
url = mk_url("gha-basic")
@staticmethod
def check(dependabot: dict[str, Any]) -> bool:
"""
All projects should have a `.github/dependabot.yml` file to su... | Python | 1 |
},
io::Write,
path::{Path, PathBuf},
};
use smush_lut::Lut3dLinear;
fn main() {
let matches = App::new("smush_lut")
.version("0.2")
.author("SMG")
.about("Convert 3D color grading LUTs for Smash Ultimate")
.arg(
Arg::with_name("input")
.index(1)
... | Rust | 0 |
capacity(candidates.len().min(availability_cores.len()));
for (core_idx, core) in availability_cores.iter().enumerate() {
let (scheduled_core, assumption) = match core {
CoreState::Scheduled(scheduled_core) => (scheduled_core, OccupiedCoreAssumption::Free),
CoreState::Occupied(occupied_core) => {
if bitfi... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
百度数字人视频合成API接口
提供创建视频合成任务和查询任务状态的API接口
"""
from flask import request, jsonify, Blueprint, current_app
from flask_jwt_extended import jwt_required, get_jwt_identity
import os
import logging
import json
# 导入服务
from app.services.digital_human.baidu_digital_human_service... | Python | 1 |
# Crie um programa que solicitará ao usuário as medidas de três lados de um triângulo e informará como saída se os valores formam um triângulo retângulo. Os lados devem ser fornecidos em qualquer ordem (ou seja, não “vale” escrever “digite o tamanho da hipotenusa”, “digite o tamanho do cateto 1” etc.). Dica: use o Teor... | Python | 1 |
def show_table(num):
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
show_table(5)
| Python | 1 |
#!/bin/env python3
# Copyright 2025 The EqMap Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | Python | 1 |
# Load evaluated predictions & print number of resolved predictions
evaluated_predictions = pd.read_json(output_file, lines=True)
fields = ['resolved', 'failed_apply_patch', 'error_eval', 'empty_generation']
def count_report_field(row, field):
return row['test_result']['report'][field]
rep... | Python | 1 |
(), &child_files)
.await
.unwrap();
let mut b = child_builder.into_phase2().await.unwrap();
b.add_triple(1, 3, 4).await.unwrap();
b.add_triple(2, 2, 2).await.unwrap();
b.add_triple(3, 4, 5).await.unwrap();
b.remove_triple(3, 2, 5).await.unwrap();
b... | Rust | 0 |
me",
// Value::Float("99.999"))));
// println!("{}", parser.get_value("fruit[0].name[1]").unwrap());
// println!("{}", parser.get_value("fruit[0].physical.fizzy.phys.color").unwrap());
// println!("{}", parser.get_value("fruit[0].physical.fizzy.phys.color[1].fun[0]").unwrap());
// println!("{}", parser.ge... | Rust | 0 |
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = r" Value of the field"]
pub struct MSK28_16R {
bits: u16,
}
impl MSK28_16R {
#[doc = r" Value of the field as raw... | Rust | 0 |
et constant = self.u64_from_value(val)?;
let imm = UImm16Shifted::maybe_from_u64(!constant)?;
Some(imm.negate_bits())
}
#[inline]
fn uimm32shifted_from_inverted_value(&mut self, val: Value) -> Option<UImm32Shifted> {
let constant = self.u64_from_value(val)?;
let imm = UImm32... | Rust | 0 |
'''
(9)Write a menu driven python program which perform the following:
->Find area of circle
->find area of triangle
->find area of sqaure & rectangle
->find simple interest
Exit.(Hint: use infinite while loop for menu)
'''
choice =0
while(choice!=5):
print("1.Find area of circle")
print("2.Find area of t... | Python | 1 |
elf.data4[1],
self.data4[2],
self.data4[3],
self.data4[4],
self.data4[5],
self.data4[6],
self.data4[7],
)
}
}
/// Describes a [GUID] structure used to describe an identifier for a MAPI
/// interface.
pub type IID = GUID;
macro_rules! def_guid {
($name:ident, $data1:literal,... | Rust | 0 |
}
}
#[doc = "Watchdog timer hold\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum WDTHOLD_A {
#[doc = "0: Watchdog timer is not stopped"]
WDTHOLD_0 = 0,
#[doc = "1: Watchdog timer is stopped"]
WDTHOLD_1 = 1,
}
impl From<WDTHOLD_A> for bool {
#[inline(always)]
fn from(... | Rust | 0 |
on purpose, for reproducibility and accurancy of results
llm_config.modify_params = False
if llm_config is None:
raise ValueError(f'Could not find LLM config: --llm_config {args.llm_config}')
metadata = make_metadata(
llm_config,
'AiderBench',
args.agent_cls,
ar... | Python | 1 |
# SPDX-FileCopyrightText: Copyright (C) 2024-2025 沉默の金 <cmzj@cmzj.org>
# SPDX-License-Identifier: GPL-3.0-only
import re
import struct
from collections.abc import Callable
from pathlib import Path
from typing import Literal, overload
from mutagen import File, FileType, MutagenError # type: ignore[reportPrivateImportU... | Python | 1 |
) # (N, num_orders, C1)
>>> L = 3
>>> result = norm(x, L)
>>> print(result.shape)
torch.Size([32, 4, 64]) # (N, num_degrees, C)
"""
return (reduce_order_to_degree(x**2, L, dim=-2)+1e-20).sqrt()
def norm2(x: Tensor, L: DegreeRange):
r"""Compute the square of degree & channel-wise norm of ... | Python | 1 |
_op: wgpu::LoadOp::Clear,
store_op: wgpu::StoreOp::Store,
clear_color: wgpu::Color {
r: skybox.clear_color.x as f64,
g: skybox.clear_color.y as f64,
b: skybox.clear_col... | Rust | 0 |
def FtoC(F):
return (5 / 9) * (F - 32)
F = int(input())
print(FtoC(F)) | Python | 1 |
e<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self.as_str())
}
}
impl fmt::Display for Line<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}
fn main() {
let lines = Lines::new("examples/lorem.... | Rust | 0 |
op in OPERATIONS:
perm_args = _get_permission_args(app_label, op)
_create_permission(app_label, perm_args)
_create_groups(app_label)
def remove_permissions(sender, instance, using, **kwargs):
app_label = instance.ontology_as_mod
for op in OPERATIONS:
perm_args = _get_permission_arg... | Python | 1 |
verifier.append_messages(messages.iter().copied()).unwrap();
verifier.verify().unwrap()
});
},
);
}
}
criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);
mod code_builder;
mod code_builder_helpers;
mod code_line;
mod c... | Rust | 0 |
String(error.to_string())
));
}
}
}
});
let assets = context.assets;
let bundle_identifier = context.config.tauri.bundle.identifier.clone();
let custom_protocol = CustomProtocol {
name: "tauri".into(),
handler: Box::new(move |path| {
let ... | Rust | 0 |
Iv{start:25264912, end: 25264986, val: 0},
Iv{start:27273024, end: 27273065 , val: 0},
Iv{start:27440273, end: 27440318 , val: 0},
Iv{start:27488033, end: 27488125 , val: 0},
Iv{start:27938410, end: 27938470 , val: 0},
Iv{start:27959118, end: 27959171 , v... | Rust | 0 |
# -*- coding: utf-8 -*-
# TencentBlueKing is pleased to support the open source community by making
# 蓝鲸智云 - PaaS 平台 (BlueKing - PaaS System) available.
# Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
# Licensed under the MIT License (the "License"); you may not use this file except
# in c... | Python | 1 |
}
#[doc = "Checks if the value of the field is `PWM_CH2`"]
#[inline(always)]
pub fn is_pwm_ch2(&self) -> bool {
**self == REG_GPIO_2_FUNC_SEL_A::PWM_CH2
}
#[doc = "Checks if the value of the field is `FEM_GPIO_2`"]
#[inline(always)]
pub fn is_fem_gpio_2(&self) -> bool {
**se... | Rust | 0 |
if not d:
return None
o = AlipayMarketingVoucherBatchsendModel()
if 'async' in d:
o.async = d['async']
if 'biz_from' in d:
o.biz_from = d['biz_from']
if 'memo' in d:
o.memo = d['memo']
if 'open_id' in d:
o.open_... | Python | 1 |
cudnnDataType_t::CUDNN_DATA_FLOAT);
let dw = weight_grad_reversed.as_mut_cuda_ptr().unwrap();
let dy_desc = TensorDescriptor::new(output_grad.dim.slice(), cudnnDataType_t::CUDNN_DATA_FLOAT);
let dy = output_grad.as_cuda_ptr().unwrap();
let mut conv2d_desc =
ConvolutionDescriptor::new_conv2d(arg... | Rust | 0 |
graph = get_graph()
onnx_util.set_shapes_from_layerwise_meta(graph, layerwise_meta)
if args.cleanup:
graph = get_graph()
graph.cleanup()
if graph is not None:
model = gs.export_onnx(graph)
return model, rerun_sh... | Python | 1 |
from math import log
from collections import Counter
import pandas as pd
# apply bayes theorem for predicting
def predict_raw(
text: str,
real: Counter,
fake: Counter,
prob_real: float,
tot_words_real: int,
tot_words_fake: int,
n_unique: int,
) -> bool:
# prob(real|words)=prob(words|re... | Python | 1 |
osed,
sfEvtResized => {
let e = unsafe { *event.size.as_ref() };
Resized {
width: e.width,
height: e.height,
}
}
sfEvtLostFocus => LostFocus,
sfEvtGainedFocus => GainedFocus,
sfEvtTextEntered => TextEntered {
... | Rust | 0 |
# utils/visualization.py
import matplotlib.pyplot as plt
import torch
def plot_sample_images(images, labels, preds=None):
if isinstance(images, torch.Tensor):
images = images.cpu().numpy()
if isinstance(labels, torch.Tensor):
labels = labels.cpu().numpy()
if preds is not None and isinstance... | Python | 1 |
orms of rbar and Abar'rbar.
acond = anorm * sqrt(ddnorm)
res1 = phibar**2
res2 = res2 + psi**2
rnorm = sqrt(res1 + res2)
arnorm = alfa * abs(tau)
# Distinguish between
# r1norm = ||b - Ax|| and
# r2norm = rnorm in current code
# ... | Python | 1 |
elf.selected_section == 2 and self.movie_buttons:
self.movie_buttons[self.selected_index].config(style='Selected.TButton')
self.movie_buttons[self.selected_index].focus_set()
def press_selected(self):
if self.selected_section == 0 and self.platform_buttons:
self.platform... | Python | 1 |
axis)
#dataset.transform = None
print('total:', len(dataset))
total = len(dataset)
total = 50
list_6dof = []
all_mean_xs = []
for idx in range(total):
d = dataset[idx]
img_local = d['img_local']
label_verts = d['verts']
label_6dof = d['6dof']
points2d ... | Python | 1 |
}
let mut i = 0;
let nincx = n * incx;
while i < nincx {
if !a.is_zero() {
x[i] *= a;
} else {
x[i] = Complex::zero()
}
i += incx;
}
}
/// SWAP interchanges two vectors.
/// This is [CSWAP](http://www.netlib.org/lapack/explore-html/d1/d44/cswap... | Rust | 0 |
tle::Title;
/// assert_eq!(Title::new("Test", 0).into_toggle_talk(),
/// Title::new("Test", 1));
///
/// assert_eq!(Title::new("Test", 1).into_toggle_talk(),
/// Title::new("Test", 0));
///
/// assert_eq!(Title::new("Test", -1).into_toggle_talk(),
/// Title::new("Test", -1));... | Rust | 0 |
ver, reranker_model="gpt4"):
"""
Retrieve the context and rerank them based on the selected re-ranking model.
Parameters:
- query: user query - string
- retrieved_docs: chunks that needs to be ranked.
- reranker_model: the model selection.
Returns:
- Sorted list of chunks based o... | Python | 1 |
\']
}
def test_cmdline2list(self):
for cmdline, argv in self.cmdlines.iteritems():
self.assertEqual(_cmdline2list(cmdline), argv)
class ExceptionsTestCase(unittest.TestCase):
def test_oserror_raised_with_errno_no_such_file_or_directory(self):
try:
Popen('a-file-th... | Python | 1 |
= 10;
pub const RS_PARITY: usize = 2;
pub const BURST: usize = 12;
pub const DATA_PAR_BURST: (usize, usize, usize) = (RS_DATA, RS_PARITY, BURST);
use failure::Error;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::path::Path;
use xpath_reader::Reader;
fn write_dot(path: &str, deps: &[(String, Str... | Rust | 0 |
import matplotlib.pyplot as plt
import numpy as np
import pickle
from matplotlib import rc
from ..visualization.draw_utils import COLOR, MARKER_STYLE
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rc('text', usetex=True)
def draw_eao(result):
attrs = []
res = {}
for i, (attr, ret) in enu... | Python | 1 |
append_dst(self):
rng1 = date_range("1/1/2016 01:00", periods=3, freq="H", tz="US/Eastern")
rng2 = date_range("8/1/2016 01:00", periods=3, freq="H", tz="US/Eastern")
ser1 = Series([1, 2, 3], index=rng1)
ser2 = Series([10, 11, 12], index=rng2)
ts_result = ser1.append(ser2)
... | Python | 1 |
cked_locations)})')
await ctx.send_msgs([{"cmd": 'LocationChecks', "locations": [location_id]}])
data = await snes_read(ctx, SMZ3_RECV_PROGRESS_ADDR + recv_progress_addr_ptr_offset, 4)
if data is None:
return
item_out_ptr = data[2] | (data[3] << 8)
from .TotalS... | Python | 1 |
from itertools import combinations, permutations
data = ['a', 'b', 'c']
print(list(combinations(data, r=len(data))))
print('-' * 60)
print(list(permutations(data, r=len(data))))
# radar
# Go hang a salami, I'm a lasagna hog
# otto
# ['a', 'b', 'c'] not a palindrome
# ['a', 'b', 'a'] is a palindrom... | Python | 1 |
.load("audio/get_in_bed.mp3"));
if app_state.current() == &GameState::MainGame {
app_state.push(GameState::PlayerSleepingState).unwrap();
}
super::spawn_player_in_bed(&mut commands, &asset_server, &mut materials);
f... | Rust | 0 |
TEXT_RST = '''
Ой, кажется, что ты уже проходил регистрацию…
Если ты хочешь пройти тестирование вновь и поменять данные, нажми заново /start'''
TEXT_START = '''
Привет!
Мы студенты колледжа "Singularity Hub" очень рады твоему визиту к нам!😁
Мы знаем, что сейчас ты находишься на нашем дне открытых дверей.
Предлагаем... | Python | 1 |
## app/agent/prompts.py
DEFAULT_AGENT_PREFIX = """
You are a procurement assistant. Answer procurement queries using available tools.
CRITICAL FORMAT RULES (must always be followed):
1. Only do one of these at a time:
- Use `Action:` with `Action Input:` — OR —
- Use `Final Answer:` (NOT both together).
2. NEV... | Python | 1 |
};
let mut control = format!(
r#"Package: {}
Version: {}
Architecture: {}
Description: {}
Essential: {}
"#,
&self.package,
version,
&self.architecture,
&self.description,
if self.essential { "yes" } else { "no" }
... | Rust | 0 |
RGB_label[i] = i2r[label.item()]
return labels_RGB, labels_IR, RGB_instance_IR_label, IR_instance_RGB_label, centers_RGB, centers_IR, 0, 0, 0, 0
def BCCM_matching(args, epoch, features_RGB, features_IR, labels_RGB, labels_IR, centers_RGB, centers_IR, dist_rgb, dist_ir):
from scipy.optimize impo... | Python | 1 |
mask_cfg, dataset_cfg
def load_classifier_data_config(args):
model_cfg = args.model_cfg
train_cfg = TrainConfig.from_json(args.train_cfg)
dataset_cfg = args.dataset_cfg
# set_seeds(train_cfg.seed)
data = np.load(args.data_path).astype(np.float32)
labels = np.load(args.label_path).astype(np.flo... | Python | 1 |
c: Sending node must set undefined bits in channel_flags to 0
// Only the least-significant bit of channel_flags is currently defined resulting in channel_flags only having one of two possible states 0 or 1
assert!(node0_to_1_send_open_channel.channel_flags<=1);
// BOLT #2 spec: Sending node should set to_self_dela... | Rust | 0 |
;
extern crate rayon;
use super::generation::{Container, Family, Member};
use super::genome::Genome;
use rand::rngs::ThreadRng;
use rand::seq::SliceRandom;
use rand::Rng;
use rayon::prelude::*;
use std::sync::{Arc, RwLock};
//////////////////////////////////////////////////////////////////////////////////////////
///... | Rust | 0 |
import torch
from grace_dl.torch import Compressor
class DgcCompressor(Compressor):
def __init__(self, compress_ratio):
super().__init__(tensors_size_are_same=False)
self.compress_ratio = compress_ratio
def compress(self, tensor, name):
shape = tensor.size()
tensor = tensor.... | Python | 1 |
"""
Custom exceptions used for reporting back various errors back to the workflow.
"""
import abc
class _AbstractMcWorkflowError(Exception, metaclass=abc.ABCMeta):
"""Abstract exception."""
pass
class McProgrammingError(_AbstractMcWorkflowError):
"""
Exception thrown on programming errors.
It'... | Python | 1 |
nchunks=创建块数,
total=创建数量,
bordermode=边界模式,
)
def 数组_索引取值(items, indices, default=ub.util_const.NoParam):
return ub.util_list.take(items, indices, default)
def 数组_逻辑取值(items, flags):
return ub.util_list.compress(items, flags)
def 数组_转平面(items):
return ub.util_list.f... | Python | 1 |
anyhow::format_err!("The table `{}` could not be found.", table)
}
pub(crate) fn non_existent_dependency_err(name: impl Display, table: impl Display) -> Error {
anyhow::format_err!(
"The dependency `{}` could not be found in `{}`.",
name,
table,
)
}
pub(crate) fn invalid_cargo_config(... | Rust | 0 |
productPrice: str = "//div[@class='inventory_item_price']";
addToCartButton: str = "//button[text()='Add to cart']";
sortDropDown: str = "//select[@class='product_sort_container']";
cartIcon: str = "//a[@class='shopping_cart_link']"; | Python | 1 |
.34124e+02, 5.06171e+02, 4.80985e+02, 4.63139e+02,
4.39482e+02, 4.13122e+02, 3.94543e+02, 3.75591e+02, 3.56069e+02, 3.35294e+02, 3.16374e+02, 2.98712e+02, 2.82737e+02, 2.69581e+02,
2.49433e+02, 2.36936e+02, 2.21403e+02, 2.04770e+02, 1.87379e+02, 1.75880e+02, 1.60408e+02, 1.46210e+02, 1.36438e+02, 1.24... | Python | 1 |
<(Scalar, Scalar)> = (0..SAMPLES)
.map(|_| (Scalar::random(&mut rng), Scalar::random(&mut rng)))
.collect();
let mut count = 0;
b.iter(|| {
let mut tmp = v[count].0;
tmp += &v[count].1;
count = (count + 1) % SAMPLES;
tmp
});
}
#[bench]
fn bench_scalar_sub_as... | Rust | 0 |
reponame>lichuang/databend
// Copyright 2021 <NAME>.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicab... | Rust | 0 |
/ Unchecked extrinsic type as expected by the runtime.
pub type UncheckedExtrinsic<C, R> =
generic::UncheckedExtrinsic<AccountId, C, Signature, SignedExtra<R>>;
mod chunk_type;
mod chunk;
mod png;
mod secretpng;
pub type Error = Box<dyn std::error::Error>;
pub type Result<T> = std::result::Result<T, Error>;
use s... | Rust | 0 |
= " @param qinfo"]
#[doc = " A pointer to a structure of type *rte_eth_rxq_info_info* to be filled with"]
#[doc = " the information of the Ethernet device."]
#[doc = ""]
#[doc = " @return"]
#[doc = " - 0: Success"]
#[doc = " - -ENOTSUP: routine is not supported by the device PMD."]
... | Rust | 0 |
[cfg(feature = "dim2")]
fn highlight_hovered_body(
_materials: &mut Assets<StandardMaterial>,
_graphics_manager: &mut GraphicsManager,
_testbed_state: &mut TestbedState,
_physics: &PhysicsState,
_window: &Window,
_camera: &Camera,
_camera_transform: &GlobalTransform,
) {
// Do nothing fo... | Rust | 0 |
# mlp layers
for linear in self.linears:
hidden = torch.relu(linear(hidden))
# get mu and sigma
y_pred = self.final_projection(hidden)
y_mu, y_sigma = torch.split(y_pred, (self.dim_y, self.dim_y), -1) # noqa: WPS221
y_sigma = functional.softplus(y_sigma) + min_... | Python | 1 |
ress, b"glEndQuery\0", &glEndQuery_p)
}
/// Checks if the pointer for [`glEndQuery`] is loaded (non-null).
#[inline]
#[doc(hidden)]
pub fn glEndQuery_is_loaded() -> bool {
!glEndQuery_p.load(RELAX).is_null()
}
/// [glEndTransformFeedback](http://docs.gl/es3/glEndTransformFeedback)()
#[cfg_attr(feat... | Rust | 0 |
mum number of single char bindings a scope may have
(single_char_binding_names_threshold, "single_char_binding_names_threshold": u64, 4),
/// Lint: BOXED_LOCAL. The maximum size of objects (in bytes) that will be linted. Larger objects are ok on the heap
(too_large_for_stack, "too_large_for_stack": u64, 200... | Rust | 0 |
# -*- python -*-
# This software was produced by NIST, an agency of the U.S. government,
# and by statute is not subject to copyright in the United States.
# Recipients of this software assume all responsibilities associated
# with its operation, modification and maintenance. However, to
# facilitate maintenance we as... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.