text
string
label_name
string
labels
int64
ence_request_t` object. #[inline] pub unsafe fn xcb_sync_await_fence_sizeof( &self, _buffer: *const c_void, fence_list_len: u32, ) -> c_int { sym!(self, xcb_sync_await_fence_sizeof)(_buffer, fence_list_len) } /// Returns `true` iff the symbol `xcb_sync_await_fence_si...
Rust
0
om) .collect(); Ok(Some(strings)) } else { Ok(None) } } } /// Get an array of `NvList`. /// /// ``` /// use libnv::libnv::{NvList, NvFlag}; /// /// let mut list = NvList::new(NvFlag::None).unwrap(); /// ...
Rust
0
void, memory_size: *mut usize, ) -> Status { // // Build capsule descriptors list // let (status, block_list) = build_capsule_descriptors (block_list_buffer, memory_resource); if status != Status::SUCCESS { return status; } // // Get the size of our descriptor...
Rust
0
canvas.to_frame(app, &frame).unwrap(); } struct Boundary { start: Point2, end: Point2, } impl Boundary { fn show(&self, canvas: &Draw) { canvas .line() .start(self.start) .end(self.end) .weight(1.) .color(rgba(1., 1., 1., 0.2)); } } ...
Rust
0
ssion_dir)}") print(f"Session B: {os.path.basename(other_session_dir)}") print() # Compare key metrics analysis1 = data1.get("turn_analysis", {}) analysis2 = data2.get("turn_analysis", {}) metrics_to_compare = [ ("total_turn_latency", "Total Turn Latency"), ...
Python
1
() => { "world" }; } #[derive(Template)] #[template(path = "rust-macros.html")] struct RustMacrosTemplate {} #[test] fn main() { let template = RustMacrosTemplate {}; assert_eq!("Hello, world!", template.render().unwrap()); } macro_rules! call_a_or_b_on_tail { ((a: $a:expr, b: $b:expr), c...
Rust
0
Ok(()) } fn get_last_modification(path: &Path) -> Result<String> { let mtime = cmd!("git --no-pager log -1 --pretty='format:%ci' {path}").read()?; match mtime.split_once(" ") { Some((date, _)) => Ok(date.to_string()), None => Err("no date found")?, } } fn get_title(path: &Path) -> R...
Rust
0
ata_iterator: loss = model(batch, mode="train") loss.backward() train_op() if step % config_data.display == 0: print("step={}, loss={:.4f}".format(step, loss)) step += 1 @torch.no_grad() def _eval_epoch(mode): if mode == 'val':...
Python
1
ey. pub fn new<R: Rng>(rng: &mut R) -> Result<Self, PrivateKeyError> { Ok(Self { secret_key: secp256k1::SecretKey::random(rng), compressed: true, _network: PhantomData, }) } /// Returns the public key of the corresponding Bitcoin private key. pub fn t...
Rust
0
def hopper_na2d_backward(*args, **kwargs): libnatten_import_error() def hopper_na3d_backward(*args, **kwargs): libnatten_import_error() ## SM100 - Blackwell FMHA def blackwell_fmha_forward(*args, **kwargs): libnatten_import_error() def blackwell_fmha_backward(*args, **kw...
Python
1
FcBool; pub fn FcStrSetEqual(sa: *FcStrSet, sb: *FcStrSet) -> FcBool; pub fn FcStrSetAdd(set: *FcStrSet, s: *FcChar8) -> FcBool; pub fn FcStrSetAddFilename(set: *FcStrSet, s: *FcChar8) -> FcBool; pub fn FcStrSetDel(set: *FcStrSet, s: *FcChar8) -> FcBool; pub fn FcStrSetDestroy(set: *FcStrSet); pub fn FcStrListCr...
Rust
0
map(|(x, y)| board.get(x, y)) .flatten() .map(|p| p != Piece::KingB) .unwrap() { last_state.2 = false; last_state.3 = false; } } ...
Rust
0
/// # use std::{task::{Context, Poll}, pin::Pin, future::Future}; /// # /// # use pyo3_asyncio::generic::{JoinError, Runtime}; /// # /// # struct MyCustomJoinError; /// # /// # impl JoinError for MyCustomJoinError { /// # fn is_panic(&self) -> bool { /// # unreachable!() /// # } /// # } /// # /// # stru...
Rust
0
pen('./xsum_prompt.txt','r',encoding='utf-8') as file: few_prompt = file.read() assert isinstance(few_prompt,str), "The document is not a string." evaluator_x_sum = Evaluator_x_sum(dataset_x_sum,tokenizer,'cuda', few_prompt) print('evaluating') x_sum = evaluator_x_sum.evalu...
Python
1
check_ne_abs(a, b, EPSILON); } } } } }; } impl_tests!(f32); impl_tests!(f64); <reponame>open-marketplace-applications/design-system<gh_stars>0 use css_in_rust::Style; use yew::prelude::*; use yew_styles::button::{Button as Btn, Props...
Rust
0
self.handle, *m, ptr::null()); } } destroyed_images.clear(); } fn find_memory_type(&self, requirements: &vk::MemoryRequirements, access: MemoryAccess) -> u32 { self.memory_types .iter() .enumerate() .find(|(i, mem_type)| { ...
Rust
0
"""Diagnostics support for EnergyZero.""" from __future__ import annotations from datetime import timedelta from typing import Any from homeassistant.core import HomeAssistant from .coordinator import EnergyZeroConfigEntry, EnergyZeroData def get_gas_price(data: EnergyZeroData, hours: int) -> float | None: ""...
Python
1
App) installation and uninstallation //! //! An App is a essentially a collection of Cells which are intended to be //! available for a particular Holochain use-case, such as a microservice used //! by some UI in a broader application. //! //! Each Cell maintains its own identity separate from any App. //! Access to Ce...
Rust
0
ize<T>(ptr: *const T) -> usize { union Pointer<T> { ptr: *const T, int: usize, } let ptr = Pointer { ptr }; unsafe { ptr.int } } #[test] #[allow(clippy::assertions_on_constants)] // This is the point of the test. fn sync_worker_id() { // Sync worker and worker thread ids may not ove...
Rust
0
#!/usr/bin/env python3 """ 测试脚本:验证修复后的发布器初始化 """ import sys import os sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from ros_comms import handler as ros_handler from loguru import logger def test_publisher_fix(): """测试发布器修复""" logger.info("=== 测试发布器修复 ===") # 检查初始状态 logger.info(...
Python
1
from filtering.anisotropic import * from rivuletpy.utils.io import * import matplotlib.pyplot as plt from scipy import io as sio try: from skimage import filters except ImportError: from skimage import filter as filters mat = sio.loadmat('tests/data/very-small-oof.mat', ) img = mat['img'] ostu_img = filters...
Python
1
asespace, debug, }; // init some useful objects let mut nb_reads : u64 = 0; // get file size for progress bar let metadata = fs::metadata(&filename).expect("Error opening input file."); let file_size = metadata.len(); let mut pb = ProgressBar::on(stderr(),file_size); let mut lmer...
Rust
0
C /* BTN_MODE */ => Event::Exit(pushed), 0x13D /* BTN_THUMBL */ => Event::Joy(pushed), 0x13E /* BTN_THUMBR */ => Event::Cam(pushed), 0x13F /* BTN_PINKYR */ => Event::PinkyRight(pushed), 0x140 /* BTN_PINKYL */ => Event::PinkyLeft(pushed), 0x220 /* BTN_DPAD_UP */ => Event::Up(push...
Rust
0
ity_filters)); } Filter::Or(filters) } _ => filter, } } fn coerce_empty( truthy: bool, operation: &str, filters: Vec<Filter>, invert: bool, invert_undefined_exclusion: bool, prefix: FilterPrefix, ) -> crate::Result<MongoFilter> { if filters.is_em...
Rust
0
# Copyright 2024-2025, Theodor Westny. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
Python
1
"""empty message Revision ID: c7feae971e82 Revises: 402dc7bf57dd Create Date: 2024-07-19 14:08:36.878349 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'c7feae971e82' down_revision = '402dc7bf57dd' branch_labels = None depends_on = None def upgrade(): # ...
Python
1
student_logits, student_features = student_model(sequences) print(f" Student outputs: logits {student_logits.shape}, features {student_features.shape}") # Teacher forward pass batch_size, seq_len = sequences.shape[:2] ...
Python
1
[`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about avaliable fields see [uartdr](uartdr) module"] pub type UARTDR = crate::Reg<u32, _UARTDR>; #[allow(missing_docs)] #[doc(hidden)] pub...
Rust
0
'description': f'日志安全测试异常: {str(e)}', 'severity': 'Low' }) return False def test_configuration_security(self): """测试配置安全""" try: from visionsub.ui.enhanced_main_window import EnhancedMainWindow class MockController: ...
Python
1
} } _ => default_err_msg?, } } } }; step_handler.result(StepResult::Success).await?; step_handler.output_step(StepType::RecordGenerated(final_path.canonicalize()?)).await?; } Ok(()) } async ...
Rust
0
e user edits full_html_path = os.path.join(OUTPUT_FOLDER, DRAFT_HTML_FILE) with open(full_html_path, "w", encoding="utf-8") as file: file.write(full_html) # messagebox.showinfo(f"\n✅ Extraction Complete! Edit `{full_html_path}` before proceeding.") messagebox.showinfo("提示信息", f"\n提取完成。{image_co...
Python
1
s: gen_kwargs["temperature"] = 0 if "top_p" not in gen_kwargs: gen_kwargs["top_p"] = 1.0 if "num_beams" not in gen_kwargs: gen_kwargs["num_beams"] = 1 assert gen_kwargs["num_beams"] == 1 def save_image_to_temp_file(image): ...
Python
1
"""! @brief Mixture consistency according to the paper. Scott Wisdom, John R Hershey, Kevin Wilson, Jeremy Thorpe, Michael Chinen, Brian Patton, and Rif A Saurous. "Differentiable consistency constraints for improved deep speech enhancement", ICASSP 2019. @author Efthymios Tzinis {etzinis2@illinois.edu} @copyright Uni...
Python
1
sim = sim.flatten(-2).mean(-1) #B*T,L return sim # sp spim = feat.permute(0, 1, 4, 2, 3).flatten(0, 1) col = im2col(spim, (3, 3), s...
Python
1
#!/usr/bin/env python3 """ Working examples of UnMDX API after fixing basic test cases. Run this script to see the fixed MDX to DAX conversion in action. """ from unmdx.api import mdx_to_dax, parse_mdx, optimize_mdx, explain_mdx def example_1_simple_measure(): """Test Case 1: Simple measure query - WORKING! ✅""" ...
Python
1
} Or a mix of the two: some critical property classes (position...) and a facility to implement custom properties via scripts. *//* */ use core::cell::UnsafeCell; use core::sync::atomic::{AtomicBool,Ordering}; pub struct Spinlock<T> { flag: AtomicBool, value: UnsafeCell<T>, } unsafe impl<T: Send> Sync for ...
Rust
0
directed::astar::astar_bag; #[test] fn multiple_sinks() { // 1 --> 2 --> 4 // --> 3 --> 4 // // 2 --> 5 --> 6 --> 7 // 3 --> 5 --> 6 --> 7 let (solutions, cost) = astar_bag( &1, |&n| match n { 1 => vec![(2, 1), (3, 1)], 2 | 3 => vec![(4, 3), (5, 1)], ...
Rust
0
::unix::net::UnixListener, prelude::FutureExt, stream::StreamExt, sync::Mutex, }; use kak::{ command::Client, range::{Pos, Range, Selection}, }; use std::{convert::TryFrom, env, path::Path, sync::Arc}; use yew_ansi::get_sgr_segments; use crate::{ args::{self, FifoArgs}, range_specs::SharedRanges, }; /// Serve ...
Rust
0
>, v2: &Option<i64>) -> Result<Option<i64>> { Ok(Some(v1.unwrap() + v2.unwrap() * 2)) } let mut columns = LazyBatchColumnVec::from(vec![ { let mut col = LazyBatchColumn::decoded_with_capacity_and_tp(3, EvalType::Real); col.mut_decoded().push_real(...
Rust
0
} #[logfn(DEBUG)] pub fn get_config() -> Result<PrincipalConfig, Error> { let config_path = "../app/tests/principal_node/config/principal_test_config.json"; let config = PrincipalConfig::load_config(config_path)?; Ok(config) } pub fn init_no_deploy(eid: u64) -> Result<Principal...
Rust
0
)) try: # Connect to Qdrant client = connect_to_qdrant() # Search for Morava K-theory content found, count = search_for_morava_content(client) if found: rprint("\n[bold green]✅ Morava K-theory content exists in the database![/bold green]")...
Python
1
# -*- coding: utf-8 -*- # License: MIT License """ MI offline analysis. """ from metabci.brainda.algorithms.decomposition.csp import FBCSP from scipy import signal import matplotlib.pyplot as plt from sklearn.svm import SVC from sklearn.pipeline import make_pipeline from sklearn.base import BaseEstimator, ClassifierMi...
Python
1
/// default: false pub premultiplied: bool, } impl std::default::Default for CompositeOptions { fn default() -> Self { CompositeOptions { x: Vec::new(), y: Vec::new(), compositing_space: Interpretation::Srgb, premultiplied: false, } } } ...
Rust
0
/// This function evaluates the tangent function of a value in ***a***. /// The error bound of the returned value is 1.0 ULP. pub fn tanf(d: f32) -> f32 { let q: i32; let mut s: Doubled<f32>; if fabsfk(d) < TRIGRANGEMAX2_F { let qf = rintfk(d * FRAC_2_PI); q = qf as i32; let u = qf.m...
Rust
0
import os import logging import traceback from lambda_base import LambdaBase from facebook_util import FacebookUtil from botocore.exceptions import ClientError from response_builder import ResponseBuilder class LoginFacebookAuthorizationUrl(LambdaBase): def get_schema(self): pass def validate_params(...
Python
1
Same as the other encode functions, but instead takes a file path as output. /// /// NOTE: This overwrites existing files without warning! pub(crate) fn encode_file<PixelType: Copy + Pixel, P: AsRef<Path>>( filepath: P, raster: &Raster<PixelType>, colortype: ColorType, bitdepth: u32, ) -> Result<(), Err...
Rust
0
jpeg_store_memory."] pub mod jpeg_store_memory; #[doc = "mjpeg_control_3 register accessor: an alias for `Reg<MJPEG_CONTROL_3_SPEC>`"] pub type MJPEG_CONTROL_3 = crate::Reg<mjpeg_control_3::MJPEG_CONTROL_3_SPEC>; #[doc = "mjpeg_control_3."] pub mod mjpeg_control_3; #[doc = "mjpeg_frame_fifo_pop register accessor: an al...
Rust
0
def row_gap_anim(obj, v): obj.set_style_pad_row(v, 0) def column_gap_anim(obj, v): obj.set_style_pad_column(v, 0) # # Demonstrate the effect of column and row gap style properties # cont = lv.obj(lv.scr_act()) cont.set_size(300, 220) cont.center() cont.set_flex_flow(lv.FLEX_FLOW.ROW_WRAP) for i in range(9)...
Python
1
" token=")?; for b in token { write!(f, "{:02x}", b)?; } } if let Some(ref versions) = self.versions { write!(f, " versions={:x?}", versions)?; } if self.ty == Type::Short { write!(f, " key_phase={}", self.key_phase)?; ...
Rust
0
fn test_send_local_to_local<I: Ip>() { test_send_local::<I>(AddressType::LocallyOwned, AddressType::LocallyOwned); } #[ip_test] fn test_send_unspecified_to_local<I: Ip>() { test_send_local::<I>( AddressType::Unspecified { can_select: true }, AddressType::LocallyOwne...
Rust
0
import heapq import math def a_star(): # Define the initial state of the city map as a 2d tuple initial_state = ( ('x', 10, 'x', 8, 13, 8, 4, 3, 15, 'x', 17), (9, 'x', 6, 4, 17, 'x', 16, 3, 19, 'x', 'x'), (8, 3, 18, 'x', 'x', 3, 'x', 7, 12, 16, 17), (8, 'x', 'x', 13, 'x', 7, 'x...
Python
1
import json import re import os from collections import defaultdict REASONING_CATEGORY_MAPPING = { # 保持原有映射关系不变 "Metaphor Understanding": "Implicit", "Theme Understanding": "Implicit", "Emotion Recognition": "Implicit", "Implicit Symbol": "Implicit", "Comment Matching": "Implicit", "Counter...
Python
1
d_data_jnp = jnp.nan_to_num(grid_data_jnp, nan=0.0) geo_trav_grid_jnp = jnp.nan_to_num(geo_trav_grid_jnp, nan=0.0) goal_marker = get_goal_marker(self.goal_state, self.get_clock().now().to_msg()) self.marker_pub.publish(goal_marker) ctrl_cmd, pred_states, t...
Python
1
Where to show the message on ui // `msg_target`: Actual PRIVMSG target to send to the server let (ui_target, msg_target): (MsgTarget, &str) = { match src { MsgSource::Serv { .. } => { // we don't split raw messages to 512-bytes long chunks client.raw_msg(&msg)...
Rust
0
import frappe from ..role import desk_properties def execute(): for role in frappe.get_all("Role", ["name", "desk_access"]): role_doc = frappe.get_doc("Role", role.name) for key in desk_properties: role_doc.set(key, role_doc.desk_access) role_doc.save()
Python
1
""" UI管理模块 - 处理游戏界面绘制和交互(添加图鉴功能) """ import pygame import math import random import sys import os from core.constants import * from animation.effects import AnimationEffects def draw_grid(surface, grid_bg_img=None): """绘制战场网格(使用背景图片或棕色边框)""" for row in range(GRID_HEIGHT): for col in range(GRID_WIDTH...
Python
1
import os import random from langchain_core.tools import StructuredTool from datetime import datetime, timedelta from typing import Annotated from jira.client import JIRA, Issue, ResultList JIRA_EMAIL = os.environ.get("JIRA_EMAIL", "") JIRA_TOKEN = os.environ.get("JIRA_TOKEN", "") JIRA_PROJECT_KEY = os.environ.get("JI...
Python
1
b5m\xe2\x99\xd6\x1a\ \xa6~x\x0f\x00N\x00Z%@\xaf\xf4m\xdc\xb7\xca\ \x88\x12Oi\xf2\xd4\x99Ji\xf5\xe6h\xfcj\xbcW\ :T\xe5{\xdc3FU\x14\xe9`9\x1d\xd2\xad)\ \xda\xdb\xac\x8asLD^\xe25x%x\x11$x\ \xe0\x16\xbf#\xfc\xd1\xc8\x02\xf4!\x12r\x0a\xa1\x01\x16\ \xf1\x0aB\x0b\xdd\xc83\x84\x1eA\x18\x0f\xd20\x22\x08\ \x0b\x07-\x0b\x10\x8a\x...
Python
1
import redis import json import traceback from .launchpad_singleton import get_launchpad # Connect to Redis cache = redis.Redis(host='localhost', port=6379, db=0) def fetch_matrix_accounts(profile_id): try: # Try to fetch from cache first cached_result = cache.get(f"matrix_{profile_id}") i...
Python
1
rror) if error.kind() == io::ErrorKind::TimedOut => { if !keepalive.swap(false, Ordering::AcqRel) { keepalive = match Arc::try_unwrap(keepalive) { Ok(_) => return Ok(()), Err(keepalive) => keepalive, ...
Rust
0
import pytest from hera.workflows import DAG, Artifact, Container, NoneArchiveStrategy, Workflow, WorkflowsService def get_workflow() -> Workflow: with Workflow( generate_name="dag-artifact-passing-", entrypoint="runner-dag", namespace="argo", workflows_service=WorkflowsService( ...
Python
1
_reserved12: [u8; 8usize], #[doc = "0x40 - PM Control Register"] pub leapmctl: LEAPMCTL, #[doc = "0x44 - PM Result Register"] pub leapmdst: LEAPMDST, #[doc = "0x48 - PM Source 1 Register"] pub leapms1: LEAPMS1, #[doc = "0x4c - PM Source 0 Register"] pub leapms0: LEAPMS0, ...
Rust
0
Iplus, Icross, hphccorr=hphc_corr, hpnorm=1.0, hcnorm=1.0, thresh=0.1, analyse_slice=slice(0, len(Iplus.data)), ) else: raise ValueError("Currently only HM and precessing is supported!") i = np.argmax(det_stat.data) ...
Python
1
/ for item in v.iter() { s += &format!("\n{}", item); } let s = json!({ "thread_id": &thread_id, "frames": &v }); println!("backtrace: {}", s); } <reponame>Wodann/io-bluetooth-rs use std::io; use std::os::raw::c_ulong; use std::time::Duration; pub mod bt; pub mod c; pub trait IsZero { fn is_zer...
Rust
0
""" Generates random IMEI numbers. The user specifies the 8-digit TAC and up to 4-digits of the serial number. The user also specifies the number of random IMEIs to generate. """ import sys import random # Src: https://github.com/arthurdejong/python-stdnum/blob/master/stdnum/luhn.py def checksum(number, alphabet='0...
Python
1
=> Some(Key::F24), RightControl => Some(Key::RightControl), Other(_code) => None, LeftAlt => Some(Key::LeftAlt), RightAlt => Some(Key::RightAlt), PageUp => Some(Key::PageUp), PageDown => Some(Key::PageDown), Print => None, PrintScreen => None, Lef...
Rust
0
, 28 LINECAPS, 30 POLYGONALCAPS, 32 TEXTCAPS, 34 CLIPCAPS, 36 RASTERCAPS, 38 ASPECTX, 40 ASPECTY, 42 ASPECTXY, 44 LOGPIXELSX, 88 LOGPIXELSY, 90 SIZEPALETTE, 104 NUMRESERVED, 106 COLORRES, 108 PHYSICALWIDTH, 110 PHYSICALHEIGHT, 111 PHYSICALOFFSETX, 112 PHYSICALOFFSETY, 113 SCALINGFACT...
Rust
0
self, _name: &str, _value: &str) -> Result<()> { Err(FileSystemErrorKind::NotImplemented.into()) } async fn remove_xattr(&mut self, _name: &str) -> Result<bool> { Ok(false) } async fn get_xattr(&self, _name: &str) -> Result<Option<String>> { Ok(None) } async fn list_x...
Rust
0
F: FnMut(Self::Item) -> U, { MatrixMN::<T, R, C>::map(&self, f) } } // TODO: Use a (more) generic implementation. impl<T> Matrix for Matrix2<T> where T: AbsDiffEq + AddAssign + MulAssign + NumCast + Real + Scalar, { type Row = RowVector2<T>; type Column = Vector2<T>; type Trans...
Rust
0
| mask as i32, ((*color).values[0] / 0.001f64 + 0.5f64).floor() * 0.001f64, 'S' as i32 | mask as i32, 'C' as i32 | mask as i32, ) } else { i = 0i32; while i < (*color).num_components { len += sprintf( buffer.offset(len as isize...
Rust
0
::{Candidate, PartyIndex, CandidateIndex, ElectionMetadata}; use std::collections::HashMap; use stv::ballot_paper::{BTL, RawBallotMarking, RawBallotMarkings}; use std::iter::FromIterator; use anyhow::anyhow; use std::fs::File; use std::io::{Read}; /// Read from a file "SenateGroupVotingTicketsDownload which defines ca...
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file contains unit tests for PyDAS. """ import unittest from pydas import DASSL import math import numpy ################################################################################ class SimpleModel(DASSL): """ A model of first-order irreversible...
Python
1
import google.generativeai as genai from flask import current_app class GeminiService: def __init__(self): try: genai.configure(api_key=current_app.config['GEMINI_API_KEY']) self.model = genai.GenerativeModel("gemini-pro") except Exception as e: print(f"Failed to...
Python
1
u32), /// A KDBX file has some invalid bits in it. BadFormat(&'static str), // @TODO maybe add the xml error text in here, but that might leak something. /// XML error. XmlError, } impl fmt::Debug for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { ...
Rust
0
# ci/collect_changed_files.py import json, os, subprocess, sys, pathlib APP_PREFIX = "app/" def sh(cmd): return subprocess.run(cmd, check=True, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) def safe_sh(cmd): return subprocess.run(cmd, check=False, text=True, stdout=subprocess.PIPE, stderr=subpro...
Python
1
text = StanModel.read_text() start = text.find("### Public methods") end = text.find("### Method `") text = text[:start] + text[end:] StanModel.write_text(text) except Exception as e: # fail loudly in Github Actions if RUNNING_IN_CI: raise e else: print("Failed to build...
Python
1
offset.y > camera_gridspace.y + CHUNK_VIEW_LIMIT || offset.y < camera_gridspace.y - CHUNK_VIEW_LIMIT || offset.z > camera_gridspace.z + CHUNK_VIEW_LIMIT || offset.z < camera_gridspace.z - CHUNK_VIEW_LIMIT } }<filename>src/files/write_output.rs use ::std::fs::File; use ::std::io::Writ...
Rust
0
!Sync` unique storage." )] #[cfg_attr( not(feature = "non_sync"), doc = "* NonSync: must activate the *non_sync* feature" )] #[cfg_attr( all(feature = "non_sync", docsrs), doc = "* <span style=\"display: table;color: #2f2f2f;background-color: #C4ECFF;border-width: 1px;bor...
Rust
0
"""Persistence of run artifacts (manifest, results JSONL, per-record) for new arch.""" from __future__ import annotations from collections.abc import Iterable from pathlib import Path import orjson from app.domain.models import PromptSnapshot, RecordResult, RunManifest, RunSummary def _public_record_view(r: Record...
Python
1
>, delete_user: &str) -> TardisResult<u64> where E: EntityTrait, { if let Some(tx) = &self.tx { TardisRelDBClient::soft_delete_inner(select, delete_user, tx).await } else { TardisRelDBClient::soft_delete_inner(select, delete_user, self.conn).await } } ...
Rust
0
comment_strip_pattern: String, pub file_extension: String, pub inclusion_pattern: String, pub game_id: i64, pub id: i64, } #[derive(Debug, Clone, PartialEq, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CategorySection { pub id: i64, pub game_id: i64, pub name: String, pu...
Rust
0
sources::Builder::default() } } /// <p>An Auto Scaling group that is associated with an Amazon EKS managed node group.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct AutoScalingGroup { /// <p>The name of the Auto Scaling group associated with an Amazon EKS managed node group...
Rust
0
from openid.extension import Extension as OpenIDExtension class MacaroonRequest(OpenIDExtension): ns_uri = "http://ns.login.ubuntu.com/2016/openid-macaroon" ns_alias = "macaroon" def __init__(self, caveat_id): self.caveat_id = caveat_id def getExtensionArgs(self): """ Return ...
Python
1
""" Random User-Agent Copyright: 2022 Ekin Karadeniz (github.com/iamdual) License: Apache License 2.0 """ import unittest import src.ua_generator as ua_generator class TestDevice(unittest.TestCase): def test_device(self): for i in range(0, 100): ua = ua_generator.generate(device=('desktop'))...
Python
1
onv2d. Default: 2 reduction_factor (int): Reduction factor of inter_channels in SplitAttentionConv2d. Default: 4. avg_down_stride (bool): Whether to use average pool for stride in Bottleneck. Default: True. kwargs (dict): Keyword arguments for ResNet. """ arch_se...
Python
1
= low + ((high - low) >> 1); if a[mid as usize] == v { if mid == 0 || a[mid as usize - 1] != v { return Some(mid as usize); } else { high = mid - 1; } } else if a[mid as usize] < v { low = mid + 1; } else { ...
Rust
0
"""Utilities for calculating project statistics. These stats are useful for estimating the size of a project, which helps us wtih cost estimation for our proofers. """ import re from collections.abc import Iterable from dataclasses import dataclass from indic_transliteration import detect, sanscript from ambuda.dat...
Python
1
annel /// was closed. pub fn close_session_channel(&mut self, dlci: &DLCI) -> bool { self.channels.remove(dlci).is_some() } /// Sends `user_data` received from the peer to the SessionChannel associated with the `dlci`. pub fn receive_user_data( &mut self, dlci: DLCI, ...
Rust
0
import discord from discord.ext import commands class HelpCmd(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command(name="aide") async def help_cmd(self, ctx: commands.Context): embed = discord.Embed( title="Aide du bot Quiz Cinéma", color=discord...
Python
1
in() predictions = context.sql(query).to_pandas() captured = capsys.readouterr() expanded = 'predict_xgb(Utf8("diamonds_model"), diamonds.carat, diamonds.depth, diamonds.x, diamonds.y, diamonds.z)' assert expanded in captured.out assert len(predictions) == sum(data.x < 4.5) assert is_float_dty...
Python
1
) if len(tax) == 0: tax = 0 while float(tax) < 0 or float(tax) > 100: print('Invalid Tax%. Enter again') tax = input('Enter tax %, if applicable. If not, press enter: ') tax = round(float(tax), 1)...
Python
1
import pandas as pd from scripts.config import BULLISH_SIGNAL, BEARISH_SIGNAL, BULLISH_TREND, BEARISH_TREND, NEUTRAL_TREND, OVERBOUGHT, OVERSOLD, NO_SIGNAL, HIGH_VOLUME, LOW_VOLUME, HIGH_VOLATILITY, LOW_VOLATILITY, INCREASING_VOLATILITY, DECREASING_VOLATILITY, STABLE_VOLATILITY, INCONCLUSIVE def signal_bams_bung_3(df:...
Python
1
"""Tests for the bob_emploi.importer.soc_job_suggest module.""" import logging import os from os import path import unittest from unittest import mock from algoliasearch import exceptions from bob_emploi.data_analysis.importer import soc_job_suggest @mock.patch(soc_job_suggest.__name__ + '.search_client') @mock.pa...
Python
1
state: &mut H) { for elt in self { elt.hash(state); } } } impl<K: Ord, V> Default for SegmentMap<K, V> { fn default() -> Self { Self::new() } } impl<K: PartialEq, V: PartialEq> PartialEq for SegmentMap<K, V> { fn eq(&self, other: &Self) -> bool { self.len()...
Rust
0
let mut inner_writer = scope .start_el("Bucket") .write_ns("http://awss3control.amazonaws.com/doc/2018-08-20/", None) .finish(); inner_writer.data(var_1.as_ref()); } if let Some(var_2) = &input.public_access_block_configuration { let inner_writer = scope ...
Rust
0
# Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
Python
1
=> ModerateIcePellets, Intensity::Heavy => HeavyIcePellets, }, // Anything else should be unreachable due to the preconditions checks. _ => unreachable!(), } } enum Mode { Stratiform, Convective, } enum Intensity { Light, Moderate, Heavy, } enum Preconditi...
Rust
0
n: %s' % str(e)) # Mark our failure return (False, content) except (OSError, IOError) as e: self.logger.warning( 'An I/O error occurred while handling {}.'.format( payload.name if isinstance(payload, AttachBase) else p...
Python
1
m_bposd = 0 worst_times = [0, 0, 0] # In this order, BPOSD, PyOTF, CppOTF stages_list = [] updates = 0 for index, detection_event in enumerate(detection_events): observable_flip = observable_flips[index] finished = 100 * (index / NMC) bposd_failed = False py_otf_failed = False cpp_otf_failed = Fal...
Python
1
subtracting a multiple of 2^256. fn subtract_modulus_approximation(&self) -> (Self, u64) { let x = self.0[4] >> 48; let t4 = self.0[4] & 0x0FFFFFFFFFFFFu64; // equivalent to self -= 2^256 * x (Self([self.0[0], self.0[1], self.0[2], self.0[3], t4]), x) } /// Checks if the field elem...
Rust
0