text string | label_name string | labels int64 |
|---|---|---|
"""
Copyright (c) 2020, Oracle Corporation and/or its affiliates.
Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl.
"""
class FlattenedFolder(object):
"""
Class containing information for processing a flattened folder.
"""
def __init__(self, mbean_t... | Python | 1 |
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Optional
from .base import TelegramMethod
class UpgradeGift(TelegramMethod[bool]):
"""
Upgrades a given regular gift to a unique gift. Requires the *can_transfer_and_upgrade_gifts* business bot right. Additionally requires the *can_tr... | Python | 1 |
}
let m = d[*o];
*o += 1;
Ok(match m {
0 => Ok(T::de_bin(o, d)?),
1 => Err(E::de_bin(o, d)?),
_ => return Err(DeBinErr{o:*o, l:0, s:d.len(), msg:format!("Result<T, E>")}),
})
}
}
impl<T> SerBin for [T] where T: SerBin {
fn ser_bin(&se... | Rust | 0 |
files.len())
}
#[async_recursion]
async fn scan_path(
&mut self,
logger: &Logger,
path: &Path,
update_list: &mut Vec<PathBuf>,
) -> Result<u64> {
let mut size: u64 = 0;
debug!(logger, "Scanning path: {}", path.display());
if path.is_file() {
... | Rust | 0 |
Job].
#[prost(enumeration = "AnnotationType", tag = "3")]
pub annotation_type: i32,
/// Optional. Metadata about annotations for the input. You must specify this
/// field if you are using this InputConfig in an [EvaluationJob][google.cloud.datalabeling.v1beta1.EvaluationJob] for a
/// model version... | Rust | 0 |
import sys, os, shutil, subprocess, time
import O4_Imagery_Utils as IMG
IMG.initialize_color_filters_dict()
IMG.initialize_providers_dict()
if __name__ == '__main__':
tdir = sys.argv[1]
if sys.argv[2] not in IMG.providers_dict:
print("Unknown provider.")
sys.exit()
if ("Earth Orbit Textures... | Python | 1 |
o_block = np.array([0])
# P = np.block([[eT,zero_block],
# [-F,1*np.ones((6,1))],
# [np.zeros(6,),-1]]) # TODO: Replace None with your result
# q = np.block([3,np.zeros((7,))]).reshape(-1,1) # TODO: Replace None with your result
# c = np.block([[np.zeros((6,1))],[1]... | Python | 1 |
let mut out = String::new();
{
let mut writer = smithy_xml::encode::XmlWriter::new(&mut out);
#[allow(unused_mut)]
let mut root = writer
.start_el("CORSConfiguration")
.write_ns("http://s3.amazonaws.com/doc/2006-03-01/", None);
crate::xml_ser::serialize_str... | Rust | 0 |
: 0..7. The default is 0. Values 1-7 will avoid eob and skip"]
#[doc = " block optimization and will change rdmult in favour of block sharpness."]
pub const AOME_SET_SHARPNESS: aome_enc_control_id = 16;
#[doc = "Codec control function to set the threshold for MBs treated static,"]
#[doc = " unsigned int parameter"]
pub... | Rust | 0 |
nent will be automatically instantiated.
If 'False' either existing component or the `noValue` object will be
returned.
Returns
-------
: :py:class:`~pyasn1.type.base.PyAsn1Item`
a PyASN1 object
Examples
--------
.. code-block:: pyth... | Python | 1 |
# Is it a palindrome?
def is_palindrome(s):
return s.lower() == s[::-1].lower()
print(is_palindrome("Radar")) | Python | 1 |
in_key_prefix() -> &'static str {
"base_node"
}
}
impl BaseNodeConfig {
pub fn set_base_path<P: AsRef<Path>>(&mut self, base_path: P) {
if !self.identity_file.is_absolute() {
self.identity_file = base_path.as_ref().join(self.identity_file.as_path());
}
if !self.data_... | Rust | 0 |
def count_vowels():
text = input("Enter a string: ")
vowels = "aeiouAEIOU"
count = sum(1 for char in text if char in vowels)
print(f"Number of vowels: {count}")
count_vowels() | Python | 1 |
s[0].data[1])
# print(record.samples[0].data[1][0],record.samples[0].data[1][1],record.samples[0].data[1][1])
now_arr2[1][arr_pos2] = record.POS
now_arr2[2][arr_pos2] = record.samples[0].data[1][0]
now_arr2[3][arr_pos2] = record.samples[0].... | Python | 1 |
(&mut self) {
// Update the texture with the contents of the screen buffer
unsafe { slice::raw::buf_as_slice(self.buffer.as_ptr() as *u8, 4 * self.buffer.len(), |bytes| {
self.texture.update(None, bytes, 4 * self.width as int);
}); }
// Render the texture (stretching it to f... | Rust | 0 |
####################################################################################################
# Copyright (c) 2016 - 2024, EPFL / Blue Brain Project
# Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch>
#
# This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis>
#
# This program is fre... | Python | 1 |
while let Some(c) = chars.next() {
match c {
'+' => tokens.push(Token::Operator(Op::Add)),
'-' => {
if tokens.len() == 0 {
tokens.push(Token::Unary);
continue;
}
match &tokens[tokens.len() - 1] {
... | Rust | 0 |
encrypted_args.to_hex(),
&encrypted_callable.to_hex(), &user_pubkey.to_hex(), gas_limit, &address.to_hex());
let v: Value = conn_and_call_ipc(&msg.to_string(), port);
(v, address.into())
}
pub fn full_addition_compute(port: &'static str, a: u64, b: u64) -> (Value, [u8; 32], [u8; ... | Rust | 0 |
# Copyright (c) 2022-2024, The Isaac Lab Project Developers.
# All rights reserved.
#
# SPDX-License-Identifier: BSD-3-Clause
from dataclasses import MISSING
from omni.isaac.lab.actuators import ActuatorBaseCfg
from omni.isaac.lab.utils import configclass
from ..rigid_object import RigidObjectCfg
from .articulation ... | Python | 1 |
"""시장 지표 밸류 오브젝트 모듈.
이 모듈은 PER, PBR, EPS 등 주식 시장 지표를 나타내는
불변 밸류 오브젝트들을 정의합니다.
"""
from dataclasses import dataclass
from datetime import datetime
from decimal import Decimal
from enum import Enum
from typing import Optional
class ValuationLevel(Enum):
"""밸류에이션 수준."""
SEVERELY_UNDERVALUED = "SEVERELY_UNDERV... | Python | 1 |
NOT.matches(first) {
//不是 not
if self.segments.is_empty() {
//sqlSegment是 and 或者 or 并且在第一位,不继续执行
return false;
}
let match_last_and = MatchSegment::AND.matches(last);
... | Rust | 0 |
(),
);
let up_derivatives = Coords3::new(
up_derivative_vecs.pop_front().unwrap(),
up_derivative_vecs.pop_front().unwrap(),
up_derivative_vecs.pop_front().unwrap(),
);
let down_derivatives = Coords3::new(
down_derivative_vecs.pop_front().unwrap(),
down_derivativ... | Rust | 0 |
signal1);
}
println!("Part 1: After 100 phases, the first 8 digits are: {:?}", &signal1[..8]);
// Part 2
let real_signal: Vec<i32> = signal.iter().copied().cycle().take(10_000 * signal.len()).collect();
println!("Part 2: The first 8 digits of the final output list are: {:?}", &fft(&real_signal, off... | Rust | 0 |
struct Member {
pub user: User,
//pub presence: Presence
}
#[derive(Debug, Deserialize, Serialize)]
pub struct Room {
pub name: String,
pub description: Option<String>,
//pub emoji:
pub position: usize,
#[serde(default)]
#[serde(deserialize_with = "from_str_opt")]
pub last_message_id: Option<u64>,
#[serde(d... | Rust | 0 |
.file(), location.line(), message);
sys_exit(1)
}
#[lang = "oom"]
fn oom(_: Layout) -> ! {
panic!("out of memory");
}
#[no_mangle]
pub extern fn abort() -> ! {
sys_exit(2)
}
#[no_mangle]
pub extern fn __mulsi3(mut a: u32, mut b: u32) -> u32 {
let mut r: u32 = 0;
while a > 0 {
if a & 1 > ... | Rust | 0 |
IT : UProperty = 0x7001;
pub static UCHAR_INVALID_CODE : UProperty = -1;
pub mod libicu {
#[link_name = "icuuc"]
#[abi = "cdecl"]
pub extern {
unsafe fn u_hasBinaryProperty(c: UChar32, which: UProperty)
-> UBool;
unsafe fn ... | Rust | 0 |
:Deserialize)]
struct Item {
details: ItemDetails,
}
#[derive(Debug, serde::Deserialize)]
struct ItemDetails {
sections: Vec<ItemSection>,
}
#[derive(Debug, serde::Deserialize)]
struct ItemSection {
fields: Vec<ItemField>,
}
#[derive(Debug, serde::Deserialize)]
struct ItemField {
k: String,
t: St... | Rust | 0 |
xt_input, new_images, chatbot, chatbot_display, existing_images],
[text_input, new_images, chatbot, chatbot_display, existing_images],
).success(
stream_model_output,
[existing_images, chatbot, chatbot_display, max_gen_len, seed, gen_t, cfg, image_top_k, text_top_k],
... | Python | 1 |
o_iter()
.filter_map(move |id| (self.0).0.roles.get(&id).map(|r| Ok(r.value().clone())));
let stream = stream::iter(iter).boxed();
future::ok(stream).boxed()
}
fn user(&self, emoji_id: EmojiId) -> GetEntityFuture<'_, UserEntity, InMemoryBackendError> {
let user = self
... | Rust | 0 |
cursor_visible().unwrap();
console::set_cursor_visible(false).unwrap();
assert_eq!(console::is_cursor_visible().unwrap(), false);
console::set_cursor_visible(visible).unwrap();
}
#[test]
fn background_color() {
let old_color = console::get_background_color().unwrap();
console::set_backgr... | Rust | 0 |
from ipaddress import ip_network
for a in range(16, 25):
net = ip_network(f'152.65.245.132/{a}', False)
for ip in net:
lcnt = f'{int(ip):032b}'[:16].count('0')
rcnt = f'{int(ip):032b}'[16:].count('0')
if not (lcnt >= rcnt):
break
else:
print(net.netmask)
| Python | 1 |
title="选择")
id = d.go()
if id == -1: return
script = script.replace(''' # If you need to parse another string in the parsing function.''',
''' _meta = response.meta.get('_plusmeta') or {}\n # If you need to parse another st... | Python | 1 |
# Condicionales (if elif else)
variable1 = True
variable2 = False
# if variable1:
# print('variable 1')
# if not variable2:
# print('variable 2')
if not variable2:
print('variable 2') # Esta
elif not variable2:
print('variable 2')
elif variable1:
print('variable 1')
elif variable1:
print('va... | Python | 1 |
idation_pool_data_storage(*pool_id).deviation_threshold;
// right_border = pool_ideal_balance_usd + pool_ideal_balance_usd * deviation_threshold
let right_border =
sum_with_mult_result(pool_ideal_balance_usd, pool_ideal_balance_usd, deviation_threshold)
.map_err(|_| Error::<T>::BalanceOverflo... | Rust | 0 |
with_title(window_title)
.with_inner_size(size)
.build(&event_loop)
.unwrap();
let canvas = window.canvas();
let document = stdweb::web::document();
let body: stdweb::web::Node = document.body().expect("Get HTML body").into();
body.append_child(&canvas);
let webgl2_context: ... | Rust | 0 |
# 驗證表單
if not selected_data_types:
st.error("請選擇至少一種資料類型")
return None
if not selected_sources:
st.error("請選擇至少一個資料來源")
return None
if update_type == "指定標的更新" and not selected_symbols:
st.error("請選... | Python | 1 |
Unsigned }},
predicate! {{ <A as Add<B>>::Output }: { Cmp }},
predicate! {{ <A as Add<B>>::Output }: { IsEqual<<A as Add<B>>::Output> }},
predicate! {{ A }: { Add<B> }},
],
);
assert_into(
op! { A / B },
vec![
... | Rust | 0 |
"""
공통 모듈
"""
| Python | 1 |
n particular no `IndexedParallelIterator` (no zip),
//! no `FromParallelIterator` (no collect)...
//! - `par_sort` is logged but it is not directly rayon's `par_sort` but a copy-pasted version of
//! it (as a demonstration). so the algorithm is hard-coded into rayon_logs.
//! - you should not mix logged and not logge... | Rust | 0 |
ser_id}" if user_id else "allocation_started",
priority="high",
correlation_id=correlation_id,
)
def create_allocation_ended_message(
factory: MessageFactory,
miner_hotkey: str,
allocation_uuid: str,
reason: str = "allocation_completed",
correlation_id: str | None = None,
) -> ... | Python | 1 |
ves a Designated channel listing")
@ext.example("channel delete user_join_log #some-channel")
@ext.docs("DesignatedChannels", "delete")
async def delete(
self, ctx: ext.ClemBotCtx, channel_type: str, channel: discord.TextChannel
) -> None:
"""
Command to delete a registered TextC... | Python | 1 |
def circular_shift(x, shift):
"""Circular shift the digits of the integer x, shift the digits right by shift
and return the result as a string.
If shift > number of digits, return digits reversed.
>>> circular_shift(12, 1)
"21"
>>> circular_shift(12, 2)
"12"
"""
# Your code here
... | Python | 1 |
tered()
.build()
.unwrap();
let mut canvas = window.into_canvas().build().unwrap();
canvas.set_draw_color(Color::RGB(0, 255, 0));
canvas.clear();
canvas.present();
SdlDisplay {
canvas
}
}
pub fn draw(&mut se... | Rust | 0 |
sk_pool.push_dyn_back(1, queue1);
let index2 = task_pool.push_dyn_back(2, queue2);
let index3 = task_pool.push_dyn_async(3, 2);
assert_eq!(task_pool.remove_sync(queue1, index1), 1);
assert_eq!(task_pool.remove_sync(queue2, index2), 2);
assert_eq!(task_pool.remove_async(index3), 3);
/**... | Rust | 0 |
elivered
pub redelivered: bool,
/// Contains the properties and the headers of the
/// message.
pub properties: BasicProperties,
/// The payload of the message in binary format.
pub data: Vec<u8>,
}
impl Delivery {
pub(crate) fn new(
delivery_tag: LongLongUInt,
exchange: S... | Rust | 0 |
e crate::cli::Filters;
pub struct Keep {
filters: Vec<Box<dyn filter::Filter>>,
internal_threshold: f64,
}
impl Keep {
pub fn new(
internal_match: f64,
matches: &std::collections::HashMap<String, clap::ArgMatches>,
) -> Self {
let filters = Vec::new();
let mut k = Keep ... | Rust | 0 |
'''
Problem Statement: https://www.hackerrank.com/challenges/ginorts/problem
Author: striker
'''
TOTAL_ALPHABETS = 26
TOTAL_DIGITS_DECIMAL = 10
upper_case_freq = [0] * TOTAL_ALPHABETS
lower_case_freq = [0] * TOTAL_ALPHABETS
digit_freq = [0] * TOTAL_DIGITS_DECIMAL
def ginorts(string_list):
for character in string_... | Python | 1 |
# the default canvas in DrawBot is 1000 x 1000 units
# the 0, 0 origin is at the bottom left of the canvas
# each DrawBot unit = 1 desktop point = 1 pixel
# this code draws a rectangle on the canvas
# rect() is a DrawBot function that takes four arguments: an x-position and a y-position for the lower-left corner of th... | Python | 1 |
base = get_juliaserver_base_url()
.with_context(|| "Failed to get Juliaup server base URL.")?;
let version = get_own_version().unwrap();
// let version = semver::Version::parse("1.5.29").unwrap();
let download_url_path = format!("juliaup/bin/juliaup-{}-{}.tar.gz", version, juliaup_target);
le... | Rust | 0 |
ut bool;
}
#[brush::wrapper]
pub type FlipperRef = dyn Flipper;
#[brush::trait_definition]
pub trait Flipper: FlipperStorage + ReentrancyGuardStorage {
#[ink(message)]
fn get_value(&self) -> bool {
self.value().clone()
}
#[ink(message)]
#[brush:... | Rust | 0 |
from _plotly_utils.files import PLOTLY_DIR, ensure_writable_plotly_dir # noqa: F401
| Python | 1 |
ug for ServiceQuotaExceededException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ServiceQuotaExceededException");
formatter.field("message", &self.message);
formatter.finish()
}
}
impl ServiceQuotaExceededException {
/// ... | Rust | 0 |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2005-2023 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at https://trac.edgewall.org/wiki/TracLicense.
#
# This software cons... | Python | 1 |
"""
סקריפט ייעודי לעיבוד נתונים: ממזג את קובצי ה-CSV הגולמיים
מ-data/raw/ לקובץ מאוחד ב-data/processed/SPY_processed.csv.
"""
import pandas as pd
import os
import logging
import sys
# הגדרת לוגינג
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[logging.S... | Python | 1 |
"""Crear tabla pokemons
Revision ID: 5c3e54bb0b25
Revises:
Create Date: 2024-10-30 16:36:31.075985
"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision: str = "5c3e54bb0b25"
down_revision: Union[str, None] = None
branch_labels: Un... | Python | 1 |
0)
}
#[doc = "reduces"]
#[inline(always)]
pub fn acmp3_cmp_igen_trim_dn_1(self) -> &'a mut W {
self.variant(ACMP3_CMP_IGEN_TRIM_DN_A::ACMP3_CMP_IGEN_TRIM_DN_1)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
... | Rust | 0 |
", "137", "Var", "Toulon"),
("84", "007", "Vaucluse", "Avignon"),
("85", "191", "Vendée", "Roche-sur-Yon"),
("86", "194", "Vienne", "Poitiers"),
("87", "085", "Haute-Vienne", "Limoges"),
("88", "160", "Vosges", "Épinal"),
("89", "024", "Yonne", "Auxerre"),
("90", ... | Python | 1 |
error("HTTP status code {}", status_code)]
DefaultResponse {
status_code: http::StatusCode,
value: models::ErrorResponse,
},
#[error("Failed to parse request URL: {}", source)]
ParseUrlError { source: url::ParseError },
#[error(... | Rust | 0 |
sp.lock().unwrap().exponential_backoff(backoff_key.clone());
// // connector w/ timeout
let to = sp
.lock()
.unwrap()
.current_timeout(backoff_key.clone())
.to_std()
.unwrap();
// let connector = awc::Connector::new()
//... | Rust | 0 |
from typing import List
from redis_om import JsonModel, EmbeddedJsonModel
from app.database.redis.session import RedisOMConnection
class ChatMessage(EmbeddedJsonModel):
role: str
content: str
created_at: str
class Meta:
database = RedisOMConnection.get_connection() # 비동기 Redis 커넥션 사용
... | Python | 1 |
expected_output = {
'summary': {
'total_drop_address': 0,
'total_lisp_local_address': 0,
'total_lisp_remote_address': 0,
'total_secure_address': 0,
},
'total_mac_address': 0,
'type': {
'mat_all_vlans': '0x10',
'mat_cpu_addr': '0x4',
'mat_discard_ad... | Python | 1 |
write().unwrap() = Arc::new(42));
}
}
noise!();
method!(read);
method!(write);
}
mod parking_rwlock {
use parking_lot::RwLock;
static L: Lazy<RwLock<Arc<usize>>> = Lazy::new(|| RwLock::new(Arc::new(0)));
fn lease() {
for _ in 0..ITERS {
test::black_box(**L.re... | Rust | 0 |
Type::Sql, true).unwrap();
assert!(mods.is_empty());
}
}
<reponame>xd009642/tensorflow-protos-rs
// This file is generated by rust-protobuf 2.17.0. Do not edit
// @generated
// https://github.com/rust-lang/rust-clippy/issues/702
#![allow(unknown_lints)]
#![allow(clippy::all)]
#![allow(unused_attributes)]
... | Rust | 0 |
b struct Slice<T> {
pub data: *mut T,
pub len: usize,
}
impl<T> std::default::Default for Slice<T> {
fn default() -> Self {
Slice { data: std::ptr::null_mut(), len: 0 }
}
}
impl<T> fmt::Debug for Slice<T> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter
... | Rust | 0 |
<'a, C, A> CallBuilder for LinkInsertCall<'a, C, A> {}
impl<'a, C, A> LinkInsertCall<'a, C, A> where C: BorrowMut<hyper::Client>, A: oauth2::GetToken {
/// Perform the operation you have build so far.
pub fn doit(mut self) -> Result<(hyper::client::Response, Link)> {
use std::io::{Read, Seek};
... | Rust | 0 |
TEXTURE_ENV_MODE,
TEXTURE_GEN_MODE,
TEXTURE_GEN_Q,
TEXTURE_GEN_R,
TEXTURE_GEN_S,
TEXTURE_GEN_T,
TEXTURE_HEIGHT,
TEXTURE_HASH_TABLE_SIZE,
TEXTURE_MAG_FILTER,
TEXTURE_MATRIX,
TEXTURE_MIN_FILTER,
TEXTURE_PRIORITY,
TEXTURE_RESIDENT,
TEXTURE_STACK_DEPTH,
TEXTURE_W... | Rust | 0 |
"""مجلد learning في 03_memory_system"""
| Python | 1 |
NBYTES_MLOFFYES)
}
}
#[doc = "0x10a8 - TCD Signed Minor Loop Offset (Minor Loop Mapping Enabled and Offset Disabled)"]
#[inline(always)]
pub fn tcd5_nbytes_mloffno(&self) -> &TCD5_NBYTES_MLOFFNO {
unsafe { &*(((self as *const Self) as *const u8).add(4264usize) as *const TCD5_NBYTES_MLOFFNO) }
}
#[do... | Rust | 0 |
nt(f"dt = {dt.value() * 1e3:.03f} ms")
plt.figure()
ax = plt.axes(projection="3d")
def plot_wireframe(ax, f, x_range, y_range, color):
x, y = np.mgrid[x_range[0] : x_range[1] : 25j, y_range[0] : y_range[1] : 25j]
# Need an (N, 2) array of (x, y) pairs.
xy = np.column_stack([x.flat... | Python | 1 |
t!("failed to parse steps: {:?}", err))
})?;
let value = R64::try_new(value).ok_or_else(|| {
D::Error::custom(format!("invalid value '{}'", token))
})?;
Ok(value)
})
... | Rust | 0 |
"""Information about Python operators"""
from __future__ import annotations
from typing import Final
# Map from binary operator id to related method name (in Python 3).
op_methods: Final = {
"+": "__add__",
"-": "__sub__",
"*": "__mul__",
"/": "__truediv__",
"%": "__mod__",
"divmod": "__divmo... | Python | 1 |
def CreateBoard():
Board = []
for i in range(3):
Rows = []
for j in range(3):
Rows.append('-')
Board.append(Rows)
return Board
def CheckHor(Board, Player):
outcomes = []
for i in range(3):
order = []
for j in range (3):
if Board[i][j] ... | Python | 1 |
};
cmp = memcmp(
(*sd1).key as *const libc::c_void,
(*sd2).key as *const libc::c_void,
keylen as _,
);
if cmp == 0 {
cmp = (*sd1).keylen - (*sd2).keylen
}
}
cmp
}
unsafe fn build_name_tree(
mut first: *mut named_object,
mut ... | Rust | 0 |
import hashlib
import hmac
import subprocess
import sys
def get_hdd_id(device_path):
cmd = ['hdparm', '--Istdout', device_path]
proc = subprocess.run(cmd, capture_output=True)
if proc.returncode != 0:
raise RuntimeError('hdparm exited with non-zero status')
id_hex = ' '.join(proc.stdout.decode(... | Python | 1 |
visit_dirs(
PathBuf::from_str(&errors_dir).unwrap(),
&mut errors_root_section,
)?;
Ok(errors_root_section)
}
#[cfg(test)]
mod test_regex {
use regex::Regex;
#[test]
fn error_code_pattern() {
let error_code_pattern = Regex::new(r"B[0-9]{4}\.md").unwrap();
assert!(err... | Rust | 0 |
.unwrap(),
Fp2::new(
Fp::from_u64s_le(&[
0x40b299b2704258c5,
0x6ef7de92e8c68b63,
0x6d2ddbe552203e82,
0x8d7f1f723d02c1d3,
0x881b3e01b611c070,
0x10f6963bbad2ebc5
... | Rust | 0 |
else:
dictTValue['tRollResult'] = rd_para_str + '=' + tmp_reply_str_1
if rd_reason_str != None:
dictTValue['tRollReason'] = rd_reason_str
tmp_reply_str = OlivaDiceCore.msgCustomManager.formatReplySTR(dictStrCustom['strRollWithReason'], dictTV... | Python | 1 |
self._n_updates += 1
if not continue_training:
break
explained_var = explained_variance(self.rollout_buffer.values.flatten(), self.rollout_buffer.returns.flatten())
# Logs
self.logger.record("train/entropy_loss", np.mean(entropy_losses))
self.logge... | Python | 1 |
> &'static str;
}
impl CenterRightNumbers for &str {
fn center_right_space(&self, _alignment: Align, _width: usize) -> &'static str {
// Disables center-right formatting and aligns strings center-left
""
}
}
impl CenterRightNumbers for String {
fn center_right_space(&self, alignment: Align... | Rust | 0 |
())))
}
/// Wipes the store.
pub fn store_wipe(&self) {
self.write_notification("store.wipe", None)
}
/// Gets a list of keys in the store.
pub async fn store_keys(&self) -> Result<Vec<String>, ResponseError> {
self.request("store.keys", None).await.map(|r| match r {
... | Rust | 0 |
EN2_R {
type Target = crate::FieldReader<u16, u16>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `TOUCH_PAD_OUTEN2` writer - Bitmap defining SET2 for generating wakeup interrupt. SET2 is \"touched\" only if at least one of touch pad in SET2 is \"touched\"."]
pu... | Rust | 0 |
ol::new(py);
let slf = py.mut_from_borrowed_ptr::<T>(slf);
let result = slf.bf_getbuffer(arg1, arg2).into();
crate::callback::cb_convert(UnitCallbackConverter, py, result)
}
Some(wrap::<T>)
}
}
// Copyright (c) 2016 DWANGO Co., Ltd. All Rights Reserved.
// See th... | Rust | 0 |
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];
}
#[cfg(test)]
mod tests_193 {
... | Rust | 0 |
object = image_object.flipv();
let (image_width, image_height) = (image_object.width(), image_object.height());
let image_size =
(std::mem::size_of::<u8>() as u32 * image_width * image_height * 4) as vk::DeviceSize;
let image_data = match &image_object {
image::DynamicImage::ImageLuma8(_)
... | Rust | 0 |
import os
import nibabel as nib
import numpy as np
from medpy.metric.binary import dc, hd95
import pandas as pd
from concurrent.futures import ThreadPoolExecutor, as_completed
import argparse
def load_nii_file(filepath):
"""加载 .nii.gz 文件并返回 numpy 数组"""
nii_img = nib.load(filepath, mmap=True)
return nii_img... | Python | 1 |
# Copyright 2024 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 |
는 C++에서 class내에 Method선언부라고 보면 된다. -> implementation
// leetcode에서 rust 답안 제출시 주어지는 template
use std::collections::HashMap; // HashMap 자료구조를 활용하기 위해 선언
impl Solution {
// 채점시 입력으로 들어오는 데이터는 vector형태로 들어옴, i32는 int 32bit의 약자
pub fn two_sum(nums: Vec<i32>, target: i32) -> Vec<i32> {
let mut solv : Vec<i... | Rust | 0 |
stom_ids : `None | tuple<RegexMatcher>`
Regex custom ids.
Raises
------
ValueError
A string or regex pattern is not satisfied.
"""
# Build
string_custom_ids = None
regex_custom_ids = None
for custom_id in custom_ids:
if isinstance(custom_id, str):
... | Python | 1 |
_total.increment();
match self {
Proposal::Put(_, _, _, monitored) => {
monitored.exit(Err(track!(e)));
}
Proposal::Delete(_, _, _, monitored) => {
monitored.exit(Err(track!(e)));
}
Proposal::DeleteByPrefix(_, _, _, _, m... | Rust | 0 |
&mut self) -> i32 {
self.elements.remove(0)
}
/** Get the front element. */
fn peek(&self) -> i32 {
self.elements[0]
}
/** Returns whether the queue is empty. */
fn empty(&self) -> bool {
self.elements.is_empty()
}
}
/**
* Your MyQueue object will be instantiated ... | Rust | 0 |
mes[1] # Subtract time at step 1 to start from 0
all_results.append({
'seed': seed,
'logliks': logliks_trimmed,
'times': times_trimmed,
'method': 'sgd_baseline_long'
})
print(f" Seed {seed}: Final loglik =... | Python | 1 |
cted.into(),
)?)
}
pub async fn get_name(&self) -> Result<String, ApiError> {
let a = ITechnology::get_properties(&self.proxy).await?;
Ok(super::get_property_fromstr::<String>(
&a,
PropertyKind::Name.into(),
)?)
}
pub async fn get_type(&self) -> ... | Rust | 0 |
atching=False, allow=False,
address_range=_damon.DamonRegion(123, 456))],
[['target matching 1', 'reject target 1'],
_damon.DamosFilter(
filter_type='target', matching=True, allow=False,
damon_target_idx='1')],
... | Python | 1 |
"""Spawn multiple `ParticipantABC`s in a single process"""
import json
import logging
import time
from typing import Optional
import xaynet_sdk
LOG = logging.getLogger(__name__)
class Participant(xaynet_sdk.ParticipantABC):
def __init__(self, p_id: int, model: list) -> None:
self.p_id = p_id
se... | Python | 1 |
to {} targets", p.id, targets.len());
let mut particle = p;
particle.data = data;
targets
.into_iter()
.map(|target| ActorEvent::Forward {
particle: particle.clone(),
... | Rust | 0 |
oc = " \\see vxScaleImageNode"]
#[doc = " \\see VX_KERNEL_SCALE_IMAGE"]
#[doc = " \\see vxuWarpAffine"]
#[doc = " \\see vxWarpAffineNode"]
#[doc = " \\see VX_KERNEL_WARP_AFFINE"]
#[doc = " \\see vxuWarpPerspective"]
#[doc = " \\see vxWarpPerspectiveNode"]
#[doc = " \\see VX_KERNEL_WARP_PERSPECTIVE"]
#[doc = " \\ingroup... | Rust | 0 |
{Affine, BezPath, Line, Point, Rect, RoundedRect, Size, Vec2};
use crate::{
Color, Error, FontFamily, ImageFormat, InterpolationMode, RenderContext, Text, TextAttribute,
TextLayout, TextLayoutBuilder,
};
const BLUE: Color = Color::rgb8(0x00, 0x00, 0x80);
const GREEN: Color = Color::rgb8(0x00, 0x80, 0x00);
cons... | Rust | 0 |
}
}
true
}
// [和了牌判定]
// 和了牌のリストを返却
// 聴牌していない場合は空のリストを返却
// 通常形
pub fn calc_tiles_to_normal_win(hand: &TileTable) -> Vec<Tile> {
let (mods, cnts) = calc_mods_cnts(hand);
let mut res = vec![];
if cnts[1] == 0 && cnts[2] == 2 {
// 雀頭候補が別種の牌(2つ)ある場合
let mut ti_mod2 = vec![];
... | Rust | 0 |
;
let mut bytes = vec![0u8; (desc.Width * desc.Height * bytes_per_pixel) as usize];
for row in 0..desc.Height {
let data_begin = (row * (desc.Width * bytes_per_pixel)) as usize;
let data_end = ((row + 1) * (desc.Width * bytes_per_pixel)) as usize;
... | Rust | 0 |
before } => data::entry::Header::OfsDelta {
base_distance: index_to_pack(nth_before),
},
}
}
}
pub mod parser;
#[cfg(test)]
mod tests;
use crate::converter::parser::{Parser, ParserResult};
use crate::reporter::diagnostic::DiagnosticBuilder;
use crate::value::Value;
pub fn asti... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.