text
string
label_name
string
labels
int64
import torch def flatten_ckpt_into_vec(ckpt): vec = [] for param in ckpt.values(): vec.append(param.flatten()) return torch.cat(vec) def select_trainable_params(model): params = {} for n, p in model.named_parameters(): if 'embed' not in n and 'Embedding' not in n: para...
Python
1
e, &dependencies, chain_name, session_account, ) } } /// Container for payment-related arguments used while constructing a `Deploy`. /// /// ## `payment_args_simple` /// /// For methods taking `payment_args_simple`, this parameter is the payment contract arguments, in //...
Rust
0
onsoante. """ letra = input("Digite qualquer letra do alfabeto: ").upper() if letra == "A" or letra == "E" or letra == "I" or letra == "O" or letra == "U": print(f"A letra '{letra}' é uma vogal.") else: print(f"A letra '{letra}' é uma consoante.") """ #15 Faça um programa para a leitura de duas notas parciais d...
Python
1
wargs) -> ClientArgs: """Get a client from the pool and return it as a context manager.""" if len(self) == 0: raise APIKeyPoolEmptyError("api key pool is empty") self._index = random.randint(0, len(self) - 1) return self.queue[self._index].client_args def __exit__(self...
Python
1
} #[test] fn random_100() { let mut arr = thread_rng().gen_iter::<u32>().take(100).collect::<Vec<_>>(); quick3way_sort(&mut arr); assert!(is_sorted(&arr)); } } <filename>src/submissions/routes.rs use chrono::Local; use diesel::dsl::any; use diesel::prelude::*; use diesel::{QueryDs...
Rust
0
Dated { // V date: Date, time: Option<Time>, }, DistributedAvailD { // D num: usize, dists: Vec<ParsedDistributedAvailDistribution>, }, } #[derive(Debug, Clone)] pub struct Record<'a> { phantom: PhantomData<&'a ()>, } #[derive(Debug, Copy, Clone)] #[cfg_a...
Rust
0
stage_id % len(self._colors)] dot.node(node.node_id, node_desc, color=color, style='filled') else: dot.node(node.node_id, node_desc) for node in self.nodes.values(): if node.node_id not in self.edges: continue ...
Rust
0
import customtkinter as ctk from .videowidget import VideoFrame class Home(ctk.CTkFrame): def __init__(self, master, backend, **kwargs): super().__init__(master, **kwargs) self.backend = backend self.sidebar_width = 400 self.sidebar_visible = True self.video_frame = ...
Python
1
::{DispatcherBuilder, Entity, Read, System, Write}; use feather_blocks::Block; use feather_core::world::{BlockPosition, ChunkMap}; use crate::systems::{BLOCK_FALLING_CREATION, BLOCK_UPDATE_PROPAGATE}; use hashbrown::HashSet; lazy_static! { /// List of block types that need to be notified /// of adjacent bloc...
Rust
0
fe2d; pub const XKB_KEY_ISO_Fast_Cursor_Up: xkb_keysym_t = 0xfe2e; pub const XKB_KEY_ISO_Fast_Cursor_Down: xkb_keysym_t = 0xfe2f; pub const XKB_KEY_ISO_Continuous_Underline: xkb_keysym_t = 0xfe30; pub const XKB_KEY_ISO_Discontinuous_Underline: xkb_keysym_t = 0xfe31; pub const XKB_KEY_ISO_Emphasize: xkb_keysym_t = 0xfe3...
Rust
0
""" Tests for the log viewer component. Tests log viewing functionality including log display, filtering, and log management. """ import pytest from unittest.mock import Mock, patch, MagicMock import sys # Mock PySide6 before importing any modules that depend on it with patch.dict('sys.modules', { 'PySide6': Moc...
Python
1
continue features.append('%s=%s' % (param, p[param])) args = [self.href, p['target']] if features: args.append(','.join(features)) return ', '.join(map(js_repr, args)) def _html_attrs(self): attrs = list(self.attrs.items()) onclick = ('window...
Python
1
cfg(not(any(feature = "config-static", feature = "config-zk")))] compile_error!("At least one config discovery feature must be activated."); // Config reader #[cfg(not(any(feature = "config-file")))] compile_error!("At least one config reader feature must be activated."); // Config format #[cfg(not(any(feature = "con...
Rust
0
clld }; if oref { x = clld * sinpik(a - D1_28 * ((a * (1. / D1_28)) as i32 as f64)); } clld = if otiny { dd(a * (D1_60 * D1_60), 0.) } else if oref { x } else { y }; (clc, clln / clld) } pub fn ldexp(x: f64, mut exp: i32) -> f64 { if exp > 210...
Rust
0
ame, model_class=self.model_class, endpoint=self.endpoint, requester=self._requester, asynchronous=self._asynchronous, ) def get(self, name: str | None = None, id: str | None = None): model_obj = self._get_details_from_id_name(name, id) endpoi...
Python
1
core.HomeAssistant(config_dir) loader.async_setup(hass) hass.config_entries = ConfigEntries(hass, {}) await ar.async_load(hass) await dr.async_load(hass) await er.async_load(hass) await ir.async_load(hass, read_only=True) components = await async_check_ha_config_file(hass) await hass.as...
Python
1
from datetime import datetime from src.commons.database.mySql.config_connect_my_sql import db from src.models.api import Api def create_api(topic_id, api_name, api_type, format_api, endpoint): new_api = Api( topic_id=topic_id, api_name=api_name, api_type=api_type, format_api=forma...
Python
1
(); type MinimumPeriod = MinimumPeriod; type WeightInfo = (); } impl pallet_sudo::Config for TestRuntime { type Event = Event; type Call = Call; } impl EscrowTrait for TestRuntime { type Currency = Balances; type Time = Timestamp; } parameter_types! { pub const MaxRequests: u32 = 2; ...
Rust
0
y_loss = -tf.reduce_mean(surrogate_loss) # HL-Gauss classification loss critic_loss = tf.reduce_mean(tf.losses.categorical_crossentropy( y_true=self.model.targets_to_probs(gvs), y_pred=tf.boolean_mask(all_vf_preds_cat[:-1], mask), ...
Python
1
::align_of::<cl_double16>(), 128usize, concat!("Alignment of ", stringify!(cl_double16)) ); assert_eq!( unsafe { &(*(::std::ptr::null::<cl_double16>())).s as *const _ as usize }, 0usize, concat!( "Offset of field: ", stringify!(cl_double16), ...
Rust
0
_name): if varname in kwargs["grad_var_to_var"]: fwd_name = kwargs["grad_var_to_var"][varname] if not main_block._find_var_recursive(fwd_name): continue if is_parameter_related(fwd_name, main_block): ...
Python
1
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2015 jaidev <jaidev@newton> # # Distributed under terms of the MIT license. """ =========================================== Morlet Scalogram of a Multicomponent Signal =========================================== This example demonstrates ...
Python
1
t, f32, f64}; use std::collections::{HashMap, HashSet, BTreeMap, BTreeSet, LinkedList, VecDeque}; use numtoa::NumToA; /// Trait that can be automatically derived for structs and enums. When it's derived, a [Debug](https://doc.rust-lang.org/std/fmt/trait.Debug.html) implementation is also added, /// so the object can ...
Rust
0
y = packet_data!({"readonly": "data"}); let streamid = "test"; let key = EllipticCurve::new(streamid).unwrap(); let streamid2 = "test2"; let key2 = EllipticCurve::new(streamid2).unwrap(); let signees = signees![{streamid => Key::Ec(key)}, {streamid2 => Key::Ec(key2)}];...
Rust
0
panded[:d1, :d2] = proj_mat proj_mat = proj_mat_expanded # previous implementation use new_zeros, new_one yeilds better results points_4 = torch.cat( [points_3d, points_3d.new_ones(*points_shape)], dim=-1) point_2d = torch.matmul(points_4, proj_mat.t()) point_2d_res = point_2d[..., :2] ...
Python
1
from typing import List, Optional from sqlalchemy.orm import Session from repositories.evolution_repository import ( get_evolution, get_evolutions, create_evolution, update_evolution, delete_evolution, search_evolution_by_name ) from schemas.evolution_schemas import EvolutionBase from models.pok...
Python
1
_pos(42, None)); /// }); /// }); /// # assert_eq!(cbor.as_slice(), vec![0x81u8, 0xa1, 0x61, b'y', 0x18, 42]); /// ``` fn write_dict<F>(self, tags: impl IntoIterator<Item = u64>, f: F) -> Self::Output where F: FnOnce(&mut DictWriter<'_>), { self.write_dict_ret(tags, f).0 ...
Rust
0
OR_ATTACHMENT9_EXT`] /// * [`GL_COLOR_ATTACHMENT9_NV`] /// * [`GL_DEPTH`] /// * [`GL_DEPTH_ATTACHMENT`] /// * [`GL_DEPTH_ATTACHMENT_EXT`] /// * [`GL_DEPTH_ATTACHMENT_OES`] /// * [`GL_DEPTH_STENCIL_ATTACHMENT`] /// * [`GL_STENCIL`] /// * [`GL_STENCIL_ATTACHMENT_EXT`] /// * [`GL_STENCIL_ATTACHMENT_OES`] pub type Invalida...
Rust
0
nd('shutit skeleton --output_dir --base_image ' + shutit.cfg[self.module_id]['base_image'] + ' --pattern docker --name /tmp/shutit_copyserver --domain shutit.copied_server --delivery docker') shutit.send('cd /tmp/shutit_copyserver') shutit.send('blueprint create shutit_copyserver') shutit.send('blueprint show -S ...
Python
1
import torch import torch.nn.functional as F class FeatureMatchLoss(torch.nn.Module): """Feature matching loss module.""" def __init__( self, average_by_layers=True, average_by_discriminators=True, include_final_outputs=False, ): """Initialize FeatureMatchLoss modu...
Python
1
import streamlit as st import pandas as pd import plotly.express as px from datetime import date, datetime from modules.graph import create_work_hours_graph, prepare_work_hours_graph_data, create_daily_attendance_chart from modules.api_client import fetch_monthly_summary, fetch_holidays, fetch_aggregate_attendance, fet...
Python
1
POLYGON (({} {}, {} {}, {} {}, {} {}, {} {}))", w, n, e, n, e, s, w, s, w, n, )) } /// Serialize the geometry as JSON. pub fn json(&self) -> Result<String> { let c_json = unsafe { ogr::OGR_G_ExportToJson(self.c_geometry()) }; ...
Rust
0
integer: 2, inocently_mispellable: () } } fn new_with_secret_three() -> Self { Self { secret_integer: 3, egregiously_nonexistent_field: () } } } } fn main() { use submodule::Demo; let demo = Demo::default(); let innocent_field_misaccess = demo.inocently_mispellabl...
Rust
0
ogits,dummy_label) # dummy_dy_dx = torch.autograd.grad(loss, net.parameters(), create_graph=True,allow_unused=True) # dummy_dy_dx = (_.to(device) for _ in dummy_dy_dx if _ is not None) # # set new ids # dummy_ids = torch.argmax(dummy_logits.detach(), dim=-1).unsqueeze(0) # if le...
Python
1
>, Self: Mul<f32, Output = Self> + Div<f32, Output = Self>, Self: DivAssign<f32>, { } pub trait Spline<Value> { fn evaluate(&self, t: f32) -> Value; fn grid(&self) -> &[f32]; /// There must be at least two grid values! /// This doesn't work if there are NaNs fn clamp_parameter_and_find_in...
Rust
0
_LONG: &'static str = "lushr"; pub const AND_INT: &'static str = "iand"; pub const AND_LONG: &'static str = "land"; pub const OR_INT: &'static str = "ior"; pub const OR_LONG: &'static str = "lor"; pub const XOR_INT: &'static str = "ixor"; pub const XOR_LONG: &'static str = "lxor"; pub co...
Rust
0
move |yielder, ()| { for i in 1..4 { yielder.suspend(i) } }); info!("{:?}", gen.resume(())); // Some(1) info!("{:?}", gen.resume(())); // Some(2) info!("{:?}", gen.resume(())); // Some(3) info!("{:?}", gen.resume(())); // None } } fn pci_stuff() { let mut pci = Pci::new(); pci....
Rust
0
from calculate_angle import calculate_angle def address(first_ankle_center_x,landmarks_dict,Time,current_time,image_width,address_tmp): right_wrist = (landmarks_dict['left_wrist'][0] *image_width) if(address_tmp==0 and (first_ankle_center_x > right_wrist) ): #오차값 5부여 (x좌표가 동일하지 않는 경우가 존재 address_tmp = ...
Python
1
steps += 1; if point == target { return Some(steps); } } return None; } fn shortest_intersection_combined_distance(&self, other: &Wire) -> i64 { let mut shortest = std::i64::MAX; for point in self.intersections(other) { ...
Rust
0
# from __future__ import annotations import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np # from matplotlib import _api from matplotlib.axes import Axes from matplotlib.collections import Collection from matplotlib.colors import is_color_like from matplotlib.figure import Figure from matplotlib....
Python
1
from phi.assistant import Assistant from phi.llm.anyscale import Anyscale from phi.tools.duckduckgo import DuckDuckGo assistant = Assistant(llm=Anyscale(), tools=[DuckDuckGo()], show_tool_calls=True, debug_mode=True) assistant.print_response("Whats happening in France? Summarize top stories with sources.", markdown=T...
Python
1
ster creation time. If unspecified, STORAGE_SSD will be used. #[prost(enumeration = "StorageType", tag = "8")] pub default_storage_type: i32, } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, ::prost::Enumeration)] #[repr(i32)] pub enum StorageType { /// The storage type used is unspecifi...
Rust
0
lgorithm)?; match named_curve { PKIXALG_SECP256R1 => { let ecdsa = VerifyingKey256::from_sec1_bytes(spki.subject_public_key); if let Ok(ecdsa) = ecdsa { let s = Signature256::from_der(signature); if let Ok(s) = s { ...
Rust
0
supported!") } Some(ID_AA64MMFR0_EL1::PARange::Value::Bits_52) => { println!("[i] MMU: Up to 52 Bit physical address range supported!") } _ => println!("[i] MMU: Invalid PARange specified!"), } let tcr = TCR_EL1.extract(); match ...
Rust
0
s_noex!($ex_name, $name, $rty, $field_name: $field_ty); }; ($ex_name: ident, $name:ident, $rty: ty, $($field_name: ident: $field_ty: ty),*) => { fn $ex_name<'a, 'b>( &'a self, $($field_name: $field_ty,)* extra: ExtendedMap, ) -> Pbfr<'b, $rty> where ...
Rust
0
import gc from typing import Any, Dict, Union import torch from accelerate.logging import get_logger logger = get_logger("finetrainers") def get_memory_statistics(precision: int = 3) -> Dict[str, Any]: memory_allocated = None memory_reserved = None max_memory_allocated = None max_memory_reserved = ...
Python
1
} #[rustfmt::skip] fn main() { let f = |x: &dyn TT| x.func(); //[default]~ ERROR: mismatched types //[nll]~^ ERROR: borrowed data escapes outside of closure } <reponame>wickerwaka/rust<gh_stars>1-10 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at...
Rust
0
# test_lrivp.py # # To run on Linux Mint 21.1: # $ PYTHONDONTWRITEBYTECODE=1 pytest-3 # # PJ, 2020-03-30 adapted from osher_riemann-test.py # 2023-06-12 convert to pytest # from gdtk.gas import GasModel, GasState, GasFlow from gdtk.numeric.zero_solvers import secant import math import os import subprocess import s...
Python
1
onnect_signals(self): """连接信号""" self.queue_manager.task_started.connect(self._on_task_started) self.queue_manager.task_completed.connect(self._on_task_completed) self.queue_manager.task_failed.connect(self._on_task_failed) self.queue_manager.queue_completed.connect(self._on_queu...
Python
1
import tkinter as tk from tkinter import ttk from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg # Create the main application window root = tk.Tk() root.title("Graph Plotter") # Function to plot the graph def plot_graph(): expression = entry.get() # Get the user-...
Python
1
tton1, XButton2 => sfMouseXButton2, } } } impl MouseButton { /// Return whether this mouse button is currently pressed. /// /// Queries the real-time state of the mouse, even if buttons have been /// pressed or released while no window was focused and no events were /// trig...
Rust
0
c![0x42]); set_tm_price_test!(set_tm_34, 34, 4000, 0x7BFB7, vec![0x14]); set_tm_price_test!(set_tm_35, 35, 4000, 0x7BFB8, vec![0x42]); set_tm_price_test!(set_tm_36, 36, 4000, 0x7BFB8, vec![0x44]); set_tm_price_test!(set_tm_37, 37, 4000, 0x7BFB9, vec![0x45]); set_tm_price_test!(set_tm_38, 38, 4000, 0x7BFB9, vec![0x24]);...
Rust
0
Result<bool, Self::Error> { let node_id = transition.node_id(); let key = strict_serialize(&node_id)?; let value = strict_serialize(transition)?; self.transitions_db.put_keyed(&key[..], &value[..])?; Ok(true) } fn remove_transition(&mut self, id: &NodeId) -> Result<bool...
Rust
0
def ladderLength(beginWord, endWord, wordList): wordList = set(wordList) if endWord not in wordList: return 0 n = len(beginWord) Q = [[beginWord, 1]] visited = set() visited.add(beginWord) while Q: curr = Q.pop(0) if curr[0...
Python
1
cfg.tissue_rgb, W_target=W_target, stain_unmixing_routine_params=stain_unmixing_routine_params) assert tuple( [int(tissue_rgb_normalized[..., i].mean()) for i in range(3)], ) in {(188, 125, 175), (188, 124, 175), (191, 132, 179), (191, 131, 179)} # Macenko - Masked, usin...
Python
1
= ptr::null_mut(); let ret = ffi::gtk_icon_info_load_surface(self.to_glib_none().0, for_window.0, &mut error); if error.is_null() { Ok(from_glib_full(ret)) } else { Err(from_glib_full(error)) } } } fn load_symbolic<'a, 'b, 'c, P: Into<Option<&'a gdk::RGBA>>, Q: Into<Option<&'b ...
Rust
0
, arg1: *const ::std::os::raw::c_void, ) -> ::std::os::raw::c_int; } extern "C" { pub fn Fl_Tabs_add(self_: *mut Fl_Tabs, arg1: *mut ::std::os::raw::c_void); } extern "C" { pub fn Fl_Tabs_insert( self_: *mut Fl_Tabs, arg1: *mut ::std::os::raw::c_void, pos: ::std::os::raw::c_i...
Rust
0
; MilliAmperes(current) }<gh_stars>10-100 use std::io::{Read, Write}; use crate::{CodePair, DxfError, DxfResult, Handle, Point, Vector}; use crate::code_pair_put_back::CodePairPutBack; use crate::code_pair_writer::CodePairWriter; use crate::enums::AcadVersion; use crate::helper_functions::*; pub(crate) const XDA...
Rust
0
(uint32_t x)// 0 - channel { int index = x / channel; float expx = rsGetElementAt_float(inBlob, x); float sum = rsGetElementAt_float(expSum, index); if(channelAligned!=channel){ int channel_offset = x % channel; int channel_index = (x - (x % channel))/channel; int index = channel...
Rust
0
x04\x9a"[..]), Done(&b""[..], (255, 2, vec!(0x24, 0x9a))) ); assert_eq!( write_memory_binary(&b"Xff,2:\xce}\x0a\x9a"[..]), Done(&b""[..], (255, 2, vec!(0xce, 0x2a, 0x9a))) ); } #[test] fn test_parse_qrcmd() { assert_eq!( query(&b"qRcmd,736f6d657468696e67"[..]), Done(&b""[..], Query::Invoke(b"something".t...
Rust
0
"""Progress Bar Simulation, by Al Sweigart al@inventwithpython.com A sample progress bar animation that can be used in other programs. This code is available at https://nostarch.com/big-book-small-python-programming Tags: tiny, module""" import random, time BAR = chr(9608) # Character 9608 is '█' def main(): # S...
Python
1
eTextResponse decoding failure due // to invalid `num_attributes`. fn test_get_player_application_setting_value_text_response_decode_attrs_error() { let command = [0x02, 0x02, 0x00, 0x04, 0x02, 0x62, 0x78]; let result = GetPlayerApplicationSettingValueTextResponse::decode(&command); asse...
Rust
0
hed container"), ) .arg( Arg::new("namespace") .short('n') .long("namespace") .required(false) .takes_value(true) .about("The namespace containing the core-dump-handler. Defaults to observe if not supplied"), ) .try_get_matches() { ...
Rust
0
="创建时间") @classmethod def find_target(cls, source): url_map = cls.find_all_target([source]) return url_map.get(source) @classmethod def find_all_target(cls, source_list): sql = """ SELECT DISTINCT ON (source) id, source, target FROM rssant_api_feedur...
Python
1
, [2, 2, 2, 2], num_classes=num_classes) elif name == 'preact-resnet34': return PreActResNet(PreActBlock, [3, 4, 6, 3], num_classes=num_classes) elif name == 'preact-resnet50': return PreActResNet(PreActBottleneck, [3, 4, 6, 3], num_classes=num_classes) elif name == 'preact-resnet101': ...
Python
1
K4ABT_VERSION_MAJOR: u32 = 1; pub const K4ABT_VERSION_MINOR: u32 = 1; pub const K4ABT_VERSION_PATCH: u32 = 0; pub const K4ABT_VERSION_PRERELEASE: &'static [u8; 1usize] = b"\0"; pub const K4ABT_VERSION_BUILD_METADATA: &'static [u8; 1usize] = b"\0"; pub const K4ABT_VERSION_STR: &'static [u8; 6usize] = b"1.1.0\0"; pub con...
Rust
0
} else { (0xe0, timestamp) } } &EventTimingCode::AudioEnd(timestamp) => (0xfd, timestamp), &EventTimingCode::AudioFileEnds(timestamp) => (0xfe, timestamp), &EventTimingCode::OneMoreByteOfEventsFollows(timestamp) => (0xff, tim...
Rust
0
# -*- coding: utf-8 -*- from easy_getscreen import get_window_abs_by_name import cv2 import numpy as np import win32api,win32con import time, math # 用的是蓝叠模拟器 # 这些数值是根据当前模拟器窗口为 432x768 运算所得 # 而因为是通过截屏取窗口,所以运算时使用的长宽会稍微大一些 #h = 573 #w = 444 key = 281.85 # 鼠标按压时间 def pushtime(t): win32api.mouse_event(win32con.MOUS...
Python
1
\biGamma" : "𝜞", "\\biDelta" : "𝜟", "\\biEpsilon" : "𝜠", "\\biZeta" : "𝜡", "\\biEta" : "𝜢", "\\biTheta" : "𝜣", "\\biIota" : "𝜤", "\\biKappa" : "𝜥", "\\biLambda" : "𝜦", "\\biMu" : "𝜧", "\\biNu" : "𝜨", "\\biXi" : "𝜩", "\\biOmicron" : "𝜪", "\\biPi" : "𝜫", ...
Python
1
_GRACE_SLOTS, ticks_per_slot * NUM_CONSECUTIVE_LEADER_SLOTS / GRACE_TICKS_FACTOR, ), )) } // synchronize PoH with a bank pub fn reset( &mut self, blockhash: Hash, start_slot: Slot, next_leader_slot: Option<(Slot, Slot)>, ) ...
Rust
0
from prowler.lib.check.models import Check, Check_Report_AWS from prowler.providers.aws.services.ecr.ecr_client import ecr_client class ecr_repositories_scan_images_on_push_enabled(Check): def execute(self): findings = [] for registry in ecr_client.registries.values(): for repository i...
Python
1
queue: &wgpu::Queue, buffer: &mut DynamicUniformBuffer<T>, blocks: &mut Vec<DynamicUniformBufferBlock<T>>, uniforms: &[T], ) where T: Pod, { blocks.clear(); buffer.clear().unwrap(); for (uni_id, uni) in uniforms.iter().enumerate() { if uni_id >= blocks.len() { let bloc...
Rust
0
# Copyright (c) Streamlit Inc. (2018-2022) Snowflake Inc. (2022-2025) # # 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...
Python
1
ame>[^,\]]+),?(?P<options>[^\]]*)\]\s*?(?P<caption>.*)$', # MOVIE:[filename, options] some caption text label{some:label} 'movie': r'^MOVIE:\s*\[(?P<filename>[^,\]]+),?(?P<options>[^\]]*)\]\s*?(?P<caption>.*)$', 'linebreak': '^(?P<text>.*)<linebreak> *$', #'footnote': # definition is in doconce.py...
Python
1
from abc import ABC, abstractmethod class LM(ABC): """Abstract class for language models.""" def __init__(self, model): self.kwargs = { "model": model, "temperature": 0.0, "max_tokens": 150, "top_p": 1, "frequency_penalty": 0, "p...
Python
1
from funcy import curry from cadCAD.configuration.utils import ep_time_step, time_step def increment(y, incr_by): return lambda _g, step, sL, s, _input, **kwargs: (y, s[y] + incr_by) def track(y): return lambda _g, step, sL, s, _input, **kwargs: (y, s[y].x) def simple_state_update(y, x): return lambda...
Python
1
ts in results.items(): if model_results: correct = sum(1 for r in model_results if r['correct']) total = len(model_results) accuracy = (correct / total) * 100 if total > 0 else 0 avg_confidence = sum(r['confidence'] for r in model_results) / total if total > 0 els...
Python
1
empty() { return Err(ParseError::EmptyProtocolString); } let mut protocols = Vec::new(); let mut parts_iter = s.split('/'); // the first character must be '/' if parts_iter.next() != Some("") { return Err(ParseError::InvalidProtocolString); } ...
Rust
0
.unwrap(); let mut center: P = midpoint(a, b); let mut radius = center.distance(b); loop { match points.iter().filter(|p| center.distance(p) > radius).next() { None => break Sphere { center, radius }, Some(p) => { let c_to_p = center.distance(&p); ...
Rust
0
RICS.clients_connected.guarded_inc(); if let Err(e) = serve_client(client_socket, &db__, consctrl, require_password, db_watcher) .await { log::error!("Error serving client: {}", e); } ...
Rust
0
( input: &crate::input::CreateCustomerGatewayInput, ) -> Result<aws_smithy_http::body::SdkBody, aws_smithy_http::operation::SerializationError> { let mut out = String::new(); #[allow(unused_mut)] let mut writer = aws_smithy_query::QueryWriter::new(&mut out, "CreateCustomerGateway", "2016-11-15")...
Rust
0
import pytest from atcoder._bit import _ceil_pow2, _bsf class TestInternalBit: @pytest.mark.parametrize(( 'n', 'expected' ), [ (0, 0), (1, 0), (2, 1), (3, 2), (4, 2), (5, 3), (6, 3), (7, 3), (8, 3), (9, 4), (...
Python
1
ense-Identifier: Apache-2.0 use crate::{ ed25519::{Ed25519PrivateKey, Ed25519PublicKey, ED25519_PUBLIC_KEY_LENGTH}, hash::HashValue, multi_ed25519::{MultiEd25519PrivateKey, MultiEd25519PublicKey}, test_utils::TEST_SEED, traits::*, CryptoMaterialError::{ValidationError, WrongLengthError}, }; us...
Rust
0
ore == dp_scores[2] { (Op::ZInsertion, (s - 1, t_d1 - 1, u_d1 - 1)) } else if score == dp_scores[3] { (Op::XDeletion, (s - 2, t_d2 - 2, u_d2 - 1)) } else if score == dp_scores[4] { (Op::YDeletion, (s - 2, t_d2 - 1, u_d2 - 1)) } else if score == dp_scores[5] { (Op::ZDeletion, ...
Rust
0
} else { 0 } } // TODO: give these different behaviors TCSETS | TCSETSW | TCSETSF => { let termios = &*(out as *const termios::termios); if e(dup_write(fd, "termios", termios)) == !0 { -1 } else { 0 ...
Rust
0
, Value::Int(j)) => Value::Float(i / j as f32), (Value::Float(i), Value::Float(j)) => Value::Float(i / j), (Value::Float(i), Value::Nil) => Value::Float(i), (Value::Int(i), Value::Nil) => Value::Int(i), (Value::Nil, Value::Float(_i)) => Value::Nil, (Value::Nil...
Rust
0
data_dir, 'file_name' : psfex_file, 'image_file_name' : wcs_file }, ] }, 'psf1' : { 'type' : 'DES_Shapelet' }, 'psf2' : { 'type' : 'DES_PSFEx', 'num' : 0 }, 'psf3' : { 'type' : 'DES_PSFEx', 'num' : 1 }, 'psf4' : { 'type' : 'DES_Shapelet', 'image_pos' : galsim.Positi...
Python
1
_wise_s_word(&self, bytes: u128, positions: u32) -> u128 { (0..positions).fold(0, |acc, position| { acc | ((self.s_word(Self::nth_byte(bytes, position)) as u128) << (position * 8)) }) } fn nth_byte(word: u128, position: u32) -> u8 { ((word >> (position * 8)) & 0xff) as u8 ...
Rust
0
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 applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS...
Rust
0
xtraction_phase() # Generate final CTF report report_file = self.generate_ctf_report(extraction_results) print(f"\n📊 CTF ANALYSIS COMPLETE!") print(f"📁 Report: {report_file}") if extraction_results: print("🎉 CTF EXPLOITATION SUCCESSFUL!")...
Python
1
s 2-3 r: rrtrrrrrr 3-8 j: nhjtkjhjwlf 5-17 b: vbtctpbhtjtkhtwcw 5-8 z: zsbkkcgqwqqvzr 4-8 c: cpccjpwccccnc 6-13 k: rhkghtnkkbqdz 8-11 p: pcppmwppnvp 12-17 k: jjbsfkkqbbqkkknkk 4-6 h: tddhcllhhhcbwq 3-4 q: sqqqqjqm 4-7 b: tbqwbbqcs 3-10 z: zjzzzzzzzhzz 4-5 m: mhxpzwrcxtgsjxfdq 17-18 q: sqqqqqpbqqqqwqhvsp 3-4 n: njnww 9-...
Rust
0
import random import numpy as np import matplotlib.pyplot as plt population = 500 mutations = 0.005 np.random.seed(42) img = np.random.randint(2, size=(15,15)) plt.imshow(img, cmap=plt.cm.gray) plt.show() def ga(array, population, mutations): def score(matrix1, matrix2): return (matrix1 == matrix2).sum(...
Python
1
import torch from transformers import GPT2Tokenizer from types import SimpleNamespace class GPT2Inference: def __init__(self, model, tokenizer, device): self.device = device self.model = model.to(device) self.tokenizer = tokenizer @torch.no_grad() def generate_sequence(self, promp...
Python
1
# -*- coding: UTF-8 -*- # Copyright © 2012-2013, 2016 marmuta <marmvta@gmail.com> # # This file is part of Onboard. # # Onboard 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,...
Python
1
0111u64); assert_eq!(_tzmsk_u64(0b0101_1001u64), 0b0000_0000u64); } } <reponame>zand/nx use crate::result::*; use crate::ipc::cmif::sf; use crate::service; use crate::mem; pub use crate::ipc::cmif::sf::hid::*; pub struct AppletResource { session: sf::Session } impl sf::IObject for AppletResource { ...
Rust
0
Some(arc) = self.elm.upgrade() { Some(HConsed { elm: arc, uid: self.uid, }) } else { None } } } impl<T: fmt::Display> fmt::Display for WHConsed<T> { #[inline] fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { ...
Rust
0
riction: None, status: None, theme_id: None, tier_configs: None, voice_enabled: None, } } } // Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 //! A library supplying various cryptographic primitives used in Libra. #![deny(...
Rust
0
o()': {unknown} [201; 202) 'y': &dyn Trait<u64> [201; 208) 'y.foo()': {unknown} [214; 215) 'z': dyn Trait<u64> [214; 221) 'z.foo()': {unknown} [227; 228) 'x': dyn Trait<u64> [227; 235) 'x.foo2()': i64 [241; 242) 'y': &dyn Trait<u64> [241; 249) 'y.foo2()': i64 [255; 256) 'z': dyn Trai...
Rust
0
er.transformer import Transformer >>> length = 5 >>> d_model, n_head, dim_feedforward = 8, 4, 64 >>> transformer_paddle = Transformer( ... d_model, n_head, dim_feedforward=dim_feedforward) >>> mask = transformer_paddle.generate_square_s...
Python
1
!("en-US"); negotiate_langs_res(lang, &Self::available_langs(), Some(&default)).map(|_|()) } } <filename>src/bin/day2/main.rs<gh_stars>0 enum Direction { Forward(u32), Up(u32), Down(u32), } impl std::str::FromStr for Direction { type Err = std::io::Error; fn from_str(s: &str) -> Result...
Rust
0