.Length - pattern.Length)
        {
            int patternIndex;
            for (patternIndex = pattern.Length - 1; patternIndex >= 0; patternIndex--)
            {
                if (!IsByteMatch(source[sourceIndex + patternIndex],
                    pattern[patternIndex],
                    allowWildcard))
                {
                    break;
                }
            }

            if (patternIndex < 0)
            {
                matches.Add(sourceIndex);
                sourceIndex += pattern.Length;
            }
            else
            {
                var shift = badCharShift[source[sourceIndex + patternIndex]];
                sourceIndex += Math.Max(1, patternIndex - shift);
            }
        }
        return matches;
    }

    /// <summary>
    /// 构建坏字符跳转表（支持通配符优化）
    /// </summary>
    private static int[] BuildBadCharTable(byte[] pattern, bool allowWildcard)
    {
        var table = new int[256];
        Array.Fill(table, -1);

        for (int i = 0; i < pattern.Length; i++)
        {
            if (allowWildcard && pattern[i] == WildcardByte) continue;
            table[pattern[i]] = i;
        }
        return table;
    }

    /// <summary>
    /// 字节匹配逻辑（支持通配符）
    /// </summary>
    private static bool IsByteMatch(byte source, byte pattern, bool allowWildcard)
    {
        return allowWildcard && pattern == WildcardByte || source == pattern;
    }

    /// <summary>
    /// 创建唯一备份文件（线程安全）
    /// </summary>
    private void CreateBackupOnce()
    {
        if (_backupCreated || File.Exists(_backupFilePath)) return;

        lock (_backupLock) // 使用私有锁对象
        {
            if (_backupCreated) return;

            File.Copy(_targetFilePath, _backupFilePath);
            _backupCreated = true;
            Log.Information($"创建备份文件：{_backupFilePath}");
        }
    }

    #region Validation Methods
    private static void ValidateAddress(long fileLength, long address)
    {
        if (address < 0 || address >= fileLength)
            throw new ArgumentOutOfRangeException(
                nameof(address),
                $"地址 {address:X} 超出文件范围 (0-{fileLength - 1:X})");
    }

    private static void ValidatePatterns(byte[] search, byte[] replace)
    {
        if (search == null || sear


p>

下一页➡

# [1234. Replace the Substring for Balanced String](https://leetcode.com/problems/replace-the-substring-for-balanced-string/)

## 题目

You are given a string containing only 4 kinds of characters `'Q',` `'W', 'E'` and `'R'`.

A string is said to be **balanced** **if each of its characters appears `n/4` times where `n` is the length of the string.

Return the minimum length of the substring that can be replaced with **any** other string of the same length to make the original string `s` **balanced**.

Return 0 if the string is already **balanced**.

**Example 1**:

    Input: s = "QWER"
    Output: 0
    Explanation: s is already balanced.

**Example 2**:

    Input: s = "QQWE"
    Output: 1
    Explanation: We need to replace a 'Q' to 'R', so that "RQWE" (or "QRWE") is balanced.

**Example 3**:

    Input: s = "QQQW"
    Output: 2
    Explanation: We can replace the first "QQ" to "ER".

**Example 4**:

    Input: s = "QQQQ"
    Output: 3
    Explanation: We can replace the last 3 'Q' to make s = "QWER".

**Constraints**:

- `1 <= s.length <= 10^5`
- `s.length` is a multiple of `4`
- `s` contains only `'Q'`, `'W'`, `'E'` and `'R'`.

## 题目大意

有一个只含有 'Q', 'W', 'E', 'R' 四种字符，且长度为 n 的字符串。假如在该字符串中，这四个字符都恰好出现 n/4 次，那么它就是一个「平衡字符串」。给你一个这样的字符串 s，请通过「替换一个子串」的方式，使原字符串 s 变成一个「平衡字符串」。你可以用和「待替换子串」长度相同的 任何 其他字符串来完成替换。请返回待替换子串的最小可能长度。如果原字符串自身就是一个平衡字符串，则返回 0。

提示：

- 1 <= s.length <= 10^5
- s.length 是 4 的倍数
- s 中只含有 'Q', 'W', 'E', 'R' 四种字符

## 解题思路

- 给出一个字符串，要求输出把这个字符串变成“平衡字符串”的最小替换字符串的长度(替换只


tal-bb', 1);
}
</script>
<script type="text/javascript" async="" crossorigin="anonymous" src="https://m.media-amazon.com/images/I/61xJcNKKLXL.js?AUIClients/AmazonUIjQuery"></script><script type="text/javascript" async="" crossorigin="anonymous" src="https://m.media-amazon.com/images/I/11Y+5x+kkTL._RC|51ExhNVPbdL.js,11yKORv-GTL.js,11GgN1+C7hL.js,01+z+uIeJ-L.js,01VRMV3FBdL.js,21BJeD9yjcL.js,01cS+tLhj4L.js,11rRjDLdAVL.js,51UOrPXYGsL.js,11nAhXzgUmL.js,11UNP9ncXuL.js,1174TO1N7GL.js,11uo7qXoO3L.js,01VhK3jZdbL.js,21paGe30x-L.js,01490L6yBnL.js,512ZCVSd+aL.js,01JYHc2oIlL.js,31nfKXylf6L.js,01ktRCtOqKL.js,216zYxN25iL.js,11bEz2VIYrL.js,31o2NGTXThL.js,01rpauTep4L.js,01gn-l4N66L.js_.js?AUIClients/AmazonUI&WOBvLLbH#786834-T1"></script><script type="text/javascript" async="" crossorigin="anonymous" src="https://m.media-amazon.com/images/I/51BqsgbDI7L.js?AUIClients/CardJsRuntimeBuzzCopyBuild"></script><script type="text/javascript" async="" crossorigin="anonymous" src="https://m.media-amazon.com/images/I/11e6YKvz8HL._RC|61fRHADwn5L.js,51Ya8hmxsRL.js,11QPSzcZzFL.js,21Tlkr4uAnL.js,31e-8pJy4aL.js_.js?AUIClients/DetailPageDesktopImageBlockMetaAsset&+TRs+Wqv#in.906870-T1.342971-T1.585425-T1"></script><script type="text/javascript" async="" crossorigin="anonymous" src="https://images-eu.ssl-images-amazon.com/images/I/41Njck3cVcL.js?xcp"></script><script type="text/javascript" async="" crossorigin="anonymous" src="https://m.media-amazon.com/images/I/01I3s4SlPiL._RC|21RnwjmhK+L.js,31V0mJ-srZL.js,11-asXJWfkL.js,01s80TZosWL.js,015gdESSAtL.js,01GJONmvbXL.js,017VcaK0ACL.js,01Gujc1zuyL.js,61i8i2cHN-L.js,01EfL1GvN7L.js,01hcvL3758L.js_.js?AUIClients/DetailPageMetaAssetFixed&6XaqJr+V#desktop.in.564914-T4"></script><script type="text/javascript" async="" crossorigin="anonymous" src="https://m.media-amazon.com/images/I/01rg6Ce9FhL._RC|21JPvQvwWNL.js_.js?AUIClients/DetailPageEverywhereMetaAsset#desktop"></script><script type="text/javascript" async="" crossorigin="anonymous" src="https://m.media-amazon.com/images/I/31hPw-WKizL._RC|316nVZ1c+gL.js,31


       var m = check.Item1;

                Assert.That(m.ToString(), Is.EqualTo(check.Item2));
                Assert.That(m.IsGenericMethod, Is.EqualTo(check.Item3));
                Assert.That(m.ContainsGenericParameters, Is.EqualTo(check.Item4));
                Assert.That(m.IsGenericMethodDefinition, Is.EqualTo(check.Item5));
                Assert.That(m.IsConstructedGenericMethod, Is.EqualTo(check.Item6));
            }
        }

        private void DisplayGenericType(TypeInfo t, string caption) {
            Console.WriteLine("\n{0}", caption);
            Console.WriteLine("    Type: {0}", t);

            Console.WriteLine("\t            IsGenericType: {0}", t.IsGenericType);
            Console.WriteLine("\t  IsGenericTypeDefinition: {0}", t.IsGenericTypeDefinition);
            Console.WriteLine("\tContainsGenericParameters: {0}", t.ContainsGenericParameters);
            Console.WriteLine("\t       IsGenericParameter: {0}", t.IsGenericParameter);

            if (t.IsGenericParameter)
                Console.WriteLine("\t GenericParameterPosition: {0}", t.GenericParameterPosition);
        }
    }
}


