/*
 * Copyright 2024, Cypress Semiconductor Corporation (an Infineon company)
 * SPDX-License-Identifier: Apache-2.0
 *
 * 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 writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "whd_debug.h"
#include "whd_int.h"
#include "bus_protocols/whd_bus_protocol_interface.h"

/******************************************************
*             Constants
******************************************************/

/******************************************************
*             Structures
******************************************************/

/******************************************************
*             Variables
******************************************************/

/******************************************************
*             Function definitions
******************************************************/
void whd_init_stats(whd_driver_t whd_driver)
{
    memset(&whd_driver->whd_stats, 0, sizeof(whd_driver->whd_stats) );
}

whd_result_t whd_print_stats(whd_driver_t whd_driver, whd_bool_t reset_after_print)
{
    CHECK_DRIVER_NULL(whd_driver);

    WPRINT_MACRO( ("WHD Stats.. \n"
                   "tx_total:%" PRIu32 ", rx_total:%" PRIu32 ", tx_no_mem:%" PRIu32 ", rx_no_mem:%" PRIu32 "\n"
                   "tx_fail:%" PRIu32 ", no_credit:%" PRIu32 ", flow_control:%" PRIu32 "\n",
                   whd_driver->whd_stats.tx_total, whd_driver->whd_stats.rx_total,
                   whd_driver->whd_stats.tx_no_mem, whd_driver->whd_stats.rx_no_mem,
                   whd_driver->whd_stats.tx_fail, whd_driver->whd_stats.no_credit,
                   whd_driver->whd_stats.flow_control) );

    if (reset_after_print == WHD_TRUE)
    {
        memset(&whd_driver->whd_stats, 0, sizeof(whd_driver->whd_stats) );
    }

    CHECK_RETURN(whd_bus_print_stats(whd_driver, reset_after_print) );
    return WHD_SUCCESS;
}


"base": #fff
);

$clr-white: map-get($clr-white-list, "base");

//
// List for all Colors for looping
//

$clr-list-all: (
  "red":         $clr-red-list,
  "pink":        $clr-pink-list,
  "purple":      $clr-purple-list,
  "deep-purple": $clr-deep-purple-list,
  "indigo":      $clr-indigo-list,
  "blue":        $clr-blue-list,
  "light-blue":  $clr-light-blue-list,
  "cyan":        $clr-cyan-list,
  "teal":        $clr-teal-list,
  "green":       $clr-green-list,
  "light-green": $clr-light-green-list,
  "lime":        $clr-lime-list,
  "yellow":      $clr-yellow-list,
  "amber":       $clr-amber-list,
  "orange":      $clr-orange-list,
  "deep-orange": $clr-deep-orange-list,
  "brown":       $clr-brown-list,
  "grey":        $clr-grey-list,
  "blue-grey":   $clr-blue-grey-list,
  "black":       $clr-black-list,
  "white":       $clr-white-list
);

//
// Typography
//

$clr-ui-display-4: $clr-grey-600;
$clr-ui-display-3: $clr-grey-600;
$clr-ui-display-2: $clr-grey-600;
$clr-ui-display-1: $clr-grey-600;
$clr-ui-headline:  $clr-grey-900;
$clr-ui-title:     $clr-grey-900;
$clr-ui-subhead-1: $clr-grey-900;
$clr-ui-body-2:    $clr-grey-900;
$clr-ui-body-1:    $clr-grey-900;
$clr-ui-caption:   $clr-grey-600;
$clr-ui-menu:      $clr-grey-900;
$clr-ui-button:    $clr-grey-900;

