#pragma once
#include "node_standard.h"

struct TopWindow : UINode
{
    enum Kind { MainWindow, Window, Popup, ModalPopup, Activity };
    enum Placement { None, Left, Right, Top, Bottom, Center, Maximize };

    direct_val<ImGuiWindowFlags_> flags = ImGuiWindowFlags_NoCollapse;
    direct_val<Kind> kind = Window;
    bindable<std::string> title = "title";
    bindable<dimension_t> size_x = 640.f;
    bindable<dimension_t> size_y = 480.f;
    bindable<dimension_t> minSize_x = 0;
    bindable<dimension_t> minSize_y = 0;
    bindable<font_name_t> style_fontName;
    bindable<float> style_fontSize; //scaled by style.FontScaleDpi
    direct_val<pzdimension2_t> style_padding;
    direct_val<pzdimension2_t> style_spacing;
    direct_val<pzdimension2_t> style_innerSpacing;
    direct_val<pzdimension_t> style_borderSize;
    direct_val<pzdimension_t> style_rounding;
    direct_val<pzdimension_t> style_scrollbarSize;
    direct_val<pzdimension2_t> style_titlePadding;
    bindable<color_t> style_bg;
    bindable<color_t> style_menuBg;
    direct_val<Placement> placement = None;
    direct_val<bool> closeOnEscape = false;
    direct_val<bool> animate = false;
    direct_val<bool> initialActivity = false;

    event<> onBackButton;
    event<> onWindowAppearing;

    std::string userCodeBefore, userCodeAfter, userCodeMid;

    TopWindow(UIContext& ctx);
    void Draw(UIContext& ctx);
    void DrawTools(UIContext& ctx) {}
    void TreeUI(UIContext& ctx);
    bool EventUI(int, UIContext& ctx);
    auto Properties() ->std::vector<Prop>;
    auto Events() ->std::vector<Prop>;
    bool PropertyUI(int i, UIContext& ctx);
    void Export(std::ostream& os, UIContext& ctx);
    void Import(cpp::stmt_iterator& sit, UIContext& ctx);
    int Behavior() { return SnapInterior; }
    int ColumnCount(UIContext& ctx) { return 0; }
    std::string GetTypeName() { return "Window"; }
    const TopWindow& Defaults() { static TopWindow node(UIContext::Defaults()); return node; }
};


pController controller;
  final markers = <String, Marker>{};
  int _markerIdCounter = 1;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.snackBar('点击地图添加标记，点击标记删除');
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text(AddRemoveMarkerPage.title)),
      body: AMapFlutter(
        initCameraPosition: CameraPosition(
          position: Position(latitude: 39.984120, longitude: 116.307484),
          zoom: 17.2,
        ),
        onMapCreated: (controller) => this.controller = controller,
        onMapPress: (position) => onTap(position),
        onMapLongPress: (position) => onTap(position),
        onPoiClick: (poi) => onTap(poi.position),
        onMarkerClick: (markerId) => onMarkerClick(markerId),
        onMarkerDragEnd: (markerId, position) =>
            context.alert('${position.latitude}, ${position.longitude}'),
      ),
    );
  }

  void onTap(Position position) async {
    final String markerId = 'marker_id_${_markerIdCounter++}';
    final marker = Marker(
      id: markerId,
      position: position,
      bitmap: Bitmap(
        asset: "assets/map-marker.png",
      ),
    );
    markers[markerId] = marker;
    controller.addMarker(marker);
  }

  void onMarkerClick(String markerId) {
    controller.removeMarker(markerId);
    markers.remove(markerId);
  }
}
import 'package:amap_flutter/amap_flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

/// 地图样式切换页面
class MapStylesPage extends StatefulWidget {
  /// 地图样式切换页面构造函数
  const MapStylesPage({super.key});

  /// 地图样式切换页面标题
  static const title = '地图样式切换';

  @override
  State<MapStylesPage> createState() => _MapStylesPageState();
}

