text
string
label_name
string
labels
int64
# This file is part of the Printrun suite. # # Printrun is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Printrun is distributed in ...
Python
1
wrap().CastTypeInfoToTensorInfo.unwrap()( typeinfo_ptr, &mut tensor_info_ptr, ) }; CheckStatus(g_ort, status).unwrap(); assert_ne!(tensor_info_ptr, std::ptr::null_mut()); let mut type_: ONNXTensorElementDataType = ONNXTensorElement...
Rust
0
s_stack_always(stack_info)) def warn(content: str, exc_info: logging._ExcInfoType = None, stack_info: bool = False): _logger.warning(content, exc_info=exc_info, stack_info=is_stack_always(stack_info)) def error(content: str, exc_info: logging._ExcInfoType = None): _logger.error(content, exc_info=exc_info, s...
Python
1
..Default::default() }; client .watch_list(&pods, namespace, listopts) .for_each(|event| { match event.typ { EventType::Added | EventType::Modified => { let p: Pod = serde_json::from_v...
Rust
0
Status(status) => { if !matched_numbers.contains(&status.code) { // Purpose: FailedDependency and MethodFailure both use 424, // but clearly they mustn't both go in here try!(write!(out, " {:u} => {},\n", status.code, status.iden...
Rust
0
nc("SC3:"," N/A ") #função para setar um mestre def setMaster(self, emulator): self.emulator = emulator self.update() #converte o inteiro no modo de execução def conversionMode(self, n): id = int(n) str = "" if(id == 1): str = "Came...
Python
1
(sound, os.path.join(sounds_dir, f"hurt_enemy_{i}.wav")) # Generate boss hurt sounds sound = generate_hurt(base_freq=200, duration=0.5, volume=0.7) save_sound(sound, os.path.join(sounds_dir, "hurt_boss_1.wav")) # Generate enemy death sounds for i in range(1, 3): sound = generate_de...
Python
1
# Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html # For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE # Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt from __future__ import annotations from typing import ( TYPE_CHECKING, A...
Python
1
RawFd, buf: &mut [u8]) -> Result<usize, ()> { let len = unsafe { libc::read(fd, buf.as_mut_ptr() as _, buf.len() as _) }; if len >= 0 { Ok(len as _) } else { Err(()) } } fn parse_terminal_keys(mut buf: &[u8], backspace_code: u8, keys: &mut Vec<Key>) { ...
Rust
0
norrSig { sig, hash_ty : SchnorrSighashType::Default }); }, 65 => { let (hash_ty, sig) = sl.split_last().expect("Slice len checked == 65"); let hash_ty = SchnorrSighashType::from_u8(*hash_ty) .map_err(|_| SchnorrSigError::InvalidSighashType(*ha...
Rust
0
from llama_index.readers.stripe_docs.base import StripeDocsReader __all__ = ["StripeDocsReader"]
Python
1
# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from typing_extensions import Literal from ..._models import BaseModel __all__ = ["ResponseFormatTextPython"] class ResponseFormatTextPython(BaseModel): type: Literal["python"] """The type of response format being defined...
Python
1
""" ErisPulse 消息处理模块 提供基于装饰器的消息事件处理功能 {!--< tips >!--} 1. 支持私聊、群聊消息分类处理 2. 支持@消息特殊处理 3. 支持自定义条件过滤 {!--< /tips >!--} """ from .base import BaseEventHandler from typing import Callable, Dict, Any class MessageHandler: def __init__(self): self.handler = BaseEventHandler("message", "message") def o...
Python
1
let re = Regex::new(&re_str).unwrap(); let mut count = 0; for x in messages { if re.is_match(x) { //println!("{:?}", x); count += 1; } } count } fn part2(rules: &HashMap<usize, &str>, messages: &Vec<&str>) -> usize { // println!("{:?} {:?}", rules, messages); let mut re_str = "^".to_owned(); re_str....
Rust
0
# https://github.com/BytedProtein/ByProt/blob/dd279dc85f76ee2c28c819b71bf3911b90159f0a/src/byprot/models/fixedbb/lm_design/modules/gvp_transformer_encoder.py import torch from torch import nn import esm class GVPTransformerEncoderWrapper(nn.Module): def __init__(self, alphabet, freeze=True): super().__init...
Python
1
tracing::warn!(%order_id, "No active rollover actor"); } } Settlement { order_id, msg: taker_to_maker::Settlement::Initiate { sig_taker }, } => { if let Err(NotConnected(_)) = self ...
Rust
0
import numpy as np import pandas as pd import torch from torch import nn def data_process_for_ml(data_filepath, bert_embedding_filepath, document_topics_filepath, manual_features_filepath): """ 加载并处理数据,合并BERT嵌入、文档主题分布和手工特征。 参数: - data_filepath: 数据集路径(用于提取标签) - bert_embedding_filepath: BERT特征向量路径 ...
Python
1
import tkinter as tk window = tk.Tk() items = [] labErr = tk.Label() def addItem(): item = ent.get() items.append(item) def displayAll(): label.config(text=items) def clearItem(): items.clear() def removeItem(): item = ent.get() if item in items: items.remove(item) def popItem(): ...
Python
1
mail_entry.place(relx=0.225,rely=0.50) #CURRENT BOOKINGS OF CUSTOMER passenger_ticket_desc=Message(internal_frame_2,text="Details about ticket of passenger based on ID ticket,coach,seat number,cost,date of flight and any other relevant information.",font=("Helvetica",10),width=800,bd=1,highlightbackground='BLACK...
Python
1
/#default-auto-field DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" # ----------------------------___CELERY SETTINGS ::::::::::::: CELERY_BROKER_URL = "amqp://guest:guest@localhost:5672//" CELERY_ACCEPT_CONTENT = ["application/json"] CELERY_RESULT_SERIALIZER = "json" CELERY_TASK_SERIALIZER = "json" CELERY_TIM...
Python
1
:ident, $a1:expr, $a2:expr, $a3:expr, $a4:expr, $a5:expr, $a6:expr) => { $crate::syscall6( $crate::nr::$nr, $a1 as usize, $a2 as usize, $a3 as usize, $a4 as usize, $a5 as usize, $a6 as usize, ) }; ($nr:ident, $a...
Rust
0
erSearch) def active(self): if self.controller.api is None: self.controller.show_frame(Login) Base.active(self) displayName = self.args['player']['commonName'] if self.args['player']['commonName'] is not '' else self.args['player']['lastName'] self.controller.status.set...
Python
1
#!/usr/bin/python # -*- mode: python -*- # # Copyright (C) 2007, 2008 Loic Dachary <loic@dachary.org> # Copyright (C) 2006 Mekensleep <licensing@mekensleep.com> # 24 rue vieille du temple, 75004 Paris # # This software's license gives you freedom; you can copy, convey, # propagate, redistribute and/o...
Python
1
""" pygments.styles.friendly ~~~~~~~~~~~~~~~~~~~~~~~~ A modern style based on the VIM pyte theme. :copyright: Copyright 2006-2025 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ from pygments.style import Style from pygments.token import Keyword, Name, Comment, Stri...
Python
1
(f"loss:{np.round(t.data.item(),2)}"), label='x') TSTensorSeqy(_y, m = '*g', label = 'y').show(ctx=ctx) TSTensorSeqy(pred, m = '-*r', label = 'pred').show(ctx=ctx) ax = axs[i*2 + 1] total = torch.zeros_like(block[list(block.keys())[0]]) for k, c in zip(block.keys(), ['y','k','g',...
Python
1
collect(); // TODO: This approach only relies on the first element. // It will not catch that types are possibly inconsistent. match types.first().and_then(|ty| ty.to_owned()) { Some(ty) => Some(Type::Array(Box::new(ty))), None => None, } } fn infer_function_call(name: &str, table: &Sy...
Rust
0
, i64_div_rem_trifecta; dbz14, u64_div_rem_asymmetric; dbz15, i64_div_rem_asymmetric; dbz16, u128_div_rem_delegate; dbz17, i128_div_rem_delegate; dbz18, u128_div_rem_trifecta; dbz19, i128_div_rem_trifecta; dbz20, u128_div_rem_asymmetric; dbz21, i128_div_rem_asymmetric; ); #[test] fn san...
Rust
0
import datetime from typing import TYPE_CHECKING import sqlalchemy as sa import sqlalchemy_utils as sa_utils import ulid from sqlalchemy.orm import Mapped, mapped_column, relationship from common.resources.database.postgres.alchemy_related import Base from common.resources.database.postgres.timescaledb.view_utils imp...
Python
1
e model view (drop date, src_ip, dst_ip, tags)") args = ap.parse_args() in_path = Path(args.input) out_dir = Path(args.outdir); out_dir.mkdir(parents=True, exist_ok=True) # 1) Load log(f"Loading {in_path}") df = pd.read_csv(in_path) # 2) Enforce types log("Enforce types") df = enf...
Python
1
1S+1N+1I for LDR, or 2N for STR pub(in super::super) fn exec_thumb_ldr_str_imm_offset< const LOAD: bool, const BYTE: bool, const OFFSET: u8, >( &mut self, insn: u16, ) -> CpuAction { let rb = insn.bit_range(3..6) as usize; let addr = self.gpr[rb].wrapp...
Rust
0
pressed. KeyPress { /// The key which was pressed. key: String, }, } #[derive(Serialize, Deserialize, Clone, Copy, Debug)] pub enum WebSocketIntent { /// Typing practice with quotes. PracticeQuote = 0, } #[derive(Serialize, Deserialize, Clone, Debug)] #[serde(tag = "op", content = "da...
Rust
0
sor.execute(sql_commands) messagebox.showinfo("Éxito", "El archivo SQL se ha ejecutado exitosamente.") display_text_status("El archivo SQL se ha ejecutado exitosamente.", "green") except cx_Oracle.DatabaseError as e: error, = e.args messagebox.showerror("Error", f'Error al ejecutar e...
Python
1
rFn::Compound { name: compound_kind, assigning: assignable, } } // Simple named functions kind => OperatorFn::Named { name: Cow::Borrowed(kind.to_string()), assigning: assignable, }, ...
Rust
0
0.0, 0.0).has_nans()); assert!(Point2::new(f32::NAN, f32::NAN).has_nans()); assert!(Point2::new(f64::NAN, f64::NAN).has_nans()); } #[test] #[should_panic] #[allow(unused)] fn div_zero_i64() { Point2::<i64>::zero() / 0; } #[test] #[should_panic] #[allow(unuse...
Rust
0
ched' result = { "question": question, "answer": answer, "messages": messages, "prediction": prediction, "termination": termination } return result if '<answer>' i...
Python
1
elf::default() } } <filename>src/model.rs use crate::builders::Template; use crate::db_entries::{Fld, ModelDbEntry, Tmpl}; use crate::Field; use anyhow::anyhow; use fancy_regex::Regex; use ramhorns::Template as RamTemplate; use std::collections::HashMap; const DEFAULT_LATEX_PRE: &str = r#" \documentclass[12pt]{art...
Rust
0
, sv599_maxkeepsearch: DWORD, sv599_minkeepcomplsearch: DWORD, sv599_maxkeepcomplsearch: DWORD, sv599_threadcountadd: DWORD, sv599_numblockthreads: DWORD, sv599_scavtimeout: DWORD, sv599_minrcvqueue: DWORD, sv599_minfreeworkitems: DWORD, sv599_xactmemsize: DWORD, sv599_threadprio...
Rust
0
build_toml(config)?; } let contents = fs::read_to_string(&config.config_file)?; Ok(contents) } /// Get a config object to use for all commands pub fn get_config() -> Result<TorConfig, Error> { // config is based on tor.yml let yml = load_yaml!("tor.yml"); let version = built_info::PKG_VERSION.to_string(); let a...
Rust
0
or query in queries] learnings = await asyncio.gather(*tasks) results = [] start_idx = 0 for queries in all_queries: learnings_str = '\n'.join(learnings[start_idx:start_idx + len(queries)]) results.append(learnings_str) start_idx += len(queries) if return_raw: retur...
Python
1
import torch import torchvision.datasets import torchvision.transforms as transforms from torch.utils.data import DataLoader import models from models import MNIST_target_net use_cuda=True image_nc=1 batch_size = 128 gen_input_nc = image_nc # Define what device we are using print("CUDA Available: ",torch.cuda.is_ava...
Python
1
in.add_view(TagView(name='Tags', endpoint='tags')) # ============= acaba aqui o Flask-Admin e rotas do admin ==================== # ============================================================================ if __name__ == '__main__': port = int(os.getenv('PORT', 5000)) # Em produção real, você não usaria ap...
Python
1
point not in self.plotted_points: # Only append and add to set if it's new self.x_buffer.append(self.pending_x) self.y_buffer.append(value) self.plotted_points.add(current_poin...
Python
1
e future a cryptographic weakness is found in the CSPRNG being used, /// or a flaw in the implementation, occasionally reseeding should make /// exploiting it much more difficult or even impossible. /// /// Use [`ReseedingRng::new`] with a `threshold` of `0` to disable reseeding /// after a fixed number of generated by...
Rust
0
; } } impl From<i32> for BigInt { fn from(v: i32) -> BigInt { let (abs, negative) = if v < 0 { (u32::MAX - v as u32 + 1, true) } else { (v as u32, false) }; return BigInt { negative, weight: 2, digits: vec![ ...
Rust
0
[s for s in sentences if len(s.split()) > 5], max_sentences=args.max_sentences, batch_size=args.batch_size, max_length=args.max_length, k_min=args.k_min, k_max=args.k_max, ) print("Model Silhouette Scores (higher is better):") for r in ...
Python
1
"TEXT", "RICH_TEXT", "DATE", "TIME", "DATE_TIME", "LINK", "ATTACHMENT", "TLP", "CPE", "CVE", "CVSS", name="old_enum", ), ...
Python
1
#! /usr/bin/python2 # -*- coding: utf-8; -*- # # (c) 2013 booya (http://booya.at) # # This file is part of the OpenGlider project. # # OpenGlider is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version ...
Python
1
ert(0.0) += 1.0; } *end .entry(prev.to_string()) .or_insert(HashMap::new()) .entry(word.to_string()) .or_insert(0.0) += 1.0; } *middle .entry(prev.to_string()) .or_insert(HashMap::new()) .entry(word.to_string()) .or_insert(0.0) += 1.0; } ...
Rust
0
xtern crate ggez; extern crate dodge_rock; use std::env; use std::path::PathBuf; // 可読性のため、use宣言を二つに分ける use ggez::{ ContextBuilder }; use ggez::event::run; use dodge_rock::{ args, etc }; use dodge_rock::core_state::CoreState; use dodge_rock::conf::GameConf; fn ggez_init(conf: GameConf) { // TODO 今は直書きだけど、後々変更を...
Rust
0
c<_>>(); BftContent(mb) } } impl Encodable for BftContent { fn rlp_append(&self, s: &mut RlpStream) { s.append_list(&self.0); } } impl Decodable for BftContent { fn decode(rlp: &Rlp) -> Result<Self, DecoderError> { let res = rlp .as_list::<u8>() .map_err...
Rust
0
名称, 后缀 = 剪去后缀(子级.animation_data.action.name) if 后缀: 子级.animation_data.action.name = 名称 子级.animation_data.action.name += "_" + 角色 else: # 如果是刚体和关节的父级空物体 if 偏好.重命名刚体和关节: ############### 如果开...
Python
1
41, 747), (749, 749), (751, 767), (885, 885), (900, 901), (8125, 8125), (8127, 8129), (8141, 8143), (8157, 8159), (8173, 8175), (8189, 8190), (12443, 12444), (42752, 42774), (42784, 42785), (42889, 42890), (43867, 43867), (43882, 43883), (64434, 64449)...
Rust
0
return rain, norain, image_name def rgb_to_y(x): rgb_to_grey = torch.tensor([0.256789, 0.504129, 0.097906], dtype=x.dtype, device=x.device).view(1, -1, 1, 1) return torch.sum(x * rgb_to_grey, dim=1, keepdim=True).add(16.0) def psnr(x, y, data_range=255.0): x, y = x / data_range, y / data_range m...
Python
1
g"] for err in e.errors()]) error_msg += ( "\n\nPlease paste your API key into the textbox on the right side :)" ) gr.Warning(error_msg) history += [[user_txt, error_msg]] yield "", history except Exception as e: msg = "\n\nPlease check if you inserted a c...
Python
1
up=pileup, proportion=proportion ) if total_compressed % 500 == 0 and total_compressed > 0: table_dict = write_table_file(table_file, table_dict, tensor_shape, param.label_size, f...
Python
1
algid', ALG_ID), ('encryptedkey', ':'), ) class DPAPI_DOMAIN_RSA_MASTER_KEY(Structure): structure = ( ('cbMasterKey', '<L=0'), ('cbSuppKey', '<L=0'), ('buffer', ':'), ) def privatekeyblob_to_pkcs1(key): ''' parse private key into pkcs#1 format :param key: :r...
Python
1
g", &main_menu_button_props.id), ..Default::default() }), width: ImageBoxSizeValue::Exact(SIZE), height: ImageBoxSizeValue::Exact(SIZE), ..Default::default() }) .with(ContentBoxItemLayout { margin: Rect { bottom: 26.0, ..Default::defaul...
Rust
0
from abc import ABCMeta, abstractmethod class BaseVectorStore(metaclass=ABCMeta): @abstractmethod async def create(self, *args, **kwargs): """Creating a new collection or index""" raise NotImplementedError @abstractmethod async def insert(self, *args, **kwargs): """Insert Vec...
Python
1
ne_channels[-3], kernel_size=2, stride=2), OneConv(backbone_channels[-3],backbone_channels[-3]), nn.ConvTranspose2d(backbone_channels[-3], backbone_channels[-4], kernel_size=2, stride=2), OneConv(backbone_channels[-4],backbone_channels[-4]), nn.Conv2d(back...
Python
1
dd the seed too. current_layer.use_text(format!("HDSeed: {}, Path: {}", seed, path).as_str(), 8, Mm(10.0), Mm(ypos-25.0), &font); } /** * Insert the given QRCode into the PDF at the given x,y co-ordinates. The qr code is a vector of RGB values. */ fn add_qrcode_image_to_page(current_layer: &PdfLayerReference,...
Rust
0
mplete git clone for tokei job"))?; if !exit_status.success() { return Err(anyhow!("Git clone for tokei job was not successful")); } Ok(()) }.await?; let paths_with_defaults = if let Some(paths) = paths { if paths.is_empty() { vec![String::from("")] ...
Rust
0
returns proof json. /// /// Note: Proof instance deallocation must be performed by calling hl_crypto_cl_proof_free. /// /// # Arguments /// * `proof_json` - Reference that contains proof json. /// * `proof_p` - Reference that will contain proof instance pointer. #[no_mangle] pub extern fn hl_crypto_cl_proof_from_json(p...
Rust
0
"""Generate party configuration files. Example: three parties on hostnames foo, bar, and baz using port 11000. Configuration files are generated as follows: generate_config_files.py foo:11000 bar:11000 baz:11000 If the parties are on the same host (localhost), then use different port numbers for each party. Eac...
Python
1
modify as required, referencing your RM's clock tree, /// or Stm32Cube IDE's interactive clock manager. Apply settings by running `.setup()`. pub struct Clocks { /// The input source for the system and peripheral clocks. Eg HSE, HSI, PLL etc pub input_src: InputSrc, /// Enable and speed status for the main...
Rust
0
let a3 = a.3; let dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3; let invDot = if dot < EPSILON { 0. } else { 1. / dot }; // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0 out.0 = -a0 * invDot; out.1 = -a1 * invDot; out.2 = -a2 * invDot; ...
Rust
0
(x.angle_with_in_degrees(y), 90.0, max_relative = 0.001); assert_relative_eq!(x.angle_with_in_degrees(-y), 90.0, max_relative = 0.001); assert_relative_eq!(y.angle_with_in_degrees(x), 90.0, max_relative = 0.001); assert_relative_eq!(y.angle_with_in_degrees(-x), 90.0, max_relative = 0.001); ...
Rust
0
""" Loop Examples in Python This script demonstrates different types of loops in Python: 1. While loop 2. For loop with range 3. For loop with string 4. Break statement """ # ------------------------------- # Example 1: While loop (counting from 1 to 5) # ------------------------------- count = 1 # Initialize counte...
Python
1
y=z4, line=dict(color='rgba(0, 0, 0, .3)', width=1, dash='dot'), text=['5% growth rate' for i in pseduoDay], hovertemplate='<b>%{text}</b><br>' + ...
Python
1
{ fn get_value(&self) -> u32 { 54321 } } StackDST::new_stable(TwoStruct, |p| p as _).unwrap() } let i1 = instance_one(); let i2 = instance_two(); assert_eq!(i1.get_value(), 12345); assert_eq!(i2.get_value(), 54321); } #[test] fn closure() { ...
Rust
0
import os from typing import List, Union import numpy as np import wandb from diffusers.utils import export_to_video from diffusers.utils.hub_utils import load_or_create_model_card, populate_model_card from PIL import Image def save_model_card( args, repo_id: str, videos: Union[List[str], Union[List[Imag...
Python
1
enumerate() .cycle() .skip(egressor.next_pull_ingressor) .take(egressor.from_ingressors.len()); for (port, from_ingressor) in rotated_iter { match from_ingressor.try_recv() { Ok(Some(packet)) => { unpark_and_wake(&egressor.task_...
Rust
0
 ġXc@stdZdddZeZdddZeZdddZdddZyddlTWne k ronXdS( sBisection algorithms.icCs|dkrtdn|dkr6t|}nxA||kry||d}|||krl|}q9|d}q9W|j...
Python
1
atchReadingError> { let (sender, receiver) = mpsc::channel(); let receiver = Arc::new(Mutex::new(receiver)); let submit_thread = thread::spawn(move || { http_submitter(target, rate as u64, receiver); }); let mut feeder = BatchListFeeder::new(reader); loop { match feeder.next_b...
Rust
0
] for test in tests: self.assertEqual( cmd.parse_create(test), "Invalid package naming" ) self.assertEqual( cmd.parse_create("~" + test), "Invalid package naming" ) @patch( "Java...
Python
1
const COLOR_AROUSAL_MANDALA_OPEN: Color = Color { // yellow orange, Low arousal 255, 174, 66 r: 255.0 / 256.0, g: 174.0 / 256.0, b: 66.0 / 256.0, a: 1.0, }; const COLOR_BREATH_MANDALA_CLOSED: Color = Color { //Blue, transparent, breath out r: 10. / 256., g: 10. / 256., b: 256. / 256....
Rust
0
_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_col_span_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_headers_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; fn connect_property_height_notify<F: Fn(&Self) + 'stati...
Rust
0
<reqwest::Response, Error> { let client = reqwest::Client::new(); client .get(url) .header("User-Agent", user_agent) .send() .await .map_err(Into::into) } #[cfg(feature = "scraper")] pub async fn wget_html<U: IntoUrl>(url: U, user_agent: &str) -> Result<scraper::Html, Er...
Rust
0
` /// let x = "should be ignored!"; /// ``` x: T, } /// ``` /// let x = "should be ignored!"; /// ``` pub static StaticFoo: u32 = 0; /// ``` /// let x = "should be ignored!"; /// ``` pub const ConstFoo: u32 = 0; /// ``` /// let x = "should be ignored!"; /// ``` pub type TypeFoo = u32; <reponame>yeslogic/...
Rust
0
).unwrap(); print!("Ratio Height: "); std::io::stdout().flush().unwrap(); std::io::stdin().read_line(&mut height_string).unwrap(); if width_string.trim().parse::<f32>().is_ok() && height_string.trim().parse::<f32>().is_ok() { break; ...
Rust
0
import datetime import json import os from loguru import logger as eval_logger from lmms_eval.tasks._task_utils.file_utils import generate_submission_file from lmms_eval.tasks.olympiadbench.olympiadbench_evals import OlympiadBenchEvaluator dir_name = os.path.dirname(os.path.abspath(__file__)) try: olympiadbench...
Python
1
from random import random, Random from typing import List from bubble_sort import swap def quick_sort(to_sort: List[int], low: int, high: int): if low < high: pivot = partition(to_sort, low, high) quick_sort(to_sort, low, pivot - 1) quick_sort(to_sort, pivot + 1, high) def partition(to_s...
Python
1
text.insert(END,"Total Mainstream student found by DBSCAN : "+str(len(dbscan_main))+"\n") text.insert(END,"Total Anomalous student found by DBSCAN : "+str(len(dbscan_noise))+"\n\n") text.insert(END,"Below are the Anomalous Students ID : \n\n") text.insert(END,str(dbscan_noise)) plt.title('Estimated...
Python
1
import torch from transformers import StoppingCriteria class KeywordsStoppingCriteria(StoppingCriteria): def __init__(self, keywords, tokenizer, input_ids): self.keywords = keywords self.keyword_ids = [tokenizer(keyword).input_ids for keyword in keywords] self.keyword_ids = [keyword_id[0] f...
Python
1
# code adapted from https://github.com/exx8/differential-diffusion import torch class DifferentialDiffusion(): @classmethod def INPUT_TYPES(s): return {"required": {"model": ("MODEL", ), }} RETURN_TYPES = ("MODEL",) FUNCTION = "apply" CATEGORY = "_for_testing" ...
Python
1
}, 999 => { crate::rt::read_repeated_message_into_vec(wire_type, is, &mut self.uninterpreted_option)?; }, _ => { crate::rt::read_unknown_or_skip_group(field_number, wire_type, is, self.mut_unknown_fields())?; ...
Rust
0
); impl<Output: for<'a> CtorNew<&'a Output>, P: Deref<Target = Output>> Ctor for Copy<P> { type Output = Output; unsafe fn ctor(self, dest: Pin<&mut MaybeUninit<Output>>) { Output::ctor_new(&*self.0).ctor(dest); } } /// !Unpin to override the blanket Ctor impl. impl<P> !Unpin for Copy<P> {} /// ...
Rust
0
'--world_size', default=1, type=int, help='number of distributed processes') parser.add_argument('--dist_url', default='env://', help='url used to set up distributed training') parser.add_argument('--distributed', default=True, type=bool) args = parser.parse_args() config = yaml.load(open(args.conf...
Python
1
annotations: HashMap::new(), } } pub fn set_name(&mut self, name: String) { self.annotations.insert(NAME_ANNOTATION.to_string(), name); } pub fn get_name(&self) -> Option<&String> { self.annotations.get(NAME_ANNOTATION) } pub(crate) fn remove_name(&mut self) { ...
Rust
0
ab)), &Binding::Scalar(TypedValue::Ref(attr))) => Some((vocab, attr)), (_, _) => None, } }); // TODO: validate that attributes.keys is a subset of versions.keys. for (vocab, attr) in pairs { if let Some...
Rust
0
= keyword("true") { Constant::Bool(true) } / keyword("false") { Constant::Bool(false) } / n:number() { n } / type_:literal_type()? str:escaped_string() { Constant::String(type_.unwrap_or(Literal::String), Ref::new(str)) } rule seq() -> Seq<SourceA...
Rust
0
ile._Tile("bcn", extents, offset, (n, self.pixel_format)) ] else: self.tile = [ImageFile._Tile("raw", extents, 0, rawmode or self.mode)] def load_seek(self, pos: int) -> None: pass class DdsRgbDecoder(ImageFile.PyDecoder): _pulls_fd = True def decode(self, buffer:...
Python
1
ta) if self.network.config.TEST_FAIL_HTLCS_AS_MALFORMED: raise OnionRoutingFailure(code=OnionFailureCode.INVALID_ONION_VERSION, data=failure_data) if self.network.config.TEST_FAIL_HTLCS_WITH_TEMP_NODE_FAILURE: raise OnionRoutingFailure(code=OnionFailureCode.TEMPORARY_NODE_FAILURE...
Python
1
PageTable = // unsafe { &mut *(boot_info.p4_table_addr as *mut PageTable) }; // // let rec_page_table = // RecursivePageTable::new(&mut page_table).expect("recursive page table creation failed"); // // let _memory_controller = memory::init(boot_info, rec_page_table); // ...
Rust
0
touch: *mut WlTouch) -> ()>, // Touch event changed shape (ellipse). shape: Option< extern "C" fn( data: *mut c_void, touch: *mut WlTouch, id: i32, major: i32, minor: i32, ) -> (), >, // Update orientation of touch point or...
Rust
0
(1, 4) | (2, 4) => IO::from(val).unwrap() << (offset * 8) as usize, (2, 1) | (4, 1) | (4, 2) => IO::from(val >> (offset * 8) as usize).unwrap(), _ => unreachable!() } } pub trait Cache { const READ: fn(&Buffer, u32) -> Self; const WRITE: fn(&mut Buffer, u32, Self); } impl Cache for u8 { ...
Rust
0
if self.size() != data.len() { Err(FromBytesError::InvalidSize) } else { let mut hash = Vec::with_capacity(self.base58check_prefix().len() + data.len()); hash.extend(self.base58check_prefix()); hash.extend(data); hash.to_base58check() ...
Rust
0
vertex_ids: Vec::new(), texcoord_ids: Vec::new(), normal_ids: Vec::new(), }; for tri in trivec.tris { for point in &tri.points { verts.push(Vector3::new(point.vertex.x, point.vertex.y, point.vertex.z)); texcoords.push(Vecto...
Rust
0
if __name__ == "__main__": # Do not change the line below a, b = 10, 5 # Modify variable `c` to make this script work without errors. # Use variables a and b to build a value for variable c c = a + b # Do not change the line below assert c == 15 print (c)
Python
1
import os from distutils.msvccompiler import MSVCCompiler as _MSVCCompiler from .system_info import platform_bits def _merge(old, new): """Concatenate two environment paths avoiding repeats. Here `old` is the environment string before the base class initialize function is called and `new` is the string ...
Python
1
# ========= Copyright 2023-2024 @ CAMEL-AI.org. 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 requ...
Python
1