text string | label_name string | labels int64 |
|---|---|---|
rate::builder::Step::Comment(text));
});
// expr
let child = children.get_next().unwrap();
steps.push_back(crate::builder::Step::NewLine);
steps.push_back(crate::builder::Step::Pad);
steps.push_back(crate::builder::Step::FormatWider(child.element)... | Rust | 0 |
def pairwise_ioa(boxes1: Boxes, boxes2: Boxes) ->torch.Tensor:
"""
Similar to :func:`pariwise_iou` but compute the IoA (intersection over boxes2 area).
Args:
boxes1,boxes2 (Boxes): two `Boxes`. Contains N & M boxes, respectively.
Returns:
Tensor: IoA, sized [N,M].
"""
area2 = b... | Python | 1 |
from django.test import TransactionTestCase
from localflavor.np.forms import NPDistrictSelect, NPPostalCodeFormField, NPProvinceSelect, NPZoneSelect
from .selectfields_html import districts_select, provinces_select, zones_select
from .models import NepalianPlace
class NepalDetails(TransactionTestCase):
"""
... | Python | 1 |
th
pub text: Option<String>,
}
#[derive(FromArgs, Debug, PartialEq)]
#[argh(subcommand, name = "list", description = "list connected devices")]
pub struct ListCommand {
#[argh(positional)]
pub nodename: Option<String>,
}
#[derive(FromArgs, Debug, PartialEq)]
#[argh(subcommand, name = "run-component", desc... | Rust | 0 |
let result = self.data as u8;
self.data >>= 8;
self.len -= 8;
Ok(result)
} else {
Err(())
}
}
pub(crate) fn insert_and_extract_byte(&mut self, byte: u8) -> u8 {
if self.len <= 64 - 8 {
self.data += u64::from(byte) << self.... | Rust | 0 |
import arxiv
import torch
import torch.nn.functional as F
from transformers import AutoTokenizer, AutoModel, DebertaV2Tokenizer, DebertaV2Model
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
import re
from sentence_transformers import SentenceTransformer
# 1. 学術論文データの取得(arXiv API を利用)
def fe... | Python | 1 |
}
#[test]
fn blocks_count() {
let mut testkit = DmbcTestApiBuilder::new()
.create();
let api = testkit.api();
let count = 2;
testkit.create_block();
testkit.create_block();
testkit.create_block();
testkit.create_block();
let (status, response): (StatusCode, BlocksResponse) = ... | Rust | 0 |
mut texture_atlases: ResMut<Assets<TextureAtlas>>,
asset_server: Res<AssetServer>,
) {
let bike_tex = asset_server.load("textures/rival_atlas.png");
let bike_atlas = RIVAL_SPRITE_DESC.make_atlas(bike_tex);
let bike_atlas_handle = texture_atlases.add(bike_atlas);
let rival_assets = RivalAssets {... | Rust | 0 |
from SuffixTreeConstruction import tree_construction
from typing import Dict, List, Tuple
def find_longest_repeated_substring(text1: str, text2: str) -> List[str]:
def dfs(tree_dictionary_: Dict[int, Dict[int, Tuple[int, int]]], text1_: str, text2_: str, current_node_: int, current_string_: str, strings: List... | Python | 1 |
unsafe { self.user.deref_with_lifetime() };
// f(user)
// }
}
impl<'a, Owner: 'a, U> Deref for SRS<Owner, U>
where
U: for<'b> DerefWithLifetime<'b>,
{
type Target = Owner;
#[inline]
fn deref(&self) -> &Self::Target {
self.owner.deref()
}
}
// technically default drop is safe ... | Rust | 0 |
ck((kgrid.ky.T, kgrid.kx.T))
def print_grid_size(kgrid):
"""
update command line status
Args:
kgrid:
Returns:
"""
k_Nx, k_Ny, k_Nz = kgrid.Nx, kgrid.Ny, kgrid.Nz
if kgrid.dim == 1:
logging.log(logging.INFO, f" computational grid size: {k_Nx} grid points")
elif kg... | Python | 1 |
we
# generate such as ik-to-fk converted rigs
objects = list(bpy.context.scene.objects)
for obj in objects:
bpy.context.view_layer.objects.active = obj
if obj.type == 'MESH':
bpy.ops.import_export.mesh2json()
if obj.type == 'ARMATURE':
bpy.ops.rigging.iktofk()
bpy.ops.import_export.armatu... | Rust | 0 |
"""Adhocracy backend customization package."""
import os
import version
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.rst')).read()
CHANGES = open(os.path.join(here, 'CHANGES.rst')).read()
requires = ['adhocracy_core',
... | Python | 1 |
_modules);
module_defs(context, modules);
match build_ordering(context) {
Err(cycle_node) => {
let cycle_ident = cycle_node.node_id().clone();
report_cycle(context, cycle_ident)
}
Ok(ordered_ids) => {
let ordering = ordered_ids
.into_it... | Rust | 0 |
::UiState;
use std::ops::Deref;
use log::error;
use crate::friends::{FriendData, FriendsApiClient};
mod api;
mod clears;
mod workers;
mod settings;
mod ui;
mod translations;
mod updates;
mod input;
mod friends;
mod urls;
const SETTINGS_FILENAME: &str = "addons/arcdps/settings_clears.json";
const TRANSLATION_FILENAME... | Rust | 0 |
)
x = self.weight_layer2(x)
x = self.weight_layer3(x)
if self.upsample is not None:
identity = self.upsample(identity)
elif self.down_scale is not None:
identity = self.down_scale(identity)
x = x + identity
return x
if __name__ == "__main__":
... | Python | 1 |
running.
This test directly tests parts of the code without actually awaiting the task.
"""
from basic_memory.api.routers.management_router import WatchStatusResponse
# Create a response object directly
response = WatchStatusResponse(running=False)
# We're just testing that the response model... | Python | 1 |
d_name.to_string());
}
let bound_type = match bound_type_text {
"FR" => BoundType::Free,
"MI" => BoundType::LowerMinusInfinity,
"PL" => BoundType::UpperInfinity,
"BV" => BoundType::Binary,
"LO" | "UP" | "FX" | "LI" | "UI" => {
let [value_text] = CR::four(rest... | Rust | 0 |
(&mut self) -> io::Result<()> {
match *self {
Connection::LinuxUdp(_) => Ok(()),
Connection::LinuxTcp(ref mut s) => s.flush(),
Connection::RuntimeUdp(ref mut s) => s.flush(),
Connection::RuntimeTcp(ref mut s) => s.flush(),
}
}
}
pub enum JoinHandle<T:... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
一进二低吸战法策略入口文件
用于运行一进二低吸战法策略,包括初始化交易环境、启动策略、注册回调函数等。
"""
import os
import sys
import time
from datetime import datetime
import traceback
# 添加项目根目录到系统路径
root_path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.insert(0, root_pat... | Python | 1 |
nly compile slog in when logging features are enabled?
fn slog(name: &str, version: &str) -> slog::Logger {
use slog::Drain;
#[cfg(not(any(feature = "syslog", feature = "journald")))]
let drain = slog::Drain::Discard;
#[cfg(feature = "syslog")]
let drain = slog_syslog::SyslogBuilder::new()
... | Rust | 0 |
"""
性能监控器 - 监控系统性能指标
"""
import time
import psutil
import asyncio
from typing import Dict, List, Any, Optional
from collections import deque, defaultdict
from dataclasses import dataclass
from app.utils.logger import setup_logger
logger = setup_logger(__name__)
@dataclass
class RequestMetrics:
"""请求指标"""
ti... | Python | 1 |
oord: Option<usize>,
) {
if let Some(i) = coord {
let other_entity = entities.get(i).unwrap();
commands
.spawn()
.insert(VerletStick {
point_a_entity: entity,
point_b_entity: *other_entity,
length,
})
.in... | Rust | 0 |
_types};
use nix::libc;
use crate::process::{io_error_to_process_error, ProcessError, ProcessResult};
use crate::Pid;
#[allow(non_camel_case_types)]
type caddr_t = *const libc::c_char;
#[allow(non_camel_case_types)]
type segsz_t = i32;
#[repr(C)]
#[derive(Copy, Clone)]
pub struct kinfo_proc {
pub kp_proc: extern_pr... | Rust | 0 |
/
/// `AsyncReader` is an individual iterator and it doesn't use `None` to indicate that the iteration is
/// finished. You can expect additional `Some(InputEvent)` after calling `next` even if you have already
/// received `None`.
///
/// # Notes
///
/// * It requires enabled raw mode (see the
/// [`crossterm_screen... | Rust | 0 |
Args,
) -> BoxFuture<'a, Result<()>> {
async move {
for device in devices.iter() {
if device.hub_id == hub_id {
let depth = device.depth.lock().unwrap().unwrap().clone();
match list_device(&device.device, device.devnum, depth, max_depth, args).await {
... | Rust | 0 |
fn validate<W, E>(&self, mut warn: W, _err: E) -> bool
where
W: FnMut(&str),
E: FnMut(&str),
{
if self.a > 10 {
warn("a is greater than 10");
}
true
}
}
struct V1Validator;
impl<'a> Validator<'a> for V1V... | Rust | 0 |
"""
===============
Hinton diagrams
===============
Hinton diagrams are useful for visualizing the values of a 2D array (e.g.
a weight matrix): Positive and negative values are represented by white and
black squares, respectively, and the size of each square represents the
magnitude of each value.
Initial idea from D... | Python | 1 |
import subprocess # nosec B404
import pytest
import logging
import sys
from test_cli_image import run_wwb, get_similarity
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def run_test(model_id, model_type, optimum_threshold, genai_threshold, tmp_path):
if sys.platform == 'darwin':
... | Python | 1 |
float, float],
name: str = "",
): ...
@overload
def add_linear_constraint(
self,
con: ComparisonConstraint,
name: str = "",
): ...
def add_linear_constraint(self, arg, *args, **kwargs):
if isinstance(arg, ComparisonConstraint):
return self._add_l... | Python | 1 |
import pandas as pd
from sklearn.model_selection import train_test_split
input_path = 'mydata_2/output_all.csv' # 带划分数据
out_dir = 'mydata_2' # 划分后数据保存目录
train_ratio = 0.7 # 训练集占比
out_names = ["train", "val", "test"]
out_path = [out_dir + "/" + out_names[i] + "_all.csv" for i ... | Python | 1 |
restricted_words = {
"Гомик",
"гомосек",
"Нигер",
"негр",
"Хохол",
"укроп",
"Жид",
"Хач",
"Петух",
"Глиномес",
"Черножопый",
"черномазый",
"Чурка",
"Инцел",
"Симп",
"Девственник",
}
| Python | 1 |
dbackMessage) -> None:
"""Route feedback message from one agent to another."""
log_event(
logger,
"directory.feedback_route",
f"Routing feedback: {feedback.sender} → {feedback.receiver}"
)
if feedback.receiver not in self.agents:
e... | Python | 1 |
api_key == 'your-coinmarketcap-api-key-here':
logger.error("❌ CMC_API_KEY is required")
logger.error("💡 Please set your CoinMarketCap API key in one of these ways:")
logger.error(" 1. Environment variable: export CMC_API_KEY='your-api-key-here'")
logger.error(" 2. Update CMC_API_KE... | Python | 1 |
r: *const _HCLUSTER, lpszgroupname: ::windows_sys::core::PCWSTR) -> *mut _HGROUP>;
#[doc = "*Required features: `\"Win32_Networking_Clustering\"`*"]
pub type PCLUSAPI_OPEN_CLUSTER_GROUP_EX = ::core::option::Option<unsafe extern "system" fn(hcluster: *const _HCLUSTER, lpszgroupname: ::windows_sys::core::PCWSTR, dwdesire... | Rust | 0 |
import requests
from typing import Optional, Dict
def get_location_by_ip(ip: str = 'auto', toolbench_rapidapi_key: str = '088440d910mshef857391f2fc461p17ae9ejsnaebc918926ff') -> Dict:
"""
Endpoint Description: Get geolocation information based on a given IP address.
Parameters:
- ip [Optional]: string ... | Python | 1 |
", first_variable);
{
let second_variable: i32 = 200;
println!("inside, second_variable = {}", second_variable);
let first_variable: i32 = 300;
println!("inside, first_variable = {}", first_variable);
}
// println!("outside, second_variable = {}", second_variable);
}use su... | Rust | 0 |
@classmethod
def raw_code(cls):
return cls.code()
| Python | 1 |
ptr(gst_rtp_sys::GST_RTP_PAYLOAD_DVI4_16000_STRING)
.to_str()
.unwrap()
});
pub static RTP_PAYLOAD_DVI4_22050_STRING: once_cell::sync::Lazy<&'static str> =
once_cell::sync::Lazy::new(|| unsafe {
CStr::from_ptr(gst_rtp_sys::GST_RTP_PAYLOAD_DVI4_22050_STRING)
.to_str()
... | Rust | 0 |
import requests
from bs4 import BeautifulSoup
def fetch_douban_chart():
url = "https://movie.douban.com/chart"
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
}
response = requests.get(url, heade... | Python | 1 |
.join(UserSavedPhoto.user)
.where(
Users.uuid == user_id,
UserSavedPhoto.photo_uuid == photo_id
)
)
userPhoto: UserSavedPhoto | None = (await session.execute(query)).scalar()
if userPhoto is None:
raise HTTPExceptio... | Python | 1 |
try:
from .emotion_recognition import get_emotion_recognition_ai
emotion_ai = get_emotion_recognition_ai()
debug_info = {
"face_model_loaded": emotion_ai.face_model is not None,
"emotion_model_loaded": emotion_ai.emotion_model is not None,
"f... | Python | 1 |
!(Err(ParseError::BadLength(0)), "".parse::<Cell>());
assert_eq!(Err(ParseError::BadLength(2)), "..".parse::<Cell>());
}
#[test]
fn test_display_cell() {
assert_eq!(".", Cell::Floor.to_string());
assert_eq!("L", Cell::EmptySeat.to_string());
assert_eq!("#", Cell::OccupiedSea... | Rust | 0 |
},
// );
parent.spawn_bundle(TextBundle {
style: Style {
position_type: PositionType::Absolute,
position: Rect {
bottom: Val::Px(0.0),
..Default::default()
},
... | Rust | 0 |
. 0x000d
APB_DATA_WIDTH .................... 32
IC_SDA_STUCK_TIMEOUT_DEFAULT ...... 0xffffffff
IC_SLV_DATA_NACK_ONLY ............. 0x1
IC_10BITADDR_SLAVE ................ 0x0
IC_CLK_TYPE ....................... 0x0
IC_SMBUS_UDID_MSB ................. 0x0
IC_SMBUS_SUSPEND_ALERT ............ 0x0
I... | Rust | 0 |
WindowManager::add(window);
if !style.contains(WindowStyle::SUSPENDED) {
handle.make_active();
}
handle
}
fn build_inner<'a>(mut self, title: &str) -> Box<RawWindow<'a>> {
let window_options = self.window_options;
if (window_options & megosabi::windo... | Rust | 0 |
from rest_framework import serializers
from .models import HealthMetrics
class HealthMetricsSerializer(serializers.ModelSerializer):
class Meta:
model = HealthMetrics
fields = [
'id',
'date',
'weight',
'body_fat_percentage',
'blood_pressu... | Python | 1 |
import datetime
import sys
import signal
import time
import os
from core.utils import isInteger, isFloat
from core.logger import Logger
from helper.tinkerforge.ip_connection import IPConnection
from helper.tinkerforge.bricklet_gps_v3 import BrickletGPSV3
HOST = os.environ.get("HOST", "localhost")
PORT = os.environ.ge... | Python | 1 |
import ijson
def load_and_print_last_tweet(json_file):
with open(json_file, 'rb') as file: # open the file in binary mode
# Directly parse items under the root array
tweets = ijson.items(file, 'item')
last_tweet = None
for tweet in tweets:
last_tweet = tweet # Continue... | Python | 1 |
oto_2, parse_goto, "goto 17");
ast_panic_test!(parse_goto_3, parse_goto, "got 17");
ast_test!(parse_retstat_1, parse_retstat, "return false,true ;",
astb!(RetStat, Some(ast!(ExpList, vec![
ast!(Bool, false),
ast!(Bool, true)
]))));
ast_test!(pars... | Rust | 0 |
Test::Char(c))) // FIXME there are other escapes, like \s
}
}
}
fn repeat(&mut self, elems: &mut Vec<Elem>, index: usize, op: RepeatOp) -> Result<(), RegexError> {
self.bump(); // consume the `*`, `+`, `?`, etc
match elems.pop() {
Some(e) => Ok(elems.push(Elem::R... | Rust | 0 |
bHelper core library
/// aka dh_lib. Specifically this implementation is based on the Ubuntu version
/// labelled 12.10ubuntu1 which is included in Ubuntu 20.04 LTS. I believe 12 is
/// a reference to Debian 12 "Bookworm", i.e. Ubuntu uses future Debian sources
/// and is also referred to as compat level 12 by debhelpe... | Rust | 0 |
urses/pdcurses/overlay.c")
.file("src/PDCurses/pdcurses/pad.c")
.file("src/PDCurses/pdcurses/panel.c")
.file("src/PDCurses/pdcurses/printw.c")
.file("src/PDCurses/pdcurses/refresh.c")
.file("src/PDCurses/pdcurses/scanw.c")
.file("src/PDCurses/pdcurses/scr_dump.c")
... | Rust | 0 |
4 {
match SocketAddrV4::from_str(address) {
Ok(parsed_address) => parsed_address,
Err(_) => {
error!("Failed to parse supplied address! {}", address);
exit(1)
}
}
}
pub fn invoke(args: &ArgMatches) {
let output_json = args.is_present("json");
let use_local = args.is_present("local");
... | Rust | 0 |
oxygen_system(code: &Intcode) -> Option<Droid> {
let mut discovered: HashMap<Point, Status> = HashMap::new();
let mut queue: VecDeque<Droid> = VecDeque::new();
queue.push_front(Droid::new(code));
loop {
let droid = queue.pop_back()?;
for d in droid.extend(&mut discovered).drain(..) {
... | Rust | 0 |
ug!("dataflow_for({:?}, id={:?}) {:?}", e, id, self.variants);
let mut sets = String::new();
let mut seen_one = false;
for &variant in &self.variants {
if seen_one { sets.push_str(" "); } else { seen_one = true; }
sets.push_str(variant.short_name());
sets.push... | Rust | 0 |
def recorrerTelefonos(lista,posicion):
#posicion -=1
for q in range(len(lista[posicion]["telefonos"])):
print("---------------------------")
print("Telefonossss#",q+1,":")
print("#### - Código:",lista[posicion]["telefonos"][q]["codigo"])
print("##... | Python | 1 |
_ as usize },
24usize,
concat!(
"Offset of field: ",
stringify!(tm),
"::",
stringify!(tm_wday)
)
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<tm>())).tm_yday as *const _ as usize },
28usize,
concat!(
"Offset of field: ",
... | Rust | 0 |
Error::new(io::ErrorKind::Other, error.to_string()));
}
};
println!("Server start at port: {}", port);
HttpServer::new(move || {
App::new()
.wrap(middleware::Logger::default())
.app_data(Data::new(AppState { db: db.clone() }))
.service(all_project)
... | Rust | 0 |
4usize],
#[doc = "0x418 - Watchdog Test"]
pub test: TEST,
_reserved7: [u8; 2020usize],
#[doc = "0xc00 - Watchdog Lock"]
pub lock: LOCK,
}
#[doc = "Watchdog Load\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write),... | Rust | 0 |
let mut tr_screen = transpose_string_vec(screen_temp.clone());
//let _fn2: fn(char)-> char = |y:char|if y == ALIEN{BLANK_SPACE}else{SHOT_OBJ};
tr_screen = move_shot(tr_screen.clone(), SHOT_OBJ);
screen_temp = transpose_s... | Rust | 0 |
),
'likes': int(video['statistics'].get('likeCount', 0)),
'published_at': video['snippet']['publishedAt'],
'url': f"https://youtube.com/watch?v={video['id']}"
}
videos.append(processed_video)
result = {
'success': True,... | Python | 1 |
locking enabled"]
ENABLED,
}
impl AUTOBLOCKR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
... | Rust | 0 |
.0[0].0);
}
#[test]
fn t2() {
let mut slice = Byte::vec(10);
let mut bit_arr = BitArrMut(&mut slice);
// safe because test run in debug
unsafe {
bit_arr.set_unchecked(0);
bit_arr.set_unchecked(2);
bit_arr.set_unchecked(4);
bit_... | Rust | 0 |
}
#[cargo_test]
fn rustc_bench() {
full_project()
.cargo("rustc -v --bench 'be*1'")
.with_stderr_contains("[RUNNING] `rustc --crate-name bench1 [..]`")
.with_stderr_contains("[RUNNING] `rustc --crate-name bin2 [..]`")
.with_stderr_contains("[RUNNING] `rustc --crate-name bin1 [..]`"... | Rust | 0 |
assert!(g1.is_in_correct_subgroup_assuming_on_curve());
assert_eq!(g1, G1Affine::prime_subgroup_generator());
break;
}
}
i += 1;
x.add_assign(&Fq::one());
}
}
#[test]
fn test_g1_addition_correctness() {
let mut p = G1Projective::new(
... | Rust | 0 |
cipher.decrypt(nonce, ciphertext.as_ref())
//! .expect("decryption failure!"); // NOTE: handle this error to avoid panics!
//!
//! assert_eq!(&plaintext, b"plaintext message");
//! ```
//!
//! ## In-place Usage (eliminates `alloc` requirement)
//!
//! This crate has an optional `alloc` feature which can be disabl... | Rust | 0 |
args.output_json}")
repo: Optional[SQLiteRepository] = None
if config.storage.enabled:
repo = persist_summary(config, summary)
if repo and args.history > 0:
print(f"\n最近 {args.history} 期历史概览:")
for stored in repo.fetch_recent_summaries(limit=args.history):
revenue_str =... | Python | 1 |
Options: SPXMLRESULTOPTIONS,
pResult: *mut BSTR,
) -> HRESULT,
fn GetXMLErrorInfo(
LineNumber: *mut c_long,
ScriptLine: *mut BSTR,
Source: *mut BSTR,
Description: *mut BSTR,
ResultCode: *mut c_long,
IsError: *mut VARIANT_BOOL,
) -> HRESULT,
}}... | Rust | 0 |
, 0, 0] + [0] * 128)
fig, ax = plt.subplots()
ax.plot(x + 1, y + 1)
ax.plot(x + 1, y + 1, 'ro')
@image_comparison(['clipping_with_nans'])
def test_clipping_with_nans():
x = np.linspace(0, 3.14 * 2, 3000)
y = np.sin(x)
x[::100] = np.nan
fig, ax = plt.subplots()
ax.plot(x, y)
ax.se... | Python | 1 |
_code[[y, x]] == HEX_4_CODE {
HEX_4_SYMB
} else if symbol_code[[y, x]] == HEX_5_CODE {
HEX_5_SYMB
} else if symbol_code[[y, x]] == HEX_6_CODE {
HEX_6_SYMB
} else if symbol_code[[y, x]] == HEX_7_CODE {
HEX_7_SYMB
} else if symbol_code[[y, x]] == HEX_8_CODE {
... | Rust | 0 |
Opts = Opts::parse();
let date: SystemTime;
if opts.key_sig_time == None {
date = SystemTime::UNIX_EPOCH;
} else {
date = SystemTime::UNIX_EPOCH
+ Duration::from_secs(opts.key_sig_time.unwrap().parse::<u64>().unwrap());
}
date
}
fn get_key_expiration_time() -> Option<Sys... | Rust | 0 |
.text_input("总累计收益率", f"{total_return:.2%}")
st.text_input("夏普比率", f"{sharpe_ratio:.2f}")
with col2:
st.text_input("成功率", f"{success_rate:.2%}")
st.text_input("年化收益率", f"{annual_return:.2%}")
st.text_input("最大回撤", f"{max_drawdown:.2%}")
st.text("") # Em... | Python | 1 |
oResource;
#[read_all]
fn read_all() {
// your handler
}
fn main() {
let cors = CorsConfig {
origin: Origin::Copy,
headers: Headers::List(vec![CONTENT_TYPE]),
max_age: 0,
credentials: true
};
let (chain, pipelines) = single_pipeline(new_pipeline().add(cors).build());
gotham::start("127.0.0.1:8080", build... | Rust | 0 |
.collect();
assert_eq!("dark", find_profile(0, &thresholds));
assert_eq!("dark", find_profile(4, &thresholds));
assert_eq!("dark", find_profile(5, &thresholds));
assert_eq!("dark", find_profile(9, &thresholds));
}
#[test]
#[should_panic]
fn test_find_profile... | Rust | 0 |
u[end_date.month - 1]}"
else:
return f"{start_date.day} {months_ru[start_date.month - 1]} - {end_date.day} {months_ru[end_date.month - 1]}"
async def create_digest(messages, start_date, end_date):
if not messages:
logging.error("No messages to create digest from")
return "No messages we... | Python | 1 |
decoded_len(1) , 1);
assert_eq!(max_decoded_len(2) , 2);
assert_eq!(max_decoded_len(3) , 3);
assert_eq!(max_decoded_len(255), 255);
}
fn codec() -> Codec {
Config::default().to_codec()
}
// A test payload.
const PAYLOAD: [u8; PAYLOAD_LEN] = [0, 1, 2, 3];
cons... | Rust | 0 |
# Generated by Django 4.1.2 on 2022-11-02 16:42
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('maintenances', '0002_maintenance_end_automatically_and_more'),
]
operations = [
migrations.AlterField(
... | Python | 1 |
PlotOutlineData(
outline_id=row.outline_id,
role_id=row.role_id,
role_name=row.role_name,
title=row.title,
birthday=row.birthday,
life=row.life,
wealth=... | Python | 1 |
ATIVE_ARCH,
weak_self.clone(),
);
t
});
let tg = session.create_initial_tg(wrapped_t.clone());
*wrapped_t.tg.borrow_mut() = Some(tg);
let addr_space = session.create_vm(&**wrapped_t, None, None);
*wrapped_t.as_.borrow_mut() = Some(addr_spa... | Rust | 0 |
def segments2boxes(segments):
"""
It converts segment labels to box labels, i.e. (cls, xy1, xy2, ...) to (cls, xywh)
Args:
segments (list): list of segments, each segment is a list of points, each point is a list of x, y coordinates
Returns:
(np.ndarray): the xywh coordinates of the boundi... | Python | 1 |
nome = str(input('Qual é seu nome completo? ')).strip()
print('Seu nome tem Silva? {}'.format('silva' in nome.lower())) | Python | 1 |
import numpy as np
#There are two words we take: Source and target
source_word = input("Please enter the source word:\n")
target_word = input("Please enter the target word:\n")
#For creating a matrix, we are adding +1 to both row and column, then we are creating matrix with zeros.
source_length = len(source_word) + 1... | Python | 1 |
from django.shortcuts import render, redirect, get_object_or_404
from .models import Course, Description
from django.contrib import messages
def index(request):
courses = Course.objects.all()
return render(request, 'index.html', {'courses': courses})
def add_course(request):
if request.method == 'POST':
... | Python | 1 |
(Error::UnsupportedSignatureAlgorithm),
}
}
//! Small crate implementing fast conversion between linear float and 8-bit
//! sRGB.
//!
//! - [`f32_to_srgb8`]: Convert f32 to an sRGB u8. Meets all the requirements of
//! [the most relevent public
//! spec](https://microsoft.github.io/DirectX-Specs/d3d/archive/D3D... | Rust | 0 |
);
/// Get the hi128 bits from a 5-limb slice.
fn hi128_8(&self) -> (u128, bool);
/// Get the hi128 bits from a 5-limb slice.
fn hi128_9(&self) -> (u128, bool);
perftools_inline!{
/// High-level exporter to extract the high 128 bits from a little-endian slice.
fn hi128(&self) -> (u128, bo... | Rust | 0 |
def convSymbols(match, _dict_):
prefix = match.group(0) + '\t'
char=match.group(1)
tstr =''
for elem in _dict_[char]:
if elem != '':
tstr += prefix + elem + '\n'
else:
tstr += prefix + '\n'
tstr = tstr[:-1]
return tstr
def convEqual(match):
tstr = ... | Python | 1 |
self.page_table.apply_update(mem, update);
Ok(())
}
BrkUpdate { new, .. } => {
self.brk = *new;
Ok(())
}
CsrWrite { addr, new, .. } => {
self.csrs.insert(*addr, *new);
Ok(())
}
... | Rust | 0 |
UnusedForRef { difference_of_pic_nums_minus1: u32 },
/// `memory_management_control_operation` value of `2`
LongTermUnusedForRef { long_term_pic_num: u32 },
/// `memory_management_control_operation` value of `3`
ShortTermUsedForLongTerm { difference_of_pic_nums_minus1: u32, long_term_frame_idx: u32 },
... | Rust | 0 |
import json
def update_requirements(requirements_path, outdated_packages_path):
with open(outdated_packages_path, 'r') as f:
outdated_packages = json.load(f)
with open(requirements_path, 'r') as f:
requirements_lines = f.readlines()
outdated_map = {pkg['name']: pkg['latest_version'] for p... | Python | 1 |
{}{}{}{}{}{}{}{}{}{}{}{}",
base + i * 16,
chunk[0], chunk[1], chunk[2], chunk[3],
chunk[4], chunk[5], chunk[6], chunk[7],
chunk[8], chunk[9], chunk[10], chunk[11],
chunk[12], chunk[13], chunk[14], chunk[15],
ch(chunk[0]), ch(chunk[1]), ch(chunk[2])... | Rust | 0 |
rs, tz, iv_series, w_len=args.w_len, m_len=args.m_len)
logger.info(f"Dataset built: X={X.shape}, y={y.shape} spanning {X.index.min().date()} to {X.index.max().date()}")
# Train
models, oof = train_harq_rr_iv(X, y, t1, cfg)
# Save artifacts
out_dir = f"artifacts/{args.instrument}/daily"
os.make... | Python | 1 |
.unwrap()));
Ok(())
}
pub fn clear_timeset(&mut self) -> Result<()> {
self.current_timeset_id = Option::None;
TEST.push(node!(ClearTimeset));
Ok(())
}
pub fn get_pin_header(&self, dut: &Dut) -> Option<PinHeader> {
if let Some(ph_id) = self.current_pin_header_id ... | Rust | 0 |
id, &their_id_bytes[0..Digest::LENGTH]);
} else {
error!(
?their_id,
"small_network attempted to retrieve bytes of ID, but seems to be libp2p ID?"
)
}
ConnectionId(id)
}
/// Creates a new [`TraceID`] based on the message count.
... | Rust | 0 |
def _configure_logging(args):
kwargs = {'format': '%(asctime)s %(levelname)-8s %(message)s',
'datefmt': '%Y-%m-%d %H:%M', 'level': logging.DEBUG if args.debug else
logging.INFO}
if args.log_file is not None:
kwargs['filename'] = args.log_file
logging.basicConfig(**kwargs)
| Python | 1 |
})
}
/// Creates a copy-on-write memory map backed by a file.
///
/// Data written to the memory map will not be visible by other processes,
/// and will not be carried through to the underlying file.
///
/// # Errors
///
/// This method returns an error when the underlying system c... | Rust | 0 |
3 fp=0xc42003efd8 sp=0xc42003efa0 pc=0x419973\n
runtime.goexit()\n
/usr/local/go/src/runtime/asm_amd64.s:2337 +0x1 fp=0xc42003efe0 sp=0xc42003efd8 pc=0x44b4d1\n
created by runtime.gcenable\n
/usr/local/go/src/runtime/mgc.go:216 +0x58\n",
// second line
"one more line, no multiline\n",
... | Rust | 0 |
macro_rules! retry_assert {
($test:expr, $timeout:expr) => {{
let mut duration = Duration::from_secs(0);
let max_duration: Duration = $timeout;
let sleep_duration = Duration::from_millis(100);
while duration.lt(&max_duration) && !$test {
tokio::time::sleep(sleep_duration... | Rust | 0 |
Event::KeyDown { keycode: Some(Keycode::Space), .. } => {
let x = piece.x;
let mut y = piece.y;
while piece.change_position(&tetris.game_map, x, y + 1) == true {
y += 1;
}
make_permane... | Rust | 0 |
import os
from magic_pdf.libs.MakeContentConfig import DropMode, MakeMode
from magic_pdf.pipe.UNIPipe import UNIPipe
from magic_pdf.pipe.OCRPipe import OCRPipe
from magic_pdf.pipe.TXTPipe import TXTPipe
from magic_doc.conv.base import BaseConv
from magic_doc.progress.filepupdator import FileBaseProgressUpdator
from m... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.