text string | label_name string | labels int64 |
|---|---|---|
fe extern "C" fn notify_key_location_trampoline<P, F: Fn(&P) + 'static>(
this: *mut ffi::WebKitDOMKeyboardEvent,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) where
P: IsA<DOMKeyboardEvent>,
{
let f: &F = &*(f as *const F);
... | Rust | 0 |
model: &Model,
idx_val_pairs: I,
) -> Result<()> {
self.set_batch(
model,
idx_val_pairs
.into_iter()
.map(|(idx, vt)| (idx, vt as c_char)),
)
}
}
impl ObjAttrGet<Constr, ConstrSense> for ConstrSenseAttr {
impl_obj_get_... | Rust | 0 |
}
}
(D, M)
}
fn compute_bonus<A, S>(haystack: A, haystack_length: usize) -> Vec<Score>
where
A: FzyScorable,
A::FzyIter: Iterator<Item = S>,
S: FzyItem,
{
let mut last_char = S::INIT;
let len = haystack_length;
haystack
.fzy_iter()
.fold(Vec::with_capacity(len), ... | Rust | 0 |
print(f"数据集配置: n_obs_steps={dataset.n_obs_steps}")
print(f"数据集配置: n_obs_steps={dataset.horizon}")
# 只在主进程计算并保存归一化器
normalizer_path = os.path.join(self.output_dir, 'normalizer.pkl')
if accelerator.is_main_process:
normalizer = dataset.get_normalizer() # 获取... | Python | 1 |
, not(feature = "no_object")))]
pub const OP_EQUALS: &str = "==";
/// Method of chaining.
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
pub enum ChainType {
/// Not a chaining type.
NonChaining,
/// Indexing.
Index,
/// Dotting... | Rust | 0 |
1, 2, 3])
arr4 = np.array([4, 5, 6])
concatenated_arr = np.concatenate((arr3, arr4))
print(concatenated_arr)
# Output: [1 2 3 4 5 6]
# Split an array
arr5 = np.array([1, 2, 3, 4, 5, 6])
split_arr = np.split(arr5, 2)
print(split_arr)
# Output: [array([1, 2, 3]), array([4, 5, 6])]
# Stack arrays vertically (row-wise)
arr... | Python | 1 |
l.public_url
self.ngrok_process = ngrok.get_ngrok_process()
threading.Thread(target=self.ngrok_process.proc.wait).start()
return JSONResponse(content={"message": "Ngrok started successfully.", "public_url": self.public_url}, status_code=200)
except Exception as e:
... | Python | 1 |
s if the value of the field is `UART2_RX_REQ`"]
#[inline(always)]
pub fn is_uart2_rx_req(&self) -> bool {
*self == DMA_SEL0_A::UART2_RX_REQ
}
#[doc = "Checks if the value of the field is `UART2_TX_REQ`"]
#[inline(always)]
pub fn is_uart2_tx_req(&self) -> bool {
*self == DMA_SEL0_... | Rust | 0 |
type } => Ok(ScalarType::Map {
value_type: Box::new(scalar_type_from_pg(value_type)?),
custom_oid: None,
}),
}
}
/// This is used to collect aggregates from within an `Expr`.
/// See the explanation of aggregate handling at the top of the file for more details.
struct AggregateFuncV... | Rust | 0 |
if not profiles:
for egg in eggs:
base = egg.split("=")[0]
profiles.append("%s:default" % base)
enabled = bool(site)
if not (
eggs or zcml or relstorage or develop or enabled or extra_extends
):
return
buildout = BU... | Python | 1 |
for e in r_map.iter() {
bytes.extend_from_slice(e.0.to_string().as_bytes());
bytes.extend_from_slice(&e.1.to_bytes());
}
}
bytes
}
}
impl AttributeTokenResp {
pub fn validate(&self, L: usize) -> DelgResult<()> {
if (self.odd_level... | Rust | 0 |
"""
pyexcel_ods3
~~~~~~~~~~~~~~~~~~~
The lower level ods file format handler using ezodf
:copyright: (c) 2015-2017 by Onni Software Ltd & its contributors
:license: New BSD License
"""
# flake8: noqa
from pyexcel_io.io import get_data as read_data
from pyexcel_io.io import isstream
from pyexcel_i... | Python | 1 |
import time#pythonproject
import pyautogui
from PIL import Image
import pytesseract
import cv2
import re
import SRday
import SRweituo
import SRwuming
import SRqianzhen
import pyautogui
import Kill_SR
pyautogui.FAILSAFE = False # 在代码开头添加
from sympy import print_glsl
# pytesseract.pytesseract.tesseract_cmd = r'C:\Users... | Python | 1 |
ptr) }))
} else {
unsafe { (*self.hazard).set_thread_reserved(Ordering::Release) };
Err(NotEqualError)
}
}
}
}
}
<reponame>ronaldslc/googapis<gh_stars>0
/// A field of an index.
#[derive(Clone, PartialEq, ::prost::Message)]
... | Rust | 0 |
,innodb_buffer_pool_pages_data," \
"innodb_buffer_pool_pages_dirty,innodb_buffer_pool_pages_flushed,innodb_buffer_pool_pages_free,innodb_buffer_pool_hit,innodb_buffer_usage,innodb_buffer_dirty_rate," \
"innodb_io_capacity,innodb_read_io_threads,innodb_write_io_threads," \... | Python | 1 |
eceived_block_list = core.run(future).unwrap();
let future = client
.put_block_list()
.with_container_name(&container.name)
.with_blob_name(name)
.with_block_list(&received_block_list.block_with_size_list.into())
.finalize();
core.run(future).unwrap();
let future = ... | Rust | 0 |
t state of thruster #{}={}'.format(thruster_id, 'ON' if is_on else 'OFF'))
else:
node.get_logger().error('Service call ' + srv_name + ' returned a "failed" value')
# Returning to previous state
if duration > 0:
while time_in_float_sec(node.get_clock().now()) < starting_time + durati... | Python | 1 |
b = desire_state[log.Desire.laneChangeLeft]
r_lane_change_prob = desire_state[log.Desire.laneChangeRight]
lane_change_prob = l_lane_change_prob + r_lane_change_prob
DH.update(sm['carState'], sm['carControl'].latActive, lane_change_prob, sm['frogpilotPlan'], frogpilot_toggles)
modelv2_send.modelV... | Python | 1 |
import os
from PIL import Image
import numpy as np
import scipy.io as sio
from utils import SVD
from utils.norm import MinMax
from .base_dataset import BaseSVDLoader, BaseRGBLoader, BaseHSILoader
class HSILoader(BaseHSILoader):
def load(self, root_path: str, name: str):
fn = os.path.join(root_path, 'hsi'... | Python | 1 |
a = float(input("enter la valeur de a :"))
b = float(input("enter la valeur de b :"))
op = (input("enter l operation + - / * :"))
if op == "+":
print("a + b =",a + b)
elif op == "-":
print("a - b =",a - b)
elif op == "*":
print("a * b =",a * b)
elif op == "/":
print("a / b =",a / b) | Python | 1 |
| Expr::Proc(_) => Ok(expr.clone()),
Expr::Sym(name) => match env.find(&name.to_owned()) {
Ok(v) => Ok(v.clone()),
Err(m) => {
if name.deref() == "t" {
Ok(ksym("t"))
} else {
Err(m)
}
... | Rust | 0 |
# pubsub.py
import threading
import time
import random
from queue import Queue
class PubSubBroker:
def __init__(self):
self.subscribers = {}
def subscribe(self, topic, callback):
if topic not in self.subscribers:
self.subscribers[topic] = []
self.subscribers[topic].append(... | Python | 1 |
prob_volume_propa = F.conv3d(prob_volume, one_hot_filter,padding=0)
return prob_volume_propa
def context_upsample(depth_low, up_weights):
###
# cv (b,1,h,w)
# sp (b,9,4*h,4*w)
###
b, c, h, w = depth_low.shape
depth_unfold = F.unfold(depth_low.reshape(b,c,h,w... | Python | 1 |
op** edge of
# the cell to the midpoint of the existing **top+bottom** bounds.
new_bds_l = 0.5 * (bds_bl + bds_tl)
new_bds_r = 0.5 * (bds_br + bds_tr)
if upper:
bds_tl, bds_tr = new_bds_l, new_bds_r
else:
bds_bl, bds_br = new_bd... | Python | 1 |
class HuffmanTreeNode:
def __init__(self, data, freq):
self.data = data
self.freq = freq
self.left = None
self.right = None
def add_left_child(self, node):
self.left = node
def add_right_child(self, node):
self.right = node
class HuffmanTree:
def __init... | Python | 1 |
"""
Step4
输入 修改好的标题等级txt文件, 重建层次的xml数据
输出 未标注的xml隐私政策
Step5
人工标注, 按照知识图谱去标注数据, 标注100份
"""
from body_extraction import bodyExtraction
from bs4 import BeautifulSoup
import bs4
import xml.etree.ElementTree as ET
import re
import os
from loguru import logger
logger.add("{time}.log", level="INFO")
PAGES = "pp_pages"
C... | Python | 1 |
-window-size", "800", "450",
"--icon-size", "100",
"--icon", "VoiceTyper.app", "200", "190",
"--app-drop-link", "600", "185",
"--format", "UDZO",
"--no-internet-enable",
dmg_name,
"dist/VoiceTyper.app"
]
dmg_res... | Python | 1 |
ON ENERGY']['S22by5-22-0.9-monoA-CP' ] = 271.43868469
DATA['NUCLEAR REPULSION ENERGY']['S22by5-22-0.9-monoB-CP' ] = 271.34619735
DATA['NUCLEAR REPULSION ENERGY']['S22by5-22-1.0-monoA-CP' ] = 271.43868470
DATA['NUCLEAR REPULSION ENERGY']['S22by5-22-1.0-monoB-CP' ] = 271.34... | Python | 1 |
if args.log_file is not None:
fileHandler = logging.FileHandler(args.save_path+args.log_file)
fileHandler.setLevel(0)
logger.addHandler(fileHandler)
streamHandler = logging.StreamHandler()
streamHandler.setLevel(0)
logger.addHandler(streamHandler)
logger.root.setLevel(0)
l... | Python | 1 |
import re
#
# weak name standardization
#
# regular expression substitutions
paren = r'\'s|\(.*\)|\.'
punct = r'[^\w\s]'
space = r'[ ]{2,}'
paren_re = re.compile(paren)
punct_re = re.compile(punct)
space_re = re.compile(space)
# standardize firm name
def standardize_weak(name):
name = name.lower()
name = pa... | Python | 1 |
x: 5, y: 2}},
MapPos{v: Vector2{x: 6, y: 2}},
],
owner_id: None,
}.center();
let expected = MapPos{v: Vector2{x: 6, y: 1}};
assert_eq!(expected, real);
}
#[test]
fn test_center_2() {
let real = Sector {
positions: vec![
... | Rust | 0 |
def scale_module(module, scale):
"""
Scale the parameters of a module and return it.
"""
for p in module.parameters():
p.detach().mul_(scale)
return module
| Python | 1 |
import streamlit as st
from lib.gpt_providers.text_generation.main_text_generation import llm_text_gen
def input_section():
st.markdown("""
<div style='background-color: #f0f2f6; padding: 20px; border-radius: 10px; margin-bottom: 20px;'>
<h2 style='color: #1E88E5;'>⭐ STAR Copywriting Generator</h2>
... | Python | 1 |
CSIC)
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or ... | Rust | 0 |
:ddZ".len();
assert_eq!(timestamp.to_rfc3339().len(), expected_length);
}
}
#[test]
#[should_panic = "InvalidTimestamp"]
fn test_parse_empty() {
Timestamp::parse("").unwrap();
}
#[test]
#[should_panic = "InvalidTimestamp"]
fn test_parse_invalid_date() {
Timestamp::parse("foo bar").un... | Rust | 0 |
__version__ = '0.1.2'
def parse_version_info(version_str):
_version_info = []
for x in version_str.split('.'):
if x.isdigit():
_version_info.append(int(x))
elif x.find('rc') != -1:
patch_version = x.split('rc')
_version_info.append(int(patch_version[0]))
... | Python | 1 |
# array de dispositivos
for dispositivo in dispositivos:
direccion, nombre, rssi = dispositivo
distancia = calcular_distancia(rssi)
color = generar_color_unico()
# posicionamiento y "pintado" de los dispositivos ajenos a nosotros
angle = random.uniform(0, 2 * pi)
... | Python | 1 |
dist.all_reduce(
tensor=(
param.grad
if not self.use_main_grad
else param.main_grad
),
group=self._dp_group,
syn... | Python | 1 |
End: "end",
Qt.Key_PageUp: "pageup",
Qt.Key_PageDown: "pagedown",
Qt.Key_Insert: "insert",
Qt.Key_Delete: "delete",
Qt.Key_Left: "left",
Qt.Key_Right: "right",
Qt.Key_Up: "up",
Qt.Key_Down: "down",
Qt.Key_Escape:... | Python | 1 |
, Error = TokenConvertError>,
{
fn read_from<R, S>(reader: &mut R) -> Result<Self>
where
R: TokenReader<Source = S>,
{
let token = reader.read_token()?;
Self::try_from(token).map_err(PreprocessorError::from)
}
}
pub trait Expect {
type Value: PartialEq + Display + ?Sized;
... | Rust | 0 |
0630, -0.1688, +0.1662, -0.2327, +0.2832, +0.1350, -0.1658, +0.0504, -0.0502, +0.1736, +0.1002, -0.0051, -0.0311, -0.0628, +0.0039, +0.5085, -0.2191, +0.5105, -0.0927, +0.2833, -0.2828, +0.1078, +0.0406, -0.0392, -0.2372, +0.1508, +0.0556, +0.0313, +0.1296, +0.1315, -0.1143, +0.1632]
])
weights_dense2_b = np.array([ -... | Python | 1 |
import django.forms
from catalog.models import AnswerOption, MultipleResponse, OnlyResponse, Survey
class SurveyForm(django.forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.visible_fields():
field.field.widget.attrs["class"] = ... | Python | 1 |
], v[j]));
}
}
hs.len() == 2 && !hs.contains(&0)
}
}
#[test]
fn test() {
let p1 = vec![0, 0];
let p2 = vec![1, 1];
let p3 = vec![1, 0];
let p4 = vec![0, 1];
let res = true;
assert_eq!(Solution::valid_square(p1, p2, p3, p4), res);
let p1 = vec![0, 0];
let ... | Rust | 0 |
ORTHO_EXP2: u32 = 13;
pub const GX_FOG_ORTHO_REVEXP: u32 = 14;
pub const GX_FOG_ORTHO_REVEXP2: u32 = 15;
pub const GX_FOG_LIN: u32 = 2;
pub const GX_FOG_EXP: u32 = 4;
pub const GX_FOG_EXP2: u32 = 5;
pub const GX_FOG_REVEXP: u32 = 6;
pub const GX_FOG_REVEXP2: u32 = 7;
pub const GX_PF_RGB8_Z24: u32 = 0;
pub const GX_PF_R... | Rust | 0 |
::memory::DeviceBuffer;
///
/// let ctx = CudnnContext::new()?;
///
/// let algo = RnnAlgo::Standard;
/// let cell_mode = RnnMode::Lstm;
/// let bias_mode = RnnBiasMode::SingleRecurrentBias;
/// let dir_mode = RnnDirectionMode::Unidirectional;
/// let input_mode = RnnInputMode::SkipInput... | Rust | 0 |
p_map_to_quat(exp_map):
angle, axis = exp_map_to_angle_axis(exp_map)
q = quat_from_angle_axis(angle, axis)
return q
@torch.jit.script
def slerp(q0, q1, t):
# type: (Tensor, Tensor, Tensor) -> Tensor
qx, qy, qz, qw = 0, 1, 2, 3
cos_half_theta = q0[..., qw] * q1[..., qw] \
+ q... | Python | 1 |
_map_prefix.unwrap();
let o_map_prefix = o_map_prefix.unwrap();
for pre in vec![o_prefix.clone(), t_map_prefix.clone(), o_map_prefix.clone()] {
assert_eq!(t_prefix.prefix_field_count, pre.prefix_field_count,);
for (field_i, (l_field, r_field)) in
t_prefix.fields.iter().zip(pre.field... | Rust | 0 |
invsqrt here?
len = 1. / f32::sqrt(len);
}
out.0 = a.0 * len;
out.1 = a.1 * len;
}
pub fn dot(a: &Vector2, b: &Vector2) -> f32 {
a.0 * b.0 + a.1 * b.1
}
pub fn cross(out: &mut Vector3, a: &Vector2, b: &Vector2) {
let z = a.0 * b.1 - a.1 * b.0;
... | Rust | 0 |
# Copyright 2025 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | Python | 1 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Licensed under the GNU General Public License, version 3.
# See the file https://www.gnu.org/licenses/gpl-3.0.txt
from pisi.actionsapi import autotools
from pisi.actionsapi import pisitools
from pisi.actionsapi import get
def setup():
# fix build failure w/ xfce4-pane... | Python | 1 |
from setuptools import setup, find_packages
setup(name='unlabeled_extrapolation',
version='0.0.1',
description='unlabeled_extrapolation',
url='https://github.com/p-lambda/unlabeled_extrapolation',
author='Kendrick Shen, Robbie Jones, Michael Xie, Ananya Kumar',
author_email='ananya@cs.sta... | Python | 1 |
return "error"
else:
self.error("Unknown response received on uploading loader.")
sys.exit(1)
except Exception as e: # pylint: disable=broad-except
self.error("Unexpected error on uploading, maybe signature of loader wasn't accepted ?\n" +... | Python | 1 |
'''
scores = [[100, 80, 82, 88...],
[97, 85, 88, 64...],
...
[72, 53, 77, 92...]]
'''
count = 0
for x in scores:
for b in x:
if b > 90:
c += 1
print() | Python | 1 |
async fn flush_gauges(
gauges_map: &HashMap<MetricKey, GaugeEntry>,
socket: &mut RetrySocket,
prefix: &str,
) {
for (key, entry) in gauges_map.iter() {
let data = format!("{}.{} {} {}\n", prefix, key, entry.value, entry.timestamp);
trace!(
"Gauge data: {:<30} {:<20} {:<20}... | Rust | 0 |
ger.append(logger_epoch)
# save checkpoint
save_checkpoint(
{
"epoch": epoch + 1,
"arch": args.arch,
"state_dict": model.state_dict(),
"optimizer": optimizer.state_dict(),
},
checkpoint=args.checkpoint,
... | Python | 1 |
g.answer(f"✅ Kata '{word}' ditambahkan ke daftar terlarang.")
@router.message(F.text.startswith("/delbanned"))
async def del_banned(msg: Message):
if not await is_admin(msg.from_user.id):
return
try:
word = msg.text.split()[1].lower()
except:
return await msg.answer("Gunakan format... | Python | 1 |
lista2 = []
medi = [
('Jeff', 10, 12),
('Rodr', 9, 9),
('Ferr', 11, 8),
('Leoo', 12, 10)
]
print(lista[2]) | Python | 1 |
import sys
input = sys.stdin.readline
def dis(x1: int,y1: int,x2: int,y2: int) -> int:
return abs(x1-x2) + abs(y1-y2)
def input_2d(n: int) -> list:#n*n
l=[]
for _ in range(n):
l.append(list(map(int,input().split())))
return l
def solve(lis: list) -> int:# lis는 오름차순 정렬된 데이터!
# tmp = 999999... | Python | 1 |
pub fn DAQmxCfgAnlgEdgeStartTrig(
taskHandle: TaskHandle,
triggerSource: *const ::std::os::raw::c_char,
triggerSlope: int32,
triggerLevel: float64,
) -> int32;
}
extern "C" {
pub fn DAQmxCfgAnlgMultiEdgeStartTrig(
taskHandle: TaskHandle,
triggerSources: *const... | Rust | 0 |
/ ordering of the operation. All ordering modes are possible. Using
/// `Acquire` makes the store part of the operation `Relaxed`, and using
/// `Release` makes the load part of the operation `Relaxed`.
fn fetch_nand(
&self,
value: <Self as Atomic>::Primitive,
ordering: Ordering,
... | Rust | 0 |
m_type_conversions() {
let expected_tpms_quote_info = TPMS_QUOTE_INFO {
pcrSelect: PcrSelectionListBuilder::new()
.with_selection(
HashingAlgorithm::Sha256,
&[
PcrSlot::Slot1,
PcrSlot::Slot2,
PcrSlot::Slo... | Rust | 0 |
: list时指定的起始标记
param: int max_keys: 本次list返回live channel的最大个数
return: :class:`ListLiveChannelResult <oss2.models.ListLiveChannelResult>`
"""
logger.debug("Start to list live-channels, bucket: {0}, prefix: {1}, marker: {2}, max_keys: {3}".format(
self.bucket_name, to_string(p... | Python | 1 |
AggregateFunction::Average { .. } => "_average".to_string(),
AggregateFunction::CountDistinct { .. } => "_countDistinct".to_string(),
AggregateFunction::Percentile {
ref percentile_str, ..
} => "p".to_string() + percentile_str,
}
}
named!(complete_agg_function<&str, (String, ... | Rust | 0 |
#!/usr/bin/env python3
# Standard library imports
from random import uniform, randint, choice as rc
# Remote library imports
from faker import Faker
import time
# Local imports
from app import app
from models import db, User, Follow
if __name__ == '__main__':
fake = Faker()
with app.app_context():
... | Python | 1 |
0), nullable=False),
sa.Column(
"guild_rank",
mysql.ENUM("OWNER", "CHIEF", "STRATEGIST", "CAPTAIN", "RECRUITER", "RECRUIT"),
nullable=False,
),
sa.Column("rank", mysql.VARCHAR(length=30), nullable=False),
sa.Column("datetime", mysql.DATETIME(), nullabl... | Python | 1 |
btainKind::HishaN,
KomaKind::Blank => {
return Err(TypeConvertError::LogicError(String::from("Can not to convert Blank to ObtainKind.")));
}
})
}
}
impl TryFrom<KomaKind,TypeConvertError<String>> for MochigomaKind {
fn try_from(kind:KomaKind) -> Result<MochigomaKind,TypeConvertError<String>> {
... | Rust | 0 |
create_fusion_thinking_seeds(knowledge_items[:3], strategy)
thinking_seeds.extend(fusion_seeds)
# 限制种子数量
thinking_seeds = thinking_seeds[:max_seeds]
logger.info(f"🌱 思维种子生成完成: {len(thinking_seeds)} 个")
return thinking_seeds
def _create_thinking_seed... | Python | 1 |
from opencompass.openicl.icl_prompt_template import PromptTemplate
from opencompass.openicl.icl_retriever import ZeroRetriever
from opencompass.openicl.icl_inferencer import GenInferencer
from opencompass.datasets import HumanevalDataset, HumanEvaluator, humaneval_postprocess
humaneval_reader_cfg = dict(
input_col... | Python | 1 |
/// assert_eq!(w.leading_zeros(), w.0.leading_zeros());
/// ```
#[inline]
pub fn leading_zeros(self) -> u32 {
self.0.leading_zeros()
}
/// Returns the number of trailing ones in the binary representation.
///
/// See also
/// <code>FixedI32::[trailing\_ones][FixedI32::trailin... | Rust | 0 |
hmac: __BindgenUnionField<TPMS_SCHEME_HMAC>,
pub exclusiveOr: __BindgenUnionField<TPMS_SCHEME_XOR>,
pub na: __BindgenUnionField<::std::os::raw::c_char>,
pub bindgen_union_field: [u16; 2usize],
}
#[test]
fn bindgen_test_layout_TPMU_SCHEME_KEYEDHASH() {
assert_eq!(::std::mem::size_of::<TPMU_SCHEME_KEYEDH... | Rust | 0 |
WinitVirtualKeyCode::Sleep => Some(ViziaKey::Standby),
WinitVirtualKeyCode::F1 => Some(ViziaKey::F1),
WinitVirtualKeyCode::F2 => Some(ViziaKey::F2),
WinitVirtualKeyCode::F3 => Some(ViziaKey::F3),
WinitVirtualKeyCode::F4 => Some(ViziaKey::F4),
WinitVirtualKeyCode::F5 => So... | Rust | 0 |
def display_menu():
print("Shopping List Manager")
print("1. Add Item")
print("2. Remove Item")
print("3. View List")
print("4. Exit")
def main():
shopping_list = []
while True:
display_menu()
choice = input("Enter your choice: ")
if choice == '1':
# Pro... | Python | 1 |
# [MXML-5-03] 2.EQP.py
# Equality constrained QP (EQP)
#
# This code was used in the machine learning online
# course provided by
# www.youtube.com/@meanxai
# www.github.com/meanxai/machine_learning
#
# A detailed description of this code can be found in
# https://youtu.be/yn04TeRxKko
#
# Least squares problem:
# min... | Python | 1 |
def get_dummy_inputs(self, device, seed=0):
if str(device).startswith('mps'):
generator = torch.manual_seed(seed)
else:
generator = torch.Generator(device=device).manual_seed(seed)
image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
mask_image = floats_tensor((1, 3,... | Python | 1 |
t, flags: *mut ::std::os::raw::c_uint) -> cudaError_t;
pub fn cudaStreamDestroy(stream: cudaStream_t) -> cudaError_t;
pub fn cudaStreamWaitEvent(stream: cudaStream_t, event: cudaEvent_t, flags: ::std::os::raw::c_uint) -> cudaError_t;
}
pub type cudaStreamCallback_t = ::std::option::Option<
unsafe extern "... | Rust | 0 |
)
)
return None
if amount_sat > self.max_sats_receivable:
logger.warning(
"LUD-06 payRequestCallback with too-high amount {amount_sat} sats".format(
amount_sat=amount_sat,
)
)
return None
... | Python | 1 |
# Copyright 2004-2017 Joe Wreschnig, Michael Urman, Iñigo Serna, Christoph Reiter
# 2013-2022 Nick Boultbee
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the Li... | Python | 1 |
Wait! There's more. Now, we encode the duplicates section.
// Push the offset in little endian.
self.output.push(offset as u8);
self.output.push((offset >> 8) as u8);
// If we were unable to fit the duplicates length into the token, write the
... | Rust | 0 |
_sessions"))
async def upload_sessions_handler(client, callback_query: CallbackQuery):
if callback_query.from_user.username not in DEVS:
await callback_query.answer("⚠️ أنت غير مخول لاستخدام هذا الأمر.", show_alert=True)
return
await callback_query.message.reply("📤 يرجى إرسال ملف الجلسات (acco... | Python | 1 |
if normalize_spectra and output_file is not None:
if output_format == '.txt':
data = [x, y/norm]
data = np.array(data).T
header = 'wavenum.(/cm) abs.coeff.(cm2)'
np.savetxt(output_file, data, fmt='%.1f %.3e',
header=header, delimiter='\t')
print(f'Saved fi... | Python | 1 |
in name:
should_skip = True
break
should_skip = name in SKIP_FULL or should_skip
if not should_skip and what == 'module':
populate_modules(None, name)
return should_skip
def find_modules(path):
package_name = path.replace('../', '').replace('\\', '.')
modules = ... | Python | 1 |
- The third one is the Java result type. Can be inferred
/// - The fourth one is the signature of the Java method. Must be specified
///
/// As a result, only one generic parameter needs to be specified -- the last one.
///
/// Example:
/// ```
/// # use rust_jni::*;
/// # use rust_jni::java::lang::String;
/// # use s... | Rust | 0 |
#[doc = "Field `HRCOUNT` reader - High Resolution Counter"]
pub struct HRCOUNT_R(crate::FieldReader<u32, u32>);
impl HRCOUNT_R {
pub(crate) fn new(bits: u32) -> Self {
HRCOUNT_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for HRCOUNT_R {
type Target = crate::FieldReader<u32, u32>;
#... | Rust | 0 |
import pandas as pd
from rapidfuzz import process, fuzz
def match_products_basic(unmatched_df, master_df, threshold=70):
"""
Toma una tabla de productos no matcheados y una tabla maestra.
Retorna la tabla no matcheada con columnas adicionales:
ProductName, ProductGroup, ProductCategory, MatchScore
... | Python | 1 |
"""Module for the Multi Feed Forward model class."""
from abc import ABC, abstractmethod
import torch
from .feed_forward import FeedForward
class MultiFeedForward(torch.nn.Module, ABC):
"""
Multi Feed Forward neural network model class.
This model allows to create a network with multiple Feed Forward ne... | Python | 1 |
# Copyright 2024 Kuokuo <500119.cpc@gmail.com>
#
# 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 agre... | Python | 1 |
)
}
#[doc = "Bit 6 - Existence of VLLS0 feature"]
#[inline(always)]
pub fn evlls0(&self) -> EVLLS0_R {
EVLLS0_R::new(((self.bits >> 6) & 0x01) != 0)
}
}
#[doc = "SMC Parameter Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--mod... | Rust | 0 |
import torch
def transform_darcy(x: torch.Tensor) -> torch.Tensor:
a, u = x[:, 0, :, :], x[:, 1, :, :]
a = torch.where(a > 7.5, torch.tensor(12.0, device=x.device), torch.tensor(3.0, device=x.device))
return torch.stack([a, u], dim=1)
class DatasetNormalizer:
def __init__(self, dataset_name, stats)... | Python | 1 |
p[key] = value
page = int(p["page"])
width = int(float(p["width"]))
height = int(float(p["height"]))
print filename, page, "%dx%d" % (width, height)
pdfpage = PDFPage(filename, page, width, height)
pdfpage.compare()
if wid... | Python | 1 |
# 高分挑战敌人
class Gftz:
def __init__(self, img_path = "", logo_path = "",
name = "",guide_path = ""
):
self.img_path = img_path # 高分挑战头像路径
self.logo_path = logo_path # 高分挑战ico路径
self.name = name # 高分挑战敌人名
s... | Python | 1 |
anyways.
let naming_hash = make_naming_hash(name);
let dep_hash = deps_rust::hash1(HashMode::Hash32Bit, dep_type, name.as_bytes());
let result = deps_rust::combine_hashes(dep_hash, naming_hash);
result
}
}
use quote::quote;
pub(crate) fn state_data(ast: &syn::DeriveInput) -> proc_m... | Rust | 0 |
'''
实验名称:DAC-蜂鸣器
版本:v1.0
日期:2019.4
作者:01Studio
说明:通过USER按键让DAC输出不同频率的方波来驱动蜂鸣器。
'''
#导入相关模块
from pyb import DAC,Switch
from machine import Pin,I2C
from ssd1306 import SSD1306_I2C
#初始化相关模块
i2c = I2C(sda=Pin("Y8"), scl=Pin("Y6"))
oled = SSD1306_I2C(128, 64, i2c, addr=0x3c)
sw = Switch() #定义按键对象名字为sw
dac = DAC(1) ... | Python | 1 |
import csv
import sys
if len(sys.argv) != 2:
print("Usage: python append_error.py <model_id>")
sys.exit(1)
model_id = sys.argv[1]
models_dict = {
"Llama3-8b-instruct": "meta-llama/Meta-Llama-3-8B-Instruct",
"Llama3.1-8b-instruct": "meta-llama/Meta-Llama-3.1-8B-Instruct",
"Llama3-8b-multilingual":... | Python | 1 |
import piexif
import piexif.helper
import click
from PIL import Image
def read_info_from_image(image: Image.Image) -> tuple[str | None, dict]:
"""
https://github.com/AUTOMATIC1111/stable-diffusion-webui/blob/cf2772fab0af5573da775e7437e6acdca424f26e/modules/images.py#L723-L761
"""
items = (image.info o... | Python | 1 |
# -*- coding: utf-8 -*- #
# Copyright 2019 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 |
coro.state.set(PrivCoroState::Poisoned);
run_defers(
vm,
gfn.lambda.bytecode.clone(),
base_reg,
base_stay,
base_defer,
&mut error,
);
Err(error)
}
}
}
//it feels wrong... | Rust | 0 |
) -> bool {
self.bit()
}
}
#[doc = r" Proxy"]
pub struct _GPIO_GPK_SHTDN_NW<'a> {
w: &'a mut W,
}
impl<'a> _GPIO_GPK_SHTDN_NW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) ->... | Rust | 0 |
_ATTEST>(),
2304usize,
concat!("Size of: ", stringify!(TPMS_ATTEST))
);
assert_eq!(
::std::mem::align_of::<TPMS_ATTEST>(),
8usize,
concat!("Alignment of ", stringify!(TPMS_ATTEST))
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<TPMS_ATTEST>())).magic as *c... | Rust | 0 |
# -*- coding: utf-8 -*- #
# Copyright 2021 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 |
se {
let result = b.atan2(a_prime).to_degrees();
if result < T::zero() {
result + from_f64(360.0)
} else {
result
}
}
};
let h_one_prime = calc_h_prime(this.b, a_one_prime);
let h_two_prime = calc_h_prime(other.b, a_two_... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.