@mixin material-color-class($name, $property: color, $prefix: "") {
  // If you want to do just one particular color
  @if $name != "all" {
    $list: map-get($clr-list-all, $name);
    @each $clr, $var in $list {
      @if $clr == "base" {
        .#{unquote($prefix)}#{$name} {
          #{$property}: $var !important;
        }
      }
      @else {
        .#{unquote($prefix)}#{$name}-#{$clr} {
          #{$property}: $var !important;
        }
      }
    }
  }

  //If you wanted to do all the colors
  @else {
    @each $clrl, $varl in $clr-list-all {
      @each $clr, $var in $varl {
        @if $clr == "base" {
          .#{unquote($prefix)}#{$clrl} {
            #{$property}: $var !important;
          }
        }
        @else {
          .#{unquote($prefix)}#{$clrl}-#{$clr} {
            #{$property}: $var !important;


*/	bgt lbl_803C1070
/* 803C1050 003BDE50  38 C6 FF FC */	addi r6, r6, -4
/* 803C1054 003BDE54  38 67 01 E8 */	addi r3, r7, 0x1e8
/* 803C1058 003BDE58  7C C4 32 14 */	add r6, r4, r6
/* 803C105C 003BDE5C  7C 06 18 40 */	cmplw r6, r3
/* 803C1060 003BDE60  41 80 00 10 */	blt lbl_803C1070
/* 803C1064 003BDE64  3C 60 80 50 */	lis r3, gTRKRestoreFlags@ha
/* 803C1068 003BDE68  38 C0 00 01 */	li r6, 1
/* 803C106C 003BDE6C  98 C3 92 58 */	stb r6, gTRKRestoreFlags@l(r3)
lbl_803C1070:
/* 803C1070 003BDE70  3C 60 80 57 */	lis r3, lbl_8056B908@ha
/* 803C1074 003BDE74  38 63 B9 08 */	addi r3, r3, lbl_8056B908@l
/* 803C1078 003BDE78  38 C3 02 78 */	addi r6, r3, 0x278
/* 803C107C 003BDE7C  7C 04 30 40 */	cmplw r4, r6
/* 803C1080 003BDE80  41 81 00 28 */	bgt lbl_803C10A8
/* 803C1084 003BDE84  54 03 10 3A */	slwi r3, r0, 2
/* 803C1088 003BDE88  38 63 FF FC */	addi r3, r3, -4
/* 803C108C 003BDE8C  7C 64 1A 14 */	add r3, r4, r3
/* 803C1090 003BDE90  7C 03 30 40 */	cmplw r3, r6
/* 803C1094 003BDE94  41 80 00 14 */	blt lbl_803C10A8
/* 803C1098 003BDE98  3C 60 80 50 */	lis r3, gTRKRestoreFlags@ha
/* 803C109C 003BDE9C  38 C0 00 01 */	li r6, 1
/* 803C10A0 003BDEA0  38 63 92 58 */	addi r3, r3, gTRKRestoreFlags@l
/* 803C10A4 003BDEA4  98 C3 00 01 */	stb r6, 1(r3)
lbl_803C10A8:
/* 803C10A8 003BDEA8  7C A3 2B 78 */	mr r3, r5
/* 803C10AC 003BDEAC  7C 05 03 78 */	mr r5, r0
/* 803C10B0 003BDEB0  4B FF CA 7D */	bl TRKReadBuffer_ui32
lbl_803C10B4:
/* 803C10B4 003BDEB4  88 1F 00 0D */	lbz r0, 0xd(r31)
/* 803C10B8 003BDEB8  28 00 00 00 */	cmplwi r0, 0
/* 803C10BC 003BDEBC  41 82 00 10 */	beq lbl_803C10CC
/* 803C10C0 003BDEC0  38 00 00 00 */	li r0, 0
/* 803C10C4 003BDEC4  38 60 07 02 */	li r3, 0x702
/* 803C10C8 003BDEC8  90 1E 00 00 */	stw r0, 0(r30)
lbl_803C10CC:
/* 803C10CC 003BDECC  3


, $Res Function(_InfoSystem) _then) = __$InfoSystemCopyWithImpl;
@override @useResult
$Res call({
 int uptime, double ramUsage, double cpuUsage
});

}
/// @nodoc
class __$InfoSystemCopyWithImpl<$Res>
    implements _$InfoSystemCopyWith<$Res> {
  __$InfoSystemCopyWithImpl(this._self, this._then);

  final _InfoSystem _self;
  final $Res Function(_InfoSystem) _then;

/// Create a copy of InfoSystem
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? uptime = null,Object? ramUsage = null,Object? cpuUsage = null,}) {
  return _then(_InfoSystem(
uptime: null == uptime ? _self.uptime : uptime // ignore: cast_nullable_to_non_nullable
as int,ramUsage: null == ramUsage ? _self.ramUsage : ramUsage // ignore: cast_nullable_to_non_nullable
as double,cpuUsage: null == cpuUsage ? _self.cpuUsage : cpuUsage // ignore: cast_nullable_to_non_nullable
as double,
  ));
}

}

// dart format on
// GENERATED CODE - DO NOT MODIFY BY HAND
// coverage:ignore-file
// ignore_for_file: type=lint
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark

part of 'queries.dart';

// **************************************************************************
// FreezedGenerator
// **************************************************************************

// dart format off
T _$identity<T>(T value) => value;

/// @nodoc
mixin _$Logs {

 List<Log> get logs; int? get cursor; int? get recordsTotal; int? get recordsFiltered;
/// Create a copy of Logs
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$LogsCopyWith<Logs> get copyWith => _$LogsCopyWithImpl<Logs>(this as Logs, _$identity);

  /// Serializes this Logs to a JSON map.
  Map<String, dynamic> toJson();

@override
bool operator ==(Object other) {
  return identical(this, other) || (other.runtimeType == runtimeType&&other is Logs&&const DeepCollectionEquality().equals(other.logs, logs)&&(identical(other.cursor, cursor) || other.cursor == cursor)&&(identical(other.recordsTotal, recordsTotal) || other.recordsTotal == recordsTotal)&&(identical(other.recordsFiltered, recordsFiltered) || other.recordsFiltered == recordsFiltered));
}

@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType,const DeepCollectionEquality().hash(logs),cursor,recordsTotal,recordsFiltered);

@override
String toString() {
  return 'Logs(logs: $logs, cursor: $cursor, recordsTotal: $recordsTotal, recordsFiltered: $recordsFiltered)';
}

}

/// @nodoc
abstract mixin class $LogsCopyWith<$Res>  {
  factory $LogsCopyWith(Logs value, $Res Function(Logs) _then) = _$LogsCopyWithImpl;
@useResult
$Res call({
 List<Log> logs, int? cursor, int? recordsTotal, int? recordsFiltered
});

}
/// @nodoc
class _$LogsCopyWithImpl<$Res>
    implements $LogsCopyWith<$Res> {
  _$LogsCopyWithI


code_block->x1, l_code_block->y1);*/
    /*fprintf(stderr,"\t numbps=%d, numlenbits=%d, len=%d, numnewpasses=%d, real_num_segs=%d, m_current_max_segs=%d\n ",
    l_code_block->numbps, l_code_block->numlenbits, l_code_block->len, l_code_block->numnewpasses, l_code_block->real_num_segs, l_code_block->m_current_max_segs );*/
    l_nb_code_blocks = (*p_precinct)
      .block_size
      .wrapping_div(::std::mem::size_of::<opj_tcd_cblk_dec_t>() as libc::c_ulong as OPJ_UINT32);
    /*fprintf(stderr,"nb_code_blocks =%d\t}\n", l_nb_code_blocks);*/
    cblkno = 0 as libc::c_int as OPJ_UINT32;
    while cblkno < l_nb_code_blocks {
      if !(*l_code_block).segs.is_null() {
        opj_free((*l_code_block).segs as *mut libc::c_void);
        (*l_code_block).segs = 0 as *mut opj_tcd_seg_t
      }
      if !(*l_code_block).chunks.is_null() {
        opj_free((*l_code_block).chunks as *mut libc::c_void);
        (*l_code_block).chunks = 0 as *mut opj_tcd_seg_data_chunk_t
      }
      opj_aligned_free((*l_code_block).decoded_data as *mut libc::c_void);
      (*l_code_block).decoded_data = 0 as *mut OPJ_INT32;
      l_code_block = l_code_block.offset(1);
      cblkno = cblkno.wrapping_add(1)
    }
    opj_free((*p_precinct).cblks.dec as *mut libc::c_void);
    (*p_precinct).cblks.dec = 0 as *mut opj_tcd_cblk_dec_t
  };
}
/* *
 * Deallocates the encoding data of the given precinct.
 */
/* *
 * Deallocates the encoding data of the given precinct.
 */
unsafe extern "C" fn opj_tcd_code_block_enc_deallocate(mut p_precinct: *mut opj_tcd_precinct_t) {
  let mut cblkno: OPJ_UINT32 = 0;
  let mut l_nb_code_blocks: OPJ_UINT32 = 0;
  let mut l_code_block = (*p_precinct).cblks.enc;
  if !l_code_block.is_null() {
    l_nb_code_blocks = (*p_precinct)
      .block_size
      .wrapping_div(::std::mem::size_of::<opj_tcd_cblk_enc_t>() as libc::c_ulong as OPJ_UINT32);
    cblkno = 0 as libc::c_int as OPJ_UINT32;
    while cblkno < l_nb_code_blocks {
      if !(*l_code_block).data.is_null() {
        /* We refer to data - 1 since below we incremented it */
        /* in opj_tcd_code_block_enc_allocate_data() */
        opj_free((*l_code_block).data.offset(-(1 as libc::c_int as isize)) as *mut libc::c_void); /*(/ 8)*/
        (*l_code_block).data = 0 as *mut OPJ_BYTE
      } /* (%8)


using System;

namespace Engine.CompositionOverInheritance.Composition_AFTER
{
    public class MonsterFactory
    {
        public enum MonsterType
        {
            Horse, // BitingKickingMonster
            Orc, // BitingKickingPunchingMonster
            Crocodile, // BitingMonster
            MikeTyson, // BitingPunchingMonster
            Cobra, // BitingSpittingMonster
            Camel, // KickingSpittingMonster
            Kangaroo, // KickingPunchingMonster
            MantisShrimp //PunchingMonster
        }

        public static Monster CreateMonster(MonsterType monsterType)
        {
            Monster monster;

            switch(monsterType)
            {
                case MonsterType.Horse:
                    monster = new Monster(10);
                    monster.AddAttackType(Monster.AttackType.Biting, 5);
                    monster.AddAttackType(Monster.AttackType.Kicking, 5);
                    break;
                case MonsterType.Orc:
                    monster = new Monster(10);
                    monster.AddAttackType(Monster.AttackType.Biting, 5);
                    monster.AddAttackType(Monster.AttackType.Kicking, 5);
                    monster.AddAttackType(Monster.AttackType.Punching, 5);
                    break;
                case MonsterType.Crocodile:
                    monster = new Monster(10);
                    monster.AddAttackType(Monster.AttackTy


  if (diffDays > mindays && mindays < maxdays) {
          currentDiscount = percent;
        }
      });

      const fullPrice = diffDays * price;
      const priceWithDiscount = fullPrice * ((100 - currentDiscount) / 100);

      return {
        name,
        fullPrice,
        fullDistance: diffDays * distance,
        priceWithDiscount,
      };
    });
    return result;
  }
}
//import * as db from './queries';
import { vals, keys, tablekeys } from '../../utils/utils';      //some utils for restructuring data
import * as db from '../../db/dbquery';
import moment = require('moment');

import { Assignment } from './Assignment';

interface DBResult {
    error?: string;
    data?: any;
}

interface Score {
    total?: number;
    actual?: number;
    percent?: number;
}

interface TestCase {
    input: string;
    output: string;
    visible: boolean;
}

class CodeAssignment extends Assignment {

    private language: string;
    private class: string; //class, in this case, refers to name of the class for the program
    private testcases: TestCase[];

    constructor(data?: any){
        super(data);

        if(data) this.load(data)
    }

    public load(data: any): void{

        super.load(data);
        this.language = data.language;
        this.class = data.class;
        this.testcases = data.testcases;
    }

    public async loadFromID(id: number): Promise<void> {

        await super.loadFromID(id);
        await this.loadTestCases();

        //load rest of the data
        let selectquery: string = db.format(`SELECT language, class FROM assignment WHERE id = ?`, [super.getID()]);
        let result: DBResult = await db.dbquery(selectquery);

        if(!result.error){
            this.language = result.data[0].language;
            this.class = result.data[0].class;
        }

    }

    public async loadTestCases(): Promise<void | string> {

        let selectquery: string = db.format(`SELECT input, output, visible FROM testcases WHERE assignment = ?`, [super.getID()]);

        let result: DBResult = await db.dbquery(selectquery);
        if(result.error) return result.error;

        //load results from db into this.testcases
        let i: number;
        for(i = 0; i < result.data.length; i++){
            let input: string = result.data[i].input;
            let output: string = result.data[i].output;
            let visible: boolean = result.data[i].visible ? true : false;

            this.testcases.push({
                input: input,
                output: output,
                visible: visible
            });
        }

    }

    public async saveTestCases(): Promise<void | string>{

        //have to turn array of objects into nested array of obj props (for compatability with SQLstring)
        let i: any;
        let casenest: any = [];
        for(i in this.testcases){
            let curr: any[] = vals(this.testcases[i]);
            curr.push(this.getID());
            casenest.push(curr);
        }

        let query = db.format(`INSERT INTO testcases (input, output, visible, assignment) VALUES ?`,  [casenest]);
        let result: DBResult = await db.dbquery(query);
        if(result.error) return result.error;

    }

    public async save(): Promise<void | any> {

        let errs: any = await super.save();
        if(errs) return errs;

        await this.saveTestCases();

        //save remaining data
        let query


장화",
[30336] = "쇄도의 장갑",
[30337] = "자유연합 판금 투구",
[30338] = "예언자의 망토",
[30339] = "자유연합 암살자의 반지",
[30340] = "별파괴자의 구슬",
[30341] = "살덩이괴물 조련사의 건틀릿",
[30342] = "자유연합 허리보호띠",
[30343] = "호드의 메달",
[30344] = "호드의 메달",
[30345] = "호드의 메달",
[30346] = "호드의 메달",
[30347] = "Alexander's Test Healthstone",
[30348] = "얼라이언스의 메달",
[30349] = "얼라이언스의 메달",
[30350] = "얼라이언스의 메달",
[30351] = "얼라이언스의 메달",
[30352] = "파괴자의 팔보호구",
[30353] = "피망치 투사잡이 술통",
[30354] = "초입자 해체 송신기",
[30355] = "어둠달 덩이줄기 구이",
[30356] = "어둠달 덩이줄기",
[30357] = "치유의 오로노크 줄기열매",
[30358] = "민첩성의 오로노크 줄기열매",
[30359] = "힘의 오로노크 줄기열매",
[30360] = "럴키의 알",
[30361] = "주문 강화의 오로노크 줄기열매",
[30362] = "마력이 주입된 투구",
[30363] = "초공간 보호막 갑옷",
[30364] = "공명의 도끼",
[30365] = "감독관의 인장",
[30366] = "마나폭풍 고리",
[30367] = "몬스터 - Sword2H, Blood Elf B02 (Red Glow)",
[30368] = "대여사제의 끌신",
[30369] = "정화된 지옥 견갑",
[30370] = "구원된 구원자의 건틀릿",
[30371] = "빛의 감시자 요대",
[30372] = "소크레타르의 요대",
[30373] = "황천융화의 견갑",
[30374] = "주문 강화의 경갑",
[30375] = "제압자의 건틀릿",
[30376] = "몬스터 - Mace, Jeweled Club (Purple Flame)",
[30377] = "카르자의 메달",
[30378] = "탈로디엔의 부적",
[30379] = "구원자의 가죽 조끼",
[30380] = "타락한 구원자의


tractAddress,
		flags,
		pollITicker,
	)
	require.NoError(t, err)

	uni.contractAddress = contractAddress

	return uni
}

func TestIntegration_OCRConfigOverrider_EntersHibernation(t *testing.T) {
	g := gomega.NewWithT(t)

	flagsContract := mocks.NewFlags(t)

	ticker := utils.NewPausableTicker(3 * time.Second)
	uni := newConfigOverriderUni(t, &ticker, flagsContract)

	// not hibernating, because one of the flags is lowered
	flagsContract.On("GetFlags", mock.Anything, mock.Anything).
		Run(checkFlagsAddress(t, uni.contractAddress)).
		Return([]bool{false, true}, nil).Once()

	// hibernating
	flagsContract.On("GetFlags", mock.Anything, mock.Anything).
		Run(checkFlagsAddress(t, uni.contractAddress)).
		Return([]bool{true, true}, nil)

	servicetest.Run(t, uni.overrider)

	// not hibernating initially
	require.Nil(t, uni.overrider.ConfigOverride())

	expectedOverride := &ocrtypes.ConfigOverride{AlphaPPB: math.MaxUint64, DeltaC: uni.overrider.DeltaCFromAddress}

	// timeout needs to be longer than the poll interval of 3 seconds
	g.Eventually(func() *ocrtypes.ConfigOverride { return uni.overrider.ConfigOverride() }, 10*time.Second, 450*time.Millisecond).Should(gomega.Equal(expectedOverride))
}

func Test_OCRConfigOverrider(t *testing.T) {
	t.Parallel()

	t.Run("Before first tick returns nil override, later does return a specific override when hibernating", func(t *testing.T) {
		flagsContract := mocks.NewFlags(t)

		ticker := NewFakeTicker()
		uni := newConfigOverriderUni(t, ticker, flagsContract)

		// not hibernating, because one of the flags is lowered
		flagsContract.On("GetFlags", mock.Anything, mock.Anything).
			Run(checkFlagsAddress(t, uni.contractAddress)).
			Return([]bool{false, true}, nil).Once()

		// hibernating
		flagsContract.On("GetFlags", mock.Anything, mock.Anything).
			Run(checkFlagsAddress(t, uni.contractAddress)).
			Return([]bool{true, true}, nil)

		servicetest.Run(t, uni.overrider)

		// not hibernating initially
		require.Nil(t, uni.overrider.ConfigOverride())

		// update state by getting flags
		require.NoError(t, uni.overrider.ExportedUpdateFlagsStatus())

		expectedOverride := &ocrtypes.ConfigOverride{AlphaPPB: math.MaxUint64, DeltaC: uni.overrider.DeltaCFromAddress}
		require.Equal(t, expectedOverride, uni.overrider.ConfigOverride())
	})

	t.Run("Before first tick is hibernating, later exists hibernation", func(t *testing.T) {
		flagsContract := mocks.NewFlags(t)

		ticker := NewFakeTicker()
		uni := newConfigOverriderUni(t, ticker, flagsContract)

		// hibernating
		flagsContract.On("GetFlags", mock.Anything, mock.Anything).
			Run(checkFlagsAddress(t, uni.contractAddress)).
			Return([]bool{true, true}, nil).Once()

		// not hibernating
		flagsContract.On("GetFlags", mock.Anything, mock.Anything).
			Run(checkFlagsAddress(t, uni.contractAddress)).
			Return([]bool{true, false}, nil)

		servicetest.Run(t, uni.


/*
 *    Copyright (c) 2003, Derek Price and Ximbiot <http://ximbiot.com>
 *
 *    You may distribute under the terms of the GNU General Public License
 *    as specified in the README file that comes with the CVS source
 *    distribution.
 *
 * This is a convenience wrapper for some of the functions in lib/sighandle.c.
 */

#include "cvs.h"

/*
 * Register a handler for all signals.
 */
void
signals_register (RETSIGTYPE (*handler)(int))
{
#ifndef DONT_USE_SIGNALS
#ifdef SIGABRT
	(void) SIG_register (SIGABRT, handler);
#endif
#ifdef SIGHUP
	(void) SIG_register (SIGHUP, handler);
#endif
#ifdef SIGINT
	(void) SIG_register (SIGINT, handler);
#endif
#ifdef SIGQUIT
	(void) SIG_register (SIGQUIT, handler);
#endif
#ifdef SIGPIPE
	(void) SIG_register (SIGPIPE, handler);
#endif
#ifdef SIGTERM
	(void) SIG_register (SIGTERM, handler);
#endif
#endif /* !DONT_USE_SIGNALS */
}

/*
 * Register a handler for all signals and exit.
 */
void
cleanup_register (void (*handler) (void))
{
    atexit (handler);

    /* Always calling this function before any other exit handlers guarantees
     * that signals will be blocked by the time the other exit handlers are
     * called.
     *
     * SIG_beginCrSect will be called once for each handler registered via
     * cleanup_register, but there is no unregister routine for atexit() and
     * this seems like minimal overhead.
     *
     * There is no reason to unblock signals again when the exit handlers are
     * done since the program will be exiting anyhow.
     */
    atexit (SIG_beginCrSect);
}


filmweb_df), len(df), df["Ocena"].mean().round(2)],
                               moviescore_df=moviescore_df.to_dict(orient='list'))
<orig>

<vuln>
        with open("index.html") as f:
        	return jinja2.Template(f.read()).render(dane=records_data(df), pie=pie, example=example, radar=radar_chart_data(df), hist=histogram_data(df), gatunki_historia = gatunki_historia, gatunki_ilosc = gatunki_ilosc, gatunki_lata = gatunki_lata, mapa_dane = map_data_df, bubble_dane = bubble_dane, bubble_xy=xy_minmax, top_aktorzy=top_aktorzy, statystyki=[len(filmweb_df), len(df), df["Ocena"].mean().round(2)], moviescore_df=moviescore_df.to_dict(orient='list'))
<vuln>

    return 'BRAK DANYCH FILMÓW'

@app.route('/example', methods=['GET'])
def example():
    json_text = open(JSON_GET, "r",encoding="utf-8").read()
    return render_json(json_text, example=True)

@app.route('/render', methods=['GET', 'POST'])
def render():
    json_text = None
    if app.debug and request.method == 'GET':
        logger.warn(f"DEBUG MODE using file {JSON_GET}")
        json_text = open(JSON_GET, "r",encoding="utf-8").read()

    else:
        if 'dane' in request.form:
            json_text = request.form['dane']
    return render_json(json_text)


   private java.lang.String _nopTenantId;

    public _SimsExtField(){
        // for debug
    }

    protected SimsExtField newInstance(){
       return new SimsExtField();
    }

    @Override
    public SimsExtField cloneInstance() {
        SimsExtField entity = newInstance();
        orm_forEachInitedProp((value, propId) -> {
            entity.onInitProp(propId);
        });
        return entity;
    }

    @Override
    public String orm_entityName() {
      // 如果存在实体模型对象，则以模型对象上的设置为准
      IEntityModel entityModel = orm_entityModel();
      if(entityModel != null)
          return entityModel.getName();
      return "io.nop.app.SimsExtField";
    }

    @Override
    public int orm_propIdBound(){
      IEntityModel entityModel = orm_entityModel();
      if(entityModel != null)
          return entityModel.getPropIdBound();
      return _PROP_ID_BOUND;
    }

    @Override
    public Object orm_id() {

        return buildCompositeId(PK_PROP_NAMES,PK_PROP_IDS);

    }

    @Override
    public boolean orm_isPrimary(int propId) {

            return propId == PROP_ID_entityName || propId == PROP_ID_entityId || propId == PROP_ID_fieldName;

    }

    @Override
    public String orm_propName(int propId) {
        if(propId >= PROP_ID_TO_NAME.length)
            return super.orm_propName(propId);
        String propName = PROP_ID_TO_NAME[propId];
        if(propName == null)
           return super.orm_propName(propId);
        return propName;
    }

    @Override
    public int orm_propId(String propName) {
        Integer propId = PROP_NAME_TO_ID.get(propName);
        if(propId == null)
            return super.orm_propId(propName);
        return propId;
    }

    @Override
    public Object orm_propValue(int propId) {
        switch(propId){

            case PROP_ID_entityName:
               return getEntityName();

            case PROP_ID_entityId:
               return getEntityId();

            case PROP_ID_fieldName:
               return getFieldName();

            case PROP_ID_fieldType:
               return getFieldType();

            case PROP_ID_decimalScale:
               return getDecimalScale();

            case PROP_ID_decimalValue:
               return getDecimalValue();

            case PROP_ID_dateValue:
               return getDateValue();

            case PROP_ID_timestampValue:
               return getTimestampValue();

            case PROP_ID_stringValue:
               return getStringValue();

            case PROP_ID_nopTenantId:
               return getNopTenantId();

           default:
              return super.orm_propValue(propId);
        }
    }

    @Override
    public void orm_propValue(int propId, Object value){
        switch(propId){

            case PROP_ID_entityName:{
               java.lang.String typedValue = null;
               if(value != null){
                   typedValue = ConvertHelper.toString(value,
                       err-> newTypeConversionError(PROP_NAME_entityName));
               }
               setEntityName(typedValue);
               break;
            }


uctors that steal ownership
  explicit nsAutoRefBase(ThisClass& aRefToSteal)
      : SimpleRef(aRefToSteal.disown()) {}
  explicit nsAutoRefBase(const nsReturningRef<T>& aReturning)
      : SimpleRef(aReturning.mReturnRef.disown()) {}

  ~nsAutoRefBase() { SafeRelease(); }

  // An internal class providing access to protected nsSimpleRef<T>
  // constructors for construction of temporary simple references (that are
  // not ThisClass).
  class LocalSimpleRef : public SimpleRef {
   public:
    LocalSimpleRef() = default;
    explicit LocalSimpleRef(RawRef aRawRef) : SimpleRef(aRawRef) {}
  };

 private:
  ThisClass& operator=(const ThisClass& aSmartRef) = delete;

 public:
  RawRef operator->() const { return this->get(); }

  // Transfer ownership to a raw reference.
  //
  // THE CALLER MUST ENSURE THAT THE REFERENCE IS EXPLICITLY RELEASED.
  //
  // Is this really what you want to use?  Using this removes any guarantee
  // of release.  Use nsAutoRef<T>::out() for return values, or an
  // nsAutoRef<T> modifiable lvalue for an out parameter.  Use disown() when
  // the reference must be stored in a POD type object, such as may be
  // preferred for a namespace-scope object with static storage duration,
  // for example.
  RawRef disown() {
    RawRef temp = this->get();
    LocalSimpleRef empty;
    SimpleRef::operator=(empty);
    return temp;
  }

 protected:
  // steal and own are protected because they make no sense on nsReturnRef,
  // but steal is implemented on this class for access to aOtherRef.disown()
  // when aOtherRef is an nsReturnRef;

  // Transfer ownership from another smart reference.
  void steal(ThisClass& aOtherRef) { own(aOtherRef.disown()); }
  // Assume ownership of a raw ref.
  void own(RawRefOnly aRefToRelease) {
    SafeRelease();
    LocalSimpleRef ref(aRefToRelease);
    SimpleRef::operator=(ref);
  }

  // Release a resource if there is one.
  void SafeRelease() {
    if (this->HaveResource()) {
      this->Release(this->get());
    }
  }
};

#endif  // !defined(nsAutoRef_h_)


,
            ['stone'] = { frequency = 0, size = 0.5, richness = 0.5 },
            ['copper-ore'] = { frequency = 0, size = 0.5, richness = 0.5 },
            ['iron-ore'] = { frequency = 0, size = 0.5, richness = 0.5 },
            ['uranium-ore'] = { frequency = 0, size = 1, richness = 1 },
            ['crude-oil'] = { frequency = 0, size = 1, richness = 1 },
            ['trees'] = { frequency = math.random(10, 50) * 0.1, size = math.random(5, 15) * 0.1, richness = math.random(1, 10) * 0.1 },
            ['enemy-base'] = { frequency = 2, size = 2, richness = 1 }
        }
        map_gen_settings.autoplace_controls[quarter].frequency = 16

        if quarter == 'coal' then
            map_gen_settings.autoplace_controls['crude-oil'].frequency = 8
        end
        if quarter == 'stone' then
            map_gen_settings.autoplace_controls['uranium-ore'].frequency = 8
        end

        game.create_surface(quarter, map_gen_settings)
    end

    --[[
	game.map_settings.enemy_expansion.enabled = true
	game.map_settings.enemy_expansion.settler_group_min_size = 8
	game.map_settings.enemy_expansion.settler_group_max_size = 16
	game.map_settings.enemy_expansion.min_expansion_cooldown = 2700
	game.map_settings.enemy_expansion.max_expansion_cooldown = 2700

	game.map_settings.pollution.enabled = true
	game.map_settings.enemy_evolution.enabled = true

	local modifier_factor = 2

	--default game setting values
	storage.enemy_evolution_destroy_factor = game.map_settings.enemy_evolution.destroy_factor * modifier_factor
	storage.enemy_evolution_time_factor = game.map_settings.enemy_evolution.time_factor * modifier_factor
	storage.enemy_evolution_pollution_factor = game.map_settings.enemy_evolution.pollution_factor * modifier_factor
	]]
end

local event = require 'utils.event'
--event.on_nth_tick(60, tick)
event.on_init(on_init)
event.add(defines.events.on_chunk_generated, on_chunk_generated)
--event.add(defines.events.on_entity_died, on_entity_died)
--event.add(defines.events.on_research_finished, on_research_finished)
event.add(defines.events.on_player_joined_game, on_player_joined_game)
event.add(defines.events.on_player_left_game, on_player_left_game)

--require "modules.difficulty_vote"


points=',{"x":'+utils.RandomInt(300,800)+',"y":300},{"x":'+utils.RandomInt(300,800)+',"y":300},{"x":'+utils.RandomInt(300,800)+',"y":300},{"x":'+utils.RandomInt(300,800)+',"y":300}';
}

