text
string
label_name
string
labels
int64
import numpy as np import matplotlib.pyplot as plt # Generate impulse response h[n] h = np.zeros(99) for i in range(99): h[i] = 0.31752 * np.sin(0.314159 * (i - 49.00001)) / (i - 49.00001) h[i] *= 0.54 - 0.46 * np.cos(0.0641114 * i) # Plot impulse response h[n] plt.figure() plt.stem(h) plt.xlabel('n') plt.yla...
Python
1
0xf0, 0xe0, 0x90, 0x90, 0x90, 0xe0, 0xf0, 0x80, 0xf0, 0x80, 0xf0, 0xf0, 0x80, 0xf0, 0x80, 0x80 ]; const SPRITE_START: usize = SPRITE_ADDR; const SPRITE_END: usize = SPRITE_ADDR + 16 * SPRITE_HEIGHT; state.memory[SPRITE_START .. SPRITE_END].copy_from_slice(&SPRITE_DATA); } fn main() -> Result<(), Er...
Rust
0
zABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' * 5, ], ) def test_with_parametrize(httpbin,data): assert requests.get(httpbin.url + "/get").status_code == 200 """ ) result = testdir.runpytest("--record-mode=all") result.assert_outcomes(passed=1) cassette_path = testdir.tmpdir.join( "casset...
Python
1
from typing import Union, List from golem.core.log import LoggerAdapter from golem.core.optimisers.opt_history_objects.individual import Individual from fedot.core.data.data import InputData from fedot.core.pipelines.adapters import PipelineAdapter from fedot.core.pipelines.ts_wrappers import out_of_sample_ts_forecast...
Python
1
= _reflection.GeneratedProtocolMessageType('StartAltitudeControlResponse', (_message.Message,), { 'DESCRIPTOR' : _STARTALTITUDECONTROLRESPONSE, '__module__' : 'manual_control.manual_control_pb2' # @@protoc_insertion_point(class_scope:mavsdk.rpc.manual_control.StartAltitudeControlResponse) }) _sym_db.RegisterMe...
Python
1
reUnit.WH", "type": "VIFUnit.ENERGY_WH", "function": "FunctionType.INSTANTANEOUS_VALUE", "storage_number": 0, "unit_enh": "VIFUnitEnhExt.POSITIVE_ACCUMULATION", } frame_rec_dict = json.loads(self.frame.records[12].to_JSON()) self.assertEqual(frame_...
Python
1
r'(\d+)\s+bounced', r'(\d+)\s+rejected\s+\((\d+)%\)', r'(\d+)\s+reject\s+warnings', r'(\d+)\s+held', r'(\d+)\s+discarded\s+\((\d+)%\)', r'(\d+)\s+bytes\s+received', r'(\d+)k\s+bytes\s+delivered', r'(\d+)\s+senders', ...
Python
1
# Generated by Django 2.2.24 on 2021-06-14 22:04 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('learning_sequences', '0012_add_user_partition_group'), ] operations = [ migrations.CreateModel( ...
Python
1
put) if not torch.is_tensor(target): target = torch.from_numpy(target) if output.dim() == 1: output = output.view(-1, 1) else: assert output.dim() == 2, \ 'wrong output size (should be 1D or 2D with one column \ per class)' ...
Python
1
Fd, FromRawFd}; use std::time::Duration; use nix::sys::time::{TimeVal, TimeValLike}; pub trait TcpListenerExt { fn accept_timeout(&self, timeout: Option<Duration>) -> io::Result<(TcpStream, SocketAddr)>; } impl TcpListenerExt for TcpListener { /// accept(2) with timeout /// /// * `timeout` /// ...
Rust
0
from nonebot_plugin_alconna.uniseg import UniMessage from nonebot_plugin_alconna.uniseg.segment import I18n from nonebot_plugin_alconna import Args, Match, Alconna, on_alconna from .i18n import Lang, lang from .typing import LudoMetadata from .config import plugin_config from .manager import ludokit_manager from .name...
Python
1
r'J:\福岛\ERA5切尔诺贝利\大气温度\\' + hpa + '\\' + 't' + str(year) + str( # month) + hpa + 'download.nc') # 下载t2m 陆地和海洋都有的 """for countryArg in range(len(country)): for i in range(1976, 1987): for j in range(4, 6): print(i) print(str(j).rjust(2, '0')) ...
Python
1
from lib.Logger import logger from lib.SaveManager import save_manager from lib.Localization import loc from controller.MenuController import MenuController from controller.LibController import LibController from data.Config import Config class SettingMenu: def __init__(self): self.consolas = LibControll...
Python
1
tid][1,1] + x[tid][1,2]*y[tid][1,2] + x[tid][2,0]*y[tid][2,0] + x[tid][2,1]*y[tid][2,1] + x[tid][2,2]*y[tid][2,2]) @wp.kernel() def set_value(x: wp.array(dtype=float), y: wp.array(dtype=float)): tid = wp.tid() x[tid] = y[tid] def wp_clamp(x, min, max): y = torch.clamp(wp.to_torch(x), min, max) wp.la...
Python
1
b0fc63e20d86b17c8bf5a7b089a63c5eac1824ee93"), ciphertext: &hex!("b2f4edf5f0b0bfc590fead6239b0f2fb"), tag: &hex!("2540ceb5ef247c95d63df84c46468533"), }, TestVector { key: &hex!("2ca76112300bed65b87ba6ec887cd514f4633c1c96565fec8e3e69ae2ba88401"), nonce: &hex!("964864510a8c957dcfb97...
Rust
0
start = pointer.wrapping_sub(start); if pointer_minus_start < length { let offset = JIS0208_RANGE_TRIPLES[i + 2] as usize; return Some((pointer_minus_start + offset) as u16); } i += 3; } None } #[inline(always)] pub fn jis0208_range_encode(bmp: u16) -> Option<usi...
Rust
0
) # then assert node assert node.up def test_ptp(self, session): # given # when ptp = session.create_ptp() # then assert ptp assert ptp.up def test_control_net(self, session): # given # when control_net = sessi...
Python
1
let ret: usize; unsafe { llvm_asm!("swi 0" : "={r0}"(ret) : "{r7}"(n), "{r0}"(a1), "{r1}"(a2), "{r2}"(a3), "{r3}"(a4) : "memory" "cc" : "volatile"); } check_errno(ret) } #[inline(always)] pub fn syscall5( n: Sysn...
Rust
0
list.push(document_name.0.into()); }); list.sort(); if list.is_empty() { OpsOutcome::DbEmpty } else { OpsOutcome::DocumentList(list) } } /// Create a new document pub(crate) async fn document_create( &mut self, repo_dir: &Ut...
Rust
0
''' 1. 다익스트라에서 가상노드 이용하기 - 맥도날드가 여러개 있는 경우, <여러 개의 맥도날드 중, 각 집들에 가장 가까운 맥도날드 최단거리> 를 구해야 한다. - 여러 개의 맥도날드들에 대해 다익스트라를 매번 돌리면 시간초과. => '가상노드' 를 추가해서 이용하는 방법 사용 - 모든 맥도날드들과 가중치 0 엣지로 연결된 가상노드(더미노드)를 추가한다. - 가상노드 사용 시, 맥도날드 노드가 1,5번이라 할때 '더미노드 > 1번노드 > 7번 집', '더미노드 > 5번노드 > 7번집' 두가지 케이스 중 더 최단거리로 ...
Python
1
ayName> <OrganizationURL xml:lang="ja"> http://www.example.com/ </OrganizationURL> </Organization> <ContactPerson contactType="technical"> <Extensions> <hoge xmlns="http://hoge.example.com/">hogehoge</hoge> </Extensions> <Company>SIOS Technology, Inc.</Company> <GivenName>Takashi</GivenName> <SurN...
Python
1
fn do_coarse(&self, cs: ClockSource, clockid: clockid_t, tp: *mut timespec) -> Result<i32, ()> { let vdso_data = self.vdso_data(cs); loop { let seq = vdso_data.seq(); atomic::fence(Ordering::Acquire); unsafe { (*tp).tv_sec = vdso_data.sec(clockid)? a...
Rust
0
import function print("Hello! Welcome to a Pig Latin converter") print("=" * 39) original_string = input( "Please type the string you would like to convert to pig latin: " ) print() print("Your converted string is:") print(function.to_pig(original_string))
Python
1
not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CO...
Rust
0
import requests import pyaudio import re import multiprocessing import threading import time import sys import keyboard import json import os # Ollama 和 GPT-Sovits TTS 的 api ollama_base_url = "http://localhost:11434/api" gpt_sovits_tts_url = "http://127.0.0.1:9880/tts" # True:仅将“”内台词生成语音,False:全部生成,(有bug =.= extract_...
Python
1
return metrics def _evaluate_single_question(self, metrics_record: ExperimentQuestionMetrics) -> Optional[EvaluationMetrics]: """Evaluate a single question and return its metrics""" try: if metrics_record.generated_answer: answer_sample = SingleTurnSample( ...
Python
1
---------# anchor_mask = [[6, 7, 8], [3, 4, 5], [0, 1, 2]], max_boxes = 100, confidence = 0.5, nms_iou = 0.3, letterbox_image = True): image_shape = K.reshape(outputs[-1],[-1]) box_xy = [] box_wh = [] box_confidence...
Python
1
:type ChannelOrderId: str :param _OrderStatus: 订单状态。关单成功CLOSED :type OrderStatus: str """ self._OutOrderId = None self._ChannelOrderId = None self._OrderStatus = None @property def OutOrderId(self): """外部商户订单号 :rtype: str """ ...
Python
1
::new("answer_updated") .add_attribute("current", Uint128::new(new_answer)) .add_attribute("round_id", round_id.to_string()), ); let previous_round_id = prev_round_id(round_id)?; let prev_round = ROUNDS.load(deps.storage, previous_round_id.into())?; // Se...
Rust
0
import spacy from collections import Counter from fuzzywuzzy import fuzz nlp = spacy.load("en_core_web_sm") STOPWORDS = {"requirements", "skills", "years", "team", "development", "solutions", "systems", "tools"} SKILL_KEYWORDS = ["experience with", "knowledge of", "proficient in", "familiarity with"] def extract_ski...
Python
1
ds a model and its associated artifacts. Args: model_id: The ID of the model version to load. Returns: A tuple containing (loaded_model, artifacts_dictionary), or None if not found. """ try: metadata = self.get_model_metadata(model_id) if...
Python
1
"""ISO7816-4 sw1 only error checker. __author__ = "https://www.gemalto.com/" Copyright 2001-2012 gemalto Author: Jean-Daniel Aussel, mailto:jean-daniel.aussel@gemalto.com This file is part of pyscard. pyscard is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public...
Python
1
# Copyright 2021 DengBoCong. 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 applicable law or a...
Python
1
s = data.reshape([1, 1, -1]) fft = ConvSTFT(N, inc, fft_len=fft_len, win_type='hanning', feature_type='complex') ifft = ConviSTFT(N, inc, fft_len=fft_len, win_type='hanning', feature_type='complex') inputs = torch.from_numpy(inputs.astype(np.float32)) outputs1 = fft(inputs) print(outputs1.shape) ...
Python
1
""" FreeRTOS support for GDR. Implements FreeRTOS specific kernel object handling and pretty-printers. """ from .detector import FreeRTOSDetector from .objects import ( FreeRTOSTask, FreeRTOSSemaphore, FreeRTOSMutex, FreeRTOSTimer, FreeRTOSQueue, ) __all__ = [ "FreeRTOSDetector", "FreeRTO...
Python
1
p_k=3, monitor='val_loss', mode='min' ) # Set up progress bar progress_bar = LitProgressBar() # Set the strategy based on the number of GPUs if num_gpus > 1: strategy = DDPStrategy(find_unused_parameters=False) else: strategy = 'auto' # Use 'auto' for single GP...
Python
1
_Security_Authentication_Identity\"`*"] pub const KERB_USE_DEFAULT_TICKET_FLAGS: u32 = 0u32; #[doc = "*Required features: `\"Win32_Security_Authentication_Identity\"`*"] pub const KERB_WRAP_NO_ENCRYPT: u32 = 2147483649u32; #[doc = "*Required features: `\"Win32_Security_Authentication_Identity\"`*"] pub const KERN_CONTE...
Rust
0
= self.to_nav_map[variable].output_layer_in_step_and_in_z.clone(); let mut this_step: usize = answers[answer_index].0.clone() - 1; let mut prev_z: Vec<usize> = Vec::new(); //let mut union_z_to_error: Vec<usize> = Vec::new(); let mut errors: Vec<Vec<f32>> = Vec::new(); // [z][error value] let mut st...
Rust
0
: 23, hi: 26, }); assert_eq!(p.parse(), Err(sol)); } #[test] fn err_alter_5() { let mut p = parser::Parser::create("alter table foo add (bar int"); let sol = parser::ParseError::NotAWord(Span { lo: 22, hi: 23, }); assert_eq!(p.parse(), Err(sol)); } #[test] fn err_alte...
Rust
0
# use sort() # alphanumerically thislist = ['orange','mango','kiwi','pineapple','banana'] thislist.sort() print(thislist) # with conditions def myfunc(n): return abs(n - 50) thislist2 = [100,50,65,82,23] thislist2.sort(key = myfunc) print(thislist2) # this function helps with CASE SENSITIVE: # i...
Python
1
e: torch.save(shard, os.path.join(output_dir, shard_file)) if not state_dict_split.is_sharded: print(f"Model weights saved in {os.path.join(output_dir, weights_name)}.") else: index = { "metadata": state_dict_split.metadata, "weight_map": state_dict_split.ten...
Python
1
); } #[repr(C)] #[derive(Debug, Copy, Clone)] pub struct SquashMemoryFuncs { pub malloc: ::std::option::Option<unsafe extern "C" fn(size: usize) -> *mut ::std::os::raw::c_void>, pub realloc: ::std::option::Option< unsafe extern "C" fn( ptr: *mut ::std::os::raw::c_void, ...
Rust
0
# Copyright 2024 Ant Group Co., Ltd. # # 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
ments::Requirement; const INPUT: &str = include_str!("input.txt"); /// See if a ticket is valid given the requirements. /// Return None if it's ok, or Some with the error rate if it's broken. fn error_rate(ticket: &[u32], reqs: &HashMap<String, Requirement>) -> Option<u32> { let bads = ticket .ite...
Rust
0
elf) @opacity.setter def opacity(self, value): shape.ShapeStim.opacity.fset(self, value) if hasattr(self, "bar"): self.bar.opacity = value @property def colorSpace(self): return shape.ShapeStim.colorSpace.fget(self) @colorSpace.setter def colorSpace(self, v...
Python
1
rse_mass()); b2.displace(displacement * -b2.inverse_mass()); } fn resolve_velocity(&self, b1: &mut Body, b2: &mut Body) { let separating_speed = self.normal() * (b1.velocity() - b2.velocity()); if separating_speed < 0.0 { let new_separating_speed = -separating_speed * b1.res...
Rust
0
-332 -92 -474 -289 -617 -141 -398 -367 -537 -369 -88 -608 -699 -257 -602 -276 -406 -92 -746 -398 -387 -234 -331 -225 -480 -667 -264 -299 -673 -265 -142 -512 -573 -508 -551 -471 -270 -328 -648 -625 -779 -232 -393 -749 -84 -240 -59 -220 -55 -224 -350 -130 -23 -239 -105 -2 -762 -702 -163 -94 -350 -11 -176 -43 -654 -136 -...
Rust
0
logical_types.update(class_name_dict) return logical_types def str_to_logical_type(self, logical_str, params=None, raise_error=True): """Helper function for converting a string value to the corresponding logical type object. If a dictionary of params for the logical type is provide...
Python
1
= Some(box_resize); (*b.widget).update = Some(box_update); // (*b.widget).find_mouse_target = Some(box_find_mouse_target); // (*b.widget).get_desired_height = Some(box_get_desired_height); // (*b.widget).get_desired_width = Some(box_get_desired_width); ...
Rust
0
headers() { if section.Characteristics & 0xE0000000 == 0x60000000 { // Mix the markov data from this binary match pe.derva_slice(section.VirtualAddress, section.VirtualSize as usize) { Ok(bytes) => analyze(bytes, &mut markov_data), Err(e) => eprintln!("cannot read code from {:?}...
Rust
0
OST': form = ProductoForm(request.POST, request.FILES, instance=producto) if form.is_valid(): form.save() return redirect('productos:index') # O redirigir a la vista detalle del producto si existe else: form = ProductoForm(instance=producto) return render(request,...
Python
1
2C16_0629, 0x0B75_DE6A), (r"textures\tx_test_firealpha00.dds", 0x2C16_0629, 0x0B75_DE6E), (r"textures\tx_w_staff_ebony_03.dds", 0x2C16_3C2A, 0x985D_8063), (r"textures\tx_w_staff_ebony_02.dds", 0x2C16_3C2A, 0x985D_8463), (r"textures\tx_w_staff_ebony_00.dds", 0x2C16_3C2A, 0x985D_8C63), (r"texture...
Rust
0
2000, 0); assert_eq!(cart.get_rom_byte(0x4060), 14); cart.write_rom_addr(0x2000, 20); assert_eq!(cart.get_rom_byte(0x4060), 20); assert_eq!(cart.rom_bank, 20); cart.write_rom_addr(0x4000, 1); cart.write_rom_addr(0x2000, 10); assert_eq!(cart.rom_bank, 42); assert_eq!(cart.get_rom_byte(0x4...
Rust
0
<R: Reason> { pub params: Vec<FunParam<R>>, pub ret: Ty<R>, } walkable!(FunType<R> => [params, ret]); #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum ParamMode { FPnormal, FPinout, } impl From<&oxidized::ast_defs::ParamKind> for ParamMode { fn from(pk: &oxidized::ast_defs::ParamKind) ...
Rust
0
from Zaid.database import cli collection = cli["Zaid"]["rraid"] async def rraid_user(chat): doc = {"_id": "Rraid", "users": [chat]} r = await collection.find_one({"_id": "Rraid"}) if r: await collection.update_one({"_id": "Rraid"}, {"$push": {"users": chat}}) else: await collection.in...
Python
1
import pytest from tic_tac_logic.agents.masks import AbstractMask, MaskRules, MaskKey from tic_tac_logic.constants import X, O, E class TestRemoveNonMatching: def test_remove_non_matching(self) -> None: mask = AbstractMask(match_symbol=X, rule=MaskRules(0, 0, 0, 0)) grid = [[X, O], [E, X]] ...
Python
1
s, max_length, test_samples_per_length) for i in range(len(transitions))] opt_losses = eval_loss_fn(params_list[-1], transitions, stationaries, test_samples, max_length) transformer_ours_losses = eval_loss_fn(transformer_params_list[-1], transitions, stationaries, test_samples, max_length) DoReMi_losses =...
Python
1
from sqlalchemy.orm import subqueryload from api.item_filter.models import FilterGroup, FilterSubGroup from database import DataBaseConnector class ItemFilterService: @staticmethod def get_all_item_filter(): """ item filter 전체 조회 """ try: session = DataBaseConnect...
Python
1
from django import template from django.template.loader import render_to_string from django_celery_results.models import TaskResult from adl.core.models import DispatchChannel from adl.monitoring.constants import NETWORK_DISPATCH_TASK_NAME from adl.monitoring.serializers import TaskResultSerializer register = templat...
Python
1
we see is a projection like `<T as // Anything<'?0>>::AssocType`, and we don't yet know if `?0` will // equal `'b` or not, so we ignore the where-clause. Obviously we // can do better here with a more involved verification step. with_signature(cell, t, |cell, t| require(cell, t)); //~^ ERROR assoc...
Rust
0
name='Tops\'s Technolgies' print(name) msg= "Be a \"strong\"" print(msg,end="\t") name="Tops technol\bogies " print(name,end="\t") name="Tops tech\tnologies" print(name)
Python
1
} else { let write_data = &rest_of_mem[..count]; match self.file_system.write(handle, write_data) { Ok(read_count) => { machine.set_flag(Flag::Carry, false); machine.set_reg_u16(Reg::AX, read_count); } Err(error_code) => { machine.set_flag...
Rust
0
s; they should not be /// present on prototypes, but instead should shadow any prototype /// properties that would match. instance_traits: Vec<Trait<'gc>>, /// The class initializer for this class. /// /// Must be called once prior to any use of this class. class_init: Method<'gc>, ///...
Rust
0
p_pre_link_matrix, dtype=tf.float32) pre_read_weightings = tf.constant(np_pre_read_weightings, dtype=tf.float32) pre_states = (pre_memory, pre_usage_vector, pre_write_weighting, pre_precedence_weighting, pre_link_matrix, pre_read_weightings) memory_unit.zero_state(config[...
Python
1
/// /// A comma separated list of `plugin_name=num_samples` pairs to explicitly specify how many /// samples to keep per tag for the specified plugin. For unspecified plugins, series are /// randomly downsampled to reasonable values to prevent out-of-memory errors in long-running /// jobs. Each `nu...
Rust
0
467, // "h" 1159, // "é" 65-301 1063, // "Ý" 59-301 490, // "l" 923, // "Í" 49-301 1033, // "Ú" 55-301 603, // "~" 365, // "W" 1195, // "ï" 69-308 803, // "Á" 41-301 893, // "É" 45-301 911, // "Ë" 45-308 414, // "^" 1231, // "ô" 6F-302 ]; /// Use binary sea...
Rust
0
res_explanations[aspect] = load(essay_id, aspect) trait_explanations_str += "Aspect: " + aspect + "\n" + trait_scores_explanations[aspect] + "\n" holistic_formatted = holistic_explanation_prompt.format(scores_and_explanations=trait_explanations_str, score=score, essay=essay, prompt=prompt, ...
Python
1
impl types::Distributor for Distributor { fn handle(&self, from: Hash, msg: Message) -> types::DistributorResult { match msg.payload { MessagePayload::DatabaseStore(_) | MessagePayload::DatabaseLookup(_) | MessagePayload::DatabaseSearchReply(_) => { let f:...
Rust
0
, 'args': self.args }, os.path.join(self.save_dir, self.save_prefix + "_last.pt") ) logger.info( "Finished saving checkpoint to {}".format( os.path.join(self.save_dir, self.save_prefix + "_last.pt") ...
Python
1
()?).await?; println!("Response: {}", resp.status()); while let Some(chunk) = resp.body_mut().data().await { stdout().write_all(&chunk?).await?; } Ok(()) } */ /// Scan private intranet /// /// The private address ranges are defined in IETF RFC 1918 and include: /// /// 10.0.0.0/8 /// 172.16....
Rust
0
#!/usr/bin/env python # -*- coding: utf-8 -*- """Test custom widgets.""" import pytest from PyQt5.QtCore import Qt from PyQt5.QtTest import QTest from PyQt5.QtWidgets import QMainWindow from uwsift.ui.custom_widgets import QAdaptiveDoubleSpinBox from uwsift.ui.pov_main_ui import Ui_MainWindow @pytest.mark.parametriz...
Python
1
a=int(input()) if a%2==0: print("Second player") else: print("First player")
Python
1
import pandas as pd import numpy as np # Read data y_train = pd.read_csv("data/y_train.txt") df = pd.read_csv("data/X_train.txt", delimiter='\t') df['label'] = y_train['label'] # List of error rates to generate error_rates = [0.05, 0.10, 0.15, 0.20, 0.25] for percentage_to_change in error_rates: df_copy = df.cop...
Python
1
/// 2. use cursor to optimize the end of pages speed /// /// pub fn handle_big_table_query<T: QueryFragment<Pg>>(this: &PgBigTablePaginated<T>, mut out: AstPass<Pg>)-> QueryResult<()>{ // https://www.sqlstyle.guide/ let select_str = format!("SELECT *, count_estimate('select * from {}') FROM ", this.table_name...
Rust
0
import json from webtest import TestApp import pecan from pecan.middleware.errordocument import ErrorDocumentMiddleware from pecan.middleware.recursive import RecursiveMiddleware from pecan.tests import PecanTestCase def four_oh_four_app(environ, start_response): if environ['PATH_INFO'].startswith('/error'): ...
Python
1
from Winton.types import Command Tasks: list[Command] = [ {"name": "ls", "description": "List files in current directory", "usage": "ls"}, {"name": "whoami", "description": "Get current user", "usage": "whoami"}, {"name": "cat", "description": "Read file", "usage": "cat <path_to_file>"}, {"name": "pwd"...
Python
1
ust types instead. #[deprecated(since = "0.2.55", note = "Use i8 instead.")] pub type int8_t = i8; #[deprecated(since = "0.2.55", note = "Use i16 instead.")] pub type int16_t = i16; #[deprecated(since = "0.2.55", note = "Use i32 instead.")] pub type int32_t = i32; #[deprecated(since = "0.2.55", note = "Use i64 instead...
Rust
0
from django import forms from .models import Resume class ResumeForm(forms.ModelForm): class Meta: model = Resume fields = ['fullName', 'Email', 'contactNo', 'address', 'summary'] widgets = { 'summary': forms.Textarea(attrs={'rows': 4}), 'address': forms.Textarea(att...
Python
1
(1 minute), 60 (1 hour), 1440 (1 day). Raises: errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True. httpx.TimeoutException: If the request takes longer than Client.timeout. Returns: ModelGetMarketCandlest...
Python
1
ing populations that have the same mean.""" raise NotImplementedError() @unimplemented def VAR(value1, value2): """Calculates the variance based on a sample.""" raise NotImplementedError() @unimplemented def VARA(value1, value2): """Calculates an estimate of variance based on a sample, setting text to the val...
Python
1
} #[test] fn if_match_optional_end_comma() { let x = 42; if_match! { x != 0 => println!("ok") } if_match! { x != 0 => println!("ok"), else => print!("0") } if_match! { x & 1 == 0 => println!("it is even"), x & 1 == 1 => println!("it is odd"), ...
Rust
0
_path.resolve()), 'files': [] } save_json(STATE_FILE, state) except Exception as e: log_error(f"Error creating album: {e}", exc_info=True) continue # Process files in folder for file in folde...
Python
1
import logging LOGGER = logging.getLogger(__name__) def setup_logging() -> logging.Logger: """Set up logging configuration.""" logging.basicConfig( format="%(asctime)s [%(levelname)s] - <%(name)s> - %(message)s", level=logging.INFO, handlers=[logging.StreamHandler()], ) def load...
Python
1
"""[DEPRECATED] Zapier Toolkit.""" from typing import List from langchain_core._api import warn_deprecated from langchain_core.tools import BaseToolkit from langchain_community.tools import BaseTool from langchain_community.tools.zapier.tool import ZapierNLARunAction from langchain_community.utilities.zapier import Z...
Python
1
class Solution: def countPairs(self, nums: List[int], k: int) -> int: count, d = 0, defaultdict(list) for i, n in enumerate(nums): d[n].append(i) for indices in d.values(): for i, a in enumerate(indices): for b in indices[:i]: if a*...
Python
1
: &mut Bencher) { bench_good_thomas_setup(b, 256, 243); } #[bench] fn good_thomas_setup_2048_3(b: &mut Bencher) { bench_good_thomas_setup(b, 2048, 3); } #[bench] fn good_thomas_setup_2048_2187(b: &mut Bencher) { bench_good_thomas_setup(b, 2048, 2187); } /// Times just the FFT execution (not allocation and ...
Rust
0
ent, pedersen::PedersenCommitment, random_generators, }; use ark_inner_products::{ ExtensionFieldElement, InnerProduct, MultiexponentiationInnerProduct, PairingInnerProduct, ScalarInnerProduct, }; type GC1 = AFGHOCommitmentG1<Bls12_381>; type GC2 = AFGHOCommitmentG2<...
Rust
0
.classes[highest_vote].label); Ok(()) } SVMType::ESvr | SVMType::NuSvr => { self.compute_kernel_values(problem); self.compute_regression_values(problem); Ok(()) } } } } impl<'a, 'b> TryFrom<&'a str> for Spa...
Rust
0
BadProof.into(); } } else { log::error!( target: "pallet::ocw::validate_unsigned - submit_offchain_pre_check_result", "⛔️ Could not find the pre-check task!" ); return InvalidTransaction::BadProof.into(); } // let signature_valid = SignedPayload::<T>::verify::<T::Offchain...
Rust
0
2.start_address().unchecked_add(ram2.size()) ); assert!(space.address_in_memory(GuestAddress(0), 0)); assert_eq!(space.address_in_memory(GuestAddress(1000), 0), false); assert_eq!(space.address_in_memory(GuestAddress(1500), 0), false); assert!(space.address_in_memory(GuestAddress...
Rust
0
_int(&mut self, n: i64) { let u: u64; if n < 0 { u = (!(n as u64) << 1) | 1; } else { u = (n as u64) << 1; } self.write_uint(u); } #[inline] pub fn write_float(&mut self, n: f64) { let bits = n.to_bits(); self.write_uint(bits.s...
Rust
0
from quadrant_processor import GoProQuadrantProcessor import os def main(): processor = GoProQuadrantProcessor() # Load the calibration if not processor.load_calibration(): print("\nNo camera calibration found.") response = input("Do you want to calibrate now? (y/n): ").lower() ...
Python
1
====================================== # Buggy Struct #======================================================================= # This bug it intermtittent! The challenge here is two interconnected # models have compatible ports in terms of bitwidth, but different # specific message types (one is Bits, the other BitStr...
Python
1
ls/rustls/issues/479>. pub fn new(roots: RootCertStore, ct_policy: Option<CertificateTransparencyPolicy>) -> Self { Self { roots, ct_policy } } /// Returns the signature verification methods supported by /// webpki. pub fn verification_schemes() -> Vec<SignatureScheme> { vec![ ...
Rust
0
# Copyright (C) 2014-Today Akretion (http://www.akretion.com). # @author Sébastien BEAU <sebastien.beau@akretion.com> # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). import time import simplejson from flask import jsonify, render_template, request from pywebdriver import app, config, drivers f...
Python
1
获取 `body_size`,但不影响 `body_ptr` 的获取 /// @warning 请勿修改其存储的请求体内容,您可以调用 `qiniu_ng_http_request_set_body()` 设置内容 #[no_mangle] pub extern "C" fn qiniu_ng_http_request_get_body( request: qiniu_ng_http_request_t, body_ptr: *mut *const c_void, body_size: *mut size_t, ) { let request: &Request = request.into(); ...
Rust
0
experiment = ExperimentData( experiment_id="excellent_test", experiment_dir=excellent_experiment_dir, config=OmegaConf.create({"learning_rate": 0.001}), metrics={ "final_metrics": { "iou": 0.88, "dice": 0.92, ...
Python
1
, ) def forward(self, x): inter = self.E_pre(x) fea = self.E(inter).squeeze(-1).squeeze(-1) out = self.mlp(fea) return fea, out, inter class CBDE(nn.Module): def __init__(self, opt): super(CBDE, self).__init__() dim = 256 # Encoder se...
Python
1
from mistralrs import Runner, Which, ChatCompletionRequest, Architecture from json import dumps runner = Runner( which=Which.Plain( model_id="microsoft/Phi-3.5-mini-instruct", ), num_device_layers=["500"], ) # @myobj will reference the JSON schema defined below (see grammars = [ ... ]) top_lark = ...
Python
1
"""Initial migration Revision ID: a73d628f3945 Revises: Create Date: 2025-03-14 11:05:37.953344 """ from typing import Sequence, Union from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision: str = 'a73d628f3945' down_revision: Union[str, None] = None branch_labels: Union[...
Python
1