text string | label_name string | labels int64 |
|---|---|---|
from django.shortcuts import get_object_or_404
from canvas.exceptions import ServiceError, ValidationError
from drawquest.apps.drawquest_auth.models import User
from drawquest.apps.following import models
from drawquest.models import user_profile
from canvas import bgwork
from drawquest.api_decorators import api_decor... | Python | 1 |
# Copyright (c) 2021 PaddlePaddle 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 appli... | Python | 1 |
ptCamera().enableFirstPersonOverride()
gearExitCamera.value.pushCamera(avatar.getKey())
rideCamera.value.popCutsceneCamera(avatar.getKey())
avatar.avatar.exitSubWorld()
avatar.physics.warpObj(gearTeleportSpot.value.getKey())
elif self._crackOpe... | Python | 1 |
=
'=' => match_equals(line, cur), // = == =>
'+' => match_plus(line, cur), // + ++ +=
'-' => match_minus(line, cur), // - -- -=
'*' => match_star(line, cur), // * ** *=
'/' => match_slash(line, cur), // / // /* /=
... | Rust | 0 |
import streamlit as st
import spacy
import json
from langchain_ollama import OllamaLLM
from langchain.prompts import PromptTemplate
from langchain.text_splitter import RecursiveCharacterTextSplitter
from datetime import datetime
# Load the spaCy model
# spacy.cli.download("en_core_web_md")
nlp = spacy.load("en_core_we... | Python | 1 |
rescore(|key, _, _| key.len() as porigon::Score)
/// ;
/// assert_eq!(strm.next(), Some(("foo".as_bytes(), 0, 3)));
/// assert_eq!(strm.next(), Some(("foobar".as_bytes(), 1, 6)));
/// assert_eq!(strm.next(), None);
/// ```
///
/// You can also use this to build upon a previously set score:
... | Rust | 0 |
committee_index / self.committees_per_slot;
let index = global_committee_index % self.committees_per_slot;
Some((epoch_start_slot.safe_add(slot_offset).ok()?, index))
}
/// Returns the number of active validators in the initialized epoch.
///
/// Always returns `usize::default()` for a ... | Rust | 0 |
on_SignatureCheck_Response| { &mut m.deny_operation },
));
::protobuf::reflect::MessageDescriptor::new_pb_name::<CFileVerification_SignatureCheck_Response>(
"CFileVerification_SignatureCheck_Response",
fields,
file_descriptor_proto()
)
... | Rust | 0 |
pub fn new() -> Self {
TypeResolverImpl {
ranges: [TypeQualifier::BangSingle; 26],
}
}
pub fn set(&mut self, x: &DefType) {
let q: &TypeQualifier = x.as_ref();
for r in x.ranges() {
match *r {
LetterRange::Single(c) => self.do_set(c, c, *q... | Rust | 0 |
from pydantic import BaseModel,Field
from typing_extensions import TypedDict,Literal
# Schema for structured output to use in evaluation
class CodeFeedback(BaseModel):
grade: Literal["Accepted", "Rejected"] = Field(
description="Decide if code of the project is Accepted or Rejected.",
)
feedback: s... | Python | 1 |
pe=right.dtype)
# In particular non-nanosecond timedelta64 needs to be cast to
# nanoseconds, or else we get undesired behavior like
# np.timedelta64(3, 'D') / 2 == np.timedelta64(1, 'D')
return Timedelta(obj)
# We want NumPy numeric scalars to behave like Python scalars
# po... | Python | 1 |
config(HashMap::new(), &Default::default());
let config = config_result.config;
assert_eq!(config_result.diagnostics.len(), 0);
assert_eq!(config.line_width, None);
assert_eq!(config.indent_width, None);
assert_eq!(config.new_line_kind.is_none(), true);
assert_eq!(config.use_tabs, None);
}
... | Rust | 0 |
file = CodeFile.objects.get(Q(path=path) & (Q(owner=user) | Q(is_public=True)))
except CodeFile.DoesNotExist:
try:
file = DataFile.objects.get(Q(path=path) & (Q(owner=user) | Q(is_public=True)))
except DataFile.DoesNotExist:
try:
file = ReportFile.objects.get... | Python | 1 |
0, "avg": 0.0, "min": d, "max": d, "total": 0.0}
)
acc["count"] += 1
acc["total"] += d
if d < acc["min"]:
acc["min"] = d
if d > acc["max"]:
acc["max"] = d
for st, acc in out.items():
... | Python | 1 |
}
}
}
/// Possible icons for an annotation.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum AnnotationIcon<'a> {
/// Speech bubble. For use with text annotations.
Comment,
/// For use with text annotations.
Key,
/// Sticky note. For use with text annotations.
Note,
///... | Rust | 0 |
dIp {
pub ipaddr: IpAddr,
pub cidr_mask: u8,
}
impl Display for AllowedIp {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(
f,
"{}={}/{}",
SetKey::AllowedIp,
self.ipaddr,
self.cidr_mask
)
}
}
#[c... | Rust | 0 |
# Created by MechAviv
# Quest ID :: 25531
# Light Reborn
from net.swordie.ms.enums import UIType
sm.curNodeEventEnd(True)
sm.setTemporarySkillSet(0)
sm.setInGameDirectionMode(True, True, False, False)
sm.sendDelay(1000)
sm.setSpeakerID(0)
sm.removeEscapeButton()
sm.flipDialoguePlayerAsSpeaker()
sm.setSpeakerType(3)... | Python | 1 |
# Post-stroke aphasia English speech from https://aphasia.talkbank.org/derived/RaPID/
import os
import sys
import requests
from contextlib import contextmanager
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from data_loaders.common import BaseDataset, interactive_flag_samples
from core.audio import ... | Python | 1 |
from os import makedirs
from os.path import isdir
from pydantic import BaseModel
from prowler.providers.common.provider import Provider
# TODO: include this for all the providers
class Audit_Metadata(BaseModel):
services_scanned: int
# We can't use a set in the expected
# checks because the set is unord... | Python | 1 |
-------------------------------------------------------------
# MODEL
# -----------------------------------------------------------------------------
_C.MODEL = CN()
# -----------------------------------------------------------------------------
# MV MODEL
# -------------------------------------------------------------... | Python | 1 |
import pytest
def test_long_text(et_tokenizer):
# Excerpt: European Convention on Human Rights
text = """
arvestades, et nimetatud deklaratsiooni eesmärk on tagada selles
kuulutatud õiguste üldine ja tõhus tunnustamine ning järgimine;
arvestades, et Euroopa Nõukogu eesmärk on saavutada tema
liikmete suurem üh... | Python | 1 |
account::Account;
use lockbook_models::file_metadata::EncryptedFileMetadata;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
pub type Tx<'a> = transaction::CoreV1<'a>;
#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
pub struct OneKey;
hmdb::schema! {
CoreV1 {
account: <OneKey, A... | Rust | 0 |
_context, service_context=merging_context
)
automerging_index.storage_context.persist(persist_dir=save_dir)
else:
automerging_index = load_index_from_storage(
StorageContext.from_defaults(persist_dir=save_dir),
service_context=merging_context,
)
return aut... | Python | 1 |
ize = 256;
/// The size of a tile (in pixels)
pub const TILE_SIZE: usize = 8;
pub const BYTES_PER_PIXEL: usize = 4;
pub mod timings {
pub const OAM_READ: u32 = 80;
pub const VRAM_READ: u32 = 172;
pub const HBLANK: u32 = 204;
pub const VBLANK: u32 = 456;
pub const FULL_FRAME: u32 = (OAM_READ + VR... | Rust | 0 |
= torch.tensor([[cos_a, -sin_a], [sin_a, cos_a]], dtype=torch.float32, device=device)
# Build G⁻¹ matrix
G_inv = rotation @ torch.diag(eigenvals) @ rotation.T
inverse_metrics.append(G_inv)
inverse_metrics = torch.stack(inverse_metrics)
det_G_inv_centroids = torch.lina... | Python | 1 |
#!/usr/bin/env python3
"""
6-sum_mixed_list module
Contains a type-annotated function sum_mixed_list
that takes a list of integers and floats and returns their sum
"""
from typing import List, Union
def sum_mixed_list(mxd_lst: List[Union[int, float]]) -> float:
"""Returns the sum of a list of integers and floats"... | Python | 1 |
#The basic idea is that we keep track of the symbols in the string that we have looked
#at and the then iterate size by 1 if that symbol is not in the substring. if it is in
#the substring we simply change biggest to size if size is bigger than biggest and set
# size to 1.
def length_of_longest_substring(s: str) -> i... | Python | 1 |
'''
Nombre: Rebeca Gregorio Espina.
Fecha: 6 de diciembre del 2024.
Descripción:
Este programa es una nueva versión del juego realizado de piedra, papel y tijeras, pero utilizando un diccionario para las reglas del juego.
INSTRUCCIONES:
Escribe un programa de nombre Diccionarios_ej1_piedra_papel_tijera.py que realice ... | Python | 1 |
ges_success(app_manager, mock_scanners):
message = "test message"
application_key = "test_app_key"
# Mock the scan method of each scanner to return specific results
with patch.object(mock_scanners[0], 'scan', return_value=ScannerResult(
traits=["trait1"],
analyzer_result=["resul... | Python | 1 |
(), new_visited_entries, state.small_cave_twice))
}
}
}
#[derive(Debug)]
struct State {
entry: MapEntry,
visited_entries: HashSet<MapEntry>,
small_cave_twice: bool,
}
impl State {
fn start() -> State {
let mut visited_entries = HashSet::new();
visited_entries.insert(MapEntr... | Rust | 0 |
# Copyright (C) 2021-2025 Université Gustave Eiffel.
# This file is part of the EasyFEA project.
# EasyFEA is distributed under the terms of the GNU General Public License v3, see LICENSE.txt and CREDITS.md for more information.
from EasyFEA.Geoms import Domain
from EasyFEA import Mesher, Models, np, Simulations
cla... | Python | 1 |
self._migration_path = path
def use_global_registry(self):
"""使用全局的 registry
请在获取 Model 之前调用此方法
用于解决多个插件模型互相关联时的问题,请谨慎启用
"""
self._use_global_registry = True
def get_plugin_data(name: Optional[str] = None) -> PluginData:
"""获取插件数据
如果名称为空,则尝试自动获取调用者所在的插件名
"""... | Python | 1 |
import numpy as np
def tb_visualizer_pedes(tb_writer, lr, epoch, train_loss, valid_loss, train_result, valid_result,
train_gt, valid_gt, train_loss_mtr, valid_loss_mtr, model, attr_name):
tb_writer.add_scalars('train/lr', {'lr': lr}, epoch)
tb_writer.add_scalars('train/losses', {'train... | Python | 1 |
ce<F> for FileSourceFile
where
F: Format + FileStoredFormat + 'static,
{
fn resolve(
&self,
format_hint: Option<F>,
) -> Result<FileSourceResult, Box<dyn Error + Send + Sync>> {
// Find file
let (filename, format) = self.find_file(format_hint)?;
// Attempt to use a r... | Rust | 0 |
aResult = oParser.parse(sHtmlContent, sPattern)
if aResult[0]:
for aEntry in aResult[1]:
watchUrl = 'https://www.youtube.com/watch?v='
if 'videoseries?list=' in aEntry:
idList = re.sub('https:.+?list=', '', aEntry)
sUrl = 'https://invidious.fdn.fr/p... | Python | 1 |
kwargs):
if args:
element = args[0]
self._elements.append(element)
return element
elif kwargs:
for k, v in kwargs.items():
setattr(self, k, v)
return v
for (cls_name, category, *_) in config.CLASSES:
if cls_name not in... | Python | 1 |
from woodwork.column_schema import ColumnSchema
from woodwork.logical_types import Double
from featuretools.primitives.base import AggregationPrimitive
class AverageCountPerUnique(AggregationPrimitive):
"""Determines the average count across all unique value.
Args:
skipna (bool): Determines if to us... | Python | 1 |
),
(
Decimal::from("0.000000001"),
&[0, 1, 255, 253, 0, 0, 0, 9, 3, 232],
),
(Decimal::from(0.2404), &[0, 1, 255, 255, 0, 0, 0, 4, 9, 100]),
(Decimal::from(0.01), &[0, 1, 255, 255, 0, 0, 0, 2, 0, 100]),
(Decimal::from(0.66), ... | Rust | 0 |
3\xcd\xe6\
\xe5w\x08\xc0Q\x18\x94\x08{\x1c*)\xc9\xc7\xab\xf5\
\xc7J\xb7nM\xd4+\x9b\xb5\xba\x9602a\xf2\xd4\
+\x8c\xe7o\x98\x0f\x04\x82;\xf0*\x06\xb2/*\xf9\
Q\xdbD\xc4\x8f1\x1e+\x19K( \xee}\xbbd\
\x03'\x00\xe4\xe0\x9c\xe0\xd2W}V\x9d7\xf9\x06\xce\
\xcbO\xbcH\xed\x95!\xfd\xd5\xbd\xdce\x06\xd5\x82\xd9\
\xac\xf2@\x18\x04n\x9... | Python | 1 |
, init: Acc, mut fold: Fold) -> R where
Self: Sized, Fold: FnMut(Acc, Self::Item) -> R, R: Try<Ok=Acc>
{
if self.n == 0 {
Try::from_ok(init)
} else {
let n = &mut self.n;
self.iter.try_fold(init, move |acc, x| {
*n -= 1;
let... | Rust | 0 |
from(form: Form<Submit<'_>>) -> Self {
Config {
seed: form.seed,
entrance_shuffle: form.entrance_shuffle_type,
}
}
}
#[derive(Responder)]
#[response(content_type = "binary")]
struct RomResponder<'a> {
file: File,
content_disposition: Header<'a>,
}
#[derive(Responde... | Rust | 0 |
sig_to_uses_and_defs(&sig);
Ok(Self {
sig,
uses,
defs,
dest: CallDest::ExtName(extname.clone(), dist),
loc,
opcode: ir::Opcode::Call,
})
}
/// Create a callsite ABI object for a call to a function pointer with the
/// g... | Rust | 0 |
fn default() -> Self { unsafe { ::std::mem::zeroed() } }
}
#[repr(C)]
#[derive(Copy)]
pub struct Struct___darwin_fp_control {
pub _bindgen_bitfield_1_: ::libc::c_ushort,
}
impl ::std::clone::Clone for Struct___darwin_fp_control {
fn clone(&self) -> Self { *self }
}
impl ::std::default::Default for Struct___darw... | Rust | 0 |
[a.len()-1] - a[0] );
}
fn hunt_2<'a>(
current_string: BTreeMap<String, u128>,
ledger: &'a BTreeMap<&str, &'a str>,
mut step_limit: u32,
) -> BTreeMap<String, u128> {
let mut main_bt = current_string;
while step_limit > 0 {
let mut building_bt = main_bt.clone();
for window in main... | Rust | 0 |
}
pub use rentals::Dims as SelectDims;
impl SelectDims {
pub fn from_query(stmt: Arc<StmtRental>) -> Self {
Self::new(stmt, |_| HashMap::new())
}
}
#[allow(clippy::module_name_repetitions)]
#[derive(Debug)]
pub struct TrickleSelect {
pub id: String,
pub select: rentals::Select,
pub windows... | Rust | 0 |
onv2d(
int(512 * alpha),
int(1024 * alpha),
3,
stride=2,
padding=1,
bias=False
),
DepthSeperabelConv2d(
int(1024 * alpha),
int(1024 * alpha),
3,
pad... | Python | 1 |
from typing import Type, Optional
import requests
from pydantic import BaseModel, Field
from superagi.image_llms.openai_dalle import OpenAiDalle
from superagi.llms.base_llm import BaseLlm
from superagi.resource_manager.file_manager import FileManager
from superagi.models.toolkit import Toolkit
from superagi.models.co... | Python | 1 |
pub blinding: String,
pub conceal: String,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct SealCoins {
pub coins: u64,
pub vout: u32,
pub txid: Option<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TransferRequest {
pub inputs: Vec<OutPoint>,
pub alloca... | Rust | 0 |
[&2], vec![3]);
/// ```
pub fn gantt_schedule(&self) -> HashMap<usize, Vec<usize>> {
let mut gantt: HashMap<usize, Vec<usize>> = HashMap::with_capacity(self.num_resources);
for (task, &resource) in self.schedule.iter().enumerate() {
match gantt.entry(resource) {
Entr... | Rust | 0 |
ntains(&TechnologyId::AlphaDrive8) {
return TechnologyId::AlphaDrive8.clone();
}
if self.available_tech_ids.contains(&TechnologyId::DaddyLongLegs7) {
return TechnologyId::DaddyLongLegs7.clone();
}
if self.available_tech_ids.contains(&TechnologyId::FuelMizer) {
... | Rust | 0 |
culty = 0x33B,
// MsgGmResetinstancelimit = 0x33C,
// SmsgMotd = 0x33D,
// SmsgMoveSetCanTransitionBetweenSwimAndFly = 0x33E,
// SmsgMoveUnsetCanTransitionBetweenSwimAndFly = 0x33F,
// CmsgMoveSetCanTransitionBetweenSwimAndFlyAck = 0x340,
// MsgMoveStartSwimCheat = 0x341,
// MsgMoveStopSwimC... | Rust | 0 |
#[test]
fn test_random_bits_dense() {
for seed in 0..100 {
let bits = gen_random_bits(10000, 0.5, seed);
let ef = EliasFano::from_bits(bits.iter().cloned(), true).unwrap();
test_rank_select(&bits, &ef);
test_successor_predecessor(&bits, &ef);
let q... | Rust | 0 |
is None:
# ont_id_to_og = {x: patch_the_ontology(load_ontology.load(x)[0]) for x in ONT_NAME_TO_ONT_ID.values()}
# return ont_id_to_og
def the_ontology():
return patch_the_ontology(load_ontology.load('17')[0])
#return _ont_id_to_og()['17']
def unit_ontology():
return load_ontology.load(UNIT_OG_... | Python | 1 |
GameOver => {}
}
Ok(())
}
}
#[cfg(target_arch = "wasm32")]
fn wasm_panic_hook(info: &std::panic::PanicInfo) {
use stdweb::console;
console!(error, info.to_string());
}
async fn app(window: Window, gfx: Graphics, mut input: Input) -> Result<()> {
let mut app = Iterativ::new(window, gfx)... | Rust | 0 |
json_data.append(
{
"model": "gtfs.Shape",
"pk": i,
"fields": {
"feed": "1234",
"shape_id": row["shape_id"],
"shape_pt_lat": row["shape_pt_lat"],
"shape_pt_lon": row["shape_pt_lon"],
"shape_pt_... | Python | 1 |
from enum import Enum
class Rutas(Enum):
INDEX="/"
COURSES="cursos"
REPOS="repositorios" | Python | 1 |
assert_eq!(serde_json::from_str::<ScriptType>(r#""multisig""#).unwrap(), ScriptType::Multisig);
assert_eq!(serde_json::from_str::<ScriptType>(r#""nulldata""#).unwrap(), ScriptType::NullData);
assert_eq!(serde_json::from_str::<ScriptType>(r#""witness_v0_scripthash""#).unwrap(), ScriptType::WitnessScript);
assert_e... | Rust | 0 |
self.current = new_tab;
return true;
}
}
false
}
}
impl<T> SetDispatch<MouseUp> for Set<T> {}
impl<T> SetDispatch<MouseMove> for Set<T> {}
impl<T> SetDispatch<MouseScroll> for Set<T> {}
impl<T> SetDispatch<Update> for Set<T> {}
impl<T> SetDispatch<TextInp... | Rust | 0 |
ctrl_(&mut self) -> _NVMCTRL_W {
_NVMCTRL_W { w: self }
}
#[doc = "Bit 5 - DMAC AHB Clock Mask"]
#[inline]
pub fn dmac_(&mut self) -> _DMAC_W {
_DMAC_W { w: self }
}
#[doc = "Bit 6 - USB AHB Clock Mask"]
#[inline]
pub fn usb_(&mut self) -> _USB_W {
_USB_W { w: sel... | Rust | 0 |
conv1d_stpts_prob_modules.append(nn.Conv1d(in_channels=in_channels, out_channels=out_channels, kernel_size=1))
conv1d_stpts_prob_modules.append(nn.BatchNorm1d(out_channels))
conv1d_stpts_prob_modules.append(nn.ReLU())
in_channels = out_channels
conv1d_stpts_... | Python | 1 |
ReportTiming {
fn default() -> Self {
Self {
frequency: 1,
start_time: SystemTime::UNIX_EPOCH,
duration: Default::default(),
}
}
}
//! SSL Services
#[cfg(feature = "ssl")]
mod openssl;
#[cfg(feature = "ssl")]
pub use self::openssl::OpensslConnector;
use maud... | Rust | 0 |
# -*- coding: utf-8 -*-
"""
This module offers a generic Easter computing method for any given year, using
Western, Orthodox or Julian algorithms.
"""
import datetime
__all__ = ["easter", "EASTER_JULIAN", "EASTER_ORTHODOX", "EASTER_WESTERN"]
EASTER_JULIAN = 1
EASTER_ORTHODOX = 2
EASTER_WESTERN = 3
def easter(year,... | Python | 1 |
/// #[derive(Clone, IntoEnumIterator, PartialEq)]
/// enum Direction {North, South, West, East}
///
/// fn main() {
/// assert_eq!(Direction::VARIANT_COUNT, 4);
/// assert!(Direction::into_enum_iter().eq([Direction::North,
/// Direction::South, Direction::West, Direction::East].iter()
/// .clon... | Rust | 0 |
se()?;
Ok(Predicate::Negative(_0cf99098eee04b8c832e38ab8cabf8bf))
} else {
unreachable!("pegcel ordered choice fallthrough case reached")
}
}
}
impl ::quote::ToTokens for Predicate {
fn to_tokens(&self, _1e94b2203d3649c48792dbbf401007d0: &mut ::proc_macro2::TokenStream) ... | Rust | 0 |
=
workspace::cargo_metadata_no_deps(&manifest_path, color, &cwd)?;
let path = cwd.join(path.strip_prefix(".").unwrap_or(&path));
let config = BikecaseConfig::load_or_create(
&config,
home_dir.as_deref(),
data_local_dir.as_deref(),
dry_run,
)?;
let template_pac... | Rust | 0 |
mut output_path = output_path.to_path_buf();
match &crate_name {
Some(crate_name) => {
output_path.push(crate_name);
let _ = std::fs::remove_dir_all(&output_path);
std::fs::create_dir_all(&output_path)?;
cargo::generate(&output_path, crate_name, &schema, Non... | Rust | 0 |
deserialize(Value { value })?))
} else {
Ok(None)
}
}
}
struct Key<'de> {
key: &'de str,
}
impl<'de> Deserializer<'de> for Key<'de> {
type Error = ValueError;
fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,... | Rust | 0 |
::ListBoxRow,
/// # }
/// #
/// # impl actix::Actor for WindowActor {
/// # type Context = actix::Context<Self>;
/// # }
/// impl actix::Handler<woab::Signal> for WindowActor {
/// type Result = woab::SignalResult;
///
/// fn handle(&mut self, msg: woab::Signal, ctx: &mut Self::Context) -> Self::Result {
//... | Rust | 0 |
s == "+" {
Ok(Strand::Pos)
} else if s == "-" {
Ok(Strand::Neg)
} else if s == "." {
Ok(Strand::None)
} else {
Err(())
}
}
}
// NB: this assumes that the path name is of the form
// "path_name#seq_id:start-end", where seq_id is a stri... | Rust | 0 |
nstraint(
&rp_params,
verif_challenge,
com_proof.conjunction_response_scalars()[1],
);
let com_verifies = com_proof.verify_knowledge_of_opening(¶ms, verif_challenge);
assert!(zero_verifies && max_verifies && com_verifies);
}
#[test]
fn range_constraint_fails_with_wrong_input() ... | Rust | 0 |
__all__ = [
"db",
"env_vars",
"generate_images",
"github_api_queries",
"github_repo_stats",
"templates",
]
| Python | 1 |
self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,description):
""" __new__(cls: type,description: s... | Python | 1 |
import heapq
from collections import defaultdict
import lz4.frame
import random
# Set a seed for reproducibility
random.seed(42) # You can use any integer as the seed
def bwt(text):
# Generate rotations and sort them using a stable sorting algorithm
rotations = sorted([(text[i:] + text[:i], i) for i in range... | Python | 1 |
: Arithmetics + PartialOrd + Clone,
{
/// Take `n` evenly spaced colors from the gradient slice, as an iterator.
pub fn take(&self, n: usize) -> Take<C, T>
where
T: AsRef<[(C::Scalar, C)]>,
{
let (min, max) = self.domain();
Take {
gradient: MaybeSlice::Slice(self.clo... | Rust | 0 |
) -> pw.Table:
def query_retriever(retriever: InnerIndex) -> pw.Table:
return retriever.query(
query_column,
number_of_matches=number_of_matches,
metadata_filter=metadata_filter,
)
return self._combine_results(
query... | Python | 1 |
, wx.BITMAP_TYPE_ANY)
def get_preview_obj_artprovider(self, bitmap, prop=None):
"""Create a wxBitmap or wx.EmptyBitmap from the given statement using wxArtProvider.
(note: Preview shows only wxART_* resources.)
bitmap: Bitmap definition (str or None)
prop: a new_properties.Property... | Python | 1 |
patterns
"""
examples_data = {
"remember": {
"title": "💾 Memory Storage Examples",
"content": """
🎯 BASIC USAGE:
kuzu-memory remember "I prefer Python over JavaScript"
kuzu-memory remember "My name is Alex and I work at TechCorp"
👤 WITH USER ID:
kuzu-memory remember "... | Python | 1 |
self) -> &'b mut [u8] {
self.bytes.slice_from_mut(self.pos)
}
}
impl<'a> Reader for MutSliceBuf<'a> {
fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
super::read(self, buf)
}
}
impl<'a> Writer for MutSliceBuf<'a> {
fn write_all(&mut self, buf: &[u8]) -> IoResult<()> {
... | Rust | 0 |
.flag_path, &mut reg, &data)?;
}
Ok(())
}
fn main() {
if let Err(ref e) = run() {
use std::io::Write;
let stderr = &mut ::std::io::stderr();
let errmsg = "Error writing to stderr";
writeln!(stderr, "Error: {}", e).expect(errmsg);
for e in e.iter().skip(1) {
... | Rust | 0 |
# -*- coding: utf-8 -*- #
# Copyright 2023 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 |
# DO NOT EDIT! This file was auto-generated by crates/build/re_types_builder/src/codegen/python/mod.rs
# Based on "crates/store/re_types/definitions/rerun/components/axis_length.fbs".
# You can extend this class by creating a "AxisLengthExt" class in "axis_length_ext.py".
from __future__ import annotations
from .. i... | Python | 1 |
#!/usr/bin/python3
"""This module prompts a user for a song and returns the top 10 words from it that are used least frequently in the English-speaking world"""
"""Import modules and defines Request Headers for Words API get request"""
import requests, re, operator
headers = {
'x-rapidapi-host': "ENTER WORDS API H... | Python | 1 |
functions such as a fast ray casting method and volume finder for use with arbitrary shaped triangular meshes.
use nalgebra::{Matrix, Point3, Vector3};
/// Find the baycentric coordinates `(u,v)` and distance `t` given three triangle veriticies `vert0`, `vert1`, `vert2` and the
/// unit vector `dir` (`D`) in the dir... | Rust | 0 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#-:-:-:-:-:-:-:-:-:#
# XSRFProbe #
#-:-:-:-:-:-:-:-:-:#
# Author: 0xInfection
# This module requires XSRFProbe
# https://github.com/0xInfection/XSRFProbe
from difflib import SequenceMatcher
def sameSequence(str1,str2):
'''
This function is intended to fi... | Python | 1 |
# wide
WIDE_CONFIG={'min_lvl': [0.0,0.8],
'max_lvl': [0.0,1.0],
'const_scale':True,
'decay_factor':[0.8,1.2],
'clear_threshold':[0.0,0.1],
'locality_degree':[1,3],
'cloud_color':True,
'channel_offset':2,
'blur_scalin... | Python | 1 |
] trait provides a method to unpack text into a [`Token`]
//! stream. The [`TokenPacker`] trait provides the opposite method to convert a
//! [`Token`] stream to text.
//!
//! Additionally, two methods [`pack_all`] and [`unpack_all`] are provided to
//! work with a [`Token`] set when the number of tokens is known aprio... | Rust | 0 |
#diffie hellman algorithm
def power(a,b,p):
if b==1:
return a
else:
return pow(a,b)%p
def main():
P=23
print("the value of p is -->",P)
G=9
print("the value of g is -->",G)
a=4
print("the private key for a is -->",a)
x=pow(G,a,P)
b=3
print("the private key fo... | Python | 1 |
#!/usr/bin/en python3
import os
import sys
import Alfred3 as Alfred
APP_FOLDER = "/Applications"
def get_app_icon(app):
"""
Gets file icon of an app even if the app is one level deeper
Args:
app (str): App name without .app
Returns:
str: Absolute Path string
"""
app_fi... | Python | 1 |
erialize)]
pub struct DatastoreCredentials {
#[doc = "Enum to determine the datastore credentials type."]
#[serde(rename = "credentialsType")]
pub credentials_type: CredentialsType,
}
impl DatastoreCredentials {
pub fn new(credentials_type: CredentialsType) -> Self {
Self { credentials_type }
... | Rust | 0 |
# -*- coding: utf-8 -*- #
# Copyright 2016 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 |
EventStatus {
self.event_status
}
fn events_sent(&self) -> EventsSent {
EventsSent {
count: 1,
byte_size: self.event_byte_size,
output: None,
}
}
fn bytes_sent(&self) -> Option<BytesSent> {
Some(BytesSent {
byte_size: sel... | Rust | 0 |
import asyncio
import os
import time
import uuid
from typing import List
from tovana import AsyncMemoryManager
async def update_user_memory(
memory_manager: AsyncMemoryManager, user_id: str, messages: List[str]
):
for message in messages:
await memory_manager.update_memory(user_id, message)
cont... | Python | 1 |
return { 'CANCELLED' }
if len( sourcelayerdata ) < 1:
ResetSubdivModLevels( subdiv_mods )
self.report( { 'WARNING' }, 'Could not find VertexColors under cursor!!!' )
return { 'CANCELLED' }
for rmmesh in active_items:
with rmmesh as rmmesh:
#apply vertexcolor
for srclyrname, layervalue in ... | Python | 1 |
r_result.get("gt_box_tensor", None)
pred_box_np = pred_box_tensor.cpu().numpy()
gt_box_np = gt_box_tensor.cpu().numpy()
# # 过滤掉多余的预测框
# # 过滤掉多余gt框
# pred_box_centers = np.mean(pred_box_np, axis=1)
# pred_box_centers_convert_mask = np.floor(pred_box_centers / vixel_xize)
... | Python | 1 |
prev).next = (*node).next;
(*(*node).next).prev = (*node).prev;
});
}
pub unsafe fn LST_remove_head(
mut listHead: *mut LinkedListNode,
mut node: *mut *mut LinkedListNode,
) {
interrupt::free(|_| {
*node = (*listHead).next;
LST_remove_node((*listHead).next);
});
}
pub unsaf... | Rust | 0 |
= "Bit 21 - Any bit equal to 1 denotes a programming error in EFUSE_SECURE_BOOT_KEY_REVOKE0."]
#[inline(always)]
pub fn secure_boot_key_revoke0_err(&self) -> SECURE_BOOT_KEY_REVOKE0_ERR_R {
SECURE_BOOT_KEY_REVOKE0_ERR_R::new(((self.bits >> 21) & 0x01) != 0)
}
#[doc = "Bit 22 - Any bit equal to ... | Rust | 0 |
ersionsResult]:
"""
Provides access to available platform versions in a location for a given project.
## Example Usage
```python
import pulumi
import pulumi_gcp as gcp
uswest = gcp.container.get_attached_versions(location="us-west1",
project="my-project")
pulumi.export("firstA... | Python | 1 |
del_name: Name of the model
model_instance_id: Unique identifier for the model instance
amount: Number of tokens requested
Returns:
Number of tokens granted
"""
async with self.lock:
# Request tokens from central controller for this model name
... | Python | 1 |
/// device.register_command.write(0xF00D);
/// ```
// todo: Mmio<T> UnsafeCell
// body: Figure out if Mmio<T> should implement UnsafeCell.
// body: Does this mean that, just like atomic, write can take self by const reference only ?
// body: But is a Mmio<T> actually atomic ?
// body:
// body: Forward all these questi... | Rust | 0 |
///
/// This value is checked by the `event!` and `span!` macros. Code that
/// manually constructs events or spans via the `Event::record` function or
/// `Span` constructors should compare the level against this value to
/// determine if those spans or events are enabled.
///
/// [module-level documentation]: ../ind... | Rust | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.