text
string
label_name
string
labels
int64
from collections import defaultdict def color_text_red(t, s): n = len(s) dp = [[-1] * (n + 1) for _ in range(len(t) + 1)] memo = {} def dfs(text_index, remaining_substrings): if (text_index, tuple(remaining_substrings)) in memo: return memo[(text_index, tuple(remaining_substrin...
Python
1
import streamlit as st import pandas as pd import matplotlib.pyplot as plt st.title("Simple Data Dashboard") upload_file = st.file_uploader("Upload a CSV file", type="csv") if upload_file is not None: # st.write("File Uploaded Successfully...") df = pd.read_csv(upload_file) st.subheader("Data Preview") ...
Python
1
"""Reduces the tensor data across all devices in such a way that all devices will get the same final result.""" from mindspore import nn, ops from mindspore.ops import ReduceOp class AllReduceSum(nn.Cell): """Reduces the tensor data across all devices in such a way that all devices will get the same final result....
Python
1
inner, parent: None, callee: get_view_for_expr_or_super(&inner.callee, bump), args: inner.args.iter().map(|value| get_view_for_expr_or_spread(value, bump)).collect(), type_args: match &inner.type_args { Some(value) => Some(get_view_for_ts_type_param_instantiation(value, bump)), None => No...
Rust
0
in advance. // // Note: If we received asset send from its reserve chain, we just need // mint the same amount of asset at local if asset_reserve_location != src_reserve_location { if rid == T::NativeTokenResourceId::get() { // ERC20 PHA save reserved assets in bridge account let _imbalance =...
Rust
0
from functools import wraps from flask import request, make_response, jsonify import bittensor from .btt_connector import BittensorNetwork from . import __spec_version__ from substrateinterface import Keypair, KeypairType #metagraph = bittensor.metagraph() # Ensure this metagraph is synced before using it in the decor...
Python
1
if page.get_title() == "page_6": self.assertEqual(len(perm), 2) else: msg = "Permission wrong at page %s" % (page.get_title()) self.assertEqual(len(perm), 0, msg) granted = [ "page_1", "page_2", "page_3", ...
Python
1
// starts with // 0b00 Invalid // 0b01 LargePage // 0b1x SmallPage match self.0 & 0b11 { 0b00 => PageTableType::Invalid, 0b01 => PageTableType::LargePage, _ => PageTableType::SmallPage, } } /// Get the physical base address the page is ...
Rust
0
import os import shutil import gzip import pickle import argparse from tqdm.auto import tqdm TYPES_FILENAME = 'types/it2_tt_v1.1_completeset_train0.types' # 'types/it2_tt_completeset_train0.types' if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--source', type=str, default=...
Python
1
from pygwarts.magical.time_turner import TimeTurner from pygwarts.irma.contrib import LibraryContrib from pygwarts.hagrid.sprouts import fssprout from pygwarts.hagrid.thrivables import Tree from pygwarts.hagrid.bloom.leafs import Transfer from pygwarts.hagrid.planting import Flourish from pygwarts.hagr...
Python
1
("serve type unwrap error, this shouldn't happen :(")) }?; let name = host; let blob_delivery = unsafe { BLOB_CACHE_DIR.as_ref().map(|dir| BlobDelivery::Persistent(dir.clone())).unwrap_or(BlobDelivery::Memory) }; Ok(match serve_type { ServeType::Databa...
Rust
0
ectedCubeSculptRemove", [OperatorSpecEditMode("sculpt_vertex_color_remove", {}, "VERT", {})], ), # Laplacian Smooth SpecMeshTest( "LaplacianSmoothDefault", "testSphereLaplacianSmoothDefault", "expectedSphereLaplacianSmoothDefault", [OperatorSpecEditMode("vert...
Python
1
b[1][1], 1); assert_eq!(b[0][1], 0); assert_eq!(b[1][0], 0); } #[test] fn test_diag() { let a = MF::<f32, 2, 2>::diag_stack(5.0); let b = MF::<f64, 2, 2>::diag_heap(3.0); assert_eq!(a[0][0], 5.0); assert_eq!(a[1][1], 5.0); assert_eq!(a[0][1...
Rust
0
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: tendermint/types/block.proto """Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor_pool from google.protobuf import message as _me...
Python
1
7 * mem::size_of::<f32>() as gl::types::GLsizei, ptr::null()); let col_attrib = gl::GetAttribLocation(shader_program, b"color\0".as_ptr() as *const _); gl::EnableVertexAttribArray(col_attrib as gl::types::GLuint); gl::VertexAttribPoint...
Rust
0
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------- # Name: sfp_stor_stdout # Purpose: SpiderFoot plug-in for dumping events to standard output. # # Author: Steve Micallef <steve@binarypool.com> # # Created: 22/10/2018 # Copyright: (c) Steve ...
Python
1
n rval else: return None def _check_equals_string(self, slot: SlotDefinition): if slot.equals_string or slot.equals_string_in: # Range "string" mandatory for "equals_string" and "equals_string_in" range = slot.range if not range: # ran...
Python
1
ure, lr_gamma=args.lr_gamma, reward_type=args.reward_type, alpha=args.alpha, beta=args.beta, gamma=args.gamma, entropy_coeff=args.entropy_coeff, # 엔트로피 가중치 전달 checkpoint_path=args.checkpoint_path, results_path=images_path, ...
Python
1
aw_circles() -> QPixmap: pixmap = QPixmap(size) pixmap.fill(Qt.GlobalColor.white) painter = QPainter(pixmap) painter.setRenderHint(QPainter.RenderHint.Antialiasing) for i, circle in folded_circles.items(): painter.setPen(QPen(Qt.GlobalColor.black, 1)) pain...
Python
1
eck_number(result,30)@ @vspace@ @center@ (@number1@ + @term[1]@) - (@number2@ + x) = @result@ @center@ x = @lib.check_number(term[1],30)@ @center@ (@number1@ - x) - (@number2@ - @term[2]@) = @result@ @center@ x = @lib.check_number(term[2],30)@ @center@ (@number1@ + x) - (@number2@ + @term[3]@) = @result@ @cent...
Rust
0
}; use ark_ec::{AffineCurve, PairingEngine, ProjectiveCurve}; use ark_ff::PrimeField; use super::{PreparedVerifyingKey, Proof, VerifyingKey}; use ark_relations::r1cs::{Result as R1CSResult, SynthesisError}; use ark_std::vec; use ark_std::vec::Vec; use core::ops::{AddAssign, Neg}; /// Prepare the verifying key `vk` ...
Rust
0
import sqlite3 from datetime import datetime from typing import List, Tuple, Optional import sys import os # データベースファイルのパス DB_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "human_tasks.db")) def initialize_db() -> None: """データベースの初期化と必要なテーブルの作成""" try: with sqlite3.connect(DB_PA...
Python
1
assert queue.consume() assert not queue.release() assert len(queue) == 0 def test_holds_lock(self): queue = self._makeOne() assert not queue.holds_lock() queue.put(b"one") queue.get(0.1) assert queue.holds_lock() queue.consume() assert ...
Python
1
def quick_sort(alist, first, last): """ 快速排序不像之前的那样把序列分成两部分 而是第一个元素通过一个low一个high游标相夹, low的左边都比第一个元素小,high的右边都比第一个元素大 以此来确定第一个元素在序列中的位置 时间复杂度O(nlogn) 第一次分成2部分,2部分分成4部分,也就是 2*2*2*...=n 也就是logn次才能变成一个个单独元素的数组推出递归 如果9个元素的话,n = log2为底9,结果为3,横向为n,纵向为logn总体最优复杂度为O(nlogn),最坏为O(n^2)...
Python
1
length as usize)) as *const Entry; unsafe { &*p } } fn read_lapic_entry(&self) -> LocalAPICEntry { unsafe { let addr = self.addr(); let flags = ptr::read((addr + 4) as *const u32); LocalAPICEntry { processor_id: ptr::read((addr + 2) as *cons...
Rust
0
stringify!(sp_compressor), "::", stringify!(atk) ) ); assert_eq!( unsafe { &(*(::std::ptr::null::<sp_compressor>())).rel as *const _ as usize }, 72usize, concat!( "Offset of field: ", stringify!(sp_compressor), ...
Rust
0
}, ] def split_prompt_response( texts: list[str], split_token: str = PROMPT_ASSISTANT, ) -> tuple[list[str], list[str]]: """Split prompt-response pairs into prompts and responses.""" def split_fn(text: str) -> tuple[str, str]: """Split a prompt-response pair into prompt and respo...
Python
1
), (ProgressState::Replicate, true, false), (ProgressState::Snapshot, false, true), (ProgressState::Snapshot, true, true), ]; for (i, &(state, paused, w)) in tests.iter().enumerate() { let mut p = new_progress(state, 0, 0, 0, 256); p.paused = p...
Rust
0
range); } #[test] fn get_host_ipv6() { let host = "[hostname:123]"; let mut range = RangeUsize::new(0, 14); assert_eq!(&host[range], host); assert!(host[range].starts_with('[') && host[range].contains(']')); let expected = RangeUsize::new(0, 14); let expected...
Rust
0
import sys import socket import pyaudio import threading class VoiceChatServer: def __init__(self, os='windows', name='server', host='localhost', port=3280): self.OS = os self.NAME = name self.HOST = host self.PORT = port self.BUFFERSIZE = 2048 self.FORMAT = pyaudio....
Python
1
from db.create_db import create_session from db.models import Applications session = create_session() def name(id: int, name: str): OBJ = session.query(Applications).filter(Applications.id == id).scalar() OBJ.name = name session.commit() def resource_url(id: int, resource_url: str): OBJ = session.que...
Python
1
num_classes = 95 # the cam score threshold of informative regions threshold = 55 # TAM parameters max_matrix_len = 1800 maximum_load_time = 80. time_slot = 80. / (max_matrix_len - 1) ''' Our traffic morphing strategy uses the following parameters: delta_up, delta_down: Boundaries parameters for the number of ...
Python
1
) comes to // implement that interface by virtue of the functions implemented on that type. // We can do the same with Rust structs as well. If a type in a third-party library implements some // function, we can create a Trait with that function, and then in our library declare that type to // implement the trait we de...
Rust
0
@torch.no_grad() def decode_latents(self, latents: torch.Tensor): latents = 1 / self.vae.config.scaling_factor * latents image = self.vae.decode(latents).sample image = (image / 2 + 0.5).clamp(0, 1) return image
Python
1
} } } } <gh_stars>100-1000 // rustc-cfg emitted by the build script: // // "use_proc_macro" // Link to extern crate proc_macro. Available on any compiler and any target // except wasm32. Requires "proc-macro" Cargo cfg to be enabled (default is // enabled). On wasm32 we never link to proc_ma...
Rust
0
od, js_name = keyPublic)] pub fn key_public(this: &WasmStorage, did: WasmDID, location: WasmKeyLocation) -> PromisePublicKey; #[wasm_bindgen(method, js_name = keyDelete)] pub fn key_delete(this: &WasmStorage, did: WasmDID, location: WasmKeyLocation) -> PromiseVoid; #[wasm_bindgen(method, js_name = keySign)] p...
Rust
0
IMAGEINFO, ) -> BOOL; pub fn ImageList_Merge( himl1: HIMAGELIST, i1: c_int, himl2: HIMAGELIST, i2: c_int, dx: c_int, dy: c_int, ) -> HIMAGELIST; pub fn ImageList_Duplicate( himl: HIMAGELIST, ) -> HIMAGELIST; pub fn HIMAGELIST_QueryInterfac...
Rust
0
llm_output={"completion_tokens": completion_tokens} ) if __name__ == '__main__': params = { "input_max_tokens": 4096, "max_new_tokens": 512, "min_new_tokens": 1, "temperature": 0.7, "top_k": 40, "top_p": 1.0, "repetition_penalty": 1.0, "div...
Python
1
#!/usr/bin/env python3 """ Скрипт для демонстрации работы Airflow с программно формируемыми абсолютными путями. Этот скрипт проверяет, что все настройки корректны и пути формируются правильно. """ import os import sys import sqlite3 from pathlib import Path def check_absolute_paths(): """Проверка абсолютных путей в к...
Python
1
k(val) => Ok(neon_serde::to_value(&mut cx, &val)?), Err(e) => cx.throw_error(e.to_string()), } } } <reponame>sanderv32/cidr-utils<filename>src/utils/v4/ipv4_cidr_separator.rs use std::cmp::Ordering; use crate::cidr::Ipv4Cidr; use crate::utils::Ipv4CidrCombiner; /// To divide an IPv4 CIDR into ...
Rust
0
CheckError::QuantityTooMuch(pos, ctx, nam, exp, det) => { writeln!(f, "Variable `{}` used too much {}", nam, pretty_pos(*pos))?; if !ctx.is_empty() { writeln!(f, "• Context:")?; for (n, uses, typ) in ctx { writeln!(f, " - {} {}: {}", uses, n, typ)?; } ...
Rust
0
SE + 0xAA0); pub const MC_SMMU_GPU_ASID: u64 = (MC_BASE + 0xAA8); pub const MC_SMMU_GPUB_ASID: u64 = (MC_BASE + 0xAAC); pub const SMMU_NUM_PAGES: usize = 0x400; static mut PTB_SET: bool = false; static mut TLB_FLUSH_SET: bool = false; static mut PTC_FLUSH_SET: bool = false; static mut LAST_MC_SMMU_TLB_FLUSH: u32 = 0;...
Rust
0
Some(*i) } else { None } } pub fn as_bool(&self) -> Option<bool> { if let JexValue::Bool(bool) = self { Some(*bool) } else { None } } pub fn as_function(&self) -> Option<&JexFunction> { if let JexValue::Function(f...
Rust
0
from dependency import get_initializer import copy # Assuming CivilizationInitializer includes a history attribute now initializer = get_initializer() def get_historical_resources(civ, round_number): # 假设history的结构是 {civ: {round: resources}} # 如果指定回合的资源信息存在,则返回该信息 if round_number in initializer.history[ci...
Python
1
0.433763, -0.286691, -0.433319, -0.061439, -0.522269, -0.410372, -0.443680, -0.313505, -0.394521, -0.431000, -0.656763, -0.587527, -0.397213, -0.579849, -0.514607, -0.342428, -0.354696, ...
Python
1
$(group.bench_function(stringify!($type), |b| { b.iter(|| { let (sender, receiver) = oneshot::channel(); sender.send(black_box($value)).unwrap(); receiver.recv_ref().unwrap() }); });)* group.fin...
Rust
0
fn_name!("vm.memory.grow.dynamic.local") => vmcalls::local_dynamic_memory_grow as _, fn_name!("vm.memory.size.dynamic.local") => vmcalls::local_dynamic_memory_size as _, fn_name!("vm.memory.grow.static.local") => vmcalls::local_static_memory_grow as _, fn_name!("vm.memory.size...
Rust
0
queryset = queryset.order_by(ordering) return queryset, True def order_module_device(self, queryset, is_descending): ordering = ('-module__device' if is_descending else 'module__device') queryset = queryset.order_by(ordering) return queryset, True def order_module_...
Python
1
from mergers import * def merge_data(): """ Merge all the data and export to a new file """ season_latin = ['2016-17', '2017-18', '2018-19', '2019-20', '2020-21', '2021-22', '2022-23'] encoding_latin = ['latin-1', 'latin-1', 'latin-1', 'utf-8', 'utf-8', 'utf-8', 'utf-8'] dfs = [] for i,j in z...
Python
1
(128, 480), "0.28": (128, 464), "0.32": (144, 448), "0.33": (144, 432), "0.35": (144, 416), "0.4": (160, 400), "0.42": (160, 384), "0.48": (176, 368), "0.5": (176, 352), "0.52": (176, 336), "0.57": (192, 336), "0.6": (192, 320), "0.68": (208, 304), "0.72": (208, 288),...
Python
1
ghts.unsqueeze(1), loss) # if self.n_class == 1: # n, loss = binary_cross_entropy(score, labels) # else: # n, loss = cross_entropy_logits(score, labels) loss = torch.sum(loss) test_loss += loss.item() ...
Python
1
> {}.is_valid()); skip_iter_eq::<{ FORMAT }>(b"123.45", b"123.45"); skip_iter_eq::<{ FORMAT }>(b"1e45", b"1e45"); skip_iter_eq::<{ FORMAT }>(b"1e", b"1e"); skip_iter_eq::<{ FORMAT }>(b"1", b"1"); skip_iter_eq::<{ FORMAT }>(b"_45", b"45"); skip_iter_eq::<{ FORMAT }>(b"__45", b"45"); skip_ite...
Rust
0
encrypted_key = f.read() decrypted_key = self.cipher.decrypt(encrypted_key).decode() # 更新使用記錄 key_info.last_used = datetime.now() key_info.usage_count += 1 self._save_keys_info() return decrypted_k...
Python
1
#! /usr/bin/env py.test from mwlib.parser.templ import pp def preprocess(s, expected, included=True): res = pp.preprocess(s, included=included) print(f"preprocess({s!r}) -> {res!r}") if expected is not None: assert res == expected, "bad preprocess result" def test_includeonly_included(): de...
Python
1
Err("unrecognized format"), }; Ok(format) } } #[derive(StructOpt, Clone)] struct DumpArgs { #[structopt(long, short, value_delimiter = ",", default_value = "main")] /// namespace to process namespaces: Vec<Namespace>, #[structopt(short, long)] /// number of pages to process [de...
Rust
0
"""Defines a Transformer model with multiple input features. For example, these could be words, parts of speech, and lemmas that are embedded in parallel and concatenated into a single input embedding. The features are separate data files with separate vocabularies. The YAML configuration file should look like this: ...
Python
1
POISONED: AtomicBool = AtomicBool::new(false); static INIT: Once = Once::new(); INIT.call_once(|| { if llvm::LLVMStartMultithreaded() != 1 { // use an extra bool to make sure that all future usage of LLVM // cannot proceed despite the Once not running more tha...
Rust
0
import json import boto3 from secret_keys import SecretKeys secret_keys = SecretKeys() sqs_client = boto3.client( "sqs", region_name=secret_keys.REGION_NAME, ) ecs_client = boto3.client( "ecs", region_name=secret_keys.REGION_NAME, ) def poll_sqs(): while True: response = sqs_client.rece...
Python
1
vRA]) periapse_state_guess.append([prefix + transcription + 'PeriapseFlybyIn: event left state vDEC', vDEC]) periapse_state_guess.append([prefix + transcription + 'PeriapseFlybyIn: event left state mass', periapse_state[6]]) periapse_state_guess.append([prefix + transcription + ': virtual chemical fuel', 0...
Python
1
m_i[from][to]; } else { temp_alpha = alpha[j][t - 1] - hmm.tr[TR_MI] - hmm.tr_m_i[from][to]; } if temp_alpha < alpha[i][t] { alpha[i][t] = temp_alpha; path[i][t] = j as i8; temp_i_1[i - I1_STATE_1] = t - 1; } } } } /***********************/ /* Non_coding state ...
Rust
0
<< 10); test_imm_op!(cpu, 0b101, 0xfffe0606, 0x81818181, 14 | 1 << 10); test_imm_op!(cpu, 0b101, 0xffffffff, 0x81818181, 31 | 1 << 10); test_imm_src1_eq_dest!(cpu, 0b101, 0xff000000, 0x80000000, 7 | 1 << 10); } #[test] fn test_ori() { let mut cpu = CPU::new(RAM::new(1024))...
Rust
0
gast.For): parent_node = self.ancestor_nodes[loop_node_index - 1] for_to_while = ForToWhileTransformer( parent_node, loop_node, cond_var_node ) for_to_while.transform() def _is_break_cond_pattern(self, break_node, loop_node): ...
Python
1
#!/usr/bin/env python3 import ffmulticonverter from distutils.core import setup data_files = [('share/applications/', ['share/ffmulticonverter.desktop']), ('share/pixmaps/', ['share/ffmulticonverter.png']), ('share/ffmulticonverter', ['share/presets.xml']), ('share/man/man1'...
Python
1
# mase_op : the set of functional equivalent IPs with different design configurations. # The first IP in each list is used by default INTERNAL_COMP = { "linear": [ { "name": "fixed_linear", "dependence_files": [ "cast/rtl/fixed_cast.sv", "fixed_arithme...
Python
1
import os import shutil from tqdm import tqdm TARGET_DIR: str = "custom-data/_dataset/brainwash/brainwash_11_24_2014_images" parent_dir: str = TARGET_DIR.split("/")[-1] for fn in tqdm(os.listdir(TARGET_DIR)): try: shutil.move( os.path.join(TARGET_DIR, fn), os.path.join(TARGET_DIR, f"{parent_d...
Python
1
Tree { raw: "+ + 5".to_owned(), ..Default::default() }; tree.parse_pos().unwrap(); tree.parse_operators().unwrap(); assert_eq!(tree.parse_node(), Err(Error::StartWithNonValueOperator)); } #[test] fn test_error_duplicate_operator() { let mut...
Rust
0
dings: Arc<RwLock<EmbeddingsWrap>>) -> Self { PyStorage { embeddings } } /// Copy storage to an array. /// /// This should only be used for storage types that do not provide /// an ndarray view that can be copied trivially, such as quantized /// storage. fn copy_storage_to_array(sto...
Rust
0
-1., self.height * 4. * pos.z * (pos.x * pos.x + pos.z * pos.z), )); // Again, only valid for exp = 4 const AREA: f64 = 6.3406654362; // thanks WolframAlpha, hope I have set up the integrals correctly if rng.gen::<bool>() { normal = -normal; } ...
Rust
0
# Python bytecode 2.7 (decompiled from Python 2.7) # Embedded file name: scripts/client/account_helpers/SyncController.py import cPickle import zlib from functools import partial import BigWorld import AccountCommands from debug_utils import LOG_CURRENT_EXCEPTION, LOG_CODEPOINT_WARNING, LOG_ERROR class SyncController(...
Python
1
} #[derive(Clone, Debug)] pub struct CubicSBox<E: Engine> { pub _marker: PhantomData<E> } impl<E: Engine>SBox<E> for CubicSBox<E> { fn apply(&self, elements: &mut [E::Fr]) { for element in elements.iter_mut() { let mut squared = *element; squared.square(); element....
Rust
0
missions); assert!(auth_context .is_owner(&Ownable { owner_id: "USER_123".to_owned(), id: "abc".to_owned() }) .is_ok()); } #[test] fn should_not_be_the_owner() { let auth = Auth { user: "USER_123".to_owned(), roles: vec!["role1".to_owned(), "...
Rust
0
RM; pub const FORMAT_G8_B8_R8_3PLANE_444_UNORM_KHR: i32 = FORMAT_G8_B8_R8_3PLANE_444_UNORM; pub const FORMAT_R10X6_UNORM_PACK16_KHR: i32 = FORMAT_R10X6_UNORM_PACK16; pub const FORMAT_R10X6G10X6_UNORM_2PACK16_KHR: i32 = FORMAT_R10X6G10X6_UNORM_2PACK16; pub const FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16_KHR: i32 = FORMA...
Rust
0
base64url for the key. /// See [RFC 7638](https://tools.ietf.org/html/rfc7638) for details. pub fn get_thumbprint_b64(&self) -> Result<String> { let jwk: BTreeMap<&'static str, String> = match self { Self::Ed25519(key) => { let group = key.group(); let curve_...
Rust
0
, O> Split for (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O) { type Left = (A, B, C, D, E, F, G); type Right = (H, I, J, K, L, M, N, O); fn split(self) -> (Self::Left, Self::Right) { match self { (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) => ((a, b, c, d, e, f, g), ...
Rust
0
pub a_pk: Option<PayingKey>, pub r: Option<CommitmentRandomness>, } impl<Scalar: PrimeField> Circuit<Scalar> for JoinSplit { fn synthesize<CS: ConstraintSystem<Scalar>>(self, cs: &mut CS) -> Result<(), SynthesisError> { assert_eq!(self.inputs.len(), 2); assert_eq!(self.outputs.len(), 2); ...
Rust
0
("huhu", answer_string); //! } //! ``` //! //! //! ## Security //! //! Not much about security in this crate, //! I would not recommend it for production use as standalone, //! always put it behind a reverse proxy. //! However any suggestions on how to improve it are very welcome. #![cfg_attr(feature = "clippy", f...
Rust
0
fs::new("test_data/agency").unwrap(); let issues = validate(&gtfs); let invalid_url_issue: Vec<_> = issues .iter() .filter(|issue| issue.issue_type == IssueType::InvalidUrl) .filter(|issue| issue.object_name == Some("Ter".to_string())) .collect(); assert_eq!(1, invalid_url_i...
Rust
0
import time from tempo.core import index_expr as ie def test_simplifications(): t = ie.Symbol("t", idx=0) T = ie.Symbol("T", is_bound=True, idx=1) e = t * 1 + 3 - 3 + T - T assert e.struct_eq(e) def test_index_expr_api(): ie.IntIndexValue.__eq__ = ie.IntIndexValue.symb_eq # type: ignore ie...
Python
1
TryFrom; use std::fs; use std::io::{BufReader, Read}; macro_rules! validate_version { ($file:expr, $version:expr) => { let file = fs::File::open($file).unwrap(); let mut buf_reader = BufReader::new(file); let mut index_bytes: Vec<u8> = Vec::new(); let...
Rust
0
") else: print(f"❌ Failed to withdraw max amount: {max_data.get('message')}") break else: ...
Python
1
related to the light client. #[derive(Clone, Debug, Error)] pub enum Kind { /// The provided header expired. #[error("old header has expired at {at:?} (now: {now:?})")] Expired { at: SystemTime, now: SystemTime }, /// Trusted header is from the future. #[error("trusted header time is too far in the...
Rust
0
string } let mut iter = db.raw_iterator(); iter.seek_to_first(); while iter.valid() { println!("{} = {:?}", bytes_to_string(&iter.key().unwrap()), iter.value().unwrap()); iter.next(); } } #[test] fn test() { remove_dir_all...
Rust
0
import pytest from llama_index.program.openai.utils import parse_partial_json def test_valid_partial_json(): assert parse_partial_json("{") == {} with pytest.raises(ValueError): parse_partial_json('{"foo":') assert parse_partial_json('{"foo": "bar') == {"foo": "bar"} def test_invalid_partial_js...
Python
1
import asyncio from playwright.async_api import async_playwright, Playwright from google_search import GoogleScraper async def run(playwright: Playwright, query: str = "python programming"): """ Run a standalone Google search demonstration. Args: playwright (Playwright): Playwright instance ...
Python
1
# SPDX-License-Identifier: BSD-3-Clause # Copyright(c) 2024-2025 Intel Corporation import os import pytest from mtl_engine import ffmpeg_app from mtl_engine.media_files import yuv_files @pytest.mark.parametrize( "video_format_1, video_format_2, test_time_mutlipler", [ ("i1080p25", "i1080p25", 4), ...
Python
1
import math import torch import torch.nn as nn import torch.nn.functional as F import modules.registry as registry from modules.utils import _l2norm, batched_index_select from .similarity import Similarity class MELMask(nn.Module): def __init__(self, cfg, katz_factor=0.999, gamma=20.0, gamma2=10.0): sup...
Python
1
, hidden_dim=128) def forward(self, net, inp, corr, flow): motion_features = self.encoder(flow, corr) inp = torch.cat([inp, motion_features], dim=1) net = self.gru(net, inp) delta_flow = self.flow_head(net) return net, None, delta_flow class BasicUpdateBlock(nn.Module): ...
Python
1
#[wasm_bindgen] #[derive(Clone, Copy, Debug, PartialEq)] pub enum Cell { Dead = 0, Alive = 1, } #[wasm_bindgen] #[derive(Clone, Debug, PartialEq)] pub struct World { pub height: usize, pub width: usize, cells: Vec<Cell>, } use std::fmt; impl fmt::Display for World { fn fmt(&self, f: &mut fm...
Rust
0
#!/usr/bin/env python3 # # import modules # import configparser import sys import os from datetime import datetime from pprint import pprint from plexapi.server import PlexServer # # Check CLI arguments # if len(sys.argv) == 2: searchPattern = sys.argv[1] else: searchPattern = '' # # Color support # class bcolo...
Python
1
yBot scenario with data_lock: current_time = datetime.now() for i in range(historical_data["time_points"].maxlen): time_point = current_time - timedelta(seconds=(historical_data["time_points"].maxlen - 1 - i) * 5) historical_data["time_...
Python
1
payload, timestamp: message .timestamp() .to_millis() .unwrap_or_else(|| millis_to_epoch(SystemTime::now())) as u64, }, ...
Rust
0
}', '\u{fe5c}'), ('\u{fe5e}', '\u{fe5e}'), ('\u{ff09}', '\u{ff09}'), ('\u{ff3d}', '\u{ff3d}'), ('\u{ff5d}', '\u{ff5d}'), ('\u{ff60}', '\u{ff60}'), ('\u{ff63}', '\u{ff63}') ]; pub const Pf_table: &'static [(char, char)] = &[ ('\u{bb}', '\u{bb}'), ('\u{2019}', '\u{2019}'), ('\u{201d}', '\...
Rust
0
cument/product/1207/96874)接口返回值字段TemplateSet获取。 :type TemplateId: str :param _TemplateRules: 防火墙模板规则列表。 :type TemplateRules: list of FirewallRule """ self._TemplateId = None self._TemplateRules = None @property def TemplateId(self): r"""防火墙模板ID。可通过[Descri...
Python
1
# Copyright (c) 2025 Kodo Robotics # # 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 applicable law or agreed to in wri...
Python
1
macro_rules! impl_unsigned_bounded_integer { ($ty:ident) => { impl NumBindWithin for $ty { fn bind_within<R: RangeBounds<Self>>(&mut self, range_bounds: &R) { use core::ops::Bound::*; let start = match range_bounds.start_bound() { Included(va...
Rust
0
.as_str()[self.index + 1..].trim() } /// Compares the given str to the header name ignoring case. /// /// ``` /// let header = "X-Forwarded-For: 127.0.0.1" /// .parse::<ureq::Header>() /// .unwrap(); /// assert!(header.is_name("x-forwarded-for")); /// ``` pub fn is_name(...
Rust
0
t'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [h...
Python
1
queeze(-2) if x.ndim == 4: # X AFTER TRANSPOSES: [BATCH_SIZE, CHANNELS, OUT_FEATURES, 1, IN_FEATURES] x = x.unsqueeze(-2).repeat(1, 1, self.out_features, 1, 1) x = x.gather( -1, self.mask.unsqueeze(0).expand(x.size(0), *self.mask.shape).unsqueeze(-2)) weight...
Python
1
unwrap(), TableColumnType::Number) } TableColumn::Text(column) => (column.name().to_owned().unwrap(), TableColumnType::Text), }) .collect(); let mut table_test = Table::from_path( file_path_test, modelfox_table::FromCsvOptions { column_types: Some(column_types), infer_options: Default::default(), ...
Rust
0
ut mock = MockStorage::new(); mock.expect_create_object() .times(1) .return_const(Err(VinotecaError::Internal("No good".to_owned()))); let rocket = rocket.manage(Config::new(mock)); let config = State::from(&rocket).unwrap(); let response =...
Rust
0