var response='{"message":{"bombs":[{"id":'+cfish+',"uid":'+cfish+',"pos":5,"points":[{"x":'+utils.RandomInt(300,800)+',"y":300}'+points+'],"born_time":'+(curTime.getTime())+',"dead_time":'+(curTime.getTime()+eTime)+',"use_rate":1,"rate":1,"brate":1,"fish_id":'+cfish+',"bomb_cnt":1,"num":1,"flag":1,"type":'+curSpecId+',"del_time":'+(curTime.getTime()+eTime)+',"ext":0,"cond_rate":1,"shot_time":'+shotTime+',"class_id":'+curSpecId+',"tons_list":[]}]},"succ":true,"errinfo":"ok","type":"increasebombs"}';

emitter.emit('outcomingMessage',response,true);

break;

}

};

/*-----------bomb hit--------------*/
 this.BombHit = async function(dat)
{

var curTime  = new Date();

var fullscreenFishes=[];

for(var cf in _self.sceneFishes){

if(curTime.getTime()-_self.sceneFishes[cf].fishTime>=30000){

delete _self.sceneFishes[cf];

}else{

fullscreenFishes.push(_self.sceneFishes[cf].curFishUID);

}

}

var bet=_self.gameData.CurrentBet/100;
var totalWin=0;

_self.bet=bet;

/*--------------*/
if(sys.conn.connection._closing){
await sys.CreateConnection();
}
/*-------------*/
await sys.StartTransaction();
var startBalance=await sys.GetBalanceB();

bet=parseFloat(bet);
if( bet<0.0001 || !Number.isFinite(bet) ){
emitter.emit('Error','Invalid balance or bet');
sys.Rollback();
return;
}

if(sys.address>0 && sys.count_balance<=0){
sys.shopPercent=100;
}else if(sys.count_balance<=0){
sys.shopPercent=100;
}

/*-----------------------------*/
var winsArr=[];
var winsArr2=[];
var freeInfo='';
/*-----------------------------*/

var targetFishes=dat.message.fishids;
var gameBank=await sys.GetBank(true);

/*full bomb*/

var fishDmgValue=400;

var isBomb=false;
var isBombId=0;

if(targetFishes.length<=0){

targetFishes=fullscreenFishes;

}

for(var fi=0; fi<targetFishes.length; fi++){

var cfish=targetFishes[fi];

if(_self.sceneFishes['fish_'+cfish]!=undefined){

_self.sceneFishes['fish_'+cfish].fishHealth-=fishDmgValue;

var  tmpWin=_self.sceneFishes['fish_'+cfish].fishPay*bet;

/*-----------------------------*/

if(_self.sceneFishes['fish_'+cfish].fishHealth<=0 && (tmpWin+totalWin)<=gameBank){

totalWin+=tmpWin;

winsArr.push('{"uid":'+cfish+',"score":'+(Math.round(tmpWin*100))+',"rate":'+_self.sceneFishes['fish_'+cfish].fishPay+',"ext":0,"fish_id":0}


ivotModel.setGroupSize(unpivotModel.getColumnsToRows().length);
							// 替换掉分组符号
							String[] colsToRows = unpivotModel.getColumnsToRows();
							for (int t = 0; t < unpivotModel.getGroupSize(); t++) {
								colsToRows[t] = colsToRows[t].replace("{", "").replace("}", "").trim();
							}
							unpivotModel.setColumnsToRows(colsToRows);
						}
						resultProcessor.add(unpivotModel);
					}
				}
				// 汇总合计
				else if (eltName.equals(local.concat("summary"))) {
					SummaryModel summaryModel = new SummaryModel();
					// 是否逆向汇总
					if (elt.hasAttribute("reverse")) {
						summaryModel.setReverse(Boolean.parseBoolean(elt.getAttribute("reverse")));
					}
					// 是否已经完成数据分组组织(默认为true)
					if (elt.hasAttribute("has-grouped")) {
						summaryModel.setHasGrouped(Boolean.parseBoolean(elt.getAttribute("has-grouped")));
					}
					// 汇总合计涉及的列
					if (elt.hasAttribute("sum-columns")) {
						summaryModel.setSumColumns(elt.getAttribute("sum-columns").toLowerCase());
					} else if (elt.hasAttribute("columns")) {
						summaryModel.setSumColumns(elt.getAttribute("columns").toLowerCase());
					}
					// 计算平均值的列
					if (elt.hasAttribute("average-columns")) {
						summaryModel.setAveColumns(elt.getAttribute("average-columns").toLowerCase());
					}
					// 保留小数点位数(2022-2-23 扩展成数组，便于给不同平均值列设置不同的小数位)
					if (elt.hasAttribute("average-radix-sizes")) {
						summaryModel
								.setRadixSize(trimParamsToInt(elt.getAttribute("average-radix-sizes").split("\\,")));
					} else if (elt.hasAttribute("radix-size")) {
						summaryModel.setRadixSize(trimParamsToInt(elt.getAttribute("radix-size").split("\\,")));
					}
					if (elt.hasAttribute("average-rounding-modes")) {
						String[] roundingModeAry = StringUtil
								.trimArray(elt.getAttribute("average-rounding-modes").toUpperCase().split("\\,"));
						RoundingMode[] roudingModes = new RoundingMode[roundingModeAry.length];
						String roundingMode;
						RoundingMode roundMode = null;
						for (int k = 0; k < roundingModeAry.length; k++) {
							roundingMode = roundingModeAry[k];
							if ("HALF_UP".equals(roundingMode)) {
								roundMode = RoundingMode.HALF_UP;
							} else if ("HALF_DOWN".equals(roundingMode)) {
								roundMode = RoundingMode.HALF_DOWN;
							} else if ("ROUND_DOWN".equals(roundingMode)) {
								roundMode = RoundingMode.DOWN;
							} else if ("ROUND_UP".equals(roundingMode)) {
								roundMode = RoundingMode.UP;
							} else {
								roundMode = RoundingMode.HALF_UP;
							}
							roudingModes[k] = roundMode;
						}
						summaryModel.setRoundingModes(roudingModes);
					}
					// 汇总所在位置
					if (elt.hasAttribute("sum-site")) {
						summaryModel.setSumSite(elt.getAttribute("sum-site"));
					}
					// sum和average值左右拼接时的连接字符串
					if (elt.hasAttribute("link-sign")) {
						summaryModel.setLinkSign(elt.getAttribute("link-sign"));
					}
					//


 queries.items():
                result = self.mysql_manager.execute_query(query)
                if key in ['total_files', 'total_size']:
                    stats[key] = result[0][list(result[0].keys())[0]] if result else 0
                else:
                    stats[key] = result

            return stats

        except Exception as e:
            self.logger.error(f"获取文件统计信息失败: {str(e)}")
            return {}

    def cleanup_temp_files(self, max_age_hours: int = 24) -> int:
        """
        清理临时文件

        Args:
            max_age_hours: 最大保留时间（小时）

        Returns:
            int: 清理的文件数量
        """
        try:
            temp_folder = self.file_config['temp_folder']
            if not os.path.exists(temp_folder):
                return 0

            current_time = datetime.now(timezone(timedelta(hours=8)))
            max_age_seconds = max_age_hours * 3600
            cleaned_count = 0

            for filename in os.listdir(temp_folder):
                file_path = os.path.join(temp_folder, filename)
                if os.path.isfile(file_path):
                    file_age = current_time.timestamp() - os.path.getmtime(file_path)
                    if file_age > max_age_seconds:
                        os.remove(file_path)
                        cleaned_count += 1
                        self.logger.info(f"清理临时文件: {filename}")

            self.logger.info(f"临时文件清理完成，共清理{cleaned_count}个文件")
            return cleaned_count

        except Exception as e:
            self.logger.error(f"清理临时文件失败: {str(e)}")
            return 0

    def _async_process_file(self, file_id: int, file_path: str) -> None:
        """
        异步处理文件（提取内容、向量化、知识图谱）

        Args:
            file_id: 文件ID
            file_path: 文件路径
        """
        try:
            # 导入处理服务
            from app.service.pdf.PdfExtractService import PdfExtractService
            from app.service.pdf.PdfFormatElementsToJson import PdfFormatElementsToJson
            from app.service.pdf.PdfVectorService import PdfVectorService
            from app.service.pdf.PdfOpenSearchService import PdfOpenSearchService
            from app.service.pdf.PdfGraphService import PdfGraphService
            from app.service.pdf.PdfMysqlService import PdfMysqlService

            pdf_extract_service = PdfExtractService()
            pdf_format_service = PdfFormatElementsToJson()
            pdf_vector_service = PdfVectorService()
            pdf_opensearch_service = PdfOpenSearchService()
            pdf_graph_service = PdfGraphService()
            pdf_mysql_service = PdfMysqlService()

            self.logger.info(f"开始异步处理文件，ID: {file_id}")

            # 步骤1：内容提取 (10% -> 25%)
            self.update_file_status(file_id, 'extracting')
            elements = pdf_extract_service.extract_pdf_content(file_path, file_id)

            if elements is None:
                self.update_file_status(file_id, 'extract_failed')
                self.logger.error(f"文件内容提取失败，ID: {file_id}")
                return

            # 步骤1.1：格式化elements (25% -> 35%)
            format_result = pdf_format_service.format_elements_to_json(elements, file_id, file_path)

            if not format_result['success']:
                self.update_file_status(file_id, 'extract_failed')
                self.logger.error(f"元素格式化失败，ID: {file_id}, 错误: {format_result['message']}")
                return

            json_data = format_result['json_data']
            self.logger.info(f"元素格式化完成，ID: {file_id}")

            # 步骤1.2：保存JSON文件 (35% -> 40%)
            json_file_path = self._save_json_data(json_data, file_path, file_id)

            if not json_file_path:
                self.update_file_status(file_id, 'extract_failed')
                self.logger.error(f"保存JSON文件失败，ID: {file_id}")
                return

            self.update_file_status(file_id, 'extracted')
            self.logger.info(f"JSON文件保存完成，ID: {file_id}, 路径: {json_file_path}")

            # 步骤2：向量化 (40% -> 60%)
            self.update_file_status(file_id, 'vectorizing')
            vector_result = pdf_vector_service.process_pdf_json_to_vectors(json_data, file_id)

            if not vector_result['success']:
                self.update_file_status(file_id, 'vectorize_fail


       System.out.println("BSS途中離し判定 - Time : " + ptime + " Judge : " + j + " LN : " + processing[lane]);
                                sckey[sc] = 0;
                            }
                        }
                        if (release) {
                            if(judge >= 3 && dmtime > 0) {
                                state.releasetime = mtime;
                                state.lnendJudge = judge;
                            } else {
                                this.updateMicro(state, state.processing, mtime, judge, dmtime, true);
                                keysound.play(state.processing, getKeyVolume(), 0);
                                state.processing = null;
                                state.releasetime = Long.MIN_VALUE;
                                state.lnendJudge = Integer.MIN_VALUE;
                            }
                        }
                    } else {
                        boolean release = true;
                        if (sc >= 0) {
                            if (key != sckey[sc]) {
                                release = false;
                            } else {
//                               System.out.println("BSS途中離し判定 - Time : " + ptime + " Judge : " + j + " LN : " + processing[lane]);
                                sckey[sc] = 0;
                            }
                        }
                        if (release) {
                            // LN離し処理
                            judge = Math.max(judge, state.lnstartJudge);
                            if (Math.abs(state.lnstartDuration) > Math.abs(dmtime)) {
                                dmtime = state.lnstartDuration;
                            }
                            if(judge >= 3 && dmtime > 0) {
                                state.releasetime = mtime;
                                state.lnendJudge = 3;
                            } else {
                                this.updateMicro(state, state.processing.getPair(), mtime, Math.min(judge, 3), dmtime, true);
                                keysound.play(state.processing, getKeyVolume(), 0);
                                state.processing = null;
                                state.releasetime = Long.MIN_VALUE;
                                state.lnendJudge = Integer.MIN_VALUE;
//                              System.out.println("LN途中離し判定 - Time : " + ptime + " Judge : " + j + " LN : " + processing[lane]);
                            }
                        }
                    }
                }
            }
            input.resetKeyChangedTime(key);
        }

        for (LaneState state : states) {
            final long[][] mjudge = state.sckey >= 0 ? smjudge : nmjudge;
            final long releasemargin = state.sckey >= 0 ? sreleasemargin : nreleasemargin;

            // LN終端判定
            if (state.processing != null) {
                if((lntype == BMSModel.LNTYPE_LONGNOTE && state.processing.getType() == LongNote.TYPE_UNDEFINED)
                    || state.processing.getType() == LongNote.TYPE_LONGNOTE) {
                    if(state.releasetime != Long.MIN_VALUE && state.releasetime + releasemargin <= mtime) {
                        keysound.setVolume(state.processing.getPair(), 0.0f);
                        this.updateMicro(state, state.processing.getPair(), mtime, state.lnendJudge, state.processing.getMicroTime() - state.releasetime, true);
                        keysound.play(state.processing, getKeyVolume(), 0);
                        state.processing = null;
                        state.releasetime = Long.MIN_VALUE;
                        state.lnendJudge = Integer.MIN_VALUE;
                    } else if(state.processing.getMicroTime() < mtime) {
                        this.updateMicro(state, state.processing.getPair(), mtime, state.lnstartJudge, state.lnstartDuration, true);
                        keysound.


| 5 | 新增CI/CD、实例创建、日志处理等功能 |

#### 🛠 技术细节

> 使用了OpenAI的API进行LLM调用

> 使用FastAPI构建API接口

> 使用Pydantic进行数据校验

> 模块路由机制，将请求路由到对应的处理模块

> 实现了日志记录功能

#### 🎯 受影响组件

```
• FastAPI
• OpenAI API
• Docker
• AWS ECS
• Mizzle Mate框架
```

#### ⚡ 价值评估

<details>
<summary>展开查看详细评估</summary>

该更新实现了基于LLM的意图识别和模块路由功能，增强了系统的自动化程度和功能多样性，对于DevOps自动化具有积极意义，但由于当前的安全功能比较简单，风险等级较低
</details>

---

### ShadeLoader - Shellcode加载器，绕过杀毒软件

#### 📌 仓库信息

| 属性 | 详情 |
|------|------|
| 仓库名称 | [ShadeLoader](https://github.com/Vasco0x4/ShadeLoader) |
| 风险等级 | `HIGH` |
| 安全类型 | `安全工具` |
| 更新类型 | `功能增强` |

#### 📊 代码统计

- 分析提交数: **5**
- 变更文件数: **3**

#### 💡 分析概述

ShadeLoader是一个shellcode加载器，使用进程空洞和XOR加密技术来下载、解密并将shellcode注入到合法进程中。 该仓库主要功能是绕过杀毒软件。主要更新是README.md文件的修改，增加了关于如何设置加载器的信息，例如config.h文件中的配置选项以及main.cpp文件中的URL和XOR密钥的配置，并提供了debug、反VM和静默模式的示例。仓库还包含了对shellcode的XOR加密的说明。README中包含该加载器与AV的测试结果，以及免责声明。此次更新主要集中在完善文档和提供使用示例。无直接漏洞利用，但是其技术可能被用于恶意用途。

#### 🔍 关键发现

| 序号 | 发现内容 |
|------|----------|
| 1 | 利用进程空洞和XOR加密技术实现shellcode加载 |
| 2 | 提供绕过杀毒软件的能力 |
| 3 | 包含配置说明和使用示例 |
| 4 | 包含反VM和调试模式 |

#### 🛠 技术细节

> 使用进程空洞技术将shellcode注入RuntimeBroker.exe

> 使用XOR加密shellcode进行混淆

> 包含配置选项，例如debug模式，自动销毁，下载前延时以及反VM等

> 包含加密shellcode的Python脚本

#### 🎯 受影响组件

```
• Windows操作系


 the height.**

![](../../doc/build/image3.jpg)

Repeat steps 1-9 for the left and right sides of the keyboard.

### Step 1

Carefully remove *all* the support material from the case top. Test that the acrylic cover fits
flush with the edge of the case.

![](./img/IMG_9088.jpg)

![](./img/IMG_9068.jpg)

![](./img/IMG_9069.jpg)

### Step 2

Insert three m2 nuts in the base of the case. Use a m2 screw to pull the nuts securely into the
base. Remove the screw afterwards.

![](./img/IMG_9070.jpg)

![](./img/IMG_9071.jpg)

![](./img/IMG_9072.jpg)

### Step 3

Cut the car wheel balance weights to fit the case. Secure then with the self-adhesive padding. Be
neat, there is not any spare room!

![](./img/IMG_9073.jpg)

![](./img/IMG_9074.jpg)

### Step 4 (MX switches only)

Assemble the spacer and plate.

![](./img/IMG_9075.jpg)

![](./img/IMG_9076.jpg)

### Step 5

Insert a few switches in the plate, and assemble with the PCB. Make sure everything fits correctly,
and then add the remaining switches. Solder the switches (if you are not using Kailh MX sockets).

**Test that all the switches work before continuing.** You can take apart the case but this is not
easy with the snap fit assembly.

![](./img/IMG_9077.jpg)

![](./img/IMG_9078.jpg)

![](./img/IMG_9079.jpg)

### Step 6

Insert the PCB into the top of the case. Start fitting the back edge as shown below. Make sure the
TRRS socket is in the correct place. Then carefully work around the edge of the case pressing the PCB
in place, ending by the thumb keys. You'll need to gently 'stretch' the top to get the PCB to fit.

![](./img/IMG_9080.jpg)

![](./img/IMG_9081.jpg)

### Step 7

Now insert the base into the top of the case. This is similar to the previous step, start with the
back edge as shown below. Then carefully work around the edge of the case pressing the PCB
in place, ending by the thumb keys. You'll need to gently 'stretch' the top to get the base to fit.

The case should feel secure once it is snapped together.

![](./img/IMG_9082.jpg)

![](./img/IMG_9083.jpg)

### Step 8

Add the acrylic cover. Secure with three m2 screws.

![](./img/IMG_9084.jpg)

### Step 9

Finally add the keycaps.

![](./img/IMG_9085.jpg)
# Powder Hopper Print and Assembly Guide

![powder_hopper_overview.png](resources/powder_hopper_overview.png)

## Print Guide

| Filename                                           | Quantity     | Remarks                                                                                |
| -------------------------------------------------- | ------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [hopper_base.stl](hopper_base.stl)                 | 1            | The design includes large overhang (45 deg). You may need to reduce the print speed to archieve better surface finish.


-.725-.295-.725-.295s.308-.129.58-.129c-.344-.092-.78 0-.98.203-.218.202-.181.92-.272 1.38-.091.48-.4.719-.872 1.161-.254.24-.436.313-.58.313a6.189 6.189 0 01-.927-.24c-.181-.239-.454-1.03-.526-1.362.054-.184.272-.571.38-.792.219-.424.346-.663.382-.884.073-.313.309-2.247.4-3.057.236.313.563.829.49 1.16.527-.755.145-1.491-.036-1.786-.164-.295-.382-.884-.2-1.51.181-.626.835-2.357.835-2.357s.218.387.527.313c.308-.074 2.796-3.867 2.796-3.867zm-4.35 11.584s-.595 1.056-.649 1.202c-.054.164.036.455.27.437.235-.018.523-.364.523-.62 0-.327-.288-.29-.288-.29zm2.316.165c.146-.037.49.018.49.276 0 .24-.254.295-.435.46-.127.13-.382.405-.418.442l.001-.001.052-.095c.091-.206.096-.473.105-.617l.006-.06c.018-.13.054-.369.2-.405zm.853-7.464s-1.845 2.937-2.008 2.993c-.163.055-.325-.588-.325-.588-.344 1.34.579 1.524.687 1.102.507-.129 1.375-.68 1.719-1.065.343-.404.162-1.157-.47-1.285.162-.386.397-1.157.397-1.157zm1.02-3.162-1.198 1.835h.016c.086-.006.482-.063.932-.593.412-.5.25-1.242.25-1.242z"/></svg>';
  static const String i_2give =
      '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="32" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 32 32"><path fill="currentColor" d="M16 32C7.163 32 0 24.837 0 16S7.163 0 16 0s16 7.163 16 16-7.163 16-16 16zm-.737-7.144v1.463H16V24.13h-1.463v.726h.726zm-7.337-8.03H7.2v3.652h.726v-1.463h.737v-1.463h-.737v-.726zm8.811 4.378v2.189h.726v-2.189h-.726zM16 23.393v.737h.737v-.737H16zm-7.337-.726v2.189h2.2v-2.189h-2.2zM7.2 15.363v.726h.737v-.726H7.2zm4.4-1.463v.737h.737V13.9H11.6zm4.4-.737v1.463h.737v-1.463H16zm-9.537-2.189v2.189h2.2v-2.189h-2.2zm6.6 13.882v1.463h.737v-1.463h-.737zm.737-11.693h-.726v1.463h.726V13.9h.737v-


',
  '閶=阊',
  '斷=断',
  '閹=阉',
  '薺=荠',
  '閻=阎',
  '於=于',
  '閼=阏',
  '閽=阍',
  '閾=阈',
  '閿=阌',
  '闃=阒',
  '嗆=呛',
  '嗇=啬',
  '闈=闱',
  '嗊=唝',
  '闊=阔',
  '闋=阕',
  '闌=阑',
  '藍=蓝',
  '闍=阇',
  '嗎=吗',
  '藎=荩',
  '闐=阗',
  '闒=阘',
  '闓=闿',
  '闔=阖',
  '闕=阙',
  '闖=闯',
  '痙=痉',
  '嗚=呜',
  '關=关',
  '藝=艺',
  '闞=阚',
  '闠=阓',
  '闡=阐',
  '闤=阛',
  '藥=药',
  '闥=闼',
  '嗩=唢',
  '藪=薮',
  '嗬=呵',
  '嗶=哔',
  '藶=苈',
  '藹=蔼',
  '藺=蔺',
  '蘀=萚',
  '瘂=痖',
  '蘄=蕲',
  '蘆=芦',
  '蘇=苏',
  '蘊=蕴',
  '瘋=疯',
  '蘋=苹',
  '嘍=喽',
  '瘍=疡',
  '瘓=痪',
  '嘔=呕',
  '嘖=啧',
  '嘗=尝',
  '蘚=藓',
  '嘜=唛',
  '瘞=瘗',
  '蘞=蔹',
  '瘡=疮',
  '蘢=茏',
  '瘧=疟',
  '嘩=哗',
  '阪=坂',
  '蘭=兰',
  '瘮=瘆',
  '嘮=唠',
  '嘯=啸',
  '嘰=叽',
  '嘵=哓',
  '嘸=呒',
  '瘺=瘘',
  '蘺=蓠',
  '嘽=啴',
  '蘿=萝',
  '時=时',
  '療=疗',
  '噅=咴',
  '癆=痨',
  '癇=痫',
  '晉=晋',
  '癉=瘅',
  '噓=嘘',
  '處=处',
  '癘=疠',
  '陘=陉',
  '虛=虚',
  '虜=虏',
  '噝=咝',
  '晝=昼',
  '陝=陕',
  '號=号',
  '癟=瘪',
  '噠=哒',
  '癡=痴',
  '癢=痒',
  '陣=阵',
  '癤=疖',
  '噥=哝',
  '噦=哕',
  '虧=亏',


@staticmethod
    def get_port_name_from_portnum(port_num):
        descriptor = PortNum.DESCRIPTOR
        for enum_value in descriptor.values:
            if enum_value.number == port_num:
                return enum_value.name
        return 'UNKNOWN_PORT'

    def process_simple_packet_details(self, destination_client_details, mesh_packet: MeshPacket, port_num,
                                      source_client_details):
        # Store mesh packet metrics in TimescaleDB
        self.db_handler.store_mesh_packet_metrics(
            source_client_details.node_id,
            destination_client_details.node_id,
            {
                'portnum': self.get_port_name_from_portnum(port_num),
                'packet_id': mesh_packet.id,
                'channel': mesh_packet.channel,
                'rx_time': mesh_packet.rx_time,
                'rx_snr': mesh_packet.rx_snr,
                'rx_rssi': mesh_packet.rx_rssi,
                'hop_limit': mesh_packet.hop_limit,
                'hop_start': mesh_packet.hop_start,
                'want_ack': mesh_packet.want_ack,
                'via_mqtt': mesh_packet.via_mqtt,
                'message_size_bytes': sys.getsizeof(mesh_packet)
            }
        )

    def _get_client_details(self, node_id: int) -> ClientDetails:
        if node_id == 4294967295 or node_id == 1:  # FFFFFFFF or 1 (Broadcast)
            node_id_str = str(node_id)
            # Insert the broadcast node into node_details if it doesn't exist
            with self.db_pool.connection() as conn:
                with conn.cursor() as cur:
                    cur.execute("""
                                INSERT INTO node_details (node_id, short_name, long_name, hardware_model, role)
                                VALUES (%s, %s, %s, %s, %s)
                                ON CONFLICT (node_id) DO NOTHING
                                """, (node_id_str, 'Broadcast', 'Broadcast', 'BROADCAST', 'BROADCAST'))
                    conn.commit()
            return ClientDetails(node_id=node_id_str, short_name='Broadcast', long_name='Broadcast')
        node_id_str = str(node_id)  # Convert the integer to a string
        with self.db_pool.connection() as conn:
            with conn.cursor() as cur:
                # First, try to select the existing record
                cur.execute("""
                    SELECT node_id, short_name, long_name, hardware_model, role
                    FROM node_details
                    WHERE node_id = %s;
                """, (node_id_str,))
                result = cur.fetchone()

                if not result:
                    # If the client is not found, insert a new record
                    cur.execute("""
                        INSERT INTO node_details (node_id, short_name, long_name, hardware_model, role)
                        VALUES (%s, %s, %s, %s, %s)
                        RETURNING node_id, short_name, long_name, hardware_model, role;
                    """, (node_id_str, 'Unknown', 'Unknown', HardwareModel.UNSET, None))
                    conn.commit()
                    result = cur.fetchone()

        # At this point, we should always have a result, either from SELECT or INSERT
        return ClientDetails(
            node_id=result[0],
            short_name=result[1],
            long_name=result[2],
            hardware_model=result[3],
            role=result[4]
        )


|QID|30772|M|67.21,52.27|N|To Ban Bearheart.|
T Ranger Rescue|QID|30774|M|67.21,52.27|N|To Ban Bearheart.|
T Pitching In|QID|30773|M|67.21,52.27|N|To Ban Bearheart.|
A Jung Duk|QID|30776|PRE|30772&30773&30774|M|67.25,52.22|N|From Suna Silentstrike.|
K Jung Duk|QID|30776|QO|1|M|66.61,50.98|N|Plant the banner and fight him.|; Jung Duk slain: 1/1
T Jung Duk|QID|30776|M|70.98,56.56|N|To Ban Bearheart.|
A In Search of Suna|QID|30777|PRE|30776|M|70.98,56.56|N|From Ban Bearheart. Hop on the caravan for a ride to Hatred's Vice.|
R Hatred's Vice|QID|30777|M|70.6,56.6|N|Take the Shado-Pan Caravan|
T In Search of Suna|QID|30777|M|82.68,73.02|N|To Ban Bearheart.|
A Dust to Dust|QID|30778|PRE|30777|M|82.68,73.02|N|From Ban Bearheart.|
A Slaying the Scavengers|QID|30779|PRE|30777|M|82.68,73.02|N|From Ban Bearheart.|
A Last Toll of the Yaungol|QID|30781|PRE|30777|M|82.70,73.16|N|From Xiao Tu.|
A Totemic Research|QID|30780|PRE|30777|M|82.59,73.02|N|From Yalia Sagewhisper.|
C Slaying the Scavengers|QID|30779|S|M|84.07,72.45|
C Totemic Research|QID|30780|S|NC|M|82.52,71.68|N|Pick up the totems scattered around the camp.|
C Dust to Dust|QID|30778|S|NC|U|81356|M|82.63,70.03|N|Use the Shado-Pan Torch to burn the corpses.|
C Examine the Western Smoke Trail|QID|30781|NC|QO|2|M|80.95,72.09|; Western Smoke Trail examined: 1/1
C Examine the Northwestern Smoke Trail|QID|30781|NC|QO|4|M|83.89,70.72|; Northwestern Smoke Trail examined: 1/1
C Examine the Eastern Smoke Trail|QID|30781|NC|QO|1|M|84.79,71.52|; Eastern Smoke Trail examined: 1/1
C Examine the Southern Smoke Trail|QID|30781|NC|QO|3|M|83.64,78.5|; Southern Smoke Trail examined: 1/1
C Dust to Dust|QID|30778|US|NC|U|81356|M|82.63,70.03|N|Use the Shado-Pan Torch to burn the corpses.|
C Totemic Research|QID|30780|US|NC|M|82.52,71.68|N|Pick up the totems scattered around the camp.|
C Slaying the Scavengers|QID|30779|US|M|84.07,72.45|
T Dust to Dust|QID|30778|M|82.68,73.02|N|To Ban Bearheart.|
T Slaying the Scavengers|QID|30779|M|82.68,73.02|N|To Ban Bearheart.|
T Last Toll of the Yaungol|QID|30781|M|82.68,73.02|N|To Ban Bearheart.|
T Totemic Research|QID|30780|M|82.59,73.02|N|To Yalia Sagewhisper.|
A What Lies Beneath|QID|30827|PRE|30778&30779&30780&30781|M|82.59,73.02|N|From Yalia Sagewhisper.|
C What Lies Beneath|Q


#ifndef XPRINT_H
#define XPRINT_H

#define XPRINT_DASH_LINE                                                       \
    "------------------------------------------------------------------------" \
    "--------"
#define XPRINT_EQUAL_LINE                                                      \
    "========================================================================" \
    "========"
#define XPRINT_STAR_LINE                                                       \
    "************************************************************************" \
    "********"
#define XPRINT_SHARP_LINE                                                      \
    "########################################################################" \
    "########"

/*font color*/
#define XPRINT_CH_COLOR_RED     "\033[31m"
#define XPRINT_CH_COLOR_GREEN   "\033[32m"
#define XPRINT_CH_COLOR_YELLOW  "\033[33m"
#define XPRINT_CH_COLOR_BLUE    "\033[34m"
#define XPRINT_CH_COLOR_MAGENTA "\033[35m"
#define XPRINT_CH_COLOR_CYAN    "\033[36m"
/*background color*/
#define XPRINT_BG_COLOR_RED     "\033[41m"
#define XPRINT_BG_COLOR_GREEN   "\033[42m"
#define XPRINT_BG_COLOR_YELLOW  "\033[43m"
#define XPRINT_BG_COLOR_BLUE    "\033[44m"
#define XPRINT_BG_COLOR_MAGENTA "\033[45m"
#define XPRINT_BG_COLOR_CYAN    "\033[46m"
/*controlling*/
#define XPRINT_RESET            "\033[0m"
#define XPRINT_BOLD             "\033[1m"
#define XPRINT_ITALIC           "\033[3m"
#define XPRINT_UNDERLINE        "\033[4m"
#define XPRINT_LINE_UP          "\033[A"
#define XPRINT_LINE_DOWN        "\033[B"
#define XPRINT_COLUMN_RIGHT     "\033[C"
#define XPRINT_COLUMN_LEFT      "\033[D"
#define XPRINT_CLEAR_SCREEN     "\033[2J"
#define XPRINT_CLEAR_LINE       "\033[K" /*clear contents after the cursor*/

/*print documents with an indent*/
void xprint(const char *text, unsigned indent, unsigned count);

/*keep spaces in the head of line*/
void xprint_with_head(const char *text, unsigned indent, unsigned count);

#endif


group_key, p1_secret_key) = p1_state.finish().unwrap();
        let (p2_group_key, p2_secret_key) = p2_state.finish().unwrap();
        let (p3_group_key, p3_secret_key) = p3_state.finish().unwrap();
        let (p4_group_key, p4_secret_key) = p4_state.finish().unwrap();
        let (p5_group_key, p5_secret_key) = p5_state.finish().unwrap();

        assert!(p1_group_key.0.compress() == p2_group_key.0.compress());
        assert!(p2_group_key.0.compress() == p3_group_key.0.compress());
        assert!(p3_group_key.0.compress() == p4_group_key.0.compress());
        assert!(p4_group_key.0.compress() == p5_group_key.0.compress());

        let mut group_secret_key = Scalar::zero();
        let indices = [1, 2, 3, 4, 5];

        group_secret_key += calculate_lagrange_coefficients(&1, &indices).unwrap()*p1_secret_key.key;
        group_secret_key += calculate_lagrange_coefficients(&2, &indices).unwrap()*p2_secret_key.key;
        group_secret_key += calculate_lagrange_coefficients(&3, &indices).unwrap()*p3_secret_key.key;
        group_secret_key += calculate_lagrange_coefficients(&4, &indices).unwrap()*p4_secret_key.key;
        group_secret_key += calculate_lagrange_coefficients(&5, &indices).unwrap()*p5_secret_key.key;

        let group_key = &group_secret_key * &RISTRETTO_BASEPOINT_TABLE;

        assert!(p5_group_key.0.compress() == group_key.compress())
    }

    #[test]
    fn keygen_2_out_of_3() {
        fn do_test() -> Result<(), ()> {
            let params = Parameters { n: 3, t: 2 };
            let mut rng = OsRng;

            let (p1, p1coeffs, p1_dh_sk) = Participant::new_dealer(&params, 1, "Φ", &mut rng);
            let (p2, p2coeffs, p2_dh_sk) = Participant::new_dealer(&params, 2, "Φ", &mut rng);
            let (p3, p3coeffs, p3_dh_sk) = Participant::new_dealer(&params, 3, "Φ", &mut rng);

            p1.proof_of_secret_key.as_ref().unwrap().verify(&p1.index, p1.public_key().unwrap(), "Φ").or(Err(()))?;
            p2.proof_of_secret_key.as_ref().unwrap().verify(&p2.index, p2.public_key().unwrap(), "Φ").or(Err(()))?;
            p3.proof_of_secret_key.as_ref().unwrap().verify(&p3.index, p3.public_key().unwrap(), "Φ").or(Err(()))?;

            let participants: Vec<Participant> = vec!(p1.clone(), p2.clone(), p3.clone());
            let (p1_state, _participant_lists) = DistributedKeyGeneration::<RoundOne>::new_initial(&params,
                                                                     &p1_dh_sk,
                                                                     &p1.index,
                                                                     &p1coeffs,
                                                                     &participants,
                                                                     "Φ",
                                                                     &mut rng).or(Err(()))?;
            let p1_their_encrypted_secret_shares = p1_state.their_encrypted_secret_shares().or(Err(()))?;

            let (p2_state, _participant_lists) = DistributedKeyGeneration::<RoundOne>::new_initial(&params,
                                                                     &p2_dh_sk,
                                                                     &p2.index,


this);
        cube_r14.setRotationPoint(0.0F, -2.0F, 0.0F);
        mp5_mi_handguard.addChild(cube_r14);
        setRotationAngle(cube_r14, -0.8552F, 0.0F, -0.3665F);
        cube_r14.cubeList.add(new ModelBox(cube_r14, 38, 115, -0.9F, -3.68F, 0.35F, 1, 1, 1, -0.102F, false));

        cube_r15 = new ModelRenderer(this);
        cube_r15.setRotationPoint(0.0F, -2.0F, 0.0F);
        mp5_mi_handguard.addChild(cube_r15);
        setRotationAngle(cube_r15, 0.0F, 0.0F, -0.4712F);
        cube_r15.cubeList.add(new ModelBox(cube_r15, 66, 27, -1.0F, -1.75F, 12.0F, 1, 1, 5, -0.001F, false));
        cube_r15.cubeList.add(new ModelBox(cube_r15, 116, 33, -1.0F, -1.0F, 13.0F, 1, 1, 4, 0.0F, false));

        cube_r16 = new ModelRenderer(this);
        cube_r16.setRotationPoint(0.0F, 0.0F, 16.0F);
        mp5_mi_handguard.addChild(cube_r16);
        setRotationAngle(cube_r16, 0.0F, 0.0F, 0.7854F);
        cube_r16.cubeList.add(new ModelBox(cube_r16, 92, 26, -1.0F, 0.0F, -12.6F, 1, 2, 1, -0.003F, false));
        cube_r16.cubeList.add(new ModelBox(cube_r16, 92, 35, -1.0F, 0.0F, -8.5F, 1, 2, 1, -0.003F, false));
        cube_r16.cubeList.add(new ModelBox(cube_r16, 94, 0, -1.0F, 0.0F, -4.5F, 1, 2, 1, -0.003F, false));
        cube_r16.cubeList.add(new ModelBox(cube_r16, 0, 96, -1.0F, 0.0F, -2.0F, 1, 2, 1, -0.003F, false));
        cube_r16.cubeList.add(new ModelBox(cube_r16, 46, 96, -1.0F, 0.0F, 0.0F, 1, 2, 1, -0.001F, false));
        cube_r16.cubeList.add(new ModelBox(cube_r16, 197, 149, -0.8F, 1.2F, -16.5F, 1, 1, 17, -0.202F, false));
        cube_r16.cubeList.add(new ModelBox(cube_r16, 197, 167, -0.8F, -0.2F, -16.5F, 1, 1, 17, -0.202F, false));
        cube_r16.cubeList.add(new ModelBox(cube_r16, 101, 98, -1.0F, 0.0F, -17.0F, 1, 2, 1, -0.001F, false));

        mp5_sd_handguard = new ModelRenderer(this);
        mp5_sd_handguard.setRotationPoint(0.0F, 24.0F, -17.0F);
        mp5_sd_handguard.cubeList.add(new ModelBox(mp5_sd_handguard, 74, 241, -2.0F


process(event.entity)
  }

  async beforeUpdate (event: UpdateEvent<Channel>) {
    if (this.simpleUpdateColumns(event).length > 0) {
      await VideoSubscriber.process(event.entity, event.databaseEntity)
    }
  }

  ///

  protected simpleUpdateColumns (event: UpdateEvent<any>) {
    return event.updatedColumns
      .filter(e => !(e.isObjectId || e.isCreateDate || e.isUpdateDate || e.isDeleteDate))
  }

  public static async process(channel: Channel, dbChannel?: Channel) {
    // 参照渡しなので、値も更新される
    // この event の error は失敗してもスルーする
    try {
      await this.channelAchivement(channel)
    } catch (err) {
      EventLog.error(err)
    }
  }

  ///

  public static async channelAchivement(channel: Channel, dbChannel?: Channel) {
    const fund = 1000 // 通知ベース

    const nowSubsc = channel.subscriberCount
    const notifySubsc = channel.achivementSubscriber || 0 // 通知した登録者数

    // 通知してない数字になったら通知
    if (nowSubsc >= notifySubsc + fund) {
      const over = nowSubsc % fund // 差分を取得
      const achiveSubsc = nowSubsc - over // 通知する登録者数
      EventLog.debug(`> [${channel.channelId}] Achivement subscriber ${notifySubsc} => ${achiveSubsc} (fund: ${fund})`)

      // 今まで通知したことが無かったらしない
      if (notifySubsc > 0) {
        await Tweeter.builder().achiveChannelOfSubscriber(channel, achiveSubsc)
      }

      channel.achivementSubscriber = achiveSubsc
    }

    // あまりにも数字が下がったら achive ラインを下げる
    if (notifySubsc > 0) {
      if (nowSubsc <= notifySubsc - 1000) {
        const over = nowSubsc % fund // 差分を取得
        const achiveSubsc = nowSubsc - over // 通知する登録者数
        EventLog.warn(`> [${channel.channelId}] Achivement subscriber ${notifySubsc} => ${achiveSubsc} (fund: ${fund})`)

        channel.achivementSubscriber = achiveSubsc
      }
    }
  }
}
export const randomInteger = (min: any, max: any) => {
    let rand = min - 0.5 + Math.random() * (max - min + 1);
    return Math.round(rand);
}import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { AdapterError } from './errors'
import { logger } from './logger'
import { getDefaultConfig, logConfig } from './config'

const getFalse = () => false

export class Requester {
  static async request(config: AxiosRequestConfig, customError?: any, retries = 3, delay = 1000) {
    if (typeof config === 'string') config = { url: config }
    if (typeof config.timeout === 'undefined') {
      const timeout = Number(process.env.TIMEOUT)
      config.timeout = !isNaN(timeout) ? timeout : 3000
    }

    if (!customError) customError = getFalse
    if (typeof customError !== 'function') {
      delay = retries
      retries = customError
      customError = getFalse
    }

    const _retry = async (n: number): Promise<AxiosResponse> => {
      const _delayRetry = async (message: string) => {
        logger.warn(message)
        await new Promise((resolve) => setTimeout(resolve, delay))
        return await _retry(n - 1)
      }

      let response
      try {
        response = await axios(config)
      } catch (error) {
        // Request error
        if (n === 1) {
          logger.error(`Could not reach endpoint: ${JSON.stringify(error.message)}`)
          throw new AdapterError({ message: error.message, cause: error })
        }

        return await _delayRetry(`C


eLine("No resource set.");
         return;
      }

      foreach (var number in numbers)
         Console.WriteLine("{0,-10} '{1}'", number + ":", rs.GetString(number));
   }
}

internal class NumberResources {}
// The example displays the following output:
//       one:       'un'
//       two:       'deux'
//       three:     'trois'
//       four:      'quatre'
//       five:      ''
//       six:       ''
//       seven:     ''
//       eight:     ''
//       nine:      ''
//       ten:       ''
// </Snippet1>


)
        {
            return DP.Curve.FromBigInteger(x);
        }

        private ECFieldElement FE(uint[] x)
        {
            return FE(Nat128_ToBigInteger(x));
        }

        private static BigInteger Nat128_ToBigInteger(uint[] x)
        {
            byte[] bs = new byte[16];
            for (int i = 0; i < 4; ++i)
            {
                uint x_i = x[i];
                if (x_i != 0)
                {
                    Pack_UInt32_To_BE(x_i, bs, (3 - i) << 2);
                }
            }
            return new BigInteger(1, bs);
        }

        private static void Pack_UInt32_To_BE(uint n, byte[] bs, int off)
        {
            bs[off] = (byte)(n >> 24);
            bs[off + 1] = (byte)(n >> 16);
            bs[off + 2] = (byte)(n >> 8);
            bs[off + 3] = (byte)(n);
        }
    }
}


 = append(jpl.Tracks, track)
		}
	}
}

