text string | label_name string | labels int64 |
|---|---|---|
from tools.configs.dump import DumpConfig
from tools.configs.font import FontConfig
version = '1.10.0'
version_time = '2025-08-24'
dump_configs = [
DumpConfig(
font_name='ASC12',
font_type='asc',
font_size=12,
),
DumpConfig(
font_name='ASC16',
font_type='asc',
... | Python | 1 |
self > u64::max_value() as i128 {
return Err(NumberOutOfRange::new::<i128>().into());
}
write_u64(w, 0, *self as u64)?;
}
Ok(())
}
}
impl Encode<DagCbor> for Cid {
fn encode<W: Write>(&self, _: DagCbor, w: &mut W) -> Result<()> {
write_tag(w, 42)?... | Rust | 0 |
nt=("Arial", 14))
lbl.pack(pady=5)
btn_sel = ttk.Button(frame, text="Seleccionar PDF a dividir", command=self.cmd_seleccionar_pdf_dividir)
btn_sel.pack(pady=5)
entradas_frame = ttk.Frame(frame)
entradas_frame.pack(pady=5)
ttk.Label(entradas_fram... | Python | 1 |
dmin, account_is_early_access, account_is_build_worker)
ON CONFLICT (account_id) DO UPDATE
SET token = account_token, expires_at = now() + interval '1 day', provider = account_provider, extern_id = account_extern_id, is_admin = account_is_a... | Rust | 0 |
# Brute solution
def ele1(arr):
n = len(arr)
for i in range(n):
element = arr[i]
count = 0
for j in range(n):
if arr[j] == element:
count+=1
if count !=2:
return element
return 0
arr = [1,1,2,3,3,4,4]
print(ele1(arr))
# TC - O(n * n)... | Python | 1 |
# Based on metatoaster's answer to
# https://stackoverflow.com/questions/38861101/how-can-i-test-the-standard-input-and-standard-output-in-python-script-with-a-un
import sys
import io
class iostub:
def stub_stdin(testcase_inst, inputs, ioclass=io.StringIO):
stdin = sys.stdin
def cleanup():
... | Python | 1 |
from solana.keypair import Keypair
# Generate a new keypair
keypair = Keypair.generate()
# Print the public key and secret key
print("Public Key:", keypair.public_key)
print("Secret Key:", keypair.secret_key) | Python | 1 |
;
}
pub trait RoleBuilder {
type Role;
/// Give access to the functions `grant_role` and `revoke_role`.
fn manage_roles() -> Self::Role;
/// This role would be the equivalent of a super role. If an account is granted it it can submit
/// any other calls.
fn root() -> Self::Role;
}
type RoleBu... | Rust | 0 |
from django.contrib import admin
from .models import WorkflowImage, WorkflowInstanceSet, WorkflowInstance, WorkflowRecipe
from simple_history.admin import SimpleHistoryAdmin
from django_json_widget.widgets import JSONEditorWidget
from jsonfield import JSONField
from django.db import models
from guardian.admin import Gu... | Python | 1 |
> F3 = pitch.Pitch('F3')
>>> A5 = pitch.Pitch('A5')
>>> D6 = pitch.Pitch('D6')
Here, the bass part moves up from C3 to D3 and the soprano part moves
up from A5 to D6. The simple interval between D3 and D6 is a perfect
octave. Therefore, there is a hidden octave between the two possibilities.
... | Python | 1 |
pe::Vbmul3,
Endomul1 => CamlPlonkGateType::Endomul1,
Endomul2 => CamlPlonkGateType::Endomul2,
Endomul3 => CamlPlonkGateType::Endomul3,
Endomul4 => CamlPlonkGateType::Endomul4,
}
}
}
impl From<GateType> for CamlPlonkGateType {
fn from(gate_type: GateType) -... | Rust | 0 |
.draw()
.expect("Can't draw axes");
chart
.draw_series(LineSeries::new(
self.audio_data.iter().enumerate().map(|(i, p)| (i, *p)),
BLUE.filled(),
))
.expect("Can't draw a series");
chart
.plotting_area()
... | Rust | 0 |
#!/usr/bin/python
# encoding: utf-8
# -*- coding: utf8 -*-
"""
Created by PyCharm.
File: LinuxBashShellScriptForOps:checkCRLFLineEndingInWorkingDirectory.py
User: Guodong
Create Date: 2017/7/14
Create Time: 14:24
Description: find out all files using CRLF line ending
Ref... | Python | 1 |
tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
use crate::types::FileType;
use crate::Result;
use async_stream::try_stream;
use futures::stream::Stream;
use glob::glob_with;
use jwalk::WalkDir;
use reqwest::Url;
use serde::Serialize;
use shellexpand::tilde;
use std::fmt::Display;
use std... | Rust | 0 |
self.fd
}
}
impl Drop for Iface {
fn drop(&mut self) {
let _ = unsafe { libc::close(self.as_raw_fd()) };
}
}
impl Read for Iface {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.recv(buf)
}
}
impl Write for Iface {
fn write(&mut self, buf: &[u8]) -> io::Result... | Rust | 0 |
assert!(Slice::from_string(":").is_err());
}
#[test]
fn slice_from_string_two_numbers() {
assert_eq!(Slice::from_string("1:2"), Ok(Slice{ begin: 1, end: Some(2) }));
}
#[test]
fn slice_from_string_number_colon() {
assert_eq!(Slice::from_string("1:"), Ok(Slice{ begin: 1, end: N... | Rust | 0 |
riterion<CyclesPerByte>) {
let mut group = c.benchmark_group("stream-cipher");
for size in &[KB, 2 * KB, 4 * KB, 8 * KB, 16 * KB] {
let mut buf = vec![0u8; *size];
group.throughput(Throughput::Bytes(*size as u64));
group.bench_function(BenchmarkId::new("apply_keystream", size), |b| {
... | Rust | 0 |
(text, options, width, d);
}
fn inventory_menu(
inventory: &[Object],
header: &str,
root: &mut RaylibDrawHandle,
) -> Option<usize> {
// how a menu with each item of the inventory as an option
let options = if inventory.len() == 0 {
vec!["Inventory is empty.".into()]
} else {
in... | Rust | 0 |
Lens)]
pub struct State {
pub main_window: Option<Rc<druid::WindowId>>,
pub editors: editors::State,
pub history: Rc<RefCell<history::History>>,
pub save_path: Option<Rc<PathBuf>>,
pub up_to_date: bool,
}
impl State {
pub fn new() -> State {
let editors = editors::State::new();
let project = Project::from_e... | Rust | 0 |
*mut pa_operation;
pub fn pa_context_move_sink_input_by_name(
c: *mut pa_context,
idx: u32,
sink_name: *const i8,
cb: pa_context_success_cb_t,
userdata: *mut c_void,
) -> *mut pa_operation;
pub fn pa_context_move_sink_input_by_index(
c: *mut pa_context,
... | Rust | 0 |
data: ReceiptUpdateOne,
// code: Uuid,
// ) -> Result<u64, ReceiptRepoError>;
// }
// #[utoipa::path(
// get,
// tag = "",
// path = "/receipts",
// responses(
// (status = 200, content_type = "application/json", description = "Success response", body = [ReceiptReadAll])
// )
//... | Rust | 0 |
from fractions import Fraction
a = 1 / 2
b = 1 / 3
c = a + b
print(c)
# Fraction ichida ishaltiladgan sonlar faqat ``integer`` tipida bo'lishi kerak.
natija = Fraction(1, 2) + Fraction(1, 3)
print(natija)
| Python | 1 |
import pandas as pd
from sklearn.metrics import accuracy_score, precision_recall_fscore_support
import torch
def train_val_test_split(df, frac_train=0.8, frac_val=0.1, frac_test=0.1):
assert abs(frac_train + frac_val + frac_test - 1.0) < 1e-6, "Fractions must sum to 1"
#For some reason the text has some NaN ... | Python | 1 |
# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
# * Rearrange models' order
# * Make sure each model has one field with primary_key=True
# * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior
# * Remove `managed =... | Python | 1 |
ble, Tuple[Callable, Callable]]:
normal_method: Optional[Callable] = getattr(mw, methodname, None)
methodname_async = methodname + "_async"
async_method: Optional[Callable] = getattr(mw, methodname_async, None)
if not async_method:
return normal_method
if not normal_m... | Python | 1 |
= None;
Some(true)
}
Event::WindowEvent {
event: winit::event::WindowEvent::Resized(size),
..
} => {
log::debug!("resize {:?}", size);
let size = UVec2::new(size.width, size.height);
if size.x == 0 || size.y == 0 {
... | Rust | 0 |
tiple properties on a given object. The
/// properties are defined using property descriptors (see napi_property_descriptor). Given an
/// array of such property descriptors, this API will set the properties on the object one at a
/// time, as defined by DefineOwnProperty() (described in Section 9.1.6 of th... | Rust | 0 |
rs, doc(cfg(feature = "password-hash")))]
pub const ARGON2ID_IDENT: Ident<'_> = Ident::new("argon2id");
/// Argon2 primitive type: variants of the algorithm.
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
pub enum Algorithm {
/// Optimizes against GPU cracking attacks but vulnerable to side-channels... | Rust | 0 |
e::new());
let result = csp.verify(&sig, &msg, Ed25519, wrong_pk);
assert!(result.unwrap_err().is_signature_verification_error());
}
#[test]
fn should_fail_to_verify_if_signature_has_wrong_type() {
let (_, pk, msg, _) = csp_testvec(RFC8032_ED25519_SHA_ABC);
let sig_with_wr... | Rust | 0 |
import cv2
import numpy as np
cv2.namedWindow("erode")
def erode_func():
size = sizeErode*2+1
kernel = cv2.getStructuringElement(cv2.MORPH_CROSS,(size , size))
img_erode = cv2.erode(img , kernel)
cv2.imshow("erode",img_erode)
def changeSize(x):
global sizeErode
sizeErode=x
erode_func()
... | Python | 1 |
RAW_TEXT_FORMAT = 8u32;
#[doc = "*Required features: `\"Win32_Graphics_Gdi\"`*"]
pub const DT_CALCRECT: DRAW_TEXT_FORMAT = 1024u32;
#[doc = "*Required features: `\"Win32_Graphics_Gdi\"`*"]
pub const DT_CENTER: DRAW_TEXT_FORMAT = 1u32;
#[doc = "*Required features: `\"Win32_Graphics_Gdi\"`*"]
pub const DT_EDITCONTROL: DR... | Rust | 0 |
let part_2_result = res.actual_distance.x.abs() + res.actual_distance.y.abs();
Self {
part_1_result: part_1_result as usize,
part_2_result: part_2_result as usize,
}
}
fn part_1(&self) -> Self::Output1 {
self.part_1_result
}
fn part_2(&self) -> Self::Output2 {
self.part_2_result
}
}
#[derive(Copy,... | Rust | 0 |
pub fn off(self) -> &'a mut W {
self.variant(MODE_A::OFF)
}
#[doc = "VIMS Cache mode"]
#[inline(always)]
pub fn cache(self) -> &'a mut W {
self.variant(MODE_A::CACHE)
}
#[doc = "VIMS GPRAM mode"]
#[inline(always)]
pub fn gpram(self) -> &'a mut W {
self.variant(MOD... | Rust | 0 |
import vampytest
from ..preinstanced import ScheduleWeeksDay
from ..schedule_nth_weeks_day import ScheduleNthWeeksDay
def _assert_fields_set(nth_weeks_day):
"""
Asserts whether every field is set of the given nth week's day.
Parameters
----------
nth_weeks_day : ``ScheduleNthWeeksDay``
... | Python | 1 |
#!/usr/bin/python
#
# \file directories.py
# \brief Directories configuration
# \date 2010-08-27 17:13GMT
# \author Jan Boon (Kaetemi)
# \date 2001-2005
# \author Nevrax
# Python port of game data build pipeline.
# Directories configuration.
#
# NeL - MMORPG Framework <http://dev.ryzom.com/projects/nel/>
# Copyright ... | Python | 1 |
::time::{SystemTime, UNIX_EPOCH};
use tokio::sync::oneshot;
use tonic::Status;
/// Argument type that is bundled with an Event
/// and used to notify the original sender
/// that an event was successfully submitted.
pub type Notifier = oneshot::Sender<OperationResult>;
/// Aggregate event struct that is sent on the s... | Rust | 0 |
np.mean(simulations) / current_price - 1, # 漂移率
np.std(simulations) / current_price # 波动率
)
}
except Exception as e:
self.logger.error(f"分析结果失败: {str(e)}")
raise
def _forecast_quarters(self, simulations: np.ndarray) -> ... | Python | 1 |
template_name = 'blog/all.html'
context_object_name = 'article_list'
def get_context_data(self, **kwargs):
kwargs['category_list'] = Category.objects.all()
kwargs['PAGE_NUM'] = settings.PAGE_NUM
return super(AllView, self).get_context_data(**kwargs)
def get_queryset(self):
... | Python | 1 |
success": False, "confidence": 0.0},
"forgery": {"success": False, "is_forged": False, "confidence": 0.0},
"face_match": {"success": False, "faces_match": False, "confidence": 0.0},
"liveness": {"success": False, "is_live": False, "confidence": 0.0}
},
... | Python | 1 |
from django.db import models
from django.contrib.auth.models import AbstractUser, PermissionsMixin
from company.models import Branch
from utils.models import TimestampedModel
class Permission(TimestampedModel):
"""
Example: 'make_sales', 'view_reports', 'manage_inventory', 'view_all_branches'
"""
cod... | Python | 1 |
if t.tau_exp and t.ramd.tau:
if ((t.type == type_comp) or ( t.type == "")):
X.append(np.log10(t.ramd.tau))
y.append(t.tau_exp)
Xt.append(np.log10(t.ramd.tau))
yt.append(t.tau_exp)
y_err.append(t.tau... | Python | 1 |
.line_num, line)
return
decoded['md5'] = hashlib.md5(body.encode('utf-8')).hexdigest()
Queue.Queue.put(self, {
'line_nums': [line_num],
'lines': [line],
'decoded': decoded,
'matches': [match]
})
return
station = match['station'] or 'rUnknown'
... | Python | 1 |
rch.any(idx_batch > 0):
f /= base * 1.0
r += f * (idx_batch % base) # * (idx_batch > 0)
idx_batch = idx_batch // base
return r
def generate_halton_samples(
num_samples,
ndims,
bases=None,
use_scipy_halton=True,
seed=123,
tensor_args: TensorDeviceType = TensorDevice... | Python | 1 |
sroot_include.exists():
print(f"Error: EMSDK sysroot include path does not exist: {sysroot_include}")
return 1
print(
f"EMSDK Headers from sysroot (actually used during compilation): {sysroot_include}"
)
print("=" * 50)
header_extensions = {".h", ".hpp", ".hh", ".h++", ".hxx"}
... | Python | 1 |
import re
from unidecode import unidecode
from ..utils import squeeze, translation, check_empty, check_str
from .phonetic_algorithm import PhoneticAlgorithm
class FuzzySoundex(PhoneticAlgorithm):
"""
Implementation of the "Fuzzy Soundex" algorithm.
[Reference]: http://wayback.archive.org/web/20100629121... | Python | 1 |
);
let poa_setup_dep = CellDep::new_builder()
.out_point(poa_setup_out_point.clone())
.build();
let owner_input_out_point = context.create_cell(
CellOutput::new_builder()
.capacity(500u64.pack())
.lock(poa_owner_script2.clone())
.build(),
Byte... | Rust | 0 |
)
entity_id = f"sensor.{device.name}_rssi"
# Ensure the entity is disabled by default by checking the registry
rssi_registry_entry = entity_registry.async_get(entity_id)
assert rssi_registry_entry is not None
assert rssi_registry_entry.disabled_by is not None
# Enabl... | Python | 1 |
2_dot(this.m_u, vp_b - vp_a);
// Predictive constraint.
if c < 0.0 {
cdot += data.step.inv_dt * c;
}
let mut impulse: f32 = -this.m_mass * cdot;
let old_impulse: f32 = this.m_impulse;
this.m_impulse = b2_min(0.0, this.m_impulse + impulse);
impulse = this.m_impulse - old_impulse;
let p: B2vec2 = impulse * t... | Rust | 0 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
def remove_trash_objectpermissions(apps, schema_editor):
"""
The `Collection` model has already been removed, so there should not be any
`ObjectPermission`s left that reference it. We need to make su... | Python | 1 |
ssion_impl_t = teec_session_impl;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct teec_shared_memory_impl {
pub vmo: zx_handle_t,
pub mapped_addr: zx_vaddr_t,
pub mapped_size: usize,
}
pub type teec_shared_memory_impl_t = teec_shared_memory_impl;
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct teec_... | Rust | 0 |
"
super().__init__()
self.features_dim = features_dim
def forward(self, x: th.Tensor) -> th.Tensor:
"""Returns zeros of same shape as `x`."""
assert x.shape[1:] == (self.features_dim,)
return th.zeros_like(x)
@pytest.mark.parametrize(
"obs_space",
[
gym.spa... | Python | 1 |
ity(map.len());
for (ch, freq) in map {
nodes.push((Node::Leaf(ch), freq));
}
nodes
};
while nodes.len() > 1 {
nodes.sort_unstable_by(|(_, a), (_, b)| b.cmp(a));
// Pop off the two least common entries and join them together
let a = nodes.pop().unwrap();
let b = nodes.pop().unwrap();
... | Rust | 0 |
from qt_py_convert.general import supported_binding
def test_import_level_styles():
assert "PySide2" == supported_binding("PySide2")
assert "PySide2" == supported_binding("PySide2.QtCore")
assert "PySide2" == supported_binding("PySide2.QtWidgets")
assert "PySide2" == supported_binding("PySide2.QtGui")... | Python | 1 |
jni_method) = __jni_env.require_class_method("android/widget/RelativeLayout$LayoutParams\0", "resolveLayoutDirection\0", "(I)V\0");
__jni_env.call_void_method_a(self.0.object, __jni_method, __jni_args.as_ptr())
}
}
/// **get** public [alignWithParent](https://developer.andro... | Rust | 0 |
List for &[] - u8 because otherwise rust can't infer type
impl ValueList for [u8; 0] {
fn serialized(&self) -> SerializedResult<'_> {
Ok(Cow::Owned(SerializedValues::new()))
}
}
// Implement ValueList for slices of Value types
impl<T: Value> ValueList for &[T] {
fn serialized(&self) -> SerializedRe... | Rust | 0 |
Int @id
as A[]
}}
"#,
datasource = api.datasource_block_with(&[("referentialIntegrity", "\"foreignKeys\"")]),
);
api.schema_push(&dm).send().assert_green();
api.assert_schema()
.assert_table("A", |table| table.assert_foreign_keys_count(1));
}
<gh_stars>0
use cr... | Rust | 0 |
# Copyright 2018 jem@seethis.link
# Licensed under the MIT license (http://opensource.org/licenses/MIT)
from hid_keycodes import *
lang = 'Lithuanian'
country = 'Lithuania'
scancode_map = {
KC_0: ('0', ')', '»', ')', '0', ''),
KC_1: ('1', '!', '¼', '!', '1', ''),
KC_2: ('2', '@', '½', '"', '2', ''),
KC_... | Python | 1 |
issue_type, o.id()).object_type(gtfs_structures::ObjectType::Fare)
}
fn has_price(fare_attributes: >fs_structures::FareAttribute) -> bool {
!fare_attributes.price.is_empty()
}
fn valid_currency(fare_attributes: >fs_structures::FareAttribute) -> bool {
iso4217::alpha3(&fare_attributes.currency).is_some()
... | Rust | 0 |
validComponent("offset_hour"))?
.assign_value_to_with(&mut parsed.offset_hour, |offset_hour: u8| {
if offset_sign == '-' {
-(offset_hour as i8)
} else {
offset_hour as _
}
});
let input = colon(input)... | Rust | 0 |
}
},
"available_themes" => match from_value::<AvailableThemes>(params) {
Ok(themes) => Either::A(
self.handle_notification(XiNotification::AvailableThemes(themes))
.into_static_future(),
),
Err(e) => {
... | Rust | 0 |
Ptr;
}
extern "C" {
pub fn xmlSchemaNewQNameValue(
namespaceName: *const xmlChar,
localName: *const xmlChar,
) -> xmlSchemaValPtr;
}
extern "C" {
pub fn xmlSchemaCompareValuesWhtsp(
x: xmlSchemaValPtr,
xws: xmlSchemaWhitespaceValueType,
y: xmlSchemaValPtr,
yws: xmlSchemaWhitespaceValueType... | Rust | 0 |
: TaskHandle,
counter: *const ::std::os::raw::c_char,
nameToAssignToChannel: *const ::std::os::raw::c_char,
units: int32,
idleState: int32,
initialDelay: float64,
freq: float64,
dutyCycle: float64,
) -> int32;
}
extern "C" {
pub fn DAQmxCreateCOPulseChanTi... | Rust | 0 |
rustls {
use super::*;
pub fn ca(ca: Option<&PathBuf>) -> Result<RustlsCertificate> {
use s2n_quic::provider::tls::rustls::certificate::IntoCertificate;
Ok(if let Some(pathbuf) = ca.as_ref() {
pathbuf.into_certificate()?
} else {
s2n_quic_core::crypto::tls::test... | Rust | 0 |
turn Ok(Some(3 + i as i32));
}
}
Ok(None)
}
impl Listener {
pub fn new<S: ?Sized + AsRef<str>>(address: &S) -> Result<Self> {
let address = address.as_ref();
if let Some(l) = activation_listener()? {
if address.starts_with("tcp:") {
unsafe {
... | Rust | 0 |
def alpa_to_digit(s):
digit=0
# print(s)
s=s[::-1]
for i,v in enumerate(s):
digit+=(ord(v)-96)*(26**i)
return digit
def digit_to_alpa(n):
st=''
stack=[]
while n>0:
stack.append(chr((n-1)%26 + 97))
n = (n-1) // 26
return ''.join(stack[::-1])
def solution(n, ... | Python | 1 |
ILER_PATH = Some(exe_path.clone());
}
exe_path
}
fn download_bebopc_internal(dest: impl AsRef<Path>) -> PathBuf {
let root_path = dest.as_ref().join(BEBOPC_VERSION).join(OS_NAME);
let exe_path = if cfg!(target_os = "windows") {
root_path.join("bebopc.exe")
} else {
root_path.join("b... | Rust | 0 |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time
# Initialize Chrome options and WebDriver
options = webdriver.ChromeOptions()
driver = webdriver.Chrome(options=options)
driver.maximize_window()
# Open the website
driver.get("https:... | Python | 1 |
skip_serializing_if = "Option::is_none")]
comment: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
timing: Option<Timing>,
}
impl IntroductionProposal {
/// Creates a new `IntroductionProposal`.
pub fn new(context: String, thread: Uuid, callback_url: Url) -> Self {
Self {
context,... | Rust | 0 |
ypatch.chdir(tmp_path)
atoms = bulk("Cu")
with pytest.raises(ValueError, match="ASE Atoms object has no attached calculator"):
Summarize().run(atoms, atoms)
initial_atoms = read(os.path.join(RUN1, "POSCAR.gz"))
atoms = read(os.path.join(RUN1, "OUTCAR.gz"))
atoms.calc.results = {}
with ... | Python | 1 |
ad, ciphertext_and_plaintext, tag_in)
}
}
}
}
macro_rules! impl_aead_cipher_with_siv_cmac {
($name:tt, $kind:tt) => {
impl AeadCipher for $name {
const KEY_LEN: usize = $name::KEY_LEN;
const BLOCK_LEN: usize = $name::BLOCK_LEN;
const TAG_LEN: us... | Rust | 0 |
rather because it may generate errors and we don't want to issue those
/// errors multiple times.
#[salsa::memoized(in crate::Jar ref)]
#[allow(clippy::needless_lifetimes)]
pub fn root_definitions(db: &dyn crate::Db, filename: Filename) -> name_lookup::RootDefinitions {
name_lookup::RootDefinitions::new(db, filena... | Rust | 0 |
let (border_x, border_y) = match octant {
0 | 3 | 4 | 7 => (border_x, border_y),
1 | 2 | 5 | 6 => (border_y, border_x),
_ => unreachable!(),
};
let tile_x = (border_x >> TILE_SHIFT as i32) as i16;
let tile_y = (border_y >> TILE_SHIFT as i32) as i16;
let local_x = (border_x &... | Rust | 0 |
from torch import Tensor
from torch import nn
from typing import Dict
import os
import json
class Dropout(nn.Module):
"""Dropout layer.
:param dropout: Sets a dropout value for dense layer.
"""
def __init__(self, dropout: float = 0.2):
super(Dropout, self).__init__()
self.dropout = d... | Python | 1 |
time - start_time, ash_rate, powerups_collected);
graphics.draw_end_game(end_time - start_time);
}
}
break;
}
if timer.elapsed_millis() > 1000{
charge -= 2;
graphics.draw_powerups(&game.items);
graphics.upda... | Rust | 0 |
from py2neo import Graph,Node,Relationship
class Neo4j():
graph = None
def __init__(self):
print("create neo4j class ...")
def connectDB(self):
self.graph = Graph("http://localhost:7474", username="neo4j", password="root")
def matchItembyTitle(self,value):
answer = self.graph.find_one(label="Hudong",proper... | Python | 1 |
signer private key to use.")
)
)
}
<filename>wasm/src/did/did_resolver.rs
use async_trait::async_trait;
use didcomm::{
did::{DIDDoc, DIDResolver as _DIDResolver},
error::{ErrorKind, Result as _Result, ResultContext, ResultExt},
};
use wasm_bindgen::prelude::*;
use crate::error::FromJsResult;
#[wa... | Rust | 0 |
from decimal import Decimal
from ... import RewardType, RewardValueType
from ...models import PromotionRule
from ...utils.promotion import fetch_promotion_rules_for_checkout_or_order
def test_fetch_promotion_rules_for_order(order, order_line_JPY, order_promotion_rule):
# given
rule = order_promotion_rule
... | Python | 1 |
_return = unsafe {
ffi::SQLSetStmtAttrW(
Handle.as_SQLHANDLE(),
A::IDENTIFIER,
ValuePtr.into_SQLPOINTER(),
ValuePtr.len(),
)
};
if SQL_SUCCEEDED(sql_return) {
ValuePtr.update_handle(Handle);
}
sql_return
}
#[cfg_attr(test, automo... | Rust | 0 |
e == 'Operations':
out.writeln(' Operations')
print_operations(member, out)
out.reset_color()
def print_usage():
"""Show usage."""
sys.stdout.write(
'Usage: print_diff.py <diff_file.json> <"TAG"|"ALPHABET">\n')
def main(argv):
if len(argv) != 2:
... | Python | 1 |
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: models
import flatbuffers
from flatbuffers.compat import import_numpy
np = import_numpy()
class HelloRequest(object):
__slots__ = ['_tab']
@classmethod
def GetRootAs(cls, buf, offset=0):
n = flatbuffers.encode.Get(... | Python | 1 |
next_hrews.append(reward)
next_hacts.append(action.copy())
next_hobvs.append(obs.copy())
# np_next_hacts and np_next_hrews are required for TD3 alg
np_next_hacts = np.asarray(next_hacts, dtype=np.float32).flatten() #(hist, action_dim) => (hist *action_dim,)
... | Python | 1 |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2025/7/29
# @Author : cyq
# @File : browserAIAgent
# @Software: PyCharm
# @Desc:
import asyncio
from browser_use import Agent, Controller
from browser_use.llm import ChatOpenAI
llm = ChatOpenAI(model="qwen-plus",
api_key="sk-2db1xxx1c",
... | Python | 1 |
als.SYSCTRL,
&mut peripherals.NVMCTRL,
);
let mut pins = circuit_playground_express::Pins::new(peripherals.PORT);
let neopixel_pin = pins.neopixel.into_push_pull_output(&mut pins.port);
let mut neopixel = Ws2812::new(neopixel_pin);
let off = RGB8::default();
let smile = [
YELLO... | Rust | 0 |
assert_content!(
"target/test_new/tasks/task.md",
"#[id: ID]\n#[priority: B]\n#[assign: User]\n#[context: test]\n"
);
delete_file!("target/test_new/tasks/task.md");
run!("todo new id: a:User title:task priority:C ctx:test");
assert_content!(
"target/test_new/tasks/task.md",
... | Rust | 0 |
# Class08B Demos
from PIL import Image
import answer_voronoi_slow as vs
## Steps to produce Voronoi Art
# TODO: 1. load a base image
im = Image.open("parkPhoto.jpg")
# TODO: 2. set a density and choose the centers
density = 0.001 # a density of points, represents how detailed the art is.
ctrs = vs.centers(im, densi... | Python | 1 |
from defs import demander_date_embauche, enregistrer_employe
def main():
# Boucle infinie pour obtenir les informations de l'employé
while True:
prenom = input("Prénom de l'employé : ").strip()
nom = input("Nom de l'employé : ").strip()
email = input("Email de l'employé : ").strip()
... | Python | 1 |
F32x1(0.0)
}
}
#[inline(always)]
unsafe fn cmpge_ps(a: Self::Vf32, b: Self::Vf32) -> Self::Vf32 {
if a.0 >= b.0 {
F32x1(mem::transmute::<i32, f32>(-1))
} else {
F32x1(0.0)
}
}
#[inline(always)]
unsafe fn cmpgt_ps(a: Self::Vf32,... | Rust | 0 |
"""Collect run logs and upload."""
| Python | 1 |
f1717')
# mpf.candlestick_ohlc(ax2, ts_arr2, width=0.6, alpha=1,
# colordown='#53c156', colorup='#ff1717')
# ax1.set_ylim([min_v, max_v])
# ax2.set_ylim([min_v, max_v])
# org_val = t_culr[0, self.atk_cdl, self.atk_chl]
... | Python | 1 |
from flask import Flask, jsonify
import requests
API_KEY = "govee api code"
BASE = "https://developer-api.govee.com/v1"
HEADERS = {"Govee-API-Key": API_KEY, "Content-Type": "application/json"}
INVERT = True # False → “any ON → turn ALL off” | True → “any OFF → turn ALL on”
app = Flask(__name__)
def list_li... | Python | 1 |
'k', fontsize=labelsize, transform=plt.gca().transAxes)
plt.plot(x, y, color=sns.color_palette()[1], linewidth=2)
xy = np.concatenate((np.concatenate((x[:,None],y[:,None]),axis=1), np.array([[plt.xlim()[1], 1]])))
t = plt.matplotlib.patches.Polygon(xy, color=sns.color_palette()[1], alpha=.4)
... | Python | 1 |
_related_push_state__ {
pub test: __IncompleteArrayField<::std::os::raw::c_int>,
}
#[test]
fn bindgen_test_layout___const_checker_eq___non_module_related_push_state__() {
assert_eq!(
::std::mem::size_of::<__const_checker_eq___non_module_related_push_state__>(),
0usize,
concat!(
... | Rust | 0 |
from __future__ import division, print_function
import numpy as np
from scipy.signal import firls, freqz
import matplotlib.pyplot as plt
numtaps = 43
fs = 200
f1 = 15
f2 = 30
bands = np.array([0, f1, f1, f2, f2, 0.5*fs])
desired = np.array([1, 1, 1, 0, 0, 0])
taps1 = firls(numtaps, bands, desired, fs=fs... | Python | 1 |
AtFlags::SYMLINK_NOFOLLOW) {
flags_arg |= FSOPT_NOFOLLOW;
}
let (attrbuf_size, times, attrs) = times_to_attrlist(times);
if setattrlist(
c_str(path),
&attrs,
as_ptr(×).cast(),
... | Rust | 0 |
MLFLOW_GATEWAY_HEALTH_ENDPOINT = "/health"
MLFLOW_GATEWAY_CRUD_ROUTE_BASE = "/api/2.0/gateway/routes/"
MLFLOW_GATEWAY_LIMITS_BASE = "/api/2.0/gateway/limits/"
MLFLOW_GATEWAY_ROUTE_BASE = "/gateway/"
MLFLOW_QUERY_SUFFIX = "/invocations"
MLFLOW_GATEWAY_SEARCH_ROUTES_PAGE_SIZE = 3000
# Specifies the timeout for the Gatew... | Python | 1 |
import networkx as nx
with open('input') as f:
ls = f.readlines()
# Part one
portals = {}
for i in range(len(ls)):
for j in range(len(ls[i])):
# Vertical portals
if ls[i][j].isupper() and i > 0 and ls[i-1][j].isupper():
if i < len(ls)-1 and ls[i+1][j] == '.':
portal... | Python | 1 |
_handler]
fn panic(_info: &PanicInfo) -> ! {
loop {}
}
impl RetStack {
/*pub fn new(capacity: usize) -> RetStack {
//println!("Creating retstack...!");
RetStack{vec: RefCell::new(Vec::with_capacity(capacity)), capacity}
}*/
pub fn push(&mut self, item: SavedRet) -> Result<(), ()> {
... | Rust | 0 |
.unwrap_or_else(|_| "Analysis retrieval was cancelled".to_owned()),
);
buf
}
pub fn workspace_root_for(&self, file_id: FileId) -> Option<&Path> {
let path = self.vfs.read().file2path(VfsFile(file_id.0));
self.workspaces.iter().find_map(|ws| ws.workspace_root_for(&path))
... | Rust | 0 |
_event_to_output("output1", message, 0)
return IoTHubMessageDispositionResult.ACCEPTED
class HubManager(object):
TIMER_COUNT = 2
TWIN_CONTEXT = 0
SEND_REPORTED_STATE_CONTEXT = 0
def __init__(
self,
protocol=IoTHubTransportProvider.MQTT):
self.client_protocol ... | Python | 1 |
4 => &mut self.overflow,
5 => &mut self.bound_range_exceeded,
6 => &mut self.invalid_opcode,
7 => &mut self.device_not_available,
9 => &mut self.coprocessor_segment_overrun,
16 => &mut self.x87_floating_point,
19 => &mut self.simd_floating_point,... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.