text string | label_name string | labels int64 |
|---|---|---|
ng.seed, 25214903917);
rng.set_seed(150123);
assert_eq!(rng.seed, 25215020038);
rng.set_seed(-500);
assert_eq!(rng.seed, 281449761806433);
}
#[wasm_bindgen_test]
fn rng_next_int() {
let mut rng: SimpleRandom = Default::default();
rng.set_seed(0);
assert_eq!(rng.next_int(), 1569741360);
... | Rust | 0 |
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
import abc
import io
from typing import NewType, Optional
from marimo._messaging.mimetypes import ConsoleMimeType
from marimo._types.ids import CellId_t
# A KernelMessage is a bytes object that contains a serialized MessageOperation.
Ke... | Python | 1 |
derer.render_mesh(&points);
if cfg!(feature = "output") {
renderer.write_fb_ppm("target/point_ortho.ppm");
renderer.write_zb_ppm("target/point_ortho_z.ppm");
}
}
#[test]
#[cfg(any(feature = "all", all(feature = "point", feature = "perspective", feature = "nomsaa")))]
fn point_perspective() {
let p: Vec3 = Ve... | Rust | 0 |
&self, m: &'a Message) -> &'a Message {
match self.fns {
FieldAccessorFunctions::SingularHasGetSet {
get_set: SingularGetSet::Message(ref get),
..
} => get.get_message(message_down_cast(m)),
FieldAccessorFunctions::Optional(ref t) => {
... | Rust | 0 |
)
# Wait on EMM Information from MME
self._s1ap_wrapper._s1_util.receive_emm_info()
print("************************* Running UE detach")
# Now detach the UE
detach_req = s1ap_types.uedetachReq_t()
detach_req.ue_Id = ue_req.ue_id
detach_req.ueDetType = (
... | Python | 1 |
(version), align_after(20), align_before(20))]
palette: PaletteV4,
#[br(args(version), parse_with = parse_sprites::<SpriteV4, _>)]
sprites: [ SpriteV4; NUM_SPRITES ],
}
impl From<FrameV4> for Frame {
fn from(old: FrameV4) -> Self {
Self {
script: old.script.into(),
sound... | Rust | 0 |
now();
} else {
messages.send(ListenMessage::new(
"Error while listening for new clients.", err)).unwrap();
return;
}
},
}
match shutdown_recv.try_recv() {
... | Rust | 0 |
RegisterLongName> BaseWriteableRegister<u16> for ReadWrite16C8B32<N> {
type Reg = N;
const REG_WIDTH: usize = 16usize;
#[inline]
fn base_set(&self, value: u16) {
let bytes: [u8; 2usize] = u16::to_be_bytes(value);
self.reg_p0.set(u8::from_be_bytes([bytes[0usize]]));
self.reg_p1.s... | Rust | 0 |
lanceOf<T>,
) -> Option<Nominations<T::AccountId, BalanceOf<T>>> {
// 1. Already nominationsd
if let Some(nominations) = Self::nominators(g_stash) {
//剩余 = 所有活跃的绑定金额-所有担保的金额
//真实的担保 = 最小值(剩余,担保)
//新的所有的担保金额 = 原来的 + 真实的担保
let remains = bonded.saturating... | Rust | 0 |
import numpy as np
import torch
class Between:
def __init__(self, object_locations: torch.Tensor, device='cuda') -> None:
"""
Args:
object_locations: torch.Tensor, shape (N, 6), N is the number of objects in the scene.
The first three columns are the center of the object... | Python | 1 |
xs = [x.strip('\n') for x in open('p3.txt').readlines()]
xs = [x.split(":") for x in xs]
xs = [[x[0], x[1].split(",")] for x in xs]
xs = {x[0]: x[1] for x in xs}
print(xs)
from collections import defaultdict
all_counts = defaultdict(int)
for each in xs.keys():
counts = defaultdict(int)
counts[each] = 1
... | Python | 1 |
#
# Copyright 2024 The InfiniFlow 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... | Python | 1 |
import re
from typing import Type
from django.contrib.auth import get_user_model
User: Type = get_user_model()
def get_profile_id_from_user(instance):
if hasattr(instance, 'doctor_profile'):
return instance.doctor_profile.id
if hasattr(instance, 'patient_profile'):
return instance.patient_pr... | Python | 1 |
essage type defines the configuration of creating
/// a backup from this BackupPlan
#[derive(Clone, PartialEq, ::prost::Message)]
pub struct BackupConfig {
/// A boolean flag specifies whether volume data should be backed up
#[prost(bool, tag="4")]
pub include_volume_data: bool,
... | Rust | 0 |
get peptide list csv file %s" % filename)
reader = csv.reader(open(filename), dialect ='excel-tab')
v= [ row[0] for row in reader if row ]
print("...done.")
return v
def removeModifications(peptides) :
peptide_output = []
for peptide in peptides :
while peptide.find('[') ... | Python | 1 |
# Copyright 2021 The Bellman Contributors
#
# 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... | Python | 1 |
from aiogram.types import BotCommand
base_commands = [
BotCommand(command='/start', description='Запуск бота'),
BotCommand(command='/show_items', description='Показать предметы'),
]
| Python | 1 |
i][j]), end="\t")
print()
end_count = 0
for i in range(19):
for j in range(15):
if field[i][j] == "*":
if output_field[i - 1][j - 1] == chr(128681):
end_count += 1
if win:
print("Вы разминировали поле.")
... | Python | 1 |
os = *best_position(&map);
println!("{:?}", detected_asteroids(&map, &pos).len());
let vaporized200th = vaporize(map, &pos, 200);
println!("{:?}", vaporized200th.x * 100 + vaporized200th.y);
}
#[derive(Debug)]
pub struct Point {
pub x: u32,
pub y: u32,
}
impl Point {
pub fn get_points<const N:... | Rust | 0 |
match (self.vertex_count, self.face_count) {
(_, Some(f)) => f,
(Some(v), None) => 2 * v,
(None, None) => 0,
}
}
}
/// Returns `true` if both given types are the same type, `false` otherwise.
///
/// The types are required to be `'static` because comparing lifeti... | Rust | 0 |
L { d, s1, s2 } => I::r(0b0110011, d, 0b101, s1, s2, 0b0000000),
SRA { d, s1, s2 } => I::r(0b0110011, d, 0b101, s1, s2, 0b0100000),
OR { d, s1, s2 } => I::r(0b0110011, d, 0b110, s1, s2, 0b0000000),
AND { d, s1, s2 } => I::r(0b0110011, d, 0b111, s1, s2, 0b0000000),
ECALL {... | Rust | 0 |
import sys, os
sys.path.insert(1, os.path.join("..","..",".."))
import h2o
from tests import pyunit_utils
from h2o.estimators.deeplearning import H2ODeepLearningEstimator
def deeplearning_multi():
print("Test checks if Deep Learning works fine with a categorical dataset")
# print(locate("smalldata/logreg/protsta... | Python | 1 |
determine_link(i, e, indexes);
None
}
Expr::Expand(i, e, f) => {
if let Some(f) = f {
assign_links(i, f, indexes);
}
assign_links(i, e, indexes);
Some(i.clone())
}
Expr::Not(e) => determine_link(root_index, e, i... | Rust | 0 |
#!/usr/bin/env python3
# DepGen.py - produce a make dependencies file for Scintilla
# Copyright 2019 by Neil Hodgson <neilh@scintilla.org>
# The License.txt file describes the conditions under which this software may be distributed.
# Requires Python 3.6 or later
import sys
sys.path.append("..")
from scripts import ... | Python | 1 |
fn input_count(&self) -> usize { 0 }
fn output_count(&self) -> usize { 0 }
fn input_id(&self, _ch_id: ReceiverChannelId)
-> Option<(ChannelId, SenderName)> { None }
fn input_channel_pos(&self, _ch_id: ReceiverChannelId)
-> ChannelPosition { ChannelPosition(0) }
fn output_channel_pos(&self, _ch_id: Sende... | Rust | 0 |
raid_times = {
'1': (60, 45),
'2': (60, 45),
'3': (60, 45),
'4': (60, 45),
'5': (60, 45),
'6': (60, 45),
"EX": (None, 45),
'7': (60, 45)
}
egg_images = {
'1': 'https://raw.githubusercontent.com/ZeChrales/PogoAssets/master/static_assets/png/ic_raid_egg_normal.png',
'2': 'https://... | Python | 1 |
m RGB to BGR, or vice versa. Note that this will trigger a conversion of
`image` to a NumPy array if it's a PIL Image.
Args:
image (`PIL.Image.Image` or `np.ndarray` or `torch.Tensor`):
The image whose color channels to flip. If `np.ndarray` or `torch.Tensor`, the channel di... | Python | 1 |
TION_FEATURE_DISABLE_UNIQUE_HANDLES_EXT = 6,
}
}
enumeration! {
/// [VkIndirectCommandsTokenTypeNV](https://www.khronos.org/registry/vulkan/specs/1.2-extensions/man/html/VkIndirectCommandsTokenTypeNV.html)
VkIndirectCommandsTokenTypeNV {
VK_INDIRECT_COMMANDS_TOKEN_TYPE_SHADER_GROUP_NV = 0,
VK_INDIRECT_CO... | Rust | 0 |
connection_settings(
&mut object_2229,
var_2228,
)?;
object_2229.finish();
}
if let Some(var_2230) = &input.cross_zone_load_balancing {
let mut object_2231 = object.key("CrossZoneLoadBalancing").start_object();
crate::json_ser::serialize_structure_crate_mo... | Rust | 0 |
e()
return render(request, 'payment_success.html')
except:
payment.success = False
payment.save()
return render(request, 'payment-fail.html')
"""
def payment_success(request):
return render(request, 'payment_success.html')
def payment_failure(request):
re... | Python | 1 |
Map,
env,
sync::Arc,
},
semver::Version,
crate::{
ContentItem,
Menu,
MenuItem,
attr::{
Color,
Params,
},
},
};
/// A type-safe handle for [SwiftBar](https://swiftbar.app/)-specific features.
///
/// Some SwiftBar-specific f... | Rust | 0 |
(),
}}
STRUCT!{struct D3D10_TECHNIQUE_DESC {
Name: LPCSTR,
Passes: UINT,
Annotations: UINT,
}}
RIDL!{#[uuid(0xdb122ce8, 0xd1c9, 0x4292, 0xb2, 0x37, 0x24, 0xed, 0x3d, 0xe8, 0xb1, 0x75)]
interface ID3D10EffectTechnique(ID3D10EffectTechniqueVtbl) {
fn IsValid() -> BOOL,
fn GetDesc(
pDesc: *mut... | Rust | 0 |
import torch
import torch.nn as nn
import tkinter as tk
from sentence_transformers import SentenceTransformer
# Set device
device = "mps" if torch.backends.mps.is_available() else "cpu"
# Load sentence transformer
llm = SentenceTransformer('thenlper/gte-large', device=device)
# Define the Decoder model
class Decoder... | Python | 1 |
# Strong Number (Special Numbers Series #2)
def factorial(n):
fact=1
for i in range(1,n+1):
fact*=i
return fact
def strong_num(number):
s = str(number)
suma = 0
for i in s:
suma += factorial(int(i))
if suma == number:
return "STRONG!!!!"
else:
return "No... | Python | 1 |
replace('_', " "), move |b| {
b.iter(|| {
for x in v.chunks($N) {
s += $SLICE_FUN(x);
}
s
})
});
}
fn $TUPLE_WINDOWS(c: &mut Criterion) {
let v: Vec<u32> = (0..1_0... | Rust | 0 |
import lvgl as lv
history = []
current_page = None # Global variable to track current page
def init(first_page):
global current_page
if current_page:
lv.obj_del(current_page) # Delete previous page if it exists
history.clear() # Clear navigation history
current_page = first_page # Se... | Python | 1 |
ude::*,
},
};
use std::ops::Range;
use std::{
cell::{Ref, RefCell},
ops::{Deref, DerefMut},
};
/// Machine node that plays specified animation.
#[derive(Default, Debug, Visit, Clone)]
pub struct PlayAnimation {
pub base: BasePoseNode,
pub animation: Handle<Animation>,
#[visit(skip)]
pub(cra... | Rust | 0 |
=False, tag="add_flag_window"):
dpg.add_input_text(label="Название нового флага", tag="new_flag_input")
dpg.add_button(label="Сохранить", callback=add_new_flag)
dpg.add_button(label="Отмена", callback=lambda: dpg.configure_item("add_flag_window", show=False))
... | Python | 1 |
# Copyright 2021 Memgraph Ltd.
#
# Use of this software is governed by the Business Source License
# included in the file licenses/BSL.txt; by using this file, you agree to be bound by the terms of the Business Source
# License, and you may not use this file except in compliance with the Business Source License.
#
# As... | Python | 1 |
ັນ', 'ਵੈਟੀਕਨ ਸਿਟੀ', 'བ་ཊི་ཀཱན་ སི་ཊི', '梵蒂岡', 'ویٹِکَن سِٹی', 'fatikáaŋ', 'Vatikaŋ', 'הוותיקן', 'වතිකානු නගරය', 'Vaticaanstad', 'バチカン市国', 'Dowla Waticaan', 'Lata Vatikan', 'Sveta Stolica', 'watikáŋ', 'Vatikaŋ Ɓoloe', 'Vaticano', 'Vatikanbýur', 'व्हॅटिकन सिटी', 'นครวาติกัน', 'Faatikaan', 'Vatikanstad', 'Firenen’i Vatika... | Python | 1 |
== TIM5_BASE) || \
((*(uint32_t*)&(PERIPH)) == TIM6_BASE) || \
((*(uint32_t*)&(PERIPH)) == TIM7_BASE) || \
((*(uint32_t*)&(PERIPH)) == TIM8_BASE))
*/
pub use crate::device::tim1::ccmr1_output::CC1MW as OCMode... | Rust | 0 |
n::downcast::*;
/// V(),
pub struct GraphVertexStep {
pub symbol: StepSymbol,
pub params: QueryParams<Vertex>,
src: Option<ArrayQueue<Vec<ID>>>,
as_labels: Vec<String>,
requirement: Requirement,
}
impl_as_any!(GraphVertexStep);
impl GraphVertexStep {
pub fn new(req: Requirement) -> Self {
... | Rust | 0 |
);
temp_str.clear();
continue;
}
is_find_str = true;
temp_str.push(item);
continue;
}
if is_find_str {
temp_str.push(item);
continue;
}
if item != '`' && item != '\'' && is_token == fa... | Rust | 0 |
h secret_or_key {
SecretOrKey::Secret(key) => {
let ring_alg = alg.into();
let digest = hmac::sign(&hmac::Key::new(ring_alg, &key), message.as_bytes());
Ok(b64_encode(digest.as_ref()))
},
_ => Err(Error::InvalidInput(ErrorDetails::new("Missing secret for HMAC ... | Rust | 0 |
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
INFIFO_FULL_CH1_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for INFIFO_FULL_CH1_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = ... | Rust | 0 |
for i in 0..self.parameters.len() {
if i < self.parameters.len() - 1 {
s.push_str(&(self.parameters[i].to_string()));
s.push_str(",");
} else {
s.push_str(&(self.parameters[i].to_string()));
}
}
s.push_str("]}")... | Rust | 0 |
stats = self.wallet_stats[wallet]
# Calculate posterior parameters
posterior_alpha = self.prior_alpha + stats.wins
posterior_beta = self.prior_beta + stats.losses
# For Beta distribution, we can use the quantile function
# Approximation using Wilson score inter... | Python | 1 |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: MIT. See LICENSE
import frappe
def execute():
frappe.reload_doc("core", "doctype", "system_settings", force=1)
frappe.db.set_single_value("System Settings", "password_reset_limit", 3)
| Python | 1 |
}
}
pub fn with_timeout_minutes(mut self, timeout_minutes: u32) -> Step {
self.timeout_minutes = Some(timeout_minutes);
self
}
}
impl Step {
#[allow(dead_code)]
pub fn env(mut self, name: &str, value: &str) -> Self {
self.env.push((name.to_owned(), value.to_owned()))... | Rust | 0 |
is the callers responsibility to ensure that the grapheme at point start
// has the same size as new_char.
pub fn replace(&mut self, start: usize, new_char: char) {
assert!(start + new_char.len_utf8() <= self.len);
// This is pretty wasteful in that we're allocat... | Rust | 0 |
from typing import List
class Solution:
def minExtraChar(self, s: str, dictionary: List[str]) -> int:
words = set(dictionary)
dp = {len(s): 0}
def dfs(i):
if i in dp:
return dp[i]
res = len(s) - i
res = 1 + dfs(i+1)
for j in ra... | Python | 1 |
ect to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
pub mod flac;use super::*;
use crate::svd::{
Field, ModifiedWriteValues, ReadAction, Register, RegisterInfo, RegisterProperties,
WriteConstr... | Rust | 0 |
> Self {
self.endowed_accounts = endowed_accounts;
self
}
pub fn one_hundred_for_alice_n_bob(self) -> Self {
self.balances(vec![(TEST_TOKEN_ID, ALICE, 100), (TEST_TOKEN_ID, BOB, 100)])
}
pub fn build(self) -> sp_io::TestExternalities {
let mut t = frame_system::GenesisC... | Rust | 0 |
64 = (index as u64).wrapping_mul(relative_prime);
key = key ^ (key >> 16);
// Don't add keys which are 0 or 1
if key >= 2 {
// Map is empty, we should only have None here:
if let Some(_old) = map.insert(key, key) {
panic!("HashMap value found which should... | Rust | 0 |
inate().await;
Ok(())
}
}
<filename>src/algorithm/quick_sort.rs
use std::cmp::Ord;
use std::mem;
use slice::Slice;
use index::Index;
use super::insertion_sort;
const QSORT_THRESHOLD: usize = 16;
pub fn sort<T: Ord>(slice: &mut Slice<T>) {
if slice.len() < QSORT_THRESHOLD {
return insertion_... | Rust | 0 |
td><td>huì tán</td><td>talks; conversation</td></tr><tr><td>348</td><td>活力</td><td>huólì</td><td>energy; vigor</td></tr><tr><td>349</td><td>活泼</td><td>huópō</td><td>lively</td></tr><tr><td>350</td><td>火柴</td><td>huǒchái</td><td>Match</td></tr><tr><td>351</td><td>火腿</td><td>huǒ tuǐ</td><td>ham</td></tr><tr><td>352<... | Python | 1 |
e in subtyping,
these two orders would demand opposite relationships between `D` and `CC_arg`.
So, we have this negative/positive distinction. Consider:
Nat (Int => String) => (∀X ⇒ X)
If you count how many negations each type is under,
you get a picture of the inputs and outputs of the type at a high level.
So,... | Rust | 0 |
conn("POSTGRES") as conn:
board_model_df = pd.read_sql(f"""
SELECT
primary_key
,board_type
,price_limit_rate
... | Python | 1 |
return Err(anyhow!(
"Right check failed: {:?}, {:?}",
(t.id, i),
(index, at.id)
));
}
}
}
}
Ok(())
}
#[cfg(test)]
mod tests {
// Note this useful idiom: importing names f... | Rust | 0 |
actions[robot_index,5].cpu().detach().numpy(),
"actions6": actions[robot_index,6].cpu().detach().numpy(),
"actions7": actions[robot_index,7].cpu().detach().numpy(),
"actions8": actions[robot_index,8].cpu().detach().numpy(),
"actions9": acti... | Python | 1 |
# configs/settings.py - 全局静态配置文件
from dotenv import load_dotenv
import os
import json
from pathlib import Path
# --- 从 .env 文件加载敏感信息到环境变量 ---
# 这使得我们可以通过 os.getenv("...") 来安全地获取密钥
load_dotenv()
# 项目根目录
ROOT_DIR = Path(__file__).parent.parent
# --- 日志配置 ---
LOG_LEVEL = "INFO" # 可选: "DEBUG", "INFO", "WARNING", "ERRO... | Python | 1 |
;
assert_eq!(1, snapshot_history.len());
assert_eq!(0u64, state_snapshot_repository.load_latest(&shard_id).unwrap());
assert_eq!(1, file_io.get_states_for_shard(&shard_id).unwrap().len());
}
#[test]
fn revert_to_removes_version_newer_than_target_hash() {
let shard_id = ShardIdentifier::random();
let (file... | Rust | 0 |
ertools::Itertools;
use lazy_static::lazy_static;
lazy_static! {
static ref DEBUG: bool = std::env::var("MKT_DEBUG").is_ok();
static ref DEBUG_IMG: bool = std::env::var("MKT_DEBUG_IMG").is_ok();
}
const DEFAULT_ITEM_WIDTH: u32 = 160;
const DEFAULT_ITEM_HEIGHT: u32 = 200;
const DEFAULT_ITEM_RATIO: f32 = DEFAUL... | Rust | 0 |
EH5BzpfHkn8+M6f9pzh+qzORZis9QuCs6N9Ir1j9GAME4g\/ZwgAI5g\nrBhxy2FRM5I39OLMv92cAu495ctERKshXKUJM0jJQvT7p\/Vy3KWeETTcJIeLWTrjZzaEQghAC+vR\nHuQXmLExI\/Yeb7KJmeDjv9YsyoSfOUJ6coGC1DQQ9ODrz2mANtUqoavwkiXPYq8DF0hIXOaEc6N8\nKd38e8z+cUqt2mI0jCnP9lUVMf1z7f1CgqLl2WnEjldFm3rkvKrgf\/k\/0fZm7Qc1VnrGFqYEoySQ\naQfBWdCZiowGnTg6JuJcoa3mM... | Python | 1 |
"""
This script can be used to check the effect of the power excursions effect
in the EDFA class.
It will model a linear topology with the params specified below and launch
a transmission with as many signals as indicated in signal_no (see below).
wdg1 will increase the average gain of the EDFAs, ... | Python | 1 |
ar
# 构建完整日期
try:
month = int(date[:2])
day = int(date[2:])
target_date = datetime(year, month, day)
except ValueError:
return {
"status": "error",
"message": "日期格式无效,应为MMDD格式,例如0113表示1月13日"
}... | Python | 1 |
nt),type(ctx.comment_content),tag.start,tag.end)
comment = ctx.comment_content[commenttag.start:commenttag.end].replace(r'--',r'-−')
fdest.write(comment)
fdest.write('\n%s\n' % (COMMENT_NOTE_END,))
ctx.pos = insert_pos
else:
srctags = tag.childs()
commenttags = ... | Python | 1 |
49) pkcs(1) pkcs-9(9) 3 }
id-messageDigest OBJECT IDENTIFIER ::= { iso(1) member-body(2)
us(840) rsadsi(113549) pkcs(1) pkcs-9(9) 4 }
id-signingTime OBJECT IDENTIFIER ::= { iso(1) member-body(2)
us(840) rsadsi(113549) pkcs(1) pkcs-9(9) 5 }
id-countersignature OBJECT IDENTIFIER ::= { iso(1) member-b... | Rust | 0 |
] for slot in slots_athos])
slot_athos12_start_date = slot1_athos.start_datetime
slot_athos12_end_datetime = slot2_athos.end_datetime
(slot1_athos + slot2_athos).undo_split_shift(slot_athos12_start_date, slot_athos12_end_datetime, slot1_athos.resource_id)
self.assertFalse(slot2_athos.exi... | Python | 1 |
up)
seq_group_meta, out = schedule_and_update_computed_tokens(scheduler)
assert set(get_sequence_groups(out)) == set(running)
# To partially prefill both sequences, both can chunk up to 30 tokens
# But the next lowest multiple of the block size (4) is 28
assert seq_group_meta[0].token_chunk_size ==... | Python | 1 |
например, в <div class="c-bibliographic-information__value">)
pages_elem = soup.select_one("div.c-bibliographic-information__value")
if pages_elem:
pages_text = pages_elem.text.strip()
pages_match = re.search(r"(\d+\s*[-–]\s*\d+)", pages_text)
page... | Python | 1 |
from typing import List, Union, Literal
def coin_exchange(coins: List[int], amount: int) -> Union[int, Literal[-1]]:
if amount < 0:
return -1
if amount == 0:
return (0, [])
dp = [float('inf')] * (amount + 1)
dp[0] = 0
coin_used = [-1] * (amount + 1)
for i in range(1, amount + ... | Python | 1 |
n redirect(url_for('auth.login', error='Error logging in: {}'.format(e)))
#incorrect username or password
else:
#if login fails, redirect back to login page with an error message and flash a message saying login failed
flash('Invalid username or password', 'error')
#i... | Python | 1 |
efinition:
- TP: Matches of connections are True Positive
- FP: Mismatches are False Positive,
- TN: Matches for non-existing synapses are True Negative
- FN: mismatches are False Negative.
"""
if not np.all(np.isin([-1, 0, 1], np.unique(estimate))):
estimate = classify_c... | Python | 1 |
);
assert_eq!(
unsafe { &(*(::std::ptr::null::<sctp_paddrparams>())).spp_pathmtu as *const _ as usize },
136usize,
concat!(
"Offset of field: ",
stringify!(sctp_paddrparams),
"::",
stringify!(spp_pathmtu)
)
);
assert_eq!(
... | Rust | 0 |
s sent by the client or browser as the origin of the request. It is set through an `Origin` header. * **Access-Control-Allow-Methods**: This specifies the allowed options for requests from that domain. This will generally be all available methods. * **Access-Control-Expose-Headers**: This will contain the headers t... | Python | 1 |
import sqlite3
import os
def create_database(db_path):
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# footfall
cursor.execute('''
CREATE TABLE IF NOT EXISTS footfall_data (
Id INTEGER PRIMARY KEY,
Date TEXT,
SiteName TEXT,
LocationName TEXT,
Locati... | Python | 1 |
# print("keep alive!")
sendMessage(connectionId, "__pong__")
else:
print('connectionId: ', connectionId)
print('routeKey: ', routeKey)
jsonBody = json.loads(body)
print('request body: ', json.dump... | Python | 1 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) Huawei Technologies Co., Ltd. 2024. 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/li... | Python | 1 |
tiplication operator `x * y`.
Mul,
/// The division operator `x / y`.
Div,
/// The modulus operator `x % y`.
Mod,
/// The power operator `x ** y`.
Pow,
/// The equality operator `x == y`.
Eq,
/// The inequality operator `x != y`.
Neq,
/// The less-than operato... | Rust | 0 |
uct GistFile {
filename: String,
truncated: bool,
content: String,
}
}
static USER_AGENT: &str = "cargo-scripts <https://github.com/qryxip/cargo-scripts>";
fn raise_synthetic_error(res: &Response) -> anyhow::Result<()> {
if let Some(err) = res.synthetic_error() {
let mut err = ... | Rust | 0 |
r_items: Vec<Item>,
#[serde(rename = "HandDropChances")]
pub hand_drop_chances: Vec<f32>,
#[serde(rename = "ArmorDropChances")]
pub armor_drop_chances: Vec<f32>,
#[serde(rename = "DeathLootTable")]
pub death_loot_table: Option<String>,
#[serde(rename = "DeathLootTableSeed")]
pub death_lo... | Rust | 0 |
from math import sin
import numpy as np
import pygame
from pharmacontroller import PharmaScreen
size = 48
vertices = (
np.array(
[
[-1, -1, -1],
[1, -1, -1],
[1, 1, -1],
[-1, 1, -1],
[-1, -1, 1],
[1, -1, 1],
[1, 1, 1],
... | Python | 1 |
import pandas as pd
import matplotlib.pyplot as plt
def best_movies(file_path='tmdb-movies.csv'):
# Read the CSV file into a DataFrame
df = pd.read_csv(file_path)
# Sort DataFrame by revenue in descending order
sorted_df = df.sort_values(by='revenue', ascending=False)
# Access the top 10 movies b... | Python | 1 |
,
) -> Option<StaleFile>
where
I: IntoIterator,
I::Item: AsRef<Path>,
{
let reference_mtime = match paths::mtime(reference) {
Ok(mtime) => mtime,
Err(..) => return Some(StaleFile::Missing(reference.to_path_buf())),
};
for path in paths {
let path = path.as_ref();
let... | Rust | 0 |
present("sprites"),
path: PathBuf::from(path),
};
let mut gameboy = Gameboy::new(cartridge, &config);
let savestate_path = Path::new(path).with_extension("state");
if let Ok(buffer) = fs::read(savestate_path) {
gameboy
.load_savestate(buffer)
.unwrap_or_else(|_| ... | Rust | 0 |
doc["file_metadata"]["original_filename"],
"file_type": rag_doc["file_metadata"]["file_type"],
"folder_id": rag_doc["folder_id"]
}
chunks = self.chunker.chunk_text(processed_text, chunk_metadata)
if not chunks:
... | Python | 1 |
import pickle
with open(r"D:\CAD数据集\j1.0.0\joint\j1.0.0_preprocessed\j1.0.0_preprocessed\val.pickle", "rb") as f:
data = pickle.load(f)
print(data.keys())
print("data[files]: ",data["files"][1] )
print("data[original_file_count]: ",(data["original_file_count"] ) ) # data["graphs"] 是一个list
print("------------... | Python | 1 |
# Copyright 2017 The TensorFlow 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 applica... | Python | 1 |
from_percent(100),
strategies: Default::default(),
};
Vault::do_create_vault(Deposit::Existential, config.try_into_validated().unwrap()).unwrap()
}
/// Creates a market with the given values and initializes some state.
//
/// State initialized:
///
/// - Price of the `borrow_asset` is set to `NORMALIZED::ONE`
///... | Rust | 0 |
apsed();
// // let start = Instant::now();
// // // let proof = Proof::read(&proof_vec[..]).unwrap();
// // // Check the proof
// // total_verifying += start.elapsed();
// // }
// // let proving_avg = total_proving / SAMPLES;
// // let proving_avg =
// // proving_av... | Rust | 0 |
#!/usr/bin/env python3
"""
Hulk v3
This module contains the Enums used in Hulk.
"""
# pylint: disable=duplicate-code
from enum import IntEnum
class ServerCommands(IntEnum):
"""
The different commands sent by Hulk Server.
"""
#: Kill the Bot.
TERMINATE: int = -1
#: Stop the attack and go to ... | Python | 1 |
from microdot_asyncio import Microdot, Response, send_file
from microdot_utemplate import render_template
from microdot_asyncio_websocket import with_websocket
from bme_module import BME280Module
import sh1106
from powerLab import POWERlab
from machine import Pin, I2C, ADC
import ujson
from boot import do_connect
ZER... | Python | 1 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
/start: баннер + канонический текст + кнопка «НАЧАТЬ РЕГИСТРАЦИЮ».
Вступление жирным в одной строке: «…познакомиться поближе. После чего Вам будут доступны:»
"""
import os
from aiogram import types
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton, ... | Python | 1 |
}
fn parse_vect_2d(i: &[u8]) -> IResult<&[u8], Vect2D> {
let (i, x) = parse_f64(i)?;
let (i, y) = parse_f64(i)?;
Ok((i, Vect2D(x, y)))
}
fn parse_point_3d(i: &[u8]) -> IResult<&[u8], Point3D> {
let (i, x) = parse_f64(i)?;
let (i, y) = parse_f64(i)?;
let (i, z) = parse_f64(i)?;
Ok((i, Poin... | Rust | 0 |
allback {
function: command_post,
parameters: &[],
},
command: "post",
help: Some("Post to cloud"),
},
&menu::Item {
item_type: menu::ItemType::Callback {
function: command_panic,
parameters: &[],
},
command: "panic",
help: Some("Deliberately crash"),
},
&menu::Item {
ite... | Rust | 0 |
}<gh_stars>1-10
// wengwengweng
use std::collections::HashMap;
use super::Texture;
// TODO: is there a way to use &dyn Into<UniformValue>?
pub type UniformValues<'a> = HashMap<&'static str, &'a dyn IntoUniformValue>;
pub trait IntoUniformValue {
fn into_uniform(&self) -> UniformValue;
}
impl IntoUniformValue for U... | Rust | 0 |
[5] >> 1) as u8;
r[idx+8] = ((t[5] >> 9) | (t[6] << 2)) as u8;
r[idx+9] = ((t[6] >> 6) | (t[7] << 5)) as u8;
r[idx+10] = (t[7] >> 3) as u8;
idx += 11
}
}
}
#[cfg(not(feature="kyber1024"))]
{
let mut t = [0u16; 4];
let mut idx = 0usize;
for i ... | Rust | 0 |
e original map are commented,
# considering that the original map has added constraints where
# low(start_plan, ANY) = 0 and low(ANY, end_plan) = 0, meaning that nothing
# comes before start_plan or after end_plan
expected_new_constraints: Dict[
Tuple[STNPlanNode, STNPlanNode... | Python | 1 |
from functools import wraps
from inspect import signature
from .dependency import *
def inject(f):
"""
Decorator that search all Dependency defaults in the decorated function parameters.
Behind the scenes, it will call the inject method to create the desired object in the
corresponding parameter.
... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.