text string | label_name string | labels int64 |
|---|---|---|
_PtrOfColoredKinfu_ColoredKinFu(&self) -> *const c_void { self.as_raw() }
#[inline] pub fn as_raw_mut_PtrOfColoredKinfu_ColoredKinFu(&mut self) -> *mut c_void { self.as_raw_mut() }
}
impl crate::rgbd::ColoredKinfu_ColoredKinFuConst for PtrOfColoredKinfu_ColoredKinFu {
#[inline] fn as_raw_ColoredKinfu_ColoredKin... | Rust | 0 |
Version::Ntsc0_00 => s.addr_0_00,
Version::Ntsc0_01 => s.addr_0_01,
Version::Ntsc0_02 => s.addr_0_02,
Version::Pal => s.addr_pal,
}.unwrap_or_else(|| panic!("Symbol {} unknown for version {}", $sym, $version))
}
... | Rust | 0 |
self.withdraw_list.iter().for_each(|withdraw| {
sink.write_var_bytes(u128_to_neo_bytes(U128::new(*withdraw as u128)).as_slice())
});
}
}
//Withdraw unfreezed ONT deposited in this governance contract.
pub fn withdraw(addr: &Address, amt: U128, peer_pub_key: &str) -> bool... | Rust | 0 |
# Function for mapping the additive number to a human-readable name (Uses additive_names.json)
def additive_name(additives_tags: list, additives_data: dict) -> list:
return [additives_data.get(additive, "Unknown") for additive in additives_tags]
# Function for mapping the nova group number to a human-readable nam... | Python | 1 |
updates[i-1].event == updates[i].event {
updates[i].delta += updates[i-1].delta;
updates[i-1].delta = 0;
}
}
updates.retain(|x| x.delta != 0);
if !updates.is_empty() {
... | Rust | 0 |
departure_time_local for traveller in self.travellers]
times.sort()
deltas = [abs(times[i+1] - times[i]) for i in range(len(times)-1)]
# approximation -> the goal is to lower deltas, not to be accurate in calculating all deltas
""" The following logic is more understandable, b... | Python | 1 |
]
qmc_identifier = sys.argv[4]
# spin (up=0,down=1)
sp = int(sys.argv[5])
if not sp in (0,1):
print('Invalid spin specfied: {}'.format(sp))
print('Must be either 0 (up) or 1 (down)')
quit()
#end if
# Collect parameters from atomic_proj.xml.
# Note: if atomic_proj.x... | Python | 1 |
#[test]
fn test_from_uuid_bytes() {
let b = [
0xa1, 0xa2, 0xa3, 0xa4, 0xb1, 0xb2, 0xc1, 0xc2, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6,
0xd7, 0xd8,
];
let u = Uuid::from_uuid_bytes(b);
let expected = "a1a2a3a4b1b2c1c2d1d2d3d4d5d6d7d8";
assert_eq!(u.simp... | Rust | 0 |
df = pd.read_csv(r"public.test.csv")
df.drop_duplicates(df.columns.drop('ID'), keep='first', inplace=True)
df.drop(df[(df.电压A > 800) | (df.电压A < 500)].index,inplace=True)
df.drop(df[(df.电压B > 800) | (df.电压B < 500)].index,inplace=True)
df.drop(df[(df.电压C > 800) | (df.电压C < 500)].index,inplace=True)
df.drop(df[(df.现场温度 >... | Python | 1 |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
class Register:
def __init__(self, driver: webdriver.Chrome):
self.driver = driver
self.wait = WebDriv... | Python | 1 |
bit flags.
//!
//! The `bitmask!` macro creates a struct and an enum that holds your flags. The enum contains all the
//! bit flag variants and the struct is a mixture of those bit flags called a bitmask.
//! It's syntax is as follows:
//!
//! ```ignore
//! bitmask! {
//! pub mask <struct_name>: <struct_type> wher... | Rust | 0 |
ageSparseSampleDrefImplicitLod")),
308 => return Err(ReadError::UnimplementedOp("OpImageSparseSampleDrefExplicitLod")),
309 => return Err(ReadError::UnimplementedOp("OpImageSparseSampleProjImplicitLod")),
310 => return Err(ReadError::UnimplementedOp("OpImageSparseSampleProjExplicitLod")),
... | Rust | 0 |
#####################################
#### Módulo 5
#### DESAFIO
###################################
"""
Criar uma nova coluna de etnia : branca, nao-branca e outras
"""
import pandas as pd
import numpy as np
#################################################
# carregar o arquivo
dados = pd.read_csv('planilha_modul... | Python | 1 |
from abc import ABC, abstractmethod
class IAvatarStorage(ABC):
@abstractmethod
def generate_upload_url(self, object_name: str, expires_in: int = 3600) -> str:
pass
@abstractmethod
def get_public_url(self, object_name: str) -> str:
pass
@abstractmethod
def delete_object(self, ... | Python | 1 |
_trait::async_trait;
use bincode::{deserialize, serialize};
use byte_unit::{Byte, ByteUnit};
use clap::{App, Arg, ArgMatches};
use crossbeam_channel::{self, Receiver, Sender};
use histogram::Histogram;
use ic_interfaces::transport::{AsyncTransportEventHandler, SendError, Transport};
use ic_logger::{error, info, warn, L... | Rust | 0 |
}
#[test]
fn test_uint_from_str_overflow() {
let mut u8_val: u8 = 255_u8;
assert!((u8::from_str(~"255") == Some(u8_val)));
assert!((u8::from_str(~"256").is_none()));
u8_val += 1 as u8;
assert!((u8::from_str(~"0") == Some(u8_val)));
assert!((u8::from_str(~"-1").is_none()));
let mut u16_val... | Rust | 0 |
}
if self.clusters[i1].dist(&self.clusters[i2]) < maxdist {
let adj_c2 = std::mem::take(&mut self.neighbours[cluster_2]);
// update cluster id for cluster 2 members
// add to cluster 1
for pos in adj_c2 {
... | Rust | 0 |
4),
"win1256" => Ok(WIN_1256),
"win1257" => Ok(WIN_1257),
"win1258" => Ok(WIN_1258),
"ascii" => Ok(ASCII),
"koi8r" => Ok(KOI8_R),
"koi8u" => Ok(KOI8_U),
"eucjp" => Ok(EUC_JP),
"big52003" => Ok(BIG5_2003),
_ => Er... | Rust | 0 |
created, and are often useful for tasks such as measuring
/// benchmarks or timing how long an operation takes.
///
/// Note, however, that instants are not guaranteed to be **steady**. In other
/// words, each tick of the underlying clock might not be the same length (e.g.
/// some seconds may be longer than others).... | Rust | 0 |
"couldn't fetch new version of the index");
let mut walk = repo.revwalk()?;
walk.push_range("HEAD~1..FETCH_HEAD")?;
walk.set_sorting(Sort::TOPOLOGICAL | Sort::REVERSE)?;
let commits: Result<Vec<_>, _> = walk.map(|oid| repo.find_commit(oid?)).collect();
let mut opts = DiffOptions::default();
let... | Rust | 0 |
with_globals(interf, impl_, &globals)
.unwrap_err()
.flatten_errors();
assert!(errs.iter().any(|e| {
inc_on_err([
matches!(e, AbiInstability::FieldCountMismatch { .. }),
matches!(e, AbiInstability::Name { .. }),
... | Rust | 0 |
prev: BlockPtr::default(),
entries: [AllocEntry::default(); ALLOC_LIST_ENTRIES],
}
}
}
impl fmt::Debug for AllocList {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let prev = self.prev;
let entries: Vec<&AllocEntry> = self
.entries
... | Rust | 0 |
duplex)
_mem.offset = mem.offset // 5000 // 10
_mem.isfm = mem.mode == "FM"
_mem.skip = mem.skip == "S"
try:
_mem.power = POWER.index(mem.power)
except ValueError:
_mem.power = 3 # High
for i in range(0, 8):
try:
_mem.... | Python | 1 |
guess_entry = tk.Entry(root, font=("Helvetica", 14), justify='center')
guess_entry.pack(pady=10)
guess_button = tk.Button(root, text="Guess", command=check_guess, font=("Helvetica", 14), bg="lightblue")
guess_button.pack(pady=10)
reset_button = tk.Button(root, text="Reset Game", command=lambda: pl... | Python | 1 |
hours, minutes, seconds = video.video_length//3600, (video.video_length%3600)//60, video.video_length%60
t = f'{hours}:{minutes}:{seconds}'
else:
minutes, seconds = (video.video_length % 3600) // 60, video.video_length % 60
t = f'{minutes}:{seco... | Python | 1 |
, Tag};
use core::convert::TryInto;
/// Parse a `BitString` from an ASN.1 `Any` value to test decoding behaviors.
fn parse_bitstring_from_any(bytes: &[u8]) -> Result<BitString<'_>> {
Any::new(Tag::BitString, bytes)?.try_into()
}
#[test]
fn reject_non_prefixed_bitstring() {
let ... | Rust | 0 |
| {
*acc += *item;
Ok::<_, ()>(())
},
|| Some(std::time::Duration::from_millis(10)),
)
.unwrap();
assert_eq!(
counts.iter().sum::<usize>(),
std::iter::repeat(1).take(num_items).sum::<usize>()
);
}
#[test]
fn stepped_reduce_next() {
let mut ite... | Rust | 0 |
inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Reader of field `RTC_ACTIVE`"]
pub type RTC_ACTIVE_R = crate::R<bool, bool>;
#[doc = "Reader of field `RTC_ENABLE`"]
pub type RTC_ENABLE_R... | Rust | 0 |
: Vec<Vec<&str>> = entry.split(' ')
.map(|x: &str| x.split(':').collect())
.collect();
for data in register{
if data.len() == 2 {
}
registers.insert(data[0].to_string(), data[1].to_string());
}
}
}
... | Rust | 0 |
m = int(input("What is the mass of the object in kilograms? "))
c = 300000000
E = m * (c ** 2)
print(f"The energy of the object is {E:,} Joules.") | Python | 1 |
our setup function.
//! runtime.run_on_workers(setup)?;
//! // And start the runtime.
//! runtime.start()
//! }
//!
//! // This setup function will on run on each created thread. In the case of
//! // this example we create two threads (see `main`).
//! fn setup(mut runtime_ref: RuntimeRef) -> Result<(), !... | Rust | 0 |
!("Couldn't open {}, {}", filename, e))?;
f.seek(SeekFrom::Start(file_offset))
.map_err(|e| format!("Couldn't seek: {}", e))?;
let mut code = vec![0; bin_len];
f.read_exact(&mut code)
.map_err(|e| format!("Couldn't read {} bytes, {}", bin_len, e))?;
Ok((code.into_boxed_slice(), loop_coun... | Rust | 0 |
Two, Suit::Hearts);
let c3 = Card::new(Value::Two, Suit::Diamonds);
let c4 = Card::new(Value::Two, Suit::Clubs);
let c5 = Card::new(Value::Three, Suit::Hearts);
let c6 = Card::new(Value::Three, Suit::Diamonds);
let cards = [&c1, &c2, &c3, &c4, &c5, &c6];
let rank = pokereval::eval_6cards(&cards... | Rust | 0 |
.get(liv, che), Some(tie));
assert_eq!(t.get(mnc, liv), Some(loss));
assert_eq!(t.get(liv, mnc), Some(win));
}
<gh_stars>1-10
#[derive(PartialEq, Clone, Debug, Copy, Eq)]
pub enum Piece {
Pawn = 1,
Knight = 2,
Bishop = 3,
Rook = 4,
Queen = 5,
King = 6,
}
impl Piece {
pub fn from_pgn... | Rust | 0 |
# Group name - app name - Nathaniel Frimpong-Santeng - [14-01-2025]
#
# this is the file that is included into the game project and allows for interfacing between the game and the engine
#
#
#
#
#
#
import os, sys
EngineRoot : str = os.path.dirname( os.path.dirname( __file__ ) )
sys.path.append(os.path.abspath(... | Python | 1 |
_coveralls.assert_called_with(
True, config_file='.coveragerc',
service_name='travis-pro',
base_dir='',
src_dir='',
)
@mock.patch.object(coveralls.cli.log, 'exception')
@mock.patch.object(coveralls.Coveralls, 'wear', side_effect=EXC)
@mock.patch.dict(os.environ, {'TRAVIS': 'True'},... | Python | 1 |
ess_one works when the second arg in the array is used
// instead of the first.
let res = App::new("unlessone")
.arg(Arg::with_name("cfg")
.required_unless_one(&["dbg", "infile"])
.takes_value(true)
.long("config"))
.arg(Arg::with_name("dbg")
.long... | Rust | 0 |
a>)> + 'a + Clone {
let copy = *self;
(0..self.num_base_paints()).filter_map(move |i| copy.base_paint(i))
}
/// Returns the number of paint layers in the table.
pub fn num_paint_layers(&self) -> u32 {
if self.version < 1 {
return 0;
}
let base = self.data... | Rust | 0 |
(string.find(substring).map(|i| i as i64 + 1)),
_ => Ok(None),
}
}
pub(crate) fn lpad(original_value: &str, return_length: i64, pattern: &str) -> String {
assert!(return_length >= 0, "LPAD return_length cannot be negative");
assert!(pattern.len() != 0, "LPAD pattern cannot be empty");
let retur... | Rust | 0 |
# NOT_RPYTHON
"""
The 'sys' module.
"""
from _structseq import structseqtype, structseqfield
import sys
def excepthook(exctype, value, traceback):
"""Handle an exception by displaying it with a traceback on sys.stderr."""
# Flush stdout as well, both files may refer to the same file
try:
sys.stdo... | Python | 1 |
c @ s d Z d d l Z d d l Z d d l Z d d l Z d d d g Z d e f d YZ d f d YZ d Z d f d YZ
d
Z d Z d e f d
YZ
d Z d Z d Z d S( s Debugger basicsiNt BdbQuitt Bdbt
Breakpointc B s e Z d Z RS... | Python | 1 |
'''from time import sleep
from selenium.webdriver.chrome.webdriver import WebDriver
driver=WebDriver()
driver.maximize_window()'''
#help=driver.find_element().click()
#driver.find_element("xpath","//img[@alt='Deals']").click()
#//h3[text()='Carrot - Orange (Loose)']/../../../..//button[text()='Add']
'''register=driver.... | Python | 1 |
h> => Fed8<$a, $b, $c, $d, $e, $f, $g, $h>; Fed7::T1, Fed7::T2, Fed7::T3, Fed7::T4, Fed7::T5, Fed7::T6, Fed7::T7);
fed_promotion!(Fed7 => Fed8; <$a, $c, $d, $e, $f, $g, $h> => <$a, $b, $c, $d, $e, $f, $g, $h>; Fed7<$a, $c, $d, $e, $f, $g, $h> => Fed8<$a, $b, $c, $d, $e, $f, $g, $h>; Fed7::T1, Fed7::T2, Fed7::T3... | Rust | 0 |
if batched else dX
dX[1:-1, :, :, 0] = (X[2:, :, :] - X[:-2, :, :]) / 2
dX[0, :, :, 0] = X[1] - X[0]
dX[-1, :, :, 0] = X[-1] - X[-2]
dX[:, 1:-1, :, 1] = (X[:, 2:, :] - X[:, :-2, :]) / 2
dX[:, 0, :, 1] = X[:, 1] - X[:, 0]
dX[:, -1, :, 1] = X[:, -1] - X[:, -2]
dX[:... | Python | 1 |
EPOCH * (opts.epoch + 1) - 1),
);
log::debug!(
"slot range: {}, {}",
first_slot_in_epoch,
last_slot_in_epoch
);
let requests = (first_slot_in_epoch..=last_slot_in_epoch)
.flat_map(|slot| {
let local_seed = seed.clone();
let local_slot = slot.to_str... | Rust | 0 |
" All cells in the center row and center column are equal to 255, and the rest are equal to zero."]
#[doc = " Dimensions of 3x3 and 5x5 must be supported."]
#[doc = " - VX_PATTERN_DISK is a matrix with dimensions equal to the given number of rows (R) and columns (C),"]
#[doc = " where R and C are odd... | Rust | 0 |
d")
print("\n6. Testing structured delegation...")
try:
result = agent.delegate_task("Analyze governance proposal for voting")
print(f" ✅ Governance delegation: {str(result)[:100]}...")
except Exception as e:
print(f" ❌ Governance delegation failed: {e}")
try:
... | Python | 1 |
"""Test job analysis functionality."""
import os
import pytest
from pathlib import Path
from dotenv import load_dotenv
from src.models import OllamaEmbedding, OpenRouterModel
from src.analysis import JobAnalyzer
# Load environment variables
load_dotenv()
OPENROUTER_API_KEY = os.getenv('OPENROUTER_API_KEY')
@pytest.f... | Python | 1 |
import logging
from telebot import TeleBot, types
from fatoshist.database.groups import GroupManager
from fatoshist.database.poll_manager import PollManager
from fatoshist.database.users import UserManager
group_manager = GroupManager()
poll_manager = PollManager()
user_manager = UserManager()
def register(bot: Te... | Python | 1 |
sql_to_run = []
password_changed = False # Initialize this in case the attributes module isn't run
if attributes:
sql_to_run.append(create_divider('attributes'))
# Password changes happen within the attributes.py module itself so we don't leak
# passwords; as a result we need to s... | Python | 1 |
)
codon = k12_genome.sequence.alphabet.decode_multiple(codon_code)
# ...and represent as string
# (['A' 'T' 'G'] -> "ATG")
codon = "".join(codon)
freq = codon_counter[codon_code]
print(f"{amino_acid} {codon} {freq:.2f}")
print()
##################################... | Python | 1 |
.
pub const EH2DISS: fcn = 4.478;
/// pi e^2 / m_e c [cm^2 Hz].
pub const PIE2_MEC: fcn = 0.02654;
/// Electron rest energy [erg].
pub const MC2_ELECTRON: fcn = M_ELECTRON * CLIGHT * CLIGHT;
/// Ionization energy of an hydrogen atom [eV].
pub const XI_H: fcn = 13.595;
// Unit conversion factors
/// Conversion factor ... | Rust | 0 |
use itertools::zip;
///
/// let data = [1, 2, 3, 4, 5];
/// for (a, b) in zip(&data, &data[1..]) {
/// /* loop body */
/// }
/// ```
pub fn zip<I, J>(i: I, j: J) -> Zip<I::IntoIter, J::IntoIter>
where I: IntoIterator,
J: IntoIterator
{
i.into_iter().zip(j)
}
/// Create an iterator that first ite... | Rust | 0 |
"Please format the answer as shown in the examples.")
elif "milk" not in output:
return CheckResult.wrong("Can't parse the number of tokens with the stem 'milk'.\n"
"Please format the answer as shown in the examples")
elif "type" not in output:
... | Python | 1 |
})
.then(move |result| {
trace!("resolve_all_ips {}: completed with {:?}", name_clone, &result);
match result {
Ok(ips) => Ok(Response::Exists(ips)),
Err(abstract_ns::Error::NameNotFound) => Ok(Response::DoesNotExist),
... | Rust | 0 |
# Rekall Memory Forensics
#
# Copyright 2013 Google Inc. All Rights Reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or (at
# your option) any later v... | Python | 1 |
import os
import pathlib
import pytest
import hydrodartpy
import hydrodartpy.core.setup_experiment_tools as hdp_tools
import xarray as xr
import yaml
def calc_file_stats(file):
ds = xr.open_dataset(file)
data_vars = set(ds.variables).difference(set(ds.coords))
stats_dict = {}
for vv in data_vars:
... | Python | 1 |
".into() => std::f64::consts::FRAC_2_SQRT_PI,
"FRAC_PI_2".into() => std::f64::consts::FRAC_PI_2,
"FRAC_PI_3".into() => std::f64::consts::FRAC_PI_3,
"FRAC_PI_4".into() => std::f64::consts::FRAC_PI_4,
"FRAC_PI_6".into() => std::f64::consts::FRAC_PI_6,
"FRAC_PI_8".into() => std::f64... | Rust | 0 |
///
/// let mut files = Files::new();
/// let file_id = files.add("test", source);
///
/// assert_eq!(files.source_span(file_id), Span::from_str(source));
/// ```
pub fn source_span(&self, file_id: FileId) -> Span {
self.get(file_id).source_span()
}
/// Return a slice of the sou... | Rust | 0 |
[`BitSet`] from the provided [`Vec<u64>`].
pub fn from_vec(bits: Vec<u64>) -> Self {
Self { bits }
}
/// Returns true if the bit at the provided index is set.
pub fn get(&self, bit_idx: usize) -> bool {
let word_idx = Self::word_idx(bit_idx);
if let Some(&word) = self.bits.get(... | Rust | 0 |
ven period.
///
/// Returns `true` iff `other` is at most `fudge` seconds before or after
/// this value’s time.
pub fn eq_fudged(self, other: Self, fudge: u64) -> bool {
self.0.saturating_sub(fudge) <= other.0 &&
self.0.saturating_add(fudge) >= other.0
}
}
//--- From
impl From<Ti... | Rust | 0 |
x-unknown-linux-gnu".to_string(),
target_endian: "big".to_string(),
target_pointer_width: "64".to_string(),
target_c_int_width: "32".to_string(),
data_layout: "E-m:e-i1:8:16-i8:8:16-i64:64-f128:64-a:8:16-n32:64".to_string(),
arch: "s390x".to_string(),
target_os: "linux".t... | Rust | 0 |
n).get_dynamic()?)?;
result.push(character);
position = position + character.size() as u64;
}
Ok((position - offset.position(), result))
}
}
impl H2TypeTrait for LPString {
fn is_static(&self) -> bool {
self.character.size().is_some()
}
fn actual_size(... | Rust | 0 |
"""
Utility for converting between Gregorian and Julian dates.
gd2jd -- convert (string) Gregorian Date into Julian Date
jd2gd -- convert (numerical) Julian Date into Gregorian Date
You can confirm that they are mutually compatible:
import dayconv
jd0 = 2451545.0001
print jd0, dayconv.gd2jd(dayconv.jd2gd(24... | Python | 1 |
0, 0, 5, // 12 1110.
0, 0, 6, // 13 1111 0.
16*3, 15*3, 0, // 14 1111 1
17*3, -1, 0, // 15 1111 11
0, 0, 7, // 16 1111 10.
0, 0, 8 // 17 1111 110.
];
pub const DCT_DC_SIZE_CHROMINANCE: [i32; 3*18] = [
2*3,... | Rust | 0 |
# """
# List-malumot tipi
# List belgisi []
# Toplam-Ma'lum bir sinfga tegishli va malum maqsadda yigilgan malumotlar
# (qiymatlar yoki ozgaruvchilar) dan tashkil topgan ro'yxat
#
# Listda malumotlar ,(belgul) bilan ajratilib yoziladi [1,2,3,4]
#
# listda elementlar indexlangan boladi va index-0 dan boshlidi
#
# """
# ... | Python | 1 |
# Copyright (C) 2018-2025 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
import pytest
import torch
from pytorch_layer_test_class import PytorchLayerTest
class aten_alias(torch.nn.Module):
def forward(self, x):
y = x.clone()
y[:, 1, :, :] = 4.
return y
class aten_alias_tensor(... | Python | 1 |
///
/// # Examples
///
/// ```
/// use num_bigint::{BigInt, Sign};
///
/// assert_eq!(BigInt::from(-1125).to_u64_digits(), (Sign::Minus, vec![1125]));
/// assert_eq!(BigInt::from(4294967295u32).to_u64_digits(), (Sign::Plus, vec![4294967295]));
/// assert_eq!(BigInt::from(4294967296u... | Rust | 0 |
Value::U32(v1.wrapping_div(v2)),
(Value::I64(v1), Value::I64(v2)) => Value::I64(v1.wrapping_div(v2)),
(Value::U64(v1), Value::U64(v2)) => Value::U64(v1.wrapping_div(v2)),
(Value::F32(v1), Value::F32(v2)) => Value::F32(v1 / v2),
(Value::F64(v1), Value::F64(v2)) => Value::F... | Rust | 0 |
ApiError> {
use crate::schema::users::dsl::*;
let conn = pool.get()?;
let all_users = users
.filter(family_id.eq(_family_id.to_string()))
.load(&conn)?;
Ok(all_users.into())
}
/// Find a user by the user's id or error out
pub fn find(pool: &PoolType, user_id: Uuid) -> Result<UserResp... | Rust | 0 |
&'a [u8]), Exception> {
let (pair_len_u32, after_len_bytes) = u32::decode(bytes)?;
let pair_len_usize = pair_len_u32 as usize;
let mut hash_map: HashMap<Term, Term> = HashMap::with_capacity(pair_len_usize);
let mut remaining_bytes = after_len_bytes;
for _ in 0..pair_len_usize {
let (key, a... | Rust | 0 |
def make_so_cache_key(version_hash, signature, constants, ids, **kwargs):
# Get unique key for the compiled code
signature = {k: 'ptr' if v[0] == '*' else v for k, v in signature.items()}
key = f"{version_hash}-{''.join(signature.values())}-{constants}-{ids}"
for kw in kwargs:
key = f"{key}-{kw... | Python | 1 |
],
),
migrations.CreateModel(
name='Sermon',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('slug', models.SlugField(null=True)),
('title', models.CharField(max_length... | Python | 1 |
);
});
}
#[test]
fn test_expect_top_level_only_visibility_fails() {
let (index, len, top_level) = parse(expect_top_level, "pub");
let error = top_level.unwrap_err();
assert_eq!(index, len);
assert_eq!(
error,
Error::Expected(
... | Rust | 0 |
Vec<$int_ty>) -> bool {
let mut bin = $mayda_ty::new();
bin.encode(&input).unwrap();
for a in 0..(input.len() + 1) {
if input[..a] != *bin.access(..a) {
return false
}
}
true
}
)*)
}
range_to!{
(Monotone: u8, rt_mon_u8)
(Monotone: u16, rt_mon_u16)
(M... | Rust | 0 |
(rest));
}
'\r' => {}
_ => {}
}
}
Err(LexError)
}
fn byte(input: Cursor) -> Result<Cursor, LexError> {
let input = input.parse("b'")?;
let mut bytes = input.bytes().enumerate();
let ok = match bytes.next().map(|(_, b)| b) {
Some(b'\\') => match by... | Rust | 0 |
from django.contrib import admin
from hotels.models import Hotel
admin.site.register(Hotel)
| Python | 1 |
&mut Self {
self.0.insert("message_reference", serde_json::to_value(reference.into()).unwrap());
self
}
}
impl<'a> Default for CreateMessage<'a> {
/// Creates a map for sending a [`Message`], setting [`Self::tts`] to `false` by
/// default.
///
/// [`Message`]: crate::model::channe... | Rust | 0 |
from aiogram import Router, F
from aiogram.types import Message
from aiogram.filters import Command
from aiogram.fsm.state import State, StatesGroup
from aiogram.fsm.context import FSMContext
import re
from keyboards.common import phone_kb
from repository.users import create_user, update_user, is_exist
router = Route... | Python | 1 |
events = NCaltech101.load_origin_data(bin_file)
np.savez(np_file,
t=events['t'],
x=events['x'],
y=events['y'],
p=events['p']
)
print(f'Save [{bin_file}] to [{np_file}].')
@staticmethod
def create_event... | Python | 1 |
cfg(not(target_os = "solana"))]
crate::program_stubs::sol_memcmp(s1.as_ptr(), s2.as_ptr(), n, &mut result as *mut i32);
result
}
/// Like C `memset`.
///
/// # Arguments
///
/// - `s` - Slice to be set
/// - `c` - Repeated byte to set
/// - `n` - Number of bytes to set
///
/// # Errors
///
/// When executed w... | Rust | 0 |
e.expect(USAGE),
&args.arg_file.expect(USAGE),
);
} else if args.flag_download {
service::Service { db, provider }.download(
&args.arg_file.expect(USAGE),
&args.arg_newname.expect(USAGE),
);
} else if args.flag_remove {
service::Service { db, p... | Rust | 0 |
mpl ::protobuf::MessageStatic for ServiceStatus {
fn new() -> ServiceStatus {
ServiceStatus::new()
}
fn descriptor_static(_: ::std::option::Option<ServiceStatus>) -> &'static ::protobuf::reflect::MessageDescriptor {
static mut descriptor: ::protobuf::lazy::Lazy<::protobuf::reflect::MessageD... | Rust | 0 |
delta_ns: {}\n".format(dev['min_delta_ns'])
text += " mult: {}\n".format(dev['mult'])
text += " shift: {}\n".format(dev['shift'])
text += " mode: {}\n".format(dev['state_use_accessors'])
text += " next_event: {} nsecs\n".format(dev['next_event'])
text += " set_nex... | Python | 1 |
[39], K64[38]),
u64x2(K64[41], K64[40]),
u64x2(K64[43], K64[42]),
u64x2(K64[45], K64[44]),
u64x2(K64[47], K64[46]),
u64x2(K64[49], K64[48]),
u64x2(K64[51], K64[50]),
u64x2(K64[53], K64[52]),
u64x2(K64[55], K64[54]),
u64x2(K64[57], K64[56]),
u64x2(K64[59], K64[58]),
u64x2(K64[... | Rust | 0 |
path, err)
}
let raspi = match File::open(Path::new(DEVICE_MOD_PATH)) {
Ok(f) => {
let reader = BufReader::new(&f);
let mut raspi = false;
for line in reader.lines() {
if let Ok(line) = line {
if line.contains("Raspberry Pi") {
... | Rust | 0 |
;
file.read_to_end(&mut elf).unwrap();
let mut executable = <dyn Executable<UserError, DefaultInstructionMeter>>::from_elf(
&elf,
None,
Config::default(),
)
.unwrap();
bencher.iter(|| executable.jit_compile().unwrap());
}
<gh_stars>1-10
use chrono::prelude::*;
use ckb_crypto:... | Rust | 0 |
= ShallowRoot()
self._reset_buffer()
with timed() as t:
aioxmpp.xml.write_single_xso(item, self.buf)
record(key+("sz",), self.buf.tell(), "B")
record(key+("rate",), self.buf.tell() / t.elapsed, "B/s")
@times(1000)
def test_shallow_and_large(self):
key = self... | Python | 1 |
# core/forms.py
from django import forms
TYPE_CHOICES = (
("compras", "Compras"),
("ventas", "Ventas"),
)
MAX_FILE_MB = 15
ALLOWED_EXTS = {".csv"}
def _validate_file(f: forms.FileField):
import os
name = f.name.lower()
ext = os.path.splitext(name)[1]
if ext not in ALLOWED_EXTS:
raise ... | Python | 1 |
"OUTBOUND_FWMARK") {
Ok(mark) => config.outbound_fwmark = Some(mark),
Err(ref err) if err.kind() == ClapErrorKind::ArgumentNotFound => {}
Err(err) => err.exit(),
}
#[cfg(target_os = "freebsd")]
match matches.value_of_t::<u32>("OUTBOUND_USER_COOKIE") {
... | Rust | 0 |
)
}
pub fn rowend_gds(lib: &mut PdkLib) -> CellGdsResult {
cell_gds(
lib,
"sram_sp_rowend.gds",
"sky130_fd_bd_sram__sram_sp_rowend",
)
}
pub fn wlstrap_gds(lib: &mut PdkLib) -> CellGdsResult {
cell_gds(
lib,
"sram_sp_wlstrap.gds",
"sky130_fd_bd_sram__sram_sp... | Rust | 0 |
r_slurm_executor._new_slurm_executor",
autospec=True,
) as mock_new_executor:
# When _new_slurm_executor is called, return our executor instance.
mock_new_executor.return_value = executor_instance
runner = pipeline.map_async(
{"x": range(10)},
tmp_path,
... | Python | 1 |
{
($name:ident, $ty:ty, $uty:ty, $sz:literal, $genrand:ident, $bs:expr, $const:expr) => {
fn $name(rng: &mut rng::Rng, writer: &mut WasmWriter) -> Option<wasm::syntax::Instr> {
use intop::BinOp::*;
use wasm::syntax::*;
let a: $ty = $genrand(rng, None);
let b:... | Rust | 0 |
tx_client_api
.send(Channel::Send(buffer.to_vec()))
.map_err(|e| ConsumerError::APIChannel(e.to_string()))?)
}
pub async fn request(
&self,
sequence: u32,
buffer: &[u8],
) -> Result<protocol::AvailableMessages, ConsumerError<E>> {
let (tx_response, rx... | Rust | 0 |
<String>> {
assert!(base_path.exists());
assert!(base_path.is_file());
let reader = BufReader::new(File::open(base_path).expect("Cannot open ids file."));
let mut ret = vec![];
for line in reader.lines() {
ret.push(line.unwrap());
}
Some(ret)
}
fn extract_tiles(ts: &Tileset, ids... | Rust | 0 |
buf = MacroAssembler::new();
let lbl = buf.create_label();
emit_jcc(&mut buf, CondCode::Zero, lbl);
emit_nop(&mut buf);
buf.bind_label(lbl);
assert_eq!(vec![0x0f, 0x84, 1, 0, 0, 0, 0x90], buf.data());
}
#[test]
fn test_emit_jcc_non_zero() {
let mut buf = Mac... | Rust | 0 |
thread::spawn(move || loop {
//Create a buffer to store the msges.
let mut buff = vec![0; MSG_SIZE];
//Hear socket entries from sender an match it with a Result.
match socket.read(&mut buff) {
//... | Rust | 0 |
this payment terms line.")
value_amount = fields.Float(string='Due', digits='Payment Terms',
help="For percent enter a ratio between 0-100.",
compute='_compute_value_amount', store=True, readonly=False)
delay_type = fields.Selection([
(... | Python | 1 |
from typing import cast
from kirin import types
from kirin.prelude import basic
from kirin.analysis import const
from kirin.dialects.py.range import Range
@basic
def new_range(a: int, b: int, c: int):
x = range(a)
y = range(a, b)
z = range(a, b, c)
return x, y, z
new_range.print()
def test_new_ra... | Python | 1 |
assert_eq!(state, expected);
}
#[quickcheck]
fn test_shift_rows_bijective(input: u128) {
let mut state = input.to_le_bytes();
shift_rows(&mut state);
inv_shift_rows(&mut state);
assert_eq!(input.to_le_bytes(), state);
let mut state = input.to_le_bytes();
... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.