.16b, v22.16b, v13.16b
    second48 w2 w3 w0 w1 w6 w7 w4 w5 w15 w19
    shl v29.4s, v27.4s, #15
    shl v30.4s, v27.4s, #23
    sri v29.4s, v27.4s, #17
    sri v30.4s, v27.4s, #9
    eor v27.16b, v27.16b, v29.16b
    second48 w1 w2 w3 w0 w5 w6 w7 w4 w20 w21
    eor v27.16b, v27.16b, v30.16b
    mov v14.s[3], v14.s[2]  // Due to ext requirements, to fill s[3]
    eor v15.16b, v27.16b, v28.16b

    // 13:52, 53, 54
    ext v23.16b, v11.16b, v12.16b, #12  // 39, 40, 41
    eor v27.16b, v24.16b, v13.16b
    st1 {v12.4s-v15.4s}, [x25]
    shl v21.4s, v15.4s, #15
    shl v22.4s, v23.4s, #7
    sri v21.4s, v15.4s, #17  // 49, 50, 51<<<15
    sri v22.4s, v23.4s, #25  // 39, 40, 41<<<7
    ldr w15, [x26, #40]
    ldr w20, [x26, #48]
    ldp w19, w21, [x25]
    second48 w0 w1 w2 w3 w4 w5 w6 w7 w15 w19
    eor v27.16b, v21.16b, v27.16b
    eor v28.16b, v22.16b, v14.16b
    second48 w3 w0 w1 w2 w7 w4 w5 w6 w20 w21
    shl v29.4s, v27.4s, #15
    shl v30.4s, v27.4s, #23
    sri v29.4s, v27.4s, #17
    sri v30.4s, v27.4s, #9
    eor v27.16b, v27.16b, v29.16b
    ldp w15, w20, [x26, #52]
    ldr w19, [x25, #8]
    ldr w21, [x25, #16]
    second48 w2 w3 w0 w1 w6 w7 w4 w5 w15 w19
    eor v27.16b, v27.16b, v30.16b
    mov v15.s[3], v15.s[2]  // Due to ext requirements, to fill s[3]
    eor v16.16b, v27.16b, v28.16b

    // 14:55, 56, 57
    ext v24.16b, v12.16b, v13.16b, #12  // 42, 43, 44
    eor v27.16b, v23.16b, v14.16b
    shl v21.4s, v16.4s, #15
    shl v22.4s, v24.4s, #7
    sri v21.4s, v16.4s, #17  // 52, 53, 54<<<15
    sri v22.4s, v24.4s, #25  // 42, 43, 44<<<7
    second48 w1 w2 w3 w0 w5 w6 w7 w4 w20 w21
    eor v27.16b, v21.16b, v27.16b
    eor v28.16b, v22.16b, v15.16b
    ldp w15, w20, [x25]
    ldp w1


";
      window.SVGPathSeg.PATHSEG_UNKNOWN = 0;
      window.SVGPathSeg.PATHSEG_CLOSEPATH = 1;
      window.SVGPathSeg.PATHSEG_MOVETO_ABS = 2;
      window.SVGPathSeg.PATHSEG_MOVETO_REL = 3;
      window.SVGPathSeg.PATHSEG_LINETO_ABS = 4;
      window.SVGPathSeg.PATHSEG_LINETO_REL = 5;
      window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_ABS = 6;
      window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_REL = 7;
      window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_ABS = 8;
      window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_REL = 9;
      window.SVGPathSeg.PATHSEG_ARC_ABS = 10;
      window.SVGPathSeg.PATHSEG_ARC_REL = 11;
      window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_ABS = 12;
      window.SVGPathSeg.PATHSEG_LINETO_HORIZONTAL_REL = 13;
      window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_ABS = 14;
      window.SVGPathSeg.PATHSEG_LINETO_VERTICAL_REL = 15;
      window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_ABS = 16;
      window.SVGPathSeg.PATHSEG_CURVETO_CUBIC_SMOOTH_REL = 17;
      window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_ABS = 18;
      window.SVGPathSeg.PATHSEG_CURVETO_QUADRATIC_SMOOTH_REL = 19; // Notify owning PathSegList on any changes so they can be synchronized back to the path element.

      window.SVGPathSeg.prototype._segmentChanged = function () {
        if (this._owningPathSegList) this._owningPathSegList.segmentChanged(this);
      };

      window.SVGPathSegClosePath = function (owningPathSegList) {
        window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_CLOSEPATH, "z", owningPathSegList);
      };

      window.SVGPathSegClosePath.prototype = Object.create(window.SVGPathSeg.prototype);

      window.SVGPathSegClosePath.prototype.toString = function () {
        return "[object SVGPathSegClosePath]";
      };

      window.SVGPathSegClosePath.prototype._asPathString = function () {
        return this.pathSegTypeAsLetter;
      };

      window.SVGPathSegClosePath.prototype.clone = function () {
        return new window.SVGPathSegClosePath(undefined);
      };

      window.SVGPathSegMovetoAbs = function (owningPathSegList, x, y) {
        window.SVGPathSeg.call(this, window.SVGPathSeg.PATHSEG_MOVETO_ABS, "M", owningPathSegList);
        this._x = x;
        this._y = y;
      };

      window.SVGPathSegMovetoAbs.prototype = Object.create(window.SVGPathSeg.prototype);

      window.SVGPathSegMovetoAbs.prototype.toString = function () {
        return "[object SVGPathSegMovetoAbs]";
      };

      window.SVGPathSegMovetoAbs.prototype._asPathString = function () {
        return this.pathSegTypeAsLetter + " " + this._x + " " + this._y;
      };

      window.SVGPathSegMovetoAbs.prototype.clone = function () {
        return new window.SVGPathSegMovetoAbs(undefined, this._x, this._y);
      };

      Object.defineProperty(window.SVGPathSegMovetoAbs.prototype, "x", {
        get: function get() {
          return this._x;
        },
        set: function set(x) {
          this._x = x;

          this._segmentChanged();
        },
        enumera


할 수 있습니다.
모듈과 달리, 여러 개의 파일을 포괄할 수 있으며, `--outFile`을 사용해 연결할 수 있습니다.
네임스페이스는 웹 애플리케이션에서 코드를 구조화하기에 좋은 방법이며, 모든 의존성은 HTML 페이지의 `<script>` 태그로 포함합니다.

특히 대규모 애플리케이션의 경우, 이 방법은 모든 전역 네임스페이스가 오염되는 경우와 마찬가지로 컴포넌트의 의존성을 식별하기 힘들게 만들 수 있습니다.

# 네임스페이스와 모듈의 위험성 (Pitfalls of Namespaces and Modules)

여기서는 네임스페이스와 모듈을 사용할 때 자주 발생하는 다양한 위험성과 그 해결책을 알아보겠습니다.

## `/// <reference>`를 사용한 모듈

일반적인 실수는 모듈 파일을 참조하기 위해 `import`문 대신 `/// <reference ... />` 구문을 사용하는 것입니다.
이 둘의 차이를 이해하기 위해, 우선 `import` 경로에 위치한 모듈에 대한 타입 정보를 컴파일러가 어떻게 찾아내는지를 이해해야 합니다. (예를 들어, `import x from "...";`, `import x = require("...");` 등 안의 `...`)

컴파일러는 `.ts`, `.tsx`를 찾은 다음 적절한 경로에 위치한 `.d.ts`를 찾습니다.
만약 특정 파일을 찾지 못한다면, 컴파일러는 *앰비언트 모듈(ambient module) 선언*을 탐색할 것입니다.
`.d.ts` 파일안에 이것들을 선언해야 한다는 점을 기억하세요.

* `myModules.d.ts`

  ```ts
  // 모듈이 아닌 .d.ts 파일 또는 .ts 파일:
  declare module "SomeModule" {
      export function fn(): string;
  }
  ```

* `myOtherModule.ts`

  ```ts
  /// <reference path="myModules.d.ts" />
  import * as m from "SomeModule";
  ```

위의 reference 태그는 앰비언트 모듈(ambient m


plyCommentDtoFixture.create(id = 2L)
                )
                every { examCommentRepository.findReplyComments(any()) } returns replies

                val actual = examCommentQueryService.getReplyComments(parentCommentId)

                Then("대댓글 리스트를 반환한다.") {
                    actual shouldBe replies
                }
            }

            And("삭제된 댓글이고 대댓글도 없는 경우") {
                every { rootComment.isDeleted() } returns true
                every { examCommentRepository.findReplyComments(any()) } returns emptyList()

                Then("예외를 발생시킨다.") {
                    shouldThrow<NotFoundException> { examCommentQueryService.getReplyComments(parentCommentId) }
                        .message shouldBe "존재하지 않는 댓글입니다. 댓글 식별자: $parentCommentId"
                }
            }
        }
    }
})

package com.fluffy.reaction.domain

import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe

class ReactionTest : StringSpec({

    "반응은 정상적으로 생성된다." {
        // given
        val reaction = Reaction.create(
            targetType = "EXAM",
            targetId = 1L,
            memberId = 1L,
            type = ReactionType.LIKE,
        )

        // when & then
        reaction.status shouldBe ReactionStatus.ACTIVE
    }

    "반응을 삭제하면 삭제 상태가 된다." {
        // given
        val reaction = Reaction.create(
            targetType = "EXAM",
            targetId = 1L,
            memberId = 1L,
            type = ReactionType.LIKE,
        )

        // when
        reaction.delete()

        // then
        reaction.status shouldBe ReactionStatus.DELETED
    }

    "반응을 활성화하면 활성 상태가 된다." {
        // given
        val reaction = Reaction.create(
            targetType = "EXAM",
            targetId = 1L,
            memberId = 1L,
            type = ReactionType.LIKE,
        )
        reaction.delete()

        // when
        reaction.activate()

        // then
        reaction.status shouldBe ReactionStatus.ACTIVE
    }
})package com.fluffy.submission.ui

import com.fluffy.global.web.Accessor
import com.fluffy.global.web.Auth
import com.fluffy.submission.application.SubmissionQueryService
import com.fluffy.submission.application.SubmissionService
import com.fluffy.submission.application.response.SubmissionDetailResponse
import com.fluffy.submission.domain.dto.MySubmissionSummaryDto
import com.fluffy.submission.domain.dto.SubmissionSummaryDto
import com.fluffy.submission.ui.request.SubmissionWebRequest
import jakarta.validation.Valid
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RestController

@RestController
class SubmissionController(
    private val submissionService: SubmissionService,
    private val submissionQueryService: SubmissionQueryService,
) {

    @GetMapping("/api/v1/exams/{examId}/submissions")
    fun getSummaries(
        @PathVariable examId


r1)
/* 803C88DC 003C453C  7C 08 03 A6 */	mtlr r0
/* 803C88E0 003C4540  38 21 00 30 */	addi r1, r1, 0x30
/* 803C88E4 003C4544  4E 80 00 20 */	blr

.global func_803C88E8
func_803C88E8:
/* 803C88E8 003C4548  38 60 00 01 */	li r3, 1
/* 803C88EC 003C454C  4E 80 00 20 */	blr

.global func_803C88F0
func_803C88F0:
/* 803C88F0 003C4550  94 21 FF D0 */	stwu r1, -0x30(r1)
/* 803C88F4 003C4554  7C 08 02 A6 */	mflr r0
/* 803C88F8 003C4558  90 01 00 34 */	stw r0, 0x34(r1)
/* 803C88FC 003C455C  39 61 00 30 */	addi r11, r1, 0x30
/* 803C8900 003C4560  4B DF E8 1D */	bl _savegpr_24
/* 803C8904 003C4564  7C 99 23 78 */	mr r25, r4
/* 803C8908 003C4568  80 84 00 64 */	lwz r4, 0x64(r4)
/* 803C890C 003C456C  7C 7B 1B 78 */	mr r27, r3
/* 803C8910 003C4570  7C BA 2B 78 */	mr r26, r5
/* 803C8914 003C4574  7F 23 CB 78 */	mr r3, r25
/* 803C8918 003C4578  3B C0 00 00 */	li r30, 0
/* 803C891C 003C457C  4B FF B7 A1 */	bl func_803C40BC
/* 803C8920 003C4580  80 99 00 64 */	lwz r4, 0x64(r25)
/* 803C8924 003C4584  7C 78 1B 78 */	mr r24, r3
/* 803C8928 003C4588  7F 23 CB 78 */	mr r3, r25
/* 803C892C 003C458C  38 A0 00 00 */	li r5, 0
/* 803C8930 003C4590  4B FF B7 D1 */	bl func_803C4100
/* 803C8934 003C4594  80 99 00 6C */	lwz r4, 0x6c(r25)
/* 803C8938 003C4598  7C 7D 1B 78 */	mr r29, r3
/* 803C893C 003C459C  7F 23 CB 78 */	mr r3, r25
/* 803C8940 003C45A0  4B FF B7 7D */	bl func_803C40BC
/* 803C8944 003C45A4  80 99 00 6C */	lwz r4, 0x6c(r25)
/* 803C8948 003C45A8  7C 7F 1B 78 */	mr r31, r3
/* 803C894C 003C45AC  7F 23 CB 78 */	mr r3, r25
/* 803C8950 003C45B0  38 A0 00 00 */	li r5, 0
/* 803C8954 003C45B4  4B FF B7 AD */	bl func_803C4100
/* 803C8958 003C45B8  80 99 00 64 */	lwz r4, 0x64(r25)
/* 803C895C 003C45BC  7C 7C 1B 78 */	mr r28, r3
/* 803C8960 003C


ase() == "http")
			HT_requestExampleLink.href += "?title=";
		else
			HT_requestExampleLink.href += "?subject=Wizard%20.NET%20Library: ";

		HT_requestExampleLink.href += "Add an Example for " + encodeURIComponent(document.title) + "&body=" +
			encodeURIComponent("Please add an example for " + document.title + ".%0D%0DTODO (optional): Describe a specific " +
			"scenario you would like to see addressed.%0D%0DHelp Topic: " + window.location.href).replace(/%250D/g, "%0D");
		HT_requestExampleLink.innerHTML = HT_requestExampleLinkText;
		</script>View Source

The VisualStyleElementExAeroWizardCommandArea type exposes the following members.

Properties

								Name	Description

	Normal
Gets a visual style element that represents the command area of a wizard.

Top

See Also

Reference

AeroWizard.VisualStyles Namespace

© 2020 David Hall. All rights reserved.

<meta http-equiv="X-UA-Compatible" content="IE=edge" /><link rel="shortcut icon" href="../icons/favicon.ico" /><link rel="stylesheet" type="text/css" href="../styles/branding.css" /><link rel="stylesheet" type="text/css" href="../styles/branding-en-US.css" /><


/// 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.
///
/// @ref gtx_rotate_vector
/// @file glm/gtx/rotate_vector.hpp
/// @date 2006-11-02 / 2011-06-07
/// @author Christophe Riccio
///
/// @see core (dependence)
/// @see gtx_transform (dependence)
///
/// @defgroup gtx_rotate_vector GLM_GTX_rotate_vector
/// @ingroup gtx
///
/// @brief Function to directly rotate a vector
///
/// <glm/gtx/rotate_vector.hpp> need to be included to use these functionalities.
///////////////////////////////////////////////////////////////////////////////////

#ifndef GLM_GTX_rotate_vector
#define GLM_GTX_rotate_vector

// Dependency:
#include "../glm.hpp"
#include "../gtx/transform.hpp"

#if(defined(GLM_MESSAGES) && !defined(GLM_EXT_INCLUDED))
#	pragma message("GLM: GLM_GTX_rotate_vector extension included")
#endif

namespace glm
{
	/// @addtogroup gtx_rotate_vector
	/// @{

	//! Rotate a two dimensional vector.
	//! From GLM_GTX_rotate_vector extension.
	template <typename T, precision P>
	GLM_FUNC_DECL detail::tvec2<T, P> rotate(
		detail::tvec2<T, P> const & v,
		T const & angle);

	//! Rotate a three dimensional vector around an axis.
	//! From GLM_GTX_rotate_vector extension.
	template <typename T, precision P>
	GLM_FUNC_DECL detail::tvec3<T, P> rotate(
		detail::tvec3<T, P> const & v,
		T const & angle,
		detail::tvec3<T, P> const & normal);

	//! Rotate a four dimensional vector around an axis.
	//! From GLM_GTX_rotate_vector extension.
	template <typename T, precision P>
	GLM_FUNC_DECL detail::tvec4<T, P> rotate(
		detail::tvec4<T, P> const & v,
		T const & angle,
		detail::tvec3<T, P> const & normal);

	//! Rotate a three dimensional vector around the X axis.
	//! From GLM_GTX_rotate_vector extension.
	template <typename T, precision P>
	GLM_FUNC_DECL detail::tvec3<T, P> rotateX(
		detail::tvec3<T, P> const & v,
		T const & angle);

	//! Rotate a three dimensional vector around the Y axis.
	//! From GLM_GTX_rotate_vector extension.
	template <typename T, precision P>
	GLM_FUNC_DECL detail::tvec3<T, P> rotateY(
		detail::tvec3<T, P> const & v,
		T const & angle);

	//! Rotate a three dimensional vector around the Z axis.
	//! From GLM_GTX_rotate_vector extension.
	template <typename T, precision P>
	GLM_FUNC_DECL detail::tvec3<T, P> rotateZ(
		detail::tvec3<T, P> const & v,
		T const & angle);

	//! Rotate a four dimentionnals vector around the X axis.
	//! From GLM_GTX_rotate_vector extension.
	template <typename T, precision P>
	GLM_FUNC_DECL detail::tvec4<T, P> rotateX(
		detail::tvec4<T, P> const & v,
		T const & angle);

	//! Rotate a four dimensional vector around the X axis.
	//! From GLM_GTX


+ minor);
                }
            }
        }

        // Parse EXTENSIONS string
        String extensionsString = memASCIISafe(invokeP(AL_EXTENSIONS, GetString));
        if (extensionsString != null) {
            MemoryStack stack = stackGet();

            StringTokenizer tokenizer = new StringTokenizer(extensionsString);
            while (tokenizer.hasMoreTokens()) {
                String extName = tokenizer.nextToken();
                try (MemoryStack frame = stack.push()) {
                    if (invokePZ(memAddress(frame.ASCII(extName, true)), IsExtensionPresent)) {
                        supportedExtensions.add(extName);
                    }
                }
            }
        }

        if (alcCaps.ALC_EXT_EFX) {
            supportedExtensions.add("ALC_EXT_EFX");
        }
        apiFilterExtensions(supportedExtensions, Configuration.OPENAL_EXTENSION_FILTER);

        ALCapabilities caps = new ALCapabilities(functionProvider, supportedExtensions, bufferFactory == null ? BufferUtils::createPointerBuffer : bufferFactory);

        if (alcCaps.ALC_EXT_thread_local_context && alcGetThreadContext() != NULL) {
            setCurrentThread(caps);
        } else {
            setCurrentProcess(caps);
        }

        return caps;
    }

    static ALCapabilities getICD() {
        return ALC.check(icd.get());
    }

    /** Function pointer provider. */
    private interface ICD {
        default void set(@Nullable ALCapabilities caps) {}
        @Nullable ALCapabilities get();
    }

    /**
     * Write-once {@link ICD}.
     *
     *
This is the default implementation that skips the thread/process lookup. When a new ALCapabilities is set, we compare it to the write-once
     * capabilities. If different function pointers are found, we fall back to the expensive lookup. This will never happen with the OpenAL-Soft
     * implementation.

     */
    private static class ICDStatic implements ICD {

        private static @Nullable ALCapabilities tempCaps;

        @SuppressWarnings("AssignmentToStaticFieldFromInstanceMethod")
        @Override
        public void set(@Nullable ALCapabilities caps) {
            if (tempCaps == null) {
                tempCaps = caps;
            } else if (caps != null && caps != tempCaps && ThreadLocalUtil.areCapabilitiesDifferent(tempCaps.addresses, caps.addresses)) {
                apiLog("[WARNING] Incompatible context detected. Falling back to thread/process lookup for AL contexts.");
                icd = AL::getCapabilities; // fall back to thread/process lookup
            }
        }

        @Override
        public ALCapabilities get() {
            return WriteOnce.caps;
        }

        private static final class WriteOnce {
            // This will be initialized the first time get() above is called
            static final ALCapabilities caps;

            static {
                ALCapabilities tempCaps = ICDStatic.tempCaps;
                if (tempCaps == null) {
                    throw new IllegalStateException("No ALCapabilities instance has been set");
                }
                caps = tempCaps;
            }
        }

    }

}package com.lwkandroid.imagepicker.data;

import android.os.Parcel;
import android.os.Parcelable;

/**
 * Function:图片实体类
 */
public class ImageBean implements Parcelable
{
    /**
     * 图片id【扫描sd卡后才有的】
     */
    private String imageId;
    /**
     * 原图地址
     */
    private String imagePath;
    /**
     * 最后修改时间
     */
    private Long lastModified;
    /**
     * 图片宽
     */
    private int width;
    /**
     * 图片高
     *


= _dereq_(19)
  , getProto = _dereq_(47).getProto
  , anObject = _dereq_(5);

$def($def.S, 'Reflect', {
  getPrototypeOf: function getPrototypeOf(target){
    return getProto(anObject(target));
  }
});
},{"19":19,"47":47,"5":5}],147:[function(_dereq_,module,exports){
// 26.1.6 Reflect.get(target, propertyKey [, receiver])
var $        = _dereq_(47)
  , has      = _dereq_(31)
  , $def     = _dereq_(19)
  , isObject = _dereq_(39)
  , anObject = _dereq_(5);

function get(target, propertyKey/*, receiver*/){
  var receiver = arguments.length < 3 ? target : arguments[2]
    , desc, proto;
  if(anObject(target) === receiver)return target[propertyKey];
  if(desc = $.getDesc(target, propertyKey))return has(desc, 'value')
    ? desc.value
    : desc.get !== undefined
      ? desc.get.call(receiver)
      : undefined;
  if(isObject(proto = $.getProto(target)))return get(proto, propertyKey, receiver);
}

$def($def.S, 'Reflect', {get: get});
},{"19":19,"31":31,"39":39,"47":47,"5":5}],148:[function(_dereq_,module,exports){
// 26.1.9 Reflect.has(target, propertyKey)
var $def = _dereq_(19);

$def($def.S, 'Reflect', {
  has: function has(target, propertyKey){
    return propertyKey in target;
  }
});
},{"19":19}],149:[function(_dereq_,module,exports){
// 26.1.10 Reflect.isExtensible(target)
var $def          = _dereq_(19)
  , anObject      = _dereq_(5)
  , $isExtensible = Object.isExtensible;

$def($def.S, 'Reflect', {
  isExtensible: function isExtensible(target){
    anObject(target);
    return $isExtensible ? $isExtensible(target) : true;
  }
});
},{"19":19,"5":5}],150:[function(_dereq_,module,exports){
// 26.1.11 Reflect.ownKeys(target)
var $def = _dereq_(19);

$def($def.S, 'Reflect', {ownKeys: _dereq_(58)});
},{"19":19,"58":58}],151:[function(_dereq_,module,exports){
// 26.1.12 Reflect.preventExtensions(target)
var $def               = _dereq_(19)
  , anObject           = _dereq_(5)
  , $preventExtensions = Object.preventExtensions;

$def($def.S, 'Reflect', {
  preventExtensions: function preventExtensions(target){
    anObject(target);
    try {
      if($preventExtensions)$preventExtensions(target);
      return true;
    } catch(e){
      return false;
    }
  }
});
},{"19":19,"5":5}],152:[function(_dereq_,module,exports){
// 26.1.14 Reflect.setPrototypeOf(target, proto)
var $def     = _dereq_(19)
  , setProto = _dereq_(65);

if(setProto)$def($def.S, 'Reflect', {
  setPrototypeOf: function setPrototypeOf(target, proto){
    setProto.check(target, proto);
    try {
      setProto.set(target, proto);
      return true;
    } catch(e){
      return false;
    }
  }
});
},{"19":19,"65":65}],153:[function(_dereq_,module,exports){
// 26.1.13 Reflect.set(target,


что с нами шутки плохи! А потом возвращайтесь ко мне. Надеюсь еще увидеть вас $Gживым:живой;.",
    ["O"] = "Заберитесь на Заоблачный пик в западной части Внутренних Земель и оставьте возле колодца в центре города последнее послание клану Громового Молота. После выполнения задания возвращайтесь к Отхо Можи\'ко в деревню Сломанного Клыка.$B$BБерегитесь дворфов Громового Молота и других сторонников Альянса.",
    ["T"] = "Последнее послание клану Громового Молота",
  },
  [7844] = {
    ["D"] = "Во Внутренних землях живет три племени троллей, $N. На этом, собственно, сходство и заканчивается – мы все тролли и мы все живем здесь.$B$BПлемя Порочной Ветви, как следует из названия, самое отвратительное – тамошние каннибалы едят и троллей, и вообще всех, кто подвернется.$B$BЕсли бы Зул\'джин был здесь, он бы уничтожил все это отродье одним движением руки! Но Зул\'джина с нами нет, поэтому приходится справляться самим.$B$BВот вам задание – пойти и убить троллей из племени Порочной Ветви.",
    ["O"] = "Убейте 6 охотников за скальпами и 2 ворожеев из племени Порочной Ветви по поручению Яо\'джин из деревни Сломанного Клыка.$B$BЯо\'джин сказала, что эти тролли живут близ храмов Шаол\'вата и Агол\'вата в северо-восточной части Внутренних земель.",
    ["T"] = "Собратья-каннибалы",
  },
  [7845] = {
    ["D"] = "Однажды ночью клан Порочной Ветви совершил набег на нашу деревню, и похитил моего мужа. Наши разведчики узнали, что он еще жив и находится в плену на самом верху Джинта\'Алора. Они сказали, что коварная жрица Ведьмиса хочет принести его в жертву их безлицему кровавому богу Хаккару.$B$BПрошу вас, $N, спасите его! Наша деревня не переживет такой тяжелой потери.",
    ["O"] = "Спасите старейшину Сломанного Клыка из Джинта\'Алора по поручению его жены из деревни Сломанного Клыка.$B$BСтарейшину держат в плену на самом верху Джинта\'Алор – гла


        border: 2
    }
}