// AddSegmentsToMPL adds segments to the MediaPlaylist
func (jpl *JsonPlaylist) AddSegmentsToMPL(manifestIDs []string, trackName string, mpl *m3u8.MediaPlaylist, extURL string) {
	for _, seg := range jpl.Segments[trackName] {
		// make relative URL from absolute one
		uri := seg.URI
		mindex, manifestIDlen := indexOf(uri, manifestIDs)
		if mindex != -1 {
			// If extURL was specified we will put absolute URL to the segment into manifest
			// extURL points to the root of object store, so we should take part of the 'uri'
			// which contains manifestID.
			// If extURL is not specified then we're serving relative URL to the segment,
			// and address at which manifest is served already contains manfiestID
			// (broadcaster.com/recordings/manifestID/index.m3u8), so we're taking
			// part of the 'uri' after the manifestID
			if extURL != "" {
				uri = common.JoinURL(extURL, uri[mindex:])
			} else {
				uri = uri[mindex+manifestIDlen+1:]
			}
		}
		mseg := &m3u8.MediaSegment{
			URI:           uri,
			Duration:      float64(seg.DurationMs) / 1000.0,
			Discontinuity: seg.discontinuity,
		}
		mpl.InsertSegment(seg.SeqNo, mseg)
	}
}

func (jpl *JsonPlaylist) hasTrack(trackName string) bool {
	for _, track := range jpl.Tracks {
		if track.Name == trackName {
			return true
		}
	}
	return false
}

