text string | label_name string | labels int64 |
|---|---|---|
'''
Update the config-to-payload map table for the fast DAQ O2O.
@author: hqu
'''
from CondTools.SiStrip.o2o_db_manager import make_dbtype, DbManager
import os
import logging
import sqlalchemy
class ConfigToPayloadMapDef(object):
__tablename__ = 'STRIP_CONFIG_TO_PAYLOAD_MAP'
config_hash = sqlalchemy.Column(... | Python | 1 |
iv - 2) * ntheta_subdiv,
coords.len() as u32 - 1,
ntheta_subdiv,
&mut idx);
let mut res = TriMesh::new(coords, Some(normals), None, Some(IndexBuffer::Unified(idx)));
let _0_5: N ... | Rust | 0 |
lder
.const_i32(global_pointers::get_reg_xmm_offset(r1) as i32 + 8);
ctx.builder.load_aligned_i64(0);
ctx.builder.store_aligned_i64(0);
}
pub fn instr_660F12_mem_jit(ctx: &mut JitContext, modrm_byte: ModrmByte, r: u32) {
ctx.builder
.const_i32(global_pointers::get_reg_xmm_offset(r) as i32);
... | Rust | 0 |
pend': base_spend,
'impressions': impressions,
'predicted': max(0, predicted) # Ensure non-negative
})
return pd.DataFrame(data_list)
def example_overall_curve():
"""Example 1: Fit overall (aggregated) response curve."""
print("=" * 80)
print("EXAMPLE ... | Python | 1 |
`frunk` crate with extra functionallity to allow transmogrification
//! between enums with similar structures.
//!
//! This crate specifically defines the data structures used in the generic representation of an
//! enum, the `frunk-enum-derive` crate adds a proc-macro to auto-generate the per-type code needed
//! to ... | Rust | 0 |
OR_DUTY_CYCLING_ENABLED: DWORD = 1;
DEFINE_GUID! {GUID_PROCESSOR_IDLE_ALLOW_SCALING,
0x6c2993b0, 0x8f48, 0x481f, 0xbc, 0xc6, 0x0, 0xdd, 0x27, 0x42, 0xaa, 0x6}
DEFINE_GUID! {GUID_PROCESSOR_IDLE_DISABLE,
0x5d76a2ca, 0xe8c0, 0x402f, 0xa1, 0x33, 0x21, 0x58, 0x49, 0x2d, 0x58, 0xad}
DEFINE_GUID! {GUID_PROCESSOR_IDLE_STATE_MA... | Rust | 0 |
"Core exceptions raised by the Redis client"
from redis._compat import unicode
class RedisError(Exception):
pass
# python 2.5 doesn't implement Exception.__unicode__. Add it here to all
# our exception types
if not hasattr(RedisError, '__unicode__'):
def __unicode__(self):
if isinstance(self.args[0]... | Python | 1 |
"""
Mixins that will be used for models with common characteristics.
"""
import uuid
from django.db import models
class TimeStampable(models.Model):
"""
Base abstract timestamp model.
This mixin is intended to be inherited by all models as it provides the
characteristics for when a model is created... | Python | 1 |
p = lllite_name.find("transformer_blocks")
if p >= 0:
tf_index = int(lllite_name[p:].split("_")[2])
if tf_index > TRANSFORMER_MAX_BLOCK_INDEX:
continue... | Python | 1 |
let mut near=section.note_num as i32-tones.unwrap()[0] as i32;
for tone in tones.unwrap(){
let tone=match section.note_num{
24..=35=>tone+12*0,
36..=47=>tone+12*1,
48..=59=>tone+12*2,
60..=71=>tone+1... | Rust | 0 |
]
self.serial.stopbits = self.serial.STOPBITS[self.choice_stopbits.GetSelection()]
self.serial.parity = self.serial.PARITIES[self.choice_parity.GetSelection()]
if self.show & SHOW_FLOW:
self.serial.rtscts = self.checkbox_rtscts.GetValue()
self.serial.xonxoff ... | Python | 1 |
info!("{}: event_len; Response: {}", env.id, size);
size as u32
})
.unwrap_or(0)
}
/// Print debug message to logs. Returns 0 on success or error code.
fn debug_log(env: &XEnv, cmd_ptr: WasmPtr<u8, Array>, cmd_len: u32) -> i32 {
env.memory_ref()
.ok_or(ErrorCode::Un... | Rust | 0 |
bytes)
#[inline]
pub fn encrypt_blocks_mut(&mut self, blocks: &mut [Block<C>]) {
self.encrypt_blocks_inout_mut(blocks.into());
}
/// Pad input and encrypt. Returns resulting ciphertext slice.
///
/// # Errors
///
/// Returns [`PadError`] if length of output buffer is not sufficient.
///
/// # ... | Rust | 0 |
of which may be
/// exchanged (including over the network) to load balance the processing of
/// this snapshot. These splits are usable by anyone with access to the
/// shard's [crate::PersistLocation]. The `len()` of the returned `Vec` is
/// `num_splits`. If a 1:1 mapping between splits and (e.g. dat... | Rust | 0 |
Context, Module};
use super::utils::directory::truncate;
use crate::config::RootModuleConfig;
use crate::configs::directory::DirectoryConfig;
use crate::formatter::StringFormatter;
/// Creates a module with the current logical or physical directory
///
/// Will perform path contraction, substitution, and truncation.
... | Rust | 0 |
# Copyright (c) 2012-2025, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
from . import AWSObject, PropsDictType
from .validators import boolean
class AccountAlias(AWSObject):
"""
`AccountAlias <http://docs.aws.a... | Python | 1 |
for all possible results of SphinxError
fn from(err: SphinxError) -> Self {
use MixProcessingError::*;
SphinxProcessingError(err)
}
}
impl From<NymNodeRoutingAddressError> for MixProcessingError {
fn from(_: NymNodeRoutingAddressError) -> Self {
use MixProcessingError::*;
... | Rust | 0 |
AllocCommand::AllocatedMemory, // not sure about this one
pub num_commands_: usize,
pub num_literals_: usize,
pub last_insert_len_: usize,
pub last_flush_pos_: u64,
pub last_processed_pos_: u64,
pub dist_cache_: [i32; 16],
pub saved_dist_cache_: [i32; kNumDistanceCacheEntries],
pub last_bytes_: u16,
... | Rust | 0 |
"""
Multiple Interactions
=====================
This example shows how multiple user inputs can be layered onto a chart. The four inputs have functionality as follows:
* Dropdown: Filters the movies by genre
* Radio Buttons: Highlights certain films by Worldwide Gross
* Mouse Drag and Scroll: Zooms the x and y scales ... | Python | 1 |
# Copyright Allo authors. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
import allo
import allo.dataflow as df
from allo.ir.types import int32
from allo.memory import Layout
import numpy as np
LyA = Layout("S0S1")
LyB = Layout("S0S1")
LyC = Layout("S0S1")
def _test_cannon():
Ty = int32
M, K, N ... | Python | 1 |
item: int):
if item >= self._qubit_count:
raise IndexError(item)
return _PAULI_INDICES[self._nontrivial.get(item, "I")]
def __len__(self):
return self._qubit_count
def __repr__(self):
factors = [self._nontrivial.get(qubit, "I") for qubit in range(self._qubit_count)... | Python | 1 |
t_pixel(15, 15, OFF);
loop {
let _xmas = RED;
let thirty_millis = time::Duration::from_millis(350);
let now = time::Instant::now();
hat_hd.set_pixel(9, 1, _xmas);
hat_hd.set_pixel(6, 2, _xmas);
hat_hd.set_pixel(9, 3, _xmas);
hat_hd.set_pixel(5, 4, _xmas);
hat_hd.set_pixel(11,... | Rust | 0 |
-> Result<ServerToClientEvent> {
if self.closed {
return Err(EventsError::Closed);
}
use async_std::stream::StreamExt;
let msg: TungsteniteMessage = self
.stream
.next()
.await
.expect("Last message in ws without closing")?;
... | Rust | 0 |
, SCPH-1080
const CONTROLLER_CLASSIC: u8 = 0xc1;
/// Analog Controller, SCPH-1110 (flightstick looking thing)
const CONTROLLER_ANALOG_JOYSTICK: u8 = 0x53;
/// DualShock in Digital mode
const CONTROLLER_DUALSHOCK_DIGITAL: u8 = 0x41;
/// DualShock
const CONTROLLER_DUALSHOCK_ANALOG: u8 = 0x73;
/// DuakShock 2
const CONTRO... | Rust | 0 |
ailed::fit(&format!(
"Cannot rescale constant column {}",
i
)));
}
}
let mut scaled_x = x.clone();
scaled_x.scale_mut(&col_mean, &col_std, 0);
Ok((scaled_x, col_mean, col_std))
}
fn augment_x_and_y(x: &M, y: &M... | Rust | 0 |
fn log_u32(a: u32);
// Multiple arguments too!
#[wasm_bindgen(js_namespace = console, js_name = log)]
fn log_many(a: &str, b: &str);
}
fn bare_bones() {
log("Hello from Rust!");
log_u32(42);
log_many("Logging", "many values!");
}
macro_rules! console_log {
// Note that this is using t... | Rust | 0 |
), pyfunc(p))
# Homogeneous
check((4, 5))
# Heterogeneous
check((4, 5.5))
def test_build_unpack_call_more(self):
def check(p):
@jit
def inner(*args):
return args
pyfunc = lambda a: inner(1, *a, *(1, 2), *a)
cfu... | Python | 1 |
"Template category"""
return obj.industry
category.short_description = 'Category'
def created_by(self, obj):
"""Template creator"""
return obj.workflow.created_by if obj.workflow else None
created_by.short_description = 'Created By'
def rating_display(self, obj):
"""D... | Python | 1 |
import numpy as np
from .base import BatchAttack
from .base import generator_decorator
from .. import nprng
class SaltAndPepperNoiseAttack(BatchAttack):
"""Increases the amount of salt and pepper noise until the input is misclassified.
"""
@generator_decorator
def as_generator(self, a, epsilons=100... | Python | 1 |
#Ребята решили собраться в поход самостоятельно. Необходимо произвести проверку рюкзаков в зависимости от требования.
trebovanie = {
"Вода": 3,
"Консервы": 4,
"Макароны": 1,
"Спички": 1,
"Палатка": 1,
"Спальный мешок": 1,
"Снеки": 2
}
deti = {'Андрей': {'Вода': 3, 'Консервы': 8, 'Макароны':... | Python | 1 |
务是根据特定标准从**<回答>**的内容中抽取核心SELFIES信息。\n\n抽取流程:\n答案分析:对于**<回答>**中选择题的回答文本,你需要抽取出当前文本中的被认为是答案的SELFIES分子式部分。注意,这些文本中有可能存在多个不同的SELFIES分子式,你需要全部抽出来并在SELFIES之间使用“;”进行隔开;而对于内容含糊不清没有明确表明具体SELFIES分子式的文本,就将<最终结果>设置为“None”。\n另外,你要注意忽略文体、语法或标点的差异。并且你的判断应完全基于所提供的回答,避免引入任何主观思考。输出要求:\n在**<抽取结果>**部分,直接给出你认为的答案,一定不要输出额外的解释说明。\n\n示例:\n\n<... | Python | 1 |
# Copyright 2022 PAL Authors. 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 applicable law or ... | Python | 1 |
[Perbill::from_percent(100)],
// // 1,
// // );
//
// // // or non-zero.
// // assert_eq!(Staking::force_era(), Forcing::NotForcing);
// // assert!(<Validators<Test>>::contains_key(11));
// // assert_ledger_consistent(11);
// // });
// // }
//
// // #[test]
// // fn reporters_receive_their_slice() {
// //... | Rust | 0 |
_next_summary_time(now)
while running:
now = datetime.now(tz)
for alert in crypto_alerts:
symbol = alert["symbol"]
current_price = get_crypto_price(symbol)
current_krw = get_upbit_price(symbol)
if current_price is None:
continue
... | Python | 1 |
from .. import networks
const = lambda x: x
def get_network(name):
if name in NETWORKS:
return NETWORKS[name]
else:
return NETWORKS["elementsregtest"]
NETWORKS = {
"liquidv1": {
"name": "Liquid",
"wif": b"\x80",
"p2pkh": b"\x00",
"p2sh": b"\x27",
... | Python | 1 |
# Split (str -> list)
my_string = "python is a good language and we are doing DSA"
words = my_string.split()
print(words)
print(len(words))
| Python | 1 |
ength = MaximumBlockLength;
type AvailableBlockRatio = AvailableBlockRatio;
type Version = ();
type ModuleToIndex = ();
type AccountData = ();
type OnNewAccount = ();
type OnKilledAccount = ();
}
impl Trait for Test {
type Event = ();
type CoinPrice = RandomPrice;
type ExpirationPeriod = Expiration... | Rust | 0 |
from typing import Optional
import uuid
from sqlmodel import Field, Relationship
from Domain.Entities.Base.base_entity import Base_Entity
from Domain.Entities.Famer_Lands.farmer_land import Farmer_Land
from Domain.Entities.Weather_Forecast.weather_forecast import Weather_Forecast
class Weather_Forecast_Alert(Base_Ent... | Python | 1 |
.set_ylabel('Oylik Maosh')
st.pyplot(fig)
st.subheader('Oylik Maosh va Ishdagi Mamnuniyat')
st.write("Ushbu box plot oylik maoshning ishdagi mamnuniyat darajasiga qanday ta’sir qilishini ko'rsatadi.")
satisfaction_order = ["Very High", "High", "Medium", "Low"]
df['Job Satisfac... | Python | 1 |
import os
import subprocess
from pathlib import Path
import streamlit as st
from dotenv import load_dotenv
# Load environment variables
load_dotenv()
# Constants
UPLOAD_DIR = Path("data/uploaded")
SUPPORTED_FORMATS = ["mp4"]
USERNAME = os.getenv("MAPILLARY_USERNAME")
def save_uploaded_file(file, destination_path):... | Python | 1 |
* std::iter::repeat(flip).take(i).product::<Mtx3>(),
);
}
}
}
let data = (0..10000)
.map(|_| {
let x = abs.sample(&mut rng) as f64 / 4096.0;
let y = abs.sample(&mut rng) as f64 / 4096.0;
let z = abs.sample(&mut ... | Rust | 0 |
import pytest
from traitlets.config import Config
from jupyter_server.services.kernels.kernelmanager import AsyncMappingKernelManager
@pytest.fixture
def jp_server_config():
return Config(
{"ServerApp": {"MappingKernelManager": {"allowed_message_types": ["kernel_info_request"]}}}
)
def test_config(... | Python | 1 |
STAT_OPENNORMAL: XACTSTAT = 1i32;
#[doc = "*Required features: `\"Win32_System_DistributedTransactionCoordinator\"`*"]
pub const XACTSTAT_OPENREFUSED: XACTSTAT = 2i32;
#[doc = "*Required features: `\"Win32_System_DistributedTransactionCoordinator\"`*"]
pub const XACTSTAT_PREPARING: XACTSTAT = 4i32;
#[doc = "*Required f... | Rust | 0 |
use futures_core::Stream;
use futures_util::TryStreamExt;
use http::header::{
HeaderName, HeaderValue, ACCEPT, AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, COOKIE,
};
use http::{Request, Response, StatusCode};
use once_cell::sync::Lazy;
use pin_utils::pin_mut;
use serde::de::{DeserializeOwned, IgnoredAny};
use ser... | Rust | 0 |
# Выборы в США
#
# Как известно, в США президент выбирается не прямым голосованием, а путем двухуровневого голосования. Сначала
# проводятся выборы в каждом штате и определяется победитель выборов в данном штате. Затем проводятся государственные
# выборы: на этих выборах каждый штат имеет определенное число голосов — ч... | Python | 1 |
import os
from dotenv import load_dotenv
from swarm_models import OpenAIChat
from swarms import Agent
from swarms.prompts.finance_agent_sys_prompt import (
FINANCIAL_AGENT_SYS_PROMPT,
)
from new_features_examples.async_executor import HighSpeedExecutor
load_dotenv()
# Get the OpenAI API key from the environment... | Python | 1 |
Process State after resuming {:?}", process.get_vpp_state());
// Resume Tock Process State
self.kernel.process_each_capability(
&self.capability,
|proc| {
let vppproc_name = process.tockprocess.unwrap().get_process_name();
... | Rust | 0 |
delayed by system clock cycles, 0: output without delayed, 1: output with the posedge of clk_apb,2 output with the negedge of clk_apb, 3: output with the spi_clk. Can be configured in CONF state."]
#[inline(always)]
pub fn d_de_mode(&self) -> D_DE_MODE_R {
D_DE_MODE_R::new(((self.bits >> 6) & 0x07) as u... | Rust | 0 |
::Windows951,
CodePage::Windows1250,
CodePage::Windows1251,
CodePage::Windows1252,
CodePage::Windows1253,
CodePage::Windows1254,
CodePage::Windows1255,
CodePage::Windows1256,
CodePage::Windows1257,
CodePage::Wind... | Rust | 0 |
{c}{a}= \\dfrac {5}{3}}$;\n\nStep 2: (2)抛物线C的顶点是该双曲线的中心(0,0), 而焦点是其左顶点(-3,0), 设抛物线C的方程为${y^{2}=-2px(p > 0)}$, 由${- \\dfrac {p}{2}=-3}$,解得p=6.则抛物线C的方程为${y^{2}=-12x}$.\n\n因此,答案为:(1)实轴长为2a=6、虚轴长2b=8、离心率${e= \\dfrac {c}{a}= \\dfrac {5}{3}}$;\n(2)抛物线C的方程为${y^{2}=-12x}$.<|im_end|>\n<|im_start|>user\n" + input_str.strip() ... | Python | 1 |
(path, libc_path))
}
fn is_header_device_specific(path: &Path, libc_path: &Path) -> bool {
is_header_in_list(path, libc_path, DEVICE_SPECIFIC_HEADERS)
}
fn is_header_in_list(path: &Path, libc_path: &Path, list: &[&str]) -> bool {
let include_path = libc_path.join("include");
list.iter()
.any(|hea... | Rust | 0 |
#[inline(always)]
pub fn pch_f(&self) -> PCH_F_R {
PCH_F_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 0 - 0:0\\]
0: No bitline precharge in first half of cycle 1: Bitline precharge in first half of cycle when in Burst Mode, BM = 1"]
#[inline(always)]
pub fn pch_l(&self) -> PCH_L_R {... | Rust | 0 |
创建管道
pipeline = DiffusionPipeline.from_pretrained(
args.pretrained_model_name_or_path,
unet=unet,
text_encoder=text_encoder,
torch_dtype=weight_dtype,
safety_checker=None,
)
pipeline = pipeline.to(DEVICE)
# 设置随机数生成器
generator = torch.Generator(device=DEVICE)... | Python | 1 |
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
/// An end-entity certificate.
///
/// Server certificate processing in a TLS connection consists of several
/// steps. All of these steps are necessary:
///
/// * `EndEntityCert.verify_is_valid_tls_server_cert`: Verify that the server's
/// certificate is currently va... | Rust | 0 |
nd_event(
self.room_id, "m.room.message", event, tok=self.bad_tok, expect_code=200
)
original_ids.append(res["event_id"])
# grab original events before ban
originals = [self.get_success(self.store.get_event(x)) for x in original_ids]
channel = self.make_... | Python | 1 |
ort::<u32>(bencher, 1 << 19); }
// #[bench] fn msort_u32_20(bencher: &mut Bencher) { merge_sort::<u32>(bencher, 1 << 20); }
// #[bench] fn msort_u32_21(bencher: &mut Bencher) { merge_sort::<u32>(bencher, 1<<21); }
// #[bench] fn msort_u32_22(bencher: &mut Bencher) { merge_sort::<u32>(bencher, 1<<22); }
// #[bench] fn m... | Rust | 0 |
def get_current_merchant_user_by_x_token(api_secret: str = Depends(token_auth_scheme)):
return await v2_user_get_merchant_by_api_secret(api_secret)
async def get_current_user_by_x_token_or_bearer(
api_secret: str = Depends(token_auth_scheme_without_auto_error),
bearer: HTTPAuthorizationCredentials = Depe... | Python | 1 |
# oop/class_inheritance.py
class Engine:
def start(self):
pass
def stop(self):
pass
class ElectricEngine(Engine): # Is-A Engine
pass
class V8Engine(Engine): # Is-A Engine
pass
class Car:
engine_cls = Engine
def __init__(self):
self.engine = self.engine_cls() # ... | Python | 1 |
;
}
if let Ok(rustc) = find_rustc_via_cargo_config(tool_name) {
return rustc;
}
tool_name.to_lowercase()
}
/// Finds the path to `rustc` or `rustdoc`.
///
/// This function will read the configuration at `.cargo/config`. The `tool_name` should be the
/// string `"RUSTC"` or `"RUSTDOC"`.
///
///... | Rust | 0 |
ome(gs) = self.get_graphstorage_as_ref(c) {
gs.size_of(ops) + std::mem::size_of::<usize>()
} else {
// Option has the size of the nullable pointer/Arc
std::mem::size_of::<usize>()
};
size += gs_size;
}
size
}
}
fn ... | Rust | 0 |
, 1, 4, 1, 9, 9, 815, 1, 47, 2, 2, 1)
)
me1200HttpsGlobalsInfoGroup.setObjects(
*(("ME1200-HTTPS-MIB", "me1200HttpsGlobalsMode"),
("ME1200-HTTPS-MIB", "me1200HttpsGlobalsRedirectToHttps"))
)
if mibBuilder.loadTexts:
me1200HttpsGlobalsInfoGroup.setStatus("current")
# Notification objects
# Notifica... | Python | 1 |
_inspector()
server_name = server_name.strip()
# Show header
console.print(
Panel.fit(f"[bold green]MCPM Inspector[/]\nInspecting server: [cyan]{server_name}[/]", border_style="cyan")
)
# Find the server configuration
server_config, location = find_installed_server(server_name)
i... | Python | 1 |
too large to be a table file".into()))
}
if &raw[raw.len()-TABLE_MAGIC_SIZE .. raw.len()] != TABLE_MAGIC {
return Err(Error::sc_table_corrupt("incorrect table magic".into()))
}
let kv_catalog_size = decode_fixed32(&raw[0..4]) as usize;
let data_size = decode_fixed32... | Rust | 0 |
from .common import InfoExtractor
from ..compat import compat_parse_qs
from ..utils import (
int_or_none,
parse_duration,
parse_iso8601,
xpath_text,
)
class FolketingetIE(InfoExtractor):
IE_DESC = 'Folketinget (ft.dk; Danish parliament)'
_VALID_URL = r'https?://(?:www\.)?ft\.dk/webtv/video/[^?... | Python | 1 |
from faker import Faker
fake = Faker()
def user_factory(role="USER"):
"""
Генерирует тестового пользователя с валидными username, password и role.
"""
prefix = "aqa"
max_len = 15
""" Генерируем случайное имя и оставляем только буквы/цифры """
rest = ''.join(ch for ch in fake.user_name()... | Python | 1 |
{z}, ymm2, ymm3/m256`
///
/// `EVEX.256.66.0F.WIG 63 /r`
///
/// `AVX512VL and AVX512BW`
///
/// `16/32/64-bit`
EVEX_Vpacksswb_ymm_k1z_ymm_ymmm256 = 1509,
/// `VPACKSSWB zmm1 {k1}{z}, zmm2, zmm3/m512`
///
/// `EVEX.512.66.0F.WIG 63 /r`
///
/// `AVX512BW`
///
/// `16/32/64-bit`
EVEX_Vpacksswb_zmm_k1z_zmm_... | Rust | 0 |
};
},
"fa" => {
if let Ok(false) = self.fasta_dw(writer) {
panic!("Model {} was not saved !", model);
};
},
_ => {
if let Ok(false) = self.tsv_dw(writer, model) {
... | Rust | 0 |
);
assert_eq!(
vec![MatchIndex(2, "pacific-cruiseship")],
fuzzymatch(&words, "PC", 0.7)
);
}
#[test]
fn should_match_snake_initials() {
let words = vec![
"fuzzy_match",
"jungle_adventure",
"pacific_cruiseship",
... | Rust | 0 |
]>> {
data: &'a T,
max_chunk_size: usize,
}
impl<'a, T> Chunker<'a, T>
where
T: AsRef<[u8]>,
{
/// Create a new [`Chunker`] that yields chunks of `T` of size
/// `max_chunk_size`. If `max_chunk_size` is `0`, then the max
/// chunk size will be set to [`DEFAULT_CHUNK_SIZE`].
pub fn new(data:... | Rust | 0 |
ion(&mut self) -> Result<ClientSession, Box<dyn Error>> {
let (downstream, peer_addr) = self.tcp_listener.accept().await?;
let upstream = TcpStream::connect(self.upstream).await?;
let upstream = self
.tls_connector
.connect(self.hostname.as_ref(), upstream)
.a... | Rust | 0 |
from utils.actions import Rule, BaseCategorizer
rules = (
Rule(r"^Introduced", "introduction"),
# reading-1
Rule(
r"(\w+) intro - (\d)\w+ rdg - to (\w+/?\s?\w+\s?\w+)",
["introduction", "reading-1"],
),
# committee actions
Rule(r"rpt prt - to\s(\w+/?\s?\w+)", "referral-committee... | Python | 1 |
d_at DESC, chapter.manga_id DESC
)"#,
)
.bind(user_id)
.bind(id)
.bind(timestamp)
.fetch_one(&mut conn)
.await
.ok();
let mut count = 0;
if let Some(row) = stream {
count = row.get(0);
}
count > 0
}
... | Rust | 0 |
("Cannot enable power button.");
return false;
}
get_kernel_manager_cluster()
.acpi_event_manager
.enable_gpes();
return true;
}
/// Init PciManager without scanning all bus
///
/// This function should be called before `init_acpi_later`.
pub fn init_pci_early() -> bool {
let pc... | Rust | 0 |
tNoise {
rng: RandomNumberGenerator,
seed: u64,
frequency: f32,
interp: Interp,
noise_type: NoiseType,
octaves: i32,
lacunarity: f32,
gain: f32,
fractal_type: FractalType,
cellular_distance_function: CellularDistanceFunction,
cellular_return_type: CellularReturnType,
cell... | Rust | 0 |
ile = File::open(&filename).unwrap();
let data = unsafe { MmapOptions::new().map(&file).unwrap() };
println!(
"Searching for {} in {:?}: {}",
needle,
filename,
search_in_slice(&backend, needle.as_bytes(), &data)
);
}
<reponame>shadowtime2000/alef-component
mod common;
use co... | Rust | 0 |
nitro(partition_key, rename = "firstName")]
//! name: String,
//! #[nitro(sort_key)]
//! joined: i64,
//! }
//!
//! impl IndexTable for EmployeeNameIndex {
//! type Table = Employees;
//! fn index_name() -> Option<String> {
//! Some("EmployeeNamesIndex".to_string())
//! }
//! }
//!
//! l... | Rust | 0 |
ailed on target.
pub fn moebius<T: PrimalityBase>(target: &T) -> i8
where
for<'r> &'r T: PrimalityRefBase<T>,
{
// remove factor 2
if target.is_even() {
let two = T::one() + T::one();
let four = &two + &two;
if (target % four).is_zero() {
return 0;
} else {
... | Rust | 0 |
Environment
+ ExportedVariableEnvironment
+ FileDescEnvironment
+ UnsetVariableEnvironment,
E::FileHandle: Clone,
E::VarName: Clone,
E::Var: Clone,
{
type IoHandle = E::IoHandle;
fn read_all(&mut self, fd: Self::IoHandle) -> BoxFuture<'static, io::Result<Vec<u8>>> {
... | Rust | 0 |
.inner_join(crates::table)
.select((versions::all_columns, ::models::krate::ALL_COLUMNS))
.first(&*conn)?
}
};
#[derive(Serialize)]
struct R {
version: EncodableVersion,
}
Ok(req.json(&R {
version: version.encodable(&krate.name... | Rust | 0 |
keys = list(doc.spans.keys())
warnings.warn(Warnings.W117.format(spans_key=spans_key, keys=keys))
title = doc.user_data.get("title", None) if hasattr(doc, "user_data") else None
settings = get_doc_settings(doc)
return {
"text": doc.text,
"spans": spans,
"title": title,
... | Python | 1 |
field_updates: dict,
option: _helpers.WriteOption = None,
) -> None:
"""Add a "change" to update a document.
See
:meth:`google.cloud.firestore_v1.document.DocumentReference.update`
for more information on ``field_updates`` and ``option``.
Args:
refe... | Python | 1 |
,
}
}
pub fn main() {
support::main(new())
}
<filename>memflow-cli/src/commands/gdb/ls.rs
use crate::dispatch::*;
use crate::Config;
use clap::{App, ArgMatches, SubCommand};
use log::trace;
use memflow_daemon::request;
pub const COMMAND_STR: &str = "ls";
pub fn command_definition<'a, 'b>() -> App<'a, 'b> {
... | Rust | 0 |
i = 4
d = 4.0
s = 'HackerRank '
j = int(input())
fl = float(input())
st = str(input())
i += j
d += fl
s += st
print(i)
print(d)
print(s) | Python | 1 |
(
"tests/module/qualifier_not_declared.rs",
vec!["qualifier struct is not annotated with the #[lockjaw::qualifier] attribute"],
)
}
#[test]
fn into_map_string_key_collision() {
let t = trybuild::TestCases::new();
t.compile_failed_with(
"tests/module/into_map_string_key_collision.rs"... | Rust | 0 |
mat1 = ConcreteMaterial(user_name="Concrete1")
mat2 = ConcreteMaterial(user_name="Concrete2")
mat3 = ConcreteMaterial(user_name="Concrete3")
print_material_info()
except Exception as e:
print(f"Test 1 failed: {e}")
# Test 2: Deleting a material and checking retag
print("\... | Python | 1 |
x9f\x14k6\xf1m\xb7\xb7\xf9\xbc\xa5\xfb\xdf\
\xde\xaf9\xd6e\xf2\xbcQoyq\x13J\xb6yu\
\x87\xf8Y\xbbf\xbd\x22\xebK\x88\xc4\xcc\xbf5a\xda\
\xe9\xf6\xb1_\xf9\xb2\xed\xfd\xd3|\xbb\xbe\xeek*\xbc\
\xa1\x83\x8c\xb9\xb9\xa4U\xf0\xbd\x85\xf4\xb6\xb2\xddk\xd2\
\xb4\xb7W\x8eghv\xecH#\xec\x98\xa6\xcb\xe28\
\xfcQ\xaf5\xd5\xbb,\xbfc\xf... | Python | 1 |
p
};
let s = s
.parse()
.map_err(|_| format!("Unable to parse sort parameter: {}", s))?;
if p.starts_with('-') {
Ok(Parameter::Descending(s))
} else {
Ok(Paramete... | Rust | 0 |
ializer![];
let mut ll = cell_trivial_initializer![];
let mut lr = cell_trivial_initializer![];
let mut hl = cell_trivial_initializer![];
let mut vl = cell_trivial_initializer![];
unsafe {
ret = cells_rounded_box(
plane,
stylemask as u32,
channels,
... | Rust | 0 |
#! /usr/bin/env python3
'''
demo script to turn liberty files to python database of cells.
ilia greenblat@mac.com
'''
import os,sys
# helpers
def makeDir(Dir):
if os.path.exists(Dir): return
os.mkdir(Dir)
def cellifyList(List,Ext):
res=[]
for Name in List:
ww = Name.split('.')
... | Python | 1 |
, 'e> {
pub fn new(action_mapper: ActionMapperSerde<'a, 'b>, config: &'c GuifastConfigSerde, module_mapper: ModuleMapperSerde<'d, 'e>, modules: ModulesSerde) -> Self {
LibfloInitialized {
action_type: action_str_id(string::module(), string::libflo_initialized_action()),
action_mapper... | Rust | 0 |
installed_toolchain_line.active = active;
}
None => {
// The passed toolchain was not found in the list. Append it.
let line: ToolChainTableLine = match toolchain {
SelectedToolchain::InstalledToolchain(t) => ToolChainTableLine ... | Rust | 0 |
0 ] )
(Array2Variant [] [I0 I1 ] )
(Array3Variant [] [I0 I1 I2 ] )
(Array4Variant [] [I0 I1 I2 I3 ] )
(Array5Variant [] [I0 I1 I2 I3 I4 ] )
(Array6Variant [] [I0 I1 I2 I3 I4 I5 ] )
(Array7Variant [] [I0 I1 I2 I3 I4 I5 I6 ] )
(Array8Variant [ArrayVariant_0_8 ] [] )
(Array9Variant [ArrayVa... | Rust | 0 |
from kivy.animation import Animation
from kivy.clock import Clock
from kivy.lang import Builder
from kivy.metrics import dp
from kivy.properties import ListProperty
from kivy.uix.boxlayout import BoxLayout
from kivymd.app import MDApp
class AnimBox(BoxLayout):
obj_pos = ListProperty([0, 0])
UI = """
<AnimBox>:... | Python | 1 |
def Q1():
name = input()
fhandle1 = open(n)
fhandle1.seek(0)
fhandle1.close()
def Q2():
name = input()
fhandle2 = open(n)
fhandle2.seek(0,2)
fhandle2.close() | Python | 1 |
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
# 设置字体为支持中文的字体
matplotlib.rcParams['font.sans-serif'] = ['SimHei'] # 设置字体为 SimHei
matplotlib.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
# 文件路径
file_path = "/home/hyq/slam/lvio/src/LICO-mid360-main/data/备份/kntsNum.txt"
# 读取文件数据
with open(fi... | Python | 1 |
(js)
}
}
<gh_stars>0
#[macro_use]
extern crate log;
use std::fs::File;
use std::process;
use bincode::{deserialize_from, serialize_into};
use clap::{App, Arg, ArgMatches};
use atglib::fasta::FastaReader;
use atglib::models::Transcripts;
use atglib::utils::errors::AtgError;
use atglib::bed;
use atglib::fasta;
use... | Rust | 0 |
fn ImPlotTime_FromDouble(pOut: *mut ImPlotTime, t: f64);
}
extern "C" {
pub fn ImPlotColormapData_ImPlotColormapData() -> *mut ImPlotColormapData;
}
extern "C" {
pub fn ImPlotColormapData_destroy(self_: *mut ImPlotColormapData);
}
extern "C" {
pub fn ImPlotColormapData_Append(
self_: *mut ImPlotCol... | Rust | 0 |
from typing import Any
from moto.core.exceptions import ServiceException
class ELBClientError(ServiceException):
pass
class DuplicateTagKeysError(ELBClientError):
def __init__(self, cidr: Any):
super().__init__(
"DuplicateTagKeys", f"Tag key was specified more than once: {cidr}"
... | Python | 1 |
mpprinter is not None:
cupsprinters[device]["device-uri"] = tempprinter.getURI()
p = subprocess.Popen(
["lpadmin",
"-p",
cupsprinters[device]["printer-info"].lstrip('-'),
... | Python | 1 |
ize = 35
# Create the scatter plot
fig, ax1 = plt.subplots(figsize=(20, 10))
ax1.grid()
ax1.set_ylabel('$Total Tube Mass \, [t]$', fontsize=label_font_size)
ax1.set_xlabel(r'$\dot{Q}_{tot} \, [MW]$', fontsize=label_font_size)
# Scatter plot
ax1.scatter(concatenated_df_filtered_Q_do... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.