text string | label_name string | labels int64 |
|---|---|---|
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import bessel, lfilter
from scipy.io import wavfile
def plot_bessel(y, data, fs, freq=-1):
"""
Plots original and filtered signal
@param y: (1D array) filtered signal
@param data: (1D array) original signal
@param fs: sample rate... | Python | 1 |
`consume_vmo` is
//! called. If `consume_vmo` is not provided, then the VMO is just dropped.
//!
//! `init_vmo` callback is called when the first connection to the file is established and is
//! responsible for providing a VMO to be used by all the connection.
//!
//! `consume_vmo` callback, if any, is called when th... | Rust | 0 |
_RX_TOG>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _RX_TOG;
#[doc = "`read()` method returns [rx_tog::R](rx_tog::R) reader structure"]
impl crate::Readable for RX_TOG {}
#[doc = "`write(|w| ..)` method takes [rx_tog::W](rx_tog::W) writer structure"]
impl crate::Writable for RX_TOG {}
#[doc = "USB PHY Receiver ... | Rust | 0 |
true,
Some("mV"),
None,
),
Property::integer("motor_current", "Motor current", false, true, None, None),
Property::boolean("charger_connected", "Charger connected", false, true, None),
];
homie
.add_node(Node {
id: "left".to_owned()... | Rust | 0 |
trics" in insights
assert "documents" in insights
assert len(insights["documents"]) == 5
# Check document structure
for doc in insights["documents"]:
assert "id" in doc
assert "cluster" in doc
assert "cluster_label" in doc
assert "... | Python | 1 |
_gen.disable(rcc);
pub struct Random {
rng: stm32f7::random::Rng,
rcc: &'static mut stm32f7::board::rcc::Rcc,
}
impl Random {
pub fn new(
rng: &'static mut stm32f7::board::rng::Rng,
rcc: &'static mut stm32f7::board::rcc::Rcc,
) -> Random {
let random_gen = stm32f7::random::Rng:... | Rust | 0 |
# Author: Paul Kippes <kippesp@gmail.com>
import unittest
from pysqlcipher3 import dbapi2 as sqlite
class DumpTests(unittest.TestCase):
def setUp(self):
self.cx = sqlite.connect(":memory:")
self.cu = self.cx.cursor()
def tearDown(self):
self.cx.close()
def CheckTableDump(self):
... | Python | 1 |
import cv2
import numpy as np
def white_balance_using_white_patch(img, white_patch):
# 하얀 영역의 평균 BGR 값을 계산합니다.
average_white = np.mean(white_patch, axis=(0, 1))
# 이미지의 각 픽셀을 흰색 영역의 평균으로 나누어 정규화합니다.
scaling_factors = 255 / average_white
img_balanced = img * scaling_factors[np.newaxis, np.newaxis, :... | Python | 1 |
class Solution:
def minimumRecolors(self, blocks: str, k: int) -> int:
countB = 0
maxCountB = 0
for i, block in enumerate(blocks):
if block == 'B':
countB += 1
if i >= k and blocks[i - k] == 'B':
countB -= 1
maxCountB = max(maxCountB, countB)
return k - maxCountB
| Python | 1 |
minimum_validator_count: 1,
invulnerables: initial_authorities.iter().map(|x| x.controller_account_id()).collect(),
slash_reward_fraction: sp_runtime::Perbill::from_percent(0), // nothing, since we're not using this at all.
stakers,
..Default::default()
... | Rust | 0 |
"""
Set 也是很常用的。 这里也学习一下for 和 if在一块的时候的语法。
"""
class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
num = set(nums)
result = [i for i in range(1,len(nums)+1) if i not in num]
retu... | Python | 1 |
/ π/8
pub const FRAC_PI_8: TwoFloat = TwoFloat {
hi: hexf64!("0x1.921fb54442d18p-2"),
lo: hexf64!("0x1.1a62633145c07p-56"),
};
/// ln(2)
pub const LN_2: TwoFloat = TwoFloat {
hi: hexf64!("0x1.62e42fefa39efp-1"),
lo: hexf64!("0x1.abc9e3b39803fp-56"),
};
/// ln(10)
pub const LN_10: TwoFloat = TwoFloat {... | Rust | 0 |
get(url)
name = '_'.join([media[id]['query'], url.split('/')[-1]])
# Need to bypass security check to write image with mimetype image/svg+xml
# ok because svgs come from whitelisted origin
context = {'binary_field_real_user': request.env['res.users'].sudo().browse([SUPERU... | Python | 1 |
data: Box::new(asset_data),
}],
})
}
}
<reponame>leejw51/RustSmallNetwork
struct Server {
version: String,
}//! Code generation for FerrumFIX.
#![deny(missing_debug_implementations, clippy::useless_conversion)]
use darling::{FromDeriveInput, FromField};
use proc_macro::TokenStream;
use p... | Rust | 0 |
# Copyright (C) 2020 Alfiananda P.A
#
# Licensed under the General Public License, Version 3.0;
# you may not use this file except in compliance with the License.
#
# Modified by Apis
import os
import numpy as np
from hachoir.metadata import extractMetadata
from hachoir.parser import createParser
from PIL import Imag... | Python | 1 |
# Copyright 2020 Camptocamp SA (http://www.camptocamp.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import uuid
from psycopg2 import sql
from odoo.addons.component.core import Component
class SavepointBuilder(Component):
"""Return a new Savepoint instance"""
_name = "shopfloor.s... | Python | 1 |
x.is_file(), f"{x} file not found"
check_requirements("pycocotools>=2.0.6" if self.is_coco else "lvis>=0.5.3")
if self.is_coco:
from pycocotools.coco import COCO # noqa
from pycocotools.cocoeval import COCOeval # noqa
anno = ... | Python | 1 |
ield(choices=[(1, '有效'), (0, '无效')], default=1, verbose_name='状态 0删除 1有效')),
('addTime', models.DateTimeField(auto_now_add=True, db_column='addTime', verbose_name='创建时间')),
('modTime', models.DateTimeField(auto_now=True, db_column='modTime', verbose_name='修改时间')),
('stati... | Python | 1 |
n new(cart: &'a mut Cartridge) -> Self {
Self {
cartridge: cart,
io_ie: 0,
io_if: 0,
high_ram: Ram::new(HIGH_RAM_START, HIGH_RAM_SIZE),
joypad: Joypad::new(),
lcd: Lcd::new(),
serial: Serial::new(),
sound: Sound::def... | Rust | 0 |
"""
pygments.lexers.rell
~~~~~~~~~~~~~~~~~~~~
Lexers for the Rell language.
:copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.lexer import RegexLexer, bygroups, default, words
from pygments.token import Comment, Keyword, N... | Python | 1 |
result), 1)
# file_data = result[0]
# block_data = file_data["block_data"]["converter_init"]
# # Check EQUIVALENCE in block data
# lookup_block = block_data["common_blocks"]["lookup_data"]
# self.assertIn("equivalence_relationships", lookup_block)
# self.assertGr... | Python | 1 |
# Read the input data
string_A = input("Enter the string A: ") # Prompt the user to enter string A and store it in the variable string_A
substring_B = input("Enter the substring B: ") # Prompt the user to enter substring B and store it in the variable substring_B
# Find all positions of the substring B in string A
p... | Python | 1 |
F89](https://docs.rs/fixed/latest/fixed/types/type.I39F89.html) constants.
macro_rules! I39F89 { ($($a:tt)+) => { ::fixed_macro::fixed!($($a)+: I39F89) } }
#[macro_export]
/// Macro to create [I38F90](https://docs.rs/fixed/latest/fixed/types/type.I38F90.html) constants.
macro_rules! I38F90 { ($($a:tt)+) => { ::fixed_ma... | Rust | 0 |
12;
/// Pin 33 (common)
pub type P33 = EMC_07;
enum QuadraticSolution {
NoSolution,
OneSolition(f64),
TwoSolutions(f64, f64),
}
fn solve_quadratic_equation(a: f64, b: f64, c: f64) -> QuadraticSolution {
let discriminant = b * b - 4.0 * a * c;
match discriminant {
x if x < 0.0 => QuadraticSo... | Rust | 0 |
pe(N, out_h, out_w, C, filter_h, filter_w)
tmp2 = np.transpose(tmp1, axes=(0, 3, 4, 5, 1, 2))
a = fill(filter_h, filter_w, stride, out_h, out_w, pad, tmp2, H, W, N, C)
return a
@nb.jit(nopython=True)
def fill(filter_h, filter_w, stride, out_h, out_w, pad, tmp2, H, W, N, C):
img = np.zeros((N, C, H + 2*... | Python | 1 |
ommendation(self, difficulty: float) -> str:
"""Get recommendation for handoff approach"""
if difficulty >= 80:
return "Use HIGH COMPLEXITY package with extensive context preservation"
elif difficulty >= 60:
return "Use FULL PROJECT package with comprehensive context"
... | Python | 1 |
inner");
// if_void_code:print_esc("ifvoid");
else if chr_code == code::if_void_code as chr_code_repr {
print_esc($globals, crate::strpool_str!("ifvoid"));
}
// if_hbox_code:print_esc("ifhbox");
// if_vbox_code:print_esc("ifvbox");
// ifx_code:print_esc("ifx")... | Rust | 0 |
();
return;
}
let (send, recv) = mpsc::channel();
self.vanilla_chan = Some(recv);
let progress_info = self.vanilla_progress.clone();
thread::spawn(move || {
let client = reqwest::blocking::Client::new();
let res = client.get(VANILLA_CLIENT_URL... | Rust | 0 |
) module"]
pub type CANBTR0 = crate::Reg<u8, _CANBTR0>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CANBTR0;
#[doc = "`read()` method returns [canbtr0::R](canbtr0::R) reader structure"]
impl crate::Readable for CANBTR0 {}
#[doc = "`write(|w| ..)` method takes [canbtr0::W](canbtr0::W) writer structure"]
impl crate... | Rust | 0 |
s.build_token("files/program6.txt");
assert_eq!(s.next_symbol().token, Token::Program);
assert_eq!(s.next_symbol().token, Token::LitStr("teste".to_string()));
assert_eq!(s.next_symbol().token, Token::Semicolon);
assert_eq!(s.next_symbol().token, Token::Var);
assert_eq!(s.next_symbol().token, Token::LitStr(... | Rust | 0 |
alidGid(gid))
} else {
Ok(Group::Id((*group).gr_gid))
};
};
}
/// Lookup group by given group name.
pub fn by_name(groupname: &str) -> Result<Group, DaemonizrError> {
let cs = match CString::new(groupname) {
Err(_) => return Err(DaemonizrE... | Rust | 0 |
rt_display_snapshot};
#[test]
fn size() {
use std::mem::size_of;
assert_debug_snapshot!(size_of::<Config>(), @"456");
assert_debug_snapshot!(size_of::<Src>(), @"184");
assert_debug_snapshot!(size_of::<translation_api_cn::baidu::User>(), @"96");
}
// 需要指定 api,但是这个测试仅仅用作例子。
#[test]
#[should_panic]
fn tr... | Rust | 0 |
"""
CEASIOMpy: Conceptual Aircraft Design Software
Developed for CFS ENGINEERING, 1015 Lausanne, Switzerland
Functions utils to run ceasiompy workflows
| Author : Leon Deligny
| Creation: 21 March 2025
"""
# =================================================================================================
# IMPORT... | Python | 1 |
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
SECRET_KEY: str = "mysecretkey" # Always set in production!
DEBUG: bool = False
MODEL: str = "ollama_chat/phi3"
SUMMARIZE_MODEL: str = "ollama_chat/phi3"
OPENAI_API_KEY: str = ""
DATABASE_URI: str = "sqlite+aiosqlite:///... | Python | 1 |
CT,
fence: ID3D12Fence,
fence_event: HANDLE,
fence_value: u64,
// Resources
vertex_buffer: ID3D12Resource,
vertex_buffer_view: D3D12_VERTEX_BUFFER_VIEW,
indices_buffer: ID3D12Resource,
indices_buffer_view: D3D12_INDEX_BUFFER_VIEW,
instance_buffer: ID3D12Resource,
frame_resou... | Rust | 0 |
ow is None, reason="Mlflow not available")
def test_get_callbacks__mlflow_user_config(tmp_path: Path) -> None:
loggers = logger_helpers.get_loggers(
logger_args=LoggerArgs(
jsonl=None,
mlflow=MLFlowLoggerArgs(experiment_name="abc"),
tensorboard=None,
wandb=Non... | Python | 1 |
IC_UNICODE[39]`: `U+0027` `"\'"`
///
/// ```text
/// ░██░░░░░
/// ░██░░░░░
/// ██░░░░░░
/// ░░░░░░░░
/// ░░░░░░░░
/// ░░░░░░░░
/// ░░░░░░░░
/// ░░░░░░░░
/// ```
///
/// ## `BASIC_UNICODE[40]`: `U+0028` `"("`
///
/// ```text
/// ░░░██░░░
/// ░░██░░░░
/// ░██░░░░░
/// ░██░░░░░
/// ░██░░░░░
/// ░░██░░░░
/// ░░░██░░░
/// ░... | Rust | 0 |
opy, Clone, Debug)]
#[repr(C)]
pub struct xcb_input_device_class_data_t__key {
pub num_keys: u16,
pub keys: *mut u32,
}
impl Default for xcb_input_device_class_data_t__key {
fn default() -> Self {
unsafe { std::mem::MaybeUninit::zeroed().assume_init() }
}
}
/// The type of [`xcb_input_device_c... | Rust | 0 |
_open(path: impl AsRef<Path>) -> io::Result<Box<dyn io::Read>> {
File::open(path).map(|x| Box::new(x) as _)
}
fn read_file_filtered(file: impl io::Read) -> io::Result<Vec<String>> {
let mut out = vec![];
for line in BufReader::new(file).lines() {
let line = line?;
// Must be flush against ... | Rust | 0 |
tan() {
let mut env = ag::VariableEnvironment::new();
let rng = ag::ndarray_ext::ArrayRng::<f64>::default();
let v = env.slot().set(rng.random_uniform(&[3], 0., 0.2));
env.run(|graph| {
let v = graph.variable(v);
let z = T::tan(v);
let g = T::grad(&[z], &[v]);
ag::test_he... | Rust | 0 |
FolderPath, subPath)
# 子文件夹创建
if not os.path.exists(toSubFolderPath):
os.makedirs(toSubFolderPath)
# 某文件出错不影响其他文件打印
try:
wb = excel.Workbooks.Open(fromFilePath)
count = wb.Worksheets.Count
insertLog("此 Excel ... | Python | 1 |
shot::ResultsPage;
use dropshot::WhichPage;
use hyper::Uri;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use std::collections::BTreeMap;
use std::net::Ipv4Addr;
use std::net::SocketAddr;
use std::ops::Bound;
use std::sync::Arc;
#[macro_use]
extern crate slog;
/**
* Item returned by our pag... | Rust | 0 |
_none()
|| self.lcl_dt_high.is_none()
{
let blow_up_anal = blow_up(self.sounding(), Some(15.0)).ok();
let (starting_pcl, dt_el, height_el, lcl_dt) = blow_up_anal
.map(|bu_anal| {
(
Some(bu_anal.starting_parcel),
... | Rust | 0 |
are less likely to enjoy using the tool.
")]
level: u32,
#[structopt(long = "mem", default_value = "32",
help = "Amount of memory to use in mebibytes (MiB).")]
mem: u32,
#[structopt(long = "threads", default_value = "2",
help = "\
Number of threa... | Rust | 0 |
)) + (a(1, 3) * b(3, 2)),
(a(1, 0) * b(0, 3)) + (a(1, 1) * b(1, 3)) + (a(1, 2) * b(2, 3)) + (a(1, 3) * b(3, 3)),
(a(2, 0) * b(0, 0)) + (a(2, 1) * b(1, 0)) + (a(2, 2) * b(2, 0)) + (a(2, 3) * b(3, 0)),
(a(2, 0) * b(0, 1)) + (a(2, 1) * b(1, 1)) + (a(2, 2) * b(2, 1)) + (a(2, 3) * b(3, 1)),
(a(2, 0) * b(0, 2)) +... | Rust | 0 |
rd_x_ori: batch_grd_ori, utms_x:batch_utm,
learning_rate: learning_rate_val}
if iter % 20 == 0:
_, loss_val = sess.run([train_step, localization_loss], feed_dict=feed_dict)
print('global %d, epoch %d, iter %d: loss : %.4f' %
... | Python | 1 |
rary(g).into())
}
}
fn random_identifier() -> String {
rand::thread_rng()
.sample_iter(&rand::distributions::Alphanumeric)
.take(32)
.map(char::from)
.collect()
}
pub struct EnrollHandler;
#[ockam_core::worker]
impl Worker for En... | Rust | 0 |
fn print_pokemon_list() {
for poki in POKEDEX {
// This strange formatter will print the pokemon ID with three digits,
// filling in 0 from the left if necessary (#003).
println!("#{:0>3} {}", poki.id, poki.name);
}
}
/// Fetches a Pokemon model from the Pokedex specified by its name.... | Rust | 0 |
method="post",
url="https://accounts.douban.com/j/app/login/request_phone_code",
params={
"timezone": "Asia/Shanghai"
},
headers={
"user-agent": "api-client/1 com.douban.frodo/7.0.1(204) Android/28 product/22127RK46C vendor/Redmi mo... | Python | 1 |
that is —amongst many things— used to compile
/// the Wasm bytes into a valid module artifact), in addition to the
/// [`Tunables`] (that are used to create the memories, tables and globals).
///
/// Spec: <https://webassembly.github.io/spec/core/exec/runtime.html#store>
#[derive(Clone)]
pub struct Store;
impl Store {... | Rust | 0 |
results)
target = np.array([5., 5., 25., 5., 25., 10., 5., 10.])
assert len(output['gt_masks']) == 1
assert len(output['gt_masks_ignore']) == 0
assert np.allclose(output['gt_masks'].masks[0][0], target)
assert output['img'].shape == (15, 30, 3)
# test __call__ with blank instace_key masks
m... | Python | 1 |
1) != 0 {
Ok((x + 1) / 2)
} else {
Ok(-x / 2)
}
}
pub fn signed_code(x: i32, stream: &mut impl bits::BitsWriter, pot: u32) -> io::Result<()> {
unsigned_code(x.abs() as u32, stream, pot)?;
if x != 0 {
stream.put_bits(if x > 0 { 1 } else { 0 }, 1)?;
}
Ok(())
}
pub fn si... | Rust | 0 |
'a>;
fn next(&mut self) -> Option<QuadRef<'a>> {
self.inner
.next()
.map(|(s, p, o, g)| self.dataset.decode_spog((s, p, o, g)))
}
}
/// Iterator returned by [`GraphView::iter`].
pub struct GraphViewIter<'a> {
dataset: &'a Dataset,
inner: std::collections::btree_set::Ran... | Rust | 0 |
f these methods:[/bold yellow]")
console.print(
"1. Create a .env file in the current directory with: GOOGLE_API_KEY=your_key_here")
console.print(
"2. Create a .terminal_agent.env file in your home directory")
console.print(
"3. Set th... | Python | 1 |
let map = map_1_m();
{
let iter = map.iter();
let mut count = 0;
for kv in iter {
count += 1;
assert_eq!(*kv.1 as u64, *kv.0 as u64 * 10)
}
assert_eq!(1_000_000, count);
}
}
#[test]
fn test_into_iter() {
let map = map_1_m();
let vec: ... | Rust | 0 |
Kind> { fn eq(&self, other: &ErrorKind) -> bool { Some(other) == self.as_ref().err() } }
<reponame>casept/sevenz<filename>src/parser/types/property_id.rs
use core::convert::TryFrom;
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum PropertyID {
End = 0x00,
Header = 0x01,
ArchivePrope... | Rust | 0 |
ch);
true
} else {
false
}
}
/// Grabs the next characters that match the predicate, as a string
fn next_while<F: Fn(&char) -> bool>(&mut self, predicate: F) -> String {
next_while(&mut self.location, &mut self.iter, predicate)
}
}
fn next_while<F: Fn(&c... | Rust | 0 |
matzipan/gtk4-rs
// Take a look at the license at the top of the repository in the LICENSE file.
use crate::{RenderNodeType, RoundedRect};
use glib::translate::*;
define_render_node!(
InsetShadowNode,
ffi::GskInsetShadowNode,
ffi::gsk_inset_shadow_node_get_type,
RenderNodeType::InsetShadowNode
);
imp... | Rust | 0 |
This class gives data about the Uridine object, and inherits
off the base residue class.
"""
def __init__(self, atoms, ref):
"""
Initialize the class
Parameters
atoms: A list of Atom objects to be stored in this class
... | Python | 1 |
t self,
_state: &Self::State,
_archetype: &Archetype,
_tables: &Tables,
) {
}
#[inline(always)]
unsafe fn set_table(&mut self, _state: &Self::State, _table: &Table) {}
#[inline(always)]
unsafe fn archetype_fetch(&mut self, _archetype_index: usize) -> Self::Item {}
... | Rust | 0 |
, 'rce', 'execution', 'execute', 'code']):
types.append('rce')
if 'privilege_escalation' not in types and any(keyword in combined_text for keyword in ['privilege', 'escalation', 'elevation']):
types.append('privilege_escalation')
if 'access_control' not in types a... | Python | 1 |
# -*- coding: utf-8 -*-
# Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | Python | 1 |
ess_config(self, node_id: int) -> dict[str, ConfigOption]:
return self.client.get_wireless_config(self.session.id, node_id)
def get_mobility_config(self, node_id: int) -> dict[str, ConfigOption]:
config = self.client.get_mobility_config(self.session.id, node_id)
logger.debug(
"g... | Python | 1 |
#! /usr/bin/python
import core1d as fd
import numpy as np
"""
PROGRAM beodriverfd
This programme is the equivalent of BeoDriverGTK.f90.
"""
#----------------------------------------------------------------------
# Uses AEM1D_FD to compute the frequency-domain layered earth
# H field for a dipole of unit moment ... | Python | 1 |
impl Node<AudioBuffer> for Oscillator {
impl_dsp_node_get_data!(node_data)
impl_dsp_node_get_inputs!(inputs, AudioBuffer)
}
impl Oscillator {
pub fn new(settings: SoundStreamSettings) -> Oscillator {
Oscillator {
node_data: NodeData::new(settings),
inputs: Vec::new()
... | Rust | 0 |
ocs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cpuirqsel5](cpuirqsel5) module"]
pub type CPUIRQSEL5 = crate::Reg<u32, _CPUIRQSEL5>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CPUIRQSEL5;
#[doc = "`read()` method returns [cpuirqsel5::R](cpuirqsel5::R) reader structure"]
... | Rust | 0 |
[i] : offset[i + 1]])
for i in range(len(remote_paths))
]
return buffers
def _get_remote_bytes_parquet(
remote_paths,
fs,
*,
columns=None,
row_groups=None,
blocksize=_BYTES_PER_THREAD_DEFAULT,
):
if columns is None and row_groups is None:
return _get_rem... | Python | 1 |
e, None]" = slice(year, None, None)
vIIN: "slice[date, date, None]" = slice(year, year, None)
vNNI: "slice[None, None, str]" = slice(None, None, "1d")
vNII: "slice[None, date, str]" = slice(None, year, "1d")
vINI: "slice[date, None, str]" = slice(year, None, "1d")
vIII: "slice[date, date, str]" = slice(year, year, "1d"... | Python | 1 |
),
A, // 1
NS, // 2
CNAME, // 5
MX, // 15
AAAA, // 28
}
impl QueryType {
pub fn to_num(&self) -> u16 {
match *self {
QueryType::UNKNOWN(x) => x,
QueryType::A => 1,
QueryType::NS => 2,
QueryType::CNAME => 5,
QueryType... | Rust | 0 |
----
items : list, optional
dictionaries with keys 'label' and 'value'. Label will be used to show
it to user and value will be used for selection.
label : str, optional
label for the switcher.
initial_selection : int, optional
index of the selected item initially.
on_pre... | Python | 1 |
03 - 05).sunday_based_week(), 9);
assert_eq!(date!(2024 - 03 - 06).sunday_based_week(), 9);
assert_eq!(date!(2024 - 03 - 07).sunday_based_week(), 9);
}
#[test]
fn from_iso_week_date() {
use Weekday::*;
assert!(Date::from_iso_week_date(2019, 1, Monday).is_ok());
assert!(Date::from_iso_week_date(201... | Rust | 0 |
l.decode_text,
**tokens_to_logits_kwargs,
)
assert method in ['greedy', 'beam']
decode_fn = greedy_decode if method == 'greedy' else beam_search
kwargs = {}
if method == 'beam':
kwargs['beam_size'] = beam_size
kwargs['alpha'] = brevity_penalty_alpha
text_tokens, _ = decode_fn(
begin_toke... | Python | 1 |
#coding:utf8
import torch
import torch.nn as nn
import numpy as np
import math
import random
import os
import re
import matplotlib.pyplot as plt
"""
基于pytorch的rnn语言模型
"""
class LanguageModel(nn.Module):
def __init__(self, input_dim, vocab):
super(LanguageModel, self).__init__()
self.embedding = n... | Python | 1 |
:cfg.ACTIVE_TRAIN.PRE_TRAIN_SAMPLE_NUMS]
unlabelled_set.infos = infos[cfg.ACTIVE_TRAIN.PRE_TRAIN_SAMPLE_NUMS:]
for info in labelled_set.infos:
labelled_set.frame_ids.append(info["frame_id"])
for info in unlabelled_set.infos:
unlabelled_set.frame_ids.a... | Python | 1 |
import core
import logging
logging = logging.getLogger(__name__)
def add(data, type_='success'):
''' Adds notification to core.NOTIFICATIONS
data (dict): notification information
type_ (str): style of notification, see javascript docs for available styles <optional - default 'success'>
Merges sup... | Python | 1 |
fn from_stack_entry(entry: StackEntry) -> Self;
}
macro_rules! impl_from_stack_entry_integer {
($($t:ty),* $(,)?) => {
$(
impl FromStackEntry for $t {
fn from_stack_entry(entry: StackEntry) -> Self {
entry.to_bits() as _
}
}
impl From<$t> for StackEntry {
fn from(value: $t) -> Self {
... | Rust | 0 |
"""
Write a function to count the pairs of reverse strings in the given string list. https://www.geeksforgeeks.org/python-program-to-count-the-pairs-of-reverse-strings/
assert count_reverse_pairs(["julia", "best", "tseb", "for", "ailuj"])== 2
"""
from collections import defaultdict
def count_reverse_pairs(strings):
... | Python | 1 |
tribution by type
print("\n6️⃣ Entity Distribution by Type")
print("-" * 30)
distribution_query = """
MATCH (e:Entity)
RETURN e.type as entity_type, count(e) as count
ORDER BY count DESC
"""
results = session.run(distribution_query)
for re... | Python | 1 |
index.
fn synchronize<'a>(&'a self, destination_index: usize) -> Result {
let source_index = self.synch_map.latest() as usize;
assert_ne!(source_index, TensorMap::CAPACITY);
// We need to borrow two different Vec elements: `src` and `mut dst`.
// Borrowck doesn't allow to do it in ... | Rust | 0 |
R,
_reserved14: [u8; 440usize],
#[doc = "0x4c4 - Two-wire error source. Write error field to 1 to clear error."]
pub errorsrc: ERRORSRC,
_reserved15: [u8; 56usize],
#[doc = "0x500 - Enable two-wire master."]
pub enable: ENABLE,
_reserved16: [u8; 4usize],
#[doc = "0x508 - Pin select for S... | Rust | 0 |
ETE, HELP, LICENSE, APPLICATIONMODE, EXIT, REPORTFORMONTH, REMOVETIME)
}
pub fn delete(mut args: Iter<String>, to_do: &mut ToDo) -> Result<String, String> {
if 0 == to_do.count() { return Err(warn(no_tasks_recorderd_message())); }
let task_name = match args.nth(0) {
Some(task) => { task.clone() },
... | Rust | 0 |
) => write!(f, "Bind({}, {})", t, expr),
Expr::FieldAccess(name, expr) => write!(f, "FieldAccess({}, {})", name, expr),
Expr::TupleFieldAccess(index, expr) => {
write!(f, "TupleFieldAccess({}, {})", index, expr)
}
Expr::Formatter(fmt, items) => write!(f, "... | Rust | 0 |
ams["reward_amount_list"]:
ctr += 1
indices = np.where(y_expected_rew_amount == reward)
plt.plot(
np.mean(y_expected_neuron[:, indices], axis=2).T,
color=params["color_list"][ctr],
lw=0.7,
)
plt.plot(
... | Python | 1 |
und::Pred(pred) => self.pred.push(pred),
Bound::Default(_) => self.can_extend = true,
}
}
fn child(&mut self, bounds: Option<Vec<Bound>>) -> BoundsChild {
let bounds = if self.can_extend {
Self::from_data(bounds)
} else {
Self::new(false)
};
... | Rust | 0 |
import pickle
import numpy as np
import scipy.stats as st
import matplotlib as mpl
from matplotlib import pyplot as plt
import matplotlib.colors as colors
mpl.font_manager._rebuild()
plt.rc('font', family='Raleway')
def truncate_colormap(cmapIn='jet', minval=0.0, maxval=1.0, n=100):
cmapIn = plt.get_cmap(cmapI... | Python | 1 |
12() {
let mut vargen = VarGen::new();
let id1 = vargen.fresh();
let id2 = vargen.fresh();
let id3 = vargen.fresh();
let id4 = vargen.fresh();
let provable = solve_icnf(
&vargen,
&Icnf {
ant: ClauseSet {
vec: vec... | Rust | 0 |
gs:
a: Input binary image.
H: Target height.
W: Target width.
Returns:
Resized binary image (H, W).
"""
h, w = a.shape
r_idx = (np.linspace(0, h - 1, H)).astype(int)
c_idx = (np.linspace(0, w - 1, W)).astype(int)
return a[r_idx][:, c_idx].astype(np.uint8)
def m... | Python | 1 |
#Faça um programa que leia uma frase e depois exiba na tela:
# A frase em minúsculas, a frase em maiúsculas, a quantidade de caracteres na frase e quantas letras tem a 2ª palavra na frase.
import os
os.system('cls')
print('-' * 90)
print('ALTERAÇÔES POR FRASES.')
print('=' * 90)
frase = str(input('ENTRE COM A FRAS... | Python | 1 |
#!/usr/bin/env python3
import sys
import signal
from scapy.all import AsyncSniffer, conf
from influxdb_client import InfluxDBClient
from collector import *
INFLUX_URL = "http://192.168.201.1:8086"
INFLUX_TOKEN = "0fO0ojKAANp-7aEehJHRDWEKE-cSNoIEHY2aK8dd1KI0VWpmO1GAsMJhRh_B1U8bXDIaozHMDVv1yEkCPm230w=="
INFLUX_ORG = "re... | Python | 1 |
# Problem: Sort The Students By Their Kth Score - https://leetcode.com/problems/sort-the-students-by-their-kth-score/
class Solution:
def sortTheStudents(self, score: List[List[int]], k: int) -> List[List[int]]:
# for i in range(len(score)):
# for j in range(len(score)-1):
... | Python | 1 |
lyoExerciseName::WeightedAlternatingJumpLunge => 1,
PlyoExerciseName::BarbellJumpSquat => 2,
PlyoExerciseName::BodyWeightJumpSquat => 3,
PlyoExerciseName::WeightedJumpSquat => 4,
PlyoExerciseName::CrossKneeStrike => 5,
PlyoExerciseName::WeightedCrossKneeStrike... | Rust | 0 |
async fn get_csv_data_route<D>(
pool: web::Data<DbPool>,
id: web::Path<Id>,
info: web::Query<Info>,
) -> Result<impl Responder, Error>
where
D: 'static + TrailerData + Serialize + Send,
{
get_data::<D>(pool, id, info, true).await
}
pub async fn get_json_data_route<D>(
pool: web::Data<DbPool>,
... | Rust | 0 |
# -*- coding: utf-8 -*-
import os
import random
from collections import OrderedDict
from datetime import datetime
import numpy as np
import torch
class AvgMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.coun... | Python | 1 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
# Step 1: Create the dataset using Pandas
data = {
'Bedrooms': [1, 1, 2, 2, 3, 3],
'Price': [80000, 90000, 100000, 90000, 100000, 90000]
}
# Create a DataFrame
df = pd.DataFrame(data)
# St... | Python | 1 |
comingLen: ArrayLength<u8>,
{
/// Attempt to split the `static` buffer into handles for Interrupt and App context
///
/// This function will only succeed once. If the underlying buffers have also
/// been split directly, this function will also fail.
///
/// Upon splitting, the Radio will be ini... | Rust | 0 |
import time
# Basic toggle pattern. Alternates between channels 1+2 and 3+4 every 500ms.
# Doesn't change frequency or pulse width, so defaults will be used - currently
# 150 hz and 150 us
class toggle:
def __init__(self, ble):
self.toggle_time_ms = 500
self.ble = ble
self.c12on = False
... | Python | 1 |
n((42_i32, 3.1415_f32));
let subworld = SubWorldRef::<(&i32, &f32)>::new(&world);
let val = subworld.try_get::<u64>(entity).unwrap();
assert_eq!(*val, 42);
}
#[test]
fn commandbuffer() {
let mut world = World::default();
let e = world.reserve_entity();
let mut cmds = CommandBuffer::default()... | Rust | 0 |
the truncated principal square root of `self` --
/// see [Roots::sqrt](https://docs.rs/num-integer/0.1/num_integer/trait.Roots.html#method.sqrt).
pub fn sqrt(&self) -> Self {
Roots::sqrt(self)
}
/// Returns the truncated principal cube root of `self` --
/// see [Roots::cbrt](https://docs.r... | Rust | 0 |
cept Exception as e_wandb_finish:
logger.error(f"Error during W&B final logging/finish: {e_wandb_finish}")
if __name__ == '__main__':
# This block allows direct execution of the script for testing purposes.
logger.info("--- Direct execution of report_generator.py for testing ---")
# Pr... | Python | 1 |
cur_image_np = image_np[i, :, :, ::-1]
original_resolution = cur_image_np.shape[0:2]
if self.face_helper is None:
return image
self.face_helper.clean_all()
self.face_helper.read_image(cur_image_np)
self.face_helper.get_face_land... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.