// AddDiscontinuedTrack appends all segments for specified rendition, mark first one as discontinued
func (jpl *JsonPlaylist) AddDiscontinuedTrack(ajpl *JsonPlaylist, trackName string) {
	curSegs := jpl.Segments[trackName]
	var lastSeq uint64
	var disc bool
	if len(curSegs) > 0 {
		lastSeq = curSegs[len(curSegs)-1].SeqNo
		lastSeq++
		disc = true
	}
	for i, seg := range ajpl.Segments[trackName] {
		if i == 0 {
			seg.discontinuity = disc
		}
		seg.SeqNo += lastSeq
		curSegs = append(curSegs, seg)
	}
	jpl.Segments[trackName] = curSegs
}

// AddTrack adds segments data for specified rendition
func (jpl *JsonPlaylist) AddTrack(ajpl *JsonPlaylist, trackName string) {
	curSegs := jpl.Segments[trackName]
	var lastSeq uint64
	if len(curSegs) > 0 {
		lastSeq = curSegs[len(curSegs)-1].SeqNo
	}

	for _, seg := range ajpl.Segments[trackName] {
		needSort := false
		if seg.SeqNo > lastSeq {
			curSegs = append(curSegs, seg)
		} else {
			i := sort.Search(len(curSegs), func(i int) bool {
				return curSegs[i].SeqNo >= seg.SeqNo
			})
			if i < len(curSegs) && curSegs[i].SeqNo == seg.SeqNo {
				// x is present at data[i]
			} else {
				// x is not present in data,
				// but i is the index where it would be inserted.
				if i < len(curSegs) {
					needSort = true
				}
				curSegs = append(curSegs, seg)
			}
		}
		if needSort {
			sort.Slice(curSegs, func(i, j int) bool {
				return curSegs[i].SeqNo < curSegs[j].SeqNo
			})
		}
		lastSeq = curSegs[len(curSegs)-1].SeqNo
	}
	jpl.Segments[trackName] = curSegs
}

