text
string
label_name
string
labels
int64
N_HOURS.value, time_left_minutes print(f"current_datetime is outside of start_time_datetime and end_time_datetime window") print(f"could not find current_datetime in any start_time_datetime and end_time_datetime window") return HoursOfOperationStatus.OUT_OF_HOURS.value, 0 def lambda_hand...
Python
1
# Generated by Django 5.1.1 on 2024-10-07 05:49 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("tracker", "0002_expense_notes"), ] operations = [ migrations.RemoveField( model_name="expense", name="notes", ...
Python
1
ent().is_empty()); assert_eq!(obj_constraints.object.unwrap().fields.len(), 1); assert!(obj_constraints.terms.is_empty()); let mixed_input = InputSpan::new("{ len: Num } + Ops"); let (mixed_rest, mixed_constraints) = type_bounds(mixed_input).unwrap(); assert!(mixed_rest.fragment().is_empty()); ...
Rust
0
#-*- coding:utf-8 -*- import pygame from pygame.locals import * ## Initialisation de la fenetre et création pygame.init() #creation de la fenetre largeur = 640 hauteur = 480 fenetre=pygame.display.set_mode((largeur,hauteur)) i=0; continuer=1 while continuer: i=i+1; print i # on recupere l'etat du clav...
Python
1
the queried `token_id` does not exist. #[receive( contract = "CIS2-NFT", name = "balanceOf", parameter = "ContractBalanceOfQueryParams", return_value = "ContractBalanceOfQueryResponse" )] fn contract_balance_of<S: HasStateApi>( ctx: &impl HasReceiveContext, host: &impl HasHost<State<S>, StateAp...
Rust
0
from typing import Dict, Any, Union from pathlib import Path from .. import PycrittyError from .command import Command from ..io import log, yio from ..resources import config_file, saves_dir from ..resources.resource import ConfigFile class SaveConfig(Command): def save_config( self, config_name:...
Python
1
(CtrlKeyMode::Unselected, CtrlKeyAction::Lock), CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Pane), CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Tab), CtrlKeyShortcut::new(CtrlKeyMode::Unselected, CtrlKeyAction::Resize), Ctr...
Rust
0
0xD7 => Instruction::Or(AluSource::Gpr(GPR_B), AluSource::Gpr(GPR_C)), // or c,b 0xD8 => Instruction::Or(AluSource::Gpr(GPR_D), AluSource::Gpr(GPR_C)), // or c,d 0xD9 => Instruction::Or(AluSource::Gpr(GPR_A), AluSource::Gpr(GPR_D)), // or d,a 0xDA => Instruction::Or(AluSource::Gpr(GPR_B...
Rust
0
2in13bc::new(&mut spi, cs, busy, dc, rst, &mut delay).expect("eink initalize error"); debug!("Initializing done"); debug!("Creating display for e-paper screen with 90 degrees rotation"); let mut display = Display2in13bc::default(); display.set_rotation(DisplayRotation::Rotate90); display.clear_buff...
Rust
0
}, since: Antichain { elements: [4] } }"))); // Invalid update let b: BlobTraceBatchPart = BlobTraceBatchPart { desc: u64_desc(0, 1), index: 0, updates: columnar_records(vec![(("0".into(), "0".into()), 0, 0)]), }; assert_eq!( b.validate()...
Rust
0
rt2: PCSTR, ) -> BOOL; pub fn SetupQueueDeleteW( QueueHandle: HSPFILEQ, PathPart1: PCWSTR, PathPart2: PCWSTR, ) -> BOOL; pub fn SetupQueueDeleteSectionA( QueueHandle: HSPFILEQ, InfHandle: HINF, ListInfHandle: HINF, Section: PCSTR, ) -> BOOL; ...
Rust
0
um)); } } None } /// Parses a `str` into an `Option` containing a `MonthOfYear`. fn parse_month_of_year_english(text: &str) -> Option<MonthOfYear> { let re = Regex::new(r"(?i)(?P<month>jan|january|feb|mar|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)(r?uary|ch|il|e|y|ust|tember|ober|ember|\b)").unwrap(...
Rust
0
import warnings warnings.filterwarnings("ignore") import os, sys import cv2 import numpy as np import pandas as pd import time import pyautogui import win32gui import win32api import torch from threading import Thread, Lock from gamecapture import GameCapture from detection import Detection from vision import Visio...
Python
1
+ self.spin(row, left_column) + self.spin(row, right_column); sum } /// Return the delta energy. pub fn calc_delta_energy(&self, row: u32, column: u32, neighbor_sum: i32) -> f64 { let neighbor_sum = neighbor_sum as f64; let spin = self.spin(row, column) as f64; ...
Rust
0
'currently','yesterday', 'yo', 'hourly', 'nightly', 'daily', 'monthly', 'yearly', 'weekly', 'last',"now", #units|frequency 'mg', 'ml','mmhg', 'g', 'cm', 'ii', 'xii', 'lb', 'xl', 'kg','xl', 'pmh','unit', 'units', 'qh', 'qd','per','sig...
Python
1
return try: img = Image.open(path) except Exception as e: tk.messagebox.showwarning( "遇到了一点小问题", f"图片载入失败。图片地址:\n{path}\n\n错误信息:\n{e}") return self.isLoading = True medianBlur = Config.get("medianBlur") if medianBlur < 0: ...
Python
1
0.25 def render_tree(gui, parent=0, parent_geo_center=tl.vec(0.5, 0.5), parent_geo_size=1.0): child_geo_size = parent_geo_size * 0.5 if node_particle_id[parent] >= 0: tl = parent_geo_center - child_geo_size br = parent_geo_center + child_geo_size...
Python
1
the CF api //! to users. //! //! This implements a proxy server that does not use authentification itself - Every request made to this server //! is passed through mostly unchanged to the CF api, except for a few things: //! - The `HOST` header is set to `api.curseforge.com`, otherwise CF will not accept requests //!...
Rust
0
utput = Matrix; fn sub(self, rhs: &'b Matrix) -> Matrix { self.sub_vec(rhs) } } /// Subtraction between Matrix & f64 impl<T> Sub<T> for Matrix where T: convert::Into<f64> + Copy, { type Output = Self; fn sub(self, other: T) -> Self { match () { #[cfg(feature = "O3")] ...
Rust
0
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT from ..model import Randomise def test_Randomise_inputs(): input_map = dict( args=dict( argstr="%s", ), base_name=dict( argstr='-o "%s"', position=1, usedefault=True, ), c_...
Python
1
from argparse import ArgumentParser from pathlib import Path import pyspark.sql.functions as F from pyspark.sql import SparkSession from pyspark.sql.types import FloatType, ArrayType from sktime.datasets import load_from_tsfile_to_dataframe import pandas as pd import numpy as np def prep_pdf(pdf: pd.DataFrame): ...
Python
1
ssful. /// /// # <weight> /// - `O(R + X)`. /// - One balance-transfer operation. /// - Up to one account-lookup operation. /// - Storage: 1 read `O(R)`, 1 mutate `O(R + X)`. /// - One event. /// # </weight> #[weight = T::WeightInfo::provide_judgem...
Rust
0
id in image_ids: bbox1 = track1.get(iid, None) bbox2 = track2.get(iid, None) if bbox1 is not None and bbox2 is not None: i_, u_ = bb_intersect_union(bbox1, bbox2) i += i_ u += u_ elif bbox1 is None and bbox2 is not None: u += bbox2[2] * bbo...
Python
1
import math import numpy as np import matplotlib.pyplot as plt g = 9.81 # Acceleration due to gravity in m/s^2 A = 0.1*g # Amplitude Tn = 0.35 # Natural period in seconds wn = 17.87 # Damped natural frequency in rad/s xi = 1.39*10**(-3) # Damping ratio (example, adjust as needed) m = 0.812 # Mass of the struct...
Python
1
# holidays # -------- # A fast, efficient Python library for generating country, province and state # specific sets of holidays on the fly. It aims to make determining whether a # specific date is a holiday as fast and flexible as possible. # # Authors: Vacanza Team and individual contributors (see CONTRIBUTORS f...
Python
1
talen as *const _ as usize }, 16usize, concat!( "Offset of field: ", stringify!(PsshEntry), "::", stringify!(datalen) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<PsshEntry>())).data as *const _ as usize }, 20usize, ...
Rust
0
h exactly. score = 100 # Item order penalty (the lower it is on the list or results, the larger the penalty). #score = score - (itemIndex * SCORE_PENALTY_ITEM_ORDER) # Compute year penalty: [equal, diff>=3] --> [0, MAX]. yearPenalty = SCORE_PENALTY_YEAR mediaYear = toInteger(mediaYear) yea...
Python
1
'\u{010F30}'..='\u{010F6F}' => Some(SOGDIAN), '\u{010F70}'..='\u{010FAF}' => Some(OLD_UYGHUR), '\u{010FB0}'..='\u{010FDF}' => Some(CHORASMIAN), '\u{010FE0}'..='\u{010FFF}' => Some(ELYMAIC), '\u{011000}'..='\u{01107F}' => Some(BRAHMI), '\u{011080}'..='\u{0110CF}' => Some(...
Rust
0
Rules> { #[cfg_attr( feature = "serialization", serde(bound( serialize = "Option<EntropySeed<R>>: Serialize", deserialize = "Option<EntropySeed<R>>: Deserialize<'de>" )) )] seed: Option<EntropySeed<R>>, } impl<R: BattleRules> ResetEntropy<R> { /// Returns...
Rust
0
// `colon_pos + 1` does not overflow because some characters must follow after the colon. &self.as_str()[(colon_pos + 1)..] }) .unwrap_or_else(|| self.as_str()); <&NcnameStr>::try_from(local) .unwrap_or_else(|_| unreachable!("Local part of `QName` is ...
Rust
0
@cloud-server:/path/to/file1 :/path/to/file2 /path/to/on-prem/backup/ rsync -avz -e "ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null" --progress /root/bigfile.txt <IP>:/root/ rsync -avPz -e ssh /src/ user@remote:/path/to/dst rsync -avz -e "ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null...
Python
1
takes precedence over `clip_cursor` fn grab_cursor(&mut self, grabbed: bool); } #[cfg(target_os = "linux")] pub use self::linux::*; #[cfg(target_os = "linux")] mod linux { extern crate x11_dl; use super::*; use std::ptr; use std::mem; use std::str; use std::ffi::CString; use gl; ...
Rust
0
from django.urls import path from .views import HerramientasListView, HerramientasDetailView, HerramientasCreate, HerramientasUpdate, HerramientasDelete herramientas_patterns = ([ path('', HerramientasListView.as_view(), name='herramientas'), path('<int:pk>/<slug:page_slug>/', HerramientasDetailView.as_view(),...
Python
1
from lib.reading_time import * def test_for_200_words(): result = reading_time('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ultricies efficitur ullamcorper. Proin urna urna, efficitur bibendum pharetra ut, condimentum eget ligula. Duis sit amet dignissim nisl, a pharetra nisi. Phasellus laoreet...
Python
1
idx_enter_from_topk)) self.bound = self._key[:count_le].max().cpu() # To prevent cross device issues if self.verbose and self.batch_size == 1: print("Bound {:.2f}".format(self.bound.item())) # Bound is top k of _total_items_queued so this gives the quantile # ...
Python
1
# Copyright (c) 2024 Microsoft Corporation. # Licensed under the MIT License """A module containing create_graph definition.""" import networkx as nx import pandas as pd def create_graph( edges: pd.DataFrame, edge_attr: list[str | int] | None = None, nodes: pd.DataFrame | None = None, node_id: str =...
Python
1
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, Message from pyrogram import Client, filters, enums class BUTTONS(object): MBUTTON = [[InlineKeyboardButton("CʜᴀᴛGPT", callback_data="mplus HELP_ChatGPT"),InlineKeyboardButton("ɢʀᴏᴜᴘs", callback_data="mplus HELP_Group"),InlineKeyboardButton("s...
Python
1
np.cross(pc_,F[i]) + \ np.cross(pc_1,F[i+1]) + \ np.dot(I[i],omega_dot[i]) + \ np.cross(omega[i],np.dot(I[i],omega[i])) # compute torque for all joints (revolute) by projection for joint_idx in range(n): if joint_types[joint_idx] == 'prismatic': ...
Python
1
TUS: u32 = 3; pub const JSPLATFORM_BEEP_DEFAULT: u32 = 4; pub const FXCT_ARROW: u32 = 0; pub const FXCT_NESW: u32 = 1; pub const FXCT_NWSE: u32 = 2; pub const FXCT_VBEAM: u32 = 3; pub const FXCT_HBEAM: u32 = 4; pub const FXCT_HAND: u32 = 5; pub const FPDFDOC_AACTION_WC: u32 = 16; pub const FPDFDOC_AACTION_WS: u32 = 17;...
Rust
0
np.save('tid_to_tweet_index.npy', tid_to_tweet_index) np.save('followers_of_following.npy', followers_of_following) np.save('num_of_tweet.npy', num_of_tweet) np.save('r.npy', r) np.save('r_help.npy', r_help) extractor = URLExtract() num_of_url = np.zeros(node_num) url_dict = [{} for i in range(node_num)] tweet_vector ...
Python
1
self, module: Any, target_positions: np.ndarray, atol: float = 0.01 ) -> bool: """Check if joint positions are reached within tolerance. This method checks whether the current joint positions of a module are within the specified tolerance of the tar...
Python
1
from collections import deque def find_blank(board): for i in range(len(board)): for j in range(len(board[0])): if board[i][j] == '_': return i, j def swap(board, i, j, di, dj): new_board = [row[:] for row in board] new_board[i][j], new_board[i+di][j+dj] = new_board[i+...
Python
1
lysisDialog): def __init__(self, parent=None): super(AnalysisSingleDialog, self).__init__(parent) self.index2Checkbox.setHidden(True) self.name2Checkbox.setHidden(True) self.resid2Checkbox.setHidden(True) self.resname2Checkbox.setHidden(True) self.segid2Checkbox.setHi...
Python
1
from numba import runtests from numba.core import config if config.ENABLE_CUDASIM: from .simulator_init import * else: from .device_init import * from .device_init import _auto_device from numba.cuda.compiler import (compile, compile_for_current_device, compile_ptx, compil...
Python
1
prediction for the data batch. - Loss discrepancy between cross-entropy and MSE for the reward/ value predictions. """ if DEBUG_MODE and self.reference.steps % LOG_RATE == 0: observations, targets, sample_weight = list(zip(*data_batch)) target_pis, target_vs = list(map(...
Python
1
} } _ => { panic! {"Could not compare packets because packet type {:?} is not implemented yet", self.packet_type} } } } equal } } impl std::fmt::Display for Packet { fn fmt(&self, f: &mut fmt::Formatter) -> f...
Rust
0
from __future__ import division import math import numpy import librosa import scipy.spatial.distance import scipy.signal CHORDS = numpy.array([ [1,0,0,0,1,0,0,1,0,0,0,0], [1,0,0,1,0,0,0,1,0,0,0,0], [0,1,0,0,0,1,0,0,1,0,0,0], [0,1,0,0,1,0,0,0,1,0,0,0], [0,0,1,0,0,0,1,0,0,1,0,0], [0,0,1,0,0,1,...
Python
1
# -*- coding: utf-8 -*- import os from pysignfe.xml_sped import * from pysignfe.nfe.manual_500 import inutnfe_310 from pysignfe.nfe.manual_600 import ESQUEMA_ATUAL DIRNAME = os.path.dirname(__file__) class InfInutEnviado(inutnfe_310.InfInutEnviado): def __init__(self): super(InfInutEnviado, self).__init_...
Python
1
os0(syscfg).freeze(); let ccdr = function(pwrcfg, rcc, syscfg); // enable itm if the feature is selected #[cfg(any(feature = "log-itm"))] unsafe { let swo_frequency = 2_000_000; crate::itm::enable_itm(&mut cp.DCB, &dp.DBGMCU, ...
Rust
0
fn dims(&self) -> Vec<Ix> { unsafe { slice::from_raw_parts(self as *const _ as *const _, self.ndim()) }.iter().cloned().collect() } } ); ($head:ty, $($tail:ty,)*) => ( impl_tuple! { @impl <($head, $($tail,)*)>, $head, $...
Rust
0
# Display a menu to the user print("🧠 Welcome to the Text Transformation Toolkit!") print("Choose a transformation:") print("1. Reverse Text") print("2. Convert to Uppercase") print("3. Convert to Lowercase") print("4. Title Case") print("5. Count Vowels") print("6. Remove All Spaces") print("7. Replace Vowels with '*...
Python
1
::EXE_EXTENSION; } #[cfg(target_arch = "x86")] mod arch { pub const ARCH: &'static str = "x86"; } #[cfg(target_arch = "x86_64")] mod arch { pub const ARCH: &'static str = "x86_64"; } #[cfg(target_arch = "arm")] mod arch { pub const ARCH: &'static str = "arm"; } #[cfg(target_arch = "aarch64")] mod arch {...
Rust
0
md") .ok(); assert_ok(&result); } #[cfg(not(windows))] #[test] fn test_doc_errors() { let result = Command::cargo_bin("specdown") .unwrap() .arg("run") .arg("--temporary-workspace-dir") .arg("docs/errors.md") .ok(); assert_ok(&result); } #[cfg(windows)] #[...
Rust
0
doc = "Bit 1 - COP Clock Select"] #[inline(always)] pub fn copclks(&mut self) -> COPCLKS_W { COPCLKS_W { w: self } } #[doc = "Bits 2:3 - COP Watchdog Timeout"] #[inline(always)] pub fn copt(&mut self) -> COPT_W { COPT_W { w: self } } } use super::{Lab, EPSILON, KAPPA}; use st...
Rust
0
egex::new(r"cannot attach \S+ to \S+ can only attach to mirrors and top-level disks").expect("failed to compile RE_CANNOT_ATTACH"); static ref RE_NO_SUCH_DEVICE: Regex = Regex::new(r"cannot attach \S+ to \S+: no such device in pool").expect("failed to compile RE_NO_SUCH_DEVICE"); static ref RE_ONLY_DEVICE: Rege...
Rust
0
from odoo import models, fields class RentalPartner(models.Model): _inherit = 'res.partner' rental_space_id = fields.Many2one('rental.space', string='Rental Space', readonly=True, ondelete='set null')
Python
1
return self.model_runner.add_prompt_adapter(prompt_adapter_request) def remove_prompt_adapter(self, prompt_adapter_id: int) -> bool: return self.model_runner.remove_lora(prompt_adapter_id) def pin_prompt_adapter(self, prompt_adapter_id: int) -> bool: return self.model_runner.pin_promp...
Python
1
| { if d.metadata()?.is_dir() { let children = read_dir(d.path())?.count(); Ok(FsEntry::Dir(d.path(), children)) } else { let size = d.metadata()?.len(); Ok(FsEntry::File(d.path(), size)) } ...
Rust
0
fn mount_point(&self) -> &Path { Path::new("") } fn total_space(&self) -> u64 { 0 } fn available_space(&self) -> u64 { 0 } fn is_removable(&self) -> bool { false } fn refresh(&mut self) -> bool { true } } use jokrey_utilities::general::...
Rust
0
column_names.append(column.id) data = [] index = [] for row in table: key_value = row[table.columns.key_column.id] r = {} for column in column_names: r[column] = row[column] data.append(r) index.append(key_value...
Python
1
)); if hit_test_path(&point, path.iter(), FillRule::NonZero, 0.0) && vis.is_visible { shape_stack.stack.insert(Shape { layer, entity }); } } for (entity, path, transform, layer, vis) in poly_q.iter() { let layer = **layer; let path = p...
Rust
0
let qabs = vel.q.abs(); match qabs.cmp(&rabs) { Ordering::Equal => { if (vel.q + vel.r) % 2 == 0 { Axial::new(vel.q / qabs, 0) } else { Axial::new(0, vel.r / rabs) } ...
Rust
0
ake"), ProposalKind::Idle => write!(f, "idle..."), ProposalKind::Connection { addr, incoming: true, id, } => write!(f, "new incoming connection: {}, addr: {}", id, addr), ProposalKind::Connection { addr, ...
Rust
0
ic_params"] = task_specific_params torch_model = convert_pegasus(tf_weights, cfg_updates) torch_model.save_pretrained(save_dir) sd = torch_model.state_dict() sd.pop("model.decoder.embed_positions.weight") sd.pop("model.encoder.embed_positions.weight") torch.save(sd, Path(save_dir) / "pytorch_mod...
Python
1
_base_ = [ '../_base_/datasets/imagenet_bs64_swin_224.py', '../_base_/schedules/imagenet_bs1024_adamw_swin.py', '../_base_/default_runtime.py', ] model = dict( type='ImageClassifier', backbone=dict( type='XCiT', patch_size=16, embed_dims=384, depth=24, num_he...
Python
1
unwrap_or_else(|e| panic!("{}", e)); let prog = command.wait_with_output().unwrap(); CmdResult { success: prog.status.success(), stdout: from_utf8(&prog.stdout).unwrap().to_string(), stderr: from_utf8(&prog.stderr).unwrap().to_string(), } } pub fn get_file_contents(name: &str) -> S...
Rust
0
# 🎯 What is it? # We compute the average numeric star rating (Rate) for each category of text-based sentiment (label_sentiment). # 🧠 Why is This Insightful? # Helps detect rating inflation or deflation based on how people feel. # For example: # If the average rating for positive text reviews is 4.8, that's consistent...
Python
1
odules) def forward(self, x): x = self.conv1(x) x = self.maxpool(x) x = self.stage2(x) x = self.stage3(x) x = self.stage4(x) # global average pooling layer x = F.avg_pool2d(x, x.data.size()[-2:]) # flatten for input to fully-connected layer ...
Python
1
from typing import TYPE_CHECKING, Any from langchain._api import create_importer if TYPE_CHECKING: from langchain_community.utilities import WolframAlphaAPIWrapper # Create a way to dynamically look up deprecated imports. # Used to consolidate logic for raising deprecation warnings and # handling optional import...
Python
1
# -*- coding: utf-8 -*- from django.conf.urls import * from .views_class_based import MapComponentAddView urlpatterns = patterns('mindmap.views', url(r'^map/new/$', 'map_new', name='mindmap_map_new'), url(r'^map/(?P<mindmap_pk>(\d|#)+)/component/add/(?P<type>(\w|#|\s)+)/?$', MapComponentAddView.as_view(), na...
Python
1
import asyncio from typing import List import numpy as np from langchain_openai import OpenAIEmbeddings from ii_researcher.config import OPENAI_BASE_URL from .base import Compressor class EmbeddingCompressor(Compressor): def __init__( self, similarity_threshold: float, embedding_model: ...
Python
1
yolo_xylist, yolo_center_x = yolo_detect(frame) print(f"yolo_xylist: {yolo_xylist}, yolo_center_x: {yolo_center_x}") if yolo_xylist: colorcone_x_persent = (yolo_center_x - frame_center_x) / frame.shape[1] print(f"relative_yolo_x: {colorcone_x_...
Python
1
"gpos_chaining3_boundary_f4.otf", "latn", "UNKN", "test", &[00, 20, 21, 22, 23, 00], &[0, 0, 0, 20, 0, 0], &[0, 0, 0, 0, 0, 0], None,None ) } #[test] fn chaining3_successive_t1_gsub() { gsub_test( "gsub_chaining3_success...
Rust
0
ap_location=self.device) # Restore rules self.rule_repository = RuleRepository() for rule_data in checkpoint['rules']: rule = SubredditRule(**rule_data) self.rule_repository.add_rule(rule) # Initialize and load model num_rules = len(self....
Python
1
te_between_unsorted(&7, &4); assert_eq!(res, vec![]); let mut res = x.delete_between_unsorted(&3, &9); res.sort(); for (idx, v) in vec![3, 5, 6, 7, 7, 9].iter().enumerate() { assert_eq!(*List::get(&res, idx)?, *v); } for (idx, v) in vec![1, 1, 1, 2, 11, 11].iter().enumerate() { a...
Rust
0
from sqlalchemy.orm import Session from app.db.models_ORM.product_orm import ProductoORM from app.mappers.mapper_product import orm_a_dominio, dominio_a_orm from app.domain.product import Producto from app.db.squemas.products_squemas import PaginacionProductos class ProductoRepository: def __init__(self, session: ...
Python
1
n(self, h: i32) -> i32 { match self { VerticalTextAnchor::Top => { 0 } VerticalTextAnchor::Center => { -h / 2 } VerticalTextAnchor::Bottom => { -h } } } } #[derive(Clone, Copy, PartialEq, Eq)] pub struct TextAnchor { pub horizontal: HorizontalTextAnchor, ...
Rust
0
`field``, it will take precendence to the first parameter ``widget`` which will effectively be ignored. ''' if field is not None: create_widget = _django_field_to_floppyform_widget.get( field.__class__) if create_widget is not None: if allow_floppify_widget_for_field(...
Python
1
Arc::new_cyclic` doesn't work. So it needs to be a two step process, where /// the second step (`RuntimeSetup::complete`) doesn't return an error and can /// be called inside `Arc::new_cyclic`. pub(crate) struct RuntimeSetup { poll: Poll, registry: Registry, } impl RuntimeSetup { /// Complete the runtime s...
Rust
0
::fetch(cx, &self.user_id).await } } /// A partial user #[derive(Debug, Deserialize, Clone, PartialEq)] pub struct PartialUser { /// User status. pub status: Option<UserStatus>, /// User profile. pub profile: Option<UserProfile>, /// User avatar. pub avatar: Option<Attachment>, /// Whet...
Rust
0
import logging from datetime import datetime from game_actions import search_for_enemy, attack, add_troops_to_training from image_processing import process_screenshot, is_worth_attacking, get_gold_and_minerals, ATTACK_WINDOW_DATA from utils import clear_screenshots_directory, get_screenshot, click_and_wait, handle_err...
Python
1
import streamlit as st import os from PIL import Image import json # 定义目录 edit_results_dirs = ['EditResult_ori', 'EditResult_ori_2nd', 'EditResult_ori_3nd', 'EditResult_ori_4nd', 'EditResult_ori_5nd'] # edit_results_dirs = ['EditResult', 'EditResult_2nd', 'EditResult_3nd', 'EditResult_4nd', 'EditResult_5nd'] tasks_d...
Python
1
"""Episode monitoring with Streamlit.""" import os.path as osp import shelve import numpy as np import pandas as pd import streamlit as st from bokeh.layouts import gridplot from bokeh.plotting import figure # pylint:disable=invalid-name,missing-docstring,pointless-string-statement # pylint:disable=no-value-for-param...
Python
1
"".to_string(), text: "".to_string(), } } } assert_eq!( SubStruct::default(), SubStruct { subitem: "".to_string(), text: "".to_string(), } ); let model = XmlStruct { item: "something".to_string(), sub_struct: SubStruct { subitem: "sub_something".to_stri...
Rust
0
# -*- coding: utf-8 -*- """ .. _example_atomic_spectra: ======================== Atomic spectrum #0: Calculate an atomic spectrum ======================== In this example, the NIST and Kurucz databases are used to compute an atomic spectrum. The same partition function is employed. The Lorentzian broadening is assume...
Python
1
ppre = read_reg!(rcc, rcc, CFGR, PPRE1); match ppre { 0b100 => hclk / 2, 0b101 => hclk / 4, 0b110 => hclk / 8, 0b111 => hclk / 16, _ => hclk, } } pub fn pclk2(&self) -> u32 { let hclk = self.hclk(); let rcc = unsafe {...
Rust
0
import pygame as pg from collections import defaultdict def feld2xy(feld): x = feld % 8 * FELD y = feld // 8 * FELD return x,y def feld2zentrum(feld): x,y = feld2xy(feld) return x + FELD//2, y + FELD//2 def generiere_zugliste(spieler): zugliste = defaultdict(list) for von,stein in brett.items(): if...
Python
1
import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from itertools import product cramped_room = { "height" : 4, "width" : 5, "wall_idx" : jnp.array([0,1,2,3,4, 5,9, 10,14, 15,16,17,18,19]), "agent_idx"...
Python
1
string = serde_json::to_string(&self)?; let resp = self.bot.send("setMyCommands", Some(string)).await?; Ok(serde_json::from_str::<bool>(&resp.text().await?)?) } pub fn commands(mut self, commands: Vec<BotCommand>) -> Self { self.commands = commands; self } } use actix::prelu...
Rust
0
data including new thumbnail self.send_group(self.username, 'thumbnail', serialized.data) #-------------------------------------------- # Catch/all broadcast to client helpers #-------------------------------------------- def send_group(self, group, source, data): response = { 'type': 'broadcast_grou...
Python
1
/recommend", methods=["POST"]) def session_recommend(): try: repo_names = json.loads(request.data) feedbacks = [ { "FeedbackType": "star", "ItemId": v, "Timestamp": datetime.utcnow().isoformat(), } for v in repo_name...
Python
1
import os from flask_admin import Admin from models import db, User, Character, Planet, Favorite from flask_admin.contrib.sqla import ModelView def setup_admin(app): app.secret_key = os.environ.get('FLASK_APP_KEY', 'sample key') app.config['FLASK_ADMIN_SWATCH'] = 'cerulean' admin = Admin(app, name='4Geeks ...
Python
1
und_modifier<V: Fold + ?Sized>( _visitor: &mut V, _i: TraitBoundModifier, ) -> TraitBoundModifier { match _i { TraitBoundModifier::None => TraitBoundModifier::None, TraitBoundModifier::Maybe(_binding_0) => { TraitBoundModifier::Maybe(Token ! [ ? ](tokens_helper(_visitor, &_bindin...
Rust
0
t_episodes(3, verbose=False) print(f"✅ Environment test successful!") print(f" Buffer size: {len(rollout.replay_buffer)} episodes") # Test sequence sampling sequences = rollout.replay_buffer.sample_sequences(2) if sequences: print(f" Sample sequenc...
Python
1
#Ejercicio 6: Sistema de GestiOn de Vehículos class Vehiculo: def __init__(self, marca, modelo, año, precio): self.marca = marca self.modelo = modelo self.año = año self.precio = precio def mostrar_info(self): print(f"Marca: {self.marca}") print(f"Modelo: {self....
Python
1
ormat::fmt(self, f) } } impl ::protobuf::reflect::ProtobufValue for Params { fn as_ref(&self) -> ::protobuf::reflect::ReflectValueRef { ::protobuf::reflect::ReflectValueRef::Message(self) } } static file_descriptor_proto_data: &'static [u8] = b"\ \n!terra/market/v1beta1/market.proto\x12\x14ter...
Rust
0
'孤條') 孤韻 = [] for 非陰聲 in 韻尾題目[0][1]: 孤韻.append(('是{}韻尾'.format(非陰聲[2:]), [非陰聲])) 韻尾 |= cls._生問題.問題集(孤韻, cls.聲韻符號, '孤條') return 韻尾 @classmethod def 輔音(cls): 塞擦題目 = [ ('塞音', ['p', 'pʰ', 't', 'tʰ', 'k', 'kʰ', 'ʔ', ]), ('塞擦音', ['ts', 'tsʰ'...
Python
1
#!/usr/bin/env python3 """ Demo de Integração dos Novos Dados Demonstra a integração da Tabela ABC Farma e NESH ao sistema de auditoria fiscal """ import sys import os from pathlib import Path # Adicionar o diretório raiz ao path sys.path.append(os.path.join(os.path.dirname(__file__), "..")) from src.auditoria_icms....
Python
1
; 3usize], pub rate_iops_min: [libc::c_uint; 3usize], pub rate_process: libc::c_uint, pub rate_ign_think: libc::c_uint, pub ioscheduler: *mut libc::c_char, pub continue_on_error: error_type, pub profile: *mut libc::c_char, pub cgroup: *mut libc::c_char, pub cgroup_weight: libc::c_uint, ...
Rust
0
print(f"\n🔍 Schema Validation Results:") print(f" • Structure validation: {'✅ PASSED' if is_valid_structure else '❌ FAILED'}") print(f" • Official schema validation: {'✅ PASSED' if is_valid_official else '⚠️ SKIPPED/FAILED'}") if not is_valid_structure: print(f" • Structur...
Python
1