export type OnRegionSelected = (region: RectangularRegion) => void
export type OnFlipPieces = (region: RectangularRegion) => void

export default class GameScreen extends BaseScreen {
    private _onRegionSelectedCallback: OnRegionSelected | null = null
    private _onFlipPiecesCallback: OnFlipPieces | null = null

    private _game!: FlippingGame

    constructor() {
        super("game-screen-template")
    }

    render(container: HTMLElement): void {
        super.render(container)

        const canvas = this.getById<HTMLCanvasElement>("canvas")
        this._game = new FlippingGame(
            canvas,
            config
        )

        this.onEvent("flip-region-btn", "click", this.onClickFlipRegionButton)

        this._game.onChangeSelectedRegion(this.onChangeSelectedRegion)
    }

    onRegionSelected(callback: OnRegionSelected) {
        this._onRegionSelectedCallback = callback
    }

    setSelectedRegion(region: RectangularRegion) {
        this._game.selectRegion(region)
    }

    onFlipPieces(callback: OnFlipPieces) {
        this._onFlipPiecesCallback = callback
    }

    flipPieces(region: RectangularRegion) {
        this._game.flipPieces(region)
    }

    setControlsEnabled(enable: boolean) {
        this._game.controlsEnabled = enable
    }

    private onChangeSelectedRegion = (region: RectangularRegion) => {
        const ruleBreaks = new CanFlipRegion(this._game.pieces, region).check()

        const ruleTopRightPieceMustNotBeFlippedElement = this.getById("rule-TopRightPieceMustNotBeFlipped")!
        const ruleWidthMustBeSquare = this.getById("rule-WidthMustBeSquare")!
        const ruleHeightMustBeTriangular = this.getById("rule-HeightMustBeTriangular")!

        ruleTopRightPieceMustNotBeFlippedElement.style.color = "#000"
        ruleWidthMustBeSquare.style.color = "#000"
        ruleHeightMustBeTriangular.style.color = "#000"

        if (ruleBreaks.includes(RuleBreaks.TopRightPieceMustNotBeFlipped)) {
            ruleTopRightPieceMustNotBeFlippedElement.style.color = "red"
        }

        if (ruleBreaks.includes(RuleBreaks.WidthMustBeSquare)) {
            ruleWidthMustBeSquare.style.color = "red"
        }

        if (ruleBreaks.includes(RuleBreaks.HeightMustBeTriangular)) {
            ruleHeightMustBeTriangular.style.color = "red"
        }

        if (ruleBreaks.length === 0) {
            this._onRegionSelectedCallback?.call(this, region)
        }
    }

    private onClickFlipRegionButton = () => {
        const currentRegion = this._game.currentSelectedRegion!

        try {
            this._game.flipPieces(currentRegion)
            this._onFlipPiecesCallback?.call(this, currentRegion)
        } catch (e) {
            // It's likely that the opponent is up to no good
            console.error(e)
        }
    }

    destroy(): void {

    }
}
import Fc from 'fast-check';
import { anyPass, complement, is, sort } from 'ramda';

import type { SomeSchema } from '../src';
import {
  validate,
  number,
  string,
  date,
  oneOf,
  object,
  array,
  boolean,
  nullable,
  optional,
  nil,
  ValidationError,
  minArrayLength,
  λ,
  pipe,
  unknown,
  tuple,
  minStringLength,
} from '../src';
import { isISODateString } from '../src/utils/dateUtils';

const shuffle = <T>(arr: readonly T[]) => sort(() => Math.random() - 0.5, arr);

const throws = <T extends readonly unknown[], Err extends Error>(
  predicate: (...args: T) => unk


3CECCBL, 0xB610021542E13ECAL, 0x0FF979D12F59E2ACL,
      0x6037DA27E4F9CC50L, 0x5E92975A0DF1847DL, 0xD66DE190D3E623FEL,
      0x5032D6B87B568048L, 0x9A36B7CE8235216EL, 0x80272A7A24F64B4AL,
      0x93EFED8B8C6916F7L, 0x37DDBFF44CCE1555L, 0x4B95DB5D4B99BD25L,
      0x92D3FDA169812FC0L, 0xFB1A4A9A90660BB6L, 0x730C196946A4B9B2L,
      0x81E289AA7F49DA68L, 0x64669A0F83B1A05FL, 0x27B3FF7D9644F48BL,
      0xCC6B615C8DB675B3L, 0x674F20B9BCEBBE95L, 0x6F31238275655982L,
      0x5AE488713E45CF05L, 0xBF619F9954C21157L, 0xEABAC46040A8EAE9L,
      0x454C6FE9F2C0C1CDL, 0x419CF6496412691CL, 0xD3DC3BEF265B0F70L,
      0x6D0E60F5C3578A9EL };

  /** S-Box T4. */
  private static final long[] T4 = {
      0x5B0E608526323C55L, 0x1A46C1A9FA1B59F5L, 0xA9E245A17C4C8FFAL,
      0x65CA5159DB2955D7L, 0x05DB0A76CE35AFC2L, 0x81EAC77EA9113D45L,
      0x528EF88AB6AC0A0DL, 0xA09EA253597BE3FFL, 0x430DDFB3AC48CD56L,
      0xC4B3A67AF45CE46FL, 0x4ECECFD8FBE2D05EL, 0x3EF56F10B39935F0L,
      0x0B22D6829CD619C6L, 0x17FD460A74DF2069L, 0x6CF8CC8E8510ED40L,
      0xD6C824BF3A6ECAA7L, 0x61243D581A817049L, 0x048BACB6BBC163A2L,
      0xD9A38AC27D44CC32L, 0x7FDDFF5BAAF410ABL, 0xAD6D495AA804824BL,
      0xE1A6A74F2D8C9F94L, 0xD4F7851235DEE8E3L, 0xFD4B7F886540D893L,
      0x247C20042AA4BFDAL, 0x096EA1C517D1327CL, 0xD56966B4361A6685L,
      0x277DA5C31221057DL, 0x94D59893A43ACFF7L, 0x64F0C51CCDC02281L,
      0x3D33BCC4FF6189DBL, 0xE005CB184CE66AF1L, 0xFF5CCD1D1DB99BEAL,
      0xB0B854A7FE42980FL, 0x7BD46A6A718D4B9FL, 0xD10FA8CC22A5FD8CL,
      0xD31484952BE4BD31L, 0xC7FA975FCB243847L, 0x4886ED1E5846C407L,
      0x28CDDB791EB70B04L, 0xC2B00BE2F573417FL, 0x5C95


alue == "all")
				.ToList();

			var backSelected = backElements
				.Where(e => e.Attribute("selected")?.Value == "all")
				.ToList();

			using var dialog = new StylizeImagesDialog(
				foreElements.Count, foreSelected.Count,
				backElements.Count, backSelected.Count);

			var result = dialog.ShowDialog(owner);
			if (result != DialogResult.OK)
			{
				return;
			}

			var updated = false;
			if (foreSelected.Any() && dialog.ApplyForeground)
			{
				Stylize(foreSelected, dialog.Style);
				updated = true;
			}

			if (backSelected.Any() && dialog.ApplyBackground)
			{
				Stylize(backSelected, dialog.Style);
				updated = true;
			}

			if (!updated)
			{
				if (foreElements.Any() && dialog.ApplyForeground)
				{
					Stylize(foreElements, dialog.Style);
					updated = true;
				}

				if (backElements.Any() && dialog.ApplyBackground)
				{
					Stylize(backElements, dialog.Style);
					updated = true;
				}
			}

			if (updated)
			{
				await one.Update(page);
			}
		}

		private void Stylize(IEnumerable<XElement> elements, ImageEditor.Stylization style)
		{
			var editor = new ImageEditor { Style = style };

			foreach (var element in elements)
			{
				editor.Apply(new OneImage(element));
			}
		}
	}
}


