text
string
label_name
string
labels
int64
21), isizex8::new(0, 3, 7, 10, 14, 17, 21, 24), isizex8::new(0, 4, 8, 12, 16, 20, 24, 28), ]; // Bitmask for ANDing during SIMD unpacking const U32_SIMD_ANDMASK: [u32x8; 9] = [ u32x8::splat(0x0f), // 1 nibble u32x8::splat(0x0f), // 2 nibbles, etc. u32x8::splat(0x0ff), u32x8::splat(0x0f...
Rust
0
from django.urls import include, path from rest_framework.routers import DefaultRouter from .views import GroupView, ModeratorView router = DefaultRouter() router.register("group", GroupView, basename="group") router.register("moderator", ModeratorView, basename="moderator") urlpatterns = [ path("", include(rout...
Python
1
# Copyright ServiceNow, Inc. 2021 – 2022 # This source code is licensed under the Apache 2.0 license found in the LICENSE file # in the root directory of this source tree. from azimuth.modules.perturbation_testing import ( PerturbationTestingMergedModule, PerturbationTestingModule, PerturbationTestingSumma...
Python
1
uctCode(), false, 0, 0) } } pub fn PL_30_68C_HI_48S_Config(&self) -> String { unsafe { let GetP = (*self).getP; if !self._Init_Is_Japan() { self._getHostNum((*GetP)("P_30_68C_HI_48S"), mw007312_def::_Code_30_68C_HI_48S(), self._productCode(), false, 0, 0)...
Rust
0
e into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ ( master_doc, "CircuitPython_Button_Handler_Library.tex", "CircuitPython Button_Handler Library Documentation", author, "m...
Python
1
import pytest from laia.data.transforms.text import ToTensor, tokenize, untokenize from laia.utils import SymbolsTable @pytest.mark.parametrize( "sentence,tokenization,space_token,space_display", [ ( "salut à toi l'endimanché", "s a l u t <space> à <space> t o i <space> l ' e ...
Python
1
pend(create_completion( option, start_position=-len(partial) if partial else 0, display_meta=arg_info.help or "" )) return completions def _complete_option_value(self, option_info: ArgumentInfo, context: CompleterConte...
Python
1
try : import requests import time import os from art import * from colorama import Fore from time import sleep import json import random from tabulate import tabulate import sys import requests from random_user_agent.user_agent import UserAgent from random_user_agen...
Python
1
ments .into_iter() .map(|a| { let media_type = match a.media_type { elefren::entities::attachment::MediaType::Image => MediaType::Image, elefren::entities::attachment::MediaType::Video => MediaType::Video, elefren::entit...
Rust
0
ngs[:n, 1], umap_embeddings[:n, 2], c="r", label="Image") ax.scatter(umap_embeddings[n:, 0], umap_embeddings[n:, 1], umap_embeddings[n:, 2], c="b", label="Text") plt.legend() if save_path: # We are saving the 3D plot as a gif, rotating the plot 360 degrees images = [] ...
Python
1
gs[0], embeddings[1]) assert isinstance(similarity_score, np.float32) assert -1.0 <= similarity_score <= 1.0 def test_dimension_property(embedding_model: CohereEmbeddings) -> None: """Test dimension property.""" assert isinstance(embedding_model.dimension, int) assert embedding_model.dimension > 0...
Python
1
(ref bytes) | Parms(ref bytes) | Config(ref bytes) | Stats(ref bytes)=> bytes.len(), // strings: +1 because we need to append a nul byte Name(ref s) => s.len() + 1, Threshold1(_) | Threshold2(_) | Threshold3(_) => 4, GcInterval(_) => 8, Other(ref attr) => attr...
Rust
0
from typing import Dict, List, ClassVar from llama_index.core.instrumentation.events import BaseEvent from llama_index.core.instrumentation.event_handlers import BaseEventHandler from llama_index.core.instrumentation import get_dispatcher from llama_index.core.instrumentation.events.llm import LLMCompletionEndEvent c...
Python
1
from enum import Enum from typing import Dict, Any, Optional from dataclasses import dataclass class ResourceType(Enum): """Enum representing different types of cloud resources.""" COMPUTE = "compute" STORAGE = "storage" NETWORK = "network" DATABASE = "database" SECURITY = "security" MONITO...
Python
1
Result<post::Post> { let response = self .client .get(format!("{}/teams/{}/posts/{}", BASE_URL, self.team.id, id)) .bearer_auth(self.team.access_token.to_string()) .send() .await?; if response.status().is_success() { let post = re...
Rust
0
uler //! This library implements several solvers for `P || C_max` task scheduling problem. //! //! `P || C_max` is a `a|b|c` notation used in *operations research* where //! 1. `P` stands for **parallel identical resources** //! 2. `||` denotes that there are no task constraints, notably that **tasks are non-preemp...
Rust
0
import datetime import unittest from borb.pdf import HexColor from borb.pdf.document import Document from borb.pdf.layout_element.calendar.day_view import DayView from borb.pdf.page import Page from borb.pdf.visitor.pdf import PDF class TestDayView(unittest.TestCase): def test_day_view(self): d: Documen...
Python
1
ficha = list() while True: nome = str(input("Nome: ")) nota1 = float(input("Nota 1: ")) nota2 = float(input("Nota 2: ")) media = (nota1 + nota2) / 2 ficha.append(nome, [nota1, nota2], media) resp = str(input("Quer continuar? [S/N] ")) if resp in "Nn": break print("-="*15) print(f"{"N...
Python
1
eq!(podcast.last_checked, p.last_checked); assert_eq!(podcast.image_url, p.image_url); assert_eq!(podcast.cache_key, p.cache_key); Ok(()) } #[async_std::test] async fn test_delete_podcast() -> Result<()> { let d = Database::new(Connection::Memory).await?; let p = d....
Rust
0
print("Welcome to the rollercoaster!") height = int(input("What is your height in cm? ")) bill = 0 if height >= 120: print("You can ride the rollercoaster") age = int(input("What is your age?")) if age < 12: bill = 5 print("Child tickets are $5.") elif age <= 18: bill = 7 print("Yout tickets ar...
Python
1
f"tx_receipt: {tx_receipt['blockHash']!r}." ) elif allow_missing_data is False: raise EthPMValidationError( "No block hash found in deployment data. " "Unable to verify block hash on tx receipt. " "I...
Python
1
gister the Formlabs 3D Printers at [https://formlabs.com/dashboard/#setup](https://formlabs.com/dashboard/#setup). This involves connecting a Formlabs 3D Printer to the Internet and then visiting the Dashboard Registration screen on the Printer to get a registration code. Type this registration code on the Dashboard Pr...
Python
1
>, Q: Hash + Eq { let mut hasher = self.hasher().build_hasher(); value.hash(&mut hasher); let hash = hasher.finish(); let entry = self.raw_entry_mut().from_key_hashed_nocheck(hash, &value); match entry { RawEntryMut::Occupied(e) => *e.key(), ...
Rust
0
} #[cfg_attr(any(test, feature = "debug_ctap"), derive(Debug, PartialEq))] pub struct PublicKeyCredentialUserEntity { pub user_id: Vec<u8>, pub user_name: Option<String>, pub user_display_name: Option<String>, pub user_icon: Option<String>, } impl TryFrom<&cbor::Value> for PublicKeyCredentialUserEnti...
Rust
0
nter, bbox_size, dir_angle], dim=-1) return bbox3d def split_pred(self, cls_preds, reg_preds, base_xyz, prefix=''): """Split predicted features to specific parts. Args: cls_preds (torch.Tensor): Class predicted features to split. reg_preds (torch.Tensor): Regression...
Python
1
SerdeJSONError(err) => Display::fmt(err, f), } } } impl Error for JSONGetTextBuildError {} impl From<io::Error> for JSONGetTextBuildError { #[inline] fn from(v: io::Error) -> JSONGetTextBuildError { JSONGetTextBuildError::IOError(v) } } impl From<JSONError> for JSONGetTextBuildError {...
Rust
0
import os from dotenv import load_dotenv from langchain_google_genai import ChatGoogleGenerativeAI from langchain_groq import ChatGroq load_dotenv() def get_llm(model_choice: str): """Get LLM based on model choice.""" if model_choice == "gemini": return ChatGoogleGenerativeAI( model="gemin...
Python
1
path.write_text(old_content) return {"output": "Last edit undone successfully"} except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @app.post("/bash") async def handle_bash(request: BashRequest): try: if request.restart: # Kill existing b...
Python
1
t_filesign; use frame_support::sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, }; use sp_core::H256; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<TestRuntime>; type Block = frame_system::mocking::MockBlock<TestRuntime>; // Configure a mock runtime to test the...
Rust
0
#!/usr/bin/env python import os from vtkmodules.vtkFiltersCore import vtkContourFilter from vtkmodules.vtkFiltersSources import vtkSphereSource from vtkmodules.vtkIOLegacy import ( vtkDataSetReader, vtkDataSetWriter, ) from vtkmodules.vtkImagingHybrid import vtkVoxelModeller from vtkmodules.vtkRenderingCore imp...
Python
1
[doc = "0x0c - Digital I/O control for port 0 pins PIO0_3"] pub pio0_3: crate::Reg<pio0_3::PIO0_3_SPEC>, #[doc = "0x10 - Digital I/O control for port 0 pins PIO0_4"] pub pio0_4: crate::Reg<pio0_4::PIO0_4_SPEC>, #[doc = "0x14 - Digital I/O control for port 0 pins PIO0_5"] pub pio0_5: crate::Reg<pio0_...
Rust
0
(), (-1.5371385).to_channel(), (-0.4985314).to_channel(), (-0.9692660).to_channel(), 1.8760108.to_channel(), 0.0415560.to_channel(), 0.0556434.to_channel(), (-0.2040259).to_channel(), 1.0572252.to_channel(), ]) } } impl TransferFunction for Srgb{ fn from_linear<T: Float>(x: T...
Rust
0
be avoided. if module.params['sshpubkey'] is not None: if len(module.params['sshpubkey']) == 1 and module.params['sshpubkey'][0] == "": module.params['sshpubkey'] = None try: client.login(username=module.params['ipa_user'], password=module.params['ipa_pass']) ...
Python
1
Control> { if let Some(WorkResultControl::Standard(ref std)) = self.result_control { Some(std) } else { None } } } #[cfg(test)] mod tests { use super::*; #[test] fn serialize_works_ident() { let works = Works::doi("10.1037/0003-066X.59.1.29"); ...
Rust
0
CircleShapeNew(body.borrow().ptr, radius, offset), body: body.clone(), } } } /// See [Working With Circle Shapes](http://chipmunk-physics.net/release/Chipmunk-7.x/Chipmunk-7.0.1-Docs/#cpShape-Circles) pub fn offset(&self) -> CPVect { unsafe { cpCircleShapeGetOffs...
Rust
0
shape (..., 5). Returns: Boolean array which specifies whether `bboxes_a` and `bboxes_b` overlap each other of shape (...). """ chex.assert_shape(bboxes_a, (..., 5)) chex.assert_equal_shape((bboxes_a, bboxes_b)) def _overlap_a_over_b(first, second): c, s = jnp.cos(first[..., 4]), jnp.sin(first...
Python
1
ent', '—')) } ] }) # 历史记录表格 history_table = { 'component': 'VCard', 'props': {'variant': 'outlined', 'class': 'mb-4'}, 'content': [ { 'component': 'VCardTitle', ...
Python
1
# 调用 nvidia-smi 获取 GPU 信息 result = subprocess.run( ["nvidia-smi", "--query-gpu=index,name,power.draw,power.limit,memory.total,memory.used", "--format=csv,noheader,nounits"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True ...
Python
1
asks.append(asyncio.create_task(_parse_retail_item(url, title, snippet, grams, milli_l))) else: # CSE images → Vision OCR (с base64) — пробуем, если есть ключ if VISION_KEY: # Try to extract image URL from snippet or use cached image image_url = re.search(...
Python
1
import cx_Freeze import sys base = None base = "Win32GUI" shortcut_table = [ ("DesktopShortcut", # Shortcut "DesktopFolder", # Directory_ "Auto WM", # Name "TARGETDIR", # Component_ "[TARGETDIR]\\Auto WM.exe", # Target None, # Arguments None, # Description None, # Hotkey ...
Python
1
_ptr() as *mut _, &lda, ipiv.as_ptr(), work.as_mut_ptr() as *mut _, &nb, info, ) } #[inline] pub unsafe fn csytrs2( uplo: u8, n: i32, nrhs: i32, a: &[c32], lda: i32, ipiv: &[i32], b: &mut [c32], ldb: i32, work: &mut [c32], info: &mut i...
Rust
0
"] pub uartmis: crate::Reg<uartmis::UARTMIS_SPEC>, #[doc = "0x44 - Interrupt Clear Register, UARTICR"] pub uarticr: crate::Reg<uarticr::UARTICR_SPEC>, #[doc = "0x48 - DMA Control Register, UARTDMACR"] pub uartdmacr: crate::Reg<uartdmacr::UARTDMACR_SPEC>, _reserved14: [u8; 0x0f94], #[doc = "0...
Rust
0
ocle_competency.cycle::text = $3 AND eval_observation.active = true AND eval_observation.date <= $2 AND eval_observation_student.student_id = $1 ", &[student_id, date, &cycle.to_str()], )? { // debug!(?row, "eval_observation_stats_by_cycle 2"); let competency_id = row.get(0); if...
Rust
0
from helpers import pytester_path PYFILE = ( """ import matplotlib.pyplot as plt import pytest @pytest.mark.mpl_image_compare def test_mpl(): fig, ax = plt.subplots() ax.plot([1, 2, 3]) return fig """ ) def test_generate_baseline_images(pytester): pytester.makepyfi...
Python
1
'a mut W { self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u16) & 0x01) << 6); self.w } } #[doc = "JTAG mailbox output interrupt enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum JMBOUTIE_A { #[doc = "0: Interrupts disabled"] DISABLE = 0, #[doc = "1...
Rust
0
import json from battleController import gSet levelNum = 5 def load(level): """ Load the data of the level """ with open(f"./save/level{level}.json", "r", encoding="utf-8") as file: data = json.load(file) return data def save(level, data): """ Save the data of the level ""...
Python
1
ops.append(to_var.assign(from_var)) return ops if __name__ == '__main__': mask = get_mask(['A', 'A', 'A'], action_space) print(mask[0]) # _, response_mask, _, _ = get_mask_alter(['A', 'A', 'A', 'J', 'J', '10', '6', '6', '5'], ['9', '9', '9', '5'], False, # ...
Python
1
n \\x7f ÿ $ \\\\ end\"", toks.to_string()?); //! //! let toks: js::Tokens = quote!(#(quoted("start π 😊 \n \x7f ÿ $ \\ end"))); //! assert_eq!("\"start π 😊 \\n \\x7f ÿ $ \\\\ end\"", toks.to_string()?); //! # Ok(()) //! # } //! ``` use crate::fmt; use crate::tokens::ItemStr; use relative_path::{RelativePath, Relative...
Rust
0
t.iter().next() { Some(rep) => rep.clone(), None => bail!( "[Bool::choose_rep] cannot choose representative of empty set" ), } ; let was_there = set.remove(& rep) ; debug_assert!( was_there ) ; Ok( (rep, set) ) } } } impl Domain for Int { fn of_cst(cst:...
Rust
0
import pytest import subprocess import os import re def run_main_py(input_file): possible_names = ["Assignment4.py", "assignment4.py", "main.py", "Main.py"] script_name = None for name in possible_names: if os.path.isfile(name): script_name = name break if script_name is...
Python
1
from app.models.stay import Stay class AvailableStaysService: available_stays_offers = [] def set_stay(self, stay: Stay) -> Stay: self.available_stays_offers.append(stay) return stay
Python
1
"""Almacenar y mostrar información de estudiantes Escribe un programa que permita al usuario ingresar el nombre y la calificación de varios estudiantes. El programa debe almacenar esta información en un diccionario donde las claves sean los nombres de los estudiantes y los valores sean sus calificaciones. Al final, el ...
Python
1
decoded: Request = decoder.decode(&buffer[..]).unwrap(); assert_eq!(decoded, request); } // Test an encoding when the provided buffer is too small (should panic). #[test] #[should_panic(expected = "failed to write whole buffer")] fn cqc_hdr_buf_too_small() { let client = Client::ne...
Rust
0
latent = outputs.last_hidden_state ids_restore = outputs.ids_restore mask = outputs.mask decoder_outputs = self.decoder(latent, ids_restore, interpolate_pos_encoding=interpolate_pos_encoding) logits = decoder_outputs.logits # shape (batch_size, num_patches, patch_size*patch_size*num_c...
Python
1
) for record, claimed_by in stats['claimed_by_external']: print(f" • {record['name']} - claimed by '{claimed_by}' (not in competing set)") print(f" Competing packs: {record['node_ids']}") print() # Still unresolved if stats['unresolved']: print("4. STIL...
Python
1
inn::{Connection, Endpoint}; use tokio::net::{TcpListener, TcpStream}; use tokio_rustls::TlsAcceptor; use futures::StreamExt; use tokio::io::AsyncWriteExt; use crate::tls::{get_quic_cfg, get_tls_cfg}; use config::Config; use crate::server::quic::{handle_quic}; #[derive(Debug, Clone)] pub struct Server { cache: Ar...
Rust
0
gonna sneak up on him.", "Now the hunted becomes the hunter.", "Yeah, right.", "Shake his hand?", "Maybe I won't send her that check.", "All right, all right, two fifty.", "She can't take it.", "It's not hers, it's theirs.", "Once there's no theirs there's no hers, it should be ours.", "How could you...
Rust
0
continue; } let bodies = stream::iter(urls) .map(|url| { let client = &client; async move { let resp = client .get(&url) .timeout(Duration::from_secs(5)) ...
Rust
0
'occaecat cupidatat non proident, sunt in ' \ 'culpa qui officia deserunt mollit anim id ' \ 'est laborum.' ticket['component'] = 'component1' ticket['version'] = '2.0 Standard and International Edition' ticket['res...
Python
1
# Helper function to check if a position is valid def is_valid(x, y, rows, cols): return 0 <= x < rows and 0 <= y < cols # DFS function to find unique paths from a trailhead to a '9' def dfs(grid, x, y, rows, cols, path, all_paths): # Directions: up, down, left, right directions = [(-1, 0), (1, 0), (0, -1...
Python
1
match board[row][column].to_digit(10) { None => continue, Some(idx) => { if table[idx as usize] > 0 { return false; } else { ...
Rust
0
nable_parallel_execution=False, # Force sequential mode ) print(" ✅ Sequential-only agent created") print(" 📝 This would use traditional LangGraph workflow for compatibility") # 4. Show configuration options print("\n4. Configuration Options:") print(" 📋 Parallel Execution Configurati...
Python
1
f)) } } fn connect_property_selection_end_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<F> = Box_::new(f); connect_raw(self.as_ptr() as *mut _, b"notify::selection-end\0".as_ptr() as *const _, Some(transmute(notify_...
Rust
0
model_inputs["input_ids"].append(input_ids) model_inputs["attention_mask"].append([1] * len(input_ids)) model_inputs["labels"].append(labels) model_inputs["kl_input_ids"].append(kl_input_ids) model_inputs["kl_attention_mask"].append([1] * len(kl_input_ids)) model_inputs["kl_l...
Python
1
from typing import List class Solution: def rotate(self, matrix: List[List[int]]) -> None: """ Rotate the image by 90 degrees (clockwise). Do not return anything, modify matrix in-place instead. Args: matrix: n x n 2D matrix representing an image ...
Python
1
ule in self.denoising_unet.attn_processors.items(): if isinstance(attn_module, IPAttnProcessor2_0): if 'up' in attn_name: ip_attn_tm.append(torch.clone(attn_module.attn_map2)) ip_attn_face.append(torch.cl...
Python
1
ION_LOW_POWER: u32 = 0; pub const XCHAL_HAVE_FUSION_AES: u32 = 0; pub const XCHAL_HAVE_FUSION_CONVENC: u32 = 0; pub const XCHAL_HAVE_FUSION_LFSR_CRC: u32 = 0; pub const XCHAL_HAVE_FUSION_BITOPS: u32 = 0; pub const XCHAL_HAVE_FUSION_AVS: u32 = 0; pub const XCHAL_HAVE_FUSION_16BIT_BASEBAND: u32 = 0; pub const XCHAL_HAVE_...
Rust
0
return Ok(()); } if dev_buf.capacity > 0 && mem::size_of::<T>() > 0 { let capacity = dev_buf.capacity; let ptr = mem::replace(&mut dev_buf.buf, DevicePointer::null()); unsafe { match cuda_free(ptr) { Ok(()) => { ...
Rust
0
) @classmethod def get_logger_class(cls, name: str): return cls.get_class(name, "logger_name_mapping") @classmethod def get_trainer_class(cls, name: str): return cls.get_class(name, "trainer_name_mapping") @classmethod def get(cls, name: str, default=None, no_warning: bool = F...
Python
1
entities = vec!["Hello","my","name","is","John","What","is","your","name","A","name","is","a","personal","identifier","Never","share","your","name","My","ssn","is","003-67-0998"]; /// let mut pttrn_def = PatternDefinition::new(); /// let rslt = pttrn_def.analyze_entities(entities); /// let pttrns = vec!["C...
Rust
0
# Quick test script from tetris_env import TetrisEnvironment print("Testing environment directly...") env = TetrisEnvironment() print("Resetting...") state, _ = env.reset(seed=123) print(f"Reset worked, state shape: {state.shape}") print("Taking one action...") state, reward, done, _, _ = env.step(13) print(f"Action...
Python
1
) if !self.include_nonconstraining => { // Constant expressions are not injective return c.ty().visit_with(self); } ty::ConstKind::Param(data) => { self.parameters.push(Parameter::from(data)); } _ => {} } c....
Rust
0
pub DeviceHandle: ::HANDLE, } DEFINE_GUID!(D3DAUTHENTICATEDCONFIGURE_SHAREDRESOURCE, 0x772d047, 0x1b40, 0x48e8, 0x9c, 0xa6, 0xb5, 0xf5, 0x10, 0xde, 0x9f, 0x1); #[repr(C)] #[derive(Clone, Copy, Debug)] pub struct D3DAUTHENTICATEDCHANNEL_CONFIGURESHAREDRESOURCE { pub Parameters: D3DAUTHENTICATEDCHANNEL_CONFIGUR...
Rust
0
iiii(RmRR*t com_with_item(RGRhtbodyRjtret((stransformer.pyRs #! cCsZt|dkr+|j|dt}nd}|j|d}t|||d|S(NiiiR((R*RRRRmtWith(...
Python
1
d() plt.xlim(1e-1, 200) plt.xlabel("$r/r_s$") plt.xticks([0.1, 1, 10, 100], ["$0.1$", "$1$", "$10$", "$100$"]) plt.ylim(-0.025, 0.025) plt.yticks( [-0.02, -0.01, 0.0, 0.01, 0.02], [r"$-2\%$", r"$-1\%$", r"$0\%$", r"$1\%$", r"$2\%$"], ) plt.savefig("error.png") plt.figure() plt.loglog(r / r_s, fac, "b-", la...
Python
1
import argparse import pandas as pd import json from io import StringIO def make_df(fname): with open(fname) as f_in: text = "" for line in f_in: if "&" in line: text += line.replace("\\", "") + "\n" data = StringIO(text) return pd.read_csv(data, sep="&") if __...
Python
1
put = subprocess.call(command, shell=True, stdout=None) # # crop video # curr_input_path = os.path.join(opt.avi_dir,opt.reference,'video.avi') # curr_output_path = os.path.join(opt.crop_dir,opt.reference,'00000.avi') # print("curr_output_path:", curr_output_path) # cmd = f"ffmpeg -i {curr_input_path} -vf \"crop={opt.x2...
Python
1
assert!(!self.was_deleted()); unsafe { #set_down_box(self._inner, f as i32) } } fn down_frame(&self) -> FrameType { assert!(!self.was_deleted()); unsafe { mem::transmute(#down...
Rust
0
elf.current_epoch, dominate_method='hoeffding', regression=False, num_split_after_samples=10, min_split_samples=5) self.assertAllEqual([4], finished.eval()) self.assertAllEqual([], stale.eval()) def testEarlyDominatesBootstrap(self): with self.test_session(): ...
Python
1
as im: im.load() def test_realloc_overflow(self, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(TiffImagePlugin, "READ_LIBTIFF", True) with Image.open("Tests/images/tiff_overflow_rows_per_strip.tif") as im: # Assert that the error code is IMAGING_CODEC_MEMORY...
Python
1
if torch.cuda.is_available(): torch.cuda.set_device(args.gpu) print(f"CUDA Device: {torch.cuda.current_device()}") # Create the grid map environment env = Map(size=MAP_SIZE, obstacle_ratio=OBSTACLE_RATIO, seed=args.seed) env.create_random_map() env.initialize_start_end()...
Python
1
child. /// /// See [`Self::setpgroup()`]. #[inline] pub fn getpgroup(&self) -> Result<libc::pid_t> { let mut pgroup = MaybeUninit::uninit(); Error::unpack_eno(unsafe { sys::posix_spawnattr_getpgroup(&self.0, pgroup.as_mut_ptr()) })?; Ok(unsafe { pgroup.assume_init() }) } ...
Rust
0
234; cpu.a = 0x72; cpu.y = 0x13; cpu.memory.borrow_mut().write(0x234, 0x1F); cpu.memory.borrow_mut().write(0x1F, 0x02); cpu.memory.borrow_mut().write(0x20, 0x0A); cpu.memory.borrow_mut().write(0x0A02 + 0x13, 0x5A); cpu.unofficial_rotate_right_memory_add_acc_indir...
Rust
0
int(minutes) * 60 + float(racetime.replace(",", ".")) return None def handle_show_odds(number: str | int | float) -> int | float: if isinstance(number, (int, float)): return number number = remove_tags(number).strip() if "," in number: return float(number.replace(",", ".")) ret...
Python
1
Type(ImageViewNode, [('Display',)]) #fclib.registerNodeType(UnsharpMaskNode, [('Image',)]) ## Method 2: If we want to make our custom node available only to this flowchart, ## then instead of registering the node type globally, we can create a new ## NodeLibrary: library = fclib.LIBRARY.copy() # start with the defaul...
Python
1
space0, eof), |input| { match input.chars().next() { Some(')') => "unexpected parens".to_string(), _ => format!("expected either the next term after ',' or the next check variant after 'or', but got '{}'", input) } }, " ,\n", )...
Rust
0
} inner.head.set_connection_type(ConnectionType::Upgrade); inner .head .headers .insert(header::UPGRADE, HeaderValue::from_static("websocket")); inner.head.headers.insert( header::SEC_WEBSOCKET_VERSION, HeaderValue::from_static("...
Rust
0
..0 let val = reg_rawrd(); reg_rawwr(val & !(0x1 << 0) | ((newval & 0x1) << 0)); } /* * ================================================================================================ * Data Structure Definitions * ===========================================================================================...
Rust
0
 -3`c@s:ddlmZddlmZdefdYZdS(i(t ProbingState(t CharSetProbertCharSetGroupProbercBsMeZddZdZedZedZdZdZ RS(cCs8tt|jd|d|_g|_...
Python
1
)> for (I1,) { type Type = I1; #[inline(always)] fn concat_many(tpls: (I1,)) -> Self::Type { let (tpl,) = tpls; tpl } } impl<Z1, Z2> TupleConcatMany<(Z1, Z2)> for (Z1, Z2) where (Z1, Z2): TupleConcat<Z1, Z2>, { type Type = ConcatT...
Rust
0
############### cairo_context.set_source_rgba(*operation['rgba1']) self._show_text_at_coords(cairo_context, layout, entire_text, \ text_x, text_y) ink_rect, logical_rect = layout.get_pixel_extents() self._preview_width = logical_rect.width self._pre...
Python
1
if retries == max_retries { return Err((v, io_error)); } retries += 1; log.grow(); } r => return r, } } } use std::path::{Path, PathBuf}; #[derive(Debug, PartialEq)] pub enum MaybePath<'a> { Pat...
Rust
0
import sys import pytest # Include the root of the project sys.path.append("..") import actions.trace import layers.packet import actions.strategy import actions.utils import evolve from scapy.all import IP, TCP def test_trace(logger): """ Tests the trace action primitive. """ trace = actions.trace....
Python
1
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class ValidateUserPrincipal(object): def __init__(self): self._principal_cert_no = None self._principal_name = None @property def principal_cert_no(self): return self._...
Python
1
MAP_EPSZ_256MB, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `EPI_ADDRMAP_EPSZ_256B`"] #[inline(always)] pub fn is_epi_addrmap_epsz_256b(&self) -> bool { *self == EPI_ADDRMAP_EPSZR::EPI_ADDRMAP_EPSZ_256B } #[doc = "Checks if the value of the f...
Rust
0
import asyncio import pytest from tac.web.ui import UIManager # Define dummy async functions to override real implementations during testing async def dummy_send_status(message): return async def dummy_send_recording_status(status): return class DummyServer: async def send_status_message(self, message): ...
Python
1
from calls import api from calls import cache from alive_progress import alive_bar import os import mutagen.mp4 from dotenv import load_dotenv # Load .env File load_dotenv() # Mapper artists = [] tracks = {} folders = os.listdir(os.getenv('IPOD_MUSIC_PATH')) with alive_bar(len(folders)) as bar: for folder in fol...
Python
1
round_idx); self.s_maj.enable(region, row)?; // Assign and copy spread_a_lo, spread_a_hi spread_halves_a .0 .copy_advice(|| "spread_a_lo", region, a_4, row - 1)?; spread_halves_a .1 .copy_advice(|| "spread_a_hi", region, a_5, row - 1)?; ...
Rust
0
tar = soup.new_tag( "a", href="https://github.com/bgruening/docker-galaxy/tarball/master" ) a_tar.string = "Download " strong_tar = soup.new_tag("strong") strong_tar.string = "TAR Ball" a_tar.append(strong_tar) li_tar.append(a_tar) ul_box.append(li_tar...
Python
1
ode(cond["seq_orig"].cpu()) save_image(noisy_input["bbox"][0:1], noisy_input["label"][0:1], noisy_input["mask"][0:1], **save_kwargs) save_image(pred["bbox"], pred["label"], pred["mask"], out_path=out_dir + dataset[target_index].attr["name"] + "/layoutdm_output.png", **save_kwargs, nrow=int(math.sqrt(n_samples) * 2...
Python
1