text
string
label_name
string
labels
int64
event that a ferox-config.toml is found but one or more of the values below // aren't listed in the config. This way, we get the correct defaults upon Deserialization /// default Configuration type for use in json output fn serialized_type() -> String { String::from("configuration") } /// default timeout value ...
Rust
0
from spm._runtime import Runtime def ft_struct2single(*args, **kwargs): """ FT_STRUCT2SINGLE converts all double precision numeric data in a structure into single precision, which takes up half the amount of memory compared to double precision. It will also convert plain matrices and cel...
Python
1
me.time() num_bins, desperdicio, sequencia_camisas = brgka_simples( n_geracoes, POP_SIZE, ELITE_FRAC, MUTANT_FRAC, INHERIT_PROB ) duracao = time.time() - inicio resultados_individuais.append((n_geracoes, duracao, desperdicio, rep + 1)) tempos.append(duracao) d...
Python
1
doc = "`reset()` method sets TX_MULTICAST_FRAMES_GOOD_BAD to value 0"] impl crate::Resettable for TX_MULTICAST_FRAMES_GOOD_BAD_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } } <filename>src/persist/src/file.rs // Copyright Materialize, Inc. and contributors. All rights reserved. // // U...
Rust
0
ROR_CODE: 0x{:016x}\n\n{:#?}", error_code, stack_frame ); } pub extern "x86-interrupt" fn machine_check_handler(stack_frame: InterruptStackFrame) -> ! { panic!("EXCEPTION: MACHINE CHECK\n\n{:#?}", stack_frame); } pub extern "x86-interrupt" fn simd_floating_point_handler(stack_frame: InterruptStackFram...
Rust
0
idation purposes. Uses safe string handling and validation. Args: module_name (str): Name of the module Returns: list: List of sanitized NPC name strings """ try: codex = get_or_create_npc_codex(module_name) npc_names = [] for npc i...
Python
1
for x in min_x..=max_x { if self.0.get(&Point { x, y }).is_some() { f.write_char('#')?; } else { f.write_char('.')?; } } writeln!(f, "")?; } Ok(()) } } impl Image { pub f...
Rust
0
// Many different sized lines. assert_cut_fields_with_regex( "a b c\nd e f g\nh\ti\nj \tk\t l m n o p\nq\tr\ts t\nu v\nw\tx y\tz", "1-", b'\n', r"\s+", "\t", false, "a\tb\tc\nd\te\tf\tg\nh\ti\nj\tk\tl\tm\tn\to\tp\nq\t...
Rust
0
from web3 import Web3 ZGS_CONFIG = { "log_config_file": "log_config", "confirmation_block_count": 1, "router": { "private_ip_enabled": True, } } BSC_CONFIG = dict( NetworkId=1000, HTTPPort=8545, HTTPHost="127.0.0.1", Etherbase="0x7df9a875a174b3bc565e6424a0050ebc1b2d1d82", D...
Python
1
er1 = start_bar(points[3]); let corner2 = end_bar(points[1]); let upper_left = (corner1.0.min(corner2.0), corner1.1.min(corner2.1)); let bottom_right = (corner1.0.max(corner2.0), corner1.1.max(corner2.1)); backend.draw_rect(upper_left, bottom_right, &self.style, false)?; ...
Rust
0
contains("abcd"); stdout_spy.assert_contains_not("efgh"); Ok(()) } #[test] fn returns_true_except_for_esc_and_enter() { let (mut view, _) = view(); let mut model = model(vec!["abcd", "efgh"]); let mut controller = controller(&mut view, &mut model); let cha...
Rust
0
::MAX as *mut c_void, b"__libc_start_main\0".as_ptr() as *const c_char) }; if real_libc_start_main as usize == 0 { println!("could not find real __libc_start_main???"); std::process::exit(1); } unsafe { core::intrinsics::transmute::<*mut c_void, extern fn(main: *const c_void, argc: c_int, argv...
Rust
0
bug_print(f"Music key not found: {key}") def stop_music(self): """ Stops the currently playing music. """ if not self.sound_enabled: return pygame.mixer.music.stop() debug.debug_print("Music stopped.") def play_sound(self, key): """ P...
Python
1
import Database _valid_constraints = ('=', '<', '<=', '>', '>=', '!=', 'contains') # TODO: should probably throw errors for the various incorrect statement # building, but for now assume we are perfect and just silently ignore invalid # queries def build_constraints(db, query, valid_columns): if 'constraints' not...
Python
1
't terminate on time, going to kill horust..."); kill(self.pid, Signal::SIGKILL).expect("horust kill"); panic!("Test didn't terminate on time: Horust killed, test failed."); } } } } fn pid_from_id(id: u32) -> Pid { let id: pid_t = id as i32; Pid::from_raw...
Rust
0
channel dimension '''plt.imshow(rgb) plt.title("Processed Image") plt.show()''' # Get the class with the highest probability predictions = model.predict(sample_list) print(predictions) emotion = np.argmax(predictions) print(emotion) return i...
Python
1
messagebox.showinfo("Task Completed", "Task is already marked as completed.") except IndexError: messagebox.showwarning("Selection Error", "Please select a task to mark as completed") def save_tasks(self): with open("todo_list_gui.txt", "w") as file: for task in s...
Python
1
import os import openai import pandas as pd import time from dotenv import load_dotenv load_dotenv() OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") MODEL = "gpt-4o" client = openai.OpenAI(api_key=OPENAI_API_KEY) CSV_PATH = "pjfire_topix_company_patterns.csv" OUT_PATH = "pjfire_topix_company_patterns_expanded.csv" DELAY...
Python
1
in conjunction with the sortOrder parameter. #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] pub enum SortBy { #[serde(rename = "instanceId")] InstanceId, #[serde(rename = "caseInstanceId")] CaseInstanceId, #[serde(rename = "dueDate")] DueDate, #[s...
Rust
0
Win32_System_Diagnostics_Debug\"`*"] pub const WVR_LIVEDUMP_RECOVERY_IOCONTEXT_TIMEOUT: BUGCHECK_ERROR = 386u32; #[doc = "*Required features: `\"Win32_System_Diagnostics_Debug\"`*"] pub const WVR_LIVEDUMP_APP_IO_TIMEOUT: BUGCHECK_ERROR = 387u32; #[doc = "*Required features: `\"Win32_System_Diagnostics_Debug\"`*"] pub c...
Rust
0
""" Home Controller """ from functools import partial from japper import PageController from japper.debug import debug from japper.utils import show_page, popup_confirm from ..views import HomeView from ..models import HomeModel from ..commons.utils import get_japper_config class HomeController(PageController): ...
Python
1
, "Description"]; pub static ref HELP_KEYBINDS: Vec<Vec<&'static str>> = vec![ vec!["c", "Chat window"], vec!["i", "Insert mode"], vec!["s", "Swap channels"], vec!["Ctrl + f", "Search messages"], vec!["?", "Bring up this window"], vec!["q", "Quit this application"], ...
Rust
0
pub(crate) use convert::Into; pub(crate) use default::Default; pub(crate) use ffi::CStr; pub(crate) use ffi::CString; pub(crate) use ffi::OsStr; pub(crate) use ffi::OsString; pub(crate) use iter::IntoIterator; pub(crate) use iter::Iterator; pub(crate) use marker::Send; pub(crate) use marker::Sized; pub(crate) use mark...
Rust
0
{Cmd, ReplControl}, anyhow::{format_err, Context as _, Error}, fidl::endpoints, fidl_fuchsia_net::{IpAddress, Ipv4Address, Subnet}, fidl_fuchsia_net_stack::{ ForwardingDestination, ForwardingEntry, InterfaceAddress, StackMarker, }, fidl_fuchsia_net_stack_ext::FidlReturn, fidl_fuchsia...
Rust
0
""" Machine Learning Model for the Hot Durham Project. This module is responsible for all machine learning-related logic, such as air quality forecasting, anomaly detection, and seasonal trend analysis. By centralizing the ML models, it becomes easier to manage, extend, and integrate with other components of the appli...
Python
1
_base_ = '../rotated_retinanet/rotated-retinanet-rbox-le135_r50_fpn_1x_dota.py' model = dict( bbox_head=dict( type='RotatedRetinaHead', loss_bbox_type='kfiou', loss_bbox=dict(type='KFLoss', loss_weight=5.0)), train_cfg=dict( assigner=dict(iou_calculator=dict(type='FakeRBboxOverl...
Python
1
from typing import List class Solution: def exist(self, board: List[List[str]], word: str) -> bool: m, n = len(board), len(board[0]) def dfs(i, j, k): if k == len(word): return True if i < 0 or i >= m or j < 0 or j >= n or board[i][j] != word[k]: ...
Python
1
s_with_obstacles(obstacle_grid: Vec<Vec<i32>>) -> i32 { unique_paths_with_obstacles(&obstacle_grid) } } pub struct Solution; #[cfg(test)] mod tests { use crate::problem_0063::unique_paths_with_obstacles; #[test] fn test_1() { assert_eq!( unique_paths_with_obstacles(&[vec![...
Rust
0
4), 2); assert_eq!(int_log(7), 3); assert_eq!(int_log(8), 3); assert_eq!(int_log(31), 5); assert_eq!(int_log(32), 5); } #[test] fn test_bit_reverse() { assert_eq!(bit_reverse(0x00000000, 32), 0x00000000); assert_eq!(bit_reverse(0xFFFFFFFF, 32), 0xFFFFFFFF); ...
Rust
0
is_err()); assert!(Arguments::new(vec![dummy_url(), unknown_flag()]).is_err()); // Single positional argument with no options is parsed correctly assert_eq!( Arguments::new(vec![dummy_url()]).expect("Unexpected error with just URL"), Arguments { root_component_url: dummy...
Rust
0
) let root_handle = self .current_root_handle() .expect("Must have a root node to seek through."); let cur_state_node = root_handle.borrow(); let children = cur_state_node.children_read(); let resulting_child = children .iter() .find(|&c| ...
Rust
0
#! /usr/bin/env python # -*- coding: utf-8 -*- ############################################################################## ## DendroPy Phylogenetic Computing Library. ## ## Copyright 2010-2015 Jeet Sukumaran and Mark T. Holder. ## All rights reserved. ## ## See "LICENSE.rst" for terms and conditions of usage. #...
Python
1
=> { map.insert("message", "Are you a human?"); } } } None => { map.insert("message", "The format of your password is incorrect."); } } } None => { ...
Rust
0
} fn set_jmp_target(&mut self, jmp_pc: usize, target: usize) { match self.prog[jmp_pc] { Insn::Jmp(ref mut next) => *next = target, _ => panic!("mutating instruction other than Jmp"), } } fn set_split_target(&mut self, split_pc: usize, target: usize, second: bo...
Rust
0
::ErrorKind::InvalidData, ReadRecordError::MissingExternalBlock(*block_content_id), ) })?; let mut buf = Vec::new(); reader.read_until(*stop_byte, &mut buf).await?; // Remove stop byte. buf.pop(); ...
Rust
0
from GameStatus_5120 import GameStatus def minimax(game_state: GameStatus, depth: int, maximizingPlayer: bool, alpha=float('-inf'), beta=float('inf')): terminal = game_state.is_terminal() if (depth==0) or (terminal): newScores = game_state.get_scores(terminal) return newScores, None """ YOUR CODE HERE TO F...
Python
1
'default'].timestamp self.assertEqual(expected_model_storage.get_model_meta(), mir_annotations.prediction.model) mock_run.assert_called_once_with(work_dir=args.work_dir, label_storage_file=args.label_storage_file, m...
Python
1
Rng::from_seed([0, 1, 2, 3]); rng.gen_iter().map(|x| [x; 16]).take(len).collect() } macro_rules! sort { ($f:ident, $name:ident, $gen:expr, $len:expr) => { #[bench] fn $name(b: &mut Bencher) { let v = $gen($len); b.iter(|| v.clone().$f()); b.bytes = $len * mem...
Rust
0
from agent_executor import ( GenieAgentExecutor ) from a2a.server.apps import A2AStarletteApplication from starlette.applications import Starlette from a2a.server.request_handlers import DefaultRequestHandler from a2a.server.tasks import InMemoryTaskStore from a2a.types import ( AgentCapabilities, AgentCard...
Python
1
stopTime = time.time() timeTaken = stopTime - startTime result.printErrors() self.stream.writeln(result.separator2) run = result.testsRun if _unavail: #skipped: requested = _unavail.keys() requested.sort() self.stream.writeln("Ran %d tes...
Python
1
: X) {} //~ERROR variable `x` has dynamically sized type `X` fn g2<type X: T>(x: X) {} //~ERROR variable `x` has dynamically sized type `X` pub fn main() { } <filename>rust/metaplex/program/src/processor.rs use { crate::instruction::MetaplexInstruction, borsh::BorshDeserialize, claim_bid::process_claim_bid...
Rust
0
error"), )); } 401 => { return Err(MessageError::ProcessingError( job_result.with_status(JobStatus::Error).with_message( "Error on child process: Process has finished with an error on one of its children", ), )); } 408 => { return ...
Rust
0
# -*- coding:utf-8 -*- """ 分析fetch_collections.py的问题 """ import json def analyze_cookies(): """分析cookies情况""" print("=== 分析Cookies ===") try: with open('cookies.json', 'r', encoding='utf-8') as f: cookies_list = json.load(f) print(f"✓ cookies.json文件存在,包含{len(cookie...
Python
1
+ ReadVarint<T>, { assert_eq!(size, v.varint_size()); let mut cur = Cursor::new(Vec::new()); assert_eq!(size, cur.write_varint(v).unwrap()); assert_eq!(size, cur.position() as usize); cur.set_position(0); assert_eq!(v, cur.read_varint().unwrap()); } #[test] fn test_all() { test_varuint(0u8,...
Rust
0
import os import sys import uuid import streamlit as st from langchain_groq import ChatGroq from langchain.schema import HumanMessage, AIMessage from rag_utils import ( stream_llm_response, load_docs_to_db, load_url_to_db, stream_rag_llm_response, initialize_vector_db ) from dotenv import load_doten...
Python
1
ompare_exchange_weak(last_time, time_stamp, Ordering::SeqCst, Ordering::SeqCst) { Ok(_) => break, Err(last_time) if last_time < time_stamp => continue, // LAST_TIME has been updated, but it is still OK as long as time_stamp is still larger Err(_) => return ...
Rust
0
) .expect("Failed to convert RoomAliasId to JSON."), r##""#ruma:example.com""## ); } #[test] fn deserialize_valid_room_alias_id() { assert_eq!( from_str::<RoomAliasId>(r##""#ruma:example.com""##) .expect("Failed to convert JSO...
Rust
0
"goods_detail": { "merchant_goods_id": "1217752501201407033233368018", "wechatpay_goods_id": "1001", "goods_name": "iPhone6s 16G", "unit_price": 528800, "refund_amount": 528800, "refund_quantity": 1 ...
Python
1
ut text, which may contain <tool_assistant> tags Returns: The matching result, containing the matched servers and tools """ # Extract the server and tool descriptions from the input server_desc, tool_desc = self.extract_tool_assistant(input_text) if ...
Python
1
j: &T) { // TODO } #[cfg(not(target_arch = "wasm32"))] pub fn maybe_read_binary<T: DeserializeOwned>(path: String, timer: &mut Timer) -> Result<T, Error> { if !path.ends_with(".bin") { panic!("read_binary needs {} to end with .bin", path); } timer.read_file(&path)?; let obj: T = bi...
Rust
0
ize the plot //print!("{}", plot); } use std::ffi::OsString; use std::fs::OpenOptions; use std::io; use std::io::BufWriter; use std::io::Stderr; use std::io::Stdin; use std::io::Stdout; use std::io::Write; use std::path::PathBuf; use structopt::StructOpt; use super::Error; use super::Result; enum Context { ///...
Rust
0
machine.operate(&Item::Operator(Close)); assert_eq!(machine.stack_length(), 0); } #[test] fn test_devolution() { // Let's create a devolution machine let mut machine = Machine::new(&pokemon_op_sys); // This time you have a Blastoise let my_creature = Blastoise; ...
Rust
0
:autogen_protobuf::test; use protocols::{CommonModelFunctions, ModuleInfo, VecModuleInfo, Destination, VecRpcData, RpcData}; struct ClientRPCHandler; struct ServerRPCHandler; struct PublicRPCHandler; //impl test::ClientRPC for ClientRPCHandler {} impl test::ServerRPC for ServerRPCHandler {} impl test::PublicRPC for P...
Rust
0
use adr::schema::contactrecords; diesel::insert(fresh_contact_record).into(contactrecords::table) .get_result(conn) .expect("Error saving new event") } fn main() { let connection = establish_connection(); println!("What would you like your name to be?"); let mut name = String::ne...
Rust
0
TE_STR_ISO8601}</lastmod> </sitemap> </sitemapindex> """ ).strip(), ) # random_tag is to check assuming sitemap namespace doesn't cause issues requests_mock.get( self.TEST_BASE_URL + "/sitemap_pages....
Python
1
xy, tyz, txz)[0] ana = principal_stresses_cardano(sx, sy, sz, txy, tyz, txz)[0] err = np.abs(ref - ana).max() status = "OK" if err < tol else "FAIL ***" print(f"{tag:<14} Δ = {err: .2e} {status}") # ------------------------------------------------------------------ # # 4. speed benchm...
Python
1
pub struct UnusedNegativeMuProtect {} } fn change_mu_opacity(parts: crate::ast_walk::LazyWalkReses<MuProtect>) -> Result<Ast, ()> { let delta = parts.extra_info; let opacity = &parts .maybe_get_term(n("opacity_for_different_phase")) .map(|a| a.to_name().sp().parse::<i32>().unwrap()); if le...
Rust
0
[5] { (7, (ordinal - days[5]) as u8) } else if ordinal > days[4] { (6, (ordinal - days[4]) as u8) } else if ordinal > days[3] { (5, (ordinal - days[3]) as u8) } else if ordinal > days[2] { (4, (ordinal - days[2]) as u8) ...
Rust
0
n_included=min_included, max_included=max_included, name='poisson', null_default_value=null_default_value ) self.mu = mu def _pmf(self, x): return math.exp(-self.mu) * self.mu ** x / factorial(x) class Histogram(ScipyDiscreteDistributionWrapper): ""...
Python
1
#coding:utf-8 # -*- coding: utf-8 -*- # @Author : NaiChuan # @Time : 2024/8/28 13:45 # @File : train.py # @Software: PyCharm from ultralytics import YOLO if __name__ == '__main__': model = YOLO('ultralytics/cfg/models/v8/yolov8-mobilenetv4.yaml') # model.load('yolov8n.pt') # loading pretrain weights ...
Python
1
= 0, x is set to zero. x.iter_mut().for_each(|v| *v = T::zero()); return Ok((0, rhs_norm)); } let tol2 = tol * rhs_norm; // Here is the internal memeory layout let ptr = self.workspace.as_mut_ptr(); let r = unsafe { from_raw_parts_mut(ptr, n) }; // &mut ...
Rust
0
0, 99)); assert_eq!(aoc2a_run(vec!(2, 3, 0, 3, 99)), vec!(2, 3, 0, 6, 99)); assert_eq!( aoc2a_run(vec!(2, 4, 4, 5, 99, 00)), vec!(2, 4, 4, 5, 99, 9801) ); assert_eq!( aoc2a_run(vec!(1, 1, 1, 4, 99, 5, 6, 0, 99)), vec!(30, 1, 1, 4, 2, 5, 6,...
Rust
0
from __future__ import annotations import sys from typing import TYPE_CHECKING import pytest from .. import _core from ..testing import check_one_way_stream, wait_all_tasks_blocked # Mark all the tests in this file as being windows-only pytestmark = pytest.mark.skipif(sys.platform != "win32", reason="windows only")...
Python
1
ncols(&self) -> usize { self.len_of(Axis(1)) } /// Return the number of columns (length of `Axis(1)`) in the two-dimensional array. #[deprecated(note = "Renamed to .ncols(), please use the new name")] pub fn cols(&self) -> usize { self.ncols() } /// Return true if the array is...
Rust
0
feed_dict = {} for name, vec in zip(names, vecs): p_embeddings = tf.placeholder(tf.float32) load_embeddings.append(tf.assign(m.variable_map['embeddings_{}'.format(name)], p_embeddings)) feed_dict[p_embeddings] = vec with tf.Session() as...
Python
1
# This file is part of rinohtype, the Python document preparation system. # # Copyright (c) Brecht Machiels. # # Use of this source code is subject to the terms of the GNU Affero General # Public License v3. See the LICENSE file or http://www.gnu.org/licenses/. from ..xml.elementtree import Parser from ..xml import (...
Python
1
# SPDX-FileCopyrightText: The Ferrocene Developers # SPDX-License-Identifier: MIT OR Apache-2.0 # -- Project information ----------------------------------------------------- project = "CriticalUp Documentation" copyright = "The Ferrocene Developers" author = "The Ferrocene Developers" # -- General configuration -...
Python
1
// Compile and link the library cc::Build::new() .file("helpers/helpers.c") .define(secure_random, None) .warnings_into_errors(true) .compile("helpers"); println!("cargo:rustc-link-lib=static=helpers"); }use rand::distributions::{Alphanumeric, Distribution}; use window_clipboard::Clipboard; use winit::{ e...
Rust
0
pub core_temp: f32, pub stability: i32, pub prevalence: i32, pub constancy: i32, pub longevity: f32, pub no_appearing: i32, vision: String, language_family: String } const LAYER_OVER: &DrawMode = &(|_x, _y, _c| true); const LAYER_UNDER: &DrawMode = &(|_x, _y, c| c == BG_COLOR); #...
Rust
0
#creating a dictionary dictionary = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(dictionary) #output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964} #accessing items in a dictionary print(dictionary["brand"]) #output: Ford print(dictionary["model"]) #output: Mustang print(dictionary...
Python
1
::All => "other", }; write!(f, "{}", repr) } } #[derive(Deserialize, Debug, PartialEq)] pub struct Friend { #[serde(rename = "steamid")] pub id: SteamID, pub relationship: Relation, pub friend_since: u32, } #[derive(Deserialize)] struct FriendsWrapper { friends: Vec<Friend>, } ...
Rust
0
import os glade_files = [] for x in os.walk("../gtk"): for y in x[2]: if y.find(".glade") == -1 or y.find("glade~") != -1: continue glade_files += [os.path.join(x[0], y)] icons = [] for g_file in glade_files: f = open(g_file, "r") data = f.read() f.close() # Get al...
Python
1
ingKind, pub(crate) raw: &'src str, pub(crate) cooked: String, } impl Display for StringLiteral<'_> { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!( f, "{}{}{}", self.kind.delimiter(), self.raw, self.kind.delimiter() ) } } //! External handlers. pub mod status;...
Rust
0
_fence_fd #[cfg(feature = "VK_KHR_external_fence_fd")] IMPORT_FENCE_FD_INFO_KHR = 1000115000, #[cfg(feature = "VK_KHR_external_fence_fd")] FENCE_GET_FD_INFO_KHR = 1000115001, // feature: VK_KHR_maintenance2 #[cfg(feature = "VK_KHR_maintenance2")] PHYSICAL_DEVICE_POINT_CLIPPING_PROPERTIES_KH...
Rust
0
te: true, run: true, }, guest: data::UserPermissions { read: false, write: false, run: false, }, }, properties: data::FileProperties...
Rust
0
} impl<'a> Game<'a> { /// Creates a new game, with all the pieces in the correct starting position. /// /// # Eksamples /// /// ``` /// # use chess::*; /// let mut game = Game::new(); /// ``` pub fn new() -> Game<'a> { let mut board: [[Option<&'a Piece>; 8]; 8] = [[None; 8]...
Rust
0
new_test_ext().execute_with(|| { assert_ok!(Pallet::<Test>::test_benchmark_upload()); assert_ok!(Pallet::<Test>::test_benchmark_update()); }); } }<reponame>media-io/rs_amqp_worker mod bind_description; mod exchange_description; mod queue_description; use crate::worker::WorkerConfiguration; use bind_descr...
Rust
0
""" MIT License Copyright (c) 2024 TheHamkerCat Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, ...
Python
1
FileDescriptorProto, }; fn parse_descriptor_proto() -> ::protobuf::descriptor::FileDescriptorProto { ::protobuf::parse_from_bytes(file_descriptor_proto_data).unwrap() } pub fn file_descriptor_proto() -> &'static ::protobuf::descriptor::FileDescriptorProto { unsafe { file_descriptor_proto_lazy.get(|| {...
Rust
0
page_id, opens_at, chapter_image_path, id FROM chapters WHERE (course_id = $2); ", copied_course.id, parent_course.id ) .execute(&mut tx) .await?; // Copy course pages. At this point, exercise ids in content will point to old course's exercises. let contents_iter = sqlx::q...
Rust
0
a job to execute. pub struct SharedQueueThreadPool { threads: Vec<Worker>, sender: mpsc::Sender<Message>, } struct Worker { id: u32, handle: Option<thread::JoinHandle<()>>, } enum Message { Job(Box<dyn FnOnce() + Send + 'static>), Shutdown, } impl ThreadPool for SharedQueueThreadPool { f...
Rust
0
) · Structure"] #[doc(alias = "VkMultiviewPerViewAttributesInfoNVX")] #[derive(Copy, Clone)] #[repr(C)] pub struct MultiviewPerViewAttributesInfoNVX { pub s_type: crate::vk1_0::StructureType, pub p_next: *const std::ffi::c_void, pub per_view_attributes: crate::vk1_0::Bool32, pub per_view_attributes_posi...
Rust
0
from typing import List, Dict import asyncio from .config import Config from .grouper import Grouper from .vector_store import vector_store from .merger import Merger from .logger import logger from .models import Record from pydantic import BaseModel import polars as pl class GroupResult(BaseModel): group_id: st...
Python
1
(args.outdir, fn)) fn = '%s/disp0cf' % (fn) # fn = os.path.join("/home2/daiyuchao_UG/shenzhelun/unet_confidence/pre_picture/", fn.split('/')[-2]) print("saving to", fn, disp_est.shape) # invalid = np.logical_or(disp_est == np.inf, disp_est != disp_est) # dis...
Python
1
import ijson from tqdm import tqdm import json import os import os.path as osp if __name__ == '__main__': for dataset in ['Twibot-22', 'Twibot-20', 'midterm-2018', 'gilani-2017', 'cresci-stock-2018', 'cresci-rtbust-2019', 'cresci-2017', 'cresci-2015', 'botometer-feedback-20...
Python
1
e; use serde_repr::{Serialize_repr, Deserialize_repr}; use typenum; use crate::ip_types::*; use crate::fib_types::*; // Implementation for fib_source #[derive(Debug, Clone, Serialize, Deserialize, Default)] pub struct FibSource { pub priority : u8, pub id : u8, pub name : FixedSizeString<typenum::U64>, } #[...
Rust
0
um shape of the batch. so the batch consists of the same boundary... for efficient learning (?) sp_out_sh, _ = torch.max(out_sh, dim=0) # (3, ) sp_out_sh = sp_out_sh.tolist() return sp_coord, sp_out_sh def _xavier_init(linear) -> None: """ Performs the Xavier weight initialization of ...
Python
1
// # Example /// /// ``` /// use std::path::PathBuf; /// use dprint_plugin_typescript::*; /// use dprint_plugin_typescript::configuration::*; /// /// // build the configuration once /// let config = ConfigurationBuilder::new() /// .line_width(80) /// .prefer_hanging(true) /// .prefer_single_line(false) /// ...
Rust
0
tw.flush().unwrap(); let written = String::from_utf8(tw.into_inner().unwrap()).unwrap(); println!("\n{}", written); Ok(()) } Err(e) => Err(Error::ScheduleStatus(e)), } } // Copyright (c) The Libra Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate...
Rust
0
from odoo import api, fields, models, _ class PdfOrientation(models.TransientModel): _name = 'pdforientation' _description = "Select the orientation of the pdf" def orientation_choices(self): return [('landscape', _('Landscape')), ('portrait', _('Portrait'))] def get_default_caution_html(sel...
Python
1
} } /// Preprocess some photons (only applicable for PNEE) fn preprocess_photons( &mut self, num_ticks : usize ) { let mut rng = self.rng.borrow_mut( ); let scene = &self.scene; for _i in 0..num_ticks { let light_id = rng.next_in_range( 0, scene.lights.len( ) ); match &scene....
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2021 Intel Corporation # # 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 # # Unl...
Python
1
ase install it with `pip install " "amd-quark`.") from err return mx.qdq_mxfp4(x, scale_calculation_mode) def _quant_dequant_mxfp4_fake(x: torch.Tensor, scale_calculation_mode: str = "even" ) -> torch.Tensor: return torch.e...
Python
1
Int let f x : Test a -> Int = match x with | Int x -> x () "#, "()" } test_check! { basic3, r#" type Test a = | Int : Int -> Test Int let f x : Test a -> a = match x with | Int x -> x () "#, "()" } test_check! { different_type...
Rust
0
# -*- coding: utf-8 -*- # Copyright (c) 2014 - 2016 Detlev Offenbach <detlev@die-offenbachs.de> # """ Module implementing a dialog to select multiple shelve names. """ from __future__ import unicode_literals from PyQt5.QtCore import pyqtSlot from PyQt5.QtWidgets import QDialog, QDialogButtonBox from .Ui_HgShelvesS...
Python
1
from random import randint,uniform from math import ceil def gen_data(n): R,T=[],0 for i in range(n): RR=[randint(6,10),randint(200,500)] T+=RR[0]*RR[1] R.append(RR) return R,randint(1200, 1500) from my_or_tools import newSolver, ObjVal, SolVal def solve_model(D,W,symmetry_break=False,knapsack=True...
Python
1
andle() .spawn_blocking("babe-proposer", babe); } // if the node isn't actively participating in consensus then it doesn't // need a keystore, regardless of which protocol we use below. let keystore = if role.is_authority() { Some(keystore as BareCryptoStorePtr) } else { None }; let config = sc_finality...
Rust
0
been modified as follows: // - improve legibility // - remove eth2-specific features. // - use keccak256 // - remove ring dependency // In accordance with its license terms, the apache2 license is reproduced below lazy_static! { /// Zero nodes to act as "synthetic" left and right subtrees of other zer...
Rust
0
} } } async fn process_past_blocks<F, T>( rpc: &Arc<Client>, mut starting_height: u64, cb: F, responder: &mut Sender<T>, ) -> u64 where F: Fn(BlockHash, u64, bool, Arc<Client>) -> T + Send + Sync + 'static + Copy, T: Debug, { let mut chain_height = 0; while chain_height !=...
Rust
0
remove_queue.sort(); for &i in remove_queue.iter().rev() { if i < scanners.len() { scanners.remove(i); } } } let beacons_vec = scanners_abs.iter().map(|((ax,ay,az),vec)|{ vec.iter().map(|&(x,y,z)|{ (x+*ax,y+*ay,z+*az) }).colle...
Rust
0