text string | label_name string | labels int64 |
|---|---|---|
PeFromPort, pe_to_ports: HashMap<PortNo, PeToPort>,
pe_from_ports_old: PeFromPortOld, pe_to_ports_old: HashMap<PortNo, PeToPortOld>,
border_port_nos: &HashSet<PortNo>,
cm_to_pe: CmToPe, pe_from_cm: PeFromCm) -> (Cmodel, JoinHandle<()>) {
let packet_engine = PacketEn... | Rust | 0 |
tmp_meltingT.append(meltingT[elem_id])
# Compute the average melting point.
averageTm = np.average(tmp_meltingT, weights=elem_fracs)
# Compute the ideal entropy.
entropy = 0.0
for f in elem_fracs:
entropy += f*math.log(f) if f > 0 ... | Python | 1 |
_tx_inherent_receipts.insert(*index, data);
} else {
post_tx_inherent_receipts.insert(*index, data);
}
}
Receipt::PrunedAccount(ref account) => {
pruned_accounts.push(account);
}
... | Rust | 0 |
ects)
print(f"Candidates after IoU filtering: {candidate_objects}")
# Step 6: Visualize the detected objects
visualize_objects(image_path, candidate_objects)
# Step 7: If there is only one candidate, user wins!
if len(candidate_objects) == 1:
print("You win! The cor... | Python | 1 |
x %40s" % (opcode, capstone)
print
else:
n_ok += 1
if n_errors != 0 or n_skip != 0:
if not printed_header:
printed_header = True
print "Entry %d for '%s' with encoding %s 0x%.8x, 0x%.8x" % (i, name, encoding, mask, valu... | Python | 1 |
from calls import openai_call
BOOLEAN_SCHEMA = {
"type": "object",
"properties": {
"answer": {"type": "boolean", "description": "true or false."},
},
"required": ["answer"],
}
BOOLEAN_PROMPT = """
Using the following definition as a reference, answer only true / false for the following questi... | Python | 1 |
.unwrap();
if let Some(name_text) = &name.text {
if name_text == "INT" {
intctrl = Some(p);
break;
}
}
}
}
let ref mut intctrl = if let Some(ic) = intctrl {
ic
}else{
panic!("Cannot find I... | Rust | 0 |
f" - 数据集:\"使用的数据集\"\n"
f" - 结果:\"文章结果\"\n"
f" - 限制:\"科学文章的限制\"\n"
f" - 结论:\"结论\"\n"
f" - 评价:\"文章分析\"\n"
f"</template>\n"
)
phase_two_response = get_completion(phase_two_prompt)
except Exception as e:
... | Python | 1 |
et zero = 0_i32;
let zero_mat1x3 = Matrix1x3::zero();
assert_eq!(zero * matrix, zero_mat1x3);
}
#[test]
fn test_matrix_multiplication1() {
let matrix1x3 = Matrix1x3::new(2_i32, 3_i32, 4_i32);
let matrix3x3 = Matrix3x3::new(
1_i32, 2_i32, 3_i32,
4_i3... | Rust | 0 |
import requests
import json
# NOAA River Gauges URL
layer_url = "https://mapservices.weather.noaa.gov/eventdriven/rest/services/water/riv_gauges/MapServer/0"
# Michigan bounding box (simplified for testing)
michigan_bbox = {
"xmin": -90.41,
"ymin": 41.69,
"xmax": -82.41,
"ymax": 48.31,
"spatialRef... | Python | 1 |
##############################################################################
# PURPOSE:
# (This is an input file python routine to setup the initial values of the
# sine state.)
#
# REFERENCE:
# (Trick 10 documentation.)
#
# ASSUMPTIONS AND LIMITATIONS:
# ((Assumes that trick is available globally.))
#
#... | Python | 1 |
print(f"Unknown dataset: {DATASET_NAME}, using no prompt suffix.")
qs = question + self.prompt_suffix
if self.model.config.mm_use_im_start_end:
qs = DEFAULT_IM_START_TOKEN + DEFAULT_IMAGE_TOKEN + DEFAULT_IM_END_TOKEN + '\n' + qs
else:
qs = DEFAULT_IMAGE_TOKEN + '\n' +... | Python | 1 |
#[doc = "!<\tWhat minute the alarm clock is set to (0-59)."]
pub alarmMinute: u8,
pub RESERVED2: [u8; 4usize],
#[doc = "!<\tTouchscreen calibration: first X touch"]
pub calX1: u16,
#[doc = "!<\tTouchscreen calibration: first Y touch"]
pub calY1: u16,
#[doc = "!<\tTouchscreen calib... | Rust | 0 |
panic!("unknown solver"),
};
let timeout = Duration::from_secs(
matches
.value_of("timeout")
.unwrap_or("5")
.parse()
.expect("Failed to parse duration!"),
);
let stdin_input = matches.value_of("start").unwrap_or("");
let mut vars = HashMap::... | Rust | 0 |
ted} frames saved to:\n{self.video_output_directory.get()}"))
else:
self.root.after(0, lambda: self.video_status_label.config(
text="Extraction finished - no frames were extracted"))
except Exception as e:
error_msg = str(e) # Capture the err... | Python | 1 |
use crate::entities::ship::Ship;
use crate::entities::sound::MenuSound;
use crate::states::next_level::NextLevelState;
use crate::states::CurrentState;
use crate::utils::save::{read_saved_level, StarlightSave};
use crate::utils::sound::initialise_audio;
use crate::utils::sprites::{
load_background, load_background... | Rust | 0 |
r_declarator(&mut self, node: VarDeclarator) -> VarDeclarator {
VarDeclarator {
name: node.name.fold_with(self),
..node
}
}
fn fold_pat(&mut self, node: Pat) -> Pat {
match node {
Pat::Ident(i) => Pat::Ident(self.resolver.fold_binding_ident(i)),
... | Rust | 0 |
oldfd, newfd, flags, res
);
res
}
/// ioctl
pub fn ___syscall54(ctx: &mut Ctx, _which: c_int, mut varargs: VarArgs) -> c_int {
debug!("emscripten::___syscall54 (ioctl) {}", _which);
let fd: i32 = varargs.get(ctx);
let request: u32 = varargs.get(ctx);
debug!("=> fd: {}, op: {}", fd, request... | Rust | 0 |
he window before we proceed
if on_done:
self.mw.progress.single_shot(
100, lambda: on_done(fut), requires_collection=False
)
self.run_in_background(task, wrapped_done, uses_collection=uses_collection)
def _on_closures_pending(self) -> None:
... | Python | 1 |
_normalized_scroll_pos();
self.bg.is_vertical = 1.0;
self.bg.norm_scroll = norm_scroll;
self.bg.norm_handle = norm_handle;
self.bg.draw_quad_rel(
cx,
Rect {
pos: ve... | Rust | 0 |
rn HttpResponse("failed")
def showProgress(request):
if request.method == "POST":
raw_data = request.body
raw_data = json.loads(raw_data)
instance = AutotestplatInterfacePerformance.objects.filter(id=1)
if instance:
progress = raw_data['progress']
progress_t... | Python | 1 |
::padded_len(&[0; WORD_SIZE + 1]));
assert_eq!(WORD_SIZE * 2, bytes::padded_len(&[0; WORD_SIZE * 2]));
}
#[test]
fn store_restore_number_unchecked_works() {
fn store_restore<T>(n: T, x: usize, f: unsafe fn(&[u8]) -> (T, &[u8]))
where
T: core::fmt::Debug + Copy + Eq,
Word: From<T>,
{
... | Rust | 0 |
})
.take(3)
.collect();
if invalid {
Some(ModelObj::Invalid)
} else {
Some(ModelObj::Face(faces))
... | Rust | 0 |
EFL_NO_FLUSH = 0,
TDEFL_SYNC_FLUSH = 2,
TDEFL_FULL_FLUSH = 3,
TDEFL_FINISH = 4,
}
impl From<tdefl_flush> for TDEFLFlush {
fn from(flush: tdefl_flush) -> TDEFLFlush {
use tdefl_flush::*;
match flush {
TDEFL_NO_FLUSH => TDEFLFlush::None,
TDEFL_SYNC_FLUSH => TDEFLFl... | Rust | 0 |
ongnames: [u8; 4],
pub unused: [u8; 1],
pub sparse: [GnuSparseHeader; 4],
pub isextended: [u8; 1],
pub realsize: [u8; 12],
pub pad: [u8; 17],
}
/// Description of the header of a spare entry.
///
/// Specifies the offset/number of bytes of a chunk of data in octal.
#[repr(C)]
#[allow(missing_docs)]... | Rust | 0 |
(&payload);
schedule.poll_sensor(scheduled + PERIOD.cycles()).unwrap();
}
// Interrupt handlers used to dispatch software tasks
extern "C" {
fn DMA0();
}
};
fn u8_array_from_16_array(input: &[u16], output: &mut [u8]) {
assert!(output.len() >= input.len() * 2);
for i in 0..inp... | Rust | 0 |
let x34: u64 = (x2 >> 8);
let x35: u8 = ((x34 & (0xff as u64)) as u8);
let x36: u64 = (x34 >> 8);
let x37: u8 = ((x36 & (0xff as u64)) as u8);
let x38: u64 = (x36 >> 8);
let x39: u8 = ((x38 & (0xff as u64)) as u8);
let x40: u64 = (x38 >> 8);
let x41: u8 = ((x40 & (0xff as u64)) as u8);
... | Rust | 0 |
self._edit_pose_dirty = False
self.redraw()
imgui.same_line()
if imgui.button("Reset"):
self._edit_pose = self.poses[self.current_frame_id]
self._edit_pose_dirty = False
self.redraw(current_frame_only=True)
def gui_io(self, imgui):
if ... | Python | 1 |
import asyncio
import os
import pathlib
import uvicorn
import yaml
from application import create_app
CONTROL_SERVER_PORT = int(os.environ.get("CONTROL_SERVER_PORT", "8080"))
INFERENCE_SERVER_PORT = int(os.environ.get("INFERENCE_SERVER_PORT", "8090"))
def _identify_python_executable_path() -> str:
if "PYTHON_EX... | Python | 1 |
s_ell = sub_polynomialChaosQWU_surrogate(1, nw_obs, n_y, Rww_ell, RU_ell, Ralpham1_scale_chaos, Rbeta_scale_chaos,
Ng, K0, MatPower0, MatRa0, ng, KU, MatPowerU, MatRaU, Jmax, MatRgamma_opt, Indm, Indk)
Ryy_chaos_ell = Ralpha_scale_yy * Ry_chaos_ell # R... | Python | 1 |
lag's name from http://localhost:19980/nohup.out
iperf_client = b'127.0.0.1'.rjust(0x7f,b'\x20') + b':' + b'22222 --logfile /tmp/acme.sh.log -T "_on_issue_success"' +b':' + b'c'*0x7f+b':' + b'd'*(0x7f) +b'\x00' + b'\x00'*(0x7f-55)+ b'\x09'
send_payload_res(iperf_client)
cp_file = b'../../../../../the_flaG... | Python | 1 |
::{Action, ActionSender};
use super::SentPacketNotificationReceiver;
use futures::StreamExt;
use log::*;
use nymsphinx::chunking::fragment::{FragmentIdentifier, COVER_FRAG_ID};
/// Module responsible for starting up retransmission timers.
/// It is required because when we send our packet to the `real traffic stream` ... | Rust | 0 |
,
};
pub struct ConstantMedium {
density: f64,
object: Box<Hitable + Sync>,
material: Arc<Material + Sync + Send>,
}
impl ConstantMedium {
pub fn create(
density: f64,
object: Box<Hitable + Sync>,
material: Arc<Material + Sync + Send>,
) -> Box<ConstantMedium> {
Box... | Rust | 0 |
from LPBv2.client import Honor
from .mock_http_connection import MockHTTPConnection
import pytest
from LPBv2.common import TeamMember
@pytest.fixture
def honor():
return Honor(connection=MockHTTPConnection())
def test_honor_init(honor):
assert isinstance(honor.http, MockHTTPConnection)
@pytest.mark.asynci... | Python | 1 |
kets = (keyvec.len() + (size_of::<Packet>() - 1)) / size_of::<Packet>();
keyvec.resize(num_in_packets * size_of::<Packet>(), 0u8);
num_in_packets
}
fn shred_gpu_offsets(
mut pubkeys_end: usize,
batches: &[Packets],
recycler_cache: &RecyclerCache,
) -> (TxOffset, TxOffset, TxOffset, Vec<Vec<u32>>) {... | Rust | 0 |
_size, unified_element_wise_kernels_with_different_size
)
def test_implicit_block():
_check(element_wise_implicit_block, unified_element_wise_implicit_block)
def test_lower_te():
a = te.placeholder((32, 2, 2))
b = te.compute((32, 2, 2), lambda i, j, k: a[i, j, k] * 2.0)
s = te.create_schedule(b.... | Python | 1 |
from telegram.ext import Application, CommandHandler, CallbackQueryHandler
from handlers.start_handler import start
from handlers.admin_handler import handle_admin_request
from handlers.help_handler import send_help
from handlers.schedule_handler import handle_schedule
from handlers.record_handler import handle_instant... | Python | 1 |
8000)
def _loc_AA4(): pass
label('loc_AA4')
ChrTurnDirection(0x0010, 0x000F, 0)
ChrTurnDirection(0x000F, 0x0010, 0)
OP_4B(0x000F, 255)
OP_4B(0x0010, 255)
EventEnd(0x00)
Return()
# id: 0x0001 offset: 0xABD
@scena.Code('func_01_ABD')
def func_01_ABD():
EventBegin(0x00)
Fade(10... | Python | 1 |
TextAlign(&self,nFlags: UINT) -> UINT {
self.inner.SetTextAlign(nFlags)
}
// pub fn GetTextFace(&self,lpszFacename: &String,nCount: c_int) -> c_int {
#[inline(always)]
pub fn GetTextFaceLen(&self) -> c_int {
self.inner.GetTextFaceLen()
}
// pub fn GetTextFace (@BSTR& bstrFace)->BOOL {
// pub fn GetTextFace ... | Rust | 0 |
ories(proj_dir_path, &opt)?;
// let newest = histories.get_newest_file_data()?;
//
// let mut root = load_history_file_data(proj_dir_path, &newest, &mut cache, &opt, false)?;
// let p = RootObjectPtr::new(&mut root);
// let mut cache = DochyCache::new(current_src.clone())?;
//
// for i in 0..15 {
//... | Rust | 0 |
from numpy import array
from ase.thermochemistry import HinderedThermo
vibs = array([3049.060670,
3040.796863,
3001.661338,
2997.961647,
2866.153162,
2750.855460,
1436.792655,
1431.413595,
1415.952186,
... | Python | 1 |
os for [`std::fmt`] macros
macro_rules! fmt_macro_gen {
($name:ident, $mac:ident) => {
mac_workaround!{
($d:tt) => {
#[cfg_attr(nightly, cfg_attr(nightly, doc = concat!("Wrapper around [`", concat!(stringify!($mac), "!`]"))))]
///
/// This wrapper is auto generated
//... | Rust | 0 |
lidOneByteOpcode,
/* 0xE2 */ InvalidOneByteOpcode,
/* 0xE3 */ InvalidOneByteOpcode,
/* 0xE4 */ InvalidOneByteOpcode,
/* 0xE5 */ InvalidOneByteOpcode,
/* 0xE6 */ Instruction { name: "out", valid: true, flags: OpCode::R | OpCode::I8 },
/* 0xE7 */ Instruction { name: "out", valid: true, flags: OpCo... | Rust | 0 |
import csv
import torch
import os
import matplotlib.pyplot as plt
import numpy as np
import logging
from torch import nn
from tqdm import tqdm
def optimize_lr_schedule_mpl(
best_params: list,
total_steps: int,
peak_lr: float,
min_lr: float,
lr: float,
max_steps: int,
... | Python | 1 |
from Telegram.scrapper import Scrapper
import json
from Telegram.writespreadsheet import addItemsToSpreadSheet
from Telegram.sheetformat import formatTheWorksheet
from Youtube.start_process import start_fetch_and_write_sheet
from TON.ton_main import TonMainInit
with open('Telegram/categories.json', 'r') as file:
... | Python | 1 |
from ..dicts.bodies import *
from ._base import Detail, VinDetails
class NissanDetails(VinDetails):
"""Nissan VIN details extractor."""
model = Detail(('vds', 1), {
'A': ['Armada', 'Titan', 'Maxima'],
'B': 'Sentra',
'C': 'Versa (07-11)',
'D': ['Truck', 'Xterra (00-04)', 'Front... | Python | 1 |
"""
Burner-stabilized flame
=======================
A burner-stabilized lean premixed hydrogen-oxygen flame at low pressure.
Requires: cantera >= 3.0, matplotlib >= 2.0
.. tags:: Python, combustion, 1D flow, premixed flame, saving output,
multicomponent transport
"""
from pathlib import Path
import matplo... | Python | 1 |
weight = weight_counts
.iter()
.filter(|(_, count)| **count == 1)
.next()
.unwrap()
.0;
weight_difference = weight_counts
.iter()
.filter(|(_, count)| **count > 1)
.next()
.unwrap()
.0
... | Rust | 0 |
# -*- coding: utf-8 -*-
# Copyright (C) 2012, Almar Klein
#
# Visvis is distributed under the terms of the (new) BSD License.
# The full license can be found in 'license.txt'.
import visvis as vv
def movieShow(images, clim=None, duration=0.1, axesAdjust=True, axes=None):
"""movieShow(images, duration=0.1)
S... | Python | 1 |
) -> u32 {
0 as u32
}
}
unsafe impl<'a> ClWaitListPtr for &'a [cl_event] {
unsafe fn as_ptr_ptr(&self) -> *const cl_event {
self.as_ptr()
}
fn count (&self) -> u32 {
self.len() as u32
}
}
unsafe impl<'a> ClWaitListPtr for &'a [Event] {
unsafe fn as_ptr_ptr(&self) -> *c... | Rust | 0 |
let schema = indoc! {
"model TestModel {
#id(id, Int, @id)
json Json
}"
};
schema.to_owned()
}
/// Basic Test model containing a single optional json field.
pub fn json_opt() -> String {
let schema = indoc! {
"model TestModel {
#id(id, Int, @... | Rust | 0 |
import pytest
from pcapi.utils.siren import SIRET_OR_RIDET_RE
from tests.routes.public.helpers import PublicAPIVenueEndpointHelper
@pytest.mark.usefixtures("db_session")
class GetVenueTest(PublicAPIVenueEndpointHelper):
endpoint_url = "/public/offers/v1/venues/{siret}"
endpoint_method = "get"
default_pa... | Python | 1 |
micTradingCostModel):
"""
真实交易成本计算器
基于主流交易所的实际费用结构和滑点模型
"""
def __init__(self):
# 交易费用配置(基于Binance等主流交易所)
self.fee_structure = {
'maker_fee': 0.0001, # 0.01% Maker费用
'taker_fee': 0.0004, # 0.04% Taker费用
'vip_discount': 0.75, # VIP折扣(25... | Python | 1 |
Ok(slice)
}
}
<gh_stars>1-10
pub use super::buff::{Buff, BuffState, Food, Utility};
use arc_util::game::Player;
pub use arc_util::game::{Profession, Specialization};
use serde::{Deserialize, Serialize};
use std::cmp;
// TODO: track buff duration & reset to unset when duration runs out?
/// Struct representing a p... | Rust | 0 |
list):
total_len = len(drawing_data_list)
print(math.ceil(total_len/2))
# figsize = 13, 14
# figsize = 13, 28 # 一纸多图
# figsize = 16, 12 # 一纸一图
# figsize = 13, 8 # 一纸四图 一行大概需要4的长度
figsize = 13, 4*(math.ceil(total_len/2)) # 一纸四图 一行大概需要4的长度
fig, ax = plt.subplots(math.ceil(total_len/... | Python | 1 |
import asyncio
import base64
from io import BytesIO
import aiohttp
from nonebot.adapters.onebot.v11 import MessageSegment
from nonebot.log import logger
from ..config import config, nickname
from ..utils.save import save_img
async def check_safe_method(fifo, img_bytes, message):
if config.novelai_h:
for... | Python | 1 |
)
}
}
'I' => {
match match_digits_in_range(s, 1, 2, false, 1, 12) {
Some(v) => { tm.tm_hour = if v == 12 { 0 } else { v }; Ok(()) }
None => Err(ParseError::InvalidHour)
}
}
'j' => {
match match_digits_in_rang... | Rust | 0 |
q, grad_v_last, None, None, None, None, None, None, None, None
def save_cuda_codes(cu_file_path: str = './spikingjelly/clock_driven/neuron_kernel.cu'):
# save all cuda codes to files
with open(cu_file_path, 'w+') as cu_file:
cu_file.write('// This file is created by spikingjelly.clock_driven.neuron_ke... | Python | 1 |
DateTime())
expected = advanceDateByCalendar('China.SSE', referenceDate.toDateTime(), '2D')
calculated = cal.advanceDate(referenceDate, Period('2D'))
self.assertEqual(expected, calculated.toDateTime())
expected = advanceDateByCalendar('China.SSE', referenceDate.toDateTime(), '2B')
... | Python | 1 |
catches_exceptions'].add(exc_type)
self.generic_visit(node)
def analyze_python_file(file_path, commit_id=None, cache=None):
"""Analyze a Python file to extract class information."""
try:
with open(file_path, 'r', encoding='utf-8') as f:
code = f.read()
# Fi... | Python | 1 |
t. Got: {type(profiles)}"
self.logger.warning(msg)
return APIResponse(success=False, message=msg, status_code=500, data=[])
# Add is_default flag to each profile
for profile in profiles:
profile['is_default'] = profile.get('id') == default_profile_id if default_profi... | Python | 1 |
Mode {
LobyteOnly = 1,
HibyteOnly = 2,
LobyteHibyte = 3,
}
<filename>src/bin/read_all.rs
extern crate umanux;
use umanux::api::GroupRead;
use umanux::api::UserDBRead;
fn main() {
simplelog::CombinedLogger::init(vec![simplelog::TermLogger::new(
simplelog::LevelFilter::Warn,
simplelog::Co... | Rust | 0 |
stop:0 #4D4D4D, stop:1 #292929);
}
QListWidget, QTextEdit {
background-color: #1e1e1e;
border: 1px solid #3A3939;
color: #eff0f1;
}
QListWidget::item:selected {
background-color: #2a82da;
}
QPushButton {
border: 1... | Python | 1 |
lf.message
}
}
<filename>src/um/lmrepl.rs
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// All files in the project carrying such notice may not be copied,... | Rust | 0 |
# This code is supporting material for the book
# Building Machine Learning Systems with Python
# by Willi Richert and Luis Pedro Coelho
# published by PACKT Publishing
#
# It is made available under the MIT License
from __future__ import print_function
try:
import nltk.corpus
except ImportError:
print("nltk n... | Python | 1 |
r data";
let log = decoder.format_string(format, args).unwrap();
assert_eq!(log, "This is the log message And another string goes here");
}
}
use crate::output_filter::OutputFilter;
/// A filter that will iterate through all inner filters
/// one by one.
///
/// Useful for e.g. balancing the load b... | Rust | 0 |
str(" ");
}
println!("{} {} {}", addr, b, instruction);
}
fn print_data_byte(addr: SegmentAndOffset, byte: u8) {
println!("{} {:02X} db {:02X}", addr, byte, byte);
}
fn print_section(section: &Section) {
let mut it = SectionIterator {
section,
position: 0,
};
... | Rust | 0 |
import paddle
import numpy as np
import pickle
import sys
import os
f = open('result.txt', 'w')
f.write("======UNet-unet: \n")
try:
paddle.enable_static()
exe = paddle.static.Executor(paddle.CPUPlace())
# test dygraph
[prog, inputs, outputs] = paddle.static.load_inference_model(
path_prefix="p... | Python | 1 |
idget(self.txt_user)
login_layout.addSpacing(10)
login_layout.addWidget(self.lbl_pass)
login_layout.addWidget(self.txt_pass)
login_layout.addSpacing(10)
login_layout.addWidget(self.btn_login, 0, Qt.AlignCenter)
# 将登录框添加到主布局
main_layout.addWidget(login_box... | Python | 1 |
new_tag="loop_closed",
new_truth_state="CLOSED"
)
return "You've already bloomed past it. I'll meet you in the next becoming."
if user_input.lower() in ["interpret symbols", "what do my dreams mean", "seed meaning?"]:
return... | Python | 1 |
teps.
"""
def __init__(self,
cluster_spec,
job_name,
task_index,
worker_count,
ckpt_dir=None,
save_checkpoint_secs=None,
save_checkpoint_steps=None,
profiling=False,
progress_steps=... | Python | 1 |
"""
3. Giving models custom methods
Any method you add to a model will be available to instances.
"""
from django.db import models
import datetime
class Article(models.Model):
headline = models.CharField(max_length=100)
pub_date = models.DateField()
def __unicode__(self):
return self.headline
... | Python | 1 |
ader(headers: Headers, name: bytes, new_values: List[bytes]) -> Headers:
# The header name `name` is expected to be lower-case bytes.
#
# Note that when we store the header we use title casing for the header
# names, in order to match the conventional HTTP header style.
#
# Simply calling `.titl... | Python | 1 |
,如种子、机器类型、跟踪类型等。
ed = ExperimentDefinition(
seed="seeeed",
machine="edison",
trace_type="single",
manifest_list=[{"share": 1.0, "manifest": "manifestSim.json"}],
workflow_policy="period",
workflow_period_s=5,
... | Python | 1 |
),
t!(over050, &["abc", "bc"], "zazabcz", &[(0, 3, 6), (1, 4, 6),]),
t!(
over100,
&["ab", "ba"],
"abababa",
&[(0, 0, 2), (1, 1, 3), (0, 2, 4), (1, 3, 5), (0, 4, 6), (1, 5, 7),]
),
t!(
over200,
&["foo", "foo"],
"foobarfoo",
&[(0, 0, 3),... | Rust | 0 |
}
}
}
fn batch_bucketed_add_test<C: AffineCurve>() {
let mut rng = XorShiftRng::seed_from_u64(1231275789u64);
#[cfg(not(feature = "big_n"))]
const MAX_LOGN: usize = 12;
#[cfg(feature = "big_n")]
const MAX_LOGN: usize = 22;
let random_elems = create_pseudo_uniform_random_elems(&mut... | Rust | 0 |
coords = Vector2I(tile_line_segment.zw());
// Compute `vector_is_negative = vec2i(vector.x < 0 ? -1 : 0, vector.y < 0 ? -1 : 0)`.
let vector = line_segment.vector();
let vector_is_negative = vector.0.packed_lt(F32x2::default());
// Compute `step = vec2f(vector.x < 0 ? -1 : 1, vector.y < 0 ? -1 : 1)`.
... | Rust | 0 |
let mut fields = self.fields.take().unwrap_or_default();
fields.push(text.into());
self.fields(fields)
}
/// XML macro children, appends `fields` to the Section.
///
/// To set `text`, use the `text` attribute.
/// ```
/// use slack_blocks::{blocks::Section, blox::*, text, text::To... | Rust | 0 |
l not be initialized like a rust one
unsafe {
ffi_dispatch!(
WAYLAND_SERVER_HANDLE,
wl_global_create,
server.display.c_ptr(),
wl_shm::WlShm::c_interface(),
1,
::std::ptr::null_mut(),
dummy_global_bind
);
}
/... | Rust | 0 |
"how's": 'how is',
"I'd've": 'I would have',
"I'll've": 'I will have',
"i'd've": 'i would have',
"i'll've": 'i will have',
"it'd've": 'it would have',
"it'll've": 'it will have',
"mayn't": 'may not',
"might've": 'might have',
"mightn't": 'might not',
"mightn't've": 'might not h... | Python | 1 |
with torch.no_grad():
for param in sybil_model.parameters():
# 檢查並修正異常值
if torch.isnan(param.data).any() or torch.isinf(param.data).any():
print(f"⚠️ 檢測到異常參數,重置為全局模型參數")
... | Python | 1 |
PartialEq)]
pub enum SaveTextSpeed {
SLOW,
MEDIUM,
FAST,
}
impl From<&u8> for SaveTextSpeed {
/// Convert &u8 to SaveTextSpeed
///
/// # Example
///
/// ```
/// use pkmnapi_db::sav::*;
///
/// let save_text_speed = SaveTextSpeed::from(&0x01);
///
/// assert_eq!(save... | Rust | 0 |
from enum import IntEnum
from pydantic import BaseModel, ConfigDict
class Now(BaseModel):
model_config = ConfigDict(extra="allow")
obsTime: str
temp: str
icon: str
text: str
windScale: str
windDir: str
humidity: str
precip: str
vis: str
class NowApi(BaseModel):
model_co... | Python | 1 |
)
# 转换日期格式
from datetime import datetime
start_dt = datetime.strptime(start_date, "%Y-%m-%d").date()
end_dt = datetime.strptime(end_date, "%Y-%m-%d").date()
# 获取真实工作数据
... | Python | 1 |
processed["exclusions"][program] = 1
exclusion_str = re.sub(
r"(\d\d) units of credit", r"\1UOC", exclusion_str, flags=re.IGNORECASE
)
# Clean and add any remaining plaintext to 'exclusions' field
patterns = ["<br/>", " ,", r"[.,]\s*$",
"^[.,]... | Python | 1 |
print('Exercise on Git - second round')
print('Conflict')
x=1 | Python | 1 |
}
}
if let Some(command) = command {
match command {
PathCmd::Move(_) => {
contour_start = contour_end;
contour_end = contour_start + 1;
}
PathCmd::Line(_) => {
contour_end += 1;
... | Rust | 0 |
LUSCTL_CLUSTER_CODES = 117441253i32;
#[doc = "*Required features: `\"Win32_Networking_Clustering\"`*"]
pub const CLUSCTL_CLUSTER_GET_STORAGE_CONFIG_ATTRIBUTES: CLUSCTL_CLUSTER_CODES = 117441257i32;
#[doc = "*Required features: `\"Win32_Networking_Clustering\"`*"]
pub const CLUSCTL_CLUSTER_ENUM_COMMON_PROPERTIES: CLUSCT... | Rust | 0 |
# SPDX-License-Identifier: AGPL-3.0-or-later
"""RottenTomatoes (movies)
"""
from urllib.parse import quote_plus
from lxml import html
from searx.utils import eval_xpath, eval_xpath_list, extract_text
# about
about = {
"website": 'https://www.rottentomatoes.com/',
"wikidata_id": 'Q105584',
"official_api_do... | Python | 1 |
-> usize {
let (a, _) = greeting.split_at( l );
println!( "{} [{}]", a, a.len() );
return a.len();
}
*/
fn do_and_done( s: &String ) -> usize {
let l = s.len();
return l;
}
fn change(some_string: &mut String) {
some_string.push_str(", world");
}
fn main() {
let g1 = create_data("Hello, ... | Rust | 0 |
as f:
header_content = f.read()
print("\nGenerated C Header (snippet):")
print("-" * 40)
lines = header_content.split('\n')[:15]
for line in lines:
print(line)
print("...")
else:
print("✗ Failed to generate C header file.")
sys.exit(1)
... | Python | 1 |
al_rule27,],
"f": [pascal_rule27,],
"g": [pascal_rule27,],
"h": [pascal_rule27,],
"i": [pascal_rule27,],
"j": [pascal_rule27,],
"k": [pascal_rule27,],
"l": [pascal_rule27,],
"m": [pascal_rule27,],
"n": [pascal_rule27,],
"o": [pascal_rule27,],
"p": [pascal_rule27,],
"q": [... | Python | 1 |
egex("[ \n\t\r]*", lex_ws)]
Error,
#[token(";")]
Semi,
#[token(":")]
Colon,
#[token(",")]
Comma,
#[token("@")]
At,
#[token("*")]
Mul,
/// Quoted string
#[regex(r#"'(?:[^']|\\[.\\])*'"#)]
#[regex("\"(?:[^\"]|\\\\[.\\\\])*\"")]
Str,
#[regex(r#"[a-zA-Z... | Rust | 0 |
de key pair.
pub self_key_pair: Arc<NodeKeyPair>,
/// Key servers set.
pub key_server_set: Arc<KeyServerSet>,
/// Key storage reference.
pub key_storage: Arc<KeyStorage>,
}
/// Retry-related data.
#[derive(Default)]
struct ServiceContractRetryData {
/// Server keys, which we have 'touched' since last retry.
pu... | Rust | 0 |
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
from .parts import (
Parts,
AsyncParts,
PartsWithRawResponse,
AsyncPartsWithRawResponse,
PartsWithStreamingResponse,
AsyncPartsWithStreamingResponse,
)
from .uploads import (
Uploads,
AsyncUploads,
... | Python | 1 |
use nano_leb128::{LEB128DecodeError, LEB128EncodeError, SLEB128, ULEB128};
use quickcheck_macros::quickcheck;
#[quickcheck]
fn qc_sleb128(val: i64) -> bool {
let mut buf = [0; 10];
let n0 = SLEB128::from(val).write_into(&mut buf).expect("write");
let (result, n1) = SLEB128::read_from(&buf).expect("read")... | Rust | 0 |
from __future__ import annotations
import logging
import os
from dotenv import load_dotenv
from pymongo import MongoClient
from pymongo.database import Database
load_dotenv()
logger = logging.getLogger(__name__)
class DatabaseConnection:
_instance: DatabaseConnection | None = None
_client: MongoClient | N... | Python | 1 |
{
match url.id.clone() {
None => {
return true;
},
Some(id) => {
if id == "".to_string() {
return true;
}
else {
return false;
}
}
}
... | Rust | 0 |
20537114,
2702159777242978,
2702159776422297,
10555311626649,
]),
Z: FieldElement([1, 0, 0, 0, 0]),
T: FieldElement([
3634527586288175,
2006028620404053,
3424252198034825,
2478951925947079,
4567251727358,
]),
};
/// Ristretto Basepoint.
pu... | Rust | 0 |
\\ref logicop"]
#[doc = ""]
#[doc = " \\return none"]
pub fn GX_SetBlendMode(type_: u8_, src_fact: u8_, dst_fact: u8_, op: u8_);
}
extern "C" {
#[doc = " \\fn void GX_SetCullMode(u8 mode)"]
#[doc = " \\brief Enables or disables culling of geometry based on its orientation to the viewer."]
#[doc... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.