text string | label_name string | labels int64 |
|---|---|---|
API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [smph7](smph7) module"]
pub type SMPH7 = crate::Reg<u32, _SMPH7>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _SMPH7;
#[doc = "`read()` method returns [smph7::R](smph7::R) reader structure"]
impl crate::Readable ... | Rust | 0 |
#!/usr/bin/env python3
# Merge k Sorted Lists
"""* 合并K个排序链表
* 基于两个链表合并的算法,我们将k中每两个链表合并一次得出的新的集合再进行同样的操作,
最终得到一个集合,T = kN 将 k 个链表配对并将同一对中的链表合并。第一轮合并以后,
k 个链表被合并成了 k/2 个链表,平均长度为 2N/k 重复这一过程,直到我们得到了最终的有序链表。
每次k的数目指数型下降,例如k k/2 k/4 k/8 S = Nlogk
* 合并两个升序链表的方法:
- 考虑几种情况,1. 逐个更新并对比插入 2. 不存在插入的情况,直接插入到链表尾部
... | Python | 1 |
"facebookresearch/swag", model="regnety_32gf_in1k")
return SwagPytorchModel(model, model_name, input_size=384, *args)
@register_model("pytorch")
def swag_regnety_128gf_in1k(model_name, *args):
model = torch.hub.load("facebookresearch/swag", model="regnety_128gf_in1k")
return SwagPytorchModel(model, model_... | Python | 1 |
def prepare_jinja_env(jinja_env) ->None:
"""Add `contains` custom test to Jinja environment."""
jinja_env.tests['contains'] = contains
| Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
from sklearn.metrics import accuracy_score, precision_recall_fscore_support
# from sklearn.metrics import precision_score, recall_score
"""
---- Input:
predict:
type, numpy.ndarray
shape, (BS=batch_size, C=class_num, W, H, D), onehot... | Python | 1 |
ctor = extractor(vec![0b10000000, 0, 0, 0, 0, 0, 0, 0]);
assert_eq!(extractor.extract_8_bits(1), 0b00000001);
assert_eq!(extractor.remaining(), SOURCE_ENCODER_BLOCK_SIZE_IN_BITS - 1);
}
#[test]
pub fn extract_8_by_4_bits_reduces_remaining() {
let mut extractor = extractor(vec![0b101... | Rust | 0 |
class Coins(object):
"""A simple class to store coin data """
def __init__(self):
self._coins = [
"SOL", "PIXEL", "JUP", "WIF", "PYTH", "BTC", "ADA", "MINA", "PAXG", "AGIX", "DOT", "ALGO", "BNB", "MATIC", "LINK", "AR", "AAVE", "EGLD",
"ETH", "SOL", "FIL", "AVAX", "APT", "R... | Python | 1 |
d = vec![
LogicalType::LIST,
LogicalType::MAP,
LogicalType::MAP_KEY_VALUE,
];
check_sort_order(undefined, SortOrder::UNDEFINED);
// Check None logical type
// This should return a sort order for byte array type.
check_sort_order(vec![LogicalTy... | Rust | 0 |
from django.contrib import admin
from django.utils.html import format_html
from .models import Medicine, Category, PharmacyImage
class PharmacyImageInline(admin.TabularInline):
model = PharmacyImage
extra = 1
readonly_fields = ("preview",)
def preview(self, obj):
if obj.image:
ret... | Python | 1 |
afe { shuffle.get_unchecked(old_low.into_usize()) };
let new_high = unsafe { shuffle.get_unchecked(old_high.into_usize()) };
let new_node = PackedBddNode::pack(variable, *new_low, *new_high);
let new_slot = unsafe { new_nodes.get_unchecked_mut(new_id.into_usize()) };
*new... | Rust | 0 |
::new_from_pixbuf(Some(&pix_buf));
win.add(&img);
// Don't forget to make all widgets visible.
win.show_all();
});
uiapp.run(&env::args().collect::<Vec<_>>());
}
// 这个是用于tensor的,tensor的展开机制是先y再x。
pub fn argmax_in_axis0(input: &[f32], shape: &[usize]) -> Vec<usize> {
input.chunks(s... | Rust | 0 |
import numpy as np
import pandas as pd
def cos_sim(vector_a, vector_b):
"""
计算两个向量之间的余弦相似度
:param vector_a: 向量 a
:param vector_b: 向量 b
:return: sim
"""
vector_a = np.mat(vector_a)
vector_b = np.mat(vector_b)
num = float(vector_a * vector_b.T)
denom = np.linalg.norm(vector_a) * np... | Python | 1 |
haracters. Each char is specified as a tuple of that
// character and a array of the columnar data for that letter. Each pixel in
// the letter is a bit in the column's number. The least significant bit is
// the bottom pixel.
letter_data: Vec<(char, [u16; LETTER_WIDTH])>,
}
#[allow(clippy::declare_int... | Rust | 0 |
(feature = "tls")]
mod with_tls_feature {
use std::fs;
use std::io::{self, Error};
use crate::http::tls::Config;
use crate::http::tls::rustls::SupportedCipherSuite as RustlsCipher;
use crate::http::tls::rustls::cipher_suite;
use yansi::Paint;
use super::{Either, RelativePathBuf, TlsConfig... | Rust | 0 |
result.get("process_info")
}
return enhance_endpoint_result(enhanced_result, "natural_language_video_edit", request, is_digital_human=False)
except Exception as e:
error_res = {"error": str(e), "function_name": "natural_language_video_edit"}
... | Python | 1 |
let byte_position = 3 - (bit >> 1) as usize;
if byte & (1 << bit) != 0 {
encoded_data
[(byte_index + 1) * 4 + byte_position] |=
1 << offset;
}
}
... | Rust | 0 |
class Solution:
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
roman = s
num = 0
rlen = len(roman)
if rlen == 0:
return 0
i = 0
while i < rlen:
if roman[i] == "M":
num = num + 1000
... | Python | 1 |
from chainlit.cli import run_chainlit
run_chainlit("chat.py")
| Python | 1 |
Returns:
Postprocessed predictions
"""
@abc.abstractmethod
def _merge_results(self, results, shape):
"""Merge results from all tiles.
Args:
results: list of tile results
shape: original full-res image shape
"""
def _crop_tile(self, im... | Python | 1 |
c.get(n_index).unwrap();
tot_pts += points_in_range(&s_point.point, neighbour, params.epsilon);
}
if tot_pts >= params.min_pts {
break;
}
}
if tot_pts >= params.min_pts {
s_point.is_core = true;
curr_cell.is_core... | Rust | 0 |
te doesn't import the OAuth2 handler. You'll also need to install some
Python modules. Change directories into the boto root directory at
third_party/boto and run:
pip install -r requirements.txt
(You probably need to run this command using sudo.)
Make sure each of the individual installati... | Python | 1 |
ut g = Graph::new();
for i in 0..10 {
assert_eq!(g.add_node(), i);
assert_eq!(g.M_star.borrow().get(i, i).unwrap(), 1);
}
assert_eq!(g.insert(1, 2).unwrap(), EdgeEffect::NewEdge(false));
assert_eq!(g.insert(2, 4).unwrap(), EdgeEffect::NewEdge(false));
asse... | Rust | 0 |
) -> Result<(T::AccountId, CollectionId, NftId), DispatchError> {
let (root_owner, _root_nft) = Pallet::<T>::lookup_root_owner(collection_id, nft_id)?;
// Check ownership
ensure!(sender == root_owner, Error::<T>::CannotRejectNonOwnedNft);
// Get NFT info
let mut rejecting_nft =
Nfts::<T>::get(collection... | Rust | 0 |
contents: contents.into(),
})
}
}
impl fmt::Display for Email {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.contents)
}
}
// This is only used for testing
#[cfg(test)]
impl std::str::FromStr for Email {
type Err = Error;
fn from_str(s: &str) -> Resu... | Rust | 0 |
# ------------------------------------------------------------------------
# 3D Deformable Transformer
# ------------------------------------------------------------------------
# Modified from Deformable DETR
# Copyright (c) 2020 SenseTime. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 [see LI... | Python | 1 |
rray_overflow_to_chunked():
# ARROW-3762
# 2^31 + 1 bytes
values = [b'x'] + [
b'x' * (1 << 20)
] * 2 * (1 << 10)
df = pd.DataFrame({'byte_col': values})
tbl = pa.Table.from_pandas(df, preserve_index=False)
read_tbl = _simple_table_roundtrip(tbl)
col0_data = read_tbl[0]
ass... | Python | 1 |
ion::new(&file, 13, 3), Integer("-42".to_owned()))]));
}
#[test]
fn precedence() {
let lexer = generate_test_lexer();
let file = FileHandle::test_new("file_name".to_owned(),
"keyword cOmPlicated keyWORD cOmPlicated keyWORD"
... | Rust | 0 |
# Copyright (C) 2018-2021 coneypo
# SPDX-License-Identifier: MIT
# 摄像头实时人脸特征描述子计算 / Real-time face descriptor computing
import dlib # 人脸识别的库 Dlib
import cv2 # 图像处理的库 OpenCV
import time
# 1. Dlib 正向人脸检测器
detector = dlib.get_frontal_face_detector()
# 2. Dlib 人脸 landmark 特征点检测器
predictor = dlib.shape_... | Python | 1 |
#!/usr/bin/env python3
"""
Web UI 文件清理腳本
此腳本用於清理重複和過時的Web UI文件,確保只有一個主要的生產版本。
"""
import os
import shutil
import logging
from pathlib import Path
# 設定日誌
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def backup_file(file_path: str, backup_dir: str = "../../backup_web_ui"):
"""備份文件到... | Python | 1 |
let tetfu = tetfu_encoder.encode(&Tetsimu2Content {
field,
comment: String::from(""),
});
let output = Command::new("java")
.arg("-jar")
.arg(MAIN_JAR)
.arg("path")
.arg("--tetfu")
.arg(tetfu)
.arg("--patterns")
.arg(&message.body.nexts)
.arg("--clear... | Rust | 0 |
Received to indicate that the process should stop.
///
/// On Unix, this is `SIGTERM`. On Windows, this is `Ctrl+Break`.
///
/// This signal is available for cleanup, but will generally not be passed on to a sub process
/// with no other consequence: it is expected the main process should terminate.
Terminate,
... | Rust | 0 |
te::Initialized }>>,
pub from_mint: Data<'b, SplMint, { AccountState::Initialized }>,
pub to_mint: Data<'b, SplMint, { AccountState::Initialized }>,
pub to_token_custody: Mut<ToCustodyTokenAccount<'b, { AccountState::Initialized }>>,
pub from_token_custody: Mut<FromCustodyTokenAccount<'b, { AccountState... | Rust | 0 |
::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [enableset0](enables... | Rust | 0 |
for n in 1..4 {
assert!(matches!(
buffer.push(LokiRecord {
labels: vec![("asdf".into(), "value1".into())],
event: LokiEvent {
timestamp: 123456780 + n,
event: format!("event #{}", n),
... | Rust | 0 |
min_input),
min(extrema[which + 1].min(), max_input),
&mut bucket,
);
}
collect_root(terms, extrema.last().unwrap().max(), max_input, &mut bucket);
}
// if we found a root on both sides of a derivative-root, we know that the derivative-root is bounded away from 0
for which in 0..extr... | Rust | 0 |
update_pkg_builder.add_file(version_file, "version")?;
}
update_pkg_builder.add_file(&board_name, "board")?;
let zbi_destination = if board.zbi.signing_script.is_some() { "zbi.signed" } else { "zbi" };
update_pkg_builder.add_file(zbi, zbi_destination)?;
if let Some(vbmeta) = vbmeta {
... | Rust | 0 |
= Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::mode\0".as_ptr() as *const _,
Some(transmute(notify_mode_trampoline::<F> as usize)),
Box_::into_raw(f),
)
}
}
#[cfg(any(feature = "v1_2", feature = "d... | Rust | 0 |
::raw::c_int
=
-200529;
pub const DAQmxErrorInvalidLineGrouping: ::std::os::raw::c_int = -200528;
pub const DAQmxErrorCtrMinMax: ::std::os::raw::c_int = -200527;
pub const DAQmxErrorWriteChanTypeMismatch: ::std::os::raw::c_int = -200526;
pub const DAQmxErrorReadChanTypeMismatch: ::std::os::raw::c_int = -2... | Rust | 0 |
from typing import List
class Solution:
def maxOperations(self, nums: List[int], k: int) -> int:
count = 0
i, j = 0, len(nums) - 1
nums.sort()
while i < j:
temp = nums[i] + nums[j]
if temp == k:
count += 1
i += 1
... | Python | 1 |
; D.affine();
let nb=e.nbits();
for i in (0..nb-1).rev() {
let b=e.bit(i);
P.copy(&R1);
P.dadd(&mut R0,&D);
R0.cswap(&mut R1,b);
R1.copy(&P);
R0.dbl();
R0.cswap(&mut R1,b);
}
P.copy(&R0)
} else {
// fixed size windows
let mut mt=BIG::new();
let mut t=BIG::new();
let ... | Rust | 0 |
Fields {}
pub trait ProgramDef {
type Uniform: UniformInput;
type Vertex: VertexInput;
type Varying: VertexOutput;
type Fragment: FragmentOutput;
fn vertex(&self) -> Statement;
fn fragment(&self) -> Statement;
#[doc(hidden)]
fn _glace_type_check_vertex(
&self,
_unifor... | Rust | 0 |
_code)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PropValue<T>(String, ExpressionValue<T>, Option<String>);
impl<T> PropValue<T> {
pub fn new(key: String, e: ExpressionValue<T>, alias: Option<String>) -> Self {
PropValue(key, e, alias)
}
pub fn key(&self) -> &str {
self.0.as_... | Rust | 0 |
Commands."""
return len(self.commands)
def append(self, cmd: Command) -> None:
"""Append a Command to run asynchronously."""
if cmd.is_save and not self._is_save:
self._is_save = True
self.commands.append(cmd)
@property
def is_save(self) -> bool:
"""Is t... | Python | 1 |
+2-1" 。
返回可以通过上述方法构造的、运算结果等于 target 的不同 表达式 的数目。
示例 1:
输入:nums = [1,1,1,1,1], target = 3
输出:5
解释:一共有 5 种方法让最终目标和为 3 。
-1 + 1 + 1 + 1 + 1 = 3
+1 - 1 + 1 + 1 + 1 = 3
+1 + 1 - 1 + 1 + 1 = 3
+1 + 1 + 1 - 1 + 1 = 3
+1 + 1 + 1 + 1 - 1 = 3
示例 2:
输入:nums = [1], target = 1
输出:1
提示:
1 <= nums.length <= 20
0 <= nums[i] <= 100... | Rust | 0 |
arse_function(
dwarf: &gimli::Dwarf<gimli::EndianSlice<gimli::RunTimeEndian>>,
unit: &gimli::Unit<gimli::EndianSlice<gimli::RunTimeEndian>>,
offset: gimli::UnitOffset,
) -> crate::defs::Result<()> {
let mut function_tree = unit.entries_tree(Some(offset))?;
// process_tree(function_tree);
let roo... | Rust | 0 |
map_or(false, |f| f.has_pse());
let has_msr = fi.as_ref().map_or(false, |f| f.has_msr());
let has_sse3 = fi.as_ref().map_or(false, |f| f.has_sse3());
let has_osfxsr = fi.as_ref().map_or(false, |f| f.has_fxsave_fxstor());
let efi = cpuid.get_extended_feature_info();
let has_smap = efi.as_ref().map_o... | Rust | 0 |
Invalid sport type"
# Generate a simple round-robin schedule
for i in range(len(sport_teams)):
for j in range(i + 1, len(sport_teams)):
if current_date > end_date:
break
home_team = sport_teams[i]["name"]
... | Python | 1 |
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from isaaclab.utils import configclass
from .rough_env_cfg import TurinV3RoughEnvCfg, TurinV3RoughRefEnvCfg
@configclass
class TurinV3FlatEnvCfg(TurinV3RoughEnvCfg):
def __post_init__(se... | Python | 1 |
: *const libc::c_void,
FileImageSize: i32,
DataType: i32,
BaseImage: *mut BaseImage,
ReverseFlag: i32,
) -> i32;
pub fn dx_CreateGraphImage(
FileName: *const i8,
DataImage: *const libc::c_void,
DataImageSize: i32,
DataImageType: i32,
GraphI... | Rust | 0 |
# Copyright (c) 2014 Amazon.com, Inc. or its affiliates. All Rights Reserved
#
# 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 ... | Python | 1 |
er_inputs)}")
word = row['Katsesõna']
meaning = row['Tähendus']
try:
response_text, thinking_text = get_response_for_input(api_key, word, meaning)
# Parsime struktureeritud vastuse
usage, expla... | Python | 1 |
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | Python | 1 |
return Err(Error::OtherError(format!(
"memcpy: Expected dest to have pointer type, got {:?}",
ty
)))
},
}
match state.type_of(src).as_ref() {
Type::PointerType { pointee_type, .. } => match pointee_type.as_ref() {
Type::IntegerT... | Rust | 0 |
ized>(_visitor: &mut V, _i: ExprAssign) -> ExprAssign {
ExprAssign {
attrs: FoldHelper::lift(_i.attrs, |it| _visitor.fold_attribute(it)),
left: Box::new(_visitor.fold_expr(*_i.left)),
eq_token: Token ! [ = ](tokens_helper(_visitor, &_i.eq_token.spans)),
right: Box::new(_visitor.fold_... | Rust | 0 |
k, score))
# Sort by score and return top suggestions
scored_tracks.sort(key=lambda x: x[1], reverse=True)
return [track for track, score in scored_tracks[:limit]]
# Global instances for use across the application
def create_smart_playlist_generator(track_repository: Repository) -> Sm... | Python | 1 |
_RepositoryDecoration: repoMatches或repoExcludes
:type RepositoryDecoration: str
:param _TagDecoration: matches或excludes
:type TagDecoration: str
:param _Disabled: 禁用规则
:type Disabled: bool
:param _RuleId: 规则 Id
:type RuleId: int
:param _NsName: 命名空间
... | Python | 1 |
s_embeds,
return_dict=return_dict,
)
pooled_output = outputs[1]
pooled_output = self.dropout(pooled_output)
logits = self.classifier(pooled_output)
loss = None
if labels is not None:
if self.num_labels == 1:
# We are doing regre... | Python | 1 |
}
}
pub fn get_mfarity(&self) -> RtResult<ModFunArity> {
Ok(ModFunArity {
m: self.m,
f: self.f,
arity: self.get_arity()?,
})
}
pub fn get_arity(&self) -> RtResult<usize> {
match self.args {
Args::List(lst) => {
return cons::list_length(lst);
}
Args::Sl... | Rust | 0 |
import openpyxl
# Открываем Excel файл
workbook = openpyxl.load_workbook('Выписка за год (по месяцам).xlsx')
Months = ["Декабрь","Ноябрь","Октябрь",
"Сентябрь","Август","Июль",
"Июнь","Май","Апрель",
"Март","Февраль","Январь"]
Months = Months[::-1]
for month in Months:
sheet = workb... | Python | 1 |
ss<A> for LibraryBase<A, T> {
fn get_address(&self) -> Result<A::Pointer> {
todo!()
}
}
impl<A: Arch, T: Sized> Parent<A> for LibraryBase<A, T> {
fn root(&self) -> Result<Weak<dyn Root<A>>> {
Ok(self.root.clone())
}
}
<reponame>huytd/actix-taskqueue<filename>src/messages.rs<gh_stars>10-... | Rust | 0 |
_range().contains(&(virtio_phys_to_virt(paddr) as *const u8)));
0
}
#[no_mangle]
pub unsafe extern "C" fn virtio_phys_to_virt(paddr: usize) -> usize {
let pool = VIRTIO_POOL.as_mut().unwrap();
debug_assert!(paddr >= pool.paddr && paddr < pool.paddr + pool.pool.len(),
"virtio_pool: invalid paddr {:0... | Rust | 0 |
import pytest
from page_objects.login_page import LoginPage
import logging as logger
pytestmark = [pytest.mark.negative, pytest.mark.login]
class TestNegative:
@pytest.mark.parametrize("username, password, expected_error_msg, test_number", [
pytest.param("incorrectUser", "Password123", "Your username is... | Python | 1 |
+ '_ {
items.iter().filter_map(InventoryHash::unmined_tx_id)
}
/// Map a list of inventory hashes to the corresponding block hashes.
/// Non-block inventory hashes are skipped.
fn block_hashes(items: &'_ [InventoryHash]) -> impl Iterator<Item = block::Hash> + '_ {
items.iter().filter_map(|item| {
if l... | Rust | 0 |
from django.core.management import call_command
from django.test import TestCase
from course_discovery.apps.course_metadata.models import CourseRunType
from course_discovery.apps.course_metadata.tests.factories import CourseRunTypeFactory
class ChangeIsMarketableToCourseRunTypesCommandTests(TestCase):
def setUp(... | Python | 1 |
let mut rc = 0;
// Read loop test
let main_exit = Arc::new(AtomicBool::new(false));
let thread_exit = main_exit.clone();
let (sender, receiver) = channel();
let mai_ref = mai.clone();
let handle = thread::spawn(move || read_loop(&mai_ref, &thread_exit, &sender));
// Let read loop run f... | Rust | 0 |
,
Err(a) => a,
};
VecInsertPos {
vec: self,
pos: pos,
}
}
}
impl<'a,T> VecInsertPos<'a,T>
{
pub fn is_end(&self) -> bool {
self.pos == self.vec.len()
}
pub fn next<'b>(&'b self) -> &'b T {
assert!( !self.is_end() );
&(*self.vec)[self.pos]
}
pub fn insert(&mut self, val: T) {
self.vec.ins... | Rust | 0 |
]])
edges = torch.tensor(edges).T
node_text = np.array(node_text)
edge_texts = np.array(edge_texts)
target_question = np.array(target_question)
target_answer = np.array(target_answer)
unique_node_feature, node_map = batch_unique_feature(node_text)
unique_edge_feature, edge_map = batch_uniq... | Python | 1 |
assert_eq!(command.parameter("param-bool", false), true);
// check option
assert_eq!(command.option("option3"), false);
// check arg
assert_eq!(command.arg(0, "falsch"), "some");
assert_eq!(command.arg(1, "falsch"), "more");
assert_eq!(command.arg(2, "falsch"), "arguments");
// check ... | Rust | 0 |
WordSegmentsTokenizingHandler {
#[inline] pub fn invoke(&self, precedingWords: &foundation::collections::IIterable<WordSegment>, words: &foundation::collections::IIterable<WordSegment>) -> Result<()> { unsafe {
let hr = (self.get_vtbl().Invoke)(self.get_abi() as *const _ as *mut _, precedingWords.get_abi(... | Rust | 0 |
from typing import List
from mediawords.languages import (
McLanguageException,
SpaceSeparatedWordsMixIn,
SentenceSplitterMixIn,
StopWordsFromFileMixIn,
)
from mediawords.languages.lt.lithuanian_stemmer import LithuanianStemmer
from mediawords.util.log import create_logger
from mediawords.util.perl imp... | Python | 1 |
ants[0] = r;
self.constants[1] = g;
self.constants[2] = b;
self.constants[3] = a;
}
pub fn add_blend_attachment(
&mut self,
attachment: vk::PipelineColorBlendAttachmentStateBuilder<'b>,
) {
// add the factor and add the attachment
// TODO: All attachm... | Rust | 0 |
///
/// The `word` must be UTF-8-encoded, and is `word_len` bytes (not characters)
/// long.
///
/// Caller must supply the `hyphens` output buffer for results; its size is
/// given in `hyphens_len`.
/// It should be at least `word_len` elements long.
///
/// Returns -1 if `word` is not valid UTF-8, or the output `hy... | Rust | 0 |
ex_list.join(";").as_bytes().to_vec())
}
/// Takes user input from terminal, optionally has a default and optionally displays it.
pub fn user_input(
message: &str,
default: Option<&str>,
show_default: bool,
allow_empty: bool,
) -> color_eyre::Result<String> {
match default {
Some(default) =... | Rust | 0 |
speech_event_type
== StreamingRecognizeResponseV1.SpeechEventType.SPEECH_ACTIVITY_END
):
return SpeechEnd(
time_since_start=time_offset + input.speech_event_time.total_seconds()
)
if input.results:
transcript = _get_transcript(input)
time_since = time_offset +... | Python | 1 |
estRaftStoreRouter {
tx: Sender<usize>,
significant_msg_sender: Sender<SignificantMsg<RocksSnapshot>>,
}
impl TestRaftStoreRouter {
pub fn new(
tx: Sender<usize>,
significant_msg_sender: Sender<SignificantMsg<RocksSnapshot>>,
) -> TestRaftStoreRouter {
... | Rust | 0 |
from datetime import datetime, timedelta
from facefusion.date_helper import describe_time_ago
def get_time_ago(days : int, hours : int, minutes : int) -> datetime:
previous_time = datetime.now() - timedelta(days = days, hours = hours, minutes = minutes)
return previous_time.astimezone()
def test_describe_time_ag... | Python | 1 |
# Adds the lib directory to the Python path
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from sshkeyboard import listen_keyboard, stop_listening
from lib.odrive_uart import ODriveUART
import json
# Load motor directions
with open(os.path.expanduser('~/quickstart/lib/motor_dir.js... | Python | 1 |
if self.eof() || self.starts_with("</") {
break;
}
nodes.push(self.parse_node());
}
nodes
}
/// Parse a single node.
fn parse_node(&mut self) -> dom::Node {
match self.next_char() {
'<' => self.parse_element(),
_ => s... | Rust | 0 |
eploytoken"},
{"name": "4. Send Token ERC20 Random or File (addressERC20.txt) | Botanix Testnet", "value": "sendtoken"},
{"name": "5. Mint NFT Circuit Breaker Ignition | Botanix Testnet [ END ]", "value": "mintnft"},
{"name": "6. Mint ConftApp Friend of coNFT │ Botanix Testnet", "val... | Python | 1 |
"""Tests for search.searchutils module."""
import pytest
import regex as re
from spaczz._search.searchutil import filter_overlapping_matches
from spaczz._search.searchutil import parse_regex
from spaczz.exceptions import RegexParseError
from spaczz.registry import get_re_pattern
def test_filter_overlapping_matches()... | Python | 1 |
from a2qt import QtCore, QtWidgets
from a2widget import hover_widget
class Demo(QtWidgets.QMainWindow):
def __init__(self):
super(Demo, self).__init__()
w = QtWidgets.QWidget(self)
w.setMinimumSize(400, 200)
self.setCentralWidget(w)
lyt = QtWidgets.QFormLayout(w)
se... | Python | 1 |
# Copyright (C) 2017-2025 Pier Carlo Chiodi
#
# 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 3 of the License, or
# (at your option) any later version.
#
# This program is distri... | Python | 1 |
existing_material_index + 4, variants[VariantConstants.LIGHT_IBEAM_KEY])
json_obj["materials"].insert(first_existing_material_index + 5, variants[VariantConstants.LOWGRADE_KEY])
# Insert palette sub-categories
palette_group["sub_categories"].insert(0, variants[VariantConstants.HULL_KEY]["name"])
palett... | Python | 1 |
ute_method = gradient_checkpointing_cfg.get("activations_checkpoint_method", "full")
tf_config.recompute_granularity = gradient_checkpointing_cfg.get(
"activations_checkpoint_granularity", "full"
)
tf_config.recompute_num_layers = gradient_checkpointin... | Python | 1 |
::create_local_sig_from_shares(
&federation.node_secret_share(),
params.self_node_index(block_height) + 1,
shared_block_secrets,
&block,
)
}
fn broadcast_localsig<C: ConnectionManager>(
sighash: BlockSigHash,
local_sig: &LocalSig,
conman: &C,
signer_id: &SignerID,
) ... | Rust | 0 |
to: *mut hl_type,
) -> *mut ::std::os::raw::c_void;
}
extern "C" {
pub fn hl_dyn_castf(data: *mut ::std::os::raw::c_void, t: *mut hl_type) -> f32;
}
extern "C" {
pub fn hl_dyn_castd(data: *mut ::std::os::raw::c_void, t: *mut hl_type) -> f64;
}
extern "C" {
pub fn hl_dyn_compare(a: *mut vdynamic, b: *mu... | Rust | 0 |
anyhow::Result<()> {
fs::write(&self.path, &self.document.to_string()).map_err(Into::into)
}
pub fn overwrite_features(&mut self, features: BTreeMap<String, BTreeSet<String>>) -> &Self {
let mut table = table();
table["default"] = value(Array::new());
for (feature, depends_feat... | Rust | 0 |
class Solution:
def maxDifference(self, s: str) -> int:
cnt = Counter(s)
s = set(s)
ans = -inf
for a in s:
for b in s:
if cnt[a] % 2 == 0 and cnt[b] % 2 == 1:
ans = max(ans, cnt[b] - cnt[a])
return ans
| Python | 1 |
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => Ok(0),
Err(e) => Err(Error::Io(e)),
}
}
/// .
pub fn flush(&self) {
unimplemented!()
}
/// .
pub fn drain(&self) {
unimplemented!()
}
// TODO: Enable available error detection (parity?) through ... | Rust | 0 |
,
"The Little Book of Rust Macros",
)
.tags("Rust macros")
.toread("yes")
.shared("no")
.description("WoW!!!")
.into_pin();
pin.time = Utc.ymd(2017, 5, 22).and_hms(17, 46, 54);
let mut buf: Vec<u8> = Vec::ne... | Rust | 0 |
ersion_zh_batch10',
'parallel_version_en_batch10',
'parallel_version_zh_batch15',
'parallel_version_en_batch15',
'parallel_version_zh_batch20',
'parallel_version_en_batch20',
],
summary_groups=needlebench_summary_groups,
)
def gen_atc_summarizer(needle_num_list):
cat... | Python | 1 |
to format a single field tuple struct (eg: `struct Foo(Bar);`)
/// which wraps *any debug type.
///
/// - `std`: to format the standard library types, where `PWrapper<ThatType>`
/// has a `const_debug_fmt` method.<br>
///
/// - `other`: to format non-standard-library types that have a `const_debug_fmt` method.
///
/// ... | Rust | 0 |
from typing import Annotated
from uuid import UUID
from click import group
from fastapi import APIRouter, Body, Depends, Query, status
from fastapi.responses import JSONResponse
from fazaconta_backend.modules.group.dtos.TransactionDTO import TransactionDTO
from fazaconta_backend.modules.group.useCases.transaction.cre... | Python | 1 |
ave been added since this code was generated.
Unknown(String),
}
impl std::convert::From<&str> for EventDataSource {
fn from(s: &str) -> Self {
match s {
"AWS_CLOUD_TRAIL" => EventDataSource::AwsCloudTrail,
"AWS_CODE_DEPLOY" => EventDataSource::AwsCodeDeploy,
other =>... | Rust | 0 |
from pydub import AudioSegment
from moviepy.editor import *
import os
import math
from parsesrt import parse
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-i', type=str,
help='input')
parser.add_argument('-srt', type=str,
help='subtitles')
parser.add_a... | Python | 1 |
= ram_init,
)
self.add_sdram("sdram",
phy = self.sdrphy,
module = sdram_module,
l2_cache_size = 0,
)
self.add_constant("SDRAM_TEST_DISABLE") # Skip SDRAM test to avoid corrupting pre-initialized contents.
def generate_dts(self... | Python | 1 |
nt.com/raphaelcohn/olympus-xmp/master/COPYRIGHT. No part of olympus-xmp, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
// Copyright © 2022 The developers of olympus-xmp. See the COPYRIGHT file in the top-level directory of this di... | Rust | 0 |
pub thumbnail: InputFile,
#[doc = "Thumbnail width, usually shouldn't exceed 320. Use 0 if unknown"]
pub width: i32,
#[doc = "Thumbnail height, usually shouldn't exceed 320. Use 0 if unknown"]
pub height: i32,
}
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
#[doc... | Rust | 0 |
(self.motors, self.curr_pos)
# Allegro compatibility, first read the allegro publisher and then convert to leap
def _receive_allegro(self, msg):
pose = lhu.allegro_to_LEAPhand(msg.position, zeros=False)
self.prev_pos = self.curr_pos
self.curr_pos = np.array(pose)
self.ft_client.... | Python | 1 |
n any finished threads to raise any
# exceptions encountered.
future.result()
try:
frame = worker_queue.get(timeout=_PROGRESS_INTERVAL)
yield frame
except queue.Empty: # pragma: NO COVER
... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.