ests,
                               Map<String, Set<String>> outcomes) {
  // Read the entire file into a byte buffer and transform it to a
  // String. This will treat the file as ascii but the only parts
  // we are interested in will be ascii in any case.
  List bytes = new File(filePath.toNativePath()).readAsBytesSync();
  String contents = decodeUtf8(bytes);
  int first_newline = contents.indexOf('\n');
  final String line_separator =
      (first_newline == 0 || contents[first_newline - 1] != '\r')
      ? '\n'
      : '\r\n';
  List<String> lines = contents.split(line_separator);
  if (lines.last == '') lines.removeLast();
  bytes = null;
  contents = null;
  Set<String> validMultitestOutcomes = new Set<String>.from(
      ['ok', 'compile-time error', 'runtime error',
       'static type warning', 'dynamic type error',
       'checked mode compile-time error']);

  // Create the set of multitests, which will have a new test added each
  // time we see a multitest line with a new key.
  Map<String, List<String>> testsAsLines = new Map<String, List<String>>();

  // Add the default case with key "none".
  testsAsLines['none'] = new List<String>();
  outcomes['none'] = new Set<String>();

  int lineCount = 0;
  for (String line in lines) {
    lineCount++;
    var annotation = new _Annotation.from(line);
    if (annotation != null) {
      testsAsLines.putIfAbsent(annotation.key,
          () => new List<String>.from(testsAsLines["none"]));
      // Add line to test with annotation.key as key, empty line to the rest.
      for (var key in testsAsLines.keys) {
        testsAsLines[key].add(annotation.key == key ? line : "");
      }
      outcomes.putIfAbsent(annotation.key, () => new Set<String>());
      if (annotation.rest != 'continued') {
        for (String nextOutcome in annotation.outcomesList) {
          if (validMultitestOutcomes.contains(nextOutcome)) {
            outcomes[annotation.key].add(nextOutcome);
          } else {
            DebugLogger.warning(
                "Warning: Invalid test directive '$nextOutcome' on line "
                "${lineCount}:\n${annotation.rest} ");
          }
        }
      }
    } else {
      for (var test in testsAsLines.values) test.add(line);
    }
  }
  // End marker, has a final line separator so we don't need to add it after
  // joining the lines.
  var marker =
      '// Test created from multitest named ${filePath.toNativePath()}.'
      '$line_separator';
  for (var test in testsAsLines.values) test.add(marker);

  var keysToDelete = [];
  // Check that every key (other than the none case) has at least one outcome
  for (var outcomeKey in outcomes.keys) {
    if (outcomeKey != 'none' && outcomes[outcomeKey].isEmpty) {
      DebugLogger.warning(
          "Warning: Test ${outcomeKey} has no valid annotated outcomes.\n"
          "Expected one of: ${validMultitestOutcomes.toString()}");
      // If this multitest doesn't have an outcome, mark the multitest for
      // deletion.
      keysToDelete.add(outcomeKey);
    }
  }
  // If a key/multitest was marked for deletion, do the necessary cleanup.
  keysToDelete.forEach(outcomes.remove);
  keysToDelete.forEach(testsAsLines.remove);

  // Copy all the tests into the output map tests, as multiline strings.
  for (String key in testsAsLines.keys) {


6
/* 05B1C 80902A5C 3C014280 */  lui     $at, 0x4280                ## $at = 42800000
/* 05B20 80902A60 44819000 */  mtc1    $at, $f18                  ## $f18 = 64.00
/* 05B24 80902A64 3C01433F */  lui     $at, 0x433F                ## $at = 433F0000
/* 05B28 80902A68 44813000 */  mtc1    $at, $f6                   ## $f6 = 191.00
/* 05B2C 80902A6C 46120102 */  mul.s   $f4, $f0, $f18
/* 05B30 80902A70 86220344 */  lh      $v0, 0x0344($s1)           ## 00000344
/* 05B34 80902A74 3C063DCC */  lui     $a2, 0x3DCC                ## $a2 = 3DCC0000
/* 05B38 80902A78 3C07453B */  lui     $a3, 0x453B                ## $a3 = 453B0000
/* 05B3C 80902A7C 3C018091 */  lui     $at, %hi(D_8090DC68)       ## $at = 80910000
/* 05B40 80902A80 34C6CCCD */  ori     $a2, $a2, 0xCCCD           ## $a2 = 3DCCCCCD
/* 05B44 80902A84 26240360 */  addiu   $a0, $s1, 0x0360           ## $a0 = 00000360
/* 05B48 80902A88 46062200 */  add.s   $f8, $f4, $f6
/* 05B4C 80902A8C 3C0544FA */  lui     $a1, 0x44FA                ## $a1 = 44FA0000
/* 05B50 80902A90 2458FFFF */  addiu   $t8, $v0, 0xFFFF           ## $t8 = FFFFFFFF
/* 05B54 80902A94 10400022 */  beq     $v0, $zero, .L80902B20
/* 05B58 80902A98 E62801B0 */  swc1    $f8, 0x01B0($s1)           ## 000001B0
/* 05B5C 80902A9C 3C05459C */  lui     $a1, 0x459C                ## $a1 = 459C0000
/* 05B60 80902AA0 A6380344 */  sh      $t8, 0x0344($s1)           ## 00000344
/* 05B64 80902AA4 34A54000 */  ori     $a1, $a1, 0x4000           ## $a1 = 459C4000
/* 05B68 80902AA8 26240360 */  addiu   $a0, $s1, 0x0360           ## $a0 = 00000360
/* 05B6C 80902AAC 3C063F00 */  lui     $a2, 0x3F00                ## $a2 = 3F000000
/* 05B70 80902AB0 0C01E107 */  jal     Math_SmoothScaleMaxF

/* 05B74 80902AB4 34E78000 */  ori     $a3, $a3, 0x8000           ## $a3 = 453B8000
/* 05B78 80902AB8 3C0545AB */  lui     $a1, 0x45AB                ## $a1 = 45AB0000
/* 05B7C 80902ABC 3C07453B */  lui     $a3, 0x453B                ## $a3 = 453B0000
/* 05B80 80902AC0 34E78000 */  ori     $a3, $a3, 0x8000           ## $a3 = 453B8000
/* 05B84 80902AC4 34A5E000 */  ori     $a1, $a1, 0xE000           ## $a1 = 45ABE000
/* 05B88 80902AC8 26240370 */  addiu   $a0


83525795ca03c2f328ab9a666baf) )
	ROM_LOAD( "1026.20m", 0x060000, 0x20000, CRC(9b20e13d) SHA1(726b6fb548c0906a5baa90b9698f99a6af9ecc36) )
	ROM_LOAD( "1021.87u", 0x080000, 0x20000, CRC(8388910c) SHA1(62c6b1885bed042ef72fb62464923a33f9b464f1) )
	ROM_LOAD( "1023.65u", 0x0a0000, 0x20000, CRC(71353112) SHA1(0aab14379e1b562b81cdd52eb209e264a12232c4) )
	ROM_LOAD( "1025.87m", 0x0c0000, 0x20000, CRC(f7b20a64) SHA1(667c539fa809d3ae4a1c127e2044dd3a4e533266) )
	ROM_LOAD( "1027.65m", 0x0e0000, 0x20000, CRC(55d54952) SHA1(73e1a388ea48bab567bde8958ee228432ebfbf67) )

	ROM_REGION( 0x40000, REGION_SOUND1, 0 )	/* ADPCM data */
	ROM_LOAD( "1040.75b", 0x00000, 0x20000, CRC(0896702b) SHA1(d826bb4812d393889584c7c656c317fd5745a05f) )
	ROM_LOAD( "1041.65b", 0x20000, 0x20000, CRC(b3b07ce9) SHA1(f1128a143b72867c16b9803b0beb0188420cbfb5) )
ROM_END

ROM_START( shuuz2 )
	ROM_REGION( 0x40000, REGION_CPU1, 0 )	/* 4*64k for 68000 code */
	ROM_LOAD16_BYTE( "23p.rom",     0x00000, 0x20000, CRC(98aec4e7) SHA1(8cbe6e7835ecf0ef74a2de723ef970a63d3bddd1) )
	ROM_LOAD16_BYTE( "13p.rom",     0x00001, 0x20000, CRC(dd9d5d5c) SHA1(0bde6be55532c232b1d27824c2ce61f33501cbb0) )

	ROM_REGION( 0x080000, REGION_GFX1, ROMREGION_DISPOSE | ROMREGION_INVERT )
	ROM_LOAD( "2030.43x", 0x000000, 0x20000, CRC(8ecf1ed8) SHA1(47143f1eaf43027c5301eb6009d8a56a98328894) )
	ROM_LOAD( "2032.20x", 0x020000, 0x20000, CRC(5af184e6) SHA1(630969466c606d1f51da81911fb365a4cac4685c) )
	ROM_LOAD( "2031.87x", 0x040000, 0x20000, CRC(72e9db63) SHA1(be13830b38c2603bbd6b875abdc1675788a60b24) )
	ROM_LOAD( "2033.65x", 0x060000, 0x20000, CRC(8f552498) SHA1(7fd323f3b30747a8645d7a9676fdf8f973b6632a) )

	ROM_REGION( 0x100000, REGION_GFX2, ROMREGION_DISPOSE | ROMREGION_INVERT )
	ROM_LOAD( "1020.43u", 0x000000, 0x20000, CRC(d21ad039) SHA1(5389745eff6690c1890f98a9630869b1084fb2f3) )
	ROM_LOAD( "1022.20u", 0x020000, 0x20000, CRC(0c10bc90) SHA1(11272757ecad42a4fae49046bd1b01d5ff7f7d4f) )
	ROM_LOAD( "1024.43m", 0x040000, 0x20000, CRC(adb09347) SHA1(5294dfb3d4aa83525795ca03c2f328ab9a666baf) )
	ROM_LOAD( "1026.20m", 0x060000, 0x20000, CRC(9b20e13d) SHA1(726b6fb548c0906a5baa90b9698f99a6af9ecc36) )
	ROM_LOAD( "1021.87u", 0x080000, 0x20000, CRC(8388910c) SHA1(62c6b1885bed042ef72fb62464923a33f9b464f1) )
	ROM_LOAD( "1023.65u", 0x0a0000, 0x20000, CRC(71353112) SHA1(0aab14379e1b562b81cdd52eb209e264a12232c4) )
	ROM_LOAD( "1025.87m", 0x0c0000, 0x20000, CRC(f7b20a64) SHA1(667c539fa809d3ae4a1c127e2044dd3a4e533266) )
	ROM_LOAD( "1027.65m", 0x0e0000, 0x20000, CRC(55d54952) SHA1(73e1a388ea48bab567bde8958ee228432ebfbf67) )

	ROM_REGION( 0x40000, REGION_SOUND1, 0 )	/* ADPCM data */
	ROM_LOAD( "1040.75b", 0x00000, 0x20000, CRC(0896702b) SHA1(d826bb4812d393889584c7c656c317fd5745a05f) )
	ROM_LOAD( "1041.65b", 0x20000, 0x20000, CRC(b3b07ce9) SHA1(f1128a143b72867c16b9803b0beb0188420cbfb5) )
ROM_END

/*************************************
 *
 *	Driver init
 *
 *************************************/

static DRIVER_INIT( shuuz )
{
	atarigen_eeprom_default = NULL;
}

/*************************************
 *
 *	Game driver(s)
 *
 *************************************/

GAME( 1990, shuuz,  0,     shuuz, shuuz,  shuuz, ROT0, "Atari Games", "Shuuz (version 8.0)" )
GAME( 1990, shuuz2, shuuz, shuuz, shuuz2, shuuz, ROT0, "Atari Games", "Shuuz (version 7.1)" )


