text string | label_name string | labels int64 |
|---|---|---|
.with_label(Label::new_primary(char_span))
},
LexerError::UnexpectedEof { end } => Diagnostic::new_error("unexpected end of file")
.with_label(Label::new_primary(ByteSpan::new(end, end))),
LexerError::UnterminatedStringLiteral { span } => {
... | Rust | 0 |
ut PixState, color: C) -> PixResult<()> {
let color = color.into();
s.fill(color);
s.no_stroke();
s.rect(self.rect)?;
s.no_fill();
s.stroke(Color::WHITE);
let top_left = self.rect.top_left();
let top_right = self.rect.top_right();
let bottom_left =... | Rust | 0 |
"color: white;">Playset</label>
<input type="checkbox" id="presale" name="presale" /><label for="presale" style="color: white;">Presale</label>
<input type="hidden" name="ebay_id" value="{ebay_posting.ebay_id}">
<p style="color: white;">{"Posted for $" + '{:.2f} {}'.format(ebay_posting.pri... | Python | 1 |
import io
from io import BytesIO
from pathlib import Path
import numpy as np
import soundfile as sf
from pydub import AudioSegment
from scipy.io import wavfile as wavfile
from typeguard import typechecked
from common.io.file_type import AudioFileType
@typechecked
def get_audio_info(file: Path | str | bytes | BytesI... | Python | 1 |
String,
pub medium: String,
}
#[derive(Serialize, Deserialize, Clone)]
pub struct Date {
pub year: Option<i64>,
pub month: Option<i64>,
pub day: Option<i64>,
}
#[derive(Serialize, Deserialize, Clone)]
pub struct MangaName {
pub romaji: String,
pub english: String,
pub native: String,... | Rust | 0 |
from_raw(rtv) })
}
} else {
None
};
Ok(Image {
resource: resource,
kind: image.kind,
usage: image.usage,
storage_flags: image.flags,
dxgi_format,
bytes_per_block: bytes_per_block,
block_d... | Rust | 0 |
Self {
self.message.nlas.push(nla);
self
}
}
// SPDX-License-Identifier: MIT
// Copyright (C) 2018-present iced project and contributors
use crate::block_enc::tests::*;
const BITNESS: u32 = 32;
const ORIG_RIP: u64 = 0x8000;
const NEW_RIP: u64 = 0x8000_0000;
#[test]
fn jmp_fwd() {
#[rustfmt::ski... | Rust | 0 |
1: ───/‾‾(10 ns@25.0MHz)‾‾\───
""",
)
@pytest.mark.parametrize(
'gate, resolver, expected',
[
(
coupler_pulse.CouplerPulse(
hold_time=cirq.Duration(nanos=sympy.Symbol('t_ns')), coupling_mhz=10
),
{'t_ns': 50},
coupler_pulse.CouplerPu... | Python | 1 |
foods = {}
total_sold_quantities = 0
while True:
command = input()
if command == "Complete":
break
split_command = command.split()
action = split_command[0]
quantity = int(split_command[1])
food = split_command[2]
if action == "Receive":
if quantity <= 0:
conti... | Python | 1 |
results.append((test_name, False))
# 汇总结果
rich_print_rule("测试结果汇总", style="cyan")
passed = sum(1 for _, success in results if success)
total = len(results)
for test_name, success in results:
status = "✅ 通过" if success else "❌ 失败"
rich_print(f"{test_name}: {status}")
rich_p... | Python | 1 |
= area_value & 0b0000_0111; // 3 bits to the right of that
for val in from_zone..=to_zone {
zones.push(ValidityZone::from(val));
}
ValidityArea::Zone(zones)
}
e => panic!("Unsupported area type: {}", e),
}
}
}
/// T... | Rust | 0 |
import cvzone
import cv2
from cvzone.HandTrackingModule import HandDetector
import numpy as np
import google.generativeai as genai
from PIL import Image
# Set your API key directly in the script
API_KEY = "AIzaSyDcMZQj-kDOyG35D86mT3zJPb_4OO0I7dE"
# Configure the generative AI model
genai.configure(api_key=API_KEY)
mo... | Python | 1 |
e measurement basis change
measurement_basis_change(m1, m2, qubit1, qubit2)
align()
measure(
"readout",
f"rr{qubit1}",
None,
dual_demo... | Python | 1 |
", nay_sayers),
Equal => return,
};
let mut list_of_people = String::with_capacity(37*verdict.2.len());
for person in &verdict.2 {
list_of_people.push_str(", ");
list_of_people.push_str(&person.mention());
... | Rust | 0 |
import torch
import torch_geometric.graphgym.register as register
from torch_geometric.graphgym.config import cfg
from torch_geometric.graphgym.models.gnn import FeatureEncoder, GNNPreMP
from torch_geometric.graphgym.register import register_network
from graphgps.layer.performer_layer import Performer as BackbonePerfo... | Python | 1 |
s)]
pub fn rx_filter_thres_ch2(&mut self) -> RX_FILTER_THRES_CH2_W {
RX_FILTER_THRES_CH2_W { w: self }
}
#[doc = "Bit 16 - This bit is used to reset divider in channel2."]
#[inline(always)]
pub fn ref_cnt_rst_ch2(&mut self) -> REF_CNT_RST_CH2_W {
REF_CNT_RST_CH2_W { w: self }
}
... | Rust | 0 |
onnect()?;
let mut stmt = conn.prepare(r#"SELECT * FROM repos where repo = :full OR repo = :org"#)?;
let cols = db::Columns::from_stmt(&stmt)?;
let mut rows = stmt.query_named(&[(":full", &repo.full_name), (":org", &repo.owner.login())])?;
let mut repos = Vec::new();
while let O... | Rust | 0 |
zero to clear flag. Write to one has no effect."]
#[inline(always)]
pub fn tx_ctrl(&mut self) -> TX_CTRL_W {
TX_CTRL_W { w: self }
}
#[doc = "Bit 5 - 5:5\\]
Interrupt flag 5. BLE mode: Acknowledgement received on a transmitted packet. IEEE 802.15.4 mode: Transmitted automatic ACK frame. Write ze... | Rust | 0 |
// NOTE: futures::future::Map<..., oneshot::Receiver, ...> can be a Future
pub fn req_res_handler<Fut>(
mut handler: impl FnMut(Request<Body>, oneshot::Sender<Response<Body>>) -> Fut,
) -> impl (FnMut(
Request<Body>,
) -> futures::future::Map<
futures::future::Join<Fut, oneshot::Receiver<Response<Body>>>,
... | Rust | 0 |
. For every call to `exit_scope()`, there must one corresponding call to
/// `enter_scope()` that executes prior to the call to `exit_scope()`. Both `enter_scope()` and
/// `exit_scope()` can be called several times in a row (which indicates that multiple scopes have
/// been entered/exited).
pub trait Scoped {
/... | Rust | 0 |
IALIZED: types::GLenum = 0x3001;
#[allow(dead_code, non_upper_case_globals)] pub const NO_CONTEXT: types::EGLContext = 0 as types::EGLContext;
#[allow(dead_code, non_upper_case_globals)] pub const NO_DISPLAY: types::EGLDisplay = 0 as types::EGLDisplay;
#[allow(dead_code, non_upper_case_globals)] pub const NO_IMAGE: typ... | Rust | 0 |
)
.args(&["describe", "--tags", "--exact-match", "HEAD"])
.current_dir(&repo_dir.path())
.output()?
.stdout;
let tag_output = str::from_utf8(&git_tag).unwrap().trim();
let expected_output = format!("{} {}", commit_output, tag_output);
let actual ... | Rust | 0 |
* * `order_id: &str` -- The ID of the order that's associated with the fulfillment event.
*/
pub async fn deprecated_202007_get_orders_param_order_fulfillments_fulfillment_event(
&self,
order_id: &str,
fulfillment_id: &str,
) -> Result<()> {
let url = format!(
... | Rust | 0 |
})
.map(|(from_addr, filter, caller)| PullData {
from_addr,
caller,
filter,
})
.collect()
});
if !requests.is_empty() {
self.stats
.pull_requests_count
... | Rust | 0 |
();
rest.iter().cloned().fold(init, |vec, list| {
partial_cartesian(vec, list)
})
},
None => {
vec![]
}
}
}
// Thanks kylewlacy: https://gist.github.com/kylewlacy/115965b40e02a3325558
fn partial_cartesian<T: Clone>(a: Vec<Vec<T>>, b: &[T]... | Rust | 0 |
::BOLD_ITALIC => glyph_cache.bold_italic_key,
Flags::ITALIC => glyph_cache.italic_key,
Flags::BOLD => glyph_cache.bold_key,
_ => glyph_cache.font_key,
};
// Don't render text of HIDDEN cells.
let mut chars = if cell.flags.contains(Flags::HIDDEN) {
... | Rust | 0 |
import uvicorn
from src.app import app
if __name__ == "__main__":
uvicorn.run("src.app:app", reload=True)
| Python | 1 |
let slashing = suite.list_validator_slashing(members[2]).unwrap();
assert!(!slashing.tombstoned);
assert_eq!(
slashing.jailed_until,
Some(Expiration::at_timestamp(
suite.block_info().time.plus_seconds(3600)
))
);
let jailed_until = JailingEnd::Until(Duration::new... | Rust | 0 |
th)?))
}
pub fn get_reader<T: AsRef<Path>>(
path: Option<T>,
) -> io::Result<Box<dyn io::Read + Send + Sync + 'static>> {
Ok(match to_stdio(path) {
None => Box::new(io::stdin()),
Some(path) => Box::new(File::open(path)?),
})
}
pub fn get_writer<T: AsRef<Path>>(
path: Option<T>,
) -> io... | Rust | 0 |
:type RequestId: str
"""
self._Result = None
self._RequestId = None
@property
def Result(self):
return self._Result
@Result.setter
def Result(self, Result):
self._Result = Result
@property
def RequestId(self):
return self._RequestId
@Requ... | Python | 1 |
# Four function Calculator commandline tool
# -------------------------------------------------------- #
# -- CALCULATOR ------------------------------------------ #
# -------------------------------------------------------- #
# Adding numbers function:
def add(a, b):
return a + b
# Subtracting numbers function:... | Python | 1 |
int_bytes.try_into().unwrap())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn read_u32_buf() {
let buf: [u8; 5] = [1, 0, 0, 0, 5];
let mut header_bytes = &buf[0..5];
let nanosecond = read_le_u32(&mut header_bytes);
assert_eq!(1, nanosecond);
assert_eq!(header_b... | Rust | 0 |
ttention('je suis trop fatigue pour conduire')
evaluateAndShowAttention('je suis desole si c est une question idiote')
evaluateAndShowAttention('je suis reellement fiere de vous')
######################################################################
# Exercises
# =========
#
# - Try with a different dataset
#
# ... | Python | 1 |
");
let (rem, result) = String::from_der(input).expect("parsing failed");
assert_eq!(&result, "Some-State");
assert_eq!(rem, &[]);
}
#[test]
fn from_der_opt_int() {
let input = &hex!("02 01 02 ff ff");
let (rem, result) = <Option<u8>>::from_der(input).expect("parsing failed");
assert_eq!(result... | Rust | 0 |
%s, %s, %s, %s, %s) ON CONFLICT (id_aluno, codigo_disciplina) DO NOTHING
""", (id_aluno, id_curso, codigo_disciplina, semestre, ano, media, faltas))
# Insert data into Leciona
cursor.execute("SELECT id_curso FROM Curso")
cursos = cursor.fetchall()
cursor.execute("SELECT id FROM Professor")
professores = curs... | Python | 1 |
},
};
use tokio::net::TcpStream;
use crate::matcher::Matcher;
pub async fn handle_connection(socket: TcpStream, mymatchlist: Arc<Vec<Matcher>>) {
let mut peekbuf = [0; 1024];
// "peek" into the socket to retrieve TLS
// ClientHello and SNI
let rsz = socket
.peek(&mut peekbuf)
.await
... | Rust | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
QEMU GUI Full — single-file manager
Features:
- Autodetect qemu-system-<arch>, qemu-img
- Many architectures supported
- Create disk (qemu-img), snapshots
- Network modes (user/tap/bridge) + hostfwd
- VNC/SPICE/nographic, extra args
- Save/load VM profiles (JSON)... | Python | 1 |
_TRANSPARENT_RGB: libc::c_int = 0x8008;
pub const GLX_TRANSPARENT_INDEX: libc::c_int = 0x8009;
pub const GLX_VISUAL_ID: libc::c_int = 0x800B;
pub const GLX_SCREEN: libc::c_int = 0x800C;
pub const GLX_NON_CONFORMANT_CONFIG: libc::c_int = 0x800D;
pub const GLX_DRAWABLE_TYPE: libc::c_int = 0x8010;
pub const GLX_RENDER_TYP... | Rust | 0 |
ory {
fn try_create(&self, path: &Path) -> Option<Box<dyn FileType>> {
if metadata(&path)
.ok()
.expect("Error fetching metadata for file")
.is_dir()
{
Some(Box::new(Dir {
path: PathBuf::from(path),
type_str: TYPE_STR,
... | Rust | 0 |
pub const STARTED: EventId = EventId(1865572685266217927843817693478761602);
/// App stopped EventId (01CX5XBT512FQVTNBY40CRCRH3)
pub const STOPPED: EventId = EventId(1865572700528146015116120354537759267);
/// constructor
pub fn new(package_id: PackageId, instance_id: ULID, state: AppLifeCycle) -... | Rust | 0 |
nome = input("Por favor, digite o seu nome: ")
print("Boa tarde, " + nome) | Python | 1 |
REG_S12: Type = 91;
pub const ARM_REG_S13: Type = 92;
pub const ARM_REG_S14: Type = 93;
pub const ARM_REG_S15: Type = 94;
pub const ARM_REG_S16: Type = 95;
pub const ARM_REG_S17: Type = 96;
pub const ARM_REG_S18: Type = 97;
pub const ARM_REG_S19: Type = 98;
pub const ARM_REG_S20: Type = ... | Rust | 0 |
use super::CmdGit;
use crate::bin::Opt;
use std::fs;
use std::io::{BufWriter, Write};
use structopt::StructOpt;
static TRACKED_FILES: [&'static str; 22] = [
".cargo/config",
".gitattributes",
".github/FUNDING.yml",
".github/dependabot.yml",
".github/work... | Rust | 0 |
":model.parameters(), "initia_lr": config_base['lr']}],
lr=config_base['lr'], weight_decay=config_base['weight_decay'])
scheduler = CosineAnnealingLR(optim, config_base['epoch'], eta_min=1.0e-7)
Max_Dice = 0
for epoch in range(config_base['epoch']):
Loss, Wbce, Wdice... | Python | 1 |
# -*- coding: utf-8 -*- #
# Copyright 2017 Google LLC. All Rights Reserved.
#
# 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 requir... | Python | 1 |
import random
def get_computer_choice(user_history):
"""
Computer choice generator.
If no user history -> random choice
If user history available -> AI predicts based on probability
"""
choices = ["rock", "paper", "scissors"]
if not user_history:
return random.choice(choices)
... | Python | 1 |
import warnings
warnings.filterwarnings('ignore')
# Importing libraries
import numpy as np
import pandas as pd
#from sklearn.preprocessing import PowerTransformer
import matplotlib.pyplot as plt
import seaborn as sns
import streamlit as st
import os
st.title("Lead Source Identification")
# Data display coustomization... | Python | 1 |
#coding:utf-8
'''
为了有效地使用它们,在用爬虫的时候我们需要在页面上做些事情
让我们看看如何创建一个爬虫来收集页面标题、正文的第一个段落
以及编辑页面的链接(如果有的话)这些信息
'''
'''
*和往常一样,决定如何做好这些事情的第一步就是先观察网站上的一些页面,然后拟定一
个采集模式。通过观察几个维基百科页面,包括词条和非词条页面,比如隐私策略之类的
页面,就会得出下面的规则。
'''
'''
• 所有的标题(所有页面上,不论是词条页面、编辑历史页面还是其他页面)都是在
h1 → span 标签里,而且页面上只有一个 h1 标签。
• 前 面 提 到 过, 所 有 的 正 文 文 字 都 在 div#bo... | Python | 1 |
.path.abspath(os.path.join(app.builder.env.srcdir,
app.config.xmlschema_path))
for root, _, files in os.walk(schemapath):
for fname in files:
if not fname.endswith(".xsd"):
continue
path = os.path.join(root, fname)
... | Python | 1 |
"""
if 'expires' in cookie_attrs:
e = email.utils.parsedate_tz(cookie_attrs["expires"])
if e:
return email.utils.mktime_tz(e)
elif 'max-age' in cookie_attrs:
try:
max_age = int(cookie_attrs['Max-Age'])
except ValueError:
pass
else:
... | Python | 1 |
set: Vec2,
pub scroll_size: Size,
pub view_size: Size,
pub gutter_width: f64,
pub header_height: f64,
pub locations: Vec<EditorLocation>,
pub current_location: usize,
pub saved_buffer_id: BufferId,
pub saved_selection: Selection,
pub saved_scroll_offset: Vec2,
#[allow(dead_code)... | Rust | 0 |
from __future__ import annotations
from abqpy.decorators import abaqus_class_doc
@abaqus_class_doc
class MeshStats:
"""The MeshStats object is a query object for holding mesh statistics and is returned by the getMeshStats
command. The object does not have any methods.
.. note::
This object can b... | Python | 1 |
)
tbl_sum = construct_tabular(
(bilateral_table_value_me, bilateral_table_value_pwr),
F=lambda u_m, u_p: u_m + u_p - u_avg_me - u_avg_pwr,
title="Change in value (sum):",
)
tbl_min = construct_tabular(
... | Python | 1 |
import json
import os
import requests
from pathlib import Path
from datetime import datetime, timedelta
from typing import Any
class ProxyManagerMeta(type):
"""
Metaclass for ProxyManager to ensure singleton behavior.
"""
@property
def ROOT(cls):
"""
Returns the root directory of t... | Python | 1 |
click: F,
event: Option<GuiEvent>,
) -> () {
if let Some(event) = event {
match event {
GuiEvent::MouseEvent(typ, pos) => {
let point = canvas
.total_matrix()
.invert()
.unwrap()
... | Rust | 0 |
6 spaces
* after every 37 characters. UNIX terminals do
* line breaks themselves, so ignore these
* characters
*/
if a == 0xe025 && (ch == 10 || ch == b' ') {
return;
}
if a == 0xe182 { // INPUT
//... | Rust | 0 |
.to_string(), CommandValue::Alias) { _ => () }
);
// Check user defined functions
shell.variables().for_each(|(key, v)|
if let Some(value) = v.value() {
if let variable::Value::Function(ref _f) = value {
match commands.insert(key.to_string(), Comm... | Rust | 0 |
{
let mut new_parent: Option<IndexPair> = None;
for col in miss.lookup_idx.iter_mut() {
let parents = node.resolve(*col).unwrap();
assert_eq!(parents.len(), 1, "query_through with more than one parent");
let (parent_global, parent_col) = parents[0];
if l... | Rust | 0 |
tions: Mutex<Vec<mpsc::Sender<Message>>>,
map_manager: Mutex<Box<dyn map_manager::MapManager + Send>>,
}
trait GameList {
fn add_game(&mut self, game: Game) -> String;
}
impl GameList for HashMap<String, Arc<Mutex<GameExecutor>>> {
fn add_game(&mut self, game: Game) -> String {
let game_id: String... | Rust | 0 |
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# 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 appli... | Python | 1 |
Incorporated
//
// 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 writing, softwar... | Rust | 0 |
# Generated by Ollama Llama 3
# Task: inside_op_xmr_scenarios_minimal
# Attempt: 4
# Success: False
# Overall Score: 0.492
import sys
import os
import re
import pyverilog.ast as ast
from pyverilog.dataTypes import dataType
from pyverilog.grammar import Grammar, Node
from pyverilog.parser import parse
from pyverilog.ut... | Python | 1 |
Token::Exponent);
symbols.insert("/", Token::Divide);
symbols.insert("//", Token::DivideFloor);
symbols.insert("%", Token::Mod);
symbols.insert("@", Token::At);
symbols.insert("<<", Token::Lshift);
symbols.insert(">>", Token::Rshift);
symbols.insert("&", Token::BitAnd);
symbols.insert("|", Toke... | Rust | 0 |
import numpy as np
from disba import PhaseDispersion
import matplotlib.pyplot as plt
def fun(x, nlayers, t, vdispobs, dc=0.005):
r"""Surface wave inversion misfit function
Create a dispersion curve from the input parameters
(thicknesses and shear wave velocities) and compute
misfit
Parameters
... | Python | 1 |
[doc = "[Vulkan Manual Page](https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VkPhysicalDeviceRGBA10X6FormatsFeaturesEXT.html) · Builder of [`PhysicalDeviceRGBA10X6FormatsFeaturesEXT`]"]
#[repr(transparent)]
pub struct PhysicalDeviceRGBA10X6FormatsFeaturesEXTBuilder<'a>(PhysicalDeviceRGBA10X6Format... | Rust | 0 |
from certificate_generator import generate_certificate
from database_manager import insert_certificate
import os
# Define test data
names = ["Pedro Perez", "Juan Rodriguez"]
course = "Actualización profesional en Analítica de Datos"
date_place = "Montevideo, 21 de noviembre de 2024"
course_details = "45 horas lectivas... | Python | 1 |
://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf
pub static SHA256: Algorithm = Algorithm {
output_len: SHA256_OUTPUT_LEN,
chaining_len: SHA256_OUTPUT_LEN,
block_len: 512 / 8,
len_len: 64 / 8,
block_data_order: GFp_sha256_block_data_order,
format_output: sha256_format_output,
initial_st... | Rust | 0 |
arams(min: Vector3<S>, max: Vector3<S>) -> Self {
Self { min, max }
}
#[inline]
pub fn new() -> Self {
Self::from_params(Vector3::zero(), Vector3::zero())
}
}
impl<S: BaseFloat> FrustumCuller<S> {
/// Creates an identity frustum culler. This is equivalent to calling the `from_matri... | Rust | 0 |
assert_eq!(UnconfirmedParams::pads(1), 7);
assert_eq!(UnconfirmedParams::pads(2), 6);
assert_eq!(UnconfirmedParams::pads(3), 5);
assert_eq!(UnconfirmedParams::pads(4), 4);
assert_eq!(UnconfirmedParams::pads(5), 3);
assert_eq!(UnconfirmedParams::pads(6), 2);
assert... | Rust | 0 |
rpret_alloc_index
};
let prev_cnums: Vec<_> = self.crate_nums
.iter()
.filter_map(|&cnum| cnum)
.map(|cnum| {
let crate_name = tcx.original_crate_name(cnum).to_string();
let crate_disambiguator = tcx.crate_disambiguator(cnum);
... | Rust | 0 |
#6c757d', 'marginTop': 50})
])
csv_file = get_csv_file()
if not csv_file:
return html.Div("No data available")
df = load_csv_data(csv_file)
if df.empty:
return html.Div("No data available")
row_idx = selected_rows[0]
# Get the actual row by matching the id
... | Python | 1 |
,
"null_accepted": True,
}
}
},
),
"CGImageMetadataTagCopyPrefix": (
b"^{__CFString=}^{CGImageMetadataTag=}",
"",
{"retval": {"already_cfretained": True}},
),
"CGImageMetadataTagCopyName": (
b"^{__CFString=}^{CGImage... | Python | 1 |
::{Failure, Output, Response, Success};
pub use self::version::Version;
use proc_macro::TokenStream;
use quote::quote;
use crate::utils::syn::{named_fields, parse_derive_input};
pub(crate) fn no_args_constructor(input: TokenStream) -> TokenStream {
let derive_input = parse_derive_input(input);
let name = &d... | Rust | 0 |
;
serde_json::from_str::<models::station::AreaNearResponse>(&res_body)
.map_err(|_| error::TankerkoenigError::ResponseParsingError { body: res_body })
}
/// Fetch all stations in a radius around the given coordinates that sell a specific kind
/// of [Fuel](models::Fuel) and [sort](model... | Rust | 0 |
import torch
from torchmetrics.image.fid import FrechetInceptionDistance
from tqdm import tqdm
import logging
from pathlib import Path
from paths import FID_PATH
logger = logging.getLogger(__name__)
def save_real_features_(fid):
state = dict(real_features_sum=fid.real_features_sum, real_features_cov_sum=fid.real_... | Python | 1 |
f (batch_idx + 1) % args.gradient_accumulation_steps == 0 or batch_idx == len(args.train_loader) - 1:
optimizer.step()
optimizer.zero_grad()
printInfo = 'TRAIN Iter {}: lr = {:.6f},\tloss = {:.6f},\t'.format(epoch, scheduler.get_last_lr()[0], objs.avg) + \
'Top-1 err = {:.6f... | Python | 1 |
OI, O>
) -> impl Iterator<Item = O>
where OI: Iterator<Item = O> {
fn apply<I, O, OI>(
maybe_oi: &mut Option<OI>,
iter: &mut impl Iterator<Item = I>,
f: &mut impl FnMut(I) -> Result<OI, O>
) -> Option<O>
where OI: Iterator<Item = O> {
// If there's an active iterator returned... | Rust | 0 |
from odoo import api, models, _
from odoo.exceptions import UserError
class ReportTax(models.AbstractModel):
_name = 'report.accounting_pdf_reports.report_tax'
_description = 'Tax Report'
@api.model
def _get_report_values(self, docids, data=None):
if not data.get('form'):
raise Us... | Python | 1 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# --- ↑↓ Do not remove these libs ↑↓ -----------------------------------------------------------------------------------
import argparse
import json
import requests
# ---- ↑ Do not remove these libs ↑ -----------------------------------------------------------------------... | Python | 1 |
# utils/data_downloader.py - 数据下载工具
import os
import time
import logging
import datetime
from typing import Dict, List, Optional, Union, Any
from pathlib import Path
import pandas as pd
import ccxt
class DataDownloader:
"""
数据下载工具,用于从交易所下载历史数据
"""
def __init__(self):
"""
初始化
... | Python | 1 |
import os
import signal
from collections.abc import Callable
from types import FrameType
from .constants import INTERVAL_SECONDS
if os.name != 'nt': # signal on windows doesn't have these attributes
TIMER = signal.ITIMER_PROF # type: ignore[attr-defined,unused-ignore] # pylint: disable=no-member # linters don... | Python | 1 |
WIDTH)
.add(
element::Line::new()
.set("x1", f64::from(x) - 0.25)
.set("x2", f64::from(x) + 0.25)
.set("y1", f64::from(y) - 0.25)
.set("y2", f64::from(y) + 0.25),
)
.add(
element::Line::new()
... | Rust | 0 |
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import uuid
from typing import List
from fastapi.middleware.cors import CORSMiddleware
import requests
app = FastAPI()
# Enable CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allows all origins
allow_credentials=Tr... | Python | 1 |
continue;
}
}
None
}
fn collect_fields_info<'a>(
fields: impl Iterator<Item = &'a syn::Field>,
) -> syn::Result<Vec<FieldInfo<'a>>> {
let mut r = Vec::new();
for f in fields {
if f.ident.is_none() {
return Err(syn::Error::new_spanned(&f, "field name is empty... | Rust | 0 |
}
#[test]
fn modify_format() {
const OUT: &str = "globtest/modified_format_and_ext/";
let mut process = SicTestCommandBuilder::new()
.glob_input_from_resources("*.png")
.glob_output_in_target(OUT)
.with_args(&["--output-format", "jpg"])
.spawn_child();
let exit_status = pr... | Rust | 0 |
8(dest_operand: i32, mut count: i32) -> i32 {
dbg_assert!(count >= 0 && count < 32);
count %= 9;
if 0 == count {
return dest_operand;
}
else {
let result =
dest_operand << count | (getcf() as i32) << count - 1 | dest_operand >> 9 - count;
*flags_changed &= !1 & !F... | Rust | 0 |
from __future__ import annotations
from typing import TYPE_CHECKING
from collections import deque
from trueseeing.core.model.cmd import CommandMixin
from trueseeing.core.ui import ui
if TYPE_CHECKING:
from typing import Literal
from trueseeing.api import CommandHelper, Command, CommandMap
UIPatternType = Lite... | Python | 1 |
get_ipv6_multicast_loop(fd), optval, optlen)
}
libc::IPV6_V6ONLY => write_bool(sockopt::get_ipv6_v6only(fd), optval, optlen),
_ => unimplemented!(
"unimplemented getsockopt IPPROTO_IPV6 optname {:?}",
optname
),
},
libc::IPP... | Rust | 0 |
from ast import arguments
from ast import ClassDef
from ast import Lambda
from ast import Load
from ast import Module
from ast import Name
from ast import Store
from ast import TypeAlias
tree = Module(
body=[
ClassDef(
name="name_4",
bases=[],
keywords=[],
bo... | Python | 1 |
from debug_toolbar.panels.sql.panel import SQLPanel
__all__ = ["SQLPanel"]
| Python | 1 |
vec());
}
assert!(table_scanner.next().unwrap().is_none());
}
#[test]
fn test_multiple_ranges() {
let mut statistics = Statistics::default();
let mut wrapper = TableScanTestWrapper::default();
// prepare range
let r1 = get_range(TABLE_ID, i64::MIN, 0);
... | Rust | 0 |
must be at least one service class UUID"));
}
let service_class_uuids = src.service_class_uuids.iter().map(fidl_bt::Uuid::from).collect();
let protocol_descriptor_list: Vec<fidl_bredr::ProtocolDescriptor> = src
.protocol_descriptor_list
.iter()
.map(|d| fidl... | Rust | 0 |
"""
Display a non-uniform image.
This example displays 2-d data as an image with non-uniformly
distributed sample points.
"""
import numpy as np
import pyqtgraph as pg
from pyqtgraph.graphicsItems.NonUniformImage import NonUniformImage
RPM2RADS = 2 * np.pi / 60
RADS2RPM = 1 / RPM2RADS
kfric = 1 # [Ws/rad] an... | Python | 1 |
.add_depends((&package, &version));
}
}
"description" => {
builder.short_desc(&item.value::<String>().unwrap());
}
"long_description" => {
builder.long_desc(&item.value::<String>().unwrap());
}
"versi... | Rust | 0 |
# encoding:utf-8
import os
import signal
import sys
import time
from channel import channel_factory
from common import const
from config import load_config
from plugins import *
import threading
def sigterm_handler_wrap(_signo):
old_handler = signal.getsignal(_signo)
def func(_signo, _stack_frame):
... | Python | 1 |
def count_up(start, stop):
"""Print all numbers from start up to and including stop.
For example:
count_up(5, 7)
should print:
5
6
7
"""
for num in range(start, stop + 1):
print(num)
count_up(5, 7)
| Python | 1 |
8, 0.0).unwrap();
/// graph.add_edge(8, 17, 0.0).unwrap();
///
/// let start = graph.get_vertex(1).unwrap();
/// let mut visitor = CustomVisitor{ visiting_order: vec![] };
/// algorithms::bfs_with_visitor(&graph, &start, &mut visitor).unwrap();
///
/// assert_eq!(vec![1, 2, 3, 4, 5, 8, 17], visitor.visiting_order);
//... | Rust | 0 |
Arc<ContractsCellDep>>;
async fn query_rollup_cell(&self) -> Result<Option<CellInfo>>;
async fn query_unlockable_withdrawals(
&self,
last_finalized_block_number: u64,
unlocked: &HashSet<OutPoint>,
) -> Result<Vec<CellInfo>>;
async fn complete_tx(&self, tx_skeleton: Transaction... | Rust | 0 |
import os
import sys
import numpy as np
import pyarrow as pa
from dora import Node
from pyorbbecsdk import Pipeline, Config, OBSensorType, FrameSet,OBFormat,OBError
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.append(current_dir)
from utils import frame_to_bgr_image
import atexit
def main():
... | Python | 1 |
import requests
from datetime import datetime
USERNAME = "anjiri"
TOKEN = "jS(d*Sa)dLOpM{UJ"
GRAPHID = "graph1"
pixela_endpoint = "https://pixe.la/v1/users"
user_params = {
"token": TOKEN,
"username": USERNAME,
"agreeTermsOfservice": "yes",
"notMinor": "yes"
}
# response = requests.post(url=pixela_en... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.