text string | label_name string | labels int64 |
|---|---|---|
otherwise."]
#[doc = ""]
#[doc = " Returns -pte_invalid if \\@decoder or \\@time is NULL."]
#[doc = " Returns -pte_no_time if there has not been a TSC packet."]
pub fn pt_qry_time(
decoder: *mut pt_query_decoder,
time: *mut u64,
lost_mtc: *mut u32,
lost_cyc: *mut u32,
... | Rust | 0 |
_by_id(&self, id: i32) -> Result<Option<User>> {
let row = self.user_by_id.query_opt(&[&id]).await?;
Ok(user_from_opt_row(&row))
}
pub async fn get_by_email(&self, email: &str) -> Result<Option<User>> {
let row = self.user_by_email.query_opt(&[&email]).await?;
Ok(user_from_opt_row(&row))
}
pub... | Rust | 0 |
amount::serde::as_btc")]
pub amt: Amount,
#[serde(with = "::util::amount::serde::as_btc")]
pub samt: SignedAmount,
}
let orig = T {
amt: Amount::from_sat(250_000__000_000_01),
samt: SignedAmount::from_sat(-215_000__000_000_01),
};
... | Rust | 0 |
::{IpAddr, Ipv4Addr, SocketAddr};
#[tokio::test]
async fn remote_addr_missing() {
let extract_remote_addr = warp::addr::remote();
let req = warp::test::request();
let resp = req.filter(&extract_remote_addr).await.unwrap();
assert_eq!(resp, None)
}
#[tokio::test]
async fn remote_addr_present() {
l... | Rust | 0 |
.endpoint,
'Content-Type': 'application/x-amz-json-1.1',
'Content-Length': str(len(body)),
}
http_request = self.build_base_http_request(
method='POST', path='/', auth_path='/', params={},
headers=headers, data=body)
response = self._mexe(http_requ... | Python | 1 |
_count": 0,
"favorited": false,
"retweeted": false,
"lang": "en"
}
"##;
let resp = RawResponse {
raw_response: response_json.to_string(),
rate_limit: None,
};
let twitter_result: TwitterResult<Tweet> = resp.parse_to_object();
assert!(twitter_result.i... | Rust | 0 |
import sys
from metaflow.sidecar import MessageTypes, Message
from metaflow.monitor import NullMonitor, Metric
class DebugMonitor(NullMonitor):
TYPE = "debugMonitor"
@classmethod
def get_worker(cls):
return DebugMonitorSidecar
class DebugMonitorSidecar(object):
def __init__(self):
... | Python | 1 |
import networkx.algorithms.tests.test_dag
import pytest
from graphscope.nx.utils.compat import import_as_graphscope_nx
from graphscope.nx.utils.compat import with_graphscope_nx_context
import_as_graphscope_nx(networkx.algorithms.tests.test_dag,
decorators=pytest.mark.usefixtures("graphscope_se... | Python | 1 |
core::fmt::Formatter<'_>) -> core::fmt::Result {
use core::fmt::Write;
use EntryBits::*;
f.write_str("<Entry: ")?;
if self.value & VALID == 0 {
f.write_fmt(format_args!("Invalid entry: {:x}", self.value))?;
} else if self.value & RWX == 0 {
f.write_fmt(f... | Rust | 0 |
back to
January 01 of the current year. Month and year "todate"
are currently available only for the built-in
(Gregorian) calendar.
templateitemname
Used to refer to a named item in this array in the
template. Named items from the template will be cre... | Python | 1 |
#Warna kode
color_red = "\033[91m"
color_purple = "\33[95m"
color_blue1 = "\33[34m"
color_blue2 = "\33[36m"
color_blue3 = "\33[96m"
color_green1 = "\033[92m"
color_green2 = "\033[32m"
color_brown = "\33[33m"
color_yellow = "\33[93m"
color_grey = "\33[37m"
color_default = "\033[0m"
HP_color = color_green1
ANSI_RESET =... | Python | 1 |
rap();
let fuel_capacity = reader.read_f32::<LittleEndian>().unwrap();
let fuel_remaining_laps = reader.read_f32::<LittleEndian>().unwrap();
let max_rpm = reader.read_u16::<LittleEndian>().unwrap();
let idle_rpm = reader.read_u16::<LittleEndian>().unwrap();
let max_gears = reader... | Rust | 0 |
from sklearn.metrics.pairwise import cosine_similarity
X = [[0, 0, 0], [1, 1, 1]]
Y = [[1, 0, 0], [1, 1, 0]]
print(cosine_similarity(X, Y)) | Python | 1 |
return params
@staticmethod
def from_alipay_dict(d):
if not d:
return None
o = ContentInfoModel()
if 'booth' in d:
o.booth = d['booth']
if 'content_id_str' in d:
o.content_id_str = d['content_id_str']
if 'ext_info' in d:
... | Python | 1 |
mp = is.read_uint32()?;
self.port = tmp;
},
3 => {
::protobuf::rt::read_singular_proto3_bytes_into(wire_type, is, &mut self.public_key)?;
},
_ => {
::protobuf::rt::read_unknown_or_skip_group(field... | Rust | 0 |
-> ::std::os::raw::c_int;
}
extern "C" {
pub fn bam_mplp_init(
n: ::std::os::raw::c_int,
func: bam_plp_auto_f,
data: *mut *mut ::std::os::raw::c_void,
) -> bam_mplp_t;
}
extern "C" {
pub fn bam_mplp_init_overlaps(iter: bam_mplp_t) -> ::std::os::raw::c_int;
}
extern "C" {
pub fn ... | Rust | 0 |
nReply,
channel_id: u64,
) -> anyhow::Result<()> {
let author_name = member.nick.clone().unwrap_or(member.user.name.clone());
reply.data.content = format!("Hi, {}! We are going to play hangman!", &author_name);
let mut response = client.post(&url).json(&reply).send().await?;
response.error_for_statu... | Rust | 0 |
lSubcompositor, move |_, _, _| {
Ok(Box::new(RequestDispatcher::new(Subcompositor::new())))
});
registry.add_global(WlOutput, move |id, _, client| {
Output::update_display_info(id, client);
Ok(Box::new(RequestDispatcher::new(Output::new())))
});
{
... | Rust | 0 |
ge(h * 0.9, h * 1.1),
random_range(s * 0.9, s * 1.1),
l * color_adjust,
1.0 / n_layers as f32,
)
};
(meander(&polygon, 5, 0.8), color, pt2(x, y))
})
.collect()
}
fn draw_shapes_layer1(draw: &Draw, model: &Model, win: &Rect) {
let shapes = generate_shapes(mode... | Rust | 0 |
cture
let (hdr_prefix, options) = if let Some(pfx) = buffer.take_obj_front::<HeaderPrefix>() {
// If the subtraction data_offset*4 - HDR_PREFIX_LEN would have been
// negative, that would imply that data_offset has an invalid value.
// Even though this will end up being Mayb... | Rust | 0 |
S, timeout=20)
detail_response.raise_for_status()
detail_soup = BeautifulSoup(detail_response.content, 'html.parser')
time.sleep(PAGE_LOAD_DELAY / 2) # Menor delay para subpáginas
# Encontrar os links dos PDFs na página de detalhes
... | Python | 1 |
Self) -> Self {
Self(self.0.min(other.0))
}
}
#[derive(Debug, PartialEq)]
pub struct Interval<T> {
pub lower: Max<T>,
pub upper: Min<T>,
}
impl<T> Interval<T>
where
T: num_traits::bounds::Bounded,
{
fn top() -> Self {
Self {
lower: Max(T::max_value()),
upper... | Rust | 0 |
from django.db import models
from apps.blog.models import BlogCommentModel
from apps.product.models import ProductCommentModel
from apps.user.models import UserModel
from django_jalali.db import models as jmodels
class TypeNotification(models.Choices):
blog_comment = 'blog_comment'
product_comment = 'product_... | Python | 1 |
nder 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. This file may not be copied, modified, or distributed
// except according to those terms.
// must-compile-successfully
us... | Rust | 0 |
plt.legend()
plt.show()
lrList = [1e-3, 1e-2, 1e-1]
x0 = -0.01
for lr in lrList:
x, y, g = gradientDescent(x0, lr)
# plt.plot(x, label="LR: " + str(lr))
# plt.plot(g, label="LR: " + str(lr))
# plt.plot(y, label="LR: " + str(lr))
plt.scatter(x, y, label="LR: "... | Python | 1 |
MessageBox()
msg.setIcon(QtWidgets.QMessageBox.Information)
msg.setText("Criminal added successfully")
msg.setWindowTitle("Success")
msg.exec_()
self.CriminalIDField.clear()
self.CriminalFirstNameField.clear()
self.CriminalLastNameField.clear()
self.Crimin... | Python | 1 |
ack([ii * 0.8 - 51.2, jj * 0.8 - 51.2, np.ones_like(ii)], axis=-1)
# 应用变换矩阵
transformed_coords = np.dot(original_coords, transformation_matrix_v2_v1.T)
new_x = ((transformed_coords[:, :, 0] + 51.2) / 0.8).astype(int)
new_y = ((transformed_coords[:, :, 1] + 51.2) / 0.8).astype(int)
# 预设输出掩码和坐标映射字典... | Python | 1 |
}
}
#[cfg(any(feature = "v3_20", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v3_20")))]
#[doc(hidden)]
impl FromGlib<ffi::GtkPopoverConstraint> for PopoverConstraint {
fn from_glib(value: ffi::GtkPopoverConstraint) -> Self {
skip_assert_initialized!();
match value {
... | Rust | 0 |
"\nAfter initialization:")
print(f"A shape: {A.shape}")
print(f"φ shape: {φ.shape}")
print(f"π shape: {π.shape}")
print(f"θ shape: {θ.shape}")
# Check initial θ values
print(f"Initial θ[0,0,:5]: {θ[0, 0, :5]}")
print(f"Initial θ exp: {jnp.exp(θ[0, 0, :5])}")
# Expand for sing... | Python | 1 |
2640\U0000FE0F': { # 🏌🏾♀️
'en': ':woman_golfing_medium-dark_skin_tone:',
'status': fully_qualified,
'E': 4,
'de': ':golferin_mitteldunkle_hautfarbe:',
'es': ':mujer_jugando_al_golf_tono_de_piel_oscuro_medio:',
'fr': ':golfeuse_peau_mate:',
'ja': ':ゴルフをする女_やや濃い... | Python | 1 |
"""
Write a python function to check whether the given list contains consecutive numbers or not.
assert check_Consecutive([1,2,3,4,5]) == True
"""
def check_Consecutive(arr):
for i in range(len(arr)-1):
if arr[i+1]-arr[i] != 1:
return False
return True
print(check_Consecutive([1, 2, 3, 4... | Python | 1 |
ter";
pub static ID_SENDER_GRID: &str = "sender_grid";
pub static ID_SENDER_HEADER: &str = "sender_header";
pub static ID_SENDER_STACK: &str = "sender_stack";
pub static ID_SENDER_STACK_ACTION: &str = "sender_stack_action";
pub static ID_SENDER_STACK_COUNTER: &str = "sender_stack_counter";
pub static ID_SENDER_LABEL_CO... | Rust | 0 |
Array,
};
impl BinaryBuilder for Vec<u8> {
fn new() -> Self {
vec![]
}
fn from_raw(ba: &mut ByteArray) -> Option<Self> {
// Length
let len: usize = ba.read_safe()?;
// Bytes Begin
let now: usize = ba.now();
// Bytes End
ba.seek_next(len)?;
// ... | Rust | 0 |
ou `Cargo.toml`:
//!
//! ``` toml
//! [dependencies.lpc8xx-hal]
//! version = "0.6"
//! features = ["824m201jhi33"]
//! ```
//!
//! The above adds a dependency on the `lpc8xx-hal` crate and selects your
//! target hardware. To find out which targets are supported, please check out
//! the list of targets in our [`Carg... | Rust | 0 |
(b" isGenerator")?;
}
if fun_def.is_async() {
w.write_all(b" isAsync")?;
}
if fun_def.is_pair_generator() {
w.write_all(b" isPairGenerator")?;
}
w.write_all(b" ")?;
braces(w, |w| {
ctx.block(w, |c, w| print_body(c, w, body, &fun_def.coeffects))?;
newline(w)
... | Rust | 0 |
#Exercise 1: Create a list, tuple, float, integer, decimal, and dictionary.
list = ['mis', 'frutas', 'del', 'cesto']
tuple = ('manzana', 'banana', 'naranja', 'uva', 'pera')
float = 2.4
integer = 46
from decimal import Decimal
mi_decimal = Decimal(2.4)
dictionary = {'ab': 12, 'bc': 23, 'cd': 34}
#Exercise 2: Round y... | Python | 1 |
(anyhow!(
"invalid buffer length: {} < {}",
len,
MASK_CONFIG_BUFFER_LEN
));
}
Ok(())
}
/// Gets the serialized group type of the masking configuration.
///
/// # Panics
/// May panic if this buffer is unchecked.
pub fn ... | Rust | 0 |
is "r" and str(sys.argv[2]) is "n") or (str(sys.argv[1]) is "n" and str(sys.argv[2]) is "r"):
[pool.apply(resize_intensity_images, args=(TRAINING_SET_PATH, IMAGE_NEW_WIDTH, IMAGE_NEW_HEIGHT, subfolder)) for subfolder in DATASET_SUBFOLDERS]
[pool.apply(normalize_depth_values, args=(TRAINING_SET_... | Python | 1 |
(0x37u32, 0x00, 0xff, 0x23, 0x14, 0x00),
(0xffu32, 0x21, 0x34, 0xac, 0xfffff99f, 0x01),
(0x23u32, 0xff, 0xff, 0x73, 0xffff01af, 0x01),
(0x716172cdu32, 0xf2413551, 0x82988190, 0xacd820ed, 0xd9e58350, 0x7b956e67),
(0xffffffffu32, 0xffffffff, 0xffffffff, 0xffffffff, 0xf... | Rust | 0 |
use umbralux::camera::Camera;
use umbralux::core::{Color, Point, Vector};
use umbralux::features::light::PointLight;
use umbralux::features::material::MaterialBuilder;
use umbralux::io::{export_as_png, export_as_ppm};
use umbralux::objects::object3d::Object3D;
use umbralux::objects::sphere::Sphere;
use umbralux::object... | Rust | 0 |
# -*- coding: utf-8 -*-
"""
@Create: 2024/9/10 10:46
@File: setup.py
@Author: Jingyuan
"""
from setuptools import setup, find_packages
setup(
name="algoSignal", # 包的名字
version="0.1", # 版本号
author="jingyuan", # 作者名字
author_email="jijingyuan@rookiequant.com", # 作者邮箱
description="research tools f... | Python | 1 |
ERR::INVALIDCALL, device.create_index_buffer(1000, Usage::None, Invalid, Pool::Default, ()).err(), "bad format");
assert_eq!(D3DERR::INVALIDCALL, device.create_index_buffer(1000, Usage::None, Format::Index16, Invalid, ()).err(), "bad pool");
assert!(device.get_indices().unwrap().is_none... | Rust | 0 |
#F-string
# to print various data types without changing it to str
# syntax
# f"str_data {other data type value}"
score=10
height=1.8
isWinning=True
print(f"your score is {score} and your height is {height}m, you are winning is {isWinning}")
| Python | 1 |
import random
#EJEMPLO PAPER
def data_paper(size_square,seed):
random.seed(seed)
#Datos para replicar el grafo del paper
num_travels = 2
num_depots = 1
num_charge_stations = 2
num_passenger_stations = 4
Travels = list(range(1,num_travels+1))
Depots = [depot+num_travels for depot in ... | Python | 1 |
x").unwrap();
},
UnaryOperator::BitwiseComplement { ref expression } => {
generate_expression(expression, output);
writeln!(output, "not %eax").unwrap();
},
UnaryOperator::LogicalNegation { ref expression } => {
... | Rust | 0 |
#!/usr/bin/env python3
"""
add_captions Tool Usage Examples
This file demonstrates complete workflows for the add_captions tool,
showing how to add text/subtitle tracks to a video draft.
"""
import sys
import json
import os
import shutil
# Mock the runtime module for standalone testing
import types
from typing impor... | Python | 1 |
'''
Baekjoon Bronze 11721
'''
import sys
input = sys.stdin.readline
word = input()
answer = []
count = 0
temp = ''
for w in word :
count += 1
temp += w
if (count == 10) :
answer.append(temp)
temp = ''
count = 0
if (temp != '') :
answer.append(temp)
for i in answer :
print(i) | Python | 1 |
aInfo,
replicas_len: libc::size_t,
proofs_ptr: *const FFIPoStProof,
proofs_len: libc::size_t,
winners_ptr: *const FFICandidate,
winners_len: libc::size_t,
prover_id: &[u8; 32],
) -> *mut VerifyPoStResponse {
catch_panic_response(|| {
init_log();
info!("verify_post: start");
... | Rust | 0 |
('eV', 'eV'): eV_to_eV
}
conversion_key = (input_unit, output_unit)
if conversion_key in conversion_function:
return conversion_function[conversion_key](energy)
else:
raise ValueError(f'Conversion from {input_unit} to {output_unit} is not supported.')
#external testing
if __na... | Python | 1 |
enitor_support::encode_path(&group_key.to_string()),
crate::progenitor_support::encode_path(&member_key.to_string()),
);
self.client.get(&url, None).await
}
/**
* This function performs a `GET` to the `/admin/directory/v1/groups/{groupKey}/members` endpoint.
*
* Retr... | Rust | 0 |
# 打印结果
for image_path, elements in results.items():
logger.info(f"图片 {image_path}: 检测到 {len(elements)} 个元素")
# 生成可视化结果
output_path = f"batch_result_{Path(image_path).stem}.jpg"
analyzer.visualize_layout(image_path, elements, output_path)
... | Python | 1 |
e2.add(B);
e2.add(C);
assert!(!e1.intersects(e2));
}
#[test]
fn test_disjoint_intersects() {
let mut e1: EnumSet<Foo> = EnumSet::empty();
e1.add(A);
let mut e2: EnumSet<Foo> = EnumSet::empty();
e2.add(B);
assert!(!e1.intersects(e2));
}
#[t... | Rust | 0 |
import flet as ft
name = "Column vertical alignments"
def example():
HEIGHT = 400
def items(count):
items = []
for i in range(1, count + 1):
items.append(
ft.Container(
content=ft.Text(value=str(i)),
alignment=ft.alignment.c... | Python | 1 |
ost")]
address: String,
/// Print the content of all packets
///
/// 0. Print nothing
/// 1. Print command string
/// 2. Print packets
/// 3. Print udp packets
#[structopt(short = "v", long, parse(from_occurrences))]
verbose: u8,
}
#[tokio::main]
async fn main() -> Result<()> { real_main().await }
async fn r... | Rust | 0 |
def cmd take_a_shot(num: i32) -> i32;
}
struct SM {
shots: i32,
}
impl StateMachineCmds for SM {
fn answer_to_the_universe<'a>(&'a self, name: String) -> BoxFuture<'_, String> {
future::ready(format!("{}, the answer is 42", name)).boxed()
... | Rust | 0 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Licensed under the GNU General Public License, version 3.
# See the file http://www.gnu.org/licenses/gpl.txt
from pisi.actionsapi import get
from pisi.actionsapi import autotools
from pisi.actionsapi import pisitools
from pisi.actionsapi import shelltools
libdir = "lib32"... | Python | 1 |
: Node> interleave::Params for Args<N>
{
// Use custom values for these constants, not their defaults.
const PRECHECK_LIMIT: u16 = 321;
const FAST_LIMIT_MAX: u16 = 3 * Self::PRECHECK_LIMIT;
const SLOW_LIMIT: u16 = Self::PREC... | Rust | 0 |
# Calcula area triangulo
"""
Elaborar un algoritmo para calcular el área de un triángulo.
Se requiere imprimir como salida el área del triángulo.
Los datos disponibles para leer como entrada son la base y la altura del triángulo. Utilizar POO.
"""
class Triangulo:
def __init__(self, base, altura):
sel... | Python | 1 |
.(\d{2,4})\.(\d{2,4})', '(.+)(\d{4}) (\d{2}) (\d{2})'] # same in service
for file in urls:
match = re.compile(file, re.I | re.IGNORECASE).findall(filename)
if match:
results['showtitle'] = match[0][0].replace('.', ' ').strip().replace('The Daily Show',
... | Python | 1 |
from src.config.default import _CN as cfg
cfg.LOFTR.MATCH_COARSE.MATCH_TYPE = 'dual_softmax'
cfg.LOFTR.MATCH_COARSE.SPARSE_SPVS = False
cfg.TRAINER.CANONICAL_LR = 8e-3
cfg.TRAINER.WARMUP_STEP = 1875 # 3 epochs
cfg.TRAINER.WARMUP_RATIO = 0.1
cfg.TRAINER.MSLR_MILESTONES = [8, 12, 16, 20, 24]
# pose estimation
cfg.TRA... | Python | 1 |
import sys
def getFormatedInput(inputFile):
formatedInput = []
id = 0
for i in range(0, len(inputFile), 2):
if (i == len(inputFile) - 1):
formatedInput.append([int(inputFile[-1]), 0, id])
else:
formatedInput.append([int(inputFile[i]), int(inputFile[i+1]), id])
... | Python | 1 |
a script and since that
// would be uglier, I decided to do the
// pattern match like this
0x00 => BRK_00,
0x01 => ORA_01,
0x05 => ORA_05,
0x06 => ASL_06,
0x08 => PHP_08,
0x09 => ORA_09,
0x0A => ASL_0A,
... | Rust | 0 |
56usize],
pub __align: ::std::os::raw::c_long,
_bindgen_union_align: [u64; 7usize],
}
impl Default for pthread_attr_t {
fn default() -> Self {
unsafe { ::std::mem::zeroed() }
}
}
#[repr(C)]
#[derive(Copy, Clone)]
pub union pthread_mutex_t {
pub __data: __pthread_mutex_s,
pub __size: [::... | Rust | 0 |
MWARE_SLOT_INFO; 1],
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for STORAGE_FIRMWARE_INFO {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for STORAGE_FIRMWARE_INFO {
fn clone(&self) -> Self {
*self
}
}
#[doc = "*Required features: `\"Win32_Storage_IscsiDisc\"`*"]
... | Rust | 0 |
0,
children: None,
kind,
}
}
fn random_playout<B: Board>(mut board: B, rng: &mut impl Rng) -> Outcome {
assert!(
!board.is_done(),
"should never start random playout on a done board"
);
loop {
board.play(board.random_available_move(rng));
if let Some(o... | Rust | 0 |
while len(max_profile) < max_length:
max_profile.append(best_value)
best_performance_profiles.append(max_profile)
best_perf_matrix = np.array(best_performance_profiles)
avg_best_perf_list = list()
std_best_perf_list = list()
for i in range(best_perf_matrix.shape[1]):
... | Python | 1 |
import cadquery as cq
import cq_warehouse.extensions
# Create an empty assembly which will be populated with the finger jointed box
polygon_box_assembly = cq.Assembly()
# Create the box shape and then the finger jointed faces
polygon_box_faces = (
cq.Workplane("XY")
.polygon(5, 100)
.extrude(60)
.edge... | Python | 1 |
nombres =["Teresa" , "Pedro" , "Carlos"]
ciudades =["Temuco" , "La Serena" , "Vallenar"]
print(nombres)
print(ciudades)
concatenadas = nombres + ciudades
print(concatenadas)
| Python | 1 |
.unwrap()
.as_integer()
.unwrap()
);
assert_eq!(
result.get_link_value().unwrap().as_integer().unwrap(),
111111
);
assert!(result.get_link_next().unwrap().is_unit());
}
#[test]
fn make_link_with_link_right() {
l... | Rust | 0 |
"""Implement some additional loss functions."""
import torch
from typing import Optional
class CausalLoss(torch.nn.Module):
"""Cross Entropy variant for next-token prediction in causal language modeling."""
def __init__(self, *args, **kwargs):
super().__init__()
self.loss_fct = torch.nn.Cros... | Python | 1 |
# nodoctest
# Numerical Sage documentation build configuration file, created by
# sphinx-quickstart on Sat Dec 6 11:08:04 2008.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# The contents of this file are pickled, so don't put values in the namespace
# that aren't pickleable (mo... | Python | 1 |
p()].status, status);
assert_eq!(exec.blips()[right_blip.unwrap()].status, status);
}
}
});
}
fn next_wind_out(exec: &Exec, p: Point3, d: Dir3) -> bool {
let block_index = exec.machine().get_index(&p).unwrap();
exec.next_blocks().wind_out[block_index][d]
}
fn next_blip_... | Rust | 0 |
u8..), b in uniform32(0u8..)) -> [u8; 64] {
let mut c = [0; 64];
c[..32].copy_from_slice(&a);
c[32..].copy_from_slice(&b);
c
}
}
prop_compose! {
fn uniform65()(a in uniform1(0u8..), b in uniform64()) -> [u8; 65] {
let mut c = [0; 65];
... | Rust | 0 |
FAULT_CLASH_CONF)
else:
config: Dict[str, Any] = copy.deepcopy(self.state.clash_template_dict)
for key, default in Crp.DEFAULT_CLASH_CONF.items():
if isinstance(default, dict):
UtilsProvider.update_with_checking(self.value_from_sub_conf(key), config.get(key, {}))... | Python | 1 |
"""
壓縮相關的子進程任務
"""
import os
import sys
import json
import gzip
def debug_print(message: str, worker_id: int = 0):
"""輸出 debug 訊息到 stderr"""
print(f"[compression-worker-{worker_id}] {message}", file=sys.stderr, flush=True)
def decompress_json_task(file_path: str, safe_mode: bool = False, worker_id: int = 0):
... | Python | 1 |
from ..basemodel import TextModelParser, Exporter, Vertex, TexCoord, Normal, FaceVertex, Face
from ..mesh import Material, MeshPart
def is_off(filename):
"""Checks that the file is a .off file
Only checks the extension of the file
:param filename: path to the file
"""
return filename[-4:] == '.off... | Python | 1 |
import unittest
import pandas as pd
from sqlflow.connectors.in_memory.in_memory_connector import (
IN_MEMORY_DATA_STORE,
InMemoryDestination,
InMemorySource,
)
class TestInMemoryConnector(unittest.TestCase):
def setUp(self):
IN_MEMORY_DATA_STORE.clear()
def test_write_and_read(self):
... | Python | 1 |
""" 7. Faça um algoritmo para calcular a área de uma circunferência, considerando a
fórmula ÁREA = π * RAIO2
. Utilize as variáveis AREA e RAIO, a constante π (pi =
3,14159) e os operadores aritméticos de multiplicação.
"""
raio = float(input('Digite o raio: '))
area = 3.14 * raio**2
print(f"A área da circunferênci... | Python | 1 |
tr() as usize, 4, 0, user_data)) }
.is_ok()
);
assert_eq!(ring.pending_sqes().unwrap(), 1);
assert_eq!(ring.num_ops(), 1);
// Full Queue.
for _ in 1..(NUM_ENTRIES) {
assert!(unsafe {
ring.push(Operation::read(0, buf.as_ptr() as usize,... | Rust | 0 |
ompliance 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, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either ... | Rust | 0 |
# RUN: python %s | filecheck %s
from xdsl.dialects.arith import AddfOp, Arith, MulfOp
from xdsl.dialects.builtin import Builtin, f64
from xdsl.frontend.pyast.context import PyASTContext
# `FrontendContext` encapsulates the mapping from Python to xDSL constructs
ctx = PyASTContext()
ctx.register_type(float, f64)
ctx.r... | Python | 1 |
from PIL import Image, ImageDraw, ImageFont
import os
# Create a 500x500 image with white background
width, height = 500, 500
image = Image.new('RGBA', (width, height), (255, 255, 255, 0))
draw = ImageDraw.Draw(image)
# Define colors
primary_color = (41, 128, 185) # Blue
secondary_color = (52, 152, 219) # Lighter b... | Python | 1 |
ssert_eq!(test_sqrt(4u64), 2u64);
assert_eq!(test_sqrt(4i8), 2i8);
assert_eq!(test_sqrt(4i16), 2i16);
assert_eq!(test_sqrt(4i32), 2i32);
assert_eq!(test_sqrt(4i64), 2i64);
assert_eq!(test_sqrt(4f32), 2f32);
assert_eq!(test_sqrt(4f64), 2f64);
}
}
<filename>src/util.r... | Rust | 0 |
"""
1
7 7
742 357 357 910 854 854 945
707 812 588 700 798 224 735
889 910 840 840 812 602 945
693 224 679 224 763 777 735
910 945 896 693 896 896 910
763 728 805 798 735 784 770
840 840 602 910 903 840 364
---------------------------
"""
tc = int(input())
rtc = []
while tc > 0:
r, c = [int(x) for x in input().split... | Python | 1 |
y!(ImPlotDateTimeFmt))
);
assert_eq!(
::std::mem::align_of::<ImPlotDateTimeFmt>(),
4usize,
concat!("Alignment of ", stringify!(ImPlotDateTimeFmt))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<ImPlotDateTimeFmt>())).Date as *const _ as usize },
0usize,
co... | Rust | 0 |
"""
>>>>>>> Ejercicios Repaso <<<<<<
"""
print (f">>>>>>> Ejercicios Repaso <<<<<<")
print (f"\n","Ejercicio 4: \n")
print (""" Escribir un programa que pida ingresar la coordenada d... | Python | 1 |
2)*G
let new_excess = secp
.commit_sum(vec![new_tmp, new_output2], vec![new_input])
.unwrap();
println!(
" input=205*G+10*H:\t{:?}\noutput1= 216*G+6*H:\t{:?}\noutput2= 68*G+4*H:\t{:?}",
new_input, new_output1, new_output2,
);
// sign it ... | Rust | 0 |
}
}
}
use crate::{
Btn, Button, Choice, Color, Dropdown, EventCtx, GeomBatch, GfxCtx, JustDraw, MultiKey,
ScreenDims, ScreenPt, Widget, WidgetImpl, WidgetOutput,
};
use geom::Polygon;
// TODO Radio buttons in the menu
pub struct PersistentSplit<T: Clone + PartialEq> {
current_value: T,
btn: B... | Rust | 0 |
gType::Idl => {
let arguments = arguments.unwrap_or("()");
let args = arguments.parse::<IDLArgs>();
let typed_args = match method_type {
None => args
.context("Failed to parse arguments with no method type info")?
.to_bytes(),
... | Rust | 0 |
"""Test the BlueMaestro sensors."""
from homeassistant.components.bluemaestro.const import DOMAIN
from homeassistant.components.sensor import ATTR_STATE_CLASS
from homeassistant.const import ATTR_FRIENDLY_NAME, ATTR_UNIT_OF_MEASUREMENT
from homeassistant.core import HomeAssistant
from . import BLUEMAESTRO_SERVICE_INFO... | Python | 1 |
# conditional statemtnts in python
age = 17
if age == 18:
print("You are eligible for voiting ..")
elif age >= 21 :
print("You are adult now ...")
else: print("you are not eligible for voiting")
# this is how we use conditional statments in python
# indentation is importent ... | Python | 1 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
###############################################################################
cvs_text = '''Author,Book,Lang,Price
"Magnus Lie Hetland","Python基础教程(第3版)","中文","75.3"
"Bill Kropla","Beginning MapServer","English","344"
"Jake VanderPlas","Python数据科学手册","中文","83.9"
"Osvaldo... | Python | 1 |
== "perceptual":
memory_tool.execute("add",
content=f"演示{info['name']}的多模态数据处理",
memory_type=memory_type,
importance=0.6,
modality="text",
data_type="demonstration"
)
def demonstr... | Python | 1 |
if options.files_list:
(success, clock, r) = scan_files_list(
options.path_name, options, out_dir)
else:
(success, clock, r) = scan_dir_list(subdirlist, options, out_dir)
if success:
print_msg("Success! ")
print_msg("Elapsed time: %2.2f sec" % clock)
else:
... | Python | 1 |
"""
事件处理器
"""
from typing import List
from datetime import datetime
from astrbot.api import logger
from .pushed_event_id_manager import PushedEventIdManager
from .github_event_data import GitHubEventData
class EventProcessor:
def __init__(self, event_limit: int, pushed_event_ids_manager: PushedEventIdManager, con... | Python | 1 |
NN
class_names = ["Covid", "Normal", "Pneumonia-Bacterial", "Pneumonia-Viral"]
top_class_name = class_names[top_class]
print("Top predicted class:", top_class_name)
# Create a combined RGB image (original + heatmap overlay)
fig, ax = plt.subplots()
ax.imshow(img)
ax.imshow(heatmap, cmap='jet', alpha=0.5)
ax.axis('off... | Python | 1 |
uresigs(pvec)?;
let vset_catchain_seqno = vset.catchain_seqno();
let vset_hash = ValidatorSet::calc_subset_hash_short(vset.list(), vset_catchain_seqno)?;
let vset_info = ValidatorBaseInfo::with_params(vset_hash, vset_catchain_seqno);
return Ok(BlockSignatures::with_params(vset_info, pure_sigs));
}
pub ... | Rust | 0 |
ype Output = Result<bool>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.get_mut();
let svc: Ptr<OCISvcCtx> = Ptr::from(this.ctx.as_ref().as_ref());
let err: Ptr<OCIError> = Ptr::from(this.ctx.as_ref().as_ref());
wait_bool_flag!(|this, ... | Rust | 0 |
"""
微电影视频模板
适用于:创意短片、艺术短片、实验影像
"""
from .base_template import BaseVideoTemplate
from typing import Dict, Any
class MicroFilmTemplate(BaseVideoTemplate):
"""微电影模板"""
def get_outline_prompt(self) -> str:
return """
你是一个独立电影导演。请根据用户的创意概念,生成一个有艺术性的微电影大纲。
大纲应包含:
1. 序幕(15秒)- 氛... | Python | 1 |
Tag))));
/// ```
pub fn delimited<I, O1, O2, O3, E: ParseError<I>, F, G, H>(
mut first: F,
mut second: G,
mut third: H,
) -> impl FnMut(I) -> IResult<I, O2, E>
where
F: Parser<I, O1, E>,
G: Parser<I, O2, E>,
H: Parser<I, O3, E>,
{
move |input: I| {
let (input, _) = first.parse(input)?;
let (input,... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.