text string | label_name string | labels int64 |
|---|---|---|
#!/usr/bin/env python3
'''FontForge: Double encode glyphs based on double encoding data in a file
Lines in file should look like: "LtnSmARetrHook",U+F236,U+1D8F'''
__url__ = 'https://github.com/silnrsi/pysilfont'
__copyright__ = 'Copyright (c) 2015-2025, SIL Global (https://www.sil.org)'
__license__ = 'Released under t... | Python | 1 |
t['status'] in ['failed', 'error']:
print(f"\n{result['status'].upper()}: {result['name']}")
if result['reason']:
print(f" Reason: {result['reason']}")
if 'expectation_details' in result:
for detail in result['expectation_details']:
if not detail['met']:
print(f" Rule {detail... | Python | 1 |
self.op_pieces &= !flip;
let value = -self.alpha_beta_search(depth, -high, -low, self.turn + 1, false);
self.my_pieces &= !flip; self.my_pieces &= !pos;
self.op_pieces |= flip;
if low < value {
low = value;
next_pos = pos.trailing_zeros() as usize;
... | Rust | 0 |
ose()).flatten()),
('mh', p*(m1_state[T-t_min:T,:].transpose()).flatten()),
('ml', p*(m2_state[T-t_min:T,:].transpose()).flatten()),
('a', (a_state[T-t_min:T,:].transpose()).flatten()),
('c', (c_state[T-t_min:T,:].transpose... | Python | 1 |
from queue import PriorityQueue
import numpy as np
from utils import get_collision_fn_PR2, load_env, execute_trajectory, draw_sphere_marker, draw_line
from pybullet_tools.utils import connect, disconnect, get_joint_positions, wait_if_gui, joint_from_name
from pybullet_tools.pr2_utils import PR2_GROUPS
import time
cla... | Python | 1 |
_SOCKET, libc::SO_SNDBUFFORCE, usize);
sockopt_impl!(GetOnly, SockType, libc::SOL_SOCKET, libc::SO_TYPE, super::SockType);
sockopt_impl!(GetOnly, AcceptConn, libc::SOL_SOCKET, libc::SO_ACCEPTCONN, bool);
#[cfg(any(target_os = "android", target_os = "linux"))]
sockopt_impl!(GetOnly, OriginalDst, libc::SOL_IP, libc::SO_O... | Rust | 0 |
ob"]
# after_job = ["rides.utils.after_job"]
# User Data Protection
# --------------------
# user_data_fields = [
# {
# "doctype": "{doctype_1}",
# "filter_by": "{filter_by}",
# "redact_fields": ["{field_1}", "{field_2}"],
# "partial": 1,
# },
# {
# "doctype": "{doctype_2}",
# "filter_by": "{filter_by}... | Python | 1 |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Train ControllableSeq2seq model.
"""
from parlai.scripts.train_model import TrainLoop
from parlai.scripts.train_mod... | Python | 1 |
pawn(move || { setup_listener(&thread_lock, STARTED, port) });
wait_for_thread_init(&lock);
let mut gdb = GdbRemote::new();
gdb.connect(("127.0.0.1", port)).unwrap();
}
#[test]
fn test_qsupported() {
let mut res = [0; 1024];
let port = 6861u16;
let lock = Ar... | Rust | 0 |
flat::POLICE_CAR_LIGHT as &crate::Emoji),
("police_officer" , &crate::flat::POLICE_OFFICER.default.default as &crate::Emoji),
("policeman" , &crate::flat::POLICE_OFFICER.gender(Gender::Male).default as &crate::Emoji),
("policewoman" , &crate::flat::POLICE_OFFICER.gender(Gender::Female).default as &crate::Emoji),
("pood... | Rust | 0 |
e with array value
(@next ([$($val:tt)*]) ($($next:tt)+) ($($args:tt)+)) => (
$($next)*($($args)* ([$($val)*]));
);
//handle with array value
(@next ([$($val:tt)*], $($rest:tt)+) ($($next:tt)+) ($($args:tt)+)) => (
$($next)*($($args)* ([$($val)*]) ($($rest)+));
);
//handle with ... | Rust | 0 |
ame): This may be changed into a visitor API once I get an AST working.
pub struct Printer {
file_id: usize,
gcx: Arc<GlobalCtxt>,
}
impl Printer {
#[must_use]
pub fn new(file_id: usize, gcx: Arc<GlobalCtxt>) -> Self {
Self { file_id, gcx }
}
}
pub mod telemetry;
pub mod world;
<filename>sr... | Rust | 0 |
/// As in:
///
/// ```
/// # fn f() -> bool {
/// # let n = 0;
/// match n {
/// 0...10 => {
/// return true;
/// }
/// // ...
/// # _ => {}
/// }
/// # false
/// # }
/// ```
///
/// *This type is available only if Syn is... | Rust | 0 |
*mut u8).add(4200usize) as *mut TCD3_NBYTES_MLOFFNO) }
}
#[doc = "0x1068 - TCD Minor Byte Count (Minor Loop Mapping Disabled)"]
#[inline(always)]
pub fn tcd3_nbytes_mlno(&self) -> &TCD3_NBYTES_MLNO {
unsafe { &*(((self as *const Self) as *const u8).add(4200usize) as *const TCD3_NBYTES_MLNO) }
}
#[doc =... | Rust | 0 |
: Option<Region>, f: F)
where
F: FnMut(Slot),
{
match cls.size {
InstanceSize::ObjArray => {
visit_object_array_refs(object, range, f);
}
InstanceSize::TupleArray(element_size) | InstanceSize::StructArray(element_size) => {
visit_struct_array_refs(object, cls, el... | Rust | 0 |
| layout::ARR_7
| layout::ARR_8
| layout::ARR_9
| layout::ARR_10 => TypeKind::Array,
_ => svm_sdk_std::panic(),
};
Result::Ok(kind)
}
}
//! Streaming SIMD Extensions 4.2 (SSE4.2)
//!
//! Extends SSE4.1 with STTNI (String and Text New Instructions).... | Rust | 0 |
build_package(src_dir, args.python, dry)
# 3. Stage them into the build tree
copy_dist(src_dir, bin_dir, dry)
# 4. Clean up temporary build folders inside the source tree
clean_artifacts([src_dir / "dist", src_dir / "build"], dry)
msg = (
"(dry run) Packaging steps simulated"
if... | Python | 1 |
spec(&self, spec: &CompilerSpec) -> Result<&Compiler> {
if let Some(language) = self.table.find_language(spec.as_language_name()) {
self.resolve_language(language)
} else if let Some(compiler) = self.table.find_compiler(spec.as_compiler_name()) {
Ok(compiler)
} else {
... | Rust | 0 |
}))
} else {
Rc::new(RefCell::new(TreeNode {
val: node_val,
left: Some(postorder_insert(left, val)),
right,
}))
}
} else {
Rc::new(RefCell::new(TreeNode::new(val)))
}
}
// Definition for a binary tree node.
#[d... | Rust | 0 |
# Copyright (C) 2013 SPARTA, Inc. a Parsons Company
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND SPARTA DISC... | Python | 1 |
_cond |c| {
cond = some(c);
}
option::unwrap(cond).signal();
}
use core::ops::{Range, RangeInclusive};
use core::borrow::{BorrowMut, Borrow};
pub use stm32_device_signature;
use cfg_if::cfg_if;
use crate::mem_ext::MemExt;
/// First and Second keys witch must be written to unlock Flash
const KEY_1: u... | Rust | 0 |
# Atividade 07:
# Contagem de Vogais em uma Palavra:
# Crie um programa que solicite uma palavra ao usuário e use um laço for com
# uma condicional para contar quantas vogais (a, e, i, o, u) a palavra contém.
word = input('Digite: ') | Python | 1 |
rupt disable bit
///
/// Flags affected: I
pub const IMPLIED: Instruction = Instruction {
opcode: 0x58,
cycles: 2,
extra_cycle: ExtraCycle::None,
operation: Operation::Implied(&cli),
};
#[cfg(test)]
mod tests {
use super::*;
use cpu::Registers;
use memory::block::BlockMemory;
#[test]
fn cli_impl() {... | Rust | 0 |
import time
import calendar
from datetime import datetime, timedelta
def get_timestamp():
return calendar.timegm(time.gmtime())
def date_to_timestamp(dt):
return time.mktime(dt.timetuple())
def timestamp_to_date(timestamp):
return datetime.fromtimestamp(timestamp)
def get_expiration_time_quotex(time... | Python | 1 |
expected_output = {
'lisp_id': {
0: {
'instance_id': {
4100: {
'eid_table': 'red',
'entries': 3,
'eid_prefix': '2001:194:168:1::72/128',
'eid': '2001:194:168:1::72',
'mask': 128,
... | Python | 1 |
<reponame>racketprogram/joke<filename>src/id.rs<gh_stars>10-100
#[derive(Clone, Debug, PartialEq)]
pub struct IdGen {
pub id: Vec<usize>,
}
impl IdGen {
pub fn new() -> IdGen {
IdGen { id: vec![0] }
}
pub fn add(&mut self) -> usize {
let id = *self.id.last().unwrap();
*self.id.... | Rust | 0 |
def solution(N, number):
if N == number:
return 1
dp = [set() for _ in range(9)] # dp[1] ~ dp[8] 사용 (인덱스 0은 사용 안 함)
for i in range(1, 9): # N 사용 횟수: 1개부터 8개까지
# 같은 숫자를 i번 반복해서 만든 수 (예: 5, 55, 555 ...)
dp[i].add(int(str(N) * i))
for j in range(1, i): # i를 두 덩어리로 쪼갬
... | Python | 1 |
_thread(reader_blockset)?;
Ok(0)
} else {
match readers.checked_add(1) {
Some(new_readers) => {
rwlock_set_readers(this, rwlock_op, Scalar::from_u32(new_readers))?;
Ok(0)
}
None => this.eval_libc_i32(... | Rust | 0 |
{
res[0][j] = 1;
res[1][j] = 1;
upper -= 1;
lower -= 1;
}
1 => {
if upper >= lower {
res[0][j] = 1;
upper -= 1;
} else ... | Rust | 0 |
self, long: &str) -> Self {
self.long = Some(long.into());
self
}
}
//! Flash memory
//!
//! # Examples
//!
//! - [Flash example](https://github.com/stm32-rs/stm32h7xx-hal/blob/master/examples/flash.rs)
//!
//! # Supported modes
//!
//! - Standard flash operations are supported only
//!
//! # Supported d... | Rust | 0 |
out_shape_dyn = tf.stack(
[shape_dyn[0],
shape_dyn[1] * strides2d[0] + shape_res2d[0],
shape_dyn[2] * strides2d[1] + shape_res2d[1],
filters])
out_shape3_sta = [None if shape_sta[1] is None else shape_sta[1] * strides2d[0] + shape_res2d[... | Python | 1 |
value): subscribed o 1: source statistics
/// descriptor 1 • 49: 3G minimum QoS traffic class - <param_val> selects
/// the acceptable value for the traffic class: o 0 (factory-programmed
/// value): subscribed o 1: conversational o 2: streaming o 3: interactive
/// o 4: background • 50: 3G min... | Rust | 0 |
for domain separation and chain versioning.
///
/// It sends through the wire a serialized `RemoteSignerRequestBody`.
pub async fn sign<R: RemoteSignerObject>(
&self,
public_key: &str,
bls_domain: Domain,
data: R,
fork: Fork,
genesis_validators_root: Hash256,... | Rust | 0 |
2 = 101002;
pub const HTS_IDX_NOCOOR: i32 = -2;
pub const HTS_IDX_START: i32 = -3;
pub const HTS_IDX_REST: i32 = -4;
pub const HTS_IDX_NONE: i32 = -5;
pub const HTS_FMT_CSI: u32 = 0;
pub const HTS_FMT_BAI: u32 = 1;
pub const HTS_FMT_TBI: u32 = 2;
pub const HTS_FMT_CRAI: u32 = 3;
pub const PRIhts_pos: &'static [u8; 3usi... | Rust | 0 |
as_bytes())?;
Ok(())
}
fn include_callback(src_path: &PathBuf)
-> impl Fn(&str, IncludeType, &str, usize) -> IncludeCallbackResult
{
let src_path = src_path.clone();
move |requested_source, include_type, requesting_source, _include_depth| {
let header_path;
let requested_source_path = ... | Rust | 0 |
_INS_AESIMC => Ok(Mnemonic::Aesimc),
ffi::_ND_INS_CLASS::ND_INS_AESKEYGENASSIST => Ok(Mnemonic::Aeskeygenassist),
ffi::_ND_INS_CLASS::ND_INS_ALTINST => Ok(Mnemonic::Altinst),
ffi::_ND_INS_CLASS::ND_INS_AND => Ok(Mnemonic::And),
ffi::_ND_INS_CLASS::ND_INS_ANDN => Ok(Mnemon... | Rust | 0 |
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILIT... | Rust | 0 |
ITESPACE | Rule::char | Rule::string | Rule::strict_string | Rule::number | Rule::key | Rule::value | Rule::file => unreachable!()
}
}
file_strc
}
#[inline]
pub fn parse_class(item: Pair<Rule>) -> (String, Class) {
let inner = item.into_inner();
let mut retclass: Class = Class{
items: D... | Rust | 0 |
s',self.videoCount,self.photoCount)
else:
print("你在干什么,请输入正确的功能序号!")
return
#匹配粘贴的url地址
def Find(self, string):
# findall() 查找匹配正则表达式的字符串
url = re.findall(
'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', string)
... | Python | 1 |
'success': True,
'data': result
})
response.headers.add('Access-Control-Allow-Origin', 'http://localhost:3000')
return response
except Exception as e:
logger.error(f"API Error in token tag evaluation: {str(e)}")
response = jsonify({'error': str(e)})
re... | Python | 1 |
import os
import re
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
from PseudoNetCDF.geoschemfiles import bpch
def cspec(path, smv2='smv2.log'):
if not os.path.isfile(smv2):
if os.path.isdir(smv2):
smv2 = os.path.join(smv2, 'smv2.log')
else:
... | Python | 1 |
def foydalanuvchi_malumotlari():
foydalanuvchilar = []
while True:
ism = input("Ismingizni kiriting: ")
familiya = input("Familiyangizni kiriting: ")
tugilgan_yil = input("Tug'ilgan yilingizni kiriting: ")
tugilgan_joy = input("Tug'ilgan joyingizni kiriting: ")
... | Python | 1 |
se and b"root" in response:
print(" ✅ Vulnerable")
vulnerable.append(port)
else:
print(" ❌ Not vulnerable")
cleanup_test_php()
return vulnerable
def main():
try:
ports = get_local_ports()
if not ports:
print("[!] No ports found on 127... | Python | 1 |
"""IZone tests."""
| Python | 1 |
C3779",
"OPENSSL_NO_SHA",
"OPENSSL_NO_SRP",
"OPENSSL_NO_SSL3_METHOD",
"OPENSSL_NO_TLSEXT",
"OPENSSL_NO_STDIO",
];
enum Version {
Openssl11x,
Openssl10x,
Libressl,
}
fn env(name: &str) -> Option<OsString> {
let prefix = env::var("TARGET").unwrap().to_uppercase().replace("-", "_");
... | Rust | 0 |
")]
pub min_length: Option<i32>,
#[serde(rename = "maxLength", skip_serializing_if = "Option::is_none")]
pub max_length: Option<i32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<ParameterMetadata>,
}
impl Default for ParameterOption {
fn default() -> Self {
Pa... | Rust | 0 |
FROM Level2 level2 \
LEFT JOIN (Level3 level2_level3) \
ON (level2.level3_id = level2_level3.id) \
JOIN Level1 level1 \
ON (level1.id = level2.level1_id AND level1.id = 1)";
toql.mock_rows(select1, vec![row!(1u64, "level... | Rust | 0 |
]
pub extern "system" fn Java_io_zbox_zboxfs_Repo_jniRemoveFile(
env: JNIEnv,
obj: JObject,
path: JString,
) {
let mut repo = env
.get_rust_field::<&str, Repo>(obj, RUST_OBJ_FIELD)
.unwrap();
let path: String = env.get_string(path).unwrap().into();
if let Err(err) = repo.remove_f... | Rust | 0 |
r_power_spell: Spell,
#[serde(rename = "minorPowerSpell")]
pub minor_power_spell: Spell,
}
#[derive(Deserialize, Serialize, Clone, Debug)]
pub struct EssenceSlot {
pub slot: u8,
pub id: u64,
pub rank: u8,
pub power: EssencePower,
}
#[derive(Deserialize, Serialize, Clone, Debug)]
pub struct Heart... | Rust | 0 |
slice(ram);
mbc
}
}
impl Mbc for Mbc1 {
fn read(&self, address: usize) -> u8 {
if address < 0x4000 {
if self.mode && self.rom_size > 4 {
let rom_address = (self.bank2 << 5) * 0x4000 + address;
self.rom[rom_address]
} else {
... | Rust | 0 |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import roc_curve, auc
from sklearn.metrics import confusion_matrix
def plot_training_history(history, model_name, save_path=None):
"""
Plot training history for a model.
"""
fig, (ax1, ax2) = plt.subplots(1, 2... | Python | 1 |
import functools
import signal
import contextlib
import time
def timeout(sec):
"""
timeout decorator
:param sec: function raise TimeoutError after ? seconds
"""
def decorator(func):
@functools.wraps(func)
def wrapped_func(*args, **kwargs):
def _handle_timeout(signum, fr... | Python | 1 |
.realpath(action.source)
if real_path not in uniqued_build_actions:
uniqued_build_actions[real_path] = action
elif build_action_uniqueing ==\
CompileActionUniqueingType.SOURCE_REGEX:
LOG.debug("uniqueing regex")
... | Python | 1 |
import os
import matplotlib.pyplot as plt
import sys
# Get input files and output file from command line arguments
input_files = sys.argv[1:-1]
output_png = sys.argv[-1]
# Initialize a structure to store data
data = {}
dataset_name = None # Variable to store the dataset name
# Loop through specified input files
for... | Python | 1 |
.org/3/library/exceptions.html#", $name, ") exception.
", $alt
)
);
($name: literal) => (
concat!(
"
Represents Python's [`", $name, "`](https://docs.python.org/3/library/exceptions.html#", $name, ") exception.
# Example: Raising ", $name, " from Rust
This exception can be sent to Python code... | Rust | 0 |
from src.ace_helpers import *
from tensorflow.keras.models import Model
import sys
import argparse
import os
import numpy as np
import tensorflow as tf
from keras.preprocessing import image
from keras.applications.xception import preprocess_input, decode_predictions
TARGET_SIZE = (299,299)
class GradCAM:
# Ada... | Python | 1 |
Bite player.
current_player().bite(attack_damage);
// Decrease the player's air with time.
let air = current_player().air;
current_player().air = air - dt * settings::PLAYER_LOSE_AIR_SPEED;
}
update_objects(dt);
fn fill_air() {
let player_pos = player_pos();
... | Rust | 0 |
[test]
fn less_than_1_0() {
expect("1<0").to_yield(false)
}
#[test]
fn less_than_1_1() {
expect("1<1").to_yield(false)
}
#[test]
fn less_than_1_2() {
expect("1<2").to_yield(true)
}
#[test]
fn less_than_1_false() {
expect("1<false").to_error(BadO... | Rust | 0 |
# coding=utf-8
import requests
from core import printmodels
from exploits import CVE_2017_9841PHPUnit
r = '\033[31m'
g = '\033[32m'
y = '\033[33m'
b = '\033[34m'
m = '\033[35m'
c = '\033[36m'
w = '\033[37m'
Headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) "
... | Python | 1 |
t_id}_report.pdf", # Full report
f"{output_path}/{self.config.subject_id}_stats.csv", # Full statistics
f"{output_path}/{self.config.subject_id}_config_gx_imaging.json" # Configurations from config .py file in JSON
f"tmp/membrane2gas.nii", # gas-normalized membrane image
... | Python | 1 |
, "AstId({}:{:?})", self.input, self.local)
}
}
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub struct Ast {
pub id: Id,
pub kind: AstKind,
}
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
pub enum AstKind {
Int(Int),
Text(Text),
Identifier(Identifier),
Symbol(Symbol),
Struct(Struct),
... | Rust | 0 |
from webspark.utils.decorators import cached_property
def test_cached_property_caches_value():
class MyClass:
def __init__(self):
self.computation_count = 0
@cached_property
def expensive_computation(self):
self.computation_count += 1
return 42
obj... | Python | 1 |
got suspended, trying to recover… (-ESTRPIPE)"
);
unsafe {
if asound::pcm::resume(this.device.pcm).is_ok() {
// Prepare, so we keep getting samples.
asound::pcm::prepare(this.device.p... | Rust | 0 |
le_variant(self, variant_position: int, alternative: str, genome: str, chromosome: str):
print("Genome:", genome)
print("Chromosome:", chromosome)
print("Variant position:", variant_position)
print("Variant alternative:", alternative)
WINDOW_SIZE = 8192
window_seq, seq_... | Python | 1 |
builtins2(self, size):
# These commands require larger memory for possible error messages
tk = self.interp.tk
value = '1' + ' ' * size
self.assertRaises(OverflowError, tk.evalfile, value)
self.assertRaises(OverflowError, tk.unsetvar, value)
self.assertRaises(OverflowError... | Python | 1 |
builder.set_timeout_config(timeout_config);
// the builder maintains a try-state. To avoid suppressing the warning when sleep is unset,
// only set it if we actually have a sleep impl.
if let Some(sleep_impl) = sleep_impl {
builder.set_sleep_impl(Some(sleep_impl));
}
... | Rust | 0 |
_os= "android"))]
extern crate gvr_sys;
#[cfg(all(target_os="windows", feature = "openvr"))]
extern crate libloading;
#[macro_use]
extern crate log;
#[cfg(all(feature = "oculusvr", target_os= "android"))]
extern crate ovr_mobile_sys;
#[cfg(any(feature = "googlevr", feature= "oculusvr"))]
mod gl {
include!(concat!(... | Rust | 0 |
&Grid<Point3>, point: Point3) -> (usize, usize) {
let mut min = Float::MAX;
let mut min_index = (0, 0);
let (rows, cols) = grid.size();
for i in 0..rows {
for j in 0..cols {
let distance = (point - grid[i][j]).length_squared();
if distance < min {
min = d... | Rust | 0 |
from cv2.typing import MatLike
from typing import Optional, List
from one_dragon.base.geometry.point import Point
from one_dragon.utils import cal_utils
from zzz_od.hollow_zero.hollow_map.hollow_map_utils import is_same_node
from zzz_od.hollow_zero.hollow_map.hollow_zero_map import HollowZeroMapNode, HollowZeroMap
d... | Python | 1 |
import os
import sys
# Ensure project root is on sys.path so that `import src...` works when running tests directly.
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
if PROJECT_ROOT not in sys.path:
sys.path.insert(0, PROJECT_ROOT)
| Python | 1 |
torch.randn(70, 130, 140),
]
# Set patch sizes and overlap ratios
t_patch, w_patch, h_patch = 3, 11, 13
t_overlap, w_overlap, h_overlap = 0.5, 0.5, 0.5
# Split the images and get indices
indices = []
paddings = []
for image_idx, image in enumerate(images):
image_indices... | Python | 1 |
word_to as u8, frac_word_to as u8, WORD_BUF_LEN);
let (int_word_to, frac_word_to) = (res.0 as usize, res.1 as usize);
let negative = lhs.negative != rhs.negative;
let frac_cnt = cmp::min(lhs.frac_cnt + rhs.frac_cnt, NOT_FIXED_DEC);
let int_cnt = int_word_to as u8 * DIGITS_PER_WORD;
let mut dec = Dec... | Rust | 0 |
#[doc = "The `FileSystemPermissionMode` enum."]
#[doc = ""]
#[doc = "*This API requires the following crate features to be activated: `FileSystemPermissionMode`*"]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileSystemPermissionMode {
Read = "read",
Readwrite = "readwrite",
}
use distaff::{ ProofOpti... | Rust | 0 |
r'答案是([ABCD])',
r'答案([ABCD])',
r'选择([ABCD])',
r'答案:([ABCD])'
]
# RE extraction
for answer_pattern in answer_patterns:
m = re.search(answer_pattern, gen_ans, re.M)
if m:
answer = m.group(1)
return answer... | Python | 1 |
std::io::prelude::*;
use std::io::ErrorKind;
use std::time::Instant;
use std::time::Duration;
fn main() {
let args: Args = Args::new(
env::args().collect(),
vec![
"-v".to_string(),
"-h".to_string(),
"-a".to_string(),
"-m".to_string(),
"-q".to_string(),
],
);
let mut inp... | Rust | 0 |
}
}
pub fn mouse_movement(event: &WindowEvent) -> Option<MouseMovement> {
match event {
WindowEvent::CursorMoved { position, .. } => Some(MouseMovement {
position: Coord {
x: position.x,
y: position.y,
},
}),
_ => None,
}
}
pu... | Rust | 0 |
LM(fi_fj[1])).total_degree())
def inter_reduction(Q):
r"""
Compute inter-reduced polynomials from a set of polynomials.
INPUT:
- ``Q`` -- a set of polynomials
OUTPUT:
if ``Q`` is the set `(f_1, ..., f_n)`, this method returns `(g_1,
..., g_s)` such that:
- `<f_1,...,f_n> = <g_1,... | Python | 1 |
import face_recognition
import cv2
import numpy as np
import csv
import os
import glob
from datetime import datetime
# import xlsxwriter as xl
video_capture=cv2.VideoCapture(0)
# job_image=face_recognition.load_image_file('7.jpg')
# jops_encoding=face_recognition.face_encodings(job_image)[0]
nithin_image=face_recogn... | Python | 1 |
print("无效的模型编号")
except ValueError:
print("请输入有效的数字")
elif choice == "3":
if not models:
print("没有可查看的模型")
continue
print("\n模型详细信息:")
for model in models:
print(f"\n模型名称: {mode... | Python | 1 |
65879822, -117.8300018)),
(7121, ("VIS", "KVIS", 36.3186988831, -119.392997742)),
(7122, ("MCE", "KMCE", 37.28469849, -120.5139999)),
(7123, ("CYR", "SUCA", -34.456401824951, -57.770599365234)),
(
7125,
("CPQ", "SDAM", -22.85919952392578, -47.10820007324219),
),
(7126, ("GYR", "K... | Rust | 0 |
from typing import Any, Callable, List, Optional, Sequence, Tuple, TypeVar, cast
from ..config import registry
from ..model import Model
from ..types import ArrayXd, ListXd
ItemT = TypeVar("ItemT")
InT = Sequence[Sequence[ItemT]]
OutT = ListXd
InnerInT = Sequence[ItemT]
InnerOutT = ArrayXd
@registry.layers("with_fl... | Python | 1 |
StorageLock {
fn new(id: StorageId, file: File) -> Self {
Self(id, Arc::new(LockData(file)))
}
}
impl Drop for LockData {
fn drop(&mut self) {
drop(self.0.unlock());
}
}
<filename>warp-api/src/adventures/mod.rs
pub mod delete;
pub mod favorite;
pub mod get;
pub mod journey;
pub mod lis... | Rust | 0 |
object with `id` (not including `id`)
/// - if `after=#id` is set; returns `limit` objects after object with `id` (not including `id`)
/// - if neither is set; returns last `limit` objects
#[derive(Debug, Serialize, Deserialize, Copy, Clone, PartialEq, Default)]
struct PaginationQuery {
before: Option<BlockNumber>... | Rust | 0 |
t_name) == 1:
sep = '-'
first_name = parts[-1].split(sep)
for i,n in enumerate(first_name):
if i > 0:
text += sep
if n.endswith('.'):
text += n
else:
text += n[0] + '.'
text += ' ' + ', '.join(parts[0:-1])
return text
def format_r... | Python | 1 |
def parse_tool_config(self, config_path: Path) -> Dict[str, Any]:
try:
with open(config_path, 'r', encoding='utf-8') as f:
content = f.read()
return self._parse_config_content(content)
except Exception as e:
print(f"解析配置文件失败 {config_path}: {e}")
... | Python | 1 |
d_data['ground_truth']
response_str = processed_data['response_str']
# Extract answer and calculate format score
answer = self._extract_answer(response_str)
format_score_val = self._compute_format_score(response_str, format_score)
# D... | Python | 1 |
_eq!(&nodes[0..4], &vec![0, 2, 6, 10]);
}
#[test]
fn aggregate_element_assembler_repeated_assembler() {
let mesh: QuadMesh2d<f64> = create_unit_square_uniform_quad_mesh_2d(3);
let qtable =
UniformQuadratureTable::from_quadrature_and_uniform_data(quadrature::tensor::quadrilateral_gauss(1), ());
let ... | Rust | 0 |
(obj.rsignal)(&mut obj.KernelHandle,
RSIG_BOOTENGINE,
mem::transmute::<PBOOTENGINE_PARAMS, PVOID>(&mut obj.BootParams),
mem::size_of::<BOOTENGINE_PARAMS>() as u32)
};
if ret != 0 {
return None;
}
... | Rust | 0 |
(P, Q)` -- True if both `P` and `Q` are true
//! - `or(P, Q)` -- True if either `P` or `Q` are true
//! - `impl(P, Q)` -- True if `or(not(P), Q)`
//!
//! LTL then adds the following to these:
//!
//! - `next(P)` -- True if `P` holds for the next element in the stream
//! - `until(P, Q)` ... | Rust | 0 |
from abc import ABC
from typing import List, Callable, Tuple
import threading
class Runnable(ABC):
def __init__(self):
self._force_stop: bool = False
self._execution_thread = None
def _start_execution_thread(self, target: Callable, args: Tuple = ()):
if self._execution_thread and self... | Python | 1 |
y() {
ExternType::Function(f) => function_info(env, f),
ExternType::Global(g) => global_info(env, g),
ExternType::Table(t) => table_info(env, t),
ExternType::Memory(m) => memory_info(env, m),
};
map = map.map_put(export_name, export_info)?;
}
Ok(ma... | Rust | 0 |
s = extract_emojis(&message);
if emojis_and_counts.is_empty() {
return None;
}
Some(UserEmojiData {
user,
emojis_and_counts,
})
}
//should check thread for all message types?
_ => None,
}
}
fn ex... | Rust | 0 |
arding = NamedSharding(mesh, PartitionSpec(*x_spec[:-1]))
amax_sharding = NamedSharding(mesh, PartitionSpec(*get_padded_spec(arg_infos[2])))
return (out_sharding, rsigma_sharding, amax_sharding)
@staticmethod
def partition(out_dtype, epsilon, mesh, arg_infos, result_infos):
del result_i... | Python | 1 |
system" fn GetWindowTextW(hWnd: HWND, lpString: LPWSTR, nMaxCount: c_int) -> c_int
pub fn get_window_text(hwnd: windef::HWND) -> String {
let max_char_count: usize = 300;
let mut buffer: Vec<winnt::WCHAR> = Vec::with_capacity(max_char_count);
unsafe {
let char_count = winuser::GetWindowTextW(
... | Rust | 0 |
acha20poly1305::{ChaCha20Poly1305, Key, Nonce};
use clap::{Parser, Subcommand};
use ed25519_dalek::{Keypair, Signature, Signer, Verifier, PublicKey, PUBLIC_KEY_LENGTH, SIGNATURE_LENGTH};
use glob::glob;
use path_clean::PathClean;
use rand::rngs::OsRng;
use rand::RngCore;
use sharks::{ Sharks, Share };
// -------... | Rust | 0 |
import heapq
def initialize():
jugs = [51, 129, 150, 138, 128, 72, 69, 111, 75]
buckets = [454, 547, 601]
num_buckets = len(buckets)
num_jugs = len(jugs)
visited_costs = {}
visited_costs[(0, 0, 0, 0, 0, 0, 0, 0, 0)] = 0
queue = [(0, 0, [], (0, 0, 0, 0, 0, 0, 0, 0, 0))]
return (jugs, bu... | Python | 1 |
);
const PATH_ABSOLUTE:&str = formatcp!("(?:/(?:{SEGMENT_NZ}{PATH_ABEMPTY})?)");
formatcp!("{PATH_ABSOLUTE}|{PATH_ABEMPTY}")
}
/// https://datatracker.ietf.org/doc/html/rfc3986#section-3.4
const fn query() -> &'static str {
formatcp!(r"(?:{PCHAR}|[/?])*")
}
/// https://datatracker.ietf.org/doc/html/rfc3986#... | Rust | 0 |
().completed_stichs().iter().map(|stich| stich[epi]))
);
let playerparties = SPlayerParties13::new(rules.epi);
for stich in gamefinishedstiche.get().completed_stichs().iter() {
for (epi_card, card) in stich.iter() {
let b_primary = playerparties.is... | Rust | 0 |
ion_notifs_rx, _peer_notifs_rx) =
build_test_peer(
rt.handle().clone(),
TimeService::mock(),
ConnectionOrigin::Inbound,
);
let remote_peer_id = peer.remote_peer_id();
let test = async move {
connection.close().await.unwrap();
assert_disconnect... | Rust | 0 |
alar.copy_from_slice(s);
scalar.complement()?;
assert_eq!(&scalar[..], c);
}
Ok(())
}
#[test]
fn scalar_add_sub_vectors() -> Result<(), AlkaliError> {
let summands = [([0x69; 32], [0x42; 32]), ([0xcd; 32], [0x42; 32])];
let sums_diffs = [
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.