text string | label_name string | labels int64 |
|---|---|---|
# We should not remove the trailing comma in a single-element subscript.
a: tuple[int,]
b = tuple[int,]
# But commas in multiple element subscripts should be removed.
c: tuple[int, int,]
d = tuple[int, int,]
# Remove commas for non-subscripts.
small_list = [1,]
list_of_types = [tuple[int,],]
small_set = {1,}
set_of_t... | Python | 1 |
if the series is not found.
pub async fn series_filter<I>(
&self,
id: I,
filter_keys: &SeriesFilterKeys,
) -> Result<FilteredSeries>
where
I: Into<SeriesID>,
{
self.series_filter_into(id, filter_keys).await
}
/// Same as [`series_filter`], but allows dese... | Rust | 0 |
}
}
map.insert(rule_name.to_string(), valid_nums);
}
return map;
}
pub fn read_rules() -> Vec<String> {
let input = "departure location: 36-363 or 377-962
departure station: 29-221 or 234-953
departure platform: 39-585 or 595-954
departure track: 31-727 or 753-952
departure date: 33... | Rust | 0 |
# -*- coding: utf-8 -*
# author: unknowwhite@outlook.com
# wechat: Ben_Xiaobai
import sys
sys.path.append("./")
import datetime
import time
import random
from configs.export import write_to_log
# 输出时间范围变量
def getdate(dateinput):
# 第一个参数是yesterday取昨天数据,第一个参数是today取今天数据,第一个参数是日期,则取对应日期的数据
today = datetime.date.... | Python | 1 |
pub kind: BinOpKind,
pub is_left_assoc: bool
}
impl BinOp {
/// Create a BinOp from a token instance.
pub fn from_token(token: &Token) -> Result<BinOp, ()> {
let fpos = token.get_file_position();
let op_kind: BinOpKind = match token {
Token::OpAdd(..) => BinOpKind::Add,
... | Rust | 0 |
buffer.set_cursor(cur!{l 827 o 0 h l 828 o 30}, Replace);
TestEdit::apply(&mut buffer, TabIn);
assert_eq!(line_count, buffer.rope.len_lines());
}
#[test]
fn does_not_lose_a_line_in_this_reduced_1_second_manually_found_case() {
use TestEdit::*;
use ReplaceOrAdd::*;
let mut buffer = t_b!(incl... | Rust | 0 |
}
}
type System = system::Module<Test>;
type Balances = balances::Module<Test>;
type Proposals = Module<Test>;
const COUNCILOR1: u64 = 1;
const COUNCILOR2: u64 = 2;
const COUNCILOR3: u64 = 3;
const COUNCILOR4: u64 = 4;
const COUNCILOR5: u64 = 5;
const PROPOSER1: u64 = ... | Rust | 0 |
Code::Escape)) => break 'main,
glutin::Event::Closed => break 'main,
_ => {},
}
}
device.submit(renderer.as_buffer());
window.swap_buffers();
}
}
use hubcaps::{Credentials, Github, Result};
use std::env;
#[tokio::main]
async fn main() -> Result<()... | Rust | 0 |
_none_mut().0,
self.to_glib_none().0 as *mut _,
)
}
value
}
fn value_type(&self) -> glib::Type {
Self::static_type()
}
}
#[doc(hidden)]
impl glib::value::ToValueOptio... | Rust | 0 |
_, ScalarValue};
/// #
/// // NOTICE: Specifying `ScalarValue` as existing type parameter.
/// #[graphql_interface(for = Human, Scalar = S)]
/// trait Character<S: ScalarValue> {
/// async fn id<'a>(&self, executor: &'a Executor<'_, '_, (), S>) -> &'a str
/// where
/// S: Send + Sync; // required by `#... | Rust | 0 |
table_name_valid,
table_name,
isCompleted,
fileNames,
upload_id):
'''
控制已上传表格的入库
'''
if all([n_clicks, table_name_valid, table_name, isCompleted, fileNames, upload_id]):
uploaded_df = pd.read_csv... | Python | 1 |
rope/Dublin
Greenwich Standard Time;(UTC+00:00) Monrovia, Reykjavik=UTC
Greenwich Standard Time;(UTC) Monrovia, Reykjavik=UTC
Morocco Standard Time;(UTC+00:00) Casablanca=UTC
Morocco Standard Time;(UTC) Casablanca=UTC
UTC;(UTC) Coordinated Universal Time=UTC
Central Europe Standard Time;(UTC+01:00) Belgrade, Bratislava... | Rust | 0 |
:
# Check what version was built
success, files, error = run_command("ls dist/*.whl", cwd=temp_repo)
if success:
wheel_file = files.split('\n')[0] if files else ""
print(f"✅ Built wheel: {os.path.basename(wheel_file)}")
... | Python | 1 |
# 获取配置
return jsonify({
'success': True,
'config': get_config_status()
})
elif request.method == 'POST':
# 更新配置(注意:这里只是演示,实际应用中需要更安全的配置管理)
try:
data = request.get_json()
# 验证配置
if 'github_repo' in data:
... | Python | 1 |
.as_str() {
"fn" => TokType::KwFn,
"int" => TokType::KwInt,
"bool" => TokType::KwBool,
"let" => TokType::KwLet,
"var" => TokType::KwVar,
"return" => TokType::KwReturn,
"true" => TokType::KwTrue,
"false" => TokType::KwFalse,
... | Rust | 0 |
ic PUSH: &'static str = include_str!("../../../../test-data/push_payload.json");
static RELEASE: &'static str = include_str!("../../../../test-data/release_payload.json");
static WATCH: &'static str = include_str!("../../../../test-data/watch_payload.json");
static OTHER_FORK_APPLY: &'static str = include_str!("../../.... | Rust | 0 |
_shl(answer_number)
.ok_or(QuestionParseError::InvalidAnswer(answer))?;
Ok(answers | answer_bit)
})?))
}
}
impl From<Vec<Questionnaire>> for Group {
fn from(forms: Vec<Questionnaire>) -> Self {
Self { forms }
}
}
impl FromStr for Group {
type Err = Question... | Rust | 0 |
let data = data.clone();
task::spawn(async move {
let mut lk = data.lock().await;
task::yield_now().await;
*lk += 1;
task::yield_now().await;
})
.unwrap();
}
run_multi(NCPU);
let guard = ... | Rust | 0 |
# Copyright 2015 Google Inc. 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 a... | Python | 1 |
ErrInvalidQueryType: WbemErrorEnum = -2147217384i32;
#[doc = "*Required features: 'Win32_System_Wmi'*"]
pub const wbemErrAlreadyExists: WbemErrorEnum = -2147217383i32;
#[doc = "*Required features: 'Win32_System_Wmi'*"]
pub const wbemErrOverrideNotAllowed: WbemErrorEnum = -2147217382i32;
#[doc = "*Required features: 'Wi... | Rust | 0 |
const VK_AMD_negative_viewport_height: u32 = 1;
pub const VK_AMD_NEGATIVE_VIEWPORT_HEIGHT_SPEC_VERSION: u32 = 1;
pub const VK_AMD_NEGATIVE_VIEWPORT_HEIGHT_EXTENSION_NAME: &'static [u8; 32usize] =
b"VK_AMD_negative_viewport_height\0";
pub const VK_AMD_gpu_shader_half_float: u32 = 1;
pub const VK_AMD_GPU_SHADER_HALF... | Rust | 0 |
re::ops::Deref for RX256_511OCTGB_R {
type Target = crate::FieldReader<u32, u32>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl R {
#[doc = "Bits 0:31 - This field indicates the number of received good and bad frames with length between 256 and 511 (inclusive) bytes, ... | Rust | 0 |
col, row_idx) as i16),
DataType::UInt16 => row.write_int2(array_val!(UInt16Array, col, row_idx) as i16),
DataType::UInt32 => row.write_int4(array_val!(UInt32Array, col, row_idx) as i32),
DataType::UInt64 => row.write_int8(array_val!(UInt64Array, col, row_idx) as i64),
DataType::Float16 => row.write_... | Rust | 0 |
// Was not accessed
Color::RGB(value, value, value)
} else {
// FIXME The color is determined by value in memory, we
// want to fade max color somewhat (to use bright colors
// by other stuff), but also show at least something
// instead o... | Rust | 0 |
_int, pe: c_int) -> c_int;
pub fn shmem_int_fadd(target: *mut c_int, value: c_int, pe: c_int) -> c_int;
pub fn shmem_int_fetch(dest: *const c_int, pe: c_int) -> c_int;
pub fn shmem_int_finc(target: *mut c_int, pe: c_int) -> c_int;
pub fn shmem_int_g(addr: *mut c_int, pe: c_int) -> c_int;
pub fn shmem_int_get(dest:... | Rust | 0 |
"""create_tables
Revision ID: a00fdac945ca
Revises:
Create Date: 2025-07-16 21:24:56.850707
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'a00fdac945ca'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... | Python | 1 |
about = "Convenience commands on environment variable secrets")]
EnvVars(EnvVarsCommand),
#[structopt(about = "Prints psonoci's license")]
License,
}
#[derive(StructOpt, Debug)]
pub enum SecretCommand {
#[structopt(about = "Get a psono secret")]
Get {
#[structopt(required = true, help = "Th... | Rust | 0 |
y_index, chunk));
}
Ok(())
}
/// Where the chunks will be written to.
pub fn inner_chunks_writer(&self) -> &W {
&self.chunk_writer
}
}
/// Compress blocks to a chunk writer in this thread.
#[derive(Debug)]
#[must_use]
pub struct SequentialBlocksCompressor<'w, W> {
meta: ... | Rust | 0 |
gInput["node_features"].append(allNodes[node])
for edge in all_edges:
start, t, end = edge
start = trueNodeMap[start]
end = trueNodeMap[end]
e = [start, t, end]
gInput["graph"].append(e)
return gInput
def extract_slices(linized_code, list_o... | Python | 1 |
Ok(())
}
#[test]
fn case_with_type_cast() -> Result<()> {
let batch = case_test_batch()?;
let schema = batch.schema();
// CASE WHEN a = 'foo' THEN 123.3 ELSE 999 END
let when = binary(
col("a", &schema)?,
Operator::Eq,
lit(ScalarValue::... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Time : 2023/5/11 17:44
@Author : alexanderwu
@File : __init__.py
"""
from enum import Enum
from metagpt.actions.action import Action
from metagpt.actions.action_output import ActionOutput
from metagpt.actions.add_requirement import UserRequirement
from metagpt.... | Python | 1 |
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain import PromptTemplate
import streamlit as st
import os
# Set up API key for Google's Generative AI
os.environ['GOOGLE_API_KEY'] = st.secrets['GOOGLE_API_KEY']
# Create a prompt template for generating recommendations
recommendation_template = "G... | Python | 1 |
#
import os
import torch
import numpy as np
import scanpy as sc
def adata_preprocess(adata_vis, min_cells=50, min_counts=10, pca_n_comps=200):
adata_vis.layers['count'] = adata_vis.X.toarray()
sc.pp.filter_genes(adata_vis, min_cells=min_cells)
sc.pp.filter_genes(adata_vis, min_counts=min_counts)
# ada... | Python | 1 |
# Vigenere Cipher Dictionary Hacker
# http://inventwithpython.com/hacking (BSD Licensed)
import detectEnglish, vigenereCipher, pyperclip
def main():
ciphertext = """Tzx isnz eccjxkg nfq lol mys bbqq I lxcz."""
hackedMessage = hackVigenere(ciphertext)
if hackedMessage != None:
print('Copying hacke... | Python | 1 |
import sqlite3
import os
def setup_database():
# Path to the database file
db_path = os.path.join(os.path.expanduser('~'), 'Dragonfruit', 'dragonfruit.db')
# Connect to the SQLite database. It will create the database file if it doesn't exist.
conn = sqlite3.connect(db_path)
# Create the 'people'... | Python | 1 |
from common import TEXTURES_FOLDER
from image import create_images, clear_images, get_image_list
from clut import clear_cluts, get_clut_list
import logging
import textwrap
logger = logging.getLogger(__name__)
RECT_SIZE = 8
CHAR_SIZE = 1
SHORT_SIZE = 2
img_names = []
clut_names = []
def construct_header() -> str:
... | Python | 1 |
metrics.
///
/// Defaults to `true`.
pub serve_health_and_metrics: bool,
/// Whether to shutdown the server gracefully.
///
/// Defaults to `true`.
pub graceful_shutdown: bool,
}
impl Default for Config {
fn default() -> Self {
Self {
bind_address: SocketAddr::from... | Rust | 0 |
lista = []
# PILA - LIFO
# Los primeros en entrar son los ultimos en salir
for i in range(1, 5):
lista.append(i) # -> apilando elementos en la lista comienza con 1, 2, 3, 4
# print(lista) # [1, 2, 3, 4]
for _ in range(1, 5):
lista.pop() # -> eliminando elementos en la lista c... | Python | 1 |
OCK), "failed to create eventfd"),
try_with!(EventFd::new(EFD_NONBLOCK), "failed to create eventfd"),
];
let fds = event_files
.iter()
.map(|ev| ev.as_raw_fd())
.collect::<Vec<_>>();
let remote_fds = try_with!(vm.transfer(fds.as_slice()), "failed to transfer sockets");
a... | Rust | 0 |
x2,
VertexFormat::Float3 => wgpu::VertexFormat::Float32x3,
VertexFormat::Float4 => wgpu::VertexFormat::Float32x4,
VertexFormat::UByte4 => wgpu::VertexFormat::Unorm8x4,
}
}
}
/// Describes a 'VertexBuffer' layout.
#[derive(Default, Debug)]
pub struct VertexLayout {
wg... | Rust | 0 |
>>) -> __jni_bindgen::std::result::Result<(), __jni_bindgen::Local<'env, crate::java::lang::Throwable>> {
// class.path == "android/media/MediaScannerConnection$OnScanCompletedListener", java.flags == PUBLIC | ABSTRACT, .name == "onScanCompleted", .descriptor == "(Ljava/lang/String;Landroid/net/Uri;)V"
... | Rust | 0 |
def hex_key(num):
"""You have been tasked to write a function that receives
a hexadecimal number as a string and counts the number of hexadecimal
digits that are primes (prime number, or a prime, is a natural number
greater than 1 that is not a product of two smaller natural numbers).
Hexadecimal... | Python | 1 |
}, {item['date_info']['date']}, 從 {item['date_info']['start_time']} 至 {item['date_info']['end_time']}。\n"
for item in items
]
result = f"{prefix}{''.join(sentences)}"
return fix_chinese_spacing(result.strip())
except Exception as e:
... | Python | 1 |
let rules = stderr_unwrap(&syntax_src, syntax(&syntax_src));
let ogex_src = include_str!("assets/cube.ogex").to_string();
let mut data = vec![];
stderr_unwrap(&ogex_src, parse(&rules, &ogex_src, &mut data));
}
#[test]
fn test_syntax_opendll() {
use piston_meta::*;
let syntax_src = include_str... | Rust | 0 |
alueError("logit_bias values must be between -100 and 100")
norm[key] = fval
return norm
@model_validator(mode="after")
def cross_validate(self):
n = self.n or 1
if self.best_of is not None and self.best_of < n:
raise ValueError("best_of must be greater than or e... | Python | 1 |
"2001:DB8:1234:5678::/64",
Ipv6Addr::new(0xa001, 0xdb8, 0x1234, 0x5679, 0x1001, 2, 3, 4),
);
}
#[test]
fn order_v4() {
test_v4_order(Ordering::Equal, "192.0.2.0/24", "192.0.2.0/24");
test_v4_order(Ordering::Less, "192.0.2.0/24", "172.16.17.32/24");
test_v4_order(Ordering::Less, "192.0.2.0/24", "192.0.2.0/25");
... | Rust | 0 |
t
pub fn new() -> Self {
Self {
cards_per_round: [0; 8usize],
round_start: [0; 8usize],
rounds: 0,
configurations: [0; 8usize],
permutations: [0; 8usize],
round_size: [0; 8usize],
permutation_to_configuration: [ptr::null_mut... | Rust | 0 |
to(),
_phantom_lifetime: Default::default(),
}
);
assert_eq!(result.rest_input, &[]);
roundtrip(&result.value, &mut Vec::new());
}
#[test]
fn mixed_consts_and_named_fields() {
ssh_packet! {
#[derive(Debug, PartialEq, Eq)]
struct Packet1 {
boolean field... | Rust | 0 |
st MAX_VALIDATORS_PER_COMMITTEE: usize,
const PENDING_ATTESTATIONS_BOUND: usize,
>(
state: &BeaconState<
SLOTS_PER_HISTORICAL_ROOT,
HISTORICAL_ROOTS_LIMIT,
ETH1_DATA_VOTES_BOUND,
VALIDATOR_REGISTRY_LIMIT,
EPOCHS_PER_HISTORICAL_VECTOR,
EPOCHS_PER_SLASHINGS_VECTOR,
... | Rust | 0 |
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import os
# Загрузка оптимизированного набора данных
df = pd.read_csv('all_regions_trimmed.csv')
# Настройка стилей для графиков
sns.set(style="whitegrid")
# Создание папки для сохранения графиков (если она не существует)
if not os.path.exists... | Python | 1 |
ContractError::Funds {}) => {}
Err(err) => {
assert!(false, "Unexpected Error {:?}", err)
}
}
// ensure the calc works
let change_name_msg = ExecuteMsg::SetTokenNameDescription {
description: Some("Another one bites the dust".to_string()),
name: None,
toke... | Rust | 0 |
Err(error) =
utils::read_text_announcement(&forecast_str, &temp_files, "w")
{
eprintln!("[weather] {}", error);
sleep_intervals = 1;
continue;
}
sleep_intervals = config.interval;
}
}
#[allow(unused_imports)]
use serde_json::Value;
#[derive(... | Rust | 0 |
#!/bin/python3
# Copyright (c) 2024 Ricoh Company, Ltd.
#
# 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... | Python | 1 |
ub fn run(&mut self) {
self.run_with_callback(|_| {});
}
pub fn run_with_callback<F>(&mut self, mut callback: F)
where
F: FnMut(&mut CPU),
{
let mut continue_execution = true;
while continue_execution {
callback(self);
let opcode_number = self.mem... | Rust | 0 |
Ord>(data: &mut [T]) {
let data_ptr = data.as_mut_ptr();
quick_sort_inner(data_ptr, 0, (data.len() - 1) as isize);
}
fn quick_sort_inner<T: Ord>(data: *mut T, low: isize, high: isize) {
if high > low {
let part = partition(data, low, high);
quick_sort_inner(data, low, part - 1);
qu... | Rust | 0 |
}
}
}
// lock
let count = {
let mut guard = senders.lock().await; // 5
guard.remove(&addr);
guard.len()
};
println!("Client {} disconnected.({})", addr, count);
}
extern crate cryptopals;
use std::num::Wrapping;
use cryptopals::get_timestamp;
use cryptopa... | Rust | 0 |
il(tok):
raise ParseError(tok, 'unexpected "{0}"'.format(tok.type))
ret = []
while True:
tok = pop()
if not tok:
return ret
if is_comma(tok):
continue
if tok.type != "IDENT":
bail(tok)
... | Python | 1 |
_mm_andnot_si128(low_mask, _mm_set1_epi32(std::i32::MAX)),
);
let value_array = std::mem::transmute::<__m128i, [u32; 4]>(values_low);
let index_array = std::mem::transmute::<__m128i, [i32; 4]>(index_low);
let min_index = simple_argmin(&index_array);
let value = *value_array.get_unchecked(... | Rust | 0 |
;
let buf = Cow::Owned(serialize(&resp)?);
Ok(Message {
method: "Oled.Update",
arg: buf,
})
}
"Clear" => {
let resp = Oled::clear(self, ctx).await?;
let buf = Cow::Owned(serial... | Rust | 0 |
class Solution:
def isPowerOfThree(self, n: int) -> bool:
return n > 0 and 3**19 % n == 0
| Python | 1 |
#Licensed under the Open Software License version 3.0
#Author: antlampas
#Created on: 2025-06-15
import re
from baseClasses import Editable
from baseClasses import Addable
from utilities import isAlpha
from utilities import isNumber
from utilities import isText
class MemberOnboardLog:
def __init__(se... | Python | 1 |
_path.push(format!(
".{}",
Local::now().format(logger::DATETIME_ROTATE_SUFFIX)
));
Ok(PathBuf::from(new_path))
}
#[allow(dead_code)]
pub fn initial_logger(config: &TiKvConfig) {
if config.log_file.is_empty() {
let drainer = logger::term_drainer();
// use async drainer and in... | Rust | 0 |
assert_eq!(scan.max_y, 13);
assert_eq!(scan.x_range(), (495, 506));
}
}
<reponame>zarelaky/fuchsia
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
anyhow::format_err,
bt_a2dp::... | Rust | 0 |
of a [CmdTable].
#[allow(clippy::missing_docs_in_private_items)]
#[repr(C)]
union Cfis {
raw_bytes: [Mmio<u8>; 64],
h2d: FisRegH2D,
// ...
}
assert_eq_size!(Cfis, [u8; 64]);
/// Physical Region Descriptor Table entry.
///
/// Used for DMAs. A physical region is represented as a physical address and its le... | Rust | 0 |
[1,{x:2},3,{x:4},5] | [.[].x?]
"#,
r#"
null
"#,
r#"
[2,4]
"#
);
test!(
multiple_optional_operators,
r#"
.x??, .
"#,
r#"
0
"#,
r#"
0
"#
);
test!(
error_against_null_backtrack,
r#"
[0, error, 1], (.x, error(null), .y) = 1
"#,
r#"
... | Rust | 0 |
import numpy as np, argparse, pickle
import matplotlib; matplotlib.use('agg')
import matplotlib.pyplot as plt
from sklearn.metrics import precision_recall_curve, average_precision_score
import pdb
def loadData(path):
preds = pickle.load(open(path, 'rb'))
y_hot = np.array(preds['y_hot'])
logit_list = np.a... | Python | 1 |
import time
from selenium.webdriver import Chrome
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
driver_path = "" # TODO: put path to webdriver
driver = Chrome(service=Service(driver_path))
driver.maximize_window()
driver.implicitly_wait(5)
driver.get('https://www... | Python | 1 |
8(i8::MAX);
let r = _mm_maskz_adds_epi8(0, a, b);
assert_eq_m128i(r, _mm_setzero_si128());
let r = _mm_maskz_adds_epi8(0b00000000_00001111, a, b);
#[rustfmt::skip]
let e = _mm_set_epi8(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, i8::MAX, i8::MAX, i8::MAX, i8::MAX);
assert_eq_m128... | Rust | 0 |
}
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum Token<'input> {
Identifier(&'input str),
StringLiteral(&'input str),
AddressLiteral(&'input str),
HexLiteral(&'input str),
Number(&'input str, &'input str),
RationalNumber(&'input str, &'input str, &'input str),
HexNumber(&'input str),
... | Rust | 0 |
) => {
let mut _buf = String::new();
stdin().read_to_string(&mut _buf).unwrap();
let mut $i = _buf.split_whitespace();
};
}
#[allow(dead_code)]
const MOD: u64 = 1_000_000_007;
fn main() {
read_init!(buf);
let (a, b): (usize, usize) = (read!(buf), read!(buf));
println!("{}", solve(a, b));
}
fn solve(a: usi... | Rust | 0 |
#
# Copyright 2015 Naver Corp.
#
# 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 agreed to in writ... | Python | 1 |
WHvX64RegisterMsrMtrrPhysMask8 = 0x00002048,
WHvX64RegisterMsrMtrrPhysMask9 = 0x00002049,
WHvX64RegisterMsrMtrrPhysMaskA = 0x0000204A,
WHvX64RegisterMsrMtrrPhysMaskB = 0x0000204B,
WHvX64RegisterMsrMtrrPhysMaskC = 0x0000204C,
WHvX64RegisterMsrMtrrPhysMaskD = 0x0000204D,
WHvX64RegisterMsrMtrrPh... | Rust | 0 |
load_allowed_users()
except Exception as e:
response_text = f"❌ Terjadi kesalahan saat menambah user: `{e}`"
try: await update.callback_query.message.delete()
except Exception: pass
from bot import send_device_menu
await send_device_menu(update, context, selected_d... | Python | 1 |
framed.filter_map(|x| async { recorder::Message::from_string(x.ok()?.as_str()) });
dump(output, skip, messages).await?;
}
SubCommand::Codegen { output } => {
codegen_main(output)?;
}
}
Ok(())
}
async fn dump(
output: PathBuf,
skip: Option<usize... | Rust | 0 |
from flask import (Blueprint, current_app, flash, redirect, render_template,
request, url_for)
from flask_login import current_user, login_required, login_user, logout_user
from ..database import dao
from ..helpers.checkers import is_admin
main = Blueprint("main", __name__)
@main.route("/", metho... | Python | 1 |
s {
Err(ContractError::NotEnoughBalanceForRewards {}) => assert_eq!(true, true),
_ => panic!("DO NOT ENTER HERE"),
}
//proper execution
// update distribution amounts
let msg = ExecuteMsg::UpdateConfig {
paused: None,
epoch_manager_contract: None,
rewards_contrac... | Rust | 0 |
pub trait Command {
const NAME: &'static str;
fn execute<M: TestModel>(matches: &ArgMatches) -> HResult<()>
where
<M::Backend as Backend>::CommonRepr: TryInto<M::Y, Error = HError>;
fn command_args_getter<'a, 'b>() -> App<'a, 'b>;
}
pub fn command_handle<C, M>(model_name: &str, matches: &ArgM... | Rust | 0 |
per',
# The font size ('10pt', '11pt' or '12pt').
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
# 'preamble': '',
# Latex figure (float) alignment
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, ... | Python | 1 |
[API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [channel](channel) module"]
pub type CHANNEL = crate::Reg<u32, _CHANNEL>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CHANNEL;
#[doc = "`read()` method returns [channel::R](channel::R) reader structure"]
impl ... | Rust | 0 |
ed => ack.not_authorized(),
_ => ack.service_unavailable(),
}
}
}
impl<Io, St> MqttResponse<v5::Handshake<Io>, v5::HandshakeAck<Io, St>> for ServerError {
fn ack(&self, ack: v5::Handshake<Io>) -> v5::HandshakeAck<Io, St> {
match self {
Self::AuthenticationFailed => {
... | Rust | 0 |
"ExecuteTimeStatistic" => AiNode::ExecuteTimeStatistic(Box::new(AiExecuteTimeStatistic::new(&__js)?)),
"ChooseTarget" => AiNode::ChooseTarget(Box::new(AiChooseTarget::new(&__js)?)),
"KeepFaceTarget" => AiNode::KeepFaceTarget(Box::new(AiKeepFaceTarget::new(&__js)?)),
... | Rust | 0 |
volume = (volume.load().await * update) / 100u32;
player.volume_update_log(scaled_volume).await;
}
update = volume_stream.select_next_some() => {
*volume.write().await = update;
scaled_volume = (update * volume_scale.load().awai... | Rust | 0 |
y['loss'], label="training")
fig_2.plot(result.history['val_loss'], label="validation")
f = open('myfile.txt', 'w')
fig_2.set_xlabel('Epochs[times]',fontsize=14)
fig_2.set_ylabel('Loss[-]',fontsize=14)
fig_2.legend(loc='upper left')
fig.savefig('fig/loss/'+path_r+'_loss.eps', bbox_inches="tight"... | Python | 1 |
pub fn slow_mode_delay_expires_in(&mut self, slow_mode_delay_expires_in: f32) -> &mut Self {
self.inner.slow_mode_delay_expires_in = slow_mode_delay_expires_in;
self
}
pub fn can_get_members(&mut self, can_get_members: bool) -> &mut Self {
self.inner.can_get_members = can_get_members;... | Rust | 0 |
type Target = PendingResolve;
fn deref(&self) -> &Self::Target {
&self.pending_resolve
}
}
impl Serialize for ResolveStat {
fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
let mut map = serializer.serialize_map(None)?;
map.serialize_... | Rust | 0 |
<Option<Value>> {
let request_id = self.request_counter;
self.request_counter += 1;
let request = Message::make_request(method, params, Some(request_id.into()));
self.channel.send_frame(request).await?;
let message = self.channel.receive_frame().await?;
if message.versi... | Rust | 0 |
stribution_named.JointDistributionNamed
jdsequential = joint_distribution_sequential.JointDistributionSequential
# Use an autobatched JD if a specific batch rank was requested.
if batch_ndims is not None:
jdnamed = functools.partial(
joint_distribution_auto_batched.JointDistributionNamedAutoBatched,
... | Python | 1 |
"""Add discovery_metadata table for tracking discovery operations
Revision ID: 004
Revises: 003
Create Date: 2025-01-13 10:00:00.000000
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '004'
down_revision = '003'
branch_labels = None
depends_on = None
def upgr... | Python | 1 |
ositions and normals. The normals are *not* normalized, since that is done most
/// efficiently on the GPU.
pub mesh: PosNormMesh,
// Used to map back from voxel stride to vertex index.
stride_to_index: Vec<u32>,
}
impl HeightMapMeshBuffer {
/// Clears all of the buffers, but keeps the memory allo... | Rust | 0 |
reeifaddrs, ifaddrs, sockaddr, sockaddr_in6, AF_INET, AF_INET6};
use data::*;
pub fn load_average() -> io::Result<LoadAverage> {
let mut loads: [f64; 3] = [0.0, 0.0, 0.0];
if unsafe { getloadavg(&mut loads[0], 3) } != 3 {
return Err(io::Error::new(io::ErrorKind::Other, "getloadavg() failed"))
}
... | Rust | 0 |
result_code, stdout, stderr = get_main_output(
[
"--podman",
"--outdir",
str(tmp_path),
get_data("tests/secondary-files-required-container.cwl"),
]
)
assert result_code == 0, stderr
assert (
json.loads(stdout)["output"]["secondaryFiles... | Python | 1 |
from spatula import JsonPage, URL, HtmlPage, CSS, XPath
from openstates.models import ScrapePerson
import re
class LegDetail(HtmlPage):
def process_page(self):
p = self.input
title_lst = CSS("h5").match_one(self.root).text_content().strip().split("\n")
title = title_lst[0].strip()
... | Python | 1 |
_SQRT is undefined
u05::sqrtf(d)
}*/
}
pub fn nextafterf(x: F32x, y: F32x) -> F32x {
let x = x.eq(ZERO).select(ZERO.mul_sign(y), x);
let mut xi2 = I32x::from_bits(x);
let c = x.is_sign_negative() ^ y.ge(x);
xi2 = c.select(I32x... | Rust | 0 |
probably be configurable
// Tantivy buffer of 100MB that will be split between indexing threads.
let mut index_writer = index.writer(100_000_000)?;
// FIXME: tantivy DocId is incremental so this creates duplication on each run
// see also https://docs.rs/tantivy/0.15.0/tantivy/type.DocId.html
... | Rust | 0 |
import random
import string
def generar_contrasena(longitud, mayusculas, minusculas, numeros, simbolos):
caracteres = ''
if mayusculas:
caracteres += string.ascii_uppercase
if minusculas:
caracteres += string.ascii_lowercase
if numeros:
caracteres += string.digits
if simbolo... | Python | 1 |
()));
if let Some(n) = config.demo {
tracing::info!("Simulating {} dummy sensors", n);
sources.push(Box::new(dummy_sensors(0..u128::from(n.get()))));
}
let update_task = task::spawn(tasks::update(ctx.clone(), stream::select_all(sources)));
if let Some(ref options) = config.mqtt_options... | Rust | 0 |
eturn_val)
}
fn fs_write(&self) -> Result<(), io::Error> {
let mut y = "".to_string();
let mut file = File::open(self.path.clone())?;
let mut contents = String::new();
file.read_to_string(&mut contents)?;
let replaced = contents
.replace("\n", "\n(*)")
... | Rust | 0 |
assert_eq!(vec![env.attack, env.decay, env.sustain, env.release], vec![10, 5, 20, 10])
}
}
<gh_stars>1-10
#![allow(dead_code)]
pub type Octet = u32;
// Mask for keeping octets as 3 bytes.
const OCTET_MASK: u32 = 0x00FF_FFFF;
pub type Sextet = u32;
// Mask for keeping sextets as 6 bits.
const SEXTET_MASK: u32 = ... | Rust | 0 |
import torch
import torch.nn as nn
torch.set_default_dtype(torch.float)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class WaveAct(nn.Module):
"""Full PINN Activation Function"""
def __init__(self, a1, a2):
super(WaveAct, self).__init__()
self.w1 = a1.clone().to(device... | Python | 1 |
import numpy as np
from scipy.io import wavfile
from scipy.fftpack import fft
def sineanalyze(file_path, amplitude_threshold=0.05):
"""
Analyze audio file and return main sine wave components
Returns only frequencies with amplitude above threshold, sorted by amplitude
"""
# Read the wav file
sa... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.