text string | label_name string | labels int64 |
|---|---|---|
x => return Err(EvalError::Unimplemented(format!("cannot cast {:?}", x))),
};
let tmp = param.get("startSet").ok_or(EvalError::Parsing)?.eval()?;
let mut items = match tmp.borrow() {
NixValue::List(x) => x.clone(),
x => return Err(EvalError::Unimplemented(for... | Rust | 0 |
ser::Serialize,
{
self.serialize_inner(value)
}
fn end(self) -> Result<()> {
// nothing to do here
Ok(())
}
}
impl<'a, W: LqWriter> ser::SerializeTupleVariant for &'a mut Serializer<'a, W> {
type Ok = ();
type Error = SLqError;
fn serialize_field<T>(&mut self, val... | Rust | 0 |
}
}
use super::*;
mod block;
mod r#type;
mod type_annotation;
pub use block::*;
pub use r#type::*;
pub use type_annotation::*;
<filename>src/storage/engine/metrics.rs<gh_stars>0
// Copyright 2016 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file excep... | Rust | 0 |
dropout=dropout,
camera_dim=96,
num_resolutions=self.num_resolutions,
layer_scale=layer_scale,
out_dim=out_dim,
kernel_size=kernel_size,
num_prompt_blocks=1,
use_norm=False,
)
self.pos_embed = PositionEmbeddingSine... | Python | 1 |
}
#[doc = "14 - DMA1 Stream3 global interrupt"]
pub struct Dma1Stream3 {
_0: (),
}
unsafe impl Context for Dma1Stream3 {}
unsafe impl Nr for Dma1Stream3 {
#[inline(always)]
fn nr(&self) -> u8 {
14
}
}
#[doc = "15 - DMA1 Stream4 global interrupt"]
pub struct Dma1Stream4 {
_0: (),
}
unsafe im... | Rust | 0 |
slot_hashes: &[SlotHash]) -> Self {
let mut slot_hashes = slot_hashes.to_vec();
slot_hashes.sort_by(|(a, _), (b, _)| b.cmp(a));
Self(slot_hashes)
}
pub fn slot_hashes(&self) -> &[SlotHash] {
&self.0
}
}
impl FromIterator<(Slot, Hash)> for SlotHashes {
fn from_iter<I: Int... | Rust | 0 |
s = "power")]
pub voting_power: vote::Power,
/// Validator proposer priority
pub proposer_priority: Option<ProposerPriority>,
}
impl Info {
/// Return the voting power of the validator.
pub fn power(&self) -> u64 {
self.voting_power.value()
}
/// Verify the given signature against... | Rust | 0 |
t_eq!(Err(ParseError::Json(JsonError::Intersection)), spec)
}
}
<reponame>kulasama/kunit<gh_stars>1-10
extern crate clap;
use std::io;
use clap::{Arg, App, SubCommand};
extern crate oci;
extern crate time;
extern crate file;
mod utils;
fn kunit() -> Result<String, io::Error> {
utils::load_spec();
l... | Rust | 0 |
t_val(...).
'''
val = int((voltage+5.)/10*2**16)
if val < 0 or val >= 2**16:
logging.error("{:s}: Value to be set out of range.".format(__name__))
return False
else:
return self.set_val(channel,val)
if __name__ == "__main__": #if e... | Python | 1 |
14), 'ESH25'), # Before rollover - still March
(datetime(2025, 3, 15), 'ESM25'), # Rollover day - move to June
(datetime(2025, 3, 21), 'ESM25'), # Actual expiry day - already rolled
(datetime(2025, 3, 22), 'ESM25'), # After expiry - definitely rolled
# T... | Python | 1 |
# -*- coding: utf-8 -*-
__author__ = 'xiaoxiaoming'
from typing import List
def bm(main: str, pattern: str) -> int:
n, m = len(main), len(pattern)
if n <= m:
return 0 if main == pattern else -1
# bc为坏字符位置表
bc = generate_bc(pattern)
# suffix为好后缀匹配的{u*}位置表,prefix为前缀匹配表
suffix, prefix =... | Python | 1 |
, light);
} else if o.geometry == "sphere" {
intersect_sphere(ray, o, light);
}
}
if ray.hit == true && ray.reflect == 0 {
ray.color.r = ray.hit_color.r;
ray.color.g = ray.hit_color.g;
ray.color.b = ray.hit_color.b;
... | Rust | 0 |
gain! ")
if choice == 'Vulpix':
trainer_one_pokemon.append(e)
trainer_two_pokemon.append(f)
else:
trainer_one_pokemon.append(f)
trainer_two_pokemon.append(e)
# Creating the Trainer objects with the given names and pokemon lists
trainer_one = Trainer(trainer_one_pokemon, 3, trainer_one_name)
trainer_two = T... | Python | 1 |
[doc = "*Required features: `\"Win32_Graphics_Direct3D12\"`*"]
pub const D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTRESOURCE: D3D12_MESSAGE_ID = 849i32;
#[doc = "*Required features: `\"Win32_Graphics_Direct3D12\"`*"]
pub const D3D12_MESSAGE_ID_COPYTEXTUREREGION_INVALIDDSTSUBRESOURCE: D3D12_MESSAGE_ID = 850i32;
#[doc ... | Rust | 0 |
<(), InnerError> {
let version = chunk.read_u8()?;
if version != 0 {
return Err(InnerError::UnknownChunkVersion {
chunk_name: "PRNT",
version: version as u32,
});
}
let number_objects = chunk.read_le_u32()?;
log::trace!("... | Rust | 0 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class HbFqPayInfo(object):
def __init__(self):
self._fq_amount = None
self._fq_inst_id = None
self._user_install_num = None
@property
def fq_amount(self):
retur... | Python | 1 |
let res = download_decrypt_params(&req, |buf| {
let _ = file.write_all(buf);
})
.unwrap();
let _ = file.flush();
assert_eq!(res.tail.len(), 10);
// In these particular examples, the 10 tail bytes should match the first 10 bytes of the generated hmac
... | Rust | 0 |
ledger, BlockVersion::MAX, token_id_to_governors, logger);
// Create a valid MintTx signed by the governor.
let mut mint_tx = create_mint_tx(
token_id_1,
&[Ed25519Pair::from(signers[0].private_key())],
1,
&mut rng,
);
assert_eq!(mint_tx_m... | Rust | 0 |
T>
where
T: Resource,
{
type Item = ResMut<'a, T>;
fn borrow(world: &'a World, change_tick: Ticks) -> Self::Item {
world
.resource_storage()
.borrow_mut(&TypeId::of::<T>())
.map(|cell| unsafe { ResMut::new(cell, world.tick(), change_tick) })
.unwrap_... | Rust | 0 |
import base64
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
def encrypt_by_public_key(data: bytes, public_key_base64: str) -> bytes:
public_key_bytes = base64.b64decode(public_key_base64)
public_key = RSA.import_key(public_key_bytes)
cipher = PKCS1_v1_5.new(public_key)
key_size... | Python | 1 |
from re import X
import torch.nn as nn
class CLSTM(nn.Module):
# sample rate and embedding sizes are required model attributes for the HEAR API
sample_rate = 16000
embedding_size = 1024
scene_embedding_size = embedding_size
timestamp_embedding_size = embedding_size
def __init__(self):
... | Python | 1 |
import os
import scanpy as sc
import pandas as pd
os.environ["R_HOME"] = "/home/zw/software/miniforge3/envs/space/lib/R"
import Space
from Space.cons_func import (
run_GraphST,
run_Leiden,
run_MENDER,
run_SCANPY,
run_SEDR,
run_SpaceFlow,
run_SpaGCN,
run_STAGATE,
run_stGCL,
run_s... | Python | 1 |
from setuptools import setup, find_packages
with open('requirements.txt') as f:
required = f.read().splitlines()
setup(
name="operator_app",
version="0.1.0",
packages=find_packages(where="src"),
package_dir={"": "src"},
install_requires=[
'annotated-types==0.6.0',
'anyio==4.3.0... | Python | 1 |
import os
from tree_sitter import Language, Parser
from pathlib import Path
cwd = Path(__file__).resolve().parent.absolute()
# clone tree-sitter if necessary
if not (cwd / "vendor/tree-sitter-c/grammar.js").exists():
os.system(
f'git clone https://github.com/tree-sitter/tree-sitter-c.git {cwd / "vendor/t... | Python | 1 |
## Parameters
///
/// This function has no parameters.
///
/// ## Return value
///
/// Returns the identity matrix.
///
/// ## Reference
///
/// <https://docs.microsoft.com/en-us/windows/win32/api/directxmath/nf-directxmath-XMMatrixIdentity>
#[inline]
pub fn XMMatrixIdentity() -> XMMATRIX
{
unsafe {
let mu... | Rust | 0 |
from openpilot.tools.lib.openpilotcontainers import OpenpilotCIContainer
def get_url(*args, **kwargs):
return OpenpilotCIContainer.get_url(*args, **kwargs)
def upload_file(*args, **kwargs):
return OpenpilotCIContainer.upload_file(*args, **kwargs)
def upload_bytes(*args, **kwargs):
return OpenpilotCIContainer.u... | Python | 1 |
ecific project).
/// This function asks Kakoune to give such override if any.
pub fn request_legacy_initialization_options_from_kakoune(
meta: &EditorMeta,
ctx: &mut Context,
) -> Option<Value> {
let fifo = temp_fifo()?;
ctx.exec(
meta.clone(),
format!(
"lsp-get-server-initia... | Rust | 0 |
enum Spread
{
Int(i32),
Float(f64),
Text(String),
}
fn te4()
{
let row = vec![
Spread::Int(3),
Spread::Text(String::from("blue")),
Spread::Float(10.12),
];
}
fn main()
{
te4();
}
<filename>src/net/mod.rs
use crate::dom::{load_doc_from_buffer, getElementsByTagName, NodeType, Docume... | Rust | 0 |
s:
self.listbox.insert(tk.END, file)
frame = ttk.Frame(self.top)
frame.grid(sticky=tk.EW)
for i in range(4):
frame.columnconfigure(i, weight=1)
button = ttk.Button(frame, text="Create", command=self.click_create)
button.grid(row=0, column=0, sticky=tk.EW,... | Python | 1 |
Visitor<'de>,
{
self.input.get(1).map_or(
Err(de::Error::custom("Expected a struct variant, got nothing")),
|item| {
de::Deserializer::deserialize_struct(
&Deserializer::new(&item.1),
"",
fields,
... | Rust | 0 |
import sqlite3
import os
from typing import Dict, Any, List, Tuple
from .knowledge_base import SimpleKnowledgeBase
from .sql_generator import SimpleSQLGenerator
class SimpleText2SQLAgent:
"""Text2SQL代理"""
def __init__(self, milvus_uri: str = "http://localhost:19530", api_key: str = None):
"""初始化代... | Python | 1 |
emonStatsRequestAttributes>;
impl PokemonStatsRequest {
pub fn get_base_hp(&self) -> u8 {
self.data.attributes.base_hp
}
pub fn get_base_attack(&self) -> u8 {
self.data.attributes.base_attack
}
pub fn get_base_defence(&self) -> u8 {
self.data.attributes.base_defence
}
... | Rust | 0 |
n[0]),
gain - 8 * i32::from(channel.subblock_gain[1]),
gain - 8 * i32::from(channel.subblock_gain[2]),
];
// Likweise, the scalefac_multiplier is constant for the granule. The actual scale is multiplied
// by 4 to combine the two pow2 operations into one by adding the exponents. The sum of ... | Rust | 0 |
;
($x:ident) => {
upgrade_weak!($x, ())
};
}
// JSON messages we communicate with
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
enum JsonMsg {
Ice {
candidate: String,
#[serde(rename = "sdpMLineIndex")]
sdp_mline_index: u32,
},
Sdp {
#[... | Rust | 0 |
"""
Minimal Qt
==========
Minimal PyQt example that displays an image.
`Figure.show()` returns a QWidget that you can use in a Qt app just like any other QWidget!
"""
# test_example = false
# sphinx_gallery_pygfx_docs = 'code'
# import Qt or PySide
from PyQt6 import QtWidgets
import fastplotlib as fpl
import imagei... | Python | 1 |
).map(|j| self[i][j] * other[j]).sum();
}
result
}
}
fn fit_scanner(scanner1: &Vec<Vec4>, scanner2: &Vec<Vec4>, orientation_matrices: &Vec<Mat4>) -> Option<Mat4> {
// Works in scanner1's frame of reference
for &m in orientation_matrices {
let rotated_scanner2: Vec<_> = scanner2.ite... | Rust | 0 |
let mut slice: &str = n;
if slice.chars().next().unwrap_or('_') == '+' {
settings.beginning = true;
slice = &slice[1..];
}
match parse_size(slice) {
Ok(m) => settings.mode = FilterMode::Bytes(m),
... | Rust | 0 |
= [{
'entry_time': first_row['datetime'],
'entry_price': first_row['close'],
'exit_time': last_row['datetime'],
'exit_price': last_row['close'],
'side': 'long',
'synergy_score': 2.0,
'reason_codes': 'Demo',
... | Python | 1 |
func: ScFunc::new(HSC_NAME, HFUNC_PASS_TYPES_FULL),
params: MutablePassTypesFullParams { id: 0 },
};
f.func.set_ptrs(&mut f.params.id, ptr::null_mut());
f
}
pub fn run_recursion(_ctx: & dyn ScFuncCallContext) -> RunRecursionCall {
let mut f = RunRecursio... | Rust | 0 |
vity, WalkSpeed},
},
standard_box::StandardBoxEvent,
};
use bevy::{input::mouse::MouseMotion, prelude::*};
use bevy_mod_raycast::{RayCastMesh, RayCastSource};
use heron::prelude::*;
pub fn walk(
mut velocity_query: Query<&mut Velocity, (With<Player>, With<Strafes>)>,
turn_query: Query<&Turn, With<Playe... | Rust | 0 |
rn df_filtered.hvplot.box(y=y_col, by=x_col if x_col != y_col else None,
height=plot_height, responsive=True,
title=f"Boxplot of {y_col} by {x_col}")
return pn.pane.Markdown("⚠️ Select a valid visualization")
# =================== Reactiv... | Python | 1 |
::Timeout,
Err(Error::InvalidLanguage) => TSTagsError::InvalidLanguage,
Err(Error::InvalidCapture(_)) => TSTagsError::InvalidCapture,
}
}
#[no_mangle]
pub extern "C" fn ts_tagger_tag(
this: *mut TSTagger,
scope_name: *const c_char,
source_code: *const u8,
source_code_len: u32,
o... | Rust | 0 |
<dyn std::error::Error>> {
# let filename = "../testdata/full_example.fits[TESTEXT]";
# let mut f = fitsio::FitsFile::open(filename)?;
# let tbl_hdu = f.hdu("TESTEXT")?;
let result: i64 = tbl_hdu.read_cell_value(&mut f, "intcol", 4)?;
assert_eq!(result, 16);
let result: String = tbl_hdu.read_ce... | Rust | 0 |
(&[0.0, 1.0, 1.0], 2f64.ln(), 1e-15, entropy);
test_almost(&[1.0, 1.0, 1.0], 3f64.ln(), 1e-15, entropy);
test_almost(&vec![1.0; 100], 100f64.ln(), 1e-14, entropy);
test_almost(&[0.0, 0.25, 0.5, 0.25], 1.0397207708399179, 1e-15, entropy);
}
#[test]
fn test_median() {
let medi... | Rust | 0 |
tamente.")
self.tree.insert("", 0, values=(nombre, apellido, documento, obra_social_nombre, numeroafiliado))
self.actualizar_treeview()
ventana.destroy()
self.cargar_paciente() # Recargar la lista de pacientes
except mysql.connector.Error as e... | Python | 1 |
ed = pred[config.TEST.OUTPUT_INDEX]
pred = F.interpolate(
input=pred, size=size[-2:],
mode='bilinear', align_corners=config.MODEL.ALIGN_CORNERS
)
if flip:
flip_img = image.numpy()[:, :, :, ::-1]
flip_output = model(torch.from_numpy(flip_img.copy(... | Python | 1 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Desc : unittest of team
from metagpt.roles.project_manager import ProjectManager
from metagpt.team import Team
def test_team():
company = Team()
company.hire([ProjectManager()])
assert len(company.env.roles) == 1
| Python | 1 |
cation, code
@staticmethod
async def send_verification_email(
db: AsyncSession,
redis: Redis,
user_id: int,
username: str,
email: str,
ip_address: str | None = None,
user_agent: UserAgentInfo | None = None,
country_code: str | None = None,
) -... | Python | 1 |
tiple_paths_in_one_event() {
let events = vec![Event {
tags: vec![
Tag::Path {
path: ospath("one.txt").into(),
file_type: None,
},
Tag::Path {
path: ospath("two.txt").into(),
file_type: None,
},
Tag::FileEventKind(FileEventKind::Any),
],
metadata: Default::default(),
}];
assert_e... | Rust | 0 |
let b = field_chip.load_private(layouter.namespace(|| "load b"), self.b)?;
// Load the constant factor into the circuit.
let constant =
field_chip.load_constant(layouter.namespace(|| "load constant"), self.constant)?;
// We only have access to plain multiplication.
... | Rust | 0 |
{
Arg::with_name("environment_file_path")
.help("Path for JSON containing the environment variables to supply to the bootstrap container in the provisioning ARM template.")
.long("environment-file-path")
.short("e")
.takes_value(true)
.default_value("./environment.json")
}
... | Rust | 0 |
# Copyright (c) 2020 Huawei Technologies Co.,Ltd.
#
# openGauss is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#
# http://license.coscl.org.cn/MulanPSL2
#
# THIS SOFTWARE IS PROVIDED ON AN "AS IS... | Python | 1 |
Err(into_err) => {
remove_bad_snapshot(snap_path);
return Err(into_err);
}
}
Ok(())
}
/// Build snapshot from source volume
pub async fn build_snapshot_from_volume(
&self,
src_vol_id: &str,
snap_id: &str,
... | Rust | 0 |
!("Missing argument '{}'", arg::CONNECTION)))
}
}
}
//! Shared contents between [`crate::battery_conservation`] and [`crate::rapid_charge`].
mod private;
use crate::{acpi_call, Handler};
use std::error::Error;
use try_drop::PureTryDrop;
pub mod enable;
#[doc(hidden)]
#[allow(drop_bounds)]
pub trait Batte... | Rust | 0 |
use mpirs::{comm_rank, num_procs, send, receive, init, finalize};
use mpirs::comm_request::RequestProc;
use mpirs::mpi_comm::MPI_COMM_WORLD;
const TAG: u64 = 42;
#[derive(Debug, Clone, RustcDecodable, RustcEncodable)]
struct Token {
pub val: u64,
}
impl fmt::Display for Token {
fn fmt(&self, f: &mut fmt::For... | Rust | 0 |
@ui.refreshable
async def create(self) -> None:
with ui.card():
with ui.row():
ui.input(label="Name").bind_value(self, "name")
ui.button(on_click=self.new, icon="add").props("flat")
# Inner Edit card is separated into its own method to allow refreshing witho... | Python | 1 |
e5a => 0x16e7a,
0x16e5b => 0x16e7b,
0x16e5c => 0x16e7c,
0x16e5d => 0x16e7d,
0x16e5e => 0x16e7e,
0x16e5f => 0x16e7f,
0x1e900 => 0x1e922,
0x1e901 => 0x1e923,
0x1e902 => 0x1e924,
0x1e903 => 0x1e925,
0x1e... | Rust | 0 |
}
}
// 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::{Context as _, Error},
async_trait::async_trait,
fidl_fidl_test_components as ftest, fidl_fuchsia_io as fio, fuchsia_async... | Rust | 0 |
p_bootstrap::run(([127, 0, 0, 1], 0), vec![])
.await
.unwrap();
tokio::spawn(driver);
let client = reqwest::Client::new();
url.set_port(Some(addr.port())).unwrap();
for info in peer_data {
let _: Option<()> = do_api(url.clone(), "put", info, &client).await.unwrap();
}
url... | Rust | 0 |
;
// Construct a padded copy of the reconstructed frame.
let mut padded_px: [[usize; 2]; 3] = [[0; 2]; 3];
for p in 0..3 {
padded_px[p][0] = (fb_width*64 >> rec.planes[p].cfg.xdec) + 4;
padded_px[p][1] = (fb_height*64 >> rec.planes[p].cfg.ydec) + 4;
}
let mut cdef_frame = Frame {
... | Rust | 0 |
let (window_raw, video_subsystem) = try!{ self.build_hack() };
(std::ptr::Unique::new_unchecked (window_raw), video_subsystem)
};
// create gl context
let gl_context_raw = unsafe {
let gl_context_raw : sdl2_sys::SDL_GLContext
= sdl2_sys::SDL_GL_CreateContext (window_raw.as_ptr());
... | Rust | 0 |
# Copyright 2024 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 |
"error_code": 0,
"text": text
}
else:
data = {
"error_code": resp["error_code"],
"text": resp["error_msg"],
"error": {... | Python | 1 |
nth($color-list, 2) == red;\
\n}"
)
.unwrap(),
"div {\
\n content: false;\
\n content: true;\
\n content: var 1/2 3 4;\
\n content: lit 1/2 3 4;\
\n content: true;\
\n a: 3, 3;\
\n b: 0.5, 0.5;\
\n content: true... | Rust | 0 |
CheckNull};
use opendp::trans::{make_bounded_mean};
use crate::any::AnyTransformation;
use crate::core::{FfiResult, IntoAnyTransformationFfiResultExt};
use crate::util::Type;
use opendp::dist::IntDistance;
#[no_mangle]
pub extern "C" fn opendp_trans__make_bounded_mean(
lower: *const c_void, upper: *const c_void,... | Rust | 0 |
import pytest
from src.hand import Finger
@pytest.fixture
def finger():
return Finger("ring")
@pytest.fixture
def mock_joint(mocker):
def _make_joint(x, y, z):
joint = mocker.Mock()
joint.x = x
joint.y = y
joint.z = z
return joint
return _make_joint
@pytest.ma... | Python | 1 |
y_batch(batch: jt.Var) -> np.ndarray:
"""
Convert a batch of FP32 jt tensors (0.0-1.0) to a NumPy uint8 array (0-255), changing from BCHW to BHWC layout.
Args:
batch (jt.Var): Input tensor batch of shape (Batch, Channels, Height, Width) and dtype jt.float32.
Returns:
(np.ndarray): Outp... | Python | 1 |
"""Task generation and management components for the Arklex framework.
This module provides specialized components for task generation, best practices,
and reusable task management. Each component is designed to handle a specific
aspect of task processing:
1. TaskGenerator
- Generates tasks from objectives and doc... | Python | 1 |
"""Migration for a given Submitty course database."""
def up(config, database, semester, course):
"""
Run up migration.
:param config: Object holding configuration details about Submitty
:type config: migrator.config.Config
:param database: Object for interacting with given database for environme... | Python | 1 |
Tile::Ground
};
self.tiles.insert(pos, tile);
}
}
}
<reponame>Ralith/iced
/*
Copyright (C) 2018-2019 <EMAIL>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the ... | Rust | 0 |
raphs[0]
for op in main_sg.operators:
if 'COMPOSITE' in flatbuffer_utils.opcode_to_name(
q_model, op.opcodeIndex
):
for inp in op.inputs:
tensor = main_sg.tensors[inp]
self.assertNotQuantiezedType(tensor)
for out in op.outputs:
tensor = main_sg.ten... | Python | 1 |
if self.args.wo_da else self.get_prompted_image(image, text_inputs, self.prototype_gather, prompter_gather=prompter_gather)
logits = self.get_logits(prompted_image, text_inputs)[0]
loss = self.loss_function(logits, label)
optimizer.zero_grad()
loss.b... | Python | 1 |
# -*- coding: utf-8 -*-
"""Location: ./tests/unit/mcpgateway/cache/test_resource_cache.py
Copyright 2025
SPDX-License-Identifier: Apache-2.0
Authors: Mihai Criveti
Unit tests for ResourceCache.
"""
# Standard
import asyncio
import time
# Third-Party
import pytest
# First-Party
from mcpgateway.cache.resource_cache i... | Python | 1 |
"""
This is a pure Python implementation of the binary insertion sort algorithm
For doctests run following command:
python -m doctest -v binary_insertion_sort.py
or
python3 -m doctest -v binary_insertion_sort.py
For manual testing run:
python binary_insertion_sort.py
"""
def binary_insertion_sort(collection: list) ... | Python | 1 |
else:
return {}
#------------------------------------------------------------------------------#
# CBS Data Coding Scheme
# TS 23.038, section 5
#------------------------------------------------------------------------------#
_CBSDCSGroup_dict = {
0 : 'Language using the GSM 7 bit default alpha... | Python | 1 |
if (max(timestamps) - min(timestamps)).days >= 3:
when = '%d days' % ((max(timestamps) - min(timestamps)).days)
weekend = [5, 6]
if max(timestamps).weekday() in weekend and min(
timestamps).weekday() in weekend and not (
max(timestamps).weekday() == ... | Python | 1 |
);
terminate(cx, "Ret");
count_insn(cx, "ret");
llvm::LLVMBuildRet(B(cx), V);
}
}
pub fn AggregateRet(cx: block, RetVals: &[ValueRef]) {
if cx.unreachable { return; }
check_not_terminated(cx);
terminate(cx, "AggregateRet");
unsafe {
llvm::LLVMBuildAggregateRet(B(cx),... | Rust | 0 |
T_NOFILE)
# Save closerange until last so that we can still get logs written
# to the endpoint.log. Meanwhile, use the exit_code as a
# last-ditch attempt at sharing "what went wrong where" to the
# parent process.
exit_code += 1
os.closerange(3,... | Python | 1 |
from django.db.models import Sum, Count, Q
from rest_framework import serializers
from apps.sponsors.models import StudentSponsor
from apps.sponsors.serializers import StudentSponsorCreateSerializer
from apps.users.models import CustomUser
from apps.general.service import validate_user
class AmountSerializer(serializ... | Python | 1 |
future use.
# def paste_text(self):
# sources = QApplication.clipboard().text().splitlines()
# invalidSources = ""
# for source in sources:
# if len(source) > 0: # Ignore empty newlines
# if source.startswith('file://'): # Allow pasting multiple files/folders c... | Python | 1 |
fc\x1e]\xc5\xd9IT\x11\x1c\xaazg\
\xd4w\x15\xe7z\xf7\x8f\xf5\x1f\x0c\x5c\xec\xbf9\x8c\xfd\
\xc9\xa39V\x1e\xb9\xa6\xf8\xc3H\xd3\xb557\xde\x11\
\xd4\xfe\xcbq\xd7\xc8f\xccO\xed\xfe\xcf\xe1\xc7\xb5p\
\xc9\xe2\xc7k\x89<5\xe2\xebs\x11\xce\x1c8\xe5\x0f\
f\x1e\xa3\xf9\x8a\xff\x002ia\xb9\xd5\xde\xab\xb7S\
\xfd\x00\xc0`\xf0\xf2\x... | Python | 1 |
ExchangeClient + Send + Sync> AssetsInfo for AssetPrices<T> {
async fn price_at(&self, asset_pair: &AssetPair, time: &DateTime<Utc>) -> Result<f64> {
self.asset_price_at(asset_pair, time).await
}
}
async fn ops_from_fetcher<'a>(
prefix: &'a str,
c: Box<dyn ExchangeDataFetcher + Send + Sync>,
)... | Rust | 0 |
0x01) != 0)
}
#[doc = "Bit 23 - Drive of PIO Line 23"]
#[inline(always)]
pub fn line23(&self) -> LINE23_R {
LINE23_R::new(((self.bits >> 23) & 0x01) != 0)
}
#[doc = "Bit 24 - Drive of PIO Line 24"]
#[inline(always)]
pub fn line24(&self) -> LINE24_R {
LINE24_R::new(((self... | Rust | 0 |
/// pool details used to construct the keyset.
///
/// Example:
/// ```no_run
/// # use jsonwebtokens_cognito::KeySet;
/// # use async_std::prelude::*;
/// # #[async_std::main]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let keyset = KeySet::new("eu-west-1", "my-user-pool-id")?;
/// let verif... | Rust | 0 |
g {
name: "dense_weights"
type: DT_FLOAT
number_attr: "num_dense_features"
}
input_arg {
name: "example_state_data"
type: DT_FLOAT
}
output_arg {
name: "out_example_state_data"
type: DT_FLOAT
}
output_arg {
name: "out_delta_sparse_weights"
type: DT_FLOAT
number_attr: ... | Python | 1 |
f present in `self.audio_formats()`).
/// Value is always 2 for Simple and Extended Type III formats (if present in `self.audio_formats()`).
/// Value is should be 0 for Type IV formats (if present in `self.audio_formats()`).
///
/// Note that there are no Type II formats.
#[inline(always)]
pub const fn audio_sub... | Rust | 0 |
from config import *
from pyrogram import Client, filters
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup
from helper.database import botdata, find_one, total_user, getid
from helper.database import dbcol
from helper.progress import humanbytes
from datetime import datetime, timezone
token = BOT_... | Python | 1 |
oftware.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
/// Error type for the `CreateByteMatchSet` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct CreateByteMatchSetError {
/// Kind of error that occurred.
pub kind: CreateByteMatchSetErrorKind,
/// Additional metadata about the error,... | Rust | 0 |
import numpy as np
from .base_cam import BaseCAM
"""Feature Explanation Method.
Fuad, K. A. A., Martin, P. E., Giot, R., Bourqui, R., Benois-Pineau, J., & Zemmari, A. (2020, November). Features understanding in 3D CNNS for actions recognition in video. In 2020 Tenth International Conference on Image Processing Theory,... | Python | 1 |
]
# paths = find_matching_paths(md_data_path, input_dir_name)
# average_data = calculate_averages(paths, input_dir_name, keys_to_average)
# analysis_folder = "diffusion_-11_-1"
# results = analyze_diffusion_constants(md_data_path, analysis_folder)
# filter_results = find_dc_in_range(
# re... | Python | 1 |
"]
use_dense_topology = False
# use_dense_topology = True
path_to_old_models = '/home/rdanecek/Workspace/mount/scratch/rdanecek/emoca/finetune_deca'
path_to_new_models = '/is/cluster/work/rdanecek/emoca/finetune_deca'
run_files = []
nicks = []
path_to_models = path_to_old_models
for... | Python | 1 |
[cfg_attr(feature = "inline-more", inline)]
fn eq(&self, other: &Rodeo<K, S>) -> bool {
self.strings == other.strings
}
}
compile! {
if #[feature = "serialize"] {
use crate::Capacity;
use core::num::NonZeroUsize;
use hashbrown::hash_map::RawEntryMut;
use serde::{
... | Rust | 0 |
y_http::operation::SerializationError> {
let mut out = String::new();
let mut object = aws_smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_crate_input_update_logger_definition_input(
&mut object,
input,
)?;
object.finish();
Ok(aws_smi... | Rust | 0 |
ENT_BIAS
// exp <<= finfo.MANTISSA_SIZE
// mant &= finfo.MANTISSA_MASK
// return mant | exp
//
//
// def into_float(mant, exp, finfo, is_positive):
// '''Converts a mantissa, exponent, and sign into a float.'''
//
// bits = into_float_bits(mant, exp, finfo)
// if not is_positive:
// ... | Rust | 0 |
r##"Recognizer {{ regex: Regex::new(r#"{regex}"#).unwrap(), is_nonindicative: {is_nonindicative}, recursive_capture_idx: {recursive_capture_idx} }}, // {idx}"##,
regex = t.from_re,
is_nonindicative = n,
idx = i,
recursive_capture_idx = t.re... | Rust | 0 |
#from airflow.models.dag import DAG
from airflow.sdk import DAG
#from airflow.operators.python import PythonOperator
from airflow.providers.standard.operators.python import PythonOperator
from src.bots_auxiliar import Bots_aux
from pendulum import today, duration
email = Bots_aux()
default_args = {
'depends_on_pa... | Python | 1 |
-0.0005129477357421059, -0.0002621470728476185,
-0.0007967195911958656, 0.01365031989418242, 0.0001408581712825875, -0.002040325515611523
);
assert_relative_eq!(result, expected, epsilon = 1e-8);
}
#[test]
fn test_matrix_times_inverse_is_identity() {
let matrix: Matrix... | Rust | 0 |
let new_iter = SimpleSelectDobuleEndedIterator{
father: self.father,
start_code: code & !(u64::MAX << inword_offset),
start_index: (middle_bit_index >> WORD_SHIFT) as usize,
end_index: self.end_index,
end_code: self.end_code,
len: self... | Rust | 0 |
return tf.argmax(vals).numpy()
def update(self, context, action, reward):
"""Updates the posterior."""
self.t += 1
self.data_h.add(context, action, reward)
# Retrain the network on the original data (data_h)
if self.t % self.update_freq_nn == 0:
print('Number of contexts observed=', self.... | Python | 1 |
# Scrapy settings for crawl_conf project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
# https://docs.scrapy.org/en/latest/topics/settings.html
# https://docs.scrapy.org/en/latest/topics/downloader-middlew... | Python | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.