text string | label_name string | labels int64 |
|---|---|---|
�新的SS段寄存器设置为NULL段选择子是为了完成远跳转(far call或INT n或中断或异常),
/// 旧SS段寄存器和RSP将被保存在新栈中
#[derive(Debug, Clone, Copy)]
#[repr(C, packed)]
pub struct TaskStateSegment {
reserved_1: u32,
/// 64位 canonical型地址,栈指针(RSP),特权级Ring0-Ring2
pub privilege_stack_table: [VirtAddr; 3],
reserved_2: u64,
/// 64位 canonical型地址 中断栈... | Rust | 0 |
), |date| date.to_string());
if let Some(cost_basis) = &self.basis {
if self.date.is_some() {
date_str = format!(", {}", date_str);
}
match cost_basis {
CostBasis::Total(total_amount) => {
write!(f, "{{{{ {}{} }}}}", total_a... | Rust | 0 |
flog exists.
pub fn log_iter_rev<'b>(
&self,
buf: &'b mut [u8],
) -> Result<Option<log::iter::Reverse<'b, std::fs::File>>, loose::reflog::Error> {
// NOTE: Have to repeat the implementation of store::reflog_iter here as borrow_check believes impl Iterator binds self
use os_str_by... | Rust | 0 |
assets(&recipient_key).iter().map(|a| a.into()).collect::<Vec<AssetBundle>>();
assert_eq!(recipient_wallet.balance, 0);
assert_eq!(recipient_assets, vec![asset]);
let sender_wallet = api.get_wallet(&public_key);
let expected_balance = balance - transaction_fee;
let sender_assets = api.get_wallet_as... | Rust | 0 |
from __future__ import annotations
from typing import TYPE_CHECKING, cast
import pytest
from litestar import get
from litestar.testing import AsyncTestClient
if TYPE_CHECKING:
from litestar import Litestar
from litestar.stores.redis import RedisStore
from redis.asyncio import Redis as AsyncRedis
from... | Python | 1 |
__all__ = ('RoleManagerMetadataBooster',)
from scarletio import copy_docs
from .base import RoleManagerMetadataBase
from .constants import BOOSTER_KEY
class RoleManagerMetadataBooster(RoleManagerMetadataBase):
"""
Role manager metadata of a booster role.
"""
__slots__ = ()
@copy_docs(RoleMa... | Python | 1 |
::GeneratorWitness(..)
| ty::FnPtr(_)
| ty::RawPtr(_)
| ty::Str
| ty::Slice(_)
| ty::Dynamic(..) => bug!("no ValTree should have been created for type {:?}", ty.kind()),
}
}
#[instrument(skip(ecx), level = "debug")]
fn valtree_into_mplace<'tcx>(
ecx: &mut CompileTimeEval... | Rust | 0 |
xmax: f32,
ymin: f32,
ymax: f32,
zmin: f32,
zmax: f32,
) -> PerspectiveCamera {
let new_direction = linalg::normalize_v3(direction);
return PerspectiveCamera {
_xmin: xmin,
_xmax: xmax,
_ymin: ymin,
_ymax: ymax,
... | Rust | 0 |
3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15)
+ Send
+ Sync
+ 'static,
) -> Self {
Self(Box::new(val))
}
}
impl<
T1: Injectable,
T2: Injectable,
T3: Injectable,
T4: Injectable,
T5: Injectable,
T6: Injectable,... | Rust | 0 |
import requests
import string
import json
import config
import dns.resolver
def verify_domain(domain):
try:
resolver = dns.resolver.Resolver()
resolver.lifetime = 10
answer = resolver.resolve(domain, 'CNAME')
for rdata in answer:
cname = str(rdata.target)
if ... | Python | 1 |
};
use std::sync::{Arc, Mutex};
use std::{
any, net,
time::{Duration, SystemTime},
};
/// Default service name if no service is configured.
static DEFAULT_SERVICE_NAME: &str = "OpenTelemetry";
/// Default agent endpoint if none is provided
static DEFAULT_AGENT_ENDPOINT: &str = "127.0.0.1:6831";
/// Jaeger spa... | Rust | 0 |
class Node():
def __init__(self, val = 0):
self.val = val
self.left = None
self.right = None
def bintree2list(root):
"""
type root: root class
"""
if not root:
return root
root = bintree2list_util(root)
while root.left:
root = root.left
return roo... | Python | 1 |
Gcm {
key: [0x7fddb574, 0x53c241d0, 0x3efbed3a, 0xc44e371c],
iv: [0xee283a3f, 0xc75575e3, 0x3efd4887],
pt: &hex!("d5de42b461646c255c87bd2962d3b9a2"),
aad: &[],
ct: &hex!("2ccda4a5415cb91e135c2a0f78c9b2fd"),
tag: [0xb36d1df9, 0xb9d5e596, 0xf83e8b7f, 0x52971cb3],
},... | Rust | 0 |
"""Position feed-forward network from "Attention is All You Need"."""
import torch.nn as nn
class PositionwiseFeedForward(nn.Module):
""" A two-layer Feed-Forward-Network with residual layer norm.
Args:
d_model (int): the size of input for the first-layer of the FFN.
d_ff (int): the hidden l... | Python | 1 |
import os
import glob
import torch
import numpy as np
import imageio
import json
import torch.nn.functional as F
import cv2
def normalize(x):
return x / np.linalg.norm(x)
def load_tankstemple_data(basedir, movie_render_kwargs={}):
pose_paths = sorted(glob.glob(os.path.join(basedir, 'pose', '*txt')))
rgb_... | Python | 1 |
{
VBATSCMP_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> VBATSCMP_A {
match self.bits {
false => VBATSCMP_A::VALUE1,
true => VBATSCMP_A::VALUE2,
}
}
#[doc = "Checks if the v... | Rust | 0 |
from argparse import ArgumentParser
import subprocess
class DockerImageBuilder:
def __init__(self, args):
self.args = args
def build_docker_image(self):
# if a base image is not specified, we use the Ubuntu 18, CUDA 10 image from NVIDIA
docker_build_command = [
"docker",
... | Python | 1 |
body: Block,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Item {
Func(Func),
Type {
name: Ident,
methods: Vec<Func>
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Block(pub Vec<Expr>);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Ident(pub String);
#[derive(Debug, Clon... | Rust | 0 |
dden_state'],1,-1)
temp = []
for i in range(len(prompts)): temp.append(dist(text_embeddings[i], wordf_embeddings[0]).item())
idx_start = temp.index(max(temp))
prompt_tgt = prompt.replace(prompts[idx_start], word_t, 1)
idx_list = [i for i in range(77)]
is_added... | Python | 1 |
.into_iter()),
};
Self { kind }
}
}
enum IntoIterKind<'k, 'v> {
Small(iter::Take<std::array::IntoIter<Param<'k, 'v>, SMALL>>),
Large(std::vec::IntoIter<Param<'k, 'v>>),
}
impl<'k, 'v> Iterator for IntoIter<'k, 'v> {
type Item = (&'k str, &'v str);
fn next(&mut self) -> Option<Self... | Rust | 0 |
"""
Здесь хранится текст сообщений бота
"""
USER_MESSAGES: dict = {
"get_password": "Введите ваш пароль от аккаунта",
"start_survey_section_1": "Ответьте мне на несколько вопросов",
"start_survey_section_2": "В следующих вопросах нужно выбрать один из нескольких вариантов",
}
USER_COMMANDS: dict = {
"... | Python | 1 |
from pydantic import BaseModel, Field, StringConstraints
from typing import Annotated
def screen_writer_prompt(user_news: str) -> str:
return f"""
You are a realistic and concise TV news SCRIPTWRITER.
Task:
From the "User Input" (below), create a short news script simulating the following dynamic:
... | Python | 1 |
must_prewrite_put(&engine, k, v, k, 2);
must_locked(&engine, k, 2);
must_pessimistic_prewrite_put_err(&engine, k, v, k, 1, 1, false);
must_pessimistic_prewrite_put_err(&engine, k, v, k, 3, 3, false);
}
#[test]
fn test_non_pessimistic_lock_conflict_with_pessismitic_txn() {
... | Rust | 0 |
from beaver import BeaverDB
import time
def priority_queue_demo():
"""Demonstrates the persistent priority queue functionality."""
print("--- Running Priority Queue Demo ---")
db = BeaverDB("demo.db")
# Get a handle to a persistent priority queue named 'agent_tasks'
tasks = db.queue("agent_tasks")... | Python | 1 |
ak` and `continue`) in a `finally` block\
will most likely lead to undesired behavior.";
#[derive(Display)]
enum NoUnsafeFinallyMessage {
#[display(fmt = "Unsafe usage of break statement")]
Break,
#[display(fmt = "Unsafe usage of continue statement")]
Continue,
#[display(fmt = "Unsafe usage of return stateme... | Rust | 0 |
AL_CONTEXTVAR': 1,
'WITH_DOC_STRINGS': 1,
'WITH_DTRACE': 0,
'WITH_DYLD': 1,
'WITH_EDITLINE': 0,
'WITH_LIBINTL': 0,
'WITH_NEXT_FRAMEWORK': 0,
'WITH_PYMALLOC': 1,
'WITH_VALGRIND': 0,
'X87_DOUBLE_ROUNDING': 0,
'XMLLIBSUBDIRS': 'xml xml/dom xml/etree xml/parsers xml/sax',
'abs_builddir': '/private/var/folders/nz... | Python | 1 |
req, "disable", body)
self.assertEqual(res_dict['status'], 'disabled')
def test_services_disable_with_binary_key(self):
req = fakes.HTTPRequest.blank('/v1/fake/os-services/disable')
body = {'host': 'host1', 'binary': 'cinder-volume'}
res_dict = self.controller.update(req, "disable"... | Python | 1 |
from pwn import *
import re
import sys
elf = ELF("../dist/chall")
context.binary = elf
if len(sys.argv) == 2 and sys.argv[1] == "debug":
context.terminal = ["tmux", "neww"]
p = gdb.debug(elf.path, """
""")
else:
p = process("nc localhost 1337", shell=True)
problems = 1
def overflow(payload):
glo... | Python | 1 |
));
let comb2 = Combinator::new(Depth::new(2, Some(2)))
| Combinator::new(Simple::new(r#"{}"#).unwrap());
let comb3 = !comb1 & comb2;
assert!(!comb3.match_path(&Path::try_from(r#"{"People"}"#).unwrap(), ParsedKind::Arr));
assert!(!comb3.match_path(&Path::try_from(r#"[0]"#).u... | Rust | 0 |
(500, b)
});
c.bench_function("bytesrepr::deserialize_era_info", |b| {
deserialize_era_info(500, b)
});
}
criterion_group!(benches, bytesrepr_bench);
criterion_main!(benches);
<filename>crates/zen-msh/src/lib.rs<gh_stars>1-10
//! This crate can deserialize [.msh](Msh) (compiled meshes),
//! and con... | Rust | 0 |
),
false => Ok(()),
}
}
}
pub fn destroy(self, flags: u32) -> Result<(), VirError> {
unsafe {
match virt::virInterfaceDestroy(self.ptr, flags) == -1 {
true => Err(VirError::new()),
false => Ok(()),
}
}
... | Rust | 0 |
fn compress_lz4_fear(input: &[u8]) -> Vec<u8> {
let mut buf = Vec::new();
if input.len() <= 0xFFFF {
compress2(input, 0, &mut U16Table::default(), &mut buf).unwrap();
} else {
compress2(input, 0, &mut U32Table::default(), &mut buf).unwrap();
}
buf
}
fn bench_compression_throughput(c... | Rust | 0 |
double_to_fixed((b2 - b1) / (m2 - m1))
}
}
/// Get the intercept of a line containing the points (`x1`, `y1`) and (`x2`, `y2`) and the horizontal line at
/// `y`.
#[inline]
fn x_intercept_for_y(x1: Fixed, y1: Fixed, x2: Fixed, y2: Fixed, y: Fixed) -> Fixed {
// fast paths
if y1 == y {
return x1;
... | Rust | 0 |
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | ((value as u16 & 0x01) << 3);
self.w
}
}
#[doc = "Field `UCADDMASK4` reader - I2C Address Mask Bit 4"]
pub struct UCADDMASK4_R(crate::Fie... | Rust | 0 |
for x in range(4):
for y in range(3):
print(f"({x}, {y})")
numbers = [5,2,5,2,2] | Python | 1 |
grams(engine: &mut Engine) -> Status {
load_var(engine, "LDGRAMS", 16, false)
}
pub(super) fn execute_ldvarint16(engine: &mut Engine) -> Status {
load_var(engine, "LDVARINT16", 16, true)
}
pub(super) fn execute_ldvaruint32(engine: &mut Engine) -> Status {
load_var(engine, "LDVARUINT32", 32, false)
}
pub(sup... | Rust | 0 |
#!/usr/bin/env python
'''
Example of how to use the van Rossum metric.
The VanRossumMetric function, which is defined as a monitor and therefore works online,
computes the metric between every neuron in a given population. The present example show
the concept of phase locking: N neurons are driven by sinusoidal... | Python | 1 |
unsafe fn raw_mut_dptr(&self) -> *mut T {
self.dptr
}
}
impl<T> GPUDeviceExtent<T> for GPUDeviceSliceMem<T> where T: Copy {
fn len(&self) -> usize {
self.phsz
}
fn size_bytes(&self) -> usize {
self.phsz
}
}
impl<T> GPUDeviceAsyncMem<T> for GPUDeviceSliceMem<T> where T: Copy + 'static {
fn wai... | Rust | 0 |
sts/ui/07-query-with-added.rs");
t.compile_fail("tests/ui/08-query-filter-invalid.rs");
}
use crate::{BranchShape, ChildIndex, Level, Tree, VectorKey};
use glam::{const_ivec2, const_ivec3, const_uvec2, const_uvec3, IVec2, IVec3, UVec2, UVec3};
use ndshape::{
ConstPow2Shape2i32, ConstPow2Shape2u32, ConstPow... | Rust | 0 |
affine=affine),
6: lambda c_in, c_out, stride, shape, affine: DilSepConv(c_in, c_out, 5, stride, 4, 2, shape, affine=affine),
7: lambda c_in, c_out, stride, shape, affine: DilSepConv(c_in, c_out, 7, stride, 6, 2, shape, affine=affine),
8: lambda c_in, c_out, stride, shape, affine: AvgPool(3, stride, 1),
... | Python | 1 |
_id);
room.forget(user_id)?;
}
let bot_user_id = self.config.matrix_bot_user_id()?;
let message = t!(["admin_room", "room_successfully_unbridged"]).with_vars(vec![("rocketchat_room_name", name.clone())]);
self.matrix_api.send_text_message(self.admin_room.id.clone(), bot_user... | Rust | 0 |
}
#[test]
fn shufpd_2() {
run_test(&Instruction { mnemonic: Mnemonic::SHUFPD, operand1: Some(Direct(XMM4)), operand2: Some(IndirectScaledIndexed(ECX, ECX, Two, Some(OperandSize::Xmmword), None)), operand3: Some(Literal8(61)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: No... | Rust | 0 |
index.
pub fn SDL_GetTouchFinger(
touchID: SDL_TouchID,
index: ::std::os::raw::c_int,
) -> *mut SDL_Finger;
}
pub type SDL_GestureID = Sint64;
extern "C" {
/// \brief Begin Recording a gesture on the specified touch, or all touches (-1)
///
///
pub fn SDL_RecordGesture(touchId:... | Rust | 0 |
# Copyright 2022 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | Python | 1 |
import sys
from telebot import types
def call_page(app_path,command):
sys.path.insert(1, app_path + '/storage/temp/telegram_bot')
import info_bot_tg
import info_user_tg
sys.path.insert(1, app_path + '/storage/temp/global')
import init_classes
sys.path.insert(1, app_path + '/storage/temp/bet_... | Python | 1 |
l) = pin_info.url {
pin.urls = vec![url];
}
if let Some(description) = pin_info.description {
pin.description = description;
}
if let Some(tags) = pin_info.tags {
pin.tags = tags
.chars()
.map(|c| c.to_lowercase().collect::<String>())
.collect:... | Rust | 0 |
import fnmatch
import os
import torch
from src.constrained_generation_config import ConstrainedGenerationConfig
from src.constraints.constraint import Constraint
from src.constraints.gradient_mixer import noise_weighting, snr
from src.constraints.real_logic import Product as Logic
from src.models.score_based.sdes.sam... | Python | 1 |
from mlflow.exceptions import MlflowException
from mlflow.protos import databricks_pb2
from mlflow.tracking.client import MlflowClient
from mlflow.tracking.default_experiment.abstract_context import DefaultExperimentProvider
from mlflow.utils import databricks_utils
from mlflow.utils.mlflow_tags import (
MLFLOW_EXP... | Python | 1 |
,
quote_amount: &T::Balance,
) -> Result<(T::Balance, Fee<T::AssetId, T::Balance>, Fee<T::AssetId, T::Balance>), DispatchError>
{
let pool_base_aum = T::Assets::balance(pool_info.pair.base, pool_account);
let pool_quote_aum = T::Assets::balance(pool_info.pair.quote, pool_account);
let total_lp_issued = T::As... | Rust | 0 |
}
self.fields.limit.replace(limit);
Ok(self)
}
/// Filter audit log for entries from a user.
///
/// This is the user who did the auditable action, not the target of the auditable action.
pub fn user_id(mut self, user_id: UserId) -> Self {
self.fields.user_id.replace(us... | Rust | 0 |
) {
unsafe {
SDL_FreeCursor(self.ptr);
}
}
}
impl Cursor {
pub fn default() -> Result<Cursor> {
let ptr = unsafe { SDL_GetDefaultCursor() };
if ptr.is_null() {
Err(SdlError::get())
} else {
Ok(Cursor { ptr })
}
}
pub f... | Rust | 0 |
plates: Linked to different source")
except (OSError, RuntimeError):
click.echo("❌ Project templates: Broken symlink")
elif self.templates_link.exists():
click.echo("⚠️ Project templates: Directory exists (not vTeam managed)")
else:
click.echo("❌ Proje... | Python | 1 |
країнська",
Vietnamese => "Tiếng Việt",
}
}
}
impl Display for Language {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}
impl FromStr for Language {
type Err = LangParseError;
/// String slice to Language.
/// Native names ... | Rust | 0 |
<u8>;
pub type Payload = SerializedBatch;
impl Mempool {
pub fn spawn(
// The public key of this authority.
name: PublicKey,
// The committee information.
committee: Committee,
// The configuration parameters.
parameters: Parameters,
// The persistent storage... | Rust | 0 |
86-linux-gnu.so', 'x86_64-linux-gnux32.so', 'i386-linux-musl.so'
else: # 8 byte pointer size
expected_suffixes = 'x86_64-linux-gnu.so', 'x86_64-linux-musl.so'
self.assertTrue(suffix.endswith(expected_suffixes),
f'unexpected suffix {suffix!r}')
@un... | Python | 1 |
s sent by the client or browser as the origin of the request. It is set through an `Origin` header. * **Access-Control-Allow-Methods**: This specifies the allowed options for requests from that domain. This will generally be all available methods. * **Access-Control-Expose-Headers**: This will contain the headers t... | Python | 1 |
e self::input_state::InputState;
use self::tetromino::{Piece, PieceType};
use self::ui_element::{UIBlockView, UITextView};
use self::well::Well;
use crate::states::game_over_state::{GameEndMode, GameEndState};
use crate::states::{Assets, State, Transition};
use crate::util::{play_click_sfx, DurationExt};
use ggez::even... | Rust | 0 |
x_byte() {
let r: &[u8] = b"";
let mut cpu = super::CPU::new(r);
cpu.execute_instruction((6, 2, 0xE, 0xA));
assert_eq!(cpu.v[2], 0xEA);
}
#[test]
fn add_vx_byte() {
let r: &[u8] = b"";
let mut cpu = super::CPU::new(r);
cpu.v[2] = 0x22;
cpu.exe... | Rust | 0 |
((0, 1, 2, 3, 4, 5, 6, 7),),
/// );
///
/// assert_eq!(
/// path_tuple!(0, 1, 2, 3, 4, 5, 6, 7, 8),
/// ((0, 1, 2, 3, 4, 5, 6, 7), (8,)),
/// );
///
/// assert_eq!(
/// path_tuple!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15),
/// (
/// (0, 1, 2, 3, 4, 5, 6, 7),
/// (8, 9, ... | Rust | 0 |
import socket
# look 'client.py', everything is identical except the order of received data, which is arbitrary
SERVER_ADD = '127.0.0.1'
SERVER_PORT = 21371
CLIENT_ADD = '127.0.0.1'
CLIENT_PORT = 21372
TRANSPORT_PROT = socket.SOCK_DGRAM # UDP
IP_FAM = socket.AF_INET # IPv4
serverSocket = socket.socket(family=IP_FAM, ... | Python | 1 |
import heapq
def solution(N, road, K):
# ➊ 각 노드에 연결된 간선들을 저장할 리스트
graph = [[] for _ in range(N + 1)]
# ➋ 출발점에서 각 노드까지의 최단 거리를 저장할 리스트
distances = [float("inf")] * (N + 1)
distances[1] = 0 # 출발점은 0으로 초기화
# ➌ 그래프 구성
for a, b, cost in road:
graph[a].append((b, cost))
graph[b].append((a, cost))
... | Python | 1 |
# This script fuses all the font images into the UIMG1.BIN
# Author: HiroshiYa
from time import sleep
from PIL import Image
import os
import numpy as np
def error_trap():
# while True:
# sleep(1E6)
quit()
return
def index_fuser(red, green):
# 1. Takes the rgb info from the red font image and the ... | Python | 1 |
# 파스칼 표기법 - 맨 앞글자만 대문자(JAVA의 class 생성 시 활용)
# 카멜 표기법 - 단어의 의미가 있는 첫글자를 대문자로 한다.(shopList)
# 스네이크 표기법 - 단어간의 구분을 _로 한다.(shop_list)
# - 파이썬에서 스네이크 표기법을 제일 많이 사용
# 리스트 생성 방법 1 - 비어있는 리스트로 생성
a = []
# 파이썬에서는 크기가 없다 무한하다.
# 리스트 생성 방법 2 - 값이 있는 리스트로 생성
shop_list = ['apple','mango','carrot','banana']
print(f'shop_list ... | Python | 1 |
s = int(len(ori_data['期数'].unique()) * n / 100)
if n > 100:
n_samples = 1
test_list = sorted(ori_data['期数'].drop_duplicates().sample(n_samples).tolist())
if n > 100:
_n_samples = int(len(ori_data['期数'].unique()) * (n - 100) / 100)
while int(ori_data[ori_data['... | Python | 1 |
import ctypes
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Load the compiled shared library
lib = ctypes.CDLL('./func.so') # Ensure you have compiled the C code as a shared library
SAMPLES = 100000
L = 0.001 # Inductance in Henry
Amp = 10.0
alpha = 0.5
TimePeriod = 0.... | Python | 1 |
convert_latin1_to_utf16(&src[..], &mut dst[..]);
assert_eq!(dst, reference);
}
//#[test]
pub fn test_convert_latin1_to_utf8_partial() {
let mut dst = [0u8, 2];
let (read, written) = convert_latin1_to_utf8_partial(b"a\xFF", &mut dst[..]);
assert_eq!(read, 1);
assert_eq!(written, 1);
}
//#[test]
p... | Rust | 0 |
# Pyrofork - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-present Dan <https://github.com/delivrance>
# Copyright (C) 2022-present Mayuri-Chan <https://github.com/Mayuri-Chan>
#
# This file is part of Pyrofork.
#
# Pyrofork is free software: you can redistribute it and/or modify
# it under ... | Python | 1 |
, |r| {
r.route().a(|_| {
Delay::new(Instant::now() + Duration::from_millis(10))
.and_then(|_| Ok(HttpResponse::Ok()))
})
})
})
});
let request = srv.get().uri(srv.url("/scope/test")).finish().un... | Rust | 0 |
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import MetaData
from sqlalchemy_serializer import SerializerMixin
metadata = MetaData(naming_convention={
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
})
db = SQLAlchemy(metadata=metadata)
class Bakery(db.Model, SerializerMixin):
... | Python | 1 |
#\!/usr/bin/env python
import sys
from ansari.agents.ansari_claude import AnsariClaude
from ansari.config import get_settings
def test_message_structure():
"""Test that message history conversion works properly."""
settings = get_settings()
agent = AnsariClaude(settings)
# Setup test message his... | Python | 1 |
{
array_init::array_init(|_| self.sample(modulus))
}
fn sample_range_array<const L: usize>(&mut self, low: &BigInt, high: &BigInt) -> [BigInt; L] {
array_init::array_init(|_| self.sample_range(low, high))
}
}
<filename>src/open_pipe/alarm_data.rs
use crate::open_pipe::connection::NotifyAla... | Rust | 0 |
]]:
"""
The port group type. Can be one of `earlyBinding` (static
binding) or `ephemeral`. Default: `earlyBinding`.
"""
return pulumi.get(self, "type")
@_builtins.property
@pulumi.getter(name="uplinkTeamingOverrideAllowed")
def uplink_teaming_override_allowed(self) -... | Python | 1 |
static mut STORM_VISIBLE_SPOOFED_GAME: Option<bw::SnpGameInfo> = None;
struct State {
spoofed_game: Option<bw::SnpGameInfo>,
spoofed_game_dirty: bool,
current_client_info: Option<bw::ClientInfo>,
messages: Vec<ReceivedMessage>,
}
lazy_static! {
static ref STATE: Mutex<State> = Mutex::new(State {
... | Rust | 0 |
will be refined later
gq: 0.0,
genotype_post: GenotypeProbs::uniform(2),
phase_set: None,
mec: 0, // mec for variant
mec_frac_variant: 0.0, // mec fraction for this variant
mec_frac_... | Rust | 0 |
5),
line_color="coral",
marker=dict(
opacity=1,
size=np.linspace(19, 1, len(intercepts[::step_size])),
line=dict(width=2, color="DarkSlateGrey"),
),
name="Descent Path",
)
)
fig.add_trace(
go.Scatter(... | Python | 1 |
bob_evm_addr()
),
Ok(90)
);
assert_err!(
EvmBridgeModule::transfer(
InvokeContext {
contract: erc20_address(),
sender: bob_evm_addr(),
origin: bob_evm_addr(),
},
alice_evm_addr(),
100
),
Error::<Runtime>::ExecutionRevert
);
});
}
<filename>src/log_gr... | Rust | 0 |
1_dec_refpass_step_mqc_macro(
flagsp, data, l_w, 1,
mqc, &mut v, poshalf);
opj_t1_dec_refpass_step_mqc_macro(
flagsp, data, l_w, 2,
mqc, &mut v, poshalf);
opj_t1_dec_refpass_step_mqc_macro(
flagsp, data, l_w, 3,
mqc,... | Rust | 0 |
d", "aziot-identityd"),
("aziot-edged", "aziot-edged"),
("docker", "docker"),
];
/// # Errors
///
/// Will return `Err` if unable to collect support bundle
pub async fn make_bundle(
output_location: OutputLocation,
log_options: LogOptions,
include_ms_only: bool,
verbose: bool,
iothub_hostna... | Rust | 0 |
from enum import Enum
class Color(Enum):
kWhite = 0
kRed = 1
kGreen = 2
class Solution:
def isBipartite(self, graph: List[List[int]]) -> bool:
colors = [Color.kWhite] * len(graph)
def isValidColor(u: int, color: Color) -> bool:
# The painted color should be same as the `color`
if colors... | Python | 1 |
import torch
from gxtb.basis.qvszp import AtomBasis, ShellDef
from gxtb.hamiltonian.overlap_tb import build_overlap
class DummyBasis(AtomBasis):
pass
def build_basis(l_list, atoms=1):
shells=[]; ao_counts=[]; ao_offsets=[]; nao=0
for a in range(atoms):
for l in l_list:
shells.append(Sh... | Python | 1 |
bound(t).await
}
async fn do_stream_trees_chunked_reverse_should_honour_an_inclusive_upper_bound(
t: TestTree,
) -> anyhow::Result<TestResult> {
let (builder, forest, xs) = t.builder()?;
let len = xs.len() as u64;
if len == 0 {
return Ok(TestResult::discard());
}
let trees = stream::onc... | Rust | 0 |
.volume}%`")
await player.set_volume(percentage)
await ctx.success(f"Set **volume** to `{percentage}%`")
@commands.command(name="disconnect", aliases=["dc", "stop"])
async def disconnect(self, ctx: Context):
"""Disconnect the music player"""
player: Player = await self.get_playe... | Python | 1 |
import numpy as np
import pdb
def bbox_iou(b1, b2):
'''
b: (x1,y1,x2,y2)
'''
lx = max(b1[0], b2[0])
rx = min(b1[2], b2[2])
uy = max(b1[1], b2[1])
dy = min(b1[3], b2[3])
if rx <= lx or dy <= uy:
return 0.
else:
interArea = (rx-lx)*(dy-uy)
a1 = float((b1[2] - b... | Python | 1 |
}
}
}
}
// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crypto::{signing::generate_genesis_keypair, PublicKey};
use types::{account_address::AccountAddress, transaction::SignedTransaction};
pub struct TransactionMetadata {
pub sender: AccountAddress,
... | Rust | 0 |
DELAY"]
#[inline(always)]
pub fn data_delay(&self) -> DATA_DELAY_R {
DATA_DELAY_R::new(((self.bits >> 8) & 0xff) as u8)
}
#[doc = "Bit 7 - MEM_LEN_24"]
#[inline(always)]
pub fn mem_len_24(&self) -> MEM_LEN_24_R {
MEM_LEN_24_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc =... | Rust | 0 |
gravity = 8;
pub const ZXDG_POSITIONER_V6_GRAVITY_LEFT: zxdg_positioner_v6_gravity = 4;
pub const ZXDG_POSITIONER_V6_GRAVITY_BOTTOM: zxdg_positioner_v6_gravity = 2;
pub const ZXDG_POSITIONER_V6_GRAVITY_TOP: zxdg_positioner_v6_gravity = 1;
pub const ZXDG_POSITIONER_V6_GRAVITY_NONE: zxdg_positioner_v6_gravity = 0;
pub ty... | Rust | 0 |
izer.zero_grad()
loss.backward()
self.optimizer.step()
print("【train】 epoch:{}/{} step:{}/{} loss:{:.6f}".format(
epoch, self.args.epochs, gloabl_step, self.args.total_step, loss.item()
))
gloabl_step += 1
... | Python | 1 |
x, _)) = closest_to(c, &landmarks) {
if skip[idx] {
continue;
}
spaces_closest[idx] += 1;
}
}
}
*spaces_closest.iter().max().unwrap()
}
#[solution(part2,
example_input = generator(EXAMPLE),
example = 5554416)]
fn pa... | Rust | 0 |
standard classification.
#[derive(PartialEq, Debug, YaSerialize, YaDeserialize)]
pub enum ColorPaletteType {
Custom,
Grayscale,
BlackHot,
WhiteHot,
Sepia,
Red,
Iron,
Rain,
Rainbow,
Isotherm,
__Unknown__(String),
}
impl Default for ColorPaletteType {
fn default() -> Color... | Rust | 0 |
StrRef;
use crate::loc::{Loc, Located};
use crate::statics::ck::ty;
use crate::statics::ck::util::{env_ins, env_merge, get_env, get_val_info, instantiate};
use crate::statics::types::{
Con, Cx, Error, Item, Pat, Result, Span, State, Sym, Ty, TyScheme, Tys, ValEnv, ValInfo,
};
use maplit::btreemap;
use std::collection... | Rust | 0 |
self.safes \
and (row, col) not in self.mines:
neighbors.append((row, col))
if (row, col) in self.mines:
count -= 1
return neighbors, count
def remove_dups(self):
unique_knowledge = []
for s in self.knowledge:
... | Python | 1 |
import cv2
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
# Log images
def log_input_image(x, opts):
if opts.label_nc == 0:
return tensor2im(x)
elif opts.label_nc == 1:
return tensor2sketch(x)
else:
return tensor2map(x)
def tensor2im(var):
var = var.cpu().detach().transpose(0, 2)... | Python | 1 |
data(ClipboardFormat::Bitmap).map(|h| HBITMAP(h.0))?;
let bitmap_info = Self::get_clipboard_data(ClipboardFormat::BitmapInfo)
.and_then(|handle| unsafe { LockedPtr::<BITMAPINFO>::new(handle) })?;
format::bitmap::get(hbitmap, bitmap_info).map(Some)
}
pub fn empty(&self) -> Result<()> {
if !unsafe { EmptyClip... | Rust | 0 |
};
Submissions::create(new_submission, &connection);
}
}
Ok(Json(json!({"status":200})))
}
Role::Teacher => match create_classuser::<Teacher>(&key.0, &class_id, &connection) {
Ok(... | Rust | 0 |
val & vk::FORMAT_FEATURE_COLOR_ATTACHMENT_BIT) != 0,
color_attachment_blend: (val & vk::FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT) != 0,
depth_stencil_attachment: (val & vk::FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT) != 0,
blit_src: (val & vk::FORMAT_FEATURE_BLIT_SRC_BIT) != 0,
... | Rust | 0 |
ebate_agents, all_thinking[-1])],
[f"{agent.role}'s final answer: {answer}" for agent, answer in zip(self.debate_agents, all_answers[-1])],
mode="code_fill"
)
return final_result['solution'], self.llm.cost_manager.total_cost
if __name__ == "__main__":
async def main():
... | Python | 1 |
,
concat!(
"Offset of field: ",
stringify!(__dc1394featureset_t),
"::",
stringify!(feature)
)
);
}
pub type dc1394featureset_t = __dc1394featureset_t;
extern "C" {
#[doc = " Collects the available features for the camera described by node and store... | Rust | 0 |
oduleSpecifier>,
_is_dynamic: bool,
) -> Pin<Box<deno_core::ModuleSourceFuture>> {
let module_specifier = module_specifier.clone();
let is_data_uri = get_source_from_data_url(&module_specifier).ok();
let code = if let Some((ref source, _)) = is_data_uri {
source.to_string()
} else {
se... | Rust | 0 |
p, mjvpc
aagrt (35) -> isrqnr, fvvrow, fuzizpc
zwprtx (5)
vzgukn (279) -> fcxdhb, xxswx
wbxcy (27)
njoqwl (12)
rgnjr (47)
ejkioj (25)
yatllw (107) -> palczfm, jgxph
ibokijo (145) -> vbutj, hpcncb
qopbuhe (33)
rkujtq (7)
qizgiau (275)
ysuoctn (88)
ntmldq (301) -> ocsqis, xtmjhz
sahdqia (19)
hviil (3327) -> xvafyvk, jqjz... | Rust | 0 |
//! |-----------|-----------------|------------------|
//! | [Louds::from::<&str>()](https://laysakura.github.io/louds-rs/louds_rs/louds/struct.Louds.html#implementations) | _O(N)_ | _N + o(N)_ |
//! | [Louds::from::<&[bool]>()](https://laysakura.github.io/louds-rs/louds_rs/louds/struct.Louds.html#implementations) | _... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.