class _MapStylesPageState extends State<MapStylesPage> {
  String mapStyle = "amap://styles/normal";
  final styles = {
    "amap://styles/normal": "标准",
    "amap://styles/macaron": "马卡龙",
    "amap://styles/graffiti": "涂鸦",
    "amap://styles/whitesmoke": "远山黛",
    "amap://styles/dark": "幻影黑",
    "amap://styles/fresh": "草色青",
    "amap://styles/darkblue": "极夜蓝",
    "amap://styles/blue": "靛青蓝",
    "amap://styles/light": "月光银",


  function peg$parseVariableDeclaratorId() {
    var s0, s1, s2, s3;

    s0 = peg$currPos;
    s1 = peg$parseIdentifier();
    if (s1 !== peg$FAILED) {
      s2 = [];
      s3 = peg$parseDim();
      while (s3 !== peg$FAILED) {
        s2.push(s3);
        s3 = peg$parseDim();
      }
      if (s2 !== peg$FAILED) {
        peg$savedPos = s0;
        s1 = peg$c43(s1, s2);
        s0 = s1;
      } else {
        peg$currPos = s0;
        s0 = peg$FAILED;
      }
    } else {
      peg$currPos = s0;
      s0 = peg$FAILED;
    }

    return s0;
  }

  function peg$parseBlock() {
    var s0, s1, s2, s3;

    s0 = peg$currPos;
    s1 = peg$parseLWING();
    if (s1 !== peg$FAILED) {
      s2 = peg$parseBlockStatements();
      if (s2 !== peg$FAILED) {
        s3 = peg$parseRWING();
        if (s3 !== peg$FAILED) {
          peg$savedPos = s0;
          s1 = peg$c44(s2);
          s0 = s1;
        } else {
          peg$currPos = s0;
          s0 = peg$FAILED;
        }
      } else {
        peg$currPos = s0;
        s0 = peg$FAILED;
      }
    } else {
      peg$currPos = s0;
      s0 = peg$FAILED;
    }

    return s0;
  }

  function peg$parseBlockStatements() {
    var s0, s1;

    s0 = [];
    s1 = peg$parseBlockStatement();
    while (s1 !== peg$FAILED) {
      s0.push(s1);
      s1 = peg$parseBlockStatement();
    }

    return s0;
  }

  function peg$parseBlockStatement() {
    var s0, s1, s2;

    s0 = peg$parseLocalVariableDeclarationStatement();
    if (s0 === peg$FAILED) {
      s0 = peg$currPos;
      s1 = [];
      s2 = peg$parseModifier();
      while (s2 !== peg$FAILED) {
        s1.push(s2);
        s2 = peg$parseModifier();
      }
      if (s1 !== peg$FAILED) {
        s2 = peg$parseClassDeclaration();
        if (s2 === peg$FAILED) {
          s2 = peg$parseEnumDeclaration();
        }
        if (s2 !== peg$FAILED) {
          peg$savedPos = s0;
          s1 = peg$c45(s1, s2);
          s0 = s1;
        } else {
          peg$currPos = s0;
          s0 = peg$FAILED;
        }
      } else {
        peg$currPos = s0;
        s0 = peg$FAILED;
      }
      if (s0 === peg$FAILED) {
        s0 = peg$parseStatement();
      }
    }

    return s0;
  }

  function peg$parseStatement() {
    var s0, s1, s2, s3, s4, s5, s6, s7, s8, s9;

    s0 = peg$parseBlock();
    if (s0 === peg$FAILED) {
      s0 = peg$currPos;
      s1 = peg$parseASSERT();
      if (s1 !== peg$FAILED) {
        s2 = peg$parseExpression();
        if (s2 !== peg$FAILED) {
          s3 = peg$currPos;
          s4 = peg$parseCOLON();
          if (s4 !== peg$FAILED) {
            s5 = peg$parseExpression();
            if (s5 !== peg$FAILED) {
              s4 = [s4, s5];
              s3 = s4;
            } else {
              peg$currPos = s3;
              s3 = peg$FAILED;
            }
          } else {
            peg$currPos = s3;
            s3 = peg$FAILED;
          }
          if (s3 === peg$FAILED) {


	imm32 r4, 0xb56789ab;
	imm32 r5, 0xc6789abc;
	imm32 r6, 0xd789abcd;
	imm32 r7, 0xe89abcde;
	R3.L = -31;
	R0 <<= R3;
	R1 <<= R3;
	R2 <<= R3;
	R4 <<= R3;
	R5 <<= R3;
	R6 <<= R3;
	R7 <<= R3;
	R3 <<= R3;
	CHECKREG r0, 0x00000000;
	CHECKREG r1, 0x00000000;
	CHECKREG r2, 0x00000000;
	CHECKREG r3, 0x00000000;
	CHECKREG r4, 0x00000000;
	CHECKREG r5, 0x00000000;
	CHECKREG r6, 0x00000000;
	CHECKREG r7, 0x00000000;

	imm32 r0, 0x00000001;
	imm32 r1, 0x12345678;
	imm32 r2, 0x23456789;
	imm32 r3, 0x3456789a;
	imm32 r4, 0x00000000;
	imm32 r5, 0x96789abc;
	imm32 r6, 0xa789abcd;
	imm32 r7, 0xb89abcde;
	R4.L = 15;
	R1 <<= R4;
	R2 <<= R4;
	R3 <<= R4;
	R0 <<= R4;
	R5 <<= R4;
	R6 <<= R4;
	R7 <<= R4;
	R4 <<= R4;
	CHECKREG r0, 0x00008000;
	CHECKREG r1, 0x2B3C0000;
	CHECKREG r2, 0xB3C48000;
	CHECKREG r3, 0x3C4D0000;
	CHECKREG r4, 0x00078000;
	CHECKREG r5, 0x4D5E0000;
	CHECKREG r6, 0xD5E68000;
	CHECKREG r7, 0x5E6F0000;

	imm32 r0, 0x01230002;
	imm32 r1, 0x00000000;
	imm32 r2, 0x93456789;
	imm32 r3, 0xa456789a;
	imm32 r4, 0xb56789ab;
	imm32 r5, 0x00000000;
	imm32 r6, 0xd789abcd;
	imm32 r7, 0xe89abcde;
	R5.L = -15;
	R0 <<= R5;
	R1 <<= R5;
	R2 <<= R5;
	R3 <<= R5;
	R4 <<= R5;
	R6 <<= R5;
	R7 <<= R5;
	R5 <<= R5;
	CHECKREG r0, 0x00000000;
	CHECKREG r1, 0x00000000;
	CHECKREG r2, 0x00000000;
	CHECKREG r3, 0x00000000;
	CHECKREG r4, 0x00000000;
	CHECKREG r5, 0x00000000;
	CHECKREG r6, 0x00000000;
	CHECKREG r7, 0x00000000;

	imm32 r0, 0x51230002;
	imm32 r1, 0x12345678;
	imm32 r2, 0xb1256790;
	imm32 r3, 0x3456789a;
	imm32 r4, 0x956789ab;
	imm32 r5, 0x86789abc;
	imm32 r6, 0x00000000;
	imm32 r7, 0x789abcde;
	R6.L = 24;
	R0 <<= R6;
	R1 <<= R6;
	R2 <<= R6;
	R3 <<= R6;
	R4 <<= R6;
	R5 <<= R6;
	R7 <<= R6;
	R6 <<= R6;
	CHECKREG r0, 0x02000000;
	CHECKREG r1, 0x78000000;
	CHECKREG r2, 0x90000000;
	CHECKREG r3


ì',
  '犢=dú',
  '犣=liè',
  '犤=pái',
  '犥=piāo',
  '犦=bào',
  '犧=xī',
  '犨=chōu',
  '犩=wéi',
  '犪=kuí',
  '犫=chōu',
  '犬=quǎn',
  '犭=quǎn',
  '犮=quǎn,bá',
  '犯=fàn',
  '犰=qiú',
  '犱=jǐ',
  '犲=chái',
  '犳=zhuó,bào',
  '犴=hān,àn',
  '犵=gē',
  '状=zhuàng',
  '犷=guǎng',
  '犸=mǎ',
  '犹=yóu',
  '犺=kàng,gǎng',
  '犻=pèi,fèi',
  '犼=hǒu',
  '犽=yà',
  '犾=yín',
  '犿=huān,fān',
  '狀=zhuàng',
  '狁=yǔn',
  '狂=kuáng',
  '狃=niǔ',
  '狄=dí',
  '狅=kuáng',
  '狆=zhòng',
  '狇=mù',
  '狈=bèi',
  '狉=pī',
  '狊=jú',
  '狋=yí,quán,chí',
  '狌=shēng,xīng',
  '狍=páo',
  '狎=xiá',
  '狏=tuó,yí',
  '狐=hú',
  '狑=líng',
  '狒=fèi',
  '狓=pī',
  '狔=nǐ',
  '狕=yǎo',
  '狖=yòu',
  '狗=gǒu',
  '狘=xuè',
  '狙=jū',
  '狚=dàn',
  '狛=bó',
  '狜=kǔ',
  '狝=xiǎn',
  '狞=níng',
  '狟=huán,huān',
  '狠=hěn',
  '狡=jiǎo',
  '狢=hé,mò',
  '狣=zhào',
  '狤=jié',
  '狥=xùn',
  '狦=shān',
  '狧=tà,shì',
  '狨=róng',
  '狩=shòu',
  '狪=tóng,dòng',
  '狫=lǎo',
  '独=dú',
  '狭=xiá',
  '狮=shī',
  '狯=kuài',
  '狰=zhēng',
  '狱=yù',
  '狲=sūn',
  '狳=yú',
  '狴=bì',
  '狵=máng,dòu',
  '狶=xī,shǐ',
  '狷=juàn',
  '狸=lí',
  '狹=xiá',
  '狺=yín',
  '狻=suān',


         LocalDate.minutes,  DateCase.getMinutes() );
  new TestCase( SECTION, DateString+".getSeconds()",          LocalDate.seconds,  DateCase.getSeconds() );
  new TestCase( SECTION, DateString+".getMilliseconds()",     LocalDate.ms,       DateCase.getMilliseconds() );

  DateCase.toString = Object.prototype.toString;

  new TestCase( SECTION,
		DateString+".toString=Object.prototype.toString;"+DateString+".toString()",
		"[object Date]",
		DateCase.toString() );
}
function MyDate() {
  this.year = 0;
  this.month = 0;
  this.date = 0;
  this.hours = 0;
  this.minutes = 0;
  this.seconds = 0;
  this.ms = 0;
}
function LocalDateFromTime(t) {
  t = LocalTime(t);
  return ( MyDateFromTime(t) );
}
function UTCDateFromTime(t) {
  return ( MyDateFromTime(t) );
}
function MyDateFromTime( t ) {
  var d       = new MyDate();
  d.year      = YearFromTime(t);
  d.month     = MonthFromTime(t);
  d.date      = DateFromTime(t);
  d.hours     = HourFromTime(t);
  d.minutes   = MinFromTime(t);
  d.seconds   = SecFromTime(t);
  d.ms        = msFromTime(t);
  d.time      = MakeTime( d.hours, d.minutes, d.seconds, d.ms );
  d.value     = TimeClip( MakeDate( MakeDay( d.year, d.month, d.date ), d.time ) );
  d.day       = WeekDay( d.value );
  return (d);
}
/* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

gTestfile = '15.9.5.33-1.js';

/**
   File Name:          15.9.5.33-1.js
   ECMA Section:       15.9.5.33 Date.prototype.setUTCDate(date)
   Description:
   1.  Let t be this time value.
   2.  Call ToNumber(date).
   3.  Compute MakeDay(YearFromTime(t), MonthFromTime(t), Result(2)).
   4.  Compute MakeDate(Result(3), TimeWithinDay(t)).
   5.  Set the [[Value]] property of the this value to TimeClip(Result(4)).
   6.  Return the value of the [[Value]] property of the this value.

   Author:             christine@netscape.com
   Date:               12 november 1997
*/
var SECTION = "15.9.5.33-1";
var VERSION = "ECMA_1";
startTest();

writeHeaderToLog( SECTION + " Date.prototype.setUTCDate(date) ");

addNewTestCase( "TDATE = new Date(0);(TDATE).setUTCDate(31);TDATE",
		UTCDateFromTime(SetUTCDate(0,31)),
		LocalDateFromTime(SetUTCDate(0,31)) );

addNewTestCase( "TDATE = new Date(0);(TDATE).setUTCDate(1);TDATE",
		UTCDateFromTime(SetUTCDate(0,1)),
		LocalDateFromTime(SetUTCDate(0,1)) );

addNewTestCase( "TDATE = new Date(86400000);(TDATE).setUTCDate(1);TDATE",
		UTCDateFromTime(SetUTCDate(86400000,1)),
		LocalDateFromTime(SetUTCDate(86400000,1)) );

test();

function addNewTestCase( DateString, UTCDate, LocalDate) {
  DateCase = eval( DateString );

  new TestCase( SECTION, DateString+".getTime()",             UTCD


(stderr, "Success!\n");
    else
        fprintf(stderr, "Failed.\n");

    Global::AppCleanup();
#ifdef _DEBUG
    fclose(gLog);
#endif

    exit(0);
}

/*
 * CiderPress
 * Copyright (C) 2007 by faddenSoft, LLC.  All Rights Reserved.
 * See the file LICENSE for distribution terms.
 */
/*
 * Drive diskimglib.  Similar to MDC.
 */
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <limits.h>
#include <errno.h>
#include "zlib.h"
#include "../diskimg/DiskImg.h"
#include "../nufxlib/NufxLib.h"
#include "StringArray.h"

using namespace DiskImgLib;

#define nil NULL
#define ASSERT assert
#define NELEM(x) (sizeof(x) / sizeof((x)[0]))
typedef const char* LPCTSTR;

#define UNIX_LIKE
#define HAVE_DIRENT_H   // linux
#define MAX_PATH_LEN 1024

/* get a grip on this opendir/readdir stuff */
#if defined(UNIX_LIKE)
#  if defined(HAVE_DIRENT_H)
#    include <dirent.h>
#    define DIR_NAME_LEN(dirent)    ((int)strlen((dirent)->d_name))
     typedef struct dirent DIR_TYPE;
#  elif defined(HAVE_SYS_DIR_H)
#    include <sys/dir.h>
#    define DIR_NAME_LEN(direct)    ((direct)->d_namlen)
     typedef struct direct DIR_TYPE;
#  elif defined(HAVE_NDIR_H)
#    include <sys/ndir.h>
#    define DIR_NAME_LEN(direct)    ((direct)->d_namlen)
     typedef struct direct DIR_TYPE;
#  else
#    error "Port this?"
#  endif
#endif

/*
 * Globals.
 */
FILE* gLog = nil;
pid_t gPid = getpid();

struct Stats {
    long    numFiles;
    long    numDirectories;
    long    goodDiskImages;
} gStats = { 0 };

typedef struct ScanOpts {
    FILE*   outfp;
} ScanOpts;

typedef enum RecordKind {
    kRecordKindUnknown = 0,
    kRecordKindDisk,
    kRecordKindFile,
    kRecordKindForkedFile,
    kRecordKindDirectory,
    kRecordKindVolumeDirectory,
} RecordKind;

//#define kFilenameExtDelim '.'     /* separates extension from filename */

/* time_t values for bad dates */
#define kDateNone       ((time_t) -2)
#define kDateInvalid    ((time_t) -1)       // should match return from mktime()

/*
 * "buf" must hold at least 64 chars.
 */
void
FormatDate(time_t when, char* buf)
{
    if (when == kDateNone) {
        strcpy(buf, "[No Date]");
    } else if (when == kDateInvalid) {
        strcpy(buf, "<invalid>");
    } else {
        struct tm* ptm;

        ptm = localtime(&when);
        strftime(buf, 64, "%d-%b-%y %H:%M", ptm);
    }
}

#if 0
/*
 * Find the filename component of a local pathname.  Uses the fssep passed
 * in.  If the fssep is '\0' (as is the case for DOS 3.3), then the entire
 * pathname is returned.
 *
 * Always returns a pointer to a string; never returns nil.
 */
const char*
FilenameOnly(const char* pathname, char fssep)
{
    const char* retstr;
    const char* pSlash;
    char* tmpStr = nil;

    ASSERT(pathname != nil);
    if (fssep == '\0') {
        retstr = pathname;


fun succCommand(node: CmdPointer) = succ(node).map(::elab)

    fun predCommand(node: CmdPointer) = pred(node).map(::elab)

    fun succ(l: U) = succCommand(l.ptr)

    fun pred(l: U) = predCommand(l.ptr)

    fun succPointer(l: U) = succ(l.ptr)
    @Suppress("unused")

    fun predPointer(l: U) = pred(l.ptr)

    fun toCommand(p: CmdPointer) = toCommand(p.block, p.pos)
    fun toCommand(block: NBId, pos: Int) = code[block]!![pos]

    fun getLhs(p: CmdPointer) = toCommand(p).getLhs()

    abstract fun elab(p: CmdPointer): U

    fun elab(b: NBId) = _nodeIdToBlock[b] ?: error("Block id $b is not in the graph")

    fun pred(b: NBId) = blockPred[b] ?: error("Block id $b is not in the graph")

    @Suppress("USELESS_CAST")
    @PerformanceCriticalUsesOnly
    fun predUntyped(b: Any?): Any? = (blockPred as Map<*, *>)[b]

    fun succ(b: NBId) = blockSucc[b] ?: error("Block id $b is not in the graph")

    fun dump() {
        code.entries.forEach { (bid, blocks) ->
            println("Block ${bid}")
            blocks.forEachIndexed { i, b ->
                println("(${bid}, ${i}): ${b} (pred: ${pred(CmdPointer(bid, i))})")
            }
            println("<<")
        }
    }

    fun dump(nbId: NBId, l: Logger, log: Logger.(() -> String) -> Unit = Logger::debug) {
        l.log {
            "Context: Contents of $nbId"
        }
        if (l.isDebugEnabled) {
            elab(nbId).commands.forEach {
                l.log { it.toString() }
            }
        }
    }

    /**
     * From [low] to [high], or if [reversed] then from [high] to [low]. inclusive on both ends.
     */
    fun lcmdSequence(
        block: NBId,
        low: Int = 0,
        high: Int = code[block]!!.size - 1,
        reverse: Boolean = false,
    ): Sequence<U> {
        val cmds = elab(block).commands
        if (low > high) {
            return emptySequence()
        }
        require(high < code[block]!!.size) {
            "$high exceeds maxmimal allowed index in $block : (${cmds.size - 1})"
        }
        require(low >= 0) {
            "$low should be at least 0"
        }
        return sequence {
            val range = if (reverse) {
                high downTo low
            } else {
                low..high
            }
            for (i in range) {
                yield(cmds[i])
            }
        }
    }

    fun blockCmdsBackwardFrom(p : CmdPointer) =
        lcmdSequence(p.block, high = p.pos, reverse = true)

    fun blockCmdsBackwardSeq(b : NBId) =
        lcmdSequence(b, reverse = true)

    fun blockCmdsForwardFrom(p : CmdPointer) =
        lcmdSequence(p.block, low = p.pos)

    fun iterateUntil(end: CmdPointer) =
        lcmdSequence(end.block, high = end.pos - 1).asIterable()

    /**
     * Going backwards from [end] - 1, returns the element satisfying [pred] within the block,
     * or null if none is found.
     */
    inline fun findLastUntil(end: CmdPointer, pred: (


nts p,#title-block-header.quarto-title-block.default .quarto-title-authors p,#title-block-header.quarto-title-block.default .quarto-title-affiliations p{margin-bottom:.1em}#title-block-header.quarto-title-block.default .quarto-title-meta-heading{text-transform:uppercase;margin-top:1em;font-size:.8em;opacity:.8;font-weight:400}#title-block-header.quarto-title-block.default .quarto-title-meta-contents{font-size:.9em}#title-block-header.quarto-title-block.default .quarto-title-meta-contents p.affiliation:last-of-type{margin-bottom:.1em}#title-block-header.quarto-title-block.default p.affiliation{margin-bottom:.1em}#title-block-header.quarto-title-block.default .keywords,#title-block-header.quarto-title-block.default .description,#title-block-header.quarto-title-block.default .abstract{margin-top:0}#title-block-header.quarto-title-block.default .keywords>p,#title-block-header.quarto-title-block.default .description>p,#title-block-header.quarto-title-block.default .abstract>p{font-size:.9em}#title-block-header.quarto-title-block.default .keywords>p:last-of-type,#title-block-header.quarto-title-block.default .description>p:last-of-type,#title-block-header.quarto-title-block.default .abstract>p:last-of-type{margin-bottom:0}#title-block-header.quarto-title-block.default .keywords .block-title,#title-block-header.quarto-title-block.default .description .block-title,#title-block-header.quarto-title-block.default .abstract .block-title{margin-top:1em;text-transform:uppercase;font-size:.8em;opacity:.8;font-weight:400}#title-block-header.quarto-title-block.default .quarto-title-meta-author{display:grid;grid-template-columns:minmax(max-content, 1fr) 1fr;grid-column-gap:1em}.quarto-title-tools-only{display:flex;justify-content:right}
/*!
 * Bootstrap  v5.3.1 (https://getbootstrap.com/)
 * Copyright 2011-2023 The Bootstrap Authors
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
 */:root,[data-bs-theme=light]{--bs-blue: #0d6efd;--bs-indigo: #6610f2;--bs-purple: #6f42c1;--bs-pink: #d63384;--bs-red: #dc3545;--bs-orange: #fd7e14;--bs-yellow: #ffc107;--bs-green: #198754;--bs-teal: #20c997;--bs-cyan: #0dcaf0;--bs-black: #000;--bs-white: #ffffff;--bs-gray: #6c757d;--bs-gray-dark: #343a40;--bs-gray-100: #f8f9fa;--bs-gray-200: #e9ecef;--bs-gray-300: #dee2e6;--bs-gray-400: #ced4da;--bs-gray-500: #adb5bd;--bs-gray-600: #6c757d;--bs-gray-700: #495057;--bs-gray-800: #343a40;--bs-gray-900: #212529;--bs-default: #dee2e6;--bs-primary: #0d6efd;--bs-secondary: #6c757d;--bs-success:


color=${cor0}>【牌型说明】</c>
<color=${cor1}>    1.火箭最大，即双王（大王和小王）可以打任意其他的牌。
    2.炸弹比火箭小，比其他牌大，都是炸弹的时候按牌的点数比大小。
    3.除火箭和炸弹外，其他牌必须要牌型相同且总张数相同才能比大小。
    4.单牌：按牌的点数，2>A>K>Q>J>10>9>8>7>6>5>4>3，不分花色。
    5.对牌：数值相同的两张牌（如：44）。
    6.三张牌：数值相同的三张牌（如：JJJ）。
    7.三带一，三带二，按三个相同的点数比。带的牌的不影响大小。
    8.单顺子，双顺子，三顺子，按顺子的最大点数。
    9.飞机带翅膀，四带二，按其中的最大的三张，或四张点数来比大小。</c>
                `;
            case GameId.JH:
                return `<color=${cor0}>【基本规则】</c>
<color=${cor1}>    1.开局：系统自动扣除玩家底注。
    2.发牌：从庄家开始发牌，每人发三张牌。
    3.流程：2~5人，从庄家开始，逆时针轮流说话，玩家可加注、跟注、看牌、弃牌、比牌、全押。
    4.轮数：一共20轮，首轮必须闷牌。
    5.看牌：第一轮押注结束后，第二轮开始才能看牌，看牌后，跟注、加注、比牌都需要双倍筹码。
    6.弃牌：未看牌的玩家在弃牌后可以看到自己的牌。
    7.比牌：第一轮过后玩家可以比牌，获胜者继续游戏，失败者结束游戏。两家牌型大小相同时，主动比牌者负。
    8.跟注：下注跟上一个玩家同样的下注筹码。
    9.加注：下注比上一个玩家更大的下注筹码。
    10.全押：第二轮过后允许玩家全押筹码（但不超过该房间上限）。
    11.胜负：大多数情况下，每局只有一个赢家，最后胜出者赢得本局的全部筹码。
    12.庄家：本游戏不采取轮庄制。上局胜者为庄家，如庄家离开，随机选定庄家。
    公平起见，第19轮后禁止使用“全押”功能。第20轮，在场的玩家各自下1注当前注，系统强制比牌。
    特殊情况：系统强制比牌，如有多个玩家牌型相同且最大时，如有庄家，庄家胜利；如没有庄家，则该多个玩家平分全部筹码。</c


	dur := time.Since(start)
		m.l.Debugf("Selected %d rows from pg_stat_statements in %s: %d new (%d shared tables), %d old.", totalN, dur, newN, newSharedN, oldN)
	}()

	current := make(statementsMap, m.statementsCache.cache.Len())
	prev := make(statementsMap, m.statementsCache.cache.Len())
	if err := m.statementsCache.Get(prev); err != nil {
		return nil, nil, err
	}

	q := m.q

	// load all databases and usernames first as we can't use querier while iterating over rows below
	databases := queryDatabases(q)
	usernames := queryUsernames(q)

	pgStatVersion, err := getPgStatVersion(q)
	if err != nil {
		return nil, nil, err
	}

	row, view := newPgStatMonitorStructs(pgStatVersion)
	columns := strings.Join(q.QualifiedColumns(view), ", ")

	rows, err := q.Query(fmt.Sprintf("SELECT /* %s */ %s FROM %s %s", queryTag, columns, q.QualifiedView(view), "WHERE queryid IS NOT NULL AND query IS NOT NULL"))
	if err != nil {
		return nil, nil, errors.Wrap(err, "couldn't get rows from pg_stat_statements")
	}
	defer rows.Close() //nolint:errcheck

	for ctx.Err() == nil {
		if err = q.NextRow(row, rows); err != nil {
			if errors.Is(err, reform.ErrNoRows) {
				err = nil
			}
			break
		}
		totalN++
		c := &pgStatStatementsExtended{
			pgStatStatements: *row,
			Database:         databases[row.DBID],
			Username:         usernames[row.UserID],
			RealQuery:        row.Query,
		}

		if p := prev[c.QueryID]; p != nil {
			oldN++
			newSharedN++

			c.Tables = p.Tables
			c.Query, c.IsQueryTruncated = p.Query, p.IsQueryTruncated
		} else {
			newN++

			c.Query, c.IsQueryTruncated = truncate.Query(c.Query, m.maxQueryLength, truncate.GetDefaultMaxQueryLength())
		}

		current[c.QueryID] = c
	}
	if ctx.Err() != nil {
		err = ctx.Err()
	}
	if err != nil {
		err = errors.Wrap(err, "failed to fetch pg_stat_statements")
	}

	return current, prev, err
}

func (m *PGStatStatementsQAN) getNewBuckets(ctx context.Context, periodStart time.Time, periodLengthSecs uint32) ([]*agentv1.MetricsBucket, error) {
	current, prev, err := m.getStatStatementsExtended(ctx)
	if err != nil {
		return nil, err
	}

	buckets := m.makeBuckets(current, prev)
	startS := uint32(periodStart.Unix())
	m.l.Debugf("Made %d buckets out of %d stat statements in %s+%d interval.",
		len(buckets), len(current), periodStart.Format("15:04:05"), periodLengthSecs)

	// merge prev and current in cache
	if err = m.statementsCache.Set(current); err != nil {
		return nil, err
	}
	m.l.Debugf("statStatementsCache: %s", m.statementsCache.cache.Stats())

	// add agent_id and timestamps
	for i, b := range buckets {
		b.Common.AgentId = m.agentID
		b.Common.PeriodStartUnixSecs = startS
		b.Common.PeriodLengthSecs = periodLengthSecs

		buckets[i] = b
	}

	return buckets, nil
}

// makeBuckets uses current state of pg_stat_statements table and accumulated previous state
// to make metrics buckets. It's a pure function for easier testing.
func (m *PGStat


 your option) any later version.
 *
 * LiquidBounce is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with LiquidBounce. If not, see <https://www.gnu.org/licenses/>.
 */
package net.ccbluex.liquidbounce.features.module.modules.exploit.phase.modes

import net.ccbluex.liquidbounce.config.types.nesting.Choice
import net.ccbluex.liquidbounce.config.types.nesting.ChoiceConfigurable
import net.ccbluex.liquidbounce.event.events.BlockShapeEvent
import net.ccbluex.liquidbounce.event.handler
import net.ccbluex.liquidbounce.event.tickHandler
import net.ccbluex.liquidbounce.features.module.modules.exploit.phase.ModulePhase
import net.ccbluex.liquidbounce.utils.entity.withStrafe
import net.minecraft.block.FluidBlock
import net.minecraft.util.shape.VoxelShapes

/**
 * @anticheat UNCP + Verus + "Watchdog"
 * @anticheatVersion 14.07.2025
 * @testedOn blocksmc.com
 * @author liquidsquid1
 */
object PhaseBlocksMC : Choice("BlocksMC") {

    override val parent: ChoiceConfigurable<*>
        get() = ModulePhase.mode

    private var spiderTicks = 1

    override fun enable() {
        spiderTicks = 1
        player.velocity.y = 0.0
        super.enable()
    }

    @Suppress("unused")
    private val tickHandler = tickHandler {
        when (spiderTicks) {
            1 -> {
                if (mc.options.jumpKey.isPressed && !world.getBlockState(player.blockPos).isAir) {
                    player.velocity.y = 0.42
                    spiderTicks++
                }
                player.isOnGround = true
            }
            2 -> {
                player.velocity.y = 0.33
                spiderTicks++
            }
            3 -> {
                player.velocity.y = 0.25
                spiderTicks++
            }
        }

        if (spiderTicks > 3 || spiderTicks == 0) {
            spiderTicks = 1
        }
        player.noClip = true
        if (player.isSneaking) {
            player.velocity = player.velocity.withStrafe(speed = 0.179)
        }
    }

    @Suppress("unused")
    private val shapeHandler = handler<BlockShapeEvent> { event ->
        if (event.state.block is FluidBlock) {
            return@handler
        }

        if (event.pos.y >= player.y) {
            event.shape = VoxelShapes.empty()
        }
    }

}
package net.ccbluex.liquidbounce.features.module.modules.combat.elytratarget

import net.ccbluex.liquidbounce.config.types.nesting.ToggleableConfigurable
import net.ccbluex.liquidbounce.event.waitTicks
import net.ccbluex.liquidbounce.event.tickHandler
import net.ccbluex.liquidbounce.utils.client.Chronometer
import net.ccbluex.liquidbounce.utils.entity.squaredBoxedDistanceTo
import net.ccbluex.liquidbounce.utils.inventory.Slots
import net.minecraft.item.Items
import net.ccbluex.liquidbounce.features.module.modules.combat.killaura.ModuleKillAura as KillAura

private const val MILLISECONDS_PER_TICK = 50

/**
 * Initial firework cooldown
 */
@Suppress("MagicNumber")
private var fireworkCooldown = 750

private val fireworkChronometer = Chronometer()

@Suppress("MagicNumber")
internal object AutoFirework : ToggleableConfigurable(ModuleElytraTarget, "AutoFirework", true) {
    private val useMode by enumChoice("UseMode", FireworkUs


            onPressed: () => IrmaRepositoryProvider.of(context).openIssueURL(
              context,
              type.fullId,
            ),
          ),
        );
      }
    } else if (!valid || isTemplate) {
      return InformationBox(
        message: FlutterI18n.translate(
          context,
          'credential.not_obtainable',
          translationParams: {
            'issuerName': issuer.name.translate(FlutterI18n.currentLocale(context)!.languageCode),
          },
        ),
      );
    }
    return Container();
  }
}
/*
 * privacyIDEA Authenticator
 *
 * Author: Frank Merkel <frank.merkel@netknights.it>
 *
 * Copyright (c) 2024-2025 NetKnights GmbH
 *
 * 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.
 */

import 'dart:convert';

import 'package:cryptography/cryptography.dart';
import 'package:http/http.dart';
import 'package:mockito/mockito.dart';
import 'package:privacyidea_authenticator/api/impl/privacy_idea_container_api.dart';
import 'package:privacyidea_authenticator/model/container_policies.dart';
import 'package:privacyidea_authenticator/model/enums/algorithms.dart';
import 'package:privacyidea_authenticator/model/enums/ec_key_algorithm.dart';
import 'package:privacyidea_authenticator/model/enums/rollout_state.dart';
import 'package:privacyidea_authenticator/model/enums/sync_state.dart';
import 'package:privacyidea_authenticator/model/riverpod_states/token_state.dart';
import 'package:privacyidea_authenticator/model/token_container.dart';
import 'package:privacyidea_authenticator/model/tokens/hotp_token.dart';
import 'package:privacyidea_authenticator/model/tokens/totp_token.dart';
import 'package:privacyidea_authenticator/utils/ecc_utils.dart';
import 'package:privacyidea_authenticator/utils/logger.dart';
import 'package:test/test.dart';

import '../../tests_app_wrapper.mocks.dart';

void main() {
  _testPrivacyIdeaContainerApi();
}

void _testPrivacyIdeaContainerApi() {
  final exampleError = {
    'id': 5,


  using Executor =
      internal::TensorExecutor<const Assign, Device, Vectorizable, Tiling>;

  Executor::run(Assign(dst, expr), d);

  for (Index i = 0; i < dst.dimensions().TotalSize(); ++i) {
    VERIFY_IS_EQUAL(dst.coeff(i), golden.coeff(i));
  }
}

template<typename T, int NumDims>
struct DummyGenerator {
  EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE
  T operator()(const array <Index, NumDims>& dims) const {
    T result = static_cast<T>(0);
    for (int i = 0; i < NumDims; ++i) {
      result += static_cast<T>((i + 1) * dims[i]);
    }
    return result;
  }
};

template <typename T, int NumDims, typename Device, bool Vectorizable,
    TiledEvaluation Tiling, int Layout>
static void test_execute_generator_op(Device d)
{
  static constexpr int Options = 0 | Layout;

  auto dims = RandomDims<NumDims>(20, 30);
  Tensor<T, NumDims, Options, Index> src(dims);
  src.setRandom();

  const auto expr = src.generate(DummyGenerator<T, NumDims>());

  // We assume that generator on a default device is tested and correct, so
  // we can rely on it to verify correctness of tensor executor and tiling.
  Tensor<T, NumDims, Options, Index> golden;
  golden = expr;

  // Now do the broadcasting using configured tensor executor.
  Tensor<T, NumDims, Options, Index> dst(golden.dimensions());

  using Assign = TensorAssignOp<decltype(dst), const decltype(expr)>;
  using Executor =
    internal::TensorExecutor<const Assign, Device, Vectorizable, Tiling>;

  Executor::run(Assign(dst, expr), d);

  for (Index i = 0; i < dst.dimensions().TotalSize(); ++i) {
    VERIFY_IS_EQUAL(dst.coeff(i), golden.coeff(i));
  }
}

template <typename T, int NumDims, typename Device, bool Vectorizable,
    TiledEvaluation Tiling, int Layout>
static void test_execute_reverse_rvalue(Device d)
{
  static constexpr int Options = 0 | Layout;

  auto dims = RandomDims<NumDims>(1, numext::pow(1000000.0, 1.0 / NumDims));
  Tensor <T, NumDims, Options, Index> src(dims);
  src.setRandom();

  // Reverse half of the dimensions.
  Eigen::array<bool, NumDims> reverse;
  for (int i = 0; i < NumDims; ++i) reverse[i] = internal::random<bool>();

  const auto expr = src.reverse(reverse);

  // We assume that reversing on a default device is tested and correct, so
  // we can rely on it to verify correctness of tensor executor and tiling.
  Tensor <T, NumDims, Options, Index> golden;
  golden = expr;

  // Now do the reversing using configured tensor executor.
  Tensor <T, NumDims, Options, Index> dst(golden.dimensions());

  using Assign = TensorAssignOp<decltype(dst), const decltype(expr)>;
  using Executor =
    internal::TensorExecutor<const Assign, Device, Vectorizable, Tiling>;

  Executor::run(Assign(dst, expr), d);

  for (Index i = 0; i < dst.dimensions().TotalSize(); ++i) {
    VERIFY_IS_EQUAL(dst.coeff(i), golden.coeff(i));
  }
}

template <typename T, int NumDims, typename Device, bool Vectorizable,
          TiledEvaluation Tiling, int Layout>
static void test_async_execute_unary_expr(Device d)
{
  static constexpr int Options = 0 | Layout;

  //


wKVbGsWzrRc6R0NUTeZAQA=') format('woff2'),
  url('iconfont.woff?t=1551432116107') format('woff'),
  url('iconfont.ttf?t=1551432116107') format('truetype'), /* chrome, firefox, opera, Safari, Android, iOS 4.2+ */
  url('iconfont.svg?t=1551432116107#iconfont') format('svg'); /* iOS 4.1- */
}

.iconfont {
  font-family: "iconfont" !important;
  font-size: 16px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.layui-extend-githup:before {
  content: "\e6be";
}

/** layui-v2.4.5 MIT License By https://www.layui.com */
 .laydate-set-ym,.layui-laydate,.layui-laydate *,.layui-laydate-list{box-sizing:border-box}html #layuicss-laydate{display:none;position:absolute;width:1989px}.layui-laydate *{margin:0;padding:0}.layui-laydate{position:absolute;z-index:66666666;margin:5px 0;border-radius:2px;font-size:14px;-webkit-animation-duration:.3s;animation-duration:.3s;-webkit-animation-fill-mode:both;animation-fill-mode:both;-webkit-animation-name:laydate-upbit;animation-name:laydate-upbit}.layui-laydate-main{width:272px}.layui-laydate-content td,.layui-laydate-header *,.layui-laydate-list li{transition-duration:.3s;-webkit-transition-duration:.3s}@-webkit-keyframes laydate-upbit{from{-webkit-transform:translate3d(0,20px,0);opacity:.3}to{-webkit-transform:translate3d(0,0,0);opacity:1}}@keyframes laydate-upbit{from{transform:translate3d(0,20px,0);opacity:.3}to{transform:translate3d(0,0,0);opacity:1}}.layui-laydate-static{position:relative;z-index:0;display:inline-block;margin:0;-webkit-animation:none;animation:none}.laydate-ym-show .laydate-next-m,.laydate-ym-show .laydate-prev-m{display:none!important}.laydate-ym-show .laydate-next-y,.laydate-ym-show .laydate-prev-y{display:inline-block!important}.laydate-time-show .laydate-set-ym span[lay-type=month],.laydate-time-show .laydate-set-ym span[lay-type=year],.laydate-time-show .layui-laydate-header .layui-icon,.laydate-ym-show .laydate-set-ym span[lay-type=month]{display:none!important}.layui-laydate-header{position:relative;line-height:30px;padding:10px 70px 5px}.laydate-set-ym span,.layui-laydate


2 330.5 99.54 282.5L254.1 128L240.1 114.9z"/></svg></g>
    <g id="font-awesome-solid:pen-fancy"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.1.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M373.5 27.11C388.5 9.885 410.2 0 433 0C476.6 0 512 35.36 512 78.98C512 101.8 502.1 123.5 484.9 138.5L277.7 319L192.1 234.3L373.5 27.11zM255.1 341.7L235.9 425.1C231.9 442.2 218.9 455.8 202 460.5L24.35 510.3L119.7 414.9C122.4 415.6 125.1 416 128 416C145.7 416 160 401.7 160 384C160 366.3 145.7 352 128 352C110.3 352 96 366.3 96 384C96 386.9 96.38 389.6 97.08 392.3L1.724 487.6L51.47 309.1C56.21 293.1 69.8 280.1 86.9 276.1L170.3 256.9L255.1 341.7z"/></svg></g>
    <g id="font-awesome-solid:pen-nib"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.1.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M368.4 18.34C390.3-3.526 425.7-3.526 447.6 18.34L493.7 64.4C515.5 86.27 515.5 121.7 493.7 143.6L437.9 199.3L312.7 74.06L368.4 18.34zM417.4 224L371.4 377.3C365.4 397.2 350.2 413 330.5 419.6L66.17 508.2C54.83 512 42.32 509.2 33.74 500.9L187.3 347.3C193.6 350.3 200.6 352 207.1 352C234.5 352 255.1 330.5 255.1 304C255.1 277.5 234.5 256 207.1 256C181.5 256 159.1 277.5 159.1 304C159.1 311.4 161.7 318.4 164.7 324.7L11.11 478.3C2.809 469.7-.04 457.2 3.765 445.8L92.39 181.5C98.1 161.8 114.8 146.6 134.7 140.6L287.1 94.6L417.4 224z"/></svg></g>
    <g id="font-awesome-solid:pen-ruler"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><!--! Font Awesome Free 6.1.2 by @fontawesome - https://fontawesome.com License - https://fontawesome.com/license/free (Icons: CC BY 4.0, Fonts: SIL OFL 1.1, Code: MIT License) Copyright 2022 Fonticons, Inc. --><path d="M492.7 42.75C517.7 67.74 517.7 108.3 492.7 133.3L436.3 189.7L322.3 75.72L378.7 19.32C403.7-5.678 444.3-5.678 469.3 19.32L492.7 42.


neos-module input[type=tel].neos-modified,.neos.neos-module input[type=color].neos-modified,.neos.neos-module input[type=number].neos-modified,.neos.neos-module .neos-uneditable-input.neos-modified{border:2px solid #00a338}.neos.neos-module textarea{border:2px solid #3f3f3f;background-color:#3f3f3f;color:#fff;font-family:"Noto Sans",sans-serif;-webkit-font-smoothing:antialiased;font-size:14px;padding:0 14px;margin:0;box-sizing:border-box;box-shadow:none;transition:none;border-radius:0px}.neos.neos-module textarea:focus{background-color:#fff;border:2px solid #fff;color:#252525;outline:none;box-shadow:none}.neos.neos-module textarea.neos-modified{border:2px solid #00a338}.neos.neos-module .neos-select{position:relative;background-color:#3f3f3f}.neos.neos-module .neos-select:focus{outline:none}.neos.neos-module .neos-select:focus:after{color:#252525}.neos.neos-module .neos-select:before{display:block;content:"";position:absolute;width:1px;height:24px;top:8px;right:41px;background-color:#fff;opacity:.15}.neos.neos-module .neos-select:after{content:"";display:block;position:absolute;right:0;top:0;width:40px;line-height:40px;text-align:center}.neos.neos-module .neos-select select{appearance:none;-webkit-border-radius:0px;-o-appearance:window;-moz-appearance:window;background-color:rgba(0,0,0,0);line-height:1;padding:7px 14px;width:100%;position:relative;z-index:1}.neos.neos-module .neos-select select:focus{color:#fff;background-color:rgba(0,0,0,0);border-color:rgba(0,0,0,0)}.neos.neos-module .neos-select option{appearance:none;-webkit-border-radius:0px;background-color:#3f3f3f}.neos.neos-module .neos-footer{position:sticky;height:72px;background-color:#141414;margin:40px -54px -40px;border-top:1px solid #3f3f3f;padding:16px;font-size:0;bottom:0;z-index:100;overflow:hidden;box-sizing:border-box}.neos.neos-module .neos-footer:after{content:"";display:table;clear:both}.neos.neos-module .neos-footer.fixedsticky-on{width:100%;position:-webkit-sticky;position:-moz-sticky;position:-ms-sticky;position:-o-sticky;position:sticky;margin-bottom:0}.fixedsticky-withoutfixedfixed .neos.neos-module .neos-footer.fixedsticky-on,.fixed-supported .neos.neos-module .neos-footer.fixedsticky-on{position:fixed}.fixedsticky-withoutfixedfixed .neos.neos-module .neos-footer.fixedsticky-off,.fixed-supported .neos.neos-module .neos-footer.fixedsticky-off{position:static}.neos.neos-module .neos-footer.fixedsticky-on+.fixedsticky-dummy{display:block}@media screen and (max-width: 1024px)and (max-height: 768px){.neos.neos-module .neos-footer{padding:0}}.neos.neos-module .neos-footer .neos-button{margin-right:8px}.neos.neos-module .neos-footer .neos-modal .


讲到 webpack 是从 `webpack/bin/webpack` 开始启动的，但是如果我们使用了 `webpack-dev-server`，那么就是从 `webpack-dev-server/bin/webpack-dev-server.js` 启动的。

![dev-server](./images/dev-server.png)

如上图所示，`webpack-dev-server` 包含了三部分：

* webpack, 负责编译代码
* webpack-dev-server，主要提供了 in-memory 内存文件系统，他会把webpack的outputFileSystem 替换成一个 inMemoryFileSystem，并且拦截全部的浏览器请求，从这个文件系统中把结果取出来返回。
* express，作为服务器

先来总结下 webpack 在server端进行热更新的流程

初始化阶段：
1, webpack-dev-server 初始化的时候
* var compiler = webpack(options) // 创建 webpack 实例
* 监听  compiler 也就是 webpack 的 `done` 事件
* 创建 express 实例
* 创建 WebpackDevMiddleware 实例
* 设置 express router，WebpackDevServer 会作为 express的一个中间件拦截所有请求

2, WebpackDevMiddleware 在初始化的时候
* 创建 一个 MemoryFileSystem  实例，替换掉 webpack.outputFileSystem，这样 webpack 编译出的文件其实都是存在内存中，而不是磁盘上
* 把对编译后的文件的请求，都重定向到上面创建的 `MemoryFileSystem` 中

热更新阶段：
1, webpack 监听文件变化，并完成编译
2, webpack-dev-server 监听 `done` 事件，并通过 `websocket` 向客户端发送消息
3, 客户端经过处理后，请求新的JS模块代码
4, WebpackDevServer 从 MemoryFileSystem 中取出代码，并返回

下面我们来看看代码：

初始化阶段，`webpack-dev-server.js` 会创建一个 `webpack` 实例：

```js
  let compiler;
  try {
    compiler = webpack(webpackOptions);
  } catch (e) {
  }
  let server;
  try {
    server = new Server(compiler, options);
  } catch (e) {
  }
```

接着，`webpack-dev-server/lib/Server.js` 会创建 express 和 WebpackDevMiddleware：

```js
function Server(compiler, options) {
  compiler.plugin('done', (stats) => {
    this._sendStats(this.sockets, stats.toJson(clientStats)); // 当完成编译的时候，就通过 websocket 发送给客户端一个消息（一个 `hash` 和 一个`ok`)
    this._stats = stats;
  });

  // Init express server
  const app = this.app = new express(); // eslint-disable-line

  // middleware for serving webpack bundle
  this.middleware = webpackDevMiddleware(compiler, options);
}

// 后面会有一行
app.use(this.middleware); // middleware会拦截所有请求，如果发现对应的请求是要请求 `dist` 中的文件，则会进行处理。
```

在热更新阶段，首先会触发这几行代码：

```js
  compiler.plugin('done', (stats) => {
    this._sendStats(this.sockets, stats.toJson(clientStats));
    this._stats = stats;
  });
```

`_sendStats` 会通过 websocket 给客户端发送两条消息。
客户端收到消息后，会去请求一个 json 配置文件，然后根据配置请求新的JS模块代码。这些请求都会被 `W


------
// EXERCISE: Students
//
//  Create a program that returns the students by the given
//  Hogwarts house name (see the data below).
//
//  Print the students sorted by name.
//
//  "bobo" doesn't belong to Hogwarts, remove it by using
//  the delete function.
//
//
// RESTRICTIONS
//
//  + Add the following data to your map as is.
//    Do not sort it manually and do not modify it.
//
//  + Slices in the map shouldn't be sorted (changed).
//    HINT: Copy them.
//
//
// EXPECTED OUTPUT
//
//  go run main.go
//
//  Please type a Hogwarts house name.
//
//
//  go run main.go bobo
//
//  Sorry. I don't know anything about "bobo".
//
//
//  go run main.go hufflepuf
//
//  ~~~ hufflepuf students ~~~
//
//        + diggory
//        + helga
//        + scamander
//        + wenlock
//
// ---------------------------------------------------------

func main() {
	// House        Student Name
	// ---------------------------
	// gryffindor   weasley
	// gryffindor   hagrid
	// gryffindor   dumbledore
	// gryffindor   lupin
	// hufflepuf    wenlock
	// hufflepuf    scamander
	// hufflepuf    helga
	// hufflepuf    diggory
	// ravenclaw    flitwick
	// ravenclaw    bagnold
	// ravenclaw    wildsmith
	// ravenclaw    montmorency
	// slytherin    horace
	// slytherin    nigellus
	// slytherin    higgs
	// slytherin    scorpius
	// bobo         wizardry
	// bobo         unwanted
}
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
// For more tutorials  : https://learngoprogramming.com
// In-person training  : https://www.linkedin.com/in/inancgumus/
// Follow me on twitter: https://twitter.com/inancgumus

package main

import (
	"fmt"
	"math"
	"os"
	"strconv"
)

// This program contains a lot of comments
// Non-commented version is in /without-comments/main.go

func main() {
	// You cannot use this syntax.
	//
	// feetInMeters is declared
	//   when the declaration completes,
	//   (at the end of the whole declaration)
	//
	// And, it's not easy to read
	//
	// const feetInMeters, feetInYards float64 = 0.3048,
	//   feetInMeters / 0.9144

	const (
		feetInMeters = 0.3048
		feetInYards  = feetInMeters / 0.9144

		// cannot call runtime funcs
		// feetInYards = math.Round(feetInYards)
	)

	// Immutable: You cannot assign new values
	// feetInYards = 0.333333

	arg := os.Args[1]

	feet, _ := strconv.ParseFloat(arg, 64)

	meters := feet * feetInMeters
	yards := math.Round(feet * feetInYards)

	fmt.Printf("%g feet is %g meters.\n", feet, meters)
	fmt.Printf("%g feet is %g yards.\n", feet, yards)
}
// Squaring numbers.

package main

import (
	"fmt"
	"sync"
)

func generator(done <-chan struct{}, nums ...int) <-chan int {
	out := make(chan int)

	go func() {
		defer close(out)
		for _, n := range nums {


rZXkiLCJwYXJhbGxlbFJvdXRlU3RhdGUiLCJzZWdtZW50Rm9yUGFyYWxsZWxSb3V0ZSIsImNhY2hlS2V5IiwiY3JlYXRlUm91dGVyQ2FjaGVLZXkiLCJwYXJhbGxlbFNlZWREYXRhIiwidW5kZWZpbmVkIiwiZXhpc3RpbmdQYXJhbGxlbFJvdXRlc0NhY2hlTm9kZSIsInBhcmFsbGVsUm91dGVzIiwiZ2V0IiwiaGFzUmV1c2FibGVQcmVmZXRjaCIsImtpbmQiLCJzdGF0dXMiLCJQcmVmZXRjaENhY2hlRW50cnlTdGF0dXMiLCJyZXVzYWJsZSIsInBhcmFsbGVsUm91dGVDYWNoZU5vZGUiLCJNYXAiLCJleGlzdGluZ0NhY2hlTm9kZSIsIm5ld0NhY2hlTm9kZSIsInNlZWROb2RlIiwibG9hZGluZyIsImxhenlEYXRhIiwicnNjIiwicHJlZmV0Y2hSc2MiLCJwcmVmZXRjaEhlYWQiLCJsYXp5RGF0YVJlc29sdmVkIiwic2V0IiwiZXhpc3RpbmdQYXJhbGxlbFJvdXRlcyJdLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///(ssr)/./node_modules/next/dist/client/components/router-reducer/fill-lazy-items-till-leaf-with-head.js\n");

/***/ }),

/***/ "(ssr)/./node_modules/next/dist/client/components/router-reducer/handle-mutable.js":
/*!***********************************************************************************!*\
  !*** ./node_modules/next/dist/client/components/router-reducer/handle-mutable.js ***!
  \***********************************************************************************/
/***/ ((module, exports, __webpack_require__) => {

"use strict";
eval("\nObject.defineProperty(exports, \"__esModule\", ({\n    value: true\n}));\nObject.defineProperty(exports, \"handleMutable\", ({\n    enumerable: true,\n    get: function() {\n        return handleMutable;\n    }\n}));\nconst _computechangedpath = __webpack_require__(/*! ./compute-changed-path */ \"(ssr)/./node_modules/next/dist/client/components/router-reducer/compute-changed-path.js\");\nfunction isNotUndefined(value) {\n    return typeof value !== \"undefined\";\n}\nfunction handleMutable(state, mutable) {\n    var _mutable_canonicalUrl;\n    var _mutable_shouldScroll;\n    // shouldScroll is true by default, can override to false.\n    const shouldScroll = (_mutable_shouldScroll = mutable.shouldScroll) != null ? _mutable_shouldScroll : true;\n    let nextUrl = state.nextUrl;\n    if (isNotUndefined(mutable.patchedTree)) {\n        // If we received a patched tree, we need to compute the changed path.\n        const changedPath = (0, _computechangedpath.computeChangedPath)(state.tree, mutable.patchedTree);\n        if (changedPath) {\n            // If the tree changed, we need to update the nextUrl\n            nextUrl = changedPath;\n        } else if (!nextUrl) {\n            // if the tree ends up being the same (ie, no changed path), and we don't have a nextUrl, then we should use the canonicalUrl\n            nextUrl = state.canonicalUrl;\n        }\n    // otherwise this will be a no-op and continue to use the existing nextUrl\n    }\n    var _mutable_scrollableSegments;\n    return {\n        buildId: state.buildId,\n        // Set href.\n        ca


/*
    #include <arpa/inet.h>
    // p:点分十进制的IP字符串，n:表示network，网络字节序的整数
    int inet_pton(int af, const char *src, void *dst);
        af:地址族： AF_INET  AF_INET6
        src:需要转换的点分十进制的IP字符串
        dst:转换后的结果保存在这个里面

    // 将网络字节序的整数，转换成点分十进制的IP地址字符串
    const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
        af:地址族： AF_INET  AF_INET6
        src: 要转换的ip的整数的地址
        dst: 转换成IP地址字符串保存的地方
        size：第三个参数的大小（数组的大小）
        返回值：返回转换后的数据的地址（字符串），和 dst 是一样的

*/

#include <stdio.h>
#include <arpa/inet.h>

int main() {

    // 创建一个ip字符串,点分十进制的IP地址字符串
    char buf[] = "192.168.1.4";
    unsigned int num = 0;

    // 将点分十进制的IP字符串转换成网络字节序的整数
    inet_pton(AF_INET, buf, &num);
    unsigned char * p = (unsigned char *)#
    printf("%d %d %d %d\n", *p, *(p+1), *(p+2), *(p+3));

    // 将网络字节序的IP整数转换成点分十进制的IP字符串
    char ip[16] = "";
    const char * str =  inet_ntop(AF_INET, &num, ip, 16);
    printf("str : %s\n", str);
    printf("ip : %s\n", str);
    printf("%d\n", ip == str);

    return 0;
}


//         ? Provider<ArticleListItem>.value(
        //             value: ArticleListItem.fromArticleListItem(
        //               queryResult: snapshot.data.$1[0],
        //               showDetail: true,
        //               addBottomPadding: false,
        //               width: (width - 16),
        //               thumbnailTag: Uuid().v4(),
        //             ),
        //             child: ArticleListItemVerySimpleWidget(),
        //           )
        //         : Container(),
        //     Row(
        //       mainAxisAlignment: MainAxisAlignment.spaceBetween,
        //       // crossAxisAlignment: CrossAxisAlignment,
        //       children: <Widget>[
        //         // Flexible(
        //         //     child: Text(
        //         //         ' ' +
        //         //             unescape.convert(snapshot.hasData
        //         //                 ? snapshot.data.results[0].title()
        //         //                 : ''),
        //         //         style: TextStyle(fontSize: 17),
        //         //         overflow: TextOverflow.ellipsis)),
        //         Flexible(
        //           // child: Text(xx.datetimeStart().split(' ')[0]),
        //           child: Text(''),
        //         ),
        //         Text(
        //             xx.lastPage().toString() +
        //                 ' ${Translations.instance!.trans('readpage')} ',
        //             style: TextStyle(
        //               color: Settings.themeWhat.value
        //                   ? Colors.grey.shade300
        //                   : Colors.grey.shade700,
        //             )),
        //       ],
        //     ),
        //   ],
        // );
        //       },
        //     ),
        //   ),
        // );
        // return ListTile() Text(snapshot.data[index].articleId().toString());
      },
      //   );
      // },
    );
  }
}
// This source code is a part of Project Violet.
// Copyright (C) 2020-2024. violet-team. Licensed under the Apache-2.0 License.

import 'dart:async';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

class CustomDelayTapListener extends StatelessWidget {
  final VoidCallback onTap;
  final Duration delay;

  const CustomDelayTapListener({
    super.key,
    required this.onTap,
    required this.delay,
  });

  @override
  Widget build(BuildContext context) {
    return RawGestureDetector(
      behavior: HitTestBehavior.translucent,
      gestures: <Type, GestureRecognizerFactory>{
        _FastTapGestureRecognizer:
            GestureRecognizerFactoryWithHandlers<_FastTapGestureRecognizer>(
              () => _FastTapGestureRecognizer(delay),
              (_FastTapGestureRecognizer instance) {
                instance.onTap = onTap;
              },
            ),
      },
    );
  }
}

// https://github.com/flutter/flutter/issues/106170#issuecomment-1551417220

class _FastTapGestureRecognizer extends TapGestureRecognizer {
  final Duration delay;
  _FastTapGestureRecognizer(this.delay);

  /// Timer to keep track of the last tap up event
  Timer? _lastTapUpEvent;

  @override
  void handleEvent(PointerEvent event) {
    if (event is PointerDownEvent) {
      _lastTapUpEvent?.cancel();
      _lastTapUpEvent = null;
    }
    if (event is PointerUpEvent) {
      _lastTapUpEvent = Timer(delay, () {
        resolve(GestureDisposition.accepted);
        // acceptGesture(event.pointer);
      });
    }
    super.handleEvent(event);
  }
}
// This source code is a part of Project Vio


SigningOutput;
use aws_smithy_eventstream::frame::{write_headers_to, Header, HeaderValue, Message};
use bytes::Bytes;
use std::io::Write;
use std::time::SystemTime;

/// Event stream signing parameters
pub type SigningParams<'a> = super::SigningParams<'a, ()>;

/// Creates a string to sign for an Event Stream message.
fn calculate_string_to_sign(
    message_payload: &[u8],
    last_signature: &str,
    time: SystemTime,
    params: &SigningParams<'_>,
) -> Vec<u8> {
    // Event Stream string to sign format is documented here:
    // https://docs.aws.amazon.com/transcribe/latest/dg/how-streaming.html
    let date_time_str = format_date_time(time);
    let date_str = format_date(time);

    let mut sts: Vec<u8> = Vec::new();
    writeln!(sts, "AWS4-HMAC-SHA256-PAYLOAD").unwrap();
    writeln!(sts, "{}", date_time_str).unwrap();
    writeln!(
        sts,
        "{}/{}/{}/aws4_request",
        date_str, params.region, params.service_name
    )
    .unwrap();
    writeln!(sts, "{}", last_signature).unwrap();

    let date_header = Header::new(":date", HeaderValue::Timestamp(time.into()));
    let mut date_buffer = Vec::new();
    write_headers_to(&[date_header], &mut date_buffer).unwrap();
    writeln!(sts, "{}", sha256_hex_string(&date_buffer)).unwrap();
    write!(sts, "{}", sha256_hex_string(&message_payload)).unwrap();
    sts
}

/// Signs an Event Stream message with the given `credentials`.
///
/// Each message's signature incorporates the signature of the previous message (`last_signature`).
/// The very first message incorporates the signature of the top-level request
/// for both HTTP 2 and WebSocket.
pub fn sign_message<'a>(
    message: &'a Message,
    last_signature: &'a str,
    params: &'a SigningParams<'a>,
) -> SigningOutput<Message> {
    let message_payload = {
        let mut payload = Vec::new();
        message.write_to(&mut payload).unwrap();
        payload
    };
    sign_payload(Some(message_payload), last_signature, params)
}

/// Returns a signed empty message
///
/// Empty signed event stream messages differ from normal signed event stream
/// in that the payload is 0-bytes rather than a nested message. There is no way
/// to create a signed empty message using [`sign_message`].
pub fn sign_empty_message<'a>(
    last_signature: &'a str,
    params: &'a SigningParams<'a>,
) -> SigningOutput<Message> {
    sign_payload(None, last_signature, params)
}

fn sign_payload<'a>(
    message_payload: Option<Vec<u8>>,
    last_signature: &'a str,
    params: &'a SigningParams<'a>,
) -> SigningOutput<Message> {
    // Truncate the sub-seconds up front since the timestamp written to the signed message header
    // needs to exactly match the string formatted timestamp, which doesn't include sub-seconds.
    let time = truncate_subsecs(params.time);

    let signing_key =
        generate_signing_key(params.secret_key, time, params.region, params.service_name);
    let string_to_sign = calculate_string_to_sign(
        message_payload.as_ref().map(|v| &v[..]).unwrap_or(&[]),
        last_signature,
        time,
        params,
    );
    let signature = calculate_signature(signing_key, &string_to_sign);

    // Generate the signed wrapper event frame


ight ratios
    new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
    dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1]  # wh padding
    if auto:  # minimum rectangle # 获取最小的矩形填充
        dw, dh = np.mod(dw, 32), np.mod(dh, 32)  # wh padding
    # 如果scaleFill=True,则不进行填充，直接resize成img_size, 任由图片进行拉伸和压缩
    elif scaleFill:  # stretch
        dw, dh = 0.0, 0.0
        new_unpad = (new_shape[1], new_shape[0])
        ratio = new_shape[1] / shape[1], new_shape[0] / shape[0]  # width, height ratios
    # 计算上下左右填充大小
    dw /= 2  # divide padding into 2 sides
    dh /= 2

    if shape[::-1] != new_unpad:  # resize
        img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)
    top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
    left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
    # 进行填充
    img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color)  # add border
    return img, ratio, (dw, dh)

# 随机透视变换
# 计算方法为坐标向量和变换矩阵的乘积
def random_perspective(img, targets=(), degrees=10, translate=.1, scale=.1, shear=10, perspective=0.0, border=(0, 0)):
    # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10))
    # targets = [cls, xyxy]

    height = img.shape[0] + border[0] * 2  # shape(h,w,c)
    width = img.shape[1] + border[1] * 2

    # Center
    C = np.eye(3)
    C[0, 2] = -img.shape[1] / 2  # x translation (pixels)
    C[1, 2] = -img.shape[0] / 2  # y translation (pixels)

    # Perspective：透视变换
    P = np.eye(3)
    P[2, 0] = random.uniform(-perspective, perspective)  # x perspective (about y)
    P[2, 1] = random.uniform(-perspective, perspective)  # y perspective (about x)

    # Rotation and Scale # 设置旋转和缩放的仿射矩阵
    R = np.eye(3)
    a = random.uniform(-degrees, degrees)
    # a += random.choice([-180, -90, 0, 90])  # add 90deg rotations to small rotations
    s = random.uniform(1 - scale, 1 + scale)
    # s = 2 ** random.uniform(-scale, scale)
    R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)

    # Shear；设置裁剪的仿射矩阵系数
    S = np.eye(3)
    S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180)  # x shear (deg)
    S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180)  # y shear (deg)

    # Translation；设置平移的仿射矩阵系数
    T = np.eye(3)
    T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width  # x translation (pixels)
    T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height  # y translation (pixels)

    # Combined rotation matrix
    # 融合仿射矩阵并作用在图片上； @表示矩阵乘法运算
    M = T @ S @ R @ P @ C  # order of operations (right to left) is IMPORTANT
    if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any():  # image changed
        if perspective:
            # 透视变换函数，可保持直线不变形，但是平行线可能不再平行
            img = cv2.warpPerspective(img, M, dsize=(width, height), borderValue=(114, 114, 114))
        else:  # affine
            # 仿射变换函数，可实现旋转，平移，缩放；变换后的平行线依旧平行
            img = cv2.warpAffine(img, M[:2], dsize=(width, height), borderValue=(114, 114, 114))

    # Visualize
    # import matplotlib.pyplot as plt
    # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()
    # ax[0].imshow(img[:, :, ::-1])  # base
    # ax[1].imshow(img2[:, :, ::-1])  # warped

    # Transform label coordinates
    # 调整框的标签
    n = len(targets)
    if n:
        # warp points
        xy = np.ones((n * 4, 3))
        xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2)  # x1y1, x2y2, x1y2, x2y1
        xy = xy @ M.T  # transform
        if perspective:
            xy = (xy[:, :2] / xy[:, 2:3]).reshape(n, 8)  # rescale
        else:  # affine
            xy = xy[:, :2].reshape(n, 8)

        # create new boxes
        x = xy[:, [0, 2, 4, 6]]
        y = xy[:, [1, 3, 5, 7]]
        xy = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T

        # # apply angle-based reduction of bounding boxes
        # radians = a * math.pi / 180
        # reduction = max(abs(math.sin(radians)), abs(math.cos(radians))) ** 0.5
        # x = (xy[:, 2] + xy[:, 0]) / 2
        # y = (xy[:, 3] + xy[:, 1]) / 2
        # w = (xy[:, 2] - xy[:, 0]) * reduction
        # h = (xy[:, 3] - xy[:, 1]) * reduction
        # xy = np.concatenate((x - w / 2, y - h / 2, x + w / 2, y + h / 2)).reshape(4, n).T

        # clip boxes
        # 去除进行上面一系列操作后被裁剪过小的框；reject warped points outside of image
        xy[:, [0, 2]] = xy[:, [0, 2]].clip(


#!/usr/bin/env python
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#

__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"

import TestSCons

python = TestSCons.python
_python_ = TestSCons._python_

test = TestSCons.TestSCons()

test.write('build.py', r"""
import sys
with open(sys.argv[1], 'wb') as f, open(sys.argv[2], 'rb') as ifp:
    f.write(ifp.read())
sys.exit(0)
""")

test.write('SConstruct', """
B1 = Builder(action = [ [ r'%(python)s', 'build.py', '.temp', '$SOURCES' ],
                        [ r'%(python)s', 'build.py', '$TARGETS', '.temp'] ])
B2 = Builder(action = r'%(_python_)s' + ' build.py .temp $SOURCES\\n' + r'%(_python_)s' + " build.py $TARGETS .temp")
env = Environment(BUILDERS = { 'B1' : B1, 'B2' : B2 })
env.B1(target = 'foo1.out', source = 'foo1.in')
env.B2(target = 'foo2.out', source = 'foo2.in')
env.B1(target = 'foo3.out', source = 'foo3.in')
""" % locals())

test.write('foo1.in', "foo1.in\n")

test.write('foo2.in', "foo2.in\n")

test.write('foo3.in', "foo3.in\n")

test.run(arguments = 'foo1.out foo2.out foo3.out')

test.fail_test(test.read(test.workpath('foo1.out')) != b"foo1.in\n")
test.fail_test(test.read(test.workpath('foo2.out')) != b"foo2.in\n")
test.fail_test(test.read(test.workpath('foo3.out')) != b"foo3.in\n")

test.pass_test()

# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4:


#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Character.h"
#include "FPSCharacter.generated.h"

UCLASS()
class MULTIPLAYERFPS_API AFPSCharacter : public ACharacter
{
	GENERATED_BODY()

protected:

	// Components

	UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "FPS Character")
	class UCameraComponent* Camera;

	// Health

	UPROPERTY(Replicated, BlueprintReadOnly, Category = "FPS Character")
	float Health = 0.0f;

	UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "FPS Character")
	float MaxHealth = 100.0f;

	// Armor

	UPROPERTY(Replicated, BlueprintReadOnly, Category = "FPS Character")
	float Armor = 0.0f;

	UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "FPS Character")
	float MaxArmor = 100.0f;

	UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "FPS Character")
	float ArmorAbsorption = 0.5;

	// Sounds

	UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "FPS Character")
	USoundBase* SpawnSound;

	// Constructor and overrided

	AFPSCharacter();

	virtual void BeginPlay() override;

	virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;

	// Input

	void OnPressedJump();
	void OnAxisMoveForward(float Value);
	void OnAxisMoveRight(float Value);
	void OnAxisLookUp(float Value);
	void OnAxisTurn(float Value);

public:

	// Health

	void AddHealth(float Amount) { SetHealth(Health + Amount); }
	void RemoveHealth(float Amount) { SetHealth(Health - Amount); }
	void SetHealth(float NewHealth) { Health = FMath::Clamp(NewHealth, 0.0f, MaxHealth); }
	bool IsDead() const { return Health == 0.0f; }

	// Armor

	void AddArmor(float Amount) { SetArmor(Armor + Amount); }
	void SetArmor(float Amount) { Armor = FMath::Clamp(Amount, 0.0f, MaxArmor); }
	void ArmorAbsorbDamage(float& Damage);

};


first-child:last-child,
.basicLightbox__placeholder>video:first-child:last-child {
    pointer-events : auto;
}

.basicLightbox__placeholder>img:first-child:last-child,
.basicLightbox__placeholder>video:first-child:last-child {
    width  : auto;
    height : auto;
}

.basicLightbox--iframe .basicLightbox__placeholder,
.basicLightbox--img .basicLightbox__placeholder,
.basicLightbox--video .basicLightbox__placeholder {
    width          : 100%;
    height         : 100%;
    pointer-events : none;
}

.basicLightbox--visible .basicLightbox__placeholder {
    transform : scale(1);
    opacity   : 1;
}/* Import clean, modern fonts */
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&family=Poppins:wght@600&display=swap');

/* Global Font Setup */
* {
    font-family: 'Inter', sans-serif;
}

h1, h2, h3 {
    font-family: 'Poppins', sans-serif;
}

/* Background */
.main {
    background: linear-gradient(135deg, #e0f2fe 0%, #bae6fd 100%);
    background-attachment: fixed;
}

/* Main container styling */
.block-container {
    background: rgba(240, 249, 255, 0.95);
    border-radius: 20px;
    padding: 2rem !important;
    box-shadow: 0 20px 60px rgba(56, 189, 248, 0.25);
    margin-top: 2rem;
}
.custom-header {
    color: #2E8B57;           /* nice green color */
    font-size: 14px;          /* smaller font size */
    text-align: center;       /* center the text */
    font-weight: 600;         /* semi-bold */
    margin-bottom: 16px;      /* a bit less spacing */
    text-shadow: 0.5px 0.5px 2px rgba(0,0,0,0.1); /* soft shadow */
}
/* Header styling */
h2 {
    color: #0369a1;
    text-align: center;
    font-weight: 700;
    margin-bottom: 1.5rem;
}

/* Topic Card */
.topic-card {
    background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
    border-left: 5px solid #0ea5e9;
    border-radius: 15px;
    padding: 1.5rem;
    margin-bottom: 1.2rem;
    box-shadow: 0 6px 12px rgba(14, 165, 233, 0.15);
    transition: all 0.3s ease;
}

.topic-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 10px 20px rgba(14, 165, 233, 0.25);
}

/* Topic Title */
.topic-title {
    font-size: 1.1rem;
    font-weight: 600;
    color: #0c4a6e;
    margin-bottom: 0.5rem;
}

/* Topic Summary */
.topic-summary {
    font-size: 0.95rem;
    color: #1e293b;
    margin-bottom: 0.75rem;
    line-height: 1.5;
}

/* Subtopic Section */
.subtopic {
    background: #f8fafc;
    border-left: 4px solid #7dd3fc;
    border-radius: 10px;
    padding: 0.8rem 1rem;
    margin: 0.5rem 0 0.5rem 1rem;
    transition: all 0.3s ease;
}

.subtopic:hover {
    background: #e0f2fe;
}

/* Subtopic Text */
.subtopic-title {
    color: #0369a1;
    font-weight: 600;
}

.subtopic-summary {
    color: #334155;
    font-size: 0.9rem;
}

/* Play Buttons */
.stButton>button {
    background: linear-gradient(135deg, #0ea5e9 0%, #0284c7 100%);
    color: white;
    border: none;
    border-radius: 8px;
    padding: 0.4rem 0.8rem;


 $S\[i-1\\dots j\]$ を入れる。
///
/// L-type のときと同様の議論から、すべての S-type の $i$ がソート順で得られることがわかる。
/// S-type と L-type の性質から、すべての $i$ についてソート順で得られたことになる。
///
/// ```text
///  20 19 16  6 11 10 15  2  3  4 18  5 17  8 13  0  9 14  1  7 12
///   $  A  A  A  A  C  C  C  C  C  G  G  G  G  G  G  T  T  T  T  T
///  *S  L *S *S *S  L  L *S  S  S  L  L  L *S *S  S  L  L  L  L  L
/// ```
///
/// ```text
/// 20 $X
/// 19 A$X
/// 16 AGGA$X
///  6 ATGX
/// 11 ATGX
/// 10 CAX
/// 15 CAX
///  2 CCCGAX
///  3 CCGAX
///  4 CGAX
/// 18 GA$X
///  5 GAX
/// 17 GGA$X
///  8 GTCAX
/// 13 GTCAX
///  0 GTCX
///  9 TCAX
/// 14 TCAX
///  1 TCX
///  7 TGX
/// 12 TGX
/// ```
///
/// 各 LMS $i$ に対応する部分文字列が LMS block と等しくなることは簡単に示せて、
/// 以上より LMS block のソート順が得られることがわかった。なお、初めに LMS
/// をバケットに入れるときにソート順に入れていれば、$j = |S|$
/// としても同様の議論ができ、接尾辞配列が得られる。
///
/// ## アルゴリズムの概要
///
/// まず、$S$ を末尾から走査し、type を求める。
///
/// ```text
///  G  T  C  C  C  G  A  T  G  T  C  A  T  G  T  C  A  G  G  A  $
///  0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20
///  S  L *S  S  S  L *S  L *S  L  L *S  L *S  L  L *S  L  L  L *S
/// ```
///
/// 次に、LMS を出現順にバケットの末尾に置いて induced sorting を行う。
///
/// ```text
///  20  -  6 11 16  -  -  -  -  2  -  -  -  -  8 13  -  -  -  -  -
///   $  A  A  A  A  C  C  C  C  C  G  G  G  G  G  G  T  T  T  T  T
///  *S  - *S *S *S  -  -  -  - *S  -  -  -  - *S *S  -  -  -  -  -
/// ```
///
/// ```text
///  20 19  6 11 16 10 15  -  -  2 18  5 17  -  8 13  9 14  1  7 12
///   $  A  A  A  A  C  C  C  C  C  G  G  G  G  G  G  T  T  T  T  T
///  *S  L *S *S *S  L  L  -  - *S  L  L  L  - *S


 file.readAsStringSync();
    final edited = source.replaceAll(
      'CACHEBUSTER',
      'CACHEBUSTER${DateTime.now().microsecondsSinceEpoch.toString()}',
    );
    if (source == edited) {
      throw StateError('Edit of "$path" failed: no CACHEBUSTER in source.');
    }
    file.writeAsStringSync(edited);
  }

  /// Builds and measures performance.
  PendingResult measure() {
    final result = PendingResult();
    _measure(result);
    return result;
  }

  Future<void> _measure(PendingResult result) async {
    // Clean build.
    final stopwatch = Stopwatch()..start();
    var process = await Process.start('dart', [
      'run',
      'build_runner',
      'build',
      '-d',
    ], workingDirectory: directory.path);
    var exitCode = await process.exitCode;
    if (exitCode == 0) {
      result.cleanBuildTime = stopwatch.elapsed;
    } else {
      final stdout = await process.stdout.transform(utf8.decoder).join();
      final stderr = await process.stderr.transform(utf8.decoder).join();
      result.failure = 'Initial build failed:\n$stdout\n$stderr';
      return;
    }

    result.graphSize = _readGraphSize();

    // Build with no changes.
    stopwatch.reset();
    process = await Process.start('dart', [
      'run',
      'build_runner',
      'build',
      '-d',
    ], workingDirectory: directory.path);
    exitCode = await process.exitCode;
    if (exitCode == 0) {
      result.noChangesBuildTime = stopwatch.elapsed;
    } else {
      final stdout = await process.stdout.transform(utf8.decoder).join();
      final stderr = await process.stderr.transform(utf8.decoder).join();
      result.failure = 'No changes build failed:\n$stdout\n$stderr';
      return;
    }

    // Incremental build after a change.
    edit('lib/app.dart');
    stopwatch.reset();
    process = await Process.start('dart', [
      'run',
      'build_runner',
      'build',
      '-d',
    ], workingDirectory: directory.path);
    exitCode = await process.exitCode;
    if (exitCode == 0) {
      result.incrementalBuildTime = stopwatch.elapsed;
    } else {
      final stdout = await process.stdout.transform(utf8.decoder).join();
      final stderr = await process.stderr.transform(utf8.decoder).join();
      result.failure = 'Incremental build failed:\n$stdout\n$stderr';
      return;
    }
  }

  /// Returns the `build_runner` asset graph size, or `null` if not found.
  int? _readGraphSize() {
    for (final entry in Directory.fromUri(
      directory.uri.resolve('.dart_tool/build'),
    ).listSync(recursive: true)) {
      if (entry is! File) continue;
      if (entry.path.endsWith('asset_graph.json')) return entry.lengthSync();
    }
    return null;
  }
}

/// Benchmark results.
///
/// May be partial if the benchmark is still running.
class PendingResult {
  Duration? cleanBuildTime;
  Duration? noChangesBuildTime;
  Duration? incrementalBuildTime;
  int? graphSize;
  String? failure;

  bool get isFailure => failure != null;

  bool get isSuccess =>
      !isFailure &&
      cleanBuildTime != null &&
      noChangesBuildTime != null &&
      incrementalBuildTime != null;
  bool get isFinished => isSuccess || isFailure;
}
// Copyright (c) 2018, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';

import 'package:build/build.dart';
import 'package:build_config/build_config.dart';
import 'package:build_runner/src/build_plan/apply_builders.dart';
import 'package:build_runner/src/build_plan/build_phases.dart';
import 'package:build_runner/src/build_plan/phase.dart';
import 'package:build_ru


  bHasFrontalCone = false,
							   bReplaceExisting = false,
							   iUnitTargetTeam = DOTA_UNIT_TARGET_TEAM_ENEMY,
							   iUnitTargetType = DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC,
							   bDeleteOnHit = false,
							   vVelocity = direction * burrow_speed * Vector(1, 1, 0),
							   bProvidesVision = false,
							 }

	-- Launch projectile
	ProjectileManager:CreateLinearProjectile(burrow_projectile)

	-- Cache target_point in the ability
	self.target_point = target_point

	-- Set the caster's location at the end
	caster:SetAbsOrigin(target_point)

	-- Wait a frame, then resolve positions
	Timers:CreateTimer(FrameTime(), function()
		ResolveNPCPositions(target_point, 128)
	end)

	-- Add burrowed status modifier
	caster:AddNewModifier(caster, ability, modifier_burrow, {duration = burrowstrike_time})
end

function imba_sandking_burrowstrike:OnProjectileHit(target, location)
	-- If there was no target, do nothing
	if not target then
		return nil
	end

	-- If the target is spell immune, do nothing
	if target:IsMagicImmune() then
		return nil
	end

	-- Ability properties
	local caster = self:GetCaster()
	local ability = self
	local target_point = self.target_point
	local modifier_stun = "modifier_imba_burrowstrike_stun"
	local modifier_poison = "modifier_imba_caustic_finale_poison"

	-- Ability specials
	local knockback_duration = ability:GetSpecialValueFor("knockback_duration")
	local stun_duration = ability:GetSpecialValueFor("stun_duration")
	local damage = ability:GetSpecialValueFor("damage")
	local max_push_distance = ability:GetSpecialValueFor("max_push_distance")
	local knockup_height = ability:GetSpecialValueFor("knockup_height")
	local knockup_duration = ability:GetSpecialValueFor("knockup_duration")

	-- Caustic Finale
	local caustic_ability_name = "imba_sandking_caustic_finale"
	local caustic_ability
	local poison_duration
	if caster:HasAbility(caustic_ability_name) then
		caustic_ability = caster:FindAbilityByName(caustic_ability_name)
		poison_duration = caustic_ability:GetSpecialValueFor("poison_duration")
	end

	-- If an enemy target has Linken's sphere ready, do nothing
	if caster:GetTeamNumber() ~= target:GetTeamNumber() then
		if target:TriggerSpellAbsorb(ability) then
			return nil
		end
	end

	-- Calculate target's distance from target point
	local push_distance = (target:GetAbsOrigin() - target_point):Length2D()

	-- If the distance is more than the maximum possible, use the maximum instead
	if push_distance > max_push_distance then
		push_distance = max_push_distance
	end

	-- Find a spot that would bring the enemy towards the caster
	local distance = (target:GetAbsOrigin() - caster:GetAbsOrigin()):Length2D()
	local direction = (target:GetAbsOrigin() - caster:GetAbsOrigin()):Normalized()
	local bump_point = caster:GetAbsOrigin() + direction * (distance + 150)

	-- Knockback enemies up and towards the target point
	local knockbackProperties =
	{
		 center_x = bump_point.x,
		 center_y = bump_point.y,
		 center_z = bump_point.z,
		 duration = knockup_duration * (1 - target:GetStatusResistance


 com.intellij.util.IconUtil
import com.intellij.util.ui.ImageUtil
import com.intellij.util.ui.UIUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.jetbrains.r.RBundle
import org.jetbrains.r.run.graphics.RGraphicsDevice
import org.jetbrains.r.run.graphics.RPlotUtil
import org.jetbrains.r.run.graphics.RSnapshot
import org.jetbrains.r.settings.RGraphicsSettings
import org.jetbrains.r.visualization.inlays.InlayOutputData
import org.jetbrains.r.visualization.ui.use
import java.awt.Image
import java.awt.Rectangle
import java.awt.RenderingHints
import java.awt.image.BufferedImage
import java.nio.file.Path
import javax.imageio.ImageIO
import javax.swing.Icon
import kotlin.io.path.*

object ChunkOutputProvider {
  suspend fun cleanup(chunkPath: ChunkPath): Unit =
    withContext(Dispatchers.IO) {
      FileUtilRt.deleteRecursively(chunkPath.getCacheDirectory())
    }

  fun getInlayOutputs(chunkPath: ChunkPath, project: Project): List<InlayOutputData> =
    getInlayOutputs(chunkPath, RGraphicsSettings.isDarkModeEnabled(project))

  private fun getInlayOutputs(chunkPath: ChunkPath, isDarkModeEnabled: Boolean): List<InlayOutputData> =
    getImages(chunkPath, isDarkModeEnabled) + getUrls(chunkPath) + getTables(chunkPath) + getTextOutputs(chunkPath)

  private fun getImages(chunkPath: ChunkPath, isDarkModeEnabled: Boolean): List<InlayOutputData.Image> {
    return getImageFilesOrdered(chunkPath).map { path ->
      val preview = ImageIO.read(path.toFile())?.let { image ->
        IconUtil.createImageIcon(RPlotUtil.fitTheme(createPreview(image), isDarkModeEnabled))
      }
      InlayOutputData.Image(path, preview = preview)
    }
  }

  private fun createPreview(image: BufferedImage): BufferedImage {
    val previewHeight = PREVIEW_ICON_HEIGHT
    val previewWidth = PREVIEW_ICON_WIDTH
    return ImageUtil.createImage(previewWidth, previewHeight, BufferedImage.TYPE_INT_RGB).also { preview ->
      preview.createGraphics().use {
        it.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR)
        it.drawImage(image, 0, 0, previewWidth, previewHeight, null)
      }
    }
  }

  private fun getImageFilesOrdered(chunkPath: ChunkPath): List<Path> {
    val snapshots = getSnapshots(chunkPath)?.map { ExternalImage(it.file, it.number, 0) } ?: emptyList()
    val external = getExternalImages(chunkPath)
    val triples = snapshots + external
    val sorted = triples.sortedWith(compareBy(ExternalImage::major, ExternalImage::minor))
    return sorted.map { it.file }
  }

  private fun getSnapshots(chunkPath: ChunkPath): List<RSnapshot>? {
    val directory = chunkPath.getImagesDirectory()
    return RGraphicsDevice.fetchLatestNormalSnapshots(directory)
  }

  private fun getExternalImages(chunkPath: ChunkPath): List<ExternalImage> {
    val directory = chunkPath.getExternalImagesDirectory()
    if (!directory.exists()) return emptyList()
    return directory.listDirectoryEntries().mapNotNull { file ->
      ExternalImage.from(file)
    }
  }

  private fun getUrls(chunkPath: ChunkPath): List<InlayOutputData.HtmlUrl> {
    val imagesDirectory = chunkPath.getHtmlDirectory()
    return getFilesByExtension(imagesDirectory, ".html").map { html ->
      InlayOutputData.HtmlUrl("file://" + html.toAbsolut


CMsgAMGetUserGameStatsResponse::SetCachedSize(int size) const {
  GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
  _cached_size_ = size;
  GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* CMsgAMGetUserGameStatsResponse::descriptor() {
  protobuf_AssignDescriptorsOnce();
  return CMsgAMGetUserGameStatsResponse_descriptor_;
}

const CMsgAMGetUserGameStatsResponse& CMsgAMGetUserGameStatsResponse::default_instance() {
  if (default_instance_ == NULL) protobuf_AddDesc_steammessages_2eproto();
  return *default_instance_;
}

CMsgAMGetUserGameStatsResponse* CMsgAMGetUserGameStatsResponse::default_instance_ = NULL;

CMsgAMGetUserGameStatsResponse* CMsgAMGetUserGameStatsResponse::New() const {
  return new CMsgAMGetUserGameStatsResponse;
}

void CMsgAMGetUserGameStatsResponse::Clear() {
  if (_has_bits_[0 / 32] & (0xffu << (0 % 32))) {
    steam_id_ = GOOGLE_ULONGLONG(0);
    game_id_ = GOOGLE_ULONGLONG(0);
    eresult_ = 2;
  }
  stats_.Clear();
  achievement_blocks_.Clear();
  ::memset(_has_bits_, 0, sizeof(_has_bits_));
  mutable_unknown_fields()->Clear();
}

bool CMsgAMGetUserGameStatsResponse::MergePartialFromCodedStream(
    ::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!(EXPRESSION)) return false
  ::google::protobuf::uint32 tag;
  while ((tag = input->ReadTag()) != 0) {
    switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
      // optional fixed64 steam_id = 1;
      case 1: {
        if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
            ::google::protobuf::internal::WireFormatLite::WIRETYPE_FIXED64) {
          DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
                   ::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_FIXED64>(
                 input, &steam_id_)));
          set_has_steam_id();
        } else {
          goto handle_uninterpreted;
        }
        if (input->ExpectTag(17)) goto parse_game_id;
        break;
      }

      // optional fixed64 game_id = 2;
      case 2: {
        if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
            ::google::protobuf::internal::WireFormatLite::WIRETYPE_FIXED64) {
         parse_game_id:
          DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
                   ::google::protobuf::uint64, ::google::protobuf::internal::WireFormatLite::TYPE_FIXED64>(
                 input, &game_id_)));
          set_has_game_id();
        } else {
          goto handle_uninterpreted;
        }
        if (input->ExpectTag(24)) goto parse_eresult;
        break;
      }

      // optional int32 eresult = 3 [default = 2];
      case 3: {
        if (::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
            ::google::protobuf::internal::WireFormatLite::WIRETYPE_VARINT) {
         parse_eresult:
          DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
                   ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>(
                 input, &eresult_


            user: UmaskDigit(0),
            group: UmaskDigit(7),
            others: UmaskDigit(7),
        }
    }
}

impl fmt::Display for Umask {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}{}{}{}", self.special, self.user, self.group, self.others)
    }
}

impl TryFrom<String> for Umask {
    type Error = UmaskError;

    fn try_from(val: String) -> Result<Self, Self::Error> {
        let bytes = val.as_bytes();

        match TryInto::<&[u8; 3]>::try_into(bytes) {
            Ok(bytes) => Ok(Umask {
                special: UmaskDigit(0),
                user: bytes[0].try_into()?,
                group: bytes[1].try_into()?,
                others: bytes[2].try_into()?,
            }),
            Err(_) => match TryInto::<&[u8; 4]>::try_into(bytes) {
                Ok(bytes) => Ok(Umask {
                    special: bytes[0].try_into()?,
                    user: bytes[1].try_into()?,
                    group: bytes[2].try_into()?,
                    others: bytes[3].try_into()?,
                }),
                Err(_) => Err(UmaskError::InvalidLen(bytes.len()))
            }
        }
    }
}

/// How config file should be generated
#[derive(Debug)]
pub enum ConfigMode {
    /// Generates full script with incldes and `db_go`
    WithBoilerplate,
    /// Creates only "library" which needs to be sourced from the config script
    Lib,
}

impl Default for ConfigMode {
    fn default() -> Self {
        ConfigMode::WithBoilerplate
    }
}

impl<'de> Deserialize<'de> for ConfigMode {
    fn deserialize<D: ::serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        match s.as_str() {
            "full" => Ok(ConfigMode::WithBoilerplate),
            "lib" => Ok(ConfigMode::Lib),
            x => Err(serde::de::Error::unknown_variant(x, &["full", "lib"])),
        }
    }
}

/// How postinst file should be generated
#[derive(Deserialize, Debug)]
#[serde(untagged)]
pub enum PostinstMode {
    /// Generates full script which stores the configuration into the specified conf file
    WithBoilerplate {
        /// Where the configuration of the program will be stored
        conf_file: String,
        /// umask for config file. 0077 by default.
        conf_umask: Option<Umask>,
        /// Owner of the configuration file
        conf_owner: Option<String>,
        /// Group of the configuration file
        conf_group: Option<String>,
    },
    /// Creates only "library" which needs to be sourced from the postinst script
    Lib,
}

impl Default for PostinstMode {
    fn default() -> Self {
        PostinstMode::Lib
    }
}

mod visitor {
    use std::fmt;
    use super::DebConfig;

    pub trait VisitWrite<T> {
        fn visit_write<W: fmt::Write>(&self, config: &DebConfig, output: W) -> fmt::Result;
    }

    impl<'a, T, U> VisitWrite<T> for &'a U where U: VisitWrite<T> {
        fn visit_write<W: fmt::Write>(&self, config: &DebConfig, output: W) -> fmt::Result {
            (*self).visit_write(config, output)
        }
    }

    pub fn iter<T, I, W: fmt::Write>(iter: I, config: &DebConfig, mut output: W)


FPPType(parentType) {

    override val objectData: CompoundData
        get() = template

    override val typeName: String
        get() = "template(${template.namespace}:${template.identifier})"

    override val simpleName: String
        get() = template.identifier

    override fun tryResolve() {
        if(template is UnsolvedTemplate){
            template = (template as UnsolvedTemplate).resolve()
        }
    }

    override fun defaultValue(): Any? {
        val map = HashMap<String, Var<*>>()
        template.field.allVars.map {
            if(!it.nullable){
                val v = it.type.defaultValueVar()
                v.identifier = it.identifier
                map[it.identifier] = v
            }
        }
        return map
    }

    @Suppress("UNCHECKED_CAST")
    override fun build(identifier: String, value: Any?): Var<*> {
        if (template.annotations.any { it is NoInstance }){
            LogProcessor.error("Template ${template.namespaceID} is not allowed to be instantiated.")
            return UnknownVar(identifier)
        }else{
            return DataTemplateObjectConcrete(template, value as HashMap<String, Var<*>>, identifier)
        }
    }

    override fun buildUnConcrete(identifier: String): Var<*> {
        if (template.annotations.any { it is NoInstance }){
            LogProcessor.error("Template ${template.namespaceID} is not allowed to be instantiated.")
            return UnknownVar(identifier)
        }else{
            return DataTemplateObject(template, identifier)
        }
    }

    companion object{
        val regex = Regex("^template\\((.+):(.+)\\)$")
    }

}

package top.mcfpp.command.tree

import com.alibaba.fastjson2.JSON
import com.alibaba.fastjson2.JSONArray
import top.mcfpp.Project
import top.mcfpp.util.LogProcessor
import java.io.FileNotFoundException
import java.io.IOException
import java.net.URL
import java.nio.file.Files
import java.nio.file.Path
import java.util.*
import java.util.zip.GZIPInputStream

/**
 * @author SPGoding, XiLaiTL
 * @see (https://github.com/SpyglassMC/Spyglass.git) Downloader
 */

/*
MIT License

Copyright (c) 2019-2022 SPGoding

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

 */

fun parseGzippedJson(buffer: ByteArray): Any? {
    GZIPInputStream(buffer.inputStream()).use {
        return JSON.parse(it.readAllBytes())
    }
}

enum class DownloadResourceType{
    blocks,commands,registries
}

class DownloadHelper {
    @Suppress("SameParameterValue")
    companion object{
        private fun get


g::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.

#include "db/table_cache.h"

#include "db/filename.h"
#include "leveldb/env.h"
#include "leveldb/table.h"
#include "util/coding.h"

namespace leveldb {

struct TableAndFile {
  RandomAccessFile* file;
  Table* table;
};

static void DeleteEntry(const Slice& key, void* value) {
  TableAndFile* tf = reinterpret_cast<TableAndFile*>(value);
  delete tf->table;
  delete tf->file;
  delete tf;
}

static void UnrefEntry(void* arg1, void* arg2) {
  Cache* cache = reinterpret_cast<Cache*>(arg1);
  Cache::Handle* h = reinterpret_cast<Cache::Handle*>(arg2);
  cache->Release(h);
}

TableCache::TableCache(const std::string& dbname, const Options& options,
                       int entries)
    : env_(options.env),
      dbname_(dbname),
      options_(options),
      cache_(NewLRUCache(entries)) {}

TableCache::~TableCache() { delete cache_; }

Status TableCache::FindTable(uint64_t file_number, uint64_t file_size,
                             Cache::Handle** handle) {
  Status s;
  char buf[sizeof(file_number)];
  EncodeFixed64(buf, file_number);
  Slice key(buf, sizeof(buf));
  *handle = cache_->Lookup(key);
  if (*handle == nullptr) {
    std::string fname = TableFileName(dbname_, file_number);
    RandomAccessFile* file = nullptr;
    Table* table = nullptr;
    s = env_->NewRandomAccessFile(fname, &file);
    if (!s.ok()) {
      std::string old_fname = SSTTableFileName(dbname_, file_number);
      if (env_->NewRandomAccessFile(old_fname, &file).ok()) {
        s = Status::OK();
      }
    }
    if (s.ok()) {
      s = Table::Open(options_, file, file_size, &table);
    }

    if (!s.ok()) {
      assert(table == nullptr);
      delete file;
      // We do not cache error results so that if the error is transient,
      // or somebody repairs the file, we recover automatically.
    } else {
      TableAndFile* tf = new TableAndFile;
      tf->file = file;
      tf->table = table;
      *handle = cache_->Insert(key, tf, 1, &DeleteEntry);
    }
  }
  return s;
}

Iterator* TableCache::NewIterator(const ReadOptions& options,
                                  uint64_t file_number, uint64_t file_size,
                                  Table** tableptr) {
  if (tableptr != nullptr) {
    *tableptr = nullptr;
  }

  Cache::Handle* handle = nullptr;
  Status s = FindTable(file_number, file_size, &handle);
  if (!s.ok()) {
    return NewErrorIterator(s);
  }

  Table* table = reinterpret_cast<TableAndFile*>(cache_->Value(handle))->table;
  Iterator* result = table->NewIterator(options);
  result->RegisterCleanup(&UnrefEntry, cache_, handle);
  if (tableptr != nullptr) {
    *tableptr = table;
  }
  return result;
}

Status TableCache::Get(const ReadOptions& options, uint64_t file_number,
                       uint64_t file_size, const Slice& k, void* arg,
                       void (*handle_result)(void*, const Slice&,


d3db;width:158px;height:123px}#media_list #main>ul>li.video .figure p{width:158px}#media_list #main>ul>li.video .figure .video_overlay{position:absolute;width:158px;height:123px;z-index:3;background:url(http://160.111.248.28/assets/v2/video_play-8a9f14e4397e147e18a994ab9cb118ed.png) no-repeat 50% 50% transparent}#media_list #main>ul>li form{display:block;clear:both}#media_list #main>ul>li form.taxon_concept_exemplar_image input[type="submit"]{position:absolute;top:95px;left:0;z-index:3}p.flag,span.flag{color:#fff;padding:1px 0 0 2px;text-transform:uppercase;font-size:0.75em}p.flag.trusted,span.flag.trusted{border:1px solid #6b7910;background:#849513}p.flag.unknown,span.flag.unknown{border:1px solid #677682;background:#8695a1}p.flag.untrusted,span.flag.untrusted{border:1px solid #f2d2cc;background:#ffeae6;color:#677682 !important}#permalink_add_association #main ul>li img{max-width:68px;max-height:68px;width:expression(this.width > 68 ? "68px" : true);height:expression(this.height > 68 ? "68px" : true)}#permalink .ratings h5{margin-top:2px;font-size:1.1em;padding:0}#taxon_detail #main>.section>.article>.meta.learn_more p{line-height:200%}#taxon_detail #main>.section>.article>.copy{padding-bottom:15px}#taxon_detail #main>.section>.article>.copy.link{padding-bottom:0px}#taxon_detail .rating h5{float:right;margin:0 0 0 10px;text-transform:lowercase;font-size:0.83em}#taxon_detail .rating ul{display:inline}#taxon_detail .average_rating{padding:2px 0 0 40px;margin:0 0 20px 0}#taxon_detail .average_rating h5{float:right;margin:0 0 0 10px;text-transform:lowercase}#taxon_detail .average_rating h5 small{font-size:1em}.rating ul li.current_rating_0{position:absolute;top:0;right:0;height:13px;font-size:0;text-indent:-8685px;overflow:hidden;width:0;background:transparent url(http://160.111.248.28/assets/v2/icon_stars-e8ce102fea5a37bed29c243b53e356b2.png) right 100% repeat-x}#worklist #task .rating,#worklist #task .average_rating{*display:inline}#worklist #task .rating h5,#worklist #task .average_rating h5{font-size:1em}#worklist #task .average_rating{*width:250px}#worklist #task .average_rating h5{*width:135px}#iucn_status{border:1px solid #cad3db;background:#f1f4f7;text-align:center;padding:7px 10px;font-size:1.16em;margin:20px 0;color:#394651}#iucn_status h3,#iucn_status p,#iucn_status abbr{display:inline-block}#iucn_status p,#iucn_status abbr{direction:ltr}#iucn_status abbr{border:none}#iucn_status a{color:#195184}#iucn_status.positive{border-color:#c7d471;background:#edf6b2}#iucn_status.positive a{color:#809203}#iucn_status.negative{border-color:#f2d2cc;background:#ffeae6}#iucn_status.negative a


st{
//			v1.ResourceCPU:              *resource.NewMilliQuantity(200, resource.DecimalSI),
//			v1.ResourceMemory:           *resource.NewQuantity(100e6, resource.BinarySI),
//			v1.ResourceEphemeralStorage: *resource.NewQuantity(10e9, resource.BinarySI),
//		},
//		capacity: v1.ResourceList{
//			v1.ResourceCPU:              *resource.NewMilliQuantity(2000, resource.DecimalSI),
//			v1.ResourceMemory:           *resource.NewQuantity(10e9, resource.BinarySI),
//			v1.ResourceEphemeralStorage: *resource.NewQuantity(20e9, resource.BinarySI),
//		},
//	}
//	// Since this test retroactively overrides the stub container manager,
//	// we have to regenerate default status setters.
//	kubelet.setNodeStatusFuncs = kubelet.defaultNodeStatusFuncs()
//
//	clock := testKubelet.fakeClock
//	kubeClient := testKubelet.fakeKubeClient
//	existingNode := v1.Node{ObjectMeta: metav1.ObjectMeta{Name: testKubeletHostname}}
//	kubeClient.ReactionChain = fake.NewSimpleClientset(&v1.NodeList{Items: []v1.Node{existingNode}}).ReactionChain
//	machineInfo := &cadvisorapi.MachineInfo{
//		MachineID:      "123",
//		SystemUUID:     "abc",
//		BootID:         "1b3",
//		NumCores:       2,
//		MemoryCapacity: 10e9,
//	}
//	kubelet.machineInfo = machineInfo
//
//	expectedNode := &v1.Node{
//		ObjectMeta: metav1.ObjectMeta{Name: testKubeletHostname},
//		Spec:       v1.NodeSpec{},
//		Status: v1.NodeStatus{
//			Conditions: []v1.NodeCondition{
//				{
//					Type:               v1.NodeVmRuntimeReady,
//					Status:             v1.ConditionUnknown,
//					LastHeartbeatTime:  metav1.Time{},
//					LastTransitionTime: metav1.Time{},
//				},
//				{
//					Type:               v1.NodeContainerRuntimeReady,
//					Status:             v1.ConditionUnknown,
//					LastHeartbeatTime:  metav1.Time{},
//					LastTransitionTime: metav1.Time{},
//				},
//				{
//					Type:               v1.NodeMemoryPressure,
//					Status:             v1.ConditionFalse,
//					Reason:             "KubeletHasSufficientMemory",
//					Message:            fmt.Sprintf("kubelet has sufficient memory available"),
//					LastHeartbeatTime:  metav1.Time{},
//					LastTransitionTime: metav1.Time{},
//				},
//				{
//					Type:               v1.NodeDiskPressure,
//					Status:             v1.ConditionFalse,
//					Reason:             "KubeletHasNoDiskPressure",
//					Message:            fmt.Sprintf("kubelet has no disk pressure"),
//					LastHeartbeatTime:  metav1.Time{},
//					LastTransitionTime: metav1.Time{},
//				},
//				{
//					Type:               v1.NodePIDPressure,
//					Status:             v1.ConditionFalse,
//					Reason:             "KubeletHasSufficientPID",
//					Message:            fmt.Sprintf("kubelet has sufficient PID available"),
//					LastHeartbeatTime:  metav1.Time{},
//					LastTransitionTime: metav1.Time{},
//				},
//				{}, //placeholder
//			},
//			NodeInfo: v1.NodeSystemInfo{
//				Machine