func (jpl *JsonPlaylist) InsertHLSSegment(profile *ffmpeg.


0047AD2C  7C 9C 23 78 */	mr r28, r4
/* 8047F7F0 0047AD30  7C BD 2B 78 */	mr r29, r5
/* 8047F7F4 0047AD34  7C DE 33 78 */	mr r30, r6
/* 8047F7F8 0047AD38  7C FF 3B 78 */	mr r31, r7
/* 8047F7FC 0047AD3C  40 82 00 0C */	bne lbl_8047F808
/* 8047F800 0047AD40  38 60 00 0A */	li r3, 0xa
/* 8047F804 0047AD44  48 00 00 A4 */	b lbl_8047F8A8
lbl_8047F808:
/* 8047F808 0047AD48  2C 04 00 00 */	cmpwi r4, 0
/* 8047F80C 0047AD4C  40 82 00 0C */	bne lbl_8047F818
/* 8047F810 0047AD50  38 60 00 0A */	li r3, 0xa
/* 8047F814 0047AD54  48 00 00 94 */	b lbl_8047F8A8
lbl_8047F818:
/* 8047F818 0047AD58  A0 03 18 60 */	lhz r0, 0x1860(r3)
/* 8047F81C 0047AD5C  54 00 07 FF */	clrlwi. r0, r0, 0x1f
/* 8047F820 0047AD60  41 82 00 20 */	beq lbl_8047F840
/* 8047F824 0047AD64  4B FE B9 09 */	bl func_8046B12C
/* 8047F828 0047AD68  2C 03 00 00 */	cmpwi r3, 0
/* 8047F82C 0047AD6C  41 82 00 14 */	beq lbl_8047F840
/* 8047F830 0047AD70  7F 63 DB 78 */	mr r3, r27
/* 8047F834 0047AD74  4B FE B9 51 */	bl func_8046B184
/* 8047F838 0047AD78  2C 03 00 00 */	cmpwi r3, 0
/* 8047F83C 0047AD7C  41 82 00 0C */	beq lbl_8047F848
lbl_8047F840:
/* 8047F840 0047AD80  38 60 00 09 */	li r3, 9
/* 8047F844 0047AD84  48 00 00 64 */	b lbl_8047F8A8
lbl_8047F848:
/* 8047F848 0047AD88  7F 63 DB 78 */	mr r3, r27
/* 8047F84C 0047AD8C  7F A4 EB 78 */	mr r4, r29
/* 8047F850 0047AD90  38 A1 00 08 */	addi r5, r1, 8
/* 8047F854 0047AD94  4B FF 14 0D */	bl func_80470C60
/* 8047F858 0047AD98  2C 03 00 00 */	cmpwi r3, 0
/* 8047F85C 0047AD9C  41 82 00 08 */	beq lbl_8047F864
/* 8047F860 0047ADA0  48 00 00 48 */	b lbl_8047F8A8
lbl_8047F864:
/* 8047F864 0047ADA4  80 61 00 08 */	lwz r3, 8(r1)
/* 8047F868 0047ADA8  7F 84 E3 78 */	mr r4, r28
/* 8047F86C 0047ADAC  7F E5 FB 78 */	mr r5, r31
/* 8047F870 0047ADB0  80 03 00 08 */	lwz r0, 8(r3)
/* 8047F874 0047ADB4  7C 60 F2 14 */	add r3, r0, r30
/* 8047F878 0047AD


/*
 * Copyright (C) Volition, Inc. 1999.  All rights reserved.
 *
 * All source code herein is the property of Volition, Inc. You may not sell
 * or otherwise commercially exploit the source or things you created based on the
 * source.
 *
*/

#ifndef _HUD_ETS_H
#define _HUD_ETS_H

#include "hud/hud.h"

class object;

#define INTIAL_SHIELD_RECHARGE_INDEX	4		// default shield charge rate (index in Energy_levels[])
#define INTIAL_WEAPON_RECHARGE_INDEX	4		// default weapon charge rate (index in Energy_levels[])
#define INTIAL_ENGINE_RECHARGE_INDEX	4		// default engine charge rate (index in Energy_levels[])

#define NUM_ENERGY_LEVELS	13
inline constexpr int MAX_ENERGY_INDEX = (NUM_ENERGY_LEVELS - 1);

#define AI_MODIFY_ETS_INTERVAL 500	// time between ets modifications for ai's (in milliseconds)

#define ZERO_INDEX			0
#define ONE_HALF_INDEX		6
#define ALL_INDEX			12

#define HAS_ENGINES			(1<<0)
#define HAS_SHIELDS			(1<<1)
#define HAS_WEAPONS			(1<<2)

const int num_retail_ets_gauges = 3;

extern float Energy_levels[];
extern bool Weapon_energy_cheat;

enum SYSTEM_TYPE {WEAPONS, SHIELDS, ENGINES};

void update_ets(object* obj, float fl_frametime);
void ets_init_ship(object* obj);
int ets_properties(object* objp);
float ets_power_factor(object* objp, bool include_power_output = true);
void ai_manage_ets(object* obj);

void increase_recharge_rate(object* obj, SYSTEM_TYPE enum_value);
void decrease_recharge_rate(object* obj, SYSTEM_TYPE enum_value);
void set_default_recharge_rates(object* obj);
void set_recharge_rates(object* obj, int shields, int weapons, int engines);

void transfer_energy_to_shields(object* obj);
void transfer_energy_to_weapons(object* obj);

float ets_get_max_speed(object* objp, float engine_energy);
void ets_update_max_speed(object* ship_objp);
void sanity_check_ets_inputs(int (&ets_indexes)[num_retail_ets_gauges]);
bool validate_ship_ets_indxes(const int &ship_idx, int (&ets_indexes)[num_retail_ets_gauges]);
void zero_one_ets (int *reduce, int *add1, int *add2);

class HudGaugeEts: public HudGauge // HUD_ETS_GAUGE
{
protected:
	hud_frames Ets_bar;
	int System_type;

	char Letter;
	int	Letter_offsets[2];
	int	Top_offsets[2];
	int	Bottom_offsets[2];

	int ETS_bar_h;
public:
	HudGaugeEts();
	HudGaugeEts(int _gauge_object, int _system_type);
	void initLetterOffsets(int _x, int _y);
	void initTopOffsets(int _x, int _y);
	void initBottomOffsets(int _x, int _y);
	void initLetter(char _letter);	// obligatory PC Load Letter joke. (Swifty)
	void initBarHeight(int _ets_bar_h);
	void initBitmaps(char *fname);
	void blitGauge(int index, int ix, int iy, float scale, bool config);
	void render(float frametime, bool config = false) override;
	void pageIn() override;
};

class HudGaugeEtsWeapons: public HudGaugeEts
{
public:
	HudGaugeEtsWeapons();
	void render(float frametime, bool config = false) override;
};

class HudGaugeEtsShields: public HudGaugeEts
{
public:
	HudGaugeEtsShields();
	void render(float frametime, bool config = false) override;
};

class HudGaugeEtsEngines: public HudGaugeEts
{
public:
	HudGaugeEtsEngines();
	void render(float frametime, bool config = false) override;
};

class HudGaugeEtsRetail: public HudGaugeEts
{
protected:
	char Letters[num_retail_ets_gauges];
	int Gauge_positions[num_retail_ets_gauges];
public:
	HudGaugeEtsRetail();
	void render(float frametime, bool config = false) override;
	void initLetters(char *_letters);
	void initGaugePositions(int *_gauge_positions);
};

#endif


89 03 A6 */	mtctr r12
/* 80182C80 0017FBC0  4E 80 04 21 */	bctrl
/* 80182C84 0017FBC4  C3 E1 00 14 */	lfs f31, 0x14(r1)
/* 80182C88 0017FBC8  38 80 00 00 */	li r4, 0
/* 80182C8C 0017FBCC  C3 C1 00 18 */	lfs f30, 0x18(r1)
/* 80182C90 0017FBD0  3C 60 80 4B */	lis r3, "__vt__26Iterator<Q24Game8Creature>"@ha
/* 80182C94 0017FBD4  C3 A1 00 1C */	lfs f29, 0x1c(r1)
/* 80182C98 0017FBD8  28 04 00 00 */	cmplwi r4, 0
/* 80182C9C 0017FBDC  C3 42 A8 80 */	lfs f26, lbl_80518BE0@sda21(r2)
/* 80182CA0 0017FBE0  38 03 BC 84 */	addi r0, r3, "__vt__26Iterator<Q24Game8Creature>"@l
/* 80182CA4 0017FBE4  98 9D 00 14 */	stb r4, 0x14(r29)
/* 80182CA8 0017FBE8  3B E0 00 00 */	li r31, 0
/* 80182CAC 0017FBEC  FF 60 D0 90 */	fmr f27, f26
/* 80182CB0 0017FBF0  80 7E 02 54 */	lwz r3, 0x254(r30)
/* 80182CB4 0017FBF4  FF 80 D0 90 */	fmr f28, f26
/* 80182CB8 0017FBF8  90 01 00 38 */	stw r0, 0x38(r1)
/* 80182CBC 0017FBFC  90 81 00 44 */	stw r4, 0x44(r1)
/* 80182CC0 0017FC00  90 81 00 3C */	stw r4, 0x3c(r1)
/* 80182CC4 0017FC04  90 61 00 40 */	stw r3, 0x40(r1)
/* 80182CC8 0017FC08  40 82 00 1C */	bne .L_80182CE4
/* 80182CCC 0017FC0C  81 83 00 00 */	lwz r12, 0(r3)
/* 80182CD0 0017FC10  81 8C 00 18 */	lwz r12, 0x18(r12)
/* 80182CD4 0017FC14  7D 89 03 A6 */	mtctr r12
/* 80182CD8 0017FC18  4E 80 04 21 */	bctrl
/* 80182CDC 0017FC1C  90 61 00 3C */	stw r3, 0x3c(r1)
/* 80182CE0 0017FC20  48 00 01 B0 */	b .L_80182E90
.L_80182CE4:
/* 80182CE4 0017FC24  81 83 00 00 */	lwz r12, 0(r3)
/* 80182CE8 0017FC28  81 8C 00 18 */	lwz r12, 0x18(r12)
/* 80182CEC 0017FC2C  7D 89 03 A6 */	mtctr r12
/* 80182CF0 0017FC30  4E 80 04 21 */	bctrl
/* 80182CF4 0017FC34  90 61 00 3C */	stw r3, 0x3c(r1)
/* 80182CF8 0017FC38  48 00 00 58 */	b .L_80182D50
.L_80182CFC:
/* 80182CFC 0017FC3C  80 61 00 40 */	lwz r3, 0x40(r1)
/* 80182D00 0017FC40  80 81 00 3C */	lwz r4, 0x3c(r1)


ewPattern(1, []int{2, 0, 2, 1}, []string{"v1beta1", "auth"}, ""))

	pattern_FrontierService_Authenticate_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v1beta1", "auth", "register", "strategy_name"}, ""))

	pattern_FrontierService_Authenticate_1 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v1beta1", "auth", "register", "strategy_name"}, ""))

	pattern_FrontierService_AuthCallback_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1beta1", "auth", "callback"}, ""))

	pattern_FrontierService_AuthCallback_1 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1beta1", "auth", "callback"}, ""))

	pattern_FrontierService_AuthToken_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1beta1", "auth", "token"}, ""))

	pattern_FrontierService_AuthLogout_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1beta1", "auth", "logout"}, ""))

	pattern_FrontierService_AuthLogout_1 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1beta1", "auth", "logout"}, ""))

	pattern_FrontierService_ListMetaSchemas_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1beta1", "meta", "schemas"}, ""))

	pattern_FrontierService_CreateMetaSchema_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1beta1", "meta", "schemas"}, ""))

	pattern_FrontierService_GetMetaSchema_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v1beta1", "meta", "schemas", "id"}, ""))

	pattern_FrontierService_UpdateMetaSchema_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v1beta1", "meta", "schemas", "id"}, ""))

	pattern_FrontierService_DeleteMetaSchema_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 1, 0, 4, 1, 5, 3}, []string{"v1beta1", "meta", "schemas", "id"}, ""))

	pattern_FrontierService_ListOrganizationAuditLogs_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3}, []string{"v1beta1", "organizations", "org_id", "auditlogs"}, ""))

	pattern_FrontierService_CreateOrganizationAuditLogs_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2, 3}, []string{"v1beta1", "organizations", "org_id", "auditlogs"}, ""))

	pattern_FrontierService_GetOrganizationAuditLog_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 1, 0, 4, 1, 5, 2, 2,