Id : number, sceneId : number, recommendationStyle : string, coins : number[]) => void;
        finalResult : any;

        client : pg.Client;
        release : () => void;

        /**
         * @param id id of the user of who you want the last experiment
         * @param finishAction callback that has as parameters
         *

         *
the id of the experiment

         *
the id of the coin combination

         *
the id of the scene

         *
the recommendation style

         *
the coins

         *

         * @private
         */
        constructor(userId : number, finishAction : (expId : number, coinCombinationId : number, sceneId : number, recommendationStyle : string, coins : number[]) => void) {

            this.userId = userId;
            this.finishAction = finishAction;
            this.finalResult = {}

            if (this.userId === undefined) {
                return;
            }

            pg.connect(pgc.url, (err, client, release) => {
                this.client = client;
                this.release = release;
                this.execute();
            });
        }

        /**
         * Executes the SQL request and calls the callback
         */
        execute() {
            this.client.query(
                'SELECT scene_id AS "sceneId", \n' +
                    '       coin_1, \n' +
                    '       coin_2, \n' +
                    '       coin_3, \n' +
                    '       coin_4, \n' +
                    '       coin_5, \n' +
                    '       coin_6, \n' +
                    '       coin_7, \n' +
                    '       coin_8, \n' +
                    '       Experiment.recommendation_style AS "recommendationStyle", \n' +
                    '       Experiment.id AS "expId", \n' +
                    '       CoinCombination.id as "coinCombinationId" \n' +
                    'FROM Experiment, CoinCombination \n' +
                    'WHERE Experiment.coin_combination_id = CoinCombination.id \n' +
                    '      AND Experiment.user_id = $1 \n' +
                    '      AND NOT Experiment.finished \n' +
                    'ORDER BY Experiment.id DESC \n' +
                    'LIMIT 1;',
                [this.userId],
                (err, result) => {

                    if (err !== null) {
                        Log.dberror(err + ' in LastExpGetter (DBReq)');
                    }

                    if (result.rows.length === 0) {
                        Log.debug('Timeout', true);
                        setTimeout(function() {
                            this.execute();
                        }, 1000);
                        return;
                    }

                    this.client.query(
                        'UPDATE Experiment SET finished = true WHERE id = $1',
                        [result.rows[0].expId],
                        () => {
                            this.finalResult.sceneId = result.rows[0].sceneId;
                            this.finalResult.recommendationStyle = result.rows[0].recommendationStyle;
                            this.finalResult.coins = [
                                result.rows[0].coin_1,
                                result.rows[0].coin_2,
                                result.rows[0].coin_3,
                                result.rows[0].coin_4,
                                result.rows[0].coin_5,
                                result.rows[0].coin_6,
                                result.rows[0].coin_7,


(it) }

        return ProjectViewDirectoriesSection(includedDirectories, excludedDirectories)
    }

    private fun toImportDepthSection(projectViewCliOptions: ProjectViewCliOptions?): ProjectViewImportDepthSection? =
        projectViewCliOptions?.importDepth?.let(::ProjectViewImportDepthSection)

    private fun toBuildFlagsSection(projectViewCliOptions: ProjectViewCliOptions?): ProjectViewBuildFlagsSection? =
        projectViewCliOptions?.buildFlags?.let { ProjectViewBuildFlagsSection(it) }

    private fun toEnabledRulesSection(projectViewCliOptions: ProjectViewCliOptions?): ProjectViewEnabledRulesSection? =
        projectViewCliOptions?.enabledRules?.let { ProjectViewEnabledRulesSection(it) }

    private fun toIdeJavaHomeOverrideSection(projectViewCliOptions: ProjectViewCliOptions?): ProjectViewIdeJavaHomeOverrideSection? =
        projectViewCliOptions?.ideJavaHomeOverride?.let { ProjectViewIdeJavaHomeOverrideSection(it) }

    private fun toDeriveTargetFlagSection(projectViewCliOptions: ProjectViewCliOptions?): ProjectViewDeriveTargetsFromDirectoriesSection? =
        projectViewCliOptions?.deriveTargetsFromDirectories?.let(::ProjectViewDeriveTargetsFromDirectoriesSection)
}
/*
 * Copyright 2024-2025 JetBrains s.r.o. and Compose Hot Reload contributors.
 * Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
 */

@file:Suppress("UnstableApiUsage")

import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar.Companion.shadowJar

plugins {
    `embedded-kotlin`
    `java-gradle-plugin`
    com.gradle.`plugin-publish`
    com.gradleup.shadow
    build.publish
    build.apiValidation
}

gradlePlugin {
    plugins.create("hot-reload") {
        id = "org.jetbrains.compose.hot-reload"
        implementationClass = "org.jetbrains.compose.reload.gradle.ComposeHotReloadPlugin"
        website = "https://github.com/JetBrains/compose-hot-reload"
        vcsUrl = "https://github.com/JetBrains/compose-hot-reload"
        displayName = "JetBrains Compose Hot Reload"
        description = "JetBrains Compose Hot Reload"
        tags = listOf("compose", "hot-reload", "hot", "reload", "hotswap")
    }
}

//region Shading/Embedding of the plugin jar

/*
Publishing Gradle plugins to the plugin portal requires embedding all dependencies
We, therefore embedd all hot-reload artifacts used by the Gradle plugin.
External dependencies (such as kotlinx.serialization) will be shaded.

Any dependency declared in the 'embedded' configuration will be included _(and made available to for compilation)_
 */

val embedded: Configuration = configurations.create("embedded").apply {
    exclude("org.jetbrains.kotlin", "kotlin-stdlib")
}

configurations.compileOnly.get().extendsFrom(embedded)
configurations.testCompileOnly.get().extendsFrom(embedded)

tasks.shadowJar.configure {
    archiveClassifier = ""
    configurations = listOf(embedded)
}

tasks.withType<ShadowJar>().configureEach {
    relocate("kotlinx", "org.jetbrains.compose.reload.shadow.kotlinx")
    /* We're shading kotlinx as 'runtime' dependency; Consumers are not supposed to compile against it. */
    exclude("**/kotlinx-serialization-core.kotlin_module")
    exclude("**/kotlinx-serialization-json.kotlin_module")
    exclude("META-INF/com.android.tools/**")
    exclude("META-INF/proguard/**")
}

//endregion

//region Configure Tests
/*
Since


IL'
  },
  {
    '_id': '62358',
    'city': 'NIOTA',
    'loc': [-91.299136, 40.597753],
    'pop': 672,
    'state': 'IL'
  },
  {
    '_id': '62359',
    'city': 'PALOMA',
    'loc': [-91.205287, 40.036616],
    'pop': 254,
    'state': 'IL'
  },
  {
    '_id': '62360',
    'city': 'PAYSON',
    'loc': [-91.262676, 39.815253],
    'pop': 1939,
    'state': 'IL'
  },
  {
    '_id': '62361',
    'city': 'PEARL',
    'loc': [-90.63795399999999, 39.444072],
    'pop': 415,
    'state': 'IL'
  },
  {
    '_id': '62362',
    'city': 'PERRY',
    'loc': [-90.746105, 39.787042],
    'pop': 703,
    'state': 'IL'
  },
  {
    '_id': '62363',
    'city': 'PITTSFIELD',
    'loc': [-90.80726900000001, 39.601306],
    'pop': 5678,
    'state': 'IL'
  },
  {
    '_id': '62365',
    'city': 'PLAINVILLE',
    'loc': [-91.143598, 39.800448],
    'pop': 986,
    'state': 'IL'
  },
  {
    '_id': '62366',
    'city': 'PLEASANT HILL',
    'loc': [-90.877011, 39.446697],
    'pop': 1521,
    'state': 'IL'
  },
  {
    '_id': '62367',
    'city': 'COLMAR',
    'loc': [-90.87381499999999, 40.288493],
    'pop': 1425,
    'state': 'IL'
  },
  {
    '_id': '62370',
    'city': 'ROCKPORT',
    'loc': [-90.972178, 39.532846],
    'pop': 641,
    'state': 'IL'
  },
  {
    '_id': '62373',
    'city': 'SUTTER',
    'loc': [-91.37609399999999, 40.309683],
    'pop': 747,
    'state': 'IL'
  },
  {
    '_id': '62374',
    'city': 'TENNESSEE',
    'loc': [-90.855605, 40.41399],
    'pop': 414,
    'state': 'IL'
  },
  {
    '_id': '62375',
    'city': 'TIMEWELL',
    'loc': [-90.866067, 40.011658],
    'pop': 539,
    'state': 'IL'
  },
  {
    '_id': '62376',
    'city': 'URSA',
    'loc': [-91.373341, 40.080918],
    'pop': 1074,
    'state': 'IL'
  },
  {
    '_id': '62378',
    'city': 'VERSAILLES',
    'loc': [-90.674147, 39.888286],
    'pop': 1136,
    'state': 'IL'
  },
  {
    '_id': '62379',
    'city': 'WARSAW',
    'loc': [-91.434803, 40.354449],
    'pop': 1882,
    'state': 'IL'
  },
  {
    '_id': '62380',
    'city': 'WEST POINT',
    'loc': [-91.249568


ulable;
import org.energy2d.model.Sensor;
import org.energy2d.model.Tree;

/**
 * @author Charles Xie
 *
 */
class HandleSetter {

	static void setRects(View2D view, Manipulable m, Rectangle2D.Float[] handle) {

		if (m instanceof Sensor)
			return;

		float h = handle[0].width / 2;
		Shape s = m.getShape();

		if (s instanceof RectangularShape) {
			setRectHandles(view, s.getBounds2D(), handle, h);
		} else if (s instanceof Polygon2D) {
			Polygon2D p = (Polygon2D) s;
			int n = p.getVertexCount();
			Point2D.Float point;
			if (n <= handle.length) {
				for (int i = 0; i < handle.length; i++) {
					if (i < n) {
						point = p.getVertex(i);
						handle[i].x = view.convertPointToPixelXf(point.x) - h;
						handle[i].y = view.convertPointToPixelYf(point.y) - h;
					} else {
						handle[i].x = handle[i].y = -100;
					}
				}
			} else {
				float k = (float) n / (float) handle.length;
				for (int i = 0; i < handle.length; i++) {
					point = p.getVertex((int) (i * k));
					handle[i].x = view.convertPointToPixelXf(point.x) - h;
					handle[i].y = view.convertPointToPixelYf(point.y) - h;
				}
			}
		} else if (s instanceof Blob2D) {
			Blob2D b = (Blob2D) s;
			int n = b.getPointCount();
			Point2D.Float point;
			if (n <= handle.length) {
				for (int i = 0; i < handle.length; i++) {
					if (i < n) {
						point = b.getPoint(i);
						handle[i].x = view.convertPointToPixelXf(point.x) - h;
						handle[i].y = view.convertPointToPixelYf(point.y) - h;
					} else {
						handle[i].x = handle[i].y = -100;
					}
				}
			} else {
				float k = (float) n / (float) handle.length;
				for (int i = 0; i < handle.length; i++) {
					point = b.getPoint((int) (i * k));
					handle[i].x = view.convertPointToPixelXf(point.x) - h;
					handle[i].y = view.convertPointToPixelYf(point.y) - h;
				}
			}
		} else if (s instanceof Annulus) {
			setRectHandles(view, s.getBounds2D(), handle, h);
		} else if (s instanceof EllipticalAnnulus) {

			EllipticalAnnulus e = (EllipticalAnnulus) s;

			Rectangle2D.Float outerBound = new Rectangle2D.Float(e.getX() - e.getOuterA(), e.getY() - e.getOuterB(), 2 * e.getOuterA(), 2 * e.getOuterB());
			handle[UPPER_LEFT].x = view.convertPointToPixelXf((float) outerBound.getMinX()) - h;
			handle[UPPER_LEFT].y = view.convertPointToPixelYf((float) outerBound.getMinY()) - h;
			handle[LOWER_LEFT].x = view.convertPointToPixelXf((float) outerBound.getMinX()) - h;
			handle[LOWER_LEFT].y = view.convertPointToPixelYf((float) outerBound.getMaxY()) - h;
			handle[UPPER_RIGHT].x = view.convertPointToPixelXf((float) outerBound.getMaxX()) - h;
			handle[UPPER_RIGHT].y = view.convertPointToPixelYf((float) outerBo


an_input(ipython_number, scan_type, motor_name, start, end, step, ct);
    csleep(1000);
    println!(
            "{message}",
            message = Paint::blue("Operation will be saved in /data/master/kits/scan.h5 (HDF5::NXscan from NXscanH5_FileRecoder)")
            );
    let now: DateTime<Utc> = Utc::now();
    println!(
        "{message}",
        message = Paint::blue(format!(
            "Scan #{scan_id} started at {start_t}",
            scan_id = scan_id,
            start_t = now.to_rfc2822()
        )),
    );

    print!(
        "{pt:^15} {motor_name:^15} {counter_name:^15}",
        pt = "#Pt No",
        motor_name = motor_name,
        counter_name = timer_name,
    );
    for name in exp_chan {
        print!("{meas_name:^15}", meas_name = name,);
    }
    println!("{dt:^15}", dt = "dt",);
    csleep(500);
    let mut t = 0;
    for n in (start..end).step_by((end - start) / step) {
        t += ct;
        let mut pulses = Vec::<f64>::new();
        for r in &exp_chan_ranges {
            let nbr = rng.gen_range(1, r) as f64;
            pulses.push(nbr);
        }
        let pulse: f64 = rng.gen_range(1, 40) as f64;
        print!(
            " {count:^15} {n:^15} {ct:^15}",
            count = count,
            n = n,
            ct = ct,
        );
        for p in &pulses {
            print!("{pls:^15}", pls = format!("{a:.6}", a = p / pulse),);
        }
        println!("{dt:^15}", dt = t,);
        count += 1;
        csleep(ct * 100);
        if appconfig.should_exit() {
            return;
        }
    }
    csleep(500);
    println!(
        "{message}",
        message = Paint::blue("Operation saved in /data/master/kits/scan.h5")
    );
    let now: DateTime<Utc> = Utc::now();
    println!(
        "{message}",
        message = Paint::blue(format!(
            "Scan #{scan_id} ended at {end_t}",
            scan_id = scan_id,
            end_t = now.to_rfc2822()
        )),
    );
    if rng.gen_range(1, 3) == 1 {
        println!(
                "{message}",
                message = Paint::red(format!("An error occurred while running macro '{scan_type}({motor_name}, {motstart}, {motend}, {step}, {ct}) -> {id}':",
                    motor_name = motor_name,
                    scan_type = scan_type,
                    motstart = start,
                    motend = end,
                    step = step,
                    ct = ct,
                    id = "353eb23a-42fe-b06a-bc56876a6e6f0",
                ))
            );
        let exc = EXCEPTIONS_LIST.choose(&mut rng);
        let exc = exc.as_deref().unwrap_or(&"ValueError");
        let desc = BOOTLOG_LIST.choose(&mut rng);
        let desc = desc.as_deref().unwrap_or(&"Unknown error");
        println!(
            "{message}",
            message = Paint::red(format!(
                "{


g fully published.

It's like setting the project in wax, allows to do some final touches of breaking changes and patches without forcing a version bump.

The suggested pattern for the pre-release id is `alpha.01`, `alpha.02`, `beta.01`, ...

### Experimental

> This is the current main channel of LIKO-12 releases for now.

Provided to allow rapid development while not being constrained with backwards compatibility.

- It's expected for the release to be "stable" (functional).
- It's completely expected to introduce breaking changes very often.
- But major breaking changes better not happen very often in-order to not restrain users from using them.
- The `CCC` in the pattern is an incremental counter that has to be incremented for every release.
- Once 1000 is reached, the counter would overflow back to `0` (will it ever reach that?).

### Development

Used to represent untagged releases with git info accessible (when the source-code is directly executed).

### Custom

Used to represent untagged builds with no git info accessed.

Can have a tag if `version.txt` is set, or can be tag-less if it's absent.

Such builds would be made by unofficial developers.

## Tagging a build

For releases, pre-releases and experimental builds there would be a single-line text file at `src/version.txt` containing the version tag.

## Detecting version

1. Check for the existence of `version.txt`, if so read the release tag from it.
    1. Determine the type of the release by checking the patterns in the order defined in the table above.
    2. If it doesn't match any of the patterns and turns out to be an empty file, consider it a `Custom` build with no tag.
    3. Otherwise if it had some content, then consider it a `Custom` build with that content as the tag.
2. Attempt to determine the commit id (presuming the code is run from version control).
    1. If it was read successfully, set the release type as `Development` and use the commit as the tag.
        - In the UI displaying only the first 7 hex digits is enough.
3. Consider it an untagged custom build.# hlink

## 基础用法

```zsh
hlink /path/to/config.mjs
```

## 生成配置文件

使用以下命令
```bash
hlink gen /path/to/outputDir
```
如果没有指定`outputDir`，则默认**用户目录**生成。可以通过 `echo ~` 查看用户目录的具体路径
```
echo ~
/User/root
```

## 配置文件说明

通过 `vim ~/hlink.config.mjs`可以进行编辑，默认内容如下
```js
// 重要说明路径地址都请填写 绝对路径！！！！
export default {
  /**
   * 源路径与目标路径的映射关系
   * 例子:
   *  pathsMapping: {
   *     '/path/to/exampleSource': '/path/to/exampleDest',
   *     '/path/to/exampleSource2': '/path/to/exampleDest2'
   *  }
   */
  pathsMapping: {},
  /**
   * 需要包含的后缀，如果与exclude同时配置，则取两者的交集
   * include 留空表示包含所有文件
   *
   * 后缀不够用? 高阶用法: https://hlink.likun.me/other/v2.html#%E6%96%B0%E5%A2%9E%E5%8A%9F%E8%83%BD
   */
  include: [
    'mp4',
    'flv',
    'f4v',
    'webm',
    'm4v',
    'mov',
    'cpk',
    'dirac',
    '3gp',
    '3g2',
    'rm',
    'rmvb',
    'wmv',
    'avi',
    'asf',
    'mpg',
    'mpeg',
    'mpe',
    'vob',
    'mkv',
    'ram',
    'qt',
    'fli',
    'flc',
    'mod',
    'iso',
  ],
  /**
   * 需要排除的后缀，如果与include同时配置，则取两者的交集
   *
   * 后缀不


define CY_BT_HIGH_DUTY_DIRECTED_ADV_MIN_INTERVAL             400
#define CY_BT_HIGH_DUTY_DIRECTED_ADV_MAX_INTERVAL             800

#define CY_BT_LOW_DUTY_DIRECTED_ADV_MIN_INTERVAL              48
#define CY_BT_LOW_DUTY_DIRECTED_ADV_MAX_INTERVAL              48
#define CY_BT_LOW_DUTY_DIRECTED_ADV_DURATION                  30

#define CY_BT_HIGH_DUTY_NONCONN_ADV_MIN_INTERVAL              160
#define CY_BT_HIGH_DUTY_NONCONN_ADV_MAX_INTERVAL              160
#define CY_BT_HIGH_DUTY_NONCONN_ADV_DURATION                  30

#define CY_BT_LOW_DUTY_NONCONN_ADV_MIN_INTERVAL               2048
#define CY_BT_LOW_DUTY_NONCONN_ADV_MAX_INTERVAL               2048
#define CY_BT_LOW_DUTY_NONCONN_ADV_DURATION                   30

/* Advertisement and scan response packets defines */
#define CY_BT_ADV_PACKET_DATA_SIZE                            3

/* cy_bt_device_name is obsolete. Use app_gap_device_name instead. */
#define cy_bt_device_name                                     app_gap_device_name

/* External definitions */
extern const wiced_bt_device_address_t cy_bt_device_address;
extern wiced_bt_ble_advert_elem_t cy_bt_adv_packet_data[];

#endif /* CYCFG_GAP_H */


opt(flatten)]
    validator_config: libra_management::validator_config::ValidatorConfig,
}

impl RotateKey {
    pub fn execute(
        self,
        key_name: &'static str,
    ) -> Result<(TransactionContext, Ed25519PublicKey), Error> {
        let mut storage = StorageWrapper::new(
            self.validator_config.validator_backend.name(),
            &self.validator_config.validator_backend.validator_backend,
        )?;
        let key = storage.rotate_key(key_name)?;

        let set_validator_config = SetValidatorConfig {
            host: self.host,
            validator_config: self.validator_config,
            validator_address: None,
            fullnode_address: None,
        };

        set_validator_config.execute().map(|txn_ctx| (txn_ctx, key))
    }
}

#[derive(Debug, StructOpt)]
pub struct RotateConsensusKey {
    #[structopt(flatten)]
    rotate_key: RotateKey,
}

impl RotateConsensusKey {
    pub fn execute(self) -> Result<(TransactionContext, Ed25519PublicKey), Error> {
        self.rotate_key.execute(CONSENSUS_KEY)
    }
}

#[derive(Debug, StructOpt)]
pub struct RotateValidatorNetworkKey {
    #[structopt(flatten)]
    rotate_key: RotateKey,
}

impl RotateValidatorNetworkKey {
    pub fn execute(self) -> Result<(TransactionContext, x25519::PublicKey), Error> {
        let (txn_ctx, key) = self.rotate_key.execute(VALIDATOR_NETWORK_KEY)?;
        Ok((txn_ctx, to_x25519(key)?))
    }
}

#[derive(Debug, StructOpt)]
pub struct RotateFullNodeNetworkKey {
    #[structopt(flatten)]
    rotate_key: RotateKey,
}

impl RotateFullNodeNetworkKey {
    pub fn execute(self) -> Result<(TransactionContext, x25519::PublicKey), Error> {
        let (txn_ctx, key) = self.rotate_key.execute(FULLNODE_NETWORK_KEY)?;
        Ok((txn_ctx, to_x25519(key)?))
    }
}

fn decode_validator_address(
    address: RawEncNetworkAddress,
    account: &AccountAddress,
    key: &Key,
    addr_idx: u32,
) -> Result<NetworkAddress, Error> {
    let enc_addr = EncNetworkAddress::try_from(&address).map_err(|e| {
        Error::UnexpectedError(format!(
            "Failed to decode network address {}",
            e.to_string()
        ))
    })?;
    let raw_addr = enc_addr.decrypt(key, account, addr_idx).map_err(|e| {
        Error::UnexpectedError(format!(
            "Failed to decrypt network address {}",
            e.to_string()
        ))
    })?;
    decode_address(raw_addr)
}

fn decode_address(raw_address: RawNetworkAddress) -> Result<NetworkAddress, Error> {
    let network_address = NetworkAddress::try_from(&raw_address).map_err(|e| {
        Error::UnexpectedError(format!(
            "Failed to decode network address {}",
            e.to_string()
        ))
    })?;
    let protocols = network_address
        .as_slice()
        .iter()
        .filter(|protocol| match protocol {
            Protocol::Dns(_)
            | Protocol::Dns4(_)
            | Protocol::Dns6(_)
            | Protocol::Ip4(_)
            | Protocol::Ip6(_)
            | Protocol::Memory(_)
            | Protocol::Tcp(_) => true,
            _ => false,


t(keytip1.onExecute).toBeDefined();

    // Keytip2
    const keytip2 = keytipConfigMap.keytip2;
    expect(arraysEqual(keytip2.keySequences, keytip2Seq)).toEqual(true);
    expect(keytip2.content).toEqual('B1');
    expect(keytip2.disabled).toEqual(true);

    // Keytip3
    const keytip3 = keytipConfigMap.keytip3;
    expect(arraysEqual(keytip3.keySequences, keytip3Seq)).toEqual(true);
    expect(keytip3.content).toEqual('C');

    // Keytip4
    const keytip4 = keytipConfigMap.keytip4;
    expect(arraysEqual(keytip4.keySequences, keytip4Seq)).toEqual(true);
    expect(keytip4.content).toEqual('T2');

    // Keytip5
    const keytip5 = keytipConfigMap.keytip5;
    expect(arraysEqual(keytip5.keySequences, keytip5Seq)).toEqual(true);
    expect(keytip5.content).toEqual('F');

    // Keytip6
    const keytip6 = keytipConfigMap.keytip6;
    expect(arraysEqual(keytip6.keySequences, keytip6Seq)).toEqual(true);
    expect(keytip6.content).toEqual('X0');
    expect(keytip6.onReturn).toBeDefined();

    // Keytip7
    const keytip7 = keytipConfigMap.keytip7;
    expect(arraysEqual(keytip7.keySequences, keytip7Seq)).toEqual(true);
    expect(keytip7.content).toEqual('YY');

    // Keytip8
    const keytip8 = keytipConfigMap.keytip8;
    expect(arraysEqual(keytip8.keySequences, keytip8Seq)).toEqual(true);
    expect(keytip8.content).toEqual('R');
  });
});
import Packer from '../Packer';

describe('Packer', (): void => {
    it('should pack items', async (): Promise<void> => {
        const expectedResult: string = ['4', '-', '2,7', '8,9'].join('\n');
        const result: string = await Packer.pack(`${__dirname}/__mocks__/test-data.txt`);
        expect(result).toEqual(expectedResult);
    });

    it('should fail with APIException error', async (): Promise<void> => {
        expect.assertions(1);
        try {
            await Packer.pack('path/does/not/exist');
        } catch (error) {
            expect(error.name).toEqual('APIException');
        }
    });
});
import { isFuture } from "date-fns";
import express from "express";
import {
  createReview,
  deleteReview,
  getReview,
  getReviews,
  updateReview,
} from "../services/review";

const ROUTES_PREFIX = "/restaurant/:restaurantId/review";
const router = express.Router();

router.get(ROUTES_PREFIX, async (req, res) => {
  try {
    const { restaurantId } = req.params;
    const docs = await getReviews(restaurantId);
    return res.status(200).json({ data: { reviews: docs } });
  } catch (err) {
    console.log(err.message);
    return res.status(400).json({ error: `${err.code} - ${err.message}` });
  }
});

router.post(ROUTES_PREFIX, async (req, res) => {
  try {
    const { restaurantId } = req.params;
    const { visitDate, rating, comment } = req.body;
    if (!restaurantId || !visitDate || !rating || !comment) {
      return res.status(400).send({ message: "Missing fields" });
    }

    if (isFuture(new Date(visitDate))) {
      return res.status(400).send({ message: "Date cannot be in the future" });
    }

    const id = await createReview({
      restaurantId,
      visitDate,
      rating,
      comment,
    });
    return res.status


            IoK8sApiAutoscalingV1HorizontalPodAutoscaler.fromJson(row);
        if (value != null) {
          result.add(value);
        }
      }
    }
    return result.toList(growable: growable);
  }

  static Map<String, IoK8sApiAutoscalingV1HorizontalPodAutoscaler> mapFromJson(
      dynamic json) {
    final map = <String, IoK8sApiAutoscalingV1HorizontalPodAutoscaler>{};
    if (json is Map && json.isNotEmpty) {
      json = json.cast<String, dynamic>(); // ignore: parameter_assignments
      for (final entry in json.entries) {
        final value =
            IoK8sApiAutoscalingV1HorizontalPodAutoscaler.fromJson(entry.value);
        if (value != null) {
          map[entry.key] = value;
        }
      }
    }
    return map;
  }

  // maps a json object with a list of IoK8sApiAutoscalingV1HorizontalPodAutoscaler-objects as value to a dart map
  static Map<String, List<IoK8sApiAutoscalingV1HorizontalPodAutoscaler>>
      mapListFromJson(
    dynamic json, {
    bool growable = false,
  }) {
    final map = <String, List<IoK8sApiAutoscalingV1HorizontalPodAutoscaler>>{};
    if (json is Map && json.isNotEmpty) {
      json = json.cast<String, dynamic>(); // ignore: parameter_assignments
      for (final entry in json.entries) {
        final value = IoK8sApiAutoscalingV1HorizontalPodAutoscaler.listFromJson(
          entry.value,
          growable: growable,
        );
        if (value != null) {
          map[entry.key] = value;
        }
      }
    }
    return map;
  }

  /// The list of required keys that must be present in a JSON.
  static const requiredKeys = <String>{};
}
//
// AUTO-GENERATED FILE, DO NOT MODIFY!
//
// @dart=2.12

// ignore_for_file: require_trailing_commas
// ignore_for_file: unused_element
// ignore_for_file: unnecessary_this
// ignore_for_file: always_put_required_named_parameters_first
// ignore_for_file: constant_identifier_names
// ignore_for_file: lines_longer_than_80_chars
// ignore_for_file: avoid_function_literals_in_foreach_calls

import 'package:kubenav/models/kubernetes/helpers.dart';

class IoK8sApiAppsV1StatefulSetCondition {
  /// Returns a new [IoK8sApiAppsV1StatefulSetCondition] instance.
  IoK8sApiAppsV1StatefulSetCondition({
    this.lastTransitionTime,
    this.message,
    this.reason,
    required this.status,
    required this.type,
  });

  /// Time is a wrapper around time.Time which supports correct marshaling to YAML and JSON.  Wrappers are provided for many of the factory methods that the time package offers.
  ///
  /// Please note: This property should have been non-nullable! Since the specification file
  /// does not include a default value (using the "default:" property), however, the generated
  /// source code must fall back to having a nullable type.
  /// Consider adding a "default:" property in the specification file to hide this note.
  ///
  DateTime? lastTransitionTime;

  /// A human readable message indicating details about the transition.
  ///
  /// Please note: This property should have been non-nullable! Since the specification file
  /// does not include a default value (using the "default:" property), however, the generated
  /// source code must fall back to having a nullable type.
  /// Consider adding a "default:" property in the specification file to hide this


#!/usr/bin/env python
#
#  Copyright (c) 2014, Facebook, Inc.
#  All rights reserved.
#
#  This source code is licensed under the BSD-style license found in the
#  LICENSE file in the root directory of this source tree. An additional grant
#  of patent rights can be found in the PATENTS file in the same directory.
#
#
import os
import re
import sys

from setuptools import setup

readme = open("README.md", "r")

install_requires = [
    'pyroute2==0.3.3',
    'pyotp==1.4.1',
    'sparts==0.7.1',
    'atc_thrift'
]

tests_require = install_requires + [
    'pytest'
]

if sys.version < '3.3':
    tests_require.append('mock')

scripts = ['bin/atcd']

def get_version(package):
    """
    Return package version as listed in `__version__` in `init.py`.
    """
    init_py = open(os.path.join(package, '__init__.py')).read()
    return re.search("__version__ = ['\"]([^'\"]+)['\"]", init_py).group(1)

version = get_version('atcd')

if sys.argv[-1] == 'publish':
    if os.system("pip freeze | grep wheel"):
        print("wheel not installed.\nUse `pip install wheel`.\nExiting.")
        sys.exit()
    if os.system("pip freeze | grep twine"):
        print("twine not installed.\nUse `pip install twine`.\nExiting.")
        sys.exit()
    os.system("python setup.py sdist bdist_wheel")
    os.system("twine upload dist/*")
    print("You probably want to also tag the version now:")
    print("  git tag -a %s -m 'version %s'" % (version, version))
    print("  git push --tags")
    sys.exit()

setup(
    name='atcd',
    version=version,
    description='ATC Daemon',
    author='Emmanuel Bretelle',
    author_email='chantra@fb.com',
    url='https://github.com/facebook/augmented-traffic-control',
    packages=['atcd',
              'atcd.backends',
              'atcd.scripts',
              'atcd.tools'],
    classifiers=['Programming Language :: Python', ],
    long_description=readme.read(),
    scripts=scripts,
    install_requires=install_requires,
    tests_require=tests_require,
)


 `Trie`树每一次调用`Commit`方法，会导致当前的`cachegen`增加1。

```go
func (t *Trie) Commit(onleaf LeafCallback) (root common.Hash, err error) {
   ...
    t.cachegen++
   ...
}
```

然后在`Trie`树插入的时候，会把当前的`cachegen`存放到节点中。

```go
func (t *Trie) insert(n node, prefix, key []byte, value node) (bool, node, error) {
            ....
            return true, &shortNode{n.Key, nn, t.newFlag()}, nil
}
func (t *Trie) newFlag() nodeFlag {
    return nodeFlag{dirty: true, gen: t.cachegen}
}

```

如果 `trie.cachegen - node.cachegen > cachelimit`，就可以把节点从内存里面拿掉。 也就是说节点经过几次`Commit`，都没有修改，那么就把节点从内存里面干掉。 只要`trie`路径上新增或者删除一个节点，整个路径的节点都需要重新实例化，也就是节点中的`nodeFlag`被初始化了。都需要重新更新到`db`磁盘。

拿掉节点过程在 `hasher.hash`方法中， 这个方法是在`commit`的时候调用。如果方法的`canUnload`方法调用返回真，那么就拿掉节点，如果只返回了`hash`节点，而没有返回`node`节点，这样节点就没有引用，不久就会被gc清除掉。 节点被拿掉之后，会用一个`hashNode`节点来表示这个节点以及其子节点。 如果后续需要使用，可以通过方法把这个节点加载到内存里面来。

```go
func (h *hasher) hash(n node, db *Database, force bool) (node, node, error) {
   	....
       // 从缓存中卸载节点。它的所有子节点将具有较低或相等的缓存世代号码。
       cacheUnloadCounter.Inc(1)
  ...
}
```

## 参考&总结

这部分重要的内容也就上面讲述的，主要集中在`Trie`上面，如果有不对的地方，可以及时指正哦。

> https://mindcarver.cn/about/
>
> https://github.com/blockchainGuide/blockchainguide

baseapp 实现了 cometBFT定义的接口：

```go
type Application interface {
	// Info/Query Connection
	Info(RequestInfo) ResponseInfo    // Return application info
	Query(RequestQuery) ResponseQuery // Query for state

	// Mempool Connection
	CheckTx(RequestCheckTx) ResponseCheckTx // Validate a tx for the mempool

	// Consensus Connection
	InitChain(RequestInitChain) ResponseInitChain // Initialize blockchain w validators/other info from CometBFT
	PrepareProposal(RequestPrepareProposal) ResponsePrepareProposal
	ProcessProposal(RequestProcessProposal) ResponseProcessProposal
	BeginBlock(RequestBeginBlock) ResponseBeginBlock // Signals the beginning of a block
	DeliverTx(RequestDeliverTx) ResponseDeliverTx


/********************************************************************************/
/*										*/
/*			    TPM 1.2 FlushSpecific				*/
/*			     Written by Ken Goldman				*/
/*		       IBM Thomas J. Watson Research Center			*/
/*	      $Id: FlushSpecific_fp.h 1257 2018-06-27 20:52:08Z kgoldman $	*/
/*										*/
/* (c) Copyright IBM Corporation 2018.						*/
/*										*/
/* All rights reserved.								*/
/* 										*/
/* Redistribution and use in source and binary forms, with or without		*/
/* modification, are permitted provided that the following conditions are	*/
/* met:										*/
/* 										*/
/* Redistributions of source code must retain the above copyright notice,	*/
/* this list of conditions and the following disclaimer.			*/
/* 										*/
/* Redistributions in binary form must reproduce the above copyright		*/
/* notice, this list of conditions and the following disclaimer in the		*/
/* documentation and/or other materials provided with the distribution.		*/
/* 										*/
/* Neither the names of the IBM Corporation nor the names of its		*/
/* contributors may be used to endorse or promote products derived from		*/
/* this software without specific prior written permission.			*/
/* 										*/
/* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS		*/
/* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT		*/
/* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR	*/
/* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT		*/
/* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,	*/
/* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT		*/
/* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,	*/
/* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY	*/
/* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT		*/
/* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE	*/
/* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.		*/
/********************************************************************************/

#ifndef FLUSHSPECIFIC_FP_H
#define FLUSHSPECIFIC_FP_H

#include <ibmtss/tpmtypes12.h>
#include <ibmtss/tpmstructures12.h>

#include <ibmtss/Implementation.h>

typedef struct {
    TPM_HANDLE handle;
    TPM_RESOURCE_TYPE resourceType;
} FlushSpecific_In;

TPM_RC
TPM2_FlushSpecific(
		   FlushSpecific_In *in            // IN: input parameter buffer
		   );

#endif


ke(chan<- int, "foo" /* ERROR "cannot convert" */)
	_ = make(chan int, - /* ERROR "must not be negative" */ 10)
	_ = make(<-chan float64, 10)
	_ = make(chan chan int, n)
	_ = make(chan string, int64(n))
	_ = make(chan bool, 10.0)
	_ = make(chan bool, 10.0<<s)
        _ = &make /* ERROR "cannot take address" */ (chan bool)

	make /* ERROR "not used" */ ([]int, 10)

	var t []int
	_ = make([]int, t[0], t[1])
	_ = make([]int, t... /* ERROR "invalid use of ..." */ )
}

func make2() {
	f1 := func() (x []int) { return }
	_ = make(f0 /* ERROR "not a type" */ ())
	_ = make(f1 /* ERROR "not a type" */ ())
}

func max1() {
	var b bool
	var c complex128
	var x int
	var s string
	type myint int
	var m myint
	_ = max() /* ERROR "not enough arguments" */
	_ = max(b /* ERROR "cannot be ordered" */ )
	_ = max(c /* ERROR "cannot be ordered" */ )
	_ = max(x)
	_ = max(s)
	_ = max(x, x)
	_ = max(x, x, x, x, x)
	var _ int = max /* ERROR "cannot use max(m) (value of type myint) as int value" */ (m)
	_ = max(x, m /* ERROR "invalid argument: mismatched types int (previous argument) and myint (type of m)" */ , x)

	_ = max(1, x)
	_ = max(1.0, x)
	_ = max(1.2 /* ERROR "1.2 (untyped float constant) truncated to int" */ , x)
	_ = max(-10, 1.0, c /* ERROR "cannot be ordered" */ )

	const (
		_ = max /* ERROR "max(x) (value of type int) is not constant" */ (x)
		_ = max(true /* ERROR "invalid argument: true (untyped bool constant) cannot be ordered" */ )
		_ = max(1)
		_ = max(1, 2.3, 'a')
		_ = max(1, "foo" /* ERROR "mismatched types" */ )
		_ = max(1, 0i /* ERROR "cannot be ordered" */ )
		_ = max(1, 2 /* ERROR "cannot be ordered" */ + 3i )
	)
}

func max2() {
	_ = assert(max(0) == 0)
	_ = assert(max(0, 1) == 1)
	_ = assert(max(0, -10, 123456789) == 123456789)
	_ = assert(max(-12345678901234567890, 0) == 0)

	_ = assert(max(1, 2.3) == 2.3)
	_ = assert(max(1, 2.3, 'a') == 'a')

	_ = assert(max("", "a") == "a")
	_ = assert(max("abcde", "xyz", "foo", "bar") == "xyz")

	const (
		_ int = max(1.0)
		_ float32 = max(1, 2)
		_ int = max /* ERROR "cannot use max(1, 2.3) (untyped float constant 2.3) as int value" */ (1, 2.3)
		_ int = max(1.2, 3) // ok!
		_ byte = max(1, 'a')
	)
}

func min1() {
	var b bool
	var c complex128
	var x int
	var s string
	type myint int
	var m myint
	_ = min() /* ERROR "not enough arguments" */
	_ = min(b /* ERROR "cannot be ordered" */ )
	_ = min(c /* ERROR "cannot be ordered" */ )
	_ = min(x)
	_ = min(s)
	_ = min(x, x)


", "<C-c>": //q or Ctrl-C to quit
				return core.ErrCanceledByUser

			case "<Resize>":
				updateUI()

			case "?":
				scrollableWidget.DisableCursor()
				scrollableWidget = help.Table
				scrollableWidget.EnableCursor()
				utilitySelected = core.Help
				updateUI()

			case "p":
				pause()

			case "<Escape>":
				utilitySelected = core.None
				scrollableWidget = page.DetailsTable
				scrollableWidget.EnableCursor()
				updateUI()

			// handle table selection
			case "1", "2", "3", "4", "5", "6":
				if utilitySelected == core.None {
					scrollableWidget.DisableCursor()
					scrollableWidget = tableMap[e.ID]
					scrollableWidget.EnableCursor()
				}

			// handle table navigations
			case "j", "<Down>":
				scrollableWidget.ScrollDown()

			case "k", "<Up>":
				scrollableWidget.ScrollUp()

			case "<C-d>":
				scrollableWidget.ScrollHalfPageDown()

			case "<C-u>":
				scrollableWidget.ScrollHalfPageUp()

			case "<C-f>":
				scrollableWidget.ScrollPageDown()

			case "<C-b>":
				scrollableWidget.ScrollPageUp()

			case "g":
				if previousKey == "g" {
					scrollableWidget.ScrollTop()
				}

			case "<Home>":
				scrollableWidget.ScrollTop()

			case "G", "<End>":
				scrollableWidget.ScrollBottom()

			}

			updateUI()
			if previousKey == "g" {
				previousKey = ""
			} else {
				previousKey = e.ID
			}

		case data := <-dataChannel:
			// page.BodyList.SelectedRowStyle = selectedStyle
			if runProc {
				// update cpu %
				page.CPUChart.Percent = int(data.CPU)

				// update mem %
				page.MemChart.Percent = int(data.Mem)

				// update Net RX and TX
				netVals, units := utils.RoundValues(data.Net.Rx, data.Net.Tx, true)
				page.NetChart.Data = netVals
				page.NetChart.Title = " Net I/O " + units

				// update Block IO
				blkVals, units := utils.RoundValues(float64(data.Blk.Read), float64(data.Blk.Write), true)
				page.BlkChart.Data = blkVals
				page.BlkChart.Title = " Block I/O " + units

				// update details table
				page.DetailsTable.Header = []string{"Name", data.Name}
				page.DetailsTable.Rows = [][]string{
					{"Image", data.Image},
					{"ID", data.ID},
					{"Status", data.Status},
					{"State", data.State},
					{"Pid", data.Pid},
				}

				// update mount volumes table
				mountData := [][]string{}
				for _, m := range data.Mounts {
					mountData = append(mountData, []string{
						m.Src,
						m.Dst,
						m.Mode,
					})
				}
				page.MountTable.Rows = mountData

				// update network settings table
				netData := [][]string{}
				for _, n := range data.NetInfo {
					netData = append(netData, []string{
						n.Name,
						n.Driver,
						n.IP,
						strconv.FormatBool(n.Ingress),
					})
				}
				page.NetworkTable.Rows = netData

				// update per cpu table
				cpuData := [][]string{}
				for i, c := range data.PerCPU {
					cpuData = append(cpuData, []string{
						fmt.Sprintf("CPU %d", i),
						c,
					})
				}
				page.CPUUsageTable.Rows = cpuData

				//


 {
				sql, _ := NewSQL("INSERT INTO test (id, name) VALUES (1, 'test')") //nolint:errcheck // ignore error
				return sql
			}(),
			want: true,
		},
		{
			name: "is not INSERT - SELECT",
			sql: func() *SQL {
				sql, _ := NewSQL("SELECT * FROM test") //nolint:errcheck // ignore error
				return sql
			}(),
			want: false,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			t.Parallel()
			if got := tt.sql.IsInsert(); got != tt.want {
				t.Errorf("SQL.IsInsert() = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestSQLIsUpdate(t *testing.T) {
	tests := []struct {
		name string
		sql  *SQL
		want bool
	}{
		{
			name: "is UPDATE - simple",
			sql: func() *SQL {
				sql, _ := NewSQL("UPDATE test SET name = 'updated'") //nolint:errcheck // ignore error
				return sql
			}(),
			want: true,
		},
		{
			name: "is UPDATE - with WHERE",
			sql: func() *SQL {
				sql, _ := NewSQL("UPDATE test SET name = 'updated' WHERE id = 1") //nolint:errcheck // ignore error
				return sql
			}(),
			want: true,
		},
		{
			name: "is not UPDATE - SELECT",
			sql: func() *SQL {
				sql, _ := NewSQL("SELECT * FROM test") //nolint:errcheck // ignore error
				return sql
			}(),
			want: false,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			t.Parallel()
			if got := tt.sql.IsUpdate(); got != tt.want {
				t.Errorf("SQL.IsUpdate() = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestSQLIsDelete(t *testing.T) {
	tests := []struct {
		name string
		sql  *SQL
		want bool
	}{
		{
			name: "is DELETE - simple",
			sql: func() *SQL {
				sql, _ := NewSQL("DELETE FROM test") //nolint:errcheck // ignore error
				return sql
			}(),
			want: true,
		},
		{
			name: "is DELETE - with WHERE",
			sql: func() *SQL {
				sql, _ := NewSQL("DELETE FROM test WHERE id = 1") //nolint:errcheck // ignore error
				return sql
			}(),
			want: true,
		},
		{
			name: "is not DELETE - SELECT",
			sql: func() *SQL {
				sql, _ := NewSQL("SELECT * FROM test") //nolint:errcheck // ignore error
				return sql
			}(),
			want: false,
		},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			t.Parallel()
			if got := tt.sql.IsDelete(); got != tt.want {
				t.Errorf("SQL.IsDelete() = %v, want %v", got, tt.want)
			}
		})
	}
}

func TestSQLIsExplain(t *testing.T) {
	tests := []struct {
		name string
		sql  *SQL
		want bool
	}{
		{
			name: "is EXPLAIN - SELECT",
			sql: func() *SQL {
				sql, _ := NewSQL("EXPLAIN SELECT * FROM test") //nolint:errcheck // ignore error
				return sql
			}(),
			want: true,
		},
		{
			name: "is EXPLAIN - with ANALYZE",
			sql: func() *SQL {


.1  | HIGH | 在网页生成过程中对输入的不正确中和（`跨站脚本攻击`）漏洞存在于 tayoricom 的 Tayori Form 中，这允许反射型 XSS。此问题影响 Tayori Form：从 n/a 到 1.2.9 版本。 | [1]https://patchstack.com/database/wordpress/plugin/tayori/vulnerability/wordpress-tayori-form-plugin-1-2-9-reflected-cross-site-scripting-xss-vulnerability?_s_id=cve |
| 53 | CVE-2025-46440 | 7.1  | HIGH | 在生成网页过程中对输入的不当中和（`跨站脚本攻击`）漏洞存在于 Mark kStats Reloaded 中，这可能导致反射型跨站脚本攻击 (Reflected XSS)。此问题影响 kStats Reloaded 版本：从 n/a 到 0.7.4。 | [1]https://patchstack.com/database/wordpress/plugin/kstats-reloaded/vulnerability/wordpress-kstats-reloaded-plugin-0-7-4-reflected-cross-site-scripting-xss-vulnerability?_s_id=cve |
| 54 | CVE-2025-46444 | 8.1  | HIGH | PHP程序中`include/require`语句的文件名控制不当（`PHP远程文件包含`）漏洞存在于scripteo Ads Pro插件中，允许PHP本地文件包含。此问题影响Ads Pro插件：从n/a到4.88版本。 | [1]https://patchstack.com/database/wordpress/plugin/ap-plugin-scripteo/vulnerability/wordpress-ads-pro-plugin-4-88-local-file-inclusion-vulnerability?_s_id=cve |
| 55 | CVE-2025-46446 | 7.1  | HIGH | 在ivanrojas的《意见簿》（Libro de Reclamaciones）中存在一个“Web页面生成时输入未正确过滤”（`跨站脚本攻击`，Cross-site Scripting）漏洞，允许存储型XSS。此问题影响《意见簿》版本：从n/a到1.0.1。 | [1]https://patchstack.com/database/wordpress/plugin/libro-de-reclamaciones/vulnerability/wordpress-libro-de-reclamaciones-1-0-1-cross-site-scripting-xss-vulnerability?_s_id=cve |
| 56 | CVE-2025-46448 | 7.1  | HIGH | 在reifsnyderb文档管理系统中，Web页面生成过程中对输入的不当 neutralization（未中和）导致了 `跨站脚本攻击`（Cross-site Scripting）漏洞，允许反射型XSS。此问题影响文档管理系统：从n/a到1.24版本。 | [1]https://patchstack.com/database/wordpress/plugin/dms/vulnerability/wordpress-document-management-system-1-24-cross-site-scripting-xss-vulnerability?_s_id=cve |
| 57 | CVE-2025-46454 | 7.5  | HIGH | 在 PHP 程序中，`PHP 远程文件包含`漏洞（即不正确地控制 `include/require` 语句的文件名）存在于 svil4ok 的 Meta Keywords 和 Description 中


85,146.381101 1.47801933,144.437125 L69.8255435,7.74207645 C73.283393,0.826377491 81.6928155,-1.97676336 88.6085145,1.48108612 C91.3178981,2.83577793 93.514813,5.03269282 94.8695048,7.74207645 Z M70.4105124,130.924678 C70.4105124,134.182506 71.5529978,136.953882 73.8380027,139.238887 C76.1230076,141.523892 78.8943829,142.666377 82.1522117,142.666377 C85.4100404,142.666377 88.1814157,141.523892 90.4664206,139.238887 C92.7514256,136.953882 93.8939109,134.182506 93.8939109,130.924678 C93.8939109,127.666849 92.7514256,124.895474 90.4664206,122.610469 C88.1814157,120.325464 85.4100404,119.182978 82.1522117,119.182978 C78.8943829,119.182978 76.1230076,120.325464 73.8380027,122.610469 C71.5529978,124.895474 70.4105124,127.666849 70.4105124,130.924678 Z M70.4105124,58.845576 C70.4105124,60.5649857 70.7951115,62.9404502 71.564321,65.9720409 C72.0620449,67.9176886 73.170595,71.8089258 74.8900046,77.645869 C76.2474333,82.2158788 77.1523722,85.7677639 77.6048484,88.3016307 C78.0573246,90.8354976 78.93964,97.4867982 80.251821,108.255732 L84.2562156,108.255732 C85.2064156,99.7039317 85.8964315,94.0141286 86.3262839,91.1861522 C86.7561363,88.3581758 87.5592696,84.8176025 88.7357078,80.564326 C90.6813555,73.505697 92.0274521,68.4267276 92.7740378,65.3272655 C93.5206236,62.2278034 93.8939109,59.9088975 93.8939109,58.3704784 C93.8939109,53.4837352 92.7061786,49.9770971 90.3306785,47.8504589 C87.9551783,45.7238206 85.22905,44.6605175 82.1522117,44.6605175 C78.9848781,44.6605175 76.2361263,45.7351324 73.9058738,47.8843944 C71.5756212,50.0336565 70.4105124,53.6873471 70.4105124,58.845576 Z' id='Error' fill='%23d9534f'%3E%3C/path%3E%3C/g%3E%3C/svg%3E");
    background-size: 28px 28px;
    width: 28px;
    height: 28px;
    opacity: 0.3; }
  .premonition.pn-quote {
    border: 0;
    margin: 3px 0 0 14px;
    background-repeat: no-repeat;
    background-color: transparent;
    background-image: url("data:image/svg+xml,%3C%3Fxml version='1.0' encoding='UTF-8'%3F%3E%3Csvg width='165px' height='165px' viewBox='0 0 165 165' ve


8044532C
/* 80445324 00442124  38 60 00 00 */	li r3, 0
/* 80445328 00442128  48 00 03 60 */	b lbl_80445688
lbl_8044532C:
/* 8044532C 0044212C  3C 60 80 51 */	lis r3, lbl_80508BC8@ha
/* 80445330 00442130  57 7E 10 3A */	slwi r30, r27, 2
/* 80445334 00442134  3B E3 8B C8 */	addi r31, r3, lbl_80508BC8@l
/* 80445338 00442138  7C 7F F0 2E */	lwzx r3, r31, r30
/* 8044533C 0044213C  2C 03 FF FF */	cmpwi r3, -1
/* 80445340 00442140  41 82 00 08 */	beq lbl_80445348
/* 80445344 00442144  48 00 43 05 */	bl func_80449648
lbl_80445348:
/* 80445348 00442148  57 03 06 3E */	clrlwi r3, r24, 0x18
/* 8044534C 0044214C  3C 00 43 30 */	lis r0, 0x4330
/* 80445350 00442150  90 61 00 2C */	stw r3, 0x2c(r1)
/* 80445354 00442154  C8 E2 FA 50 */	lfd f7, lbl_805E6150@sda21(r2)
/* 80445358 00442158  90 01 00 28 */	stw r0, 0x28(r1)
/* 8044535C 0044215C  C0 02 F9 FC */	lfs f0, lbl_805E60FC@sda21(r2)
/* 80445360 00442160  C8 21 00 28 */	lfd f1, 0x28(r1)
/* 80445364 00442164  EC 21 38 28 */	fsubs f1, f1, f7
/* 80445368 00442168  FC 01 00 40 */	fcmpo cr0, f1, f0
/* 8044536C 0044216C  40 81 00 A4 */	ble lbl_80445410
/* 80445370 00442170  90 61 00 2C */	stw r3, 0x2c(r1)
/* 80445374 00442174  C8 C2 FA 00 */	lfd f6, lbl_805E6100@sda21(r2)
/* 80445378 00442178  90 01 00 28 */	stw r0, 0x28(r1)
/* 8044537C 0044217C  C8 A2 FA 08 */	lfd f5, lbl_805E6108@sda21(r2)
/* 80445380 00442180  C8 01 00 28 */	lfd f0, 0x28(r1)
/* 80445384 00442184  90 61 00 34 */	stw r3, 0x34(r1)
/* 80445388 00442188  FC 00 38 28 */	fsub f0, f0, f7
/* 8044538C 0044218C  90 01 00 30 */	stw r0, 0x30(r1)
/* 80445390 00442190  FC 60 00 34 */	frsqrte f3, f0
/* 80445394 00442194  C8 01 00 30 */	lfd f0, 0x30(r1)
/* 80445398 00442198  90 61 00 3C */	stw r3, 0x3c(r1)
/* 8044539C 0044219C  FC 40 38 28 */	fsub f2, f0, f7
/* 804453A0 004421A0  FC 23 00 F2 */	fmul f1, f3, f3
/* 804453A4 004421A4  90 01 00 38 */	stw r0, 0x38(r1)
/* 8


)
	if !exists {
		return fmt.Errorf("destination chain %d not found in state", c.DestinationChainSelector)
	}
	// check for existing chain contracts on both source and destination chains
	if err := arePrerequisitesMet(sourceChainState, sourceChain); err != nil {
		return err
	}
	if err := arePrerequisitesMet(destChainState, destChain); err != nil {
		return err
	}
	// TODO: Add rest of the config validation
	return nil
}

func (c *DeployLaneConfig) populateAddresses(state stateview.CCIPOnChainState) error {
	sourceChainState := state.MustGetEVMChainState(c.SourceChainSelector)
	srcLink, err := sourceChainState.LinkTokenAddress()
	if err != nil {
		return fmt.Errorf("failed to get LINK token address for source chain %d: %w", c.SourceChainSelector, err)
	}
	c.OnRampStaticCfg.LinkToken = srcLink
	c.OnRampStaticCfg.RmnProxy = sourceChainState.RMNProxy.Address()
	c.OnRampStaticCfg.TokenAdminRegistry = sourceChainState.TokenAdminRegistry.Address()

	c.OnRampDynamicCfg.Router = sourceChainState.Router.Address()
	c.OnRampDynamicCfg.PriceRegistry = sourceChainState.PriceRegistry.Address()
	return nil
}

func DeployLanesChangeset(env cldf.Environment, c DeployLanesConfig) (cldf.ChangesetOutput, error) {
	state, err := stateview.LoadOnchainState(env)
	if err != nil {
		return cldf.ChangesetOutput{}, fmt.Errorf("failed to load CCIP onchain state: %w", err)
	}
	if err := c.Validate(env, state); err != nil {
		return cldf.ChangesetOutput{}, fmt.Errorf("invalid DeployChainContractsConfig: %w", err)
	}
	// populate addresses from the state
	for i := range c.Configs {
		if err := c.Configs[i].populateAddresses(state); err != nil {
			return cldf.ChangesetOutput{}, err
		}
	}
	newAddresses := cldf.NewMemoryAddressBook()
	for _, cfg := range c.Configs {
		if err := deployLane(env, state, newAddresses, cfg); err != nil {
			return cldf.ChangesetOutput{
				AddressBook: newAddresses,
			}, err
		}
	}
	return cldf.ChangesetOutput{
		AddressBook: newAddresses,
	}, nil
}

func deployLane(e cldf.Environment, state stateview.CCIPOnChainState, ab cldf.AddressBook, cfg DeployLaneConfig) error {
	// update prices on the source price registry
	sourceChainState := state.MustGetEVMChainState(cfg.SourceChainSelector)
	destChainState := state.MustGetEVMChainState(cfg.DestinationChainSelector)
	sourceChain := e.BlockChains.EVMChains()[cfg.SourceChainSelector]
	destChain := e.BlockChains.EVMChains()[cfg.DestinationChainSelector]
	sourcePriceReg := sourceChainState.PriceRegistry
	tx, err := sourcePriceReg.UpdatePrices(sourceChain.DeployerKey, price_registry_1_2_0.InternalPriceUpdates{
		TokenPriceUpdates: cfg.InitialTokenPrices,
		GasPriceUpdates:   cfg.GasPriceUpdates,
	})
	if err != nil {
		return err
	}
	_, err = sourceChain.Confirm(tx)
	if err != nil {
		return fmt.Errorf("failed to confirm price update tx for chain %s: %w", sourceChain.String(), cldf.MaybeDataErr(err))
	}
	// ================================================================
	// │                        D