text string | label_name string | labels int64 |
|---|---|---|
ds a new element to the heap. The heap will be rebalanced to
/// maintain the string and heap properties.
///
/// Elements pushed more than once will not be deduplicated.
pub fn push(&mut self, item: T) {
self.data.push(item);
self.layout.push();
balance_after_push(self.data.as... | Rust | 0 |
sticsQueryArgs,
_: (),
) -> Result<WebGpuResult, AnyError> {
let render_pass_resource = state
.resource_table
.get::<WebGpuRenderPass>(args.render_pass_rid)
.ok_or_else(bad_resource_id)?;
wgpu_core::command::render_ffi::wgpu_render_pass_end_pipeline_statistics_query(
&mut render_pass_resource.0.b... | Rust | 0 |
import scipy
import torch
import sys
sys.path.append("src")
import conf
PROJ_DIR = conf.PROJ_DIR
from art2mus.art2mus_4_pipeline import AudioLDM2Pipeline
import art2mus.utils.train_test_utils as tu
def generate_audio(prompt=None, img_path=None, img_emb=None, neg_prompt="Low quality.",
inf_steps=2... | Python | 1 |
changed_item.new)
}
},
)?;
print_items_with_header(
w,
"Added items to the public API\n\
=============================",
&diff.added,
|w, item| {
if use_color {
writeln!(w, "+{}... | Rust | 0 |
_rate` approaches 1.0. After `n`
// consecutive steps of increasing the `kill_rate`, it will
// be `1 - (1-KILL_RATE_STEP_UP)^n`
//
// When we step down, we do that in fixed size steps to move away from
// dropping queries fairly quickly so that after `n` steps of reducing
... | Rust | 0 |
37886, false, Some(b"LMT"))),
unwrap!(LocalTimeType::new(-37800, false, Some(b"HST"))),
unwrap!(LocalTimeType::new(-34200, true, Some(b"HDT"))),
unwrap!(LocalTimeType::new(-34200, true, Some(b"HWT"))),
unwrap!(LocalTimeType::new(-34200, tru... | Rust | 0 |
}
&*INSTANCE
}
fn is_initialized(&self) -> bool {
true
}
fn merge_from(
&mut self,
_is: &mut ::protobuf::CodedInputStream,
) -> ::protobuf::ProtobufResult<()> {
unimplemented!();
}
fn get_unknown_fields(&self) -> &::protobuf::UnknownFields {
... | Rust | 0 |
función es la siguiente.
//!
//! ```
//! < id > ( < expresion >, < expresion > );
//! ```
//! Cada expresión va a representar el parámetro a enviar de dicha función.
//! También se permiten que se escriba el resultado de una expresión siguiendo la estructura de
//!
//! ##### Ejemplos
//! ```
//! suma(2, 3, 4);
//! l... | Rust | 0 |
"""
Methods to store, access or create modifiers
"""
from typing import Dict
import bpy.types as bpy_types
class ModifierCreator:
"""
Helper class to create modifiers
"""
def __init__(self, _type: str, name: str, properties: Dict, _object: bpy_types.Object = None):
self.object = _object
... | Python | 1 |
f (
db_type
in [
"float",
"real",
"double",
"decimal",
"numeric",
]
or db_type.startswith("decimal")
or db_type.startswith("float")
):
return "number"
# Boolean type
if db_type == "boolean":
r... | Python | 1 |
)
.split_point(0.4)
.draggable(true)
.solid_bar(false)
.bar_size(2.0)
.min_bar_area(5.0)
.min_size(200.0, 200.0), //.border(Color::rgb8(0x71, 0x71, 0x71),... | Rust | 0 |
nclude_str!("templates/dmg/dmg-license.py"),
)?;
// chmod script for execution
Command::new("chmod")
.arg("777")
.arg(&bundle_script_path)
.arg(&license_script_path)
.current_dir(output_path.clone())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.output()
.expect("Failed to chmo... | Rust | 0 |
len)
topk_index = topk_index.masked_fill_(mask, blank_id) # (B, maxlen)
hyps = [hyp.tolist() for hyp in topk_index]
scores = topk_prob.max(1)
results = []
for hyp in hyps:
r = remove_duplicates_and_blank(hyp, blank_id)
results.append(r)
return re... | Python | 1 |
])
plt.colorbar();
plt.show()
# +
# show_answer('Bifurcations96', 'a')
# -
# #### Exc (optional) -- Doubling time
#
# Maximise `N` (for a large sample), minimise `ε` (to approach linear conditions) and set `Time=1` (a reasonable first guess). Compute a rough estimate of the doubling time in the cell below fr... | Python | 1 |
0, pattern1_0, expr1_0, pattern2_0)?;
return Some(expr2_0);
}
// Generated as internal constructor for term lshl_imm.
pub fn constructor_lshl_imm<C: Context>(
ctx: &mut C,
arg0: Type,
arg1: Reg,
arg2: u8,
) -> Option<Reg> {
let pattern0_0 = arg0;
let pattern1_0 = arg1;
let pattern2_0 = ... | Rust | 0 |
re above this value.
k: Max number of matching queries to return.
fetch_k: Number of queries to retrieve from vector store before trimming.
Returns:
A list of (query_cell_id, score) tuples in descending score order.
"""
must_query = [
{"term": {"m... | Python | 1 |
"is stored. If this is not provided then no postprocessing "
"will be made. It is strongly recommended to provide the "
"postprocessing file!",
... | Python | 1 |
t_predict_y, executor.config.nrank, axis=0)
test_predict_y = np.concatenate(
split_test_predict_y, axis=1)
else:
test_predict_y = predict_y
test_loss_val = loss_val
if executor.rank == 0:
gt_loss_val = np... | Python | 1 |
# -*- coding: utf-8 -*-
"""
Description:
-
-
"""
from flask_restful import Resource
from connect import security
from lib.enums.roles import Roles
from services.analytics.vertical import AnalyticsVerticalService
from schemas.keyword_url import RemoveKeywordFormDataSchema, AddKeywordFormdataSchema
... | Python | 1 |
tialEq)]
pub enum State {
Menu,
Play,
GameOver,
}
mod flip;
mod rotate_90;
mod sobel;
mod filters;
mod resize;
mod jpeg_quality;
mod random_noise;
mod salt_n_pepper_noise;
mod gaussian_noise;
mod gaussian_blur;
mod unsharp;
mod rotate;
mod crop;
mod compose;
mod drawing;
mod interlace;
mod apply_palette;
mo... | Rust | 0 |
side: i32,
bevel: Option<(BevelKind, LinearEquation)>,
stroke_color: Option<C>,
fill_color: Option<C>,
}
impl<C: PixelColor> StyledPixelsIterator<C> {
fn new(primitive: &Sector, style: &PrimitiveStyle<C>) -> Self {
let stroke_area = style.stroke_area(primitive);
let fill_area = style.... | Rust | 0 |
// compression algorithm, has a technique to ensure that input data can't be encoded in such a
// way where it's expanded by a meaningful amount.
//
// This technique allows storing blocks of uncompressed data with only 5 bytes of overhead per
// block. Technically, the blocks can be up to 65KB in Defla... | Rust | 0 |
# Copyright 2025 CNOE
# SPDX-License-Identifier: Apache-2.0
# Generated by CNOE OpenAPI MCP Codegen tool
"""Tools for /metric/{name} operations"""
import logging
from typing import Any
from mcp_splunk.api.client import make_api_request, assemble_nested_body
# Configure logging
logging.basicConfig(level=logging.INFO)... | Python | 1 |
import speech_recognition as sr
import requests
import json
# 语音识别
def recognize_speech(audio_file):
recognizer = sr.Recognizer()
with sr.AudioFile(audio_file) as source:
audio_data = recognizer.record(source)
return recognizer.recognize_google(audio_data, language='en-US')
# 文本翻译
def translate_te... | Python | 1 |
DispatchObject, context: *mut c_void);
pub fn dispatch_set_target_queue(obj: *const DispatchObject, queue: *const DispatchQueue);
pub fn dispatch_get_global_queue(identifier: c_long, flags: c_ulong) -> *const DispatchQueue;
pub fn dispatch_queue_get_label(queue: *const DispatchQueue) -> *const c_char;
... | Rust | 0 |
from snapshot import Caretaker, Memento, Originator
class EvalCalculator:
def __init__(self, expression: Originator, caretaker: Caretaker):
self.expression = expression
self.caretaker = caretaker
self.results = []
def input_char(self, char: str):
self.expression.add_char(char)... | Python | 1 |
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
import os
import glob
def read_csv_files(directory):
edges_files = glob.glob(os.path.join(directory, 'edges.csv', '*.csv'))
vertices_files = glob.glob(os.path.join(directory, 'vertices.csv', '*.csv'))
if not edges_files or not ... | Python | 1 |
4 ), W!( 0, 0, 4, -16, 65, 89, -18, 4 ),
W!( 0, 0, 4, -16, 63, 91, -18, 4 ), W!( 0, 0, 4, -16, 60, 94, -18, 4 ),
W!( 0, 0, 3, -15, 58, 96, -18, 4 ), W!( 0, 0, 4, -15, 55, 98, -18, 4 ),
W!( 0, 0, 3, -14, 52, 100, -17, 4 ), W!( 0, 0, 3, -14, 50, 102, -17, 4 ),
W!( 0, 0, 3, -13, 47, 104, -17, 4 ), W!(... | Rust | 0 |
: str = parser.parse_args().dataset
schema_content_type: str = parser.parse_args().schema_content_type
row_content_type: str = parser.parse_args().row_content_type
include_contexts: bool = parser.parse_args().include_contexts
if schema_content_type == "none" and row_content_type == "none":
rais... | Python | 1 |
>
// SPDX-License-Identifier: Apache-2.0
/// ! An example of using a custom storage adapter (in this case, using sled).
use iota_wallet::{
account::AccountIdentifier, account_manager::AccountManager, client::ClientOptionsBuilder, storage::StorageAdapter,
};
use sled::Db;
use std::path::Path;
struct MyStorage {
... | Rust | 0 |
u back the full source file.
// Ignores newline characters.
#[test]
fn returns_all_with_next(input in "(\\PC{0,8}\\n)*") {
let file = SourceFile::dummy_file(input.split("\n").collect());
let iterator = file.chars();
let output: String = iterator.collect();
assert_eq!(output, input.re... | Rust | 0 |
2, 402, 502],
],
"5m": [
[1635840000000, 100, 200, 300, 400, 500],
[1635840300000, 105, 201, 301, 401, 501],
[1635840600000, 102, 202, 302, 402, 502],
],
}
}
mocker.patch("freqtrade.exchange.exchange_ws.ExchangeWS._start... | Python | 1 |
bic',
)
assert int(w0) == patch_pos_embed.shape[-2] and int(h0) == patch_pos_embed.shape[-1]
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
return patch_pos_embed
def prepare_tokens(self, x):
B, nc, w, h = x.shape
x = self.patch_embed(x) # pa... | Python | 1 |
"""
clip_min = -1
clip_max = 1
eta = tf.constant([[0.0], [-1.0], [1], [0.5], [-1], [1], [-0.9], [0.9]])
grad = tf.constant([[1.0], [-1.0], [1.0], [1.0], [1.0], [-1.0], [-1.0], [1.0]])
grad2 = self.sess.run(
utils_tf.zero_out_clipped_grads(grad, eta, clip_min, clip_... | Python | 1 |
from src.helper import b2Tob16, message_to_mm_bit_list_chunks, chunker, normalize_hex_strings_to_bit_lists
from src.bitwise.operators import *
from src.constants import *
def expand_chunk(chunk):
sub_chunks = chunker(chunk, 32)
# cop 1 - expander
memo = {}
def new_sub_chunk(i,memo):
#... | Python | 1 |
is_users.exists(user_id)?;
if redis_exists {
return Ok(true);
}
let exists_result_rows=self.postgres_session.query(
"SELECT EXISTS(SELECT 1 FROM users WHERE id=$1)",
&[&user_id]
)?;
if exists_result_rows.len()>0 {
let exists:bool... | Rust | 0 |
# Copyright 2025 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | Python | 1 |
;
#[doc = "*Required features: `\"Win32_Graphics_DirectWrite\"`*"]
pub const DWRITE_FONT_STRETCH_UNDEFINED: DWRITE_FONT_STRETCH = 0i32;
#[doc = "*Required features: `\"Win32_Graphics_DirectWrite\"`*"]
pub const DWRITE_FONT_STRETCH_ULTRA_CONDENSED: DWRITE_FONT_STRETCH = 1i32;
#[doc = "*Required features: `\"Win32_Graphi... | Rust | 0 |
: &[u8]) -> String {
let mut mac = HmacSha1::new_from_slice(key).unwrap();
mac.update(data);
let result = mac.finalize().into_bytes();
base64::encode(&result)
}
}
#[cfg(test)]
mod test {
use super::RemotingClient;
#[test]
fn test_calculate_signature() {
let sign... | Rust | 0 |
# -*- coding: utf-8 -*-
import os
import re
ROOT = os.path.dirname(__file__)
def main():
version_projecttoml = get_version_projecttoml()
version_versionpy = get_version_versionpy()
version_metayaml = get_version_metayaml()
try:
for i in range(0,3):
assert version_projecttoml[... | Python | 1 |
#!/usr/bin/python3
# -*- coding: utf-8 -*
from PyQt5.QtWidgets import QWidget
from allplan_manage import AttributeDatas
from tools import set_appearance_number
from ui_attribute_unknown import Ui_AttributeUnknown
class AttributeUnknown(QWidget):
def __init__(self, attribute_obj: AttributeDatas, value: str):
... | Python | 1 |
PE => "Peru",
PF => "French Polynesia",
PG => "Papua New Guinea",
PH => "Philippines",
PK => "Pakistan",
PL => "Poland",
PM => "Saint Pierre and Miquelon",
PN => "Pitcairn",
PR => "Puerto Rico",
PS =... | Rust | 0 |
e
/// main part of the keyboard is encoded as [`Backspace`].
///
/// [`Backspace`]: Self::Backspace
Delete,
/// <kbd>Page Down</kbd>, <kbd>End</kbd>, or <kbd>↘</kbd>
End,
/// <kbd>Help</kbd>. Not present on standard PC keyboards.
Help,
/// <kbd>Home</kbd> or <kbd>↖</kbd>
Home,
/// <kbd>Insert</kbd> or <kbd>I... | Rust | 0 |
width_f = st.number_input("Footer Width:", step=1, value=1780, key="width_f")
height_f = st.number_input("Footer Height:", step=1, value=2520, key="height_f")
if st.button("Confirm Footer"):
app.save_footers(r"ScannedPDF_Final\page_1.jpg",x0_f, y0_f,width_f,height_f)
st... | Python | 1 |
, Seat::Occupied]];
assert_eq!(vec![&Seat::Floor, &Seat::Floor, &Seat::Floor, &Seat::Empty, &Seat::Occupied, &Seat::Empty, &Seat::Floor, &Seat::Floor], get_adjacent_seats_los(0, 0, &seats));
assert_eq!(vec![&Seat::Empty, &Seat::Floor, &Seat::Floor, &Seat::Occupied, &Seat::Floor, &Seat::Floor, &Seat::Floor, &Sea... | Rust | 0 |
}
#[test]
fn test_transfer() {
let zero = Hash::default();
let keypair0 = KeyPair::new();
let keypair1 = KeyPair::new();
let pubkey1 = keypair1.pubkey();
let tr0 = Transaction::new(&keypair0, pubkey1, 42, zero);
assert!(tr0.verify_plan());
}
#[test]
... | Rust | 0 |
on
text_x = margin_px
text_y = page_height_px - margin_px - text_height
# Draw the text
draw_final.text((text_x, text_y), text, font=font, fill="black")
# Save as PDF
filename = f"charuco_board_{paper_size}.pdf"
final_image.save(filename, "PDF", resolution=DPI)
print(f"ChArUco board sav... | Python | 1 |
"""
Rutas de la API para el recurso Empresa
"""
from typing import List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.exc import IntegrityError
from app.schemas.empresa import Empresa, EmpresaCreate
from app.services.empresa_service import get... | Python | 1 |
ew(-1, 3, image_size, image_size)
cols = image_size // 2
half_refer_image = refer_image[..., :cols]
for c, sigma in enumerate(sigmas):
labels = torch.empty(x_mod.shape[0], dtype=torch.long, device=x_mod.device).fill_(c)
step_size = step_lr * (sigma / sigmas[-1]) ** 2
for k in range(... | Python | 1 |
def preprocess_image(image):
w, h = image.size
w, h = (x - x % 32 for x in (w, h))
image = image.resize((w, h), resample=PIL_INTERPOLATION['lanczos'])
image = np.array(image).astype(np.float32) / 255.0
image = image[None].transpose(0, 3, 1, 2)
return 2.0 * image - 1.0
| Python | 1 |
e, &message_byte, true)
.unwrap()
.0;
assert_eq!(tbs, tbv);
// sign and verify
let key = &[0, 1, 2, 3, 4];
let tag = TsigAlgorithm::HmacSha256.mac_data(key, &tbv).unwrap();
TsigAlgorithm::HmacSha256
.verify_mac(key, &tbv, &tag)
... | Rust | 0 |
# -*- encoding: utf-8 -*-
'''
@Description: :将纯真IP数据库内的地址细分为省市区.
@Date :2020/10/08 20:04:08
@Author :a76yyyy
@version :1.0
'''
import os
import sys
sys.path.append(os.path.abspath(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.abspath(os.path.dirname(__file__)))
from datab... | Python | 1 |
#!/usr/bin/env python3
# Copyright (c) 2025 FuzzingLabs
#
# Licensed under the Business Source License 1.1 (BSL). See the LICENSE file
# at the root of this repository for details.
#
# After the Change Date (four years from publication), this version of the
# Licensed Work will be made available under the Apache Licens... | Python | 1 |
et mix_prob as 1.0 and 0.0 to force cover lines
cfg_ = deepcopy(self.default_cfg)
cfg_['mix_prob'] = 1
g = StyleGAN1Generator(**cfg_)
res = g(torch.randn, num_batches=2)
assert res.shape == (2, 3, 256, 256)
cfg_ = deepcopy(self.default_cfg)
cfg_['mix_prob'] = 1
... | Python | 1 |
duplicates.is_empty() {
None
} else {
let mut duplicates = duplicates.into_iter().collect::<Vec<_>>();
duplicates.sort();
Some(duplicates)
}
}
// Copyright 2022. The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitte... | Rust | 0 |
)
else:
trainer.evaluate('corpus/bllip/topks_3_text.txt', 'corpus/bllip/topks_3_new_parses.txt', dataloader)
elif args.eval_mode == 2 and is_master:
if args.left == 1:
trainer.evaluate_doc('corpus/bllip/bllip_test.raw', 'corpus/bllip/supar_eval_parses_new.txt')
else:
... | Python | 1 |
let copy = self.clone();
let renew_task = Interval::new_interval(Duration::from_secs(interval))
.for_each(move |_instant| {
debug!("Renewing GCP pubsub token");
if let Err(error) = copy.regenerate_token() {
error!(message = "Failed to update GCP pu... | Rust | 0 |
t clusters_par = raster::par::cluster_tiles(slices, min_cluster_size);
// regular raster should give the correct result
let (tiles_seq, _) = raster::map_to_tiles(&points, precision, threshold);
let clusters_seq = raster::cluster_tiles(tiles_seq, min_cluster_size);
assert_eq!(clusters_p... | Rust | 0 |
x = result.to_hex().to_string();
return x;
}<filename>day-13/src/main.rs
use std::{env, fs};
fn find_earliest(timestamp: u64, bus_ids: Vec<&str>) -> (u64, u64) {
let (chosen_bus, wait) = bus_ids
.iter()
.filter(|id| **id != "\'x\'")
.map(|id| {
let bus_id = id.parse::<u64>(... | Rust | 0 |
Piece::J3 => &IJ3,
Piece::J4 => &IJ4,
Piece::L1 => &IL1,
Piece::L2 => &IL2,
Piece::L3 => &IL3,
Piece::L4 => &IL4,
Piece::T1 => &IT1,
Piece::T2 => &IT2,
Piece::T3 => &IT3,
Piece::T4 => &IT4,
}
... | Rust | 0 |
Reader, _header: &BlockHeader) -> Result<()> {
Ok(())
}
}
<filename>src/main.rs
use std::error::Error;
use std::io::{BufRead, BufReader};
static VERSION: &str = env!("CARGO_PKG_VERSION");
mod args;
pub mod cfg;
pub mod err;
mod exec;
pub mod pkg;
mod tags;
use tags::Tags;
fn main() -> Result<(), Box<E... | Rust | 0 |
from bots.bot import Bot
import random
class RandomBot(Bot):
def __init__(self) -> None:
super().__init__()
def get_move(self, board):
moves = board.generate_legal_moves()
indexes = []
for index, move in enumerate(moves):
if not board.move_is_legal(move, board):
... | Python | 1 |
h("ais.cli.main.get_config", return_value={}):
result = runner.invoke(config, ["--get", "missing_key"])
assert result.exit_code == 0
assert "missing_key: 未设置" in result.output
def test_config_command_list_providers(self):
"""Test config command list providers."""
... | Python | 1 |
low running this script without staring main config
del cfg["defaults"]
cfg["batch_size"] = 8
print(cfg)
data = hydra.utils.instantiate(cfg)
data.prepare_data()
data.setup()
# Check the dataset loads correctly
image, label = next(iter(data.train_dataloader()))
print("Image train sh... | Python | 1 |
CU_LOG2),
);
EVC_TRACE(&mut bs.tracer, " y pos ");
EVC_TRACE(
&mut bs.tracer,
y_pel + ((cup / (lcu_s >> MIN_CU_LOG2)) << MIN_CU_LOG2),
);
EVC_TRACE(&mut bs.tracer, " width ");
EVC_TRACE(&mut bs.tracer, cuw);
EVC_TRACE(&mut bs.tracer, " height ");
EVC_TRACE(&mut bs.tracer,... | Rust | 0 |
omponentMappingOptions,
src3: ShaderComponentMappingOptions,
) -> Self {
Self(
(src0 as u32 & ShaderComponentMappingMask)
| ((src1 as u32 & ShaderComponentMappingMask)
<< ShaderComponentMappingShift)
| ((src2 as u32 & ShaderComponentMap... | Rust | 0 |
}
let entry_mapping = EntryMapping { source, value };
// attempt to update an existing
// entry for this document, if
// present
let mut found = false;
for mapping in &mut view_entry.mappings {
if ... | Rust | 0 |
ema(description = "IMDB ID")]
link: StackString,
#[schema(description = "Rating")]
rating: Option<f64>,
#[schema(description = "IsTv Flag")]
istv: Option<bool>,
#[schema(description = "Source")]
source: Option<TvShowSourceWrapper>,
}
#[derive(Default, Debug, Serialize, Deserialize, Into, Fr... | Rust | 0 |
in msg_len.chars() {
if c.is_numeric() == true {
index = index + 1;
}
}
msg_len.truncate(index);
msg_len
}
fn decoded_message(msg_len: &str,
stream: &mut TcpStream)
-> String {
let mut remaining_data = msg_len.parse::<i32>().unwrap();
let mut msg:... | Rust | 0 |
@param[in] pitchedDevPtr"]
#[doc = " @param[in] value - constant value to be set"]
#[doc = " @param[in] extent"]
#[doc = " @param[in] stream"]
#[doc = " @return #hipSuccess, #hipErrorInvalidValue, #hipErrorMemoryFree"]
pub fn hipMemset3DAsync(
pitchedDevPtr: hipPitchedPtr,
val... | Rust | 0 |
_init_mut(buf)
})
})
}
/// Allocate a runtime length slice of uninitialised `T` on the stack, call `callback` with this buffer, and then deallocate the buffer.
///
/// The slice is aligned to type `T`.
///
/// See `alloca()`.
#[inline] pub fn stackalloc_uninit<T, U, F>(size: usize, callback: F) -> U
where F: FnO... | Rust | 0 |
class AutoDescribe(type):
def __new__(mcs, name, bases, namespace):
if 'describe' not in namespace:
def describe(self):
return f"This is an instance of {name}"
namespace['describe'] = describe
return super().__new__(mcs, name, bases, namespace)
class MyClass(... | Python | 1 |
rt:04d}_{end:04d}.pkl'
if args.save_adv_example:
assert args.chunk_size == 1
save_adv_example = f"--save_adv_example --cex_path {args.log_dir}/cex_{start}.txt"
else:
save_adv_example = ""
command = (f"unbuffer python abcrown.py --device {args.device} {command}... | Python | 1 |
# -*- coding: utf-8 -*- #
# Copyright 2024 Google LLC. 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 requir... | Python | 1 |
0x4f68bce3e8cd4db196e7fbcaf984b709u128 => "Linux root (x86-64)",
0x69dad7102ce44e3cb16c21a1d49abed3u128 => "Linux root (ARM 32)",
0xb921b0451df041c3af444c6f280d3faeu128 => "Linux root (ARM 64)",
0xbc13c2ff59e64262a352b275fd6f7172u128 => "Linux /boot",
0x0657fd6da4ab43c484e50933c84b4f4fu128 => "Linu... | Rust | 0 |
###############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) typedef int GmbH
#
# 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 Software ... | Python | 1 |
// Unmount this channel's mountpoint
let _ = self.unmount();
}
}
impl Channel {
/// Create a new communication channel to the kernel driver using the given file descriptor
/// obtained by calling fusermount or any other FUSE mount mechanism. When the channel is
/// dropped, the file de... | Rust | 0 |
print(f"\n📋 Original ranking:")
for j, doc in enumerate(original_docs[:3]):
print(f" {j+1}. {doc['source']} (score: {doc['original_score']:.2f})")
# Perform reranking / 执行重排序
reranked_docs, scores = reranker.rerank(
query=query,
documents=original_d... | Python | 1 |
import logging
from sqlalchemy import Table, Column
from sqlalchemy import Unicode, UnicodeText
from adhocracy.model import meta
log = logging.getLogger(__name__)
staticpage_table = Table(
'staticpage', meta.data,
Column('key', Unicode(256), primary_key=True),
Column('lang', Unicode(7), primary_key=Tru... | Python | 1 |
ndler.change_set.objects_to_add) == 0
assert len(parameter_handler.change_set.objects_to_update) == 0
assert len(parameter_handler.change_set.objects_in_sync) == 1
@patch("ansible_collections.vmware.vmware.plugins.module_utils.vm.parameter_handlers.device_linked._network_adapters.NetworkAdapter")
... | Python | 1 |
from pytube import YouTube
#location where you save.
PATH = "E:/" #to_do
#link of video.
link=["https://www.youtube.com/watch?v=p8FuTenSWPI",
"https://www.youtube.com/watch?v=JWbnEt3xuos"
]#list of video links.
for i in link:
try:
yt = YouTube(i)
except:
print("Connection Error") #to handle exception ... | Python | 1 |
def get_p1(score):
return score[0]
def get_p2(score):
return score[1]
def get_p3(score):
return score[2]
def get_average(score):
return (get_p1(score) + get_p2(score) + get_p3(score)) / 3
def set_p1(score, n):
if n not in range(0, 11):
raise ValueError("Invalid score")
score[0] =... | Python | 1 |
"""
Logging configuration and formatters for the DisPinMap application.
"""
import logging
from colorama import Fore, Style, init
# Initialize colorama
init()
class ColoredFormatter(logging.Formatter):
"""Custom formatter that adds colors to log messages based on level."""
COLORS = {
logging.DEBUG... | Python | 1 |
ro(),
};
let f0 = tr.eval_inner(tr.left - tr.shift);
let f1 = tr.eval_inner(tr.right - tr.shift);
tr.coeffs[0] = tr.coeffs[0] - f0;
tr.after = f1 - f0;
tr
}
pub fn shift(self: &Self, shift: F) -> Polynomial<F> {
Polynomial {
coeffs: self.coef... | Rust | 0 |
IB_loss_proxy /= iter_num
proxy_loss /= iter_num
mimin_total /= iter_num
mimin_loss_total /= iter_num
# if self.training:
# print('mimin:{:.4f},mimin_loss:{:.4f}'.format(mimin_total, mimin_loss_total))
logits = torch.mean(logits, dim=0)
if return_a... | Python | 1 |
## First Start Converting with - 0
class Solution:
def BinaryString(self, index, flag, number, result):
if index >= len(number):
result.append("".join(number))
return
number[index] = "0"
self.BinaryString(index + 1, True, number, result)
if flag == True:
... | Python | 1 |
: RelativePos::FromStart(5),
/// // This is substraction from .right()
/// left: RelativePos::FromEnd(10),
/// // This is substration from .width
/// width: RelativeSize::Absolute(4),
/// // This is an absolute values, not modified
/// height: RelativeSize::Relative(5)
... | Rust | 0 |
cular trading period.
pub trait Volume {
fn volume(&self) -> f64;
}
<filename>src/lib.rs<gh_stars>0
mod utils;
use age::keys::RecipientKey;
use age::Format;
use std::fmt::Debug;
use std::io::Write;
use std::str::FromStr;
use wasm_bindgen::prelude::*;
// When the `wee_alloc` feature is enabled, use `wee_alloc` as... | Rust | 0 |
executor::{
error::{CompileError, SymbolError},
semantic_analysis::{
constraints::{infer, unify},
hm::{
type_environment::TypeEnvironment, type_tree::build_type_tree, types::Type, Fresh,
TypedAst,
},
symbol_validity::ch... | Rust | 0 |
ABILITY_2_PK);
let msg = hex_to_byte_vec(TESTVEC_MESSAGE_LEN_256_BIT_STABILITY_2_MSG);
let sig = CspSignature::ed25519_from_hex(TESTVEC_MESSAGE_LEN_256_BIT_STABILITY_2_SIG);
(sk, pk, msg, sig)
}
_ => unimplemented!("not implemented because currently not used"),
}
... | Rust | 0 |
as WindowIcon, Window, WindowBuilder as WryWindowBuilder, WindowId},
},
webview::{
FileDropEvent as WryFileDropEvent, RpcRequest as WryRpcRequest, RpcResponse, WebView,
WebViewBuilder,
},
};
use std::{
collections::HashMap,
convert::TryFrom,
sync::{
mpsc::{channel, Sender},
Arc, Mutex,
}... | Rust | 0 |
u16,
pub(crate) width: u16,
pub(crate) slant: i16,
pub(crate) isReg: bool,
pub(crate) isBold: bool,
pub(crate) isItalic: bool,
}
#[derive(Clone)]
#[repr(C)]
pub(crate) struct XeTeXFontMgrNameCollection {
pub(crate) m_familyNames: VecDeque<String>,
pub(crate) m_styleNames: VecDeque<String>,... | Rust | 0 |
X_R::new(((self.bits >> 19) & 0x01) != 0)
}
#[doc = "Bit 18"]
#[inline(always)]
pub fn pu_rbb_pkdet_lorx(&self) -> PU_RBB_PKDET_LORX_R {
PU_RBB_PKDET_LORX_R::new(((self.bits >> 18) & 0x01) != 0)
}
#[doc = "Bit 17"]
#[inline(always)]
pub fn pu_rosdac_lorx(&self) -> PU_ROSDAC_LORX_... | Rust | 0 |
# Copyright (c) 2015 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
import sys
class Platform:
"""Convenience class to simplify OS checking and similar platform-specific handling."""
class PlatformType:
Windows = 1
Linux = 2
OSX = 3
Other = 4
... | Python | 1 |
from ibm_watsonx_orchestrate.agent_builder.tools import tool, ToolPermission
from pydantic import BaseModel, Field
import requests
class WeatherData(BaseModel):
wind_speed: float = Field(description="Wind Speed")
temperature: float = Field(description="Temperature")
current_weather: str = Field(description=... | Python | 1 |
![2], got);
let got = log_tree.range_keys(0..3)?;
assert_eq!(vec![2], got);
let got = log_tree.range_keys(0..10)?;
assert_eq!(vec![2, 9], got);
let got = log_tree.range_keys(0..11)?;
assert_eq!(vec![2, 9, 10], got);
let got = log_tree.range_keys(9..11)?;
assert_eq!(vec![9, 10], got);... | Rust | 0 |
def write_mean_summaries(writer, metrics, abs_step, mode="train", optimizer=None):
for key in metrics:
writer.add_scalars(main_tag=key, tag_scalar_dict={'%s_Average' % mode: metrics[key]},
global_step=abs_step, walltime=None)
if optimizer is not None:
writer.add_scalar... | Python | 1 |
e_item_e[i]
pred = torch.matmul(u_embedding, i_embedding.t())
return pred.cpu().item()
def rank(self, test_loader):
if self.restore_user_e is None or self.restore_item_e is None:
self.restore_user_e, self.restore_item_e = self.forward()
rec_ids = torch.tensor([], devic... | Python | 1 |
andler)
# Process events from stdin
try:
while True:
# Check if data is available with timeout
readable, _, _ = select.select([sys.stdin], [], [], 0.1)
if readable:
line = sys.stdin.readline()
if not line:
break
... | Python | 1 |
_GetComponents(AObj: usize, AIndex: i32) -> usize;
pub fn ScrollBox_GetAnchorSide(AObj: usize, AKind: TAnchorKind) -> usize;
pub fn ScrollBox_StaticClassType() -> TClass;
// ----------------- TCheckListBox ----------------------
pub fn CheckListBox_Create(AOwner: usize) -> usize;
pub fn CheckListBox_Free(AOb... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.