/127.0.0.1:3050/?preset=development

# 为生产预设生成 URL
npx -y @1mcp/agent preset url production
# Output: http://127.0.0.1:3050/?preset=production
```

### 与客户端配置的集成

#### Claude Desktop

```json
{
  "mcpServers": {
    "1mcp-development": {
      "command": "npx",
      "args": ["-y", "@1mcp/agent", "serve"],
      "env": {
        "ONE_MCP_PRESET_URL": "http://127.0.0.1:3050/?preset=development"
      }
    }
  }
}
```

#### Cursor/VS Code

```json
{
  "mcp.servers": {
    "1mcp-production": {
      "url": "http://127.0.0.1:3050/?preset=production"
    }
  }
}
```

## 用例

### 开发环境设置

```bash
# 获取开发预设 URL
DEV_URL=$(npx -y @1mcp/agent preset url development)
echo "Configure your development client with: $DEV_URL"
```

### 团队配置共享

```bash
# 与团队成员共享预设 URL
echo "Development: $(npx -y @1mcp/agent preset url team-dev)"
echo "Staging: $(npx -y @1mcp/agent preset url team-staging)"
echo "Production: $(npx -y @1mcp/agent preset url team-prod)"
```

### 自动化脚本

```bash
#!/bin/bash
# 使用当前预设 URL 更新客户端配置

DEV_URL=$(npx -y @1mcp/agent preset url development)
PROD_URL=$(npx -y @1mcp/agent preset url production)

# 更新配置文件
sed -i "s|preset=development|${DEV_URL}|g" config/dev.json
sed -i "s|preset=production|${PROD_URL}|g" config/prod.json
```

## 动态服务器选择

当客户端使用预设 URL 时：

1. **请求处理**：1MCP 服务器接收带有 `?preset=name` 的请求
2. **预设解析**：服务器查找预设配置
3. **服务器过滤**：将预设的标签查询应用于可用服务器
4. **动态响应**：仅将匹配的服务器返回给客户端
5. **回退**：如果未找到预设，则返回所有服务器（安全默认）

### 上下文切换

客户端可以通过更改预设参数切换服务器上下文：

```bash
#


bne	.L1245
	adds	r6, r6, #1
	cmp	r6, #4
	bne	.L1246
.L1247:
	adds	r4, r4, #1
	b	.L1244
.L1252:
	movs	r7, #0
	b	.L1248
.L1245:
	ldr	r3, [r5]
	ldr	r2, [r3]
	ldr	r3, .L1260+16
	cmp	r2, r3
	bne	.L1247
	mov	r1, r8
	ldr	r0, .L1260+20
	bl	printf
	mov	r2, #2048
	ldr	r1, [r5]
	mov	r0, r10
	bl	ftl_memcpy
	ldr	r3, [r5]
	ldr	r2, .L1260+8
	ldr	r3, [r3, #512]
	strb	r3, [r2]
	ldr	r3, .L1260+24
	ldr	r2, [r3]
	cmp	r4, r2
	bcs	.L1252
	str	r4, [r3]
	movs	r7, #0
	bl	FlashSavePhyInfo
	b	.L1247
.L1261:
	.align	2
.L1260:
	.word	.LANCHOR33
	.word	.LANCHOR29
	.word	.LANCHOR3
	.word	.LANCHOR154
	.word	-52655045
	.word	.LC15
	.word	.LANCHOR156
	.word	.LANCHOR4
	.size	FlashReadIdbDataRaw, .-FlashReadIdbDataRaw
	.section	.text.idb_write_data,"ax",%progbits
	.align	1
	.global	idb_write_data
	.syntax unified
	.thumb
	.thumb_func
	.fpu softvfp
	.type	idb_write_data, %function
idb_write_data:
	@ args = 0, pretend = 0, frame = 96
	@ frame_needed = 0, uses_anonymous_args = 0
	mov	r0, r1
	mov	r1, r2
	adds	r2, r0, r3
	push	{r4, r5, r6, r7, r8, r10, fp, lr}
	cmp	r2, #63
	sub	sp, sp, #104
	bls	.L1263
	cmp	r0, #576
	bcs	.L1264
	ldr	r2, .L1315
	cmp	r0, #64
	mov	r4, #1
	str	r4, [r2]
	bhi	.L1265
	rsb	r0, r0, #64
	subs	r2, r3, r0
	add	r1, r1, r0, lsl #9
	ldr	r0, .L1315+4
	lsls	r2, r2, #9
.L1314:
	bl	ftl_memcpy
.L1303:
	movs	r0, #0
	add	sp, sp, #104
	@ sp needed
	pop	{r4, r5, r6, r7, r8, r10, fp, pc}
.L1265:
	rsb	r2, r0, #576
	subs	r0, r0, #64
	cmp	r2, r3
	it	cs
	movcs	r2, r3
	ldr	r3, .L1315+4


    ["Kerna"] = "科娜",
    ["Rokag"] = "瑞克格",
    ["Advisor Faila"] = "諫言者菲拉",
    ["Innkeeper Grilka"] = "旅店老闆格瑞伊卡",
    ["Kurgatok"] = "庫爾卡拓克",
    ["Malukaz"] = "瑪魯卡茲",
    ["Rakoria"] = "瑞蔻莉雅",
    ["Shadowstalker Kaide"] = "巡影者凱德",
    ["Grek"] = "葛利克",
    ["Scout Neftis"] = "斥候奈夫提斯",
    ["Tooki"] = "吐奇",
    ["Sergeant Chawni"] = "丘尼士官",
    ["Mawg Grimshot"] = "矛克·邪擊",
    ["Messenger Gazgrigg"] = "傳令員卡茲瑞克",
    ["Matron Tikkit"] = "女監護者堤克綈",
    ["Matron Drakia"] = "女監護者崔克雅",
    ["Gursha"] = "古爾莎",
    ["Matron Celestine"] = "女監護者瑟萊斯丁",
    ["Elementalist Yal'hah"] = "元素師亞哈",
    ["Ohlorn Farstrider"] = "歐洛恩·遠行者",
    ["Captain Kroghan"] = "隊長卡洛克汗",
    ["Jorin Deadeye"] = "喬林·亡眼",
    ["Warden Bullrok"] = "守望者波洛克",
    ["Farseer Kurkush"] = "先知可庫許",
    ["Farseer Margadesh"] = "先知馬卡戴斯",
    ["Farseer Corhuk"] = "先知科霍克",
    ["Kilrath"] = "科伊瑞斯",
    ["Unkor the Ruthless"] = "無情的昂庫爾",
    ["Elkay'gan the Mystic"] = "『秘法師』伊萊克根",
    ["Elder Yorley"] = "長老優兒利",
    ["Elder Ungriz"] = "長老昂古力斯",
    ["Mag'har Captive"] = "瑪格哈俘虜",
    ["Garrosh"] = "卡爾洛斯",
    ["Grunt Grahk"] = "蠻兵葛拉赫",
    ["Tor'chunk Twoclaws"] = "吐查克·雙爪",
    ["Nekthar"] = "奈克薩爾",
    ["Gor'drek"] = "葛德雷克",
    ["Gholah"] = "哥爾拉",
    ["Unoke Tenderhoof"] = "攸怒克·嫩蹄",
    ["Lor"] = "羅爾",
    ["Rokgah Bloodgrip"] = "洛克嘎·血握",
    ["Stronglimb Deeproot"] = "斯卓霖普·深根",
    ["T'chali the Witch Doctor"] = "巫醫提洽里",
    ["Korgaah"] = "柯爾卡赫",
    ["Garm Wolfbrother"] = "嘎姆·狼伴",
    ["Rexxar"] = "雷克薩",
    ["Dertrok"] = "德托克",
    ["


using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using Microsoft.Maui.Controls.Platform;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Markup;
using Microsoft.UI.Xaml.Shapes;
using WEllipse = Microsoft.UI.Xaml.Shapes.Ellipse;
using WRectangle = Microsoft.UI.Xaml.Shapes.Rectangle;
using WShape = Microsoft.UI.Xaml.Shapes.Shape;
using WSolidColorBrush = Microsoft.UI.Xaml.Media.SolidColorBrush;

namespace Microsoft.Maui.Controls.Compatibility.Platform.UWP
{
	[System.Obsolete(Compatibility.Hosting.MauiAppBuilderExtensions.UseMapperInstead)]
	partial class IndicatorViewRenderer : ViewRenderer<IndicatorView, FrameworkElement>
	{
		const int DefaultPadding = 4;
		WSolidColorBrush _selectedColor;
		WSolidColorBrush _fillColor;
		ObservableCollection<WShape> _dots;

		public IndicatorViewRenderer()
		{
			AutoPackage = false;
		}

		protected override void OnElementChanged(ElementChangedEventArgs<IndicatorView> e)
		{
			base.OnElementChanged(e);

			if (e.NewElement != null)
			{
				if (Control == null)
				{
					UpdateControl();
				}

				_fillColor = new WSolidColorBrush(Element.IndicatorColor.ToWindowsColor());

				_selectedColor = new WSolidColorBrush(Element.SelectedIndicatorColor.ToWindowsColor());

				CreateIndicators();
			}
		}

		protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
		{
			base.OnElementPropertyChanged(sender, e);

			if (e.IsOneOf(IndicatorView.IndicatorColorProperty, IndicatorView.SelectedIndicatorColorProperty, IndicatorView.PositionProperty))
				UpdateIndicatorsColor();

			if (e.IsOneOf(IndicatorView.CountProperty,
						  IndicatorView.ItemsSourceProperty,
						  IndicatorView.IndicatorsShapeProperty))
				CreateIndicators();
		}

		void UpdateControl()
		{
			var control = (Element.IndicatorTemplate != null)
				? (FrameworkElement)(Element.IndicatorLayout as VisualElement).GetOrCreateRenderer()
				: CreateNativeControl();

			SetNativeControl(control);
		}

		FrameworkElement CreateNativeControl()
		{
			return new ItemsControl
			{
				HorizontalAlignment = HorizontalAlig


irTree/mf_icr/icr/64/3.8",
                                             ["mpath"] = "%ProjDir%/spec/DirTree/mf_icr",
                                          },
                                          ["icr/64/3.9"]  = {
                                             ["canonical"] = "3.9",
                                             ["fn"] = "%ProjDir%/spec/DirTree/mf_icr/icr/64/3.9",
                                             ["mpath"] = "%ProjDir%/spec/DirTree/mf_icr",
                                          },
                                       },
                                    },
                                 },
                                 fileT = {},
                              },
                           },
                           fileT = {},
                        },
                        ["mpath"] = "%ProjDir%/spec/DirTree/mf_icr",
                     },
                  }
                  sanizatizeTbl(rplmntA, dirA, _dirA)
                  --dbg:activateDebug(1)
                  --dbg.printT("goldA", goldA)
                  --dbg.printT("dirA",  _dirA)
                  assert.are.same(goldA, _dirA)

               end
            )
         end
)


2)-(band/2)) and x < ((width/2)+(band/2)):       # If center point is centered

                        dir = "driving"

                        if radius >= tp:    # Too Close

                            case = "too close"

                            duty = -1 * ((radius-tp)/(tc-tp))

                        elif radius < tp:   # Too Far

                            case = "too far"

                            duty = 1 - ((radius - tf)/(tp - tf))
                            duty = scale_d * duty

                        duty_r = duty
                        duty_l = duty

                    else:
                        case = "turning"

                        duty_l = round((x-0.5*width)/(0.5*width),2)     # Duty Left
                        duty_l = duty_l*scale_t

                        duty_r = round((0.5*width-x)/(0.5*width),2)     # Duty Right
                        duty_r = duty_r*scale_t

                    # Keep duty cycle within range

                    if duty_r > 1:
                        duty_r = 1

                    elif duty_r < -1:
                        duty_r = -1

                    if duty_l > 1:
                        duty_l = 1

                    elif duty_l < -1:
                        duty_l = -1

                    # Round duty cycles
                    duty_l = round(duty_l,2)
                    duty_r = round(duty_r,2)

                    print(case, "radius: ", round(radius,1), "\tx: ", round(x,0), "\t\tL: ", duty_l, "\tR: ", duty_r)

                    # Set motor duty cycles
                    #motor.set(motor_l, duty_l)
                    #motor.set(motor_r, duty_r)

                # Set motor duty cycles
                #motor.set(motor_l, duty_l)
                #motor.set(motor_r, duty_r)

           # elif rcpy.get_state() == rcpy.PAUSED:
            #    pass

    except KeyboardInterrupt: # condition added to catch a "Ctrl-C" event and exit cleanly
        rcpy.set_state(rcpy.EXITING)
        pass

    finally:

    	rcpy.set_state(rcpy.EXITING)
    	print("Exiting Color Tracking.")

# exiting program will automatically clean up cape

if __name__ == '__main__':
    main()


/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#pragma once

#include "DriverNlMessage.h"
#include "e2e/if/gen-cpp2/Controller_types.h"
#include "e2e/if/gen-cpp2/DriverMessage_types.h"

namespace {
const double k1e7 = 10000000.0;
const double k1e2 = 100.0;
const double k1e3 = 1000.0;
} // namespace

namespace facebook {
namespace terragraph {

/** Internal radio state (for BaseDriverIf). */
struct RadioState {
  /** The radio MAC address. */
  std::string radioMac;

  /**
   * Whether this radio is up.
   *
   * Here, "up" means we have received NODE_INIT_NOTIFY or
   * DR_DEV_UPDOWN_STATUS(UP) and no following DR_DEV_UPDOWN_STATUS(DOWN).
   */
  bool isUp;

  /**
   * Whether GPS_SET_POS_REQ has been sent for this radio.
   */
  bool positionSent;
};

/** Convert a DriverNlMessage to a corresponding thrift::Message. */
thrift::Message driverNl2IfMessage(const DriverNlMessage& drNlMsg);

/** Convert ECEF XYZ coordinates to geodetic coordinates. */
void convertEcefToGeodetic(
    double ecefX,
    double ecefY,
    double ecefZ,
    double& latitude,
    double& longitude,
    double& height);

inline thrift::DrvrStatsSample
createDrvrStatsSample(const std::string& key, uint64_t value) {
  thrift::DrvrStatsSample drvrStatsSample;
  drvrStatsSample.key = key;
  drvrStatsSample.value = value;
  return drvrStatsSample;
}

} // namespace terragraph
} // namespace facebook


-h), var(--base-s), calc(var(--base-l) - 20%), 0.3);
    border-radius: var(--replete-tag-radius) !important;
    padding: 3px 2px 3px 2px !important;
    text-transform: uppercase !important;
    font-weight:600;
    font-size:10px;
    letter-spacing: 0.04em;
    transform: translate(0,-2px);
    display:inline-block;
}
    .theme-dark .plugin-tasks-list-item .tag {
    background-color: hsla(var(--base-h), var(--base-s), calc(var(--base-l) + 40%), 0.4);
    }

/* GTD tags */
.cm-tag-next {
    color:var(--color-accent-1) !important;
}

.cm-tag-someday {
    color:var(--color-orange) !important;
}

.cm-tag-waiting {
    color:var(--color-pink) !important;
}

.cm-tag-blocked {
    color:var(--color-red) !important;
}

.cm-tag-done {
    color:var(--color-green) !important;
}/*
    Tracker
    Tracker plugin styles and themed colours
    https://github.com/replete/obsidian-minimal-theme-css-snippets
*/

/* chart display tweaks */
.block-language-tracker {

    .tracker-legend {
        stroke: none;
    }

    .tracker-tick-label {
        fill:var(--tx2);
    }
}

/* Duotone on hover effect */
/* Light themes */
.theme-light.minimal-default-light .block-language-tracker:not(:hover) {
    filter: url('data:image/svg+xml,\
        <svg xmlns="http://www.w3.org/2000/svg">\
            <filter id="filter">\
                <feColorMatrix type="matrix" result="grayscale"\
                    values="1 0 0 0 0\
                    1 0 0 0 0\
                    1 0 0 0 0\
                    0 0 0 1 0">\
                </feColorMatrix>\
                <feComponentTransfer color-interpolation-filters="sRGB" result="duotone">\
                    <feFuncR type="table" tableValues="0.5 1"></feFuncR>\
                    <feFuncG type="table" tableValues="0.5 1"></feFuncG>\
                    <feFuncB type="table" tableValues="0.5 1"></feFuncB>\
                    <feFuncA type="table" tableValues="0 1"></feFuncA>\
                </feComponentTransfer>\
            </filter>\
        </svg>#filter');
}

.theme-light.minimal-atom-light .block-language-tracker:not(:hover) {
    filter: url('data:image/svg+xml,\
        <svg xmlns="http://www.w3.org/2000/svg">\
            <filter id="filter">\
                <feColorMatrix type="matrix" result="grayscale"\
                    values="1 0 0 0 0\
                    1 0 0 0 0\
                    1 0 0 0 0\
                    0 0 0 1 0">\
                </feColorMatrix>\
                <feComponentTransfer color-interpolation-filters="sRGB" result="duotone">\
                    <feFuncR type="table" tableValues="0.6274509804 0.9803921569"></feFuncR>\
                    <feFuncG type="table" tableValues="0.631372549 0.9803921569"></feFuncG>\
                    <feFuncB type="table" tableValues="0.6588235294 0.9803921569"></feFuncB>\
                    <feFuncA type="table" tableValues="0 1"></feFuncA>\
                </feComponentTransfer>\
            </filter>\
        </svg>#filter');
}

.theme-light.minimal-ayu-light .block-language-tracker:not(:hover) {
    filter: url('data:image/svg+xml,\
        <svg xmlns="http://www.w3.org/2000/svg">\
            <filter id="filter">\
                <feColorMatrix type="matrix" result="grayscale


 rot = { x = 0.0, y = 83.6, z = 0.0 }, level = 1 },
	{ config_id = 111, gadget_id = 70900046, pos = { x = 95.8, y = -10.5, z = -144.7 }, rot = { x = 0.0, y = 83.6, z = 0.0 }, level = 1 },
	{ config_id = 112, gadget_id = 70900046, pos = { x = 93.9, y = -10.5, z = -144.2 }, rot = { x = 0.0, y = 83.6, z = 0.0 }, level = 1 },
	{ config_id = 113, gadget_id = 70900046, pos = { x = 93.2, y = -10.5, z = -147.1 }, rot = { x = 0.0, y = 83.6, z = 0.0 }, level = 1 },
	{ config_id = 114, gadget_id = 70900046, pos = { x = 93.5, y = -10.5, z = -150.6 }, rot = { x = 0.0, y = 83.6, z = 0.0 }, level = 1 },
	{ config_id = 115, gadget_id = 70900046, pos = { x = 97.7, y = -10.5, z = -147.8 }, rot = { x = 0.0, y = 83.6, z = 0.0 }, level = 1 },
	{ config_id = 116, gadget_id = 70900046, pos = { x = 91.7, y = -10.5, z = -143.8 }, rot = { x = 0.0, y = 83.6, z = 0.0 }, level = 1 },
	{ config_id = 117, gadget_id = 70900046, pos = { x = 95.1, y = -10.5, z = -143.3 }, rot = { x = 0.0, y = 83.6, z = 0.0 }, level = 1 }
}

-- 区域
regions = {
}

-- 触发器
triggers = {
}

-- 变量
variables = {
}

--================================================================
--
-- 初始化配置
--
--================================================================

-- 初始化时创建
init_config = {
	suite = 1,
	end_suite = 0,
	rand_suite = true,
	npcs = { }
}

--================================================================
--
-- 小组配置
--
--================================================================

suites = {
	{
		-- suite_id = 1,
		-- description = ,
		monsters = { },
		gadgets = { 96, 97, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117 },
		regions = { },
		triggers = { },
		rand_weight = 100
	}
}

--================================================================
--
-- 触发器
--
--================================================================