}

  public _getValue(value: string) {
    let snippets = value.match(this._snippetRegex);
    snippets.forEach(snippet => {
      value = value.replace(snippet, this._getSnippetContent(snippet));
    });
    return value;
  }

  public _getSnippetContent(snippet) {
    this.snippetsList.forEach(s => {
      if (
        s.name.toLowerCase() ===
        snippet
          .trim()
          .replace('`', '')
          .toLowerCase()
      ) {
        snippet = s.content;
      }
    });
    return snippet;
  }
}
import EventDispatcher from '../events/EventDispatcher'
import UtilsEvent from '../events/UtilsEvent'

/**
 * 加载序列
 */
export default class LoadQueue extends EventDispatcher {
  private _currentIndex: number = 0;
  private _list: string[] = [];
  private _loading: Boolean;

  constructor (assetsList: string[]) {
    super()

    this._list = assetsList
  }

  public start ():void {
    if (this._loading) {
      return
    }
    this._loading = true
    this._loadAsset(this._list[this._currentIndex])
  }

  private _loadAsset (src: string):void {
    var img:HTMLImageElement = new Image()
    img.onload = () => {
      this._currentIndex ++
      this.dispatchWith(UtilsEvent.LOAD_QUEUE_PROGRESS,  this._currentIndex, this._list.length, img)
      if (this._currentIndex >= this._list.length) {
        this.dispatchWith(UtilsEvent.LOAD_QUEUE_COMPLETE)
      }
    }
    img.onerror = (e: any) => {
      this.dispatchWith(UtilsEvent.LOAD_QUEUE_ERROR, e, src)
      this.dispatchWith(UtilsEvent.LOAD_QUEUE_PROGRESS,  this._currentIndex, this._list.length, img)
      if (this._currentIndex >= this._list.length) {
        this.dispatchWith(UtilsEvent.LOAD_QUEUE_COMPLETE)
      }
    }
    img.src = src
  }
}import { AcceptedResponse, ExportRoutes, RouteConfiguration, Routed } from '@/router'

import { SlashCommandBuilder } from '@discordjs/builders'

export const Routes = ExportRoutes(
  new RouteConfiguration({
    category: 'Admin',
    controller: listCommandCategories,
    description: 'Help.Admin.CommandCategories.Description',
    example: '{{prefix}}admin commands',
    name: 'admin-commands-slash',
    permissions: {
      serverAdminOnly: true
    },
    slash: new SlashCommandBuilder().setName('admin').setDescription('Server Administrator Commands to adjust functionality of Kiera'),
    type: 'discord-chat-interaction',
    validate: '/admin:string/commands:string'
  })
  // {
  //   category: 'Admin',
  //   controller: listCommandCategories,
  //   description: 'Help.Admin.CommandCategories.Description',
  //   example: '{{prefix}}admin commands',
  //   name: 'admin-command-categories',
  //   permissions: {
  //     serverAdminOnly: true
  //   },
  //   type: 'message',
  //   validate: '/admin:string/commands:string'
  // },
  // {
  //   category: 'Admin',
  //   controller: listCategoryCommands,
  //   description: 'Help.Admin.CategoryCommands.Description',
  //   example: '{{prefix}}admin category Fun',
  //   name: 'admin-category-commands',
  //   permissions: {
  //     serverAdminOnly: true
  //   },
  //   type: 'message',
  //   validate: '/admin:string/commands:string/category:string/category=string'
  // },
  // {
  //   category: 'Admin',
  //   controller: commandRestrict,
  //   description: 'Help.Admin.CommandRes


}

@media (-moz-os-version: windows-xp),
       (-moz-os-version: windows-vista),
       (-moz-os-version: windows-win7) {
  /* < Win8 */
  :root {
    --toolbarbutton-hover-background: linear-gradient(hsla(0,0%,100%,.6), hsla(0,0%,100%,.1));
    --toolbarbutton-hover-bordercolor: hsla(210,54%,20%,.15) hsla(210,54%,20%,.2) hsla(210,54%,20%,.25);
    --toolbarbutton-hover-boxshadow: 0 1px hsla(0,0%,100%,.3) inset,
                                     0 1px hsla(210,54%,20%,.03),
                                     0 0 2px hsla(210,54%,20%,.1);

    --toolbarbutton-active-background: hsla(210,54%,20%,.15) linear-gradient(hsla(0,0%,100%,.6), hsla(0,0%,100%,.1));
    --toolbarbutton-active-bordercolor: hsla(210,54%,20%,.3) hsla(210,54%,20%,.35) hsla(210,54%,20%,.4);
    --toolbarbutton-active-boxshadow: 0 1px 1px hsla(210,54%,20%,.1) inset,
                                      0 0 1px hsla(210,54%,20%,.2) inset,
/* allows keyhole-forward-clip-path to be used for non-hover as well as hover: */
                                      0 1px 0 hsla(210,54%,20%,0),
                                      0 0 2px hsla(210,54%,20%,0);

    --toolbarbutton-checkedhover-backgroundcolor: rgba(90%,90%,90%,.4);
  }
}

#nav-bar .toolbarbutton-1 > .toolbarbutton-menubutton-button > .toolbarbutton-icon:-moz-locale-dir(ltr),
#nav-bar .toolbarbutton-1 > .toolbarbutton-menubutton-dropmarker > .dropmarker-icon:-moz-locale-dir(rtl) {
  border-top-right-radius: 0;
  border-bottom-right-radius: 0;
}

#nav-bar .toolbarbutton-1 > .toolbarbutton-menubutton-button > .toolbarbutton-icon:-moz-locale-dir(rtl),
#nav-bar .toolbarbutton-1 > .toolbarbutton-menubutton-dropmarker > .dropmarker-icon:-moz-locale-dir(ltr) {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}

#nav-bar .toolbarbutton-1 > .toolbarbutton-menubutton-button > .toolbarbutton-icon {
  border-inline-end-style: none;
}

#nav-bar .toolbarbutton-1:not(:-moz-any(@primaryToolbarButtons@)) > .toolbarbutton-icon,
#nav-bar .toolbarbutton-1:not(:-moz-any(@primaryToolbarButtons@)) > .toolbarbutton-badge-stack,
#nav-bar .toolbarbutton-1:not(:-moz-any(@primaryToolbarButtons@)) > .toolbarbutton-menubutton-button > .toolbarbutton-icon {
  padding: calc(var(--toolbarbutton-vertical-inner-padding) + 1px) 7px;
}

#nav-bar .toolbarbutton-1[type=panel] > .toolbarbutton-icon,
#nav-bar .toolbarbutton-1[type=panel] > .toolbarbutton-badge-stack,
#nav-bar .toolbarbutton-1[type=menu]:not(#PanelUI-menu-button):not(#back-button):not(#forward-button) > .toolbarbutton-icon,
#nav-bar .toolbarbutton-1[type=menu]:not(#PanelUI-menu-button) > .toolbarbutton-badge-stack,
#nav-bar .toolbarbutton-1[type=menu] > .toolbarbutton-text /* hack for add-ons that forcefully display the label */ {
  -moz-padding-end: 17px;
}

#nav-


cutter.net.proto.NDKAMJGCKKNOuterClass.NDKAMJGCKKNOrBuilder>
        getLevelInfoListOrBuilderList();
    /**
     * repeated .NDKAMJGCKKN level_info_list = 15;
     */
    emu.grasscutter.net.proto.NDKAMJGCKKNOuterClass.NDKAMJGCKKNOrBuilder getLevelInfoListOrBuilder(
        int index);
  }
  /**
   * Protobuf type {@code PNJGECAFHGE}
   */
  public static final class PNJGECAFHGE extends
      com.google.protobuf.GeneratedMessageV3 implements
      // @@protoc_insertion_point(message_implements:PNJGECAFHGE)
      PNJGECAFHGEOrBuilder {
  private static final long serialVersionUID = 0L;
    // Use PNJGECAFHGE.newBuilder() to construct.
    private PNJGECAFHGE(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
      super(builder);
    }
    private PNJGECAFHGE() {
      levelInfoList_ = java.util.Collections.emptyList();
    }

    @java.lang.Override
    @SuppressWarnings({"unused"})
    protected java.lang.Object newInstance(
        UnusedPrivateParameter unused) {
      return new PNJGECAFHGE();
    }

    @java.lang.Override
    public final com.google.protobuf.UnknownFieldSet
    getUnknownFields() {
      return this.unknownFields;
    }
    private PNJGECAFHGE(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      this();
      if (extensionRegistry == null) {
        throw new java.lang.NullPointerException();
      }
      int mutable_bitField0_ = 0;
      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
          com.google.protobuf.UnknownFieldSet.newBuilder();
      try {
        boolean done = false;
        while (!done) {
          int tag = input.readTag();
          switch (tag) {
            case 0:
              done = true;
              break;
            case 122: {
              if (!((mutable_bitField0_ & 0x00000001) != 0)) {
                levelInfoList_ = new java.util.ArrayList<emu.grasscutter.net.proto.NDKAMJGCKKNOuterClass.NDKAMJGCKKN>();
                mutable_bitField0_ |= 0x00000001;
              }
              levelInfoList_.add(
                  input.readMessage(emu.grasscutter.net.proto.NDKAMJGCKKNOuterClass.NDKAMJGCKKN.parser(), extensionRegistry));
              break;
            }
            default: {
              if (!parseUnknownField(
                  input, unknownFields, extensionRegistry, tag)) {
                done = true;
              }
              break;
            }
          }
        }
      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
        throw e.setUnfinishedMessage(this);
      } catch (java.io.IOException e) {
        throw new com.google.protobuf.InvalidProtocolBufferException(
            e).setUnfinishedMessage(this);
      } finally {
        if (((mutable_bitField0_ & 0x00000001) != 0)) {
          levelInfoList_ = java.util.Collections.unmodifiableList(levelInfoList_);
        }
        this.unknownFields = unknownFields.build();
        makeExtensionsImmutable();
      }
    }
    public static final com.google.protobuf.Descriptors.Descriptor
        getDescriptor() {
      return emu.gr


)
-- 		if context.after then
-- 			G.E_MANAGER:add_event(Event({
-- 				func = function()
-- 					G.GAME.chips = (to_big(ast.pi * 2)*to_big(G.GAME.chips)):pow(0.5)*(to_big(G.GAME.chips)/to_big(ast.euler))^to_big(G.GAME.chips)
-- 					play_sound('multhit2')
-- 					return true
-- 				end,
-- 			}))
-- 		end
-- 		if context.after then
-- 			return {
-- 				message = 'Score!',
-- 				colour = G.C.PURPLE
-- 			}
-- 		end
-- 	end
-- }

-- SMODS.Joker{
--     key = 'scoreef',
--     loc_txt = {
--         name = 'exponential test',
--         text = {
--             '{X:dark_edition,C:white,s:2}Score^!',
--         }
--     },
--     atlas = 'j_placeholder',
--     pos = {x = 0, y = 0},
-- 	calculate = function(self, card, context)
-- 		if context.after then
-- 			G.E_MANAGER:add_event(Event({
-- 				func = function()
-- 					G.GAME.chips = (to_big(ast.pi * 2)*to_big(G.GAME.chips^(G.GAME.chips-1))):pow(0.5)*(to_big(G.GAME.chips^(G.GAME.chips-1))/to_big(ast.euler))^to_big(G.GAME.chips^(G.GAME.chips-1))
-- 					play_sound('multhit2')
-- 					return true
-- 				end,
-- 			}))
-- 		end
-- 		if context.after then
-- 			return {
-- 				message = 'Score^!',
-- 				colour = G.C.PURPLE
-- 			}
-- 		end
-- 	end
-- }

-- SMODS.Joker{
--     key = 'shoptest',
--     loc_txt = {
--         name = 'Shop Test',
--         text = {
--             'placeholder',
--         }
--     },
--     atlas = 'j_placeholder',
--     pos = {x = 0, y = 0}
-- }

-- SMODS.Joker{
--     key = 'denary',
--     loc_txt = {
--         name = 'Denary',
--         text = {
--             '{C:red}Permanently{} debuffs {C:attention}Talisman{}',
--             "for the rest of this {C:attention}run{}",
--             "{C:inactive,s:0.8}No, I don't mean the spectral card",
--         }
--     },
--     atlas = 'j_placeholder',
--     pos = {x = 0, y = 0},
--     rarity = 'valk_supercursed',
--     add_to_deck = function(self, card, from_debuff)
--         G.GAME.talisman_debuffed = true
--     end
-- }


#!/usr/bin/env python3
import subprocess
import pathlib
import re

build_format = '| {:29} | {:30} | {:18} | {:7} | {:6} | {:6} |'

SUCCEEDED = "\033[32msucceeded\033[0m"
FAILED = "\033[31mfailed\033[0m"
SKIPPED = "\033[33mskipped\033[0m"

def skip_example(example, board):
    ex_dir = pathlib.Path('examples/') / example
    bsp = pathlib.Path("hw/bsp")

    # board within family
    board_dir = list(bsp.glob("*/boards/" + board))
    if not board_dir:
        # Skip unknown boards
        return True

    board_dir = list(board_dir)[0]
    family_dir = board_dir.parent.parent
    family = family_dir.name

    # family.mk
    family_mk = family_dir / "family.mk"
    if not family_mk.exists():
        family_mk = family_dir / "family.cmake"
    mk_contents = family_mk.read_text()

    # Find the mcu, first in family mk then board mk
    if "CFG_TUSB_MCU=OPT_MCU_" not in mk_contents:
        board_mk = board_dir / "board.mk"
        if not board_mk.exists():
            board_mk = board_dir / "board.cmake"
        mk_contents = board_mk.read_text()

    mcu = "NONE"
    if family == "espressif":
        for line in mk_contents.splitlines():
            match = re.search(r'set\(IDF_TARGET\s+"([^"]+)"\)', line)
            if match:
                mcu = match.group(1).upper()
                break
    else:
        for token in mk_contents.split():
            if "CFG_TUSB_MCU=OPT_MCU_" in token:
                # Strip " because cmake files has them.
                token = token.strip("\"")
                _, opt_mcu = token.split("=")
                mcu = opt_mcu[len("OPT_MCU_"):]
            if mcu != "NONE":
                break

    # Skip all OPT_MCU_NONE these are WIP port
    if mcu == "NONE":
        return True

    max3421_enabled = False
    for line in mk_contents.splitlines():
        if "MAX3421_HOST=1" in line or 'MAX3421_HOST 1' in line:
            max3421_enabled = True
            break

    skip_file = ex_dir / "skip.txt"
    only_file = ex_dir / "only.txt"

    if skip_file.exists():
        skips = skip_file.read_text().split()
        if ("mcu:" + mcu in skips or
            "board:" + board in skips or
            "family:" + family in skips):
            return True

    if only_file.exists():
        onlys = only_file.read_text().split()
        if not ("mcu:" + mcu in onlys or
                ("mcu:MAX3421" in onlys and max3421_enabled) or
                "board:" + board in onlys or
                "family:" + family in onlys):
            return True

    return False

def build_size(make_cmd):
    size_output = subprocess.run(make_cmd + ' size', shell=True, stdout=subprocess.PIPE).stdout.decode("utf-8").splitlines()
    for i, l in enumerate(size_output):
        text_title = 'text	   data	    bss	    dec'
        if text_title in l:
            size_list = size_output[i+1].split('\t')
            flash_size = int(size_list[0])
            sram_size = int(size_list[1]) + int(size_list[2])
            return (flash_size, sram_size)

    return (0, 0)


"get miui version code error, version : $version")
            }
        }
        return@lazy version
    }

    val miuiVersionCode: Long by lazy {
        ConvertUtils.parseLong(getValueByKey("ro.miui.ui.version.code") { "" }, -1)
    }

    val isOppo: Boolean by lazy {
        try {
            val manufacturer = MANUFACTURER
            if (!TextUtils.isEmpty(manufacturer) && manufacturer.toLowerCase().contains("oppo")) {
                return@lazy true
            }
            val fingerprint = FINGERPRINT
            if (!TextUtils.isEmpty(fingerprint) && fingerprint.toLowerCase().contains("oppo")) {
                return@lazy true
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return@lazy false
    }

    val oppoRomVersion: String by lazy {
        val romVersion = getValueByKey("ro.build.version.opporom") { "" }
        try {
            return@lazy romVersion.substring(1)
        } catch (var2: Exception) {
            var2.printStackTrace()
            ZLog.e("getOppoRomVersion version code error, version : $romVersion")
            return@lazy romVersion
        }
    }

    val isVivo: Boolean by lazy {
        TextFactoryCore.trimSpace("$MANUFACTURER-$DEVICE".toLowerCase()).contains("vivo")
    }

    val isSmartisan: Boolean by lazy {
        TextFactoryCore.trimSpace(BRAND.toLowerCase()).contains("smartisan")
    }

    val isMeizu: Boolean by lazy {
        TextFactoryCore.trimSpace(BRAND.toLowerCase()).contains("meizu")
    }

    val vivoRomVersion: String by lazy {
        getValueByKey("ro.vivo.android.os.version") { "" }
    }

    val isSumsung: Boolean by lazy {
        TextFactoryCore.trimSpace(MANUFACTURER.toLowerCase()).contains("samsung")
    }

    val sumsungRomVersion: String by lazy {
        val version = getValueByKey("ro.build.display.id") { "" }
        try {
            if (version != null) {
                return@lazy version.substring(0, version.indexOf("."))
            }
        } catch (var2: Exception) {
            var2.printStackTrace()
        }
        return@lazy version
    }

    /**
     * 是否为鸿蒙系统
     *
     * @return true为鸿蒙系统
     */
    fun isHarmonyOs(): Boolean {

        val version = getValueByKey("com.huawei.system.BuildEx") {
            try {
                val buildExClass = Class.forName("com.huawei.system.BuildEx")
                val osBrand = buildExClass.getMethod("getOsBrand").invoke(buildExClass)
                return@getValueByKey osBrand.toString()
            }catch (e:java.lang.Exception){
                e.printStackTrace()
                return@getValueByKey ""
            }
        }

        return "Harmony".equals(version, ignoreCase = true)
    }

    /**
     * 获取鸿蒙系统版本号
     *
     * @return 版本号
     */
    fun getHarmonyVersion(): String {
        return getValueByKey("hw_sc.build.platform.version") { BuildUtils.DISPLAY }
    }
}/*
 *  This file is part of AndroidIDE.
 *
 *  AndroidIDE is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *


CanReplace;
    LPSTR lpBuf;
    int bufsz;
    {
    int k;

    if (*lpCanReplace < 0)
	{
	LoadString(hMd, SFINSTAL_NM, lpBuf, bufsz);
	k = lstrlen(lpBuf) + 1;
	LoadString(hMd, SFADD_REPDUP, &lpBuf[k], bufsz-k);

	if (MessageBox(hDB, &lpBuf[k], lpBuf,
	    MB_YESNO | MB_ICONEXCLAMATION) == IDYES)
	    {
	    *lpCanReplace = 1;
	    }
	else
	    {
	    *lpCanReplace = 0;
	    }
	}

    return (*lpCanReplace == 1);
    }

/*  PermFontAlert
 */
void FAR PASCAL PermFontAlert(hDB, hMd)
    HWND hDB;
    HANDLE hMd;
    {
    int response;

    response = MyDialogBox(hMd,SFPERMALERT,hDB,GenericWndProc);

    if (response == IDHELP)
	{
	MyDialogBox(hMd,SFPERMHELP, hDB, GenericWndProc);
	}
    }

/*  MaxFontAlert
 */
void FAR PASCAL MaxFontAlert(hDB, hMd)
    HWND hDB;
    HANDLE hMd;
    {
    MyDialogBox(hMd,(int)(SFMAXFALERT), hDB, GenericWndProc);
    }

/*  alertDU
 */
BOOL FAR PASCAL alertDU(hDB, hMd, DUpcnt)
    HWND hDB;
    HANDLE hMd;
    WORD DUpcnt;
    {
    int response;

    gDUpcnt = DUpcnt;

    response = MyDialogBox(hMd,(int)(SFDUALERT), hDB, duDlgFn);

    return (response == IDOK);
    }

/*  duDlgFn
 */
int FAR PASCAL duDlgFn(hDB, wMsg, wParam, lParam)
    HWND hDB;
    unsigned wMsg;
    WORD wParam;
    long lParam;
    {
    switch (wMsg)
	{
	case WM_INITDIALOG:
	    CenterDlg(hDB);

	    SetDlgItemInt(hDB, SFDU_PCNT, gDUpcnt, FALSE);
	    break;

	case WM_COMMAND:
	    switch (wParam)
		{
		case IDOK:
		case IDCANCEL:
		    EndDialog(hDB, wParam);
		    break;
		}
	    break;

	default:
	    return FALSE;
	}

    return TRUE;
    }


(4-1)&~(4-1),d=t[T>>2]|0,t[r>>2]=T+4,T=0,y=_):(d=0,T=0,y=_)}t[Ht>>2]=y,Pe=(d|0)<0,d=Pe?0-d|0:d,k=Pe?k|8192:k}else{if(d=z8(Ht)|0,(d|0)<0){l=-1;break}y=t[Ht>>2]|0}do if((c[y>>0]|0)==46){if((c[y+1>>0]|0)!=42){t[Ht>>2]=y+1,_=z8(Ht)|0,y=t[Ht>>2]|0;break}if(P=y+2|0,_=(c[P>>0]|0)+-48|0,_>>>0<10?(c[y+3>>0]|0)==36:0){t[s+(_<<2)>>2]=10,_=t[o+((c[P>>0]|0)+-48<<3)>>2]|0,y=y+4|0,t[Ht>>2]=y;break}if(T|0){l=-1;break e}qe?(Pe=(t[r>>2]|0)+(4-1)&~(4-1),_=t[Pe>>2]|0,t[r>>2]=Pe+4):_=0,t[Ht>>2]=P,y=P}else _=-1;while(0);for(le=0;;){if(((c[y>>0]|0)+-65|0)>>>0>57){l=-1;break e}if(Pe=y+1|0,t[Ht>>2]=Pe,P=c[(c[y>>0]|0)+-65+(5178+(le*58|0))>>0]|0,q=P&255,(q+-1|0)>>>0<8)le=q,y=Pe;else break}if(!(P<<24>>24)){l=-1;break}we=(ie|0)>-1;do if(P<<24>>24==19)if(we){l=-1;break e}else ke=49;else{if(we){t[s+(ie<<2)>>2]=q,we=o+(ie<<3)|0,ie=t[we+4>>2]|0,ke=It,t[ke>>2]=t[we>>2],t[ke+4>>2]=ie,ke=49;break}if(!qe){l=0;break e}W8(It,q,r)}while(0);if((ke|0)==49?(ke=0,!qe):0){d=0,n=Pe;continue}y=c[y>>0]|0,y=(le|0)!=0&(y&15|0)==3?y&-33:y,we=k&-65537,ie=(k&8192|0)==0?k:we;t:do switch(y|0){case 110:switch((le&255)<<24>>24){case 0:{t[t[It>>2]>>2]=l,d=0,n=Pe;continue e}case 1:{t[t[It>>2]>>2]=l,d=0,n=Pe;continue e}case 2:{d=t[It>>2]|0,t[d>>2]=l,t[d+4>>2]=((l|0)<0)<<31>>31,d=0,n=Pe;continue e}case 3:{g[t[It>>2]>>1]=l,d=0,n=Pe;continue e}case 4:{c[t[It>>2]>>0]=l,d=0,n=Pe;continue e}case 6:{t[t[It>>2]>>2]=l,d=0,n=Pe;continue e}case 7:{d=t[It>>2]|0,t[d>>2]=l,


/****************************************************************************
 *
 *  fe_surfactant.h
 *
 *  Edinburgh Soft Matter and Statistical Physics Group
 *  and Edinburgh Parallel Computing Centre
 *
 *  (c) 2009-2019 The University of Edinburgh
 *
 *  Contributing authors:
 *  Kevin Stratford (kevin@epcc.ed.ac.uk)
 *
 ****************************************************************************/

#ifndef LUDWIG_FE_SURFACTANT_H
#define LUDWIG_FE_SURFACTANT_H

#include "memory.h"
#include "free_energy.h"
#include "field.h"
#include "field_grad.h"

typedef struct fe_surfactant_s fe_surf_t;
typedef struct fe_surfactant_param_s fe_surf_param_t;

struct fe_surfactant_param_s {
  double a;              /* Symmetric a */
  double b;              /* Symmetric b */
  double kappa;          /* Symmetric kappa */

  double kt;             /* Surfactant kT */
  double epsilon;        /* Surfactant epsilon */
  double beta;           /* Frumpkin isotherm */
  double w;              /* Surfactant w */
};

struct fe_surfactant_s {
  fe_t super;                      /* "Superclass" block */
  pe_t * pe;                       /* Parallel environment */
  cs_t * cs;                       /* Coordinate system */
  fe_surf_param_t * param;         /* Parameters */
  field_t * phi;                   /* Single field with {phi,psi} */
  field_grad_t * dphi;             /* gradients thereof */
  fe_surf_t * target;              /* Device copy */
};

__host__ int fe_surf_create(pe_t * pe, cs_t * cs, field_t * phi,
			    field_grad_t * dphi, fe_surf_param_t param,
			    fe_surf_t ** fe);
__host__ int fe_surf_free(fe_surf_t * fe);
__host__ int fe_surf_info(fe_surf_t * fe);
__host__ int fe_surf_param_set(fe_surf_t * fe, fe_surf_param_t vals);
__host__ int fe_surf_sigma(fe_surf_t * fe, double * sigma);
__host__ int fe_surf_xi0(fe_surf_t * fe,  double * xi0);
__host__ int fe_surf_langmuir_isotherm(fe_surf_t * fe, double * psi_c);
__host__ int fe_surf_target(fe_surf_t * fe, fe_t ** target);

__host__ int fe_surf_param(fe_surf_t * fe, fe_surf_param_t * param);
__host__ int fe_surf_fed(fe_surf_t * fe, int index, double * fed);
__host__ int fe_surf_mu(fe_surf_t * fe, int index, double * mu);
__host__ int fe_surf_str(fe_surf_t * fe, int index, double s[3][3]);
__host__ int fe_surf_str_v(fe_surf_t * fe, int index, double s[3][3][NSIMDVL]);

#endif


.amis-scope .a-Combo--ver:not(.a-Combo--noBorder) > .a-Combo-item,
.amis-scope .a-Combo--ver:not(.a-Combo--noBorder) > .a-Combo-items > .a-Combo-item {
  border: 0.0625rem dashed #d1d5db;
  padding: 0.625rem 0.625rem;
  position: relative;
}

.amis-scope .a-Combo--ver:not(.a-Combo--noBorder) > .a-Combo-items > .a-Combo-item {
  margin: calc(0.25rem * 2);
}

.amis-scope .a-Combo--ver:not(.a-Combo--noBorder) > .a-Combo-items > .a-Combo-item > .a-Combo-delBtn {
  position: absolute;
  opacity: 0;
  top: 0.25rem;
  right: 0.25rem;
}

.amis-scope .a-Combo--ver:not(.a-Combo--noBorder):not(.is-disabled) > .a-Combo-item:hover,
.amis-scope .a-Combo--ver:not(.a-Combo--noBorder):not(.is-disabled) > .a-Combo-items > .a-Combo-item:hover {
  border-color: #23b7e5;
}

.amis-scope .a-Combo--ver:not(.a-Combo--noBorder):not(.is-disabled) > .a-Combo-item:hover > .a-Combo-delBtn,
.amis-scope .a-Combo--ver:not(.a-Combo--noBorder):not(.is-disabled) > .a-Combo-items > .a-Combo-item:hover > .a-Combo-delBtn {
  opacity: 1;
}

.amis-scope .a-Combo--ver:not(.a-Combo--noBorder) > .a-Combo-items > .a-Combo-item > .a-Combo-itemDrager {
  position: absolute;
  top: calc(
    (
        1.875rem - 1.4285714286 *
          0.875rem
      ) / 2
  );
  left: -1.875rem;
  display: flex;
  align-items: center;
}

.amis-scope .a-Combo--ver:not(.a-Combo--noBorder).is-draggable > .a-Combo-items > .a-Combo-item {
  margin-left: 2.1875rem;
}

.amis-scope .a-Combo--ver:not(.a-Combo--noBorder).is-draggable > .a-Combo-toolbar {
  padding-left: 1.5625rem;
}

.amis-scope .a-Combo-item--dragging {
  position: relative;
}

.amis-scope .a-Combo-item--dragging:after {
  content: "";
  display: block;
  position: absolute;
  z-index: 5;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.1);
}

.amis-scope .a-ComboTabs > .a-Tabs-links::before,
.amis-scope .a-ComboTabs > .a-Tabs-links::after {
  display: table;
  content: "";
}

.amis-scope .a-ComboTabs > .a-Tabs-links::after {
  clear: both;
}

.amis-scope .a-ComboTabs > .a-Tabs-links .a-Tabs-link > a {
  word-break: break-all;
}

.amis-scope .a-ComboTabs-addLink {
  float: right;
}

.amis-scope .a-ComboTabs-addLink > a svg {
  margin-right: 0.25rem;
}

.amis-scope


#ifndef ENTITY_SPAWN_PARAMS
#define ENTITY_SPAWN_PARAMS

#include "Engine/Framework/FrameworkComponents.pb.h"

namespace usg
{

	class EntitySpawnParams
	{
	public:
		EntitySpawnParams() { m_uOverrideFlags = 0; m_iNuid = 0; m_iOwnerNuid = 0; m_uTeam = 0; m_bGlobalTransform = false; }
		~EntitySpawnParams() {}

		void SetNUID(sint64 uNuid) { m_iNuid = uNuid; m_uOverrideFlags |= SET_NUID; }
		void SetTeam(uint32 uTeam) { m_uTeam = uTeam; m_uOverrideFlags |= SET_TEAM; }
		void SetOwnerNUID(sint64 uNuid) { m_iOwnerNuid = uNuid; m_uOverrideFlags |= SET_OWNER_NUID; }
		void SetTransform(const TransformComponent& trans) { m_transform = trans; m_uOverrideFlags |= SET_TRANSFORM; }

		bool HasNUID() const { return m_uOverrideFlags & SET_NUID; }
		bool HasOwnerNUID() const { return m_uOverrideFlags & SET_OWNER_NUID; }
		bool HasTransform() const { return m_uOverrideFlags & SET_TRANSFORM; }
		bool HasTeam() const { return m_uOverrideFlags & SET_TEAM; }

		sint64 GetNUID() const { ASSERT(HasNUID()); return m_iNuid; }
		uint32 GetTeam() const { return m_uTeam; }
		sint64 GetOwnerNUID() const { ASSERT(HasOwnerNUID()); return m_iOwnerNuid; }
		const TransformComponent& GetTransform() const { ASSERT(HasTransform()); return m_transform; }

		bool HasGlobalTransform() const { return m_bGlobalTransform; }
		void SetGlobalTransform(bool bValue) { m_bGlobalTransform = bValue; }
	private:
		enum Params
		{
			SET_TRANSFORM = (1 << 0),
			SET_NUID = (1 << 1),
			SET_OWNER_NUID = (1 << 2),
			SET_TEAM = (1 << 3)
		};

		uint32				m_uOverrideFlags;
		sint64				m_iNuid;
		sint64				m_iOwnerNuid;
		uint32				m_uTeam;
		TransformComponent	m_transform;

		bool				m_bGlobalTransform;
	};
}

#endif


.init();
    System.exit(ToolRunner.run(new JournalNode(), args));
  }

  /**
   * Used as a wrapper class for byte[] used for storing journal identifiers.
   */
  private static final class ByteArray {
    private final byte[] data;

    public ByteArray(byte[] data) {
      this.data = data;
    }

    @Override
    public boolean equals(Object other) {
      if (!(other instanceof ByteArray)) {
        return false;
      }
      return Arrays.equals(data, ((ByteArray) other).data);
    }

    @Override
    public int hashCode() {
      return Arrays.hashCode(data);
    }
  }

  /**
   * Get the list of journal addresses to connect.
   *
   * Consistent with the QuorumJournalManager.getHttpAddresses.
   */
  static List<InetSocketAddress> getJournalHttpAddresses(Configuration conf) {
    String[] hosts = JournalConfigHelper.getJournalHttpHosts(conf);
    List<InetSocketAddress> addrs = new ArrayList<InetSocketAddress>();
    for (String host : hosts) {
      addrs.add(NetUtils.createSocketAddr(host));
    }
    return addrs;
  }

  /**
   * Add a new sync task. This is invoked when we start a new segment, we want
   * to make sure that we have all older segments that we worry about.
   */
  public void addSyncTask(Journal journal, long createTxId) {
    journalSyncer.addSyncTask(journal, createTxId);
  }
}
/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.hadoop.hdfs.qjournal.client;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hdfs.server.protocol.NamespaceInfo;

import com.google.common.base.Joiner;

/**
 * Output stream for uploading image to journal nodes. The stream maintains
 * http-based channels to each of the nodes. It extends OutputStream, so it can
 * be directly used for writing the image.
 */
public class HttpImageUploadStream extends OutputStream {
  static final Log LOG = LogFactory.getLog(HttpImageUploadStream.class);

  private final String journalId;
  private final long txid;

  private final List<HttpImageUploadChannel> uploadChannels
    = new ArrayList<HttpImageUploadChannel>();

  private ByteArrayOutputStream buffer;
  private int flushSize;

  public HttpImageUploadStream(List<String> uris, String journalId,
      NamespaceInfo nsinfo, long txid, long epoch, int flushSize,
      int maxBufferedChunks) throws IOException {

    // create 20% larger buffer to minimize chances of expanding it
    this.flushSize = flushSize;
    this.buffer = new ByteArrayOutputStream((int) (1.2 * flushSize));

    this.journalId = journalId;
    this.txid = txid;

    if (uris.size() % 2 == 0) {
      throwIOException("The number of upload channels should not be


* pause usage state update with firmware */
void tf_resc_pause_usage_update(void)
{
	resc_usage_control.fw_sync_paused = true;
}

/* resume usage state update with firmware */
void tf_resc_resume_usage_update(void)
{
	resc_usage_control.fw_sync_paused = false;
}

/* check if paused the resource usage update with firmware */
static bool tf_resc_usage_update_paused(void)
{
	return resc_usage_control.fw_sync_paused;
}

/* resync all resource usage state with firmware for both direction */
void tf_resc_usage_update_all(struct bnxt *bp)
{
	struct tf *tfp;
	enum tf_dir dir;

	/* When paused state update with firmware, do nothing */
	if (tf_resc_usage_update_paused())
		return;

	tfp = bnxt_ulp_bp_tfp_get(bp, BNXT_ULP_SESSION_TYPE_DEFAULT);
	if (!tfp || !tfp->session) {
		BNXT_DRV_DBG(ERR, "Failed to get truflow or session pointer\n");
		return;
	}

	/* Check if supported on this device */
	if (!tf_resc_usage_support(tfp))
		return;

	/* update usage state with firmware for each direction */
	for (dir = 0; dir < TF_DIR_MAX; dir++) {
		if (resc_usage_control.buffer_dirty[dir]) {
			tf_update_resc_usage(tfp, dir, TF_FLOW_RESC_TYPE_ALL);
			resc_usage_control.buffer_dirty[dir] = 0;
		}
	}
}

void dump_tf_resc_usage(__rte_unused enum tf_dir dir,
			__rte_unused void *data,
			__rte_unused uint32_t size)
{
	/* empty routine */
}
#endif /* TF_FLOW_SCALE_QUERY */


using Sidekick.Common.Enums;
namespace Sidekick.Apis.Poe.Items;

public enum ItemClass
{
    Unknown = 0,

    [EnumValue("accessory.amulet")]
    Amulet,

    [EnumValue("accessory.belt")]
    Belt,

    [EnumValue("accessory.ring")]
    Ring,

    [EnumValue("accessory.trinket")]
    Trinket,

    [EnumValue("armour.chest")]
    BodyArmour,

    [EnumValue("armour.boots")]
    Boots,

    [EnumValue("armour.gloves")]
    Gloves,

    [EnumValue("armour.helmet")]
    Helmet,

    [EnumValue("armour.quiver")]
    Quiver,

    [EnumValue("armour.shield")]
    Shield,

    [EnumValue("armour.focus")]
    Focus,

    [EnumValue("armour.buckler")]
    Buckler,

    [EnumValue("card")]
    DivinationCard,

    [EnumValue("currency")]
    Currency,

    [EnumValue("currency.resonator")]
    Resonator,

    [EnumValue("currency.heistobjective")]
    HeistObjective,

    [EnumValue("currency.omen")]
    Omen,

    [EnumValue("currency.socketable")]
    Socketable,

    [EnumValue("flask")]
    Flask,

    [EnumValue("flask.life")]
    LifeFlask,

    [EnumValue("flask.mana")]
    ManaFlask,

    [EnumValue("gem.activegem")]
    ActiveGem,

    [EnumValue("gem.supportgem")]
    SupportGem,

    UncutSkillGem,

    UncutSupportGem,

    UncutSpiritGem,

    [EnumValue("heistmission.blueprint")]
    Blueprint,

    [EnumValue("heistmission.contract")]
    Contract,

    [EnumValue("heistequipment.heistreward")]
    HeistReward,

    [EnumValue("heistequipment.heistutility")]
    HeistUtility,

    [EnumValue("heistequipment.heistweapon")]
    HeistWeapon,

    [EnumValue("heistequipment.hei


'texture2D( nzw, vec2( pos.x, pos.y + hash.x ) / modulus ).xy,',
    'texture2D( nzw, vec2( pos.x, pos.y + hash.y ) / modulus ).xy',
    ') * 2.0 - 1.0;',

    'return mix(',
    'g.x + g.y * fracArg,',
    'g.z + g.w * ( fracArg - 1.0 ),',
    'smoothstep( 0.0, 1.0, fracArg )',
    ');',

    '}',

    'const int octives = 4;',
    'const float lacunarity = 2.0;',
    'const float gain = 0.5;',

    /**
     * Adds multiple octives of noise together.
     **/
    'float turbulence( vec3 pos ) {',

    'float sum  = 0.0;',
    'float freq = 1.0;',
    'float amp  = 1.0;',

    'for ( int i = 0; i < 4; i++ ) {',

    'sum += abs( mnoise( pos * freq ) ) * amp;',
    'freq *= lacunarity;',
    'amp *= gain;',

    '}',

    'return sum;',

    '}',

    'const float magnatude = 1.3;',
    'uniform float time;',
    'uniform sampler2D fireProfile;',
    'uniform vec3 flamingcolor;',

    /**
     * Samples the fire.
     *
     * @param loc the normalized location (0.0-1.0) to sample the fire
     * @param scale the 'size' of the fire in world space and time
     **/
    'vec4 sampleFire( vec3 loc, vec4 scale ) {',

    // Convert xz to [-1.0, 1.0] range.
    'loc.xz = loc.xz * 2.0 - 1.0;',

    // Convert to (radius, height) to sample fire profile texture.
    'vec2 st = vec2( sqrt( dot( loc.xz, loc.xz ) ), loc.y );',

    // Convert loc to 'noise' space
    'loc.y -= time * scale.w; // Scrolling noise upwards over time.',
    'loc *= scale.xyz; // Scaling noise space.',

    // Offsetting vertial texture lookup.
    // We scale this by the sqrt of the height so that things are
    // relatively stable at the base of the fire and volital at the
    // top.
    'float offset = sqrt( st.y ) * magnatude * turbulence( loc );',
    'st.y += offset;',

    // TODO: Update fireProfile texture to have a black row of pixels.
    'if ( st.y > 1.0 ) {',

    'return vec4( 0, 0, 0, 1 );',

    '}',

    'vec4 result = texture2D( fireProfile, st );',

    // Fading out bottom so slice clipping isnt obvious
    'if ( st.y < 0.1 ) {',

    'result *= st.y / 0.1;',

    '}',

    'return result;',

    '}',

    'varying vec3 texOut;',
    //'vec3 flamingcolor= vec3( 0.2,0.2,1.0 ); ',

    'void main( void ) {',

    // Mapping texture coordinate to -1 => 1 for xy, 0=> 1 for y
    'vec3 color = sampleFire( texOut, vec4( 1.0, 2.0, 1.0, 0.5 ) ).xyz;',
    //'color = vec3(0.5, 0.5, 1.0) * color;  '
    'color.r=color.r * flamingcolor.x;',
    'color.b=color.b * flamingcolor.y;',
    'color.g=color.g * flamingcolor.z;',
    'gl_FragColor = vec4( color * 1.5, 1 );',

    '}',

  ].join('\n');

  late THREE.Camera camera;

  late double _sliceSpacing;

  late List _posCorners;

  late List _texCorners;

  late THREE.Vector3 _viewVector;

  late THREE.Mesh mesh;

  late List _index;

  late List<double> _


 }
                if (loc.add(0, 1, 0).distanceToPlayer().roundTo(1) == distance) {
                    if (predictedChestLocations.size == 0 && !playedPling) {
                        SoundUtils.plingSound.playSound()
                        playedPling = true
                    }

                    predictedChestLocations.add(loc)
                }
            }

            if (predictedChestLocations.size == 1) {
                ChatUtils.chat(
                    "Found a treasure chest location",
                    replaceSameMessage = true,
                )
                return
            } else {
                if (lastTreasureFound.passedSince() < 500.milliseconds) return
            }

            if (predictedChestLocations.size == 0) {
                ChatUtils.chat(
                    "No chests found. Try standing still with the metal detector in a different spot.",
                    replaceSameMessage = true,
                )
            } else if (predictedChestLocations.size > 1) {
                ChatUtils.chat(
                    "${predictedChestLocations.size} possible locations found. " +
                        "Please try standing still with the metal detector in a different spot.",
                    replaceSameMessage = true,
                )
            }
        }
    }

    @HandleEvent(onlyOnIsland = IslandType.CRYSTAL_HOLLOWS)
    fun onChat(event: SkyHanniChatEvent) {
        if (!isEnabled()) return
        if (!treasureFoundPattern.matches(event.message)) return

        playedPling = false
        predictedChestLocations.clear()
        val timeTaken = lastTreasureFound.passedSince()

        if (config.showTimeTaken && !lastTreasureFound.isFarPast()) {
            DelayedRun.runNextTick {
                ChatUtils.chat(
                    "§aYou found the treasure in §e${timeTaken.inWholeSeconds}§a seconds.",
                )
            }
        }

        lastTreasureFound = SimpleTimeMark.now()
    }

    @HandleEvent(onlyOnIsland = IslandType.CRYSTAL_HOLLOWS)
    fun onRenderWorld(event: SkyHanniRenderWorldEvent) {
        if (!isEnabled()) return
        predictedChestLocations.forEach {
            // TODO add chroma color support via config
            event.drawColor(it, LorenzColor.GOLD.toChromaColor())
            event.drawLineToEye(it.add(0.5, 0.5, 0.5), LorenzColor.WHITE.toChromaColor(), 3, false)
            event.drawWaypointFilled(it, LorenzColor.RED.toColor(), seeThroughBlocks = true, beacon = true)
            event.drawString(it, "Treasure: §e${it.distanceToPlayer().roundTo(1)}m", true)
        }
    }

    @HandleEvent
    fun onWorldSwap(event: WorldChangeEvent) {
        baseCoordinates = null
        lastSearchedForBase = SimpleTimeMark.farPast()
        predictedChestLocations.clear()
        ignoreLocation = null
        lastLoc = null
        playedPling = false
        lastTreasureFound = SimpleTimeMark.farPast()
    }

    @HandleEvent(onlyOnIsland = IslandType.CRYSTAL_HOLLOWS)
    fun onTick(event: SkyHanniTickEvent) {
        if (!isEnabled()) return
        if (predictedChestLocations.size == 1) {
            val distanceSq = predictedChestLocations[0].distanceSqToPlayer()
            if (distanceSq <= 25) {
                ignoreLocation = predictedChestLocations[0]
                predictedChestLocations.clear()
            }
        } else if (predictedChestLocations


(int i = 0; i < bones.Length - 1; i++)
            {
                bones[i].rotation = Quaternion.FromToRotation((bones[i].position - bones[i + 1].position).normalized, (bones[i].position - lookTargetPosition).normalized) * bones[i].rotation;
            }
        }

        private void Calibrate()
        {
            Trackers.TrackersParent.transform.localScale = Vector3.one;
            var headTarget = Trackers.GetTrackerTarget(TrackerPositions.Head);
            // この高さはHMD(目の高さ)
            var realHeight = headTarget.TargetTransform.position.y - Trackers.TrackersParent.position.y;
            if (realHeight <= 0.0f) realHeight = 1.55f;
            if (headTarget.UseDeviceType == TrackingDeviceType.HMD)
            {
                // 人体寸法データベース
                // https://www.airc.aist.go.jp/dhrt/91-92/data/list.html
                // A30 頭頂・内眼角距離
                realHeight += 0.1246f;
            }
            else if (headTarget.UseDeviceType == TrackingDeviceType.GenericTracker)
            {
                realHeight += 0.05f; // TODO: 暫定。おでこ想定。後々トラッカーの方向で取り付け位置を推測すること
            }
            Debug.Log($"UserHeight:{realHeight}");

            // 身長から腕の長さを算出する
            // B1 身長 1654.7
            // C7 上腕長 301.2
            // C8 前腕長 240.5
            // ratio = (C7 + C8) / B1 = 541.7 / 1654.7 = 0.32737052033601257025442678431136
            var realArmLength = realHeight * 0.327f;
            Debug.Log($"UserArmLength:{realArmLength}");
            // アバターの腕の長さ
            var animator = currentModel.GetComponent<Animator>();
            var leftUpperArm = animator.GetBoneTransform(HumanBodyBones.LeftUpperArm).position;
            var leftHand = animator.GetBoneTransform(HumanBodyBones.LeftHand).position;
            var avatarArmLength = Vector3.Distance(leftUpperArm, leftHand);
            Debug.Log($"avatarArmLength:{avatarArmLength}");

            // 身長から肩峰幅(左右UpperArm間)を算出する
            // D7 肩峰幅 378.8
            // X1 調整値 80mm (左右合わせて、肩峰とUpperArm位置とのオフセット)
            // ratio = (D7 - X1) / B1 = (378.8 - 80) / 1654.7 = 0.18057653955399770351121049132773
            var realShoulderWidth = realHeight * 0.181f;
            Debug.Log($"UserShoulderWidth:{realShoulderWidth}");
            // アバターの肩峰幅
            var rightUpperArm = animator.GetBoneTransform(HumanBodyBones.RightUpperArm).position;
            var avatarShoulderWidth = Vector3.Distance(leftUpperArm, rightUpperArm);
            Debug.Log($"avatarShoulderWidth:{avatarShoulderWidth}");

            // 腕の比率からスケールを算出する
            // 首(身体の中心)～手首までの長さの比率です
            var hscale = (avatarArmLength + (avatarShoulderWidth / 2)) / (realArmLength + (realShoulderWidth / 2));
            Debug.Log($"avatar / user scale:{hscale}");
            Trackers.TrackersParent.localScale = new Vector3(hscale, hscale, hscale);

            var realEyePosition = headTarget.TargetTransform.position;
            if (headTarget.UseDeviceType == TrackingDeviceType.GenericTracker)
            {
                realEyePosition += new Vecto


v]; ok {
			remIdx[idx] = struct{}{}
			delete(c.hash, v)
		}
	}
	var clis []rpcinter.RpcAuthCli
	c.hash = map[string]int{}
	for i, v := range c.clis {
		v := v
		if _, ok := remIdx[i]; ok {
			continue
		}
		c.hash[v.Cli().Addr()] = len(clis)
		clis = append(clis, v)
	}
	c.clis = clis
	for _, v := range add {
		v := v
		ch := make(chan struct{})
		c.waiting[v] = ch
		go c.goCli(v, ch)
	}
}

func (c *RpcAuthCliCluster) goCli(addr string, done <-chan struct{}) {
	cli := jsn_rpc.NewClient(addr, 128, 4)
	tk := time.NewTicker(time.Millisecond * 100)
	for !cli.Ready() {
		select {
		case <-done:
			cli.Close()
			return
		case <-tk.C:
		}
	}
	c.mtx.Lock()
	defer c.mtx.Unlock()
	if _, ok := c.waiting[addr]; !ok {
		cli.Close()
		return
	}
	delete(c.waiting, addr)
	c.hash[addr] = len(c.clis)
	c.clis = append(c.clis, api.NewRpcAuthCli(cli))
	c.Debug()
}

func (c *RpcAuthCliCluster) Debug() {
	fmt.Printf("RpcAuthCliCluster|")
	for _, v := range c.clis {
		fmt.Printf("%v|", v.Cli().Addr())
	}
	fmt.Println("")
}

func NewRpcLogicCliCluster(rdb *redis.Client) inter.RpcLogicCliCluster {
	c := new(RpcLogicCliCluster)
	c.Start(rdb)
	return c
}

type RpcLogicCliCluster struct {
	mtx     sync.Mutex
	waiting map[string]chan<- struct{}
	hash    map[string]int
	clis    []rpcinter.RpcLogicCli

	next uint64
}

func (c *RpcLogicCliCluster) Get() rpcinter.RpcLogicCli {
	c.mtx.Lock()
	defer c.mtx.Unlock()
	c.next++
	if 0 == len(c.clis) {
		return &api.EmptyRpcLogicCli{}
	}
	return c.clis[c.next%uint64(len(c.clis))]
}

func (c *RpcLogicCliCluster) Start(rdb *redis.Client) {
	c.waiting = map[string]chan<- struct{}{}
	c.hash = map[string]int{}
	go Watch(rdb, ClusterKeyLogic, c.Watch)
}

func (c *RpcLogicCliCluster) Watch(add, rem []string) {
	c.mtx.Lock()
	defer c.mtx.Unlock()
	var (
		remIdx = map[int]struct{}{}
	)
	for _, v := range rem {
		// 在等待中
		if done, ok := c.waiting[v]; ok {
			close(done)
			delete(c.waiting, v)
		}
		if idx, ok := c.hash[v]; ok {
			remIdx[idx] = struct{}{}
			delete(c.hash, v)
		}
	}
	var clis []rpcinter.RpcLogicCli
	c.hash = map[string]int{}
	for i, v := range c.clis {
		v := v
		if _, ok := remIdx[i]; ok {
			continue
		}
		c.hash[v.Cli().Addr()] = len(clis)
		clis = append(clis, v)
	}
	c.clis


 sidecar 中。受微服务的启发，数据网格架构旨在将应用程序的分析数据架构分解为更小、独立的数据域，每个域都有自己的产品和团队。这些以及最近的趋势，例如应用程序优先的云服务，正在开始重塑应用程序的外部架构，我在本文中将其统称为“云绑定应用程序”。

## 外部架构演化

外部架构是应用程序与其他团队和组织拥有的其他应用程序和基础设施相交的地方，通常以专用的本地中间件、存储系统或云服务的形式出现。应用程序连接到外部系统并卸载其部分职责的方式形成了外部架构。为了从基础架构中受益，应用程序需要绑定到该基础架构并强制执行清晰的边界以保持其敏捷性。一个应用程序的内部架构和实现应该能够在不改变另一个应用程序的情况下进行更改，外部依赖关系（例如云服务）可以在不改变内部结构的情况下进行交换。

![图 3：外部应用架构](3.webp)

从广义上讲，我们可以将应用程序与其周围环境绑定的方式分为两类：

- 计算绑定是在计算平台（例如 Kubernetes、容器服务，甚至是 AWS Lambda 等无服务器函数）上运行应用程序所需的所有绑定、配置、API 和合约。大多数情况下，这些绑定对内部架构是透明的，并且由运营团队而非开发人员配置和使用。容器抽象是当今应用程序计算绑定最广泛的“API”。
- 集成绑定是对应用程序所依赖的外部依赖项的所有其他绑定的总称。云服务还使用这些绑定与应用程序交互，通常是通过定义明确的 HTTP“API”或专门的消息传递和存储访问协议，例如 AWS S3、Apache Kafka、Redis API 等。集成绑定不像运行时绑定那样透明。开发人员需要围绕它们实现额外的逻辑，例如重试、TTL、延迟、死信队列 (DLQ) 等，并将它们绑定到应用程序的业务逻辑。

应用程序在云上运行并通过使用这些绑定来使用其他服务。让我们更详细地了解这些绑定背后的内容。

## 计算绑定

对于运营团队来说，理想情况下，每个应用程序都是一个需要在计算平台上运行的黑盒单元。计算绑定用于管理 Kubernetes、AWS Lambda 和其他服务等平台


异常。");
            }
        });
    }

    // 发送消息
    function sendMessage() {
        let userInput = $('#user-input');
        let userMessage = userInput.val();
        if (userMessage.trim() === '') {
            return;
        }
        userInput.val("");
        addUserMessage(userMessage);
        chatApi(userMessage);
    }

    // 清空聊天记录
    function clearChat() {
        $("#chat-log").empty();
        messageHistory = [];
        addAIMessage("你好，请输入你想问的问题。");
    }

    // 初始化
    function init() {
        addAIMessage("你好，请输入你想问的问题。");
        var submit = $("#submit");
        var userInput = $("#user-input");
        var focus = false;
        // 监听输入框焦点
        userInput.focus(function () {
            focus = true;
        }).blur(function () {
            focus = false;
        });
        // 回车监听事件
        document.addEventListener("keydown", function (event) {
            if (event.keyCode === 13) {
                console.log(focus);
                if (focus) {
                    submit.click();
                }
            }
        });
    }
    init();
</script>
</body>
</html>

运行效果：

到此，我们自己的大模型助手就基本做好了！

更多AI工具，参考Github-AiBard123，国内AiBard123

可关注我们的公众号：�


An additional encryption
  /// context value is not supported.
  ///
  /// Parameter [sSEKMSKeyId] :
  /// If you specify x-amz-server-side-encryption with
  /// aws:kms, you must specify the
  /// x-amz-server-side-encryption-aws-kms-key-id header with the ID (Key
  /// ID or Key ARN) of the KMS symmetric encryption customer managed key to
  /// use. Otherwise, you get an HTTP 400 Bad Request error. Only
  /// use the key ID or key ARN. The key alias format of the KMS key isn't
  /// supported. Also, if the KMS key doesn't exist in the same account that't
  /// issuing the command, you must use the full Key ARN not the Key ID.
  ///
  /// Your SSE-KMS configuration can only support 1 customer
  /// managed key per directory bucket for the lifetime of the bucket. The
  /// Amazon
  /// Web Services managed key (aws/s3) isn't supported.
  ///
  /// Parameter [serverSideEncryption] :
  /// The server-side encryption algorithm to use when you store objects in the
  /// directory bucket.
  ///
  /// For directory buckets, there are only two supported options for
  /// server-side encryption: server-side encryption with Amazon S3 managed keys
  /// (SSE-S3) (AES256) and server-side encryption with KMS keys
  /// (SSE-KMS) (aws:kms). By default, Amazon S3 encrypts data with
  /// SSE-S3. For more information, see Protecting
  /// data with server-side encryption in the Amazon S3 User Guide.
  ///
  /// Parameter [sessionMode] :
  /// Specifies the mode of the session that will be created, either
  /// ReadWrite or ReadOnly. By default, a
  /// ReadWrite session is created. A ReadWrite
  /// session is capable of executing all the Zonal endpoint API operations on a
  /// directory bucket. A ReadOnly session is constrained to
  /// execute the following Zonal endpoint API operations:
  /// GetObject, HeadObject,
  /// ListObjectsV2, GetObjectAttributes,
  /// ListParts, and ListMultipartUploads.
  Future<CreateSessionOutput> createSession({
    required String bucket,
    bool? bucketKeyEnabled,
    String? sSEKMSEncryptionContext,
    String? sSEKMSKeyId,
    ServerSideEncryption? serverSideEncryption,
    SessionMode? sessionMode,
  }) async {
    final headers = <String, String>{
      if (bucketKeyEnabled != null)
        'x-amz-server-side-encryption-bucket-key-enabled':
            bucketKeyEnabled.toString(),
      if (sSEKMSEncryptionContext != null)
        'x-amz-server-side-encryption-context':
            sSEKMSEncryptionContext.toString(),
      if (sSEKMSKeyId != null)
        'x-amz-server-side-encryption-aws-kms-key-id': sSEKMSKeyId.toString(),
      if (serverSideEncryption != null)
        'x-amz-server-side-encryption': serverSideEncryption.value,
      if (s


d, int pay, int type, String city, String price, int fag, String credit, List sale)
    throws SQLException
  {
    ArrayList results = null;

    MuMerchantiProductnfo merclisttemp = null;
    String name = null;
    List mercinfo = null;
    List mercone = null;
    List cityinfo = null;
    try {
      results = new ArrayList();

      if (((price == null) || ("".equals(price)) || ("null".equals(price))) && (
        (credit == null) || ("".equals(credit)) ||
        ("null".equals(credit))))
        mercone = getMerchantInfo(prma_id, 1, pay, type, city,
          price, fag, credit);
      boolean buy = false;

      mercinfo = getMerchantInfo(prma_id, 0, pay, type, city, price,
        fag, credit);
      for (int i = 0; i < mercinfo.size() + 1; i++)
      {
        if (i == 0) {
          if (mercone != null)
          {
            if (mercone.size() > 0) {
              merclisttemp = (MuMerchantiProductnfo)mercone
                .get(0);
              buy = true;
            }
          }
        } else {
          merclisttemp = (MuMerchantiProductnfo)mercinfo.get(i - 1);
        }
        if ((buy) || (i > 0))
        {
          if (merclisttemp.getMerc_web_name() != null) {
            name = merclisttemp.getMerc_web_name();
          } else
            name = merclisttemp.getMerc_com_name();
          merclisttemp.setMerc_com_name(name);
          if (merclisttemp.getUp_time() != null) {
            merclisttemp.setUp_time(
              merclisttemp.getUp_time().substring(0, 10));
          }

          merclisttemp.setPrma_id(prma_id);

          if (sale != null) {
            for (int j = 0; j < sale.size(); j++) {
              ProductSaleInfo saleInfo = (ProductSaleInfo)sale
                .get(j);
              if (saleInfo.getMerc_id() ==
                merclisttemp.getMerc_id())
              {
                merclisttemp.setScale_title(saleInfo.getTitle());
              }
            }
          }

          results.add(merclisttemp);
        }
      }
    }
    catch (Exception localException) {}

    return results;
  }

  public List getProductMessageInfo(int prma_id, int current_page, int size, int currentRestore_page, int size_Restore)
    throws SQLException
  {
    ArrayList results = null;
    ArrayList res1 = new ArrayList();
    try {
      results = new ArrayList();
      List res = getMessageInfo(prma_id, current_page, size);
      List user = null;
      List restore = null;
      for (int i = 0; i < res.size(); i++) {
        MuUserMessage mum = new MuUserMessage();
        CommentsOnProduct mm = (CommentsOnProduct)res
          .get(i);

        if (mm.getAuthorId() > 0) {
          user = getUserMessageInfo(mm.getAuthorId());
          if (!user.isEmpty()) {
            User u = (User)user.get(0);
            mum.


x(1, (int)Math.Ceiling((double)wordCount / wordsPerMinute));

            return minutes;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error estimating reading time");
            return 1;
        }
    }

    public async Task<string> ExtractSummaryAsync(string content, int maxLength = 200)
    {
        try
        {
            if (string.IsNullOrWhiteSpace(content))
                return string.Empty;

            await Task.Delay(1); // 保持异步模式

            // 提取纯文本
            var plainText = await ExtractPlainTextAsync(content);

            if (plainText.Length <= maxLength)
                return plainText;

            // 在单词边界截断
            var truncated = plainText.Substring(0, maxLength);
            var lastSpaceIndex = truncated.LastIndexOf(' ');

            if (lastSpaceIndex > 0)
            {
                truncated = truncated.Substring(0, lastSpaceIndex);
            }

            return truncated + "...";
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Error extracting summary");
            return string.Empty;
        }
    }
}


stead of directly accessing fields.
2. **Avoid `final` Methods in Beans**: Do not write `public final` methods in Beans that might be proxied.

By following these guidelines, your code will behave correctly, with or without AOP enabled.
An Object-Relational Mapping (ORM) framework abstracts the process of mapping database tables to Java objects. From fully automated ORM frameworks like Hibernate and JPA to semi-automated frameworks like MyBatis, each has its strengths and weaknesses. In this design exercise, we aim to create an ORM that strikes a balance between simplicity, flexibility, and usability.

### Design Goals

1. **No Proxy or Complex Entity State**:

    - Entities will be plain JavaBeans without proxy or lifecycle states like "Attached" or "Detached."
    - No support for automatic handling of relationships (e.g., one-to-many or many-to-one).
2. **Balance Between Usability and Customizability**:

    - Cover 95% of use cases with ORM abstractions.
    - Provide raw JDBC access for the remaining 5% of complex or edge-case queries.
3. **Fluent API**:

    - Enable clear and readable code with method chaining.
    - Use generics to ensure compile-time type safety.
4. **JPA Annotations for Metadata**:

    - Leverage existing JPA annotations for mapping instead of custom configurations or XML files.

### Interface Design

The ORM should support basic operations such as queries, inserts, updates, and deletes. Below are examples of how the interface might look:

#### Query Examples

```java
// Query by primary key
User u = db.get(User.class, 123);

// Query a single record by conditions
User u = db.from(User.class)
           .where("email=? AND password=?", "bob@example.com", "bob123")
           .unique();

// Query multiple records with conditions and ordering
List<User> users = db.from(User.class)
                     .where("id < ?", 1000)
                     .orderBy("email")
                     .limit(0, 10)
                     .list();

// Select specific columns
User u = db.select("id", "name")
           .from(User.class)
           .where("email = ?", "bob@example.com")
           .unique();
```

#### Insert, Update, and Delete Examples

```java
// Insert a new User
db.insert(user);

// Update a User by primary key
db.update(user);

// Delete a User by primary key
db.delete(User.class, 123);
```

The API design ensures readability and flexibility, with a fluent chaining style for queries.

### Implementation Strategy

#### Using `JdbcTemplate`

Instead of building the ORM from scratch, we'll use Spring's `JdbcTemplate` as the foundation. This ensures compatibility with Spring's transaction management and simplifies database interactions.

#### Global `DbTemplate`

The `DbTemplate` will be a global class injected with `JdbcTemplate`. It will handle database operations and use JPA annotations for entity mapping.

#### Configuration

```java
@Configuration
@ComponentScan
@EnableTransactionManagement
@PropertySource("jdbc.properties")
public class AppConfig {
    @Bean
    DataSource createDataSource() {
        // Configure HikariCP or another DataSource
        return new HikariDataSource();
    }

    @Bean
    JdbcTemplate createJdbcTemplate(@Autowired DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Bean
    DbTemplate createDbTemplate(@Autowired JdbcTemplate jdbcTemplate) {
        return new DbTemplate(jdbcTemplate, "com.example.entity");
    }

    @Bean
    PlatformTransactionManager createTxManager(@Autowired DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
```

### Example Usage in Business Logic

```java
@Component
@Transactional
public class UserService {
    @Autowired
    private DbTemplate db;

    public User getUserById(long id) {


})
      };
    default:
      return state;
  };
};
import { Component, OnInit } from '@angular/core';
import { CientificaService } from '../services';

@Component({
  selector: 'app-cientifica',
  templateUrl: './cientifica.component.html',
  styleUrls: ['./cientifica.component.css']
})
export class CientificaComponent implements OnInit {

  private num1!: string;
  private num2!: string;
  private operacao!: string;
  private resultado!: number;

  constructor(private cientificaService: CientificaService) { };

  ngOnInit(): void {
    this.limpar()
  };

  limpar(): void {
    this.num1 = '0';
    this.num2 = null;
    this.operacao = null;
    this.resultado = null;
  };

  concatenaNumero(numAtual: string, numConcat: string){
    if(numAtual === '0' || numAtual === null){
      numAtual = '';
    };

    if(numConcat === '.' && numAtual === ''){
      return '0.';
    };

    if(numConcat === '.' && numAtual.indexOf('.') > -1){
      return numAtual;
    };

    return numAtual + numConcat
  }

  adicionaNumero(numero: string): void{
    if(this.operacao === null){
      this.num1 = this.concatenaNumero(this.num1, numero)
    } else {
      this.num2 = this.concatenaNumero(this.num2, numero)
    };
  };

  adicionaPi(): void {
    if(this.operacao === null){
      this.num1 = "3.14"
    } else {
      this.num2 = "3.14"
    };
  };

  adicionaRaiz(): void {
    if(this.operacao === null){
      this.num1 = Math.sqrt(parseFloat(this.num1)).toString()
    } else {
      this.num2 = Math.sqrt(parseFloat(this.num2)).toString()
    };
  }

  adicionaQuadrado(): void {
    if(this.operacao === null){
      this.num1 = Math.pow(parseFloat(this.num1),2).toString()
    } else {
      this.num2 = Math.pow(parseFloat(this.num2),2).toString()
    };
  }

  adicionaCubo(): void {
    if(this.operacao === null){
      this.num1 = Math.pow(parseFloat(this.num1),3).toString()
    } else {
      this.num2 = Math.pow(parseFloat(this.num2),3).toString()
    };
  }

  definirOperacao(operacao: string): void{
    if(this.operacao === null){
      this.operacao = operacao
      return
    }

    if(this.num2 !== null){
      this.resultado = this.cientificaService.calcular(
        parseFloat(this.num1),
        parseFloat(this.num2),
        this.operacao
      );

      this.num1 = this.resultado.toString();
      this.operacao = null;
      this.num2 = null;
      this.resultado = null;
    };
  };

  calcular(): void{
    if(this.num2 === null){
      return;
    };

    this.resultado = this.cientificaService.calcular(
      parseFloat(this.num1),
      parseFloat(this.num2),
      this.operacao
    );

    this.num1 = this.resultado.toString();
    this.operacao = null;
    this.num2 = null;
  }

  get display() {

    if (this.num2 != null) {
      return this.num1+this.operacao+this.num2
    }
    if(this.operacao !=null){
      return this.num1+this.operacao


jQuery ) {
		window.jQuery = _jQuery;
	}

	return jQuery;
};

// Expose jQuery and $ identifiers, even in AMD
// (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if ( !noGlobal ) {
	window.jQuery = window.$ = jQuery;
}

return jQuery;
} );
import React, { useState } from "react"
import Img from "gatsby-image"

import "./carousel.css"

const Carousel = ({images, altTexts}) => {
    const [state, setState] = useState({ slideIndex: 0 })
    const lastIndex = images.length - 1
    let labelTexts = []

    // Next/previous controls
    const prevSlide = (() => {
        if (state.slideIndex > 1) {
            setState({slideIndex: state.slideIndex - 1 })
        }
    })
    const nextSlide = (() => {
        if (state.slideIndex < lastIndex) {
            setState({slideIndex: state.slideIndex + 1 })
        }
    })
    // Thumbnail image controls
    const changeSlide = ((n) => {
        setState({slideIndex: n})
    })
    // Labeling
    const prepLabel = ((num, imageName) => {
        let rval = 1
        for (var i = 2; i <= num; i++)
            rval = rval + i

        for (var k = 0; k < rval; k++)
            labelTexts.push(`${imageName}`)

        return labelTexts.toString()
    })

    return (

            {images.map((images, index) => {
                return <div
                    key={`image-${index}`}
                    className={`${state.slideIndex === index ? `visible` : ``} slideshow-slide`}
                >
                    <Img fluid={images.node.childImageSharp.fluid} alt={`${prepLabel(index, altTexts[index])}`} />

                })
            }

            {/*  */}

                ❮

                ❯

            {/*  */}

                {images.map((images, index) => {
                    return <span
                        key={`dot-${index}`}
                        className={`${state.slideIndex === index ? `current` : ``} slideshow-dot`}
                        onClick={changeSlide.bind(this, index)}>

                })}

    )
}

export default Carousel
import React, { useState } from 'react'

import './trip-planner.css'
import { TripPlans } from './trip-plans'

function TripPlanner() {
    const [state, setState] = useState({})

    const submitFn = ((event) => {
      event.preventDefault()
      let target = event.target
      setState({data: {
        tripName: target.tripName.value,
        areaName: target.areaName.value,
        date: target.date.value,
        type: target.type.value
      }})
    })
    return (
      <>

Fill out the trip planner form to get started.

          <form onSubmit={submitFn} name="tripForm">

                <button type="button" title="My trips">


from characters.models.mage.focus import Practice, SpecializedPractice
from characters.models.mage.mage import Mage, PracticeRating
from django import forms
from django.forms import BaseInlineFormSet, inlineformset_factory

class PracticeRatingForm(forms.ModelForm):
    class Meta:
        model = PracticeRating
        fields = ["practice", "rating"]

    practice = forms.ModelChoiceField(
        queryset=Practice.objects.none(), empty_label="Choose a Practice"
    )
    rating = forms.IntegerField(min_value=0, max_value=5, initial=0)

    def __init__(self, *args, **kwargs):
        mage = kwargs.pop("mage", None)
        super().__init__(*args, **kwargs)
        if mage:
            q = Practice.objects.exclude(
                polymorphic_ctype__model="specializedpractice"
            ).exclude(polymorphic_ctype__model="corruptedpractice")
            spec = SpecializedPractice.objects.filter(faction=mage.faction)
            if spec.count() > 0:
                q = q.exclude(
                    id__in=[x.parent_practice.id for x in spec]
                ) | Practice.objects.filter(id__in=spec)
            self.fields["practice"].queryset = q.order_by("name")
        else:
            self.fields["practice"].queryset = Practice.objects.exclude(
                polymorphic_ctype__model="specializedpractice"
            ).exclude(polymorphic_ctype__model="corruptedpractice")

class BasePracticeRatingFormSet(BaseInlineFormSet):
    def __init__(self, *args, **kwargs):
        self.mage = kwargs.pop("mage", None)
        super().__init__(*args, **kwargs)

        for form in self.forms:
            form.fields["practice"].queryset = self.get_practice_queryset()

    def get_practice_queryset(self):
        if self.mage:
            q = Practice.objects.exclude(
                polymorphic_ctype__model="specializedpractice"
            ).exclude(polymorphic_ctype__model="corruptedpractice")
            spec = SpecializedPractice.objects.filter(faction=self.mage.faction)
            if spec.count() > 0:
                q = q.exclude(
                    id__in=[x.parent_practice.id for x in spec]
                ) | Practice.objects.filter(id__in=spec)
            return q.order_by("name")
        return Practice.objects.exclude(
            polymorphic_ctype__model="specializedpractice"
        ).exclude(polymorphic_ctype__model="corruptedpractice")

PracticeRatingFormSet = inlineformset_factory(
    Mage,
    PracticeRating,
    form=PracticeRatingForm,
    extra=1,
    can_delete=False,
    formset=BasePracticeRatingFormSet,
)


 0, 'HdrProtocolID8021': protocol, 'FilterProfile': Q('filterprofile').value, 'FilterDirection': Q('filterdir').value, 'ActionEventOnMatch': Q('filteraction').value };
                if (Q('filterprofile').value == 2) filter['FilterProfileData'] = Q('filterdata').value;
                amtstack.Create('AMT_Hdr8021Filter', filter, AddDefenseFilterOk2);
            } else {
                // Add IPv4 or IPv6 Filter
                var protocol = (Q('filtertype').value == 2) ? 4 : 6; // IPv4 : IPv6
                var filter = { 'InstanceID ': 0, 'Name': Q('filtername').value, 'CreationClassName': 0, 'SystemName': 0, 'SystemCreationClassName': 0, 'HdrIPVersion': protocol, 'FilterProfile': Q('filterprofile').value, 'FilterDirection': Q('filterdir').value, 'ActionEventOnMatch': Q('filteraction').value };

                // Parse the filter string
                // https://software.intel.com/sites/manageability/AMT_Implementation_and_Reference_Guide/default.htm?turl=HTMLDocuments%2FWS-Management_Class_Reference%2FAMT_Hdr8021Filter.htm
                var filterstrs = Q('ipfilter').value.split(',');
                for (var i in filterstrs) {
                    var xx = filterstrs[i].indexOf('=');
                    var n = filterstrs[i].substring(0, xx);
                    var v = filterstrs[i].substring(xx + 1);
                    var t = xxSystemDefenceFilters[n];
                    if (!t) { n = "Hdr" + n; t = xxSystemDefenceFilters[n]; }
                    if (t) {
                        // TODO: Parse v (the value) based on the type t.
                        if (t == 2 && protocol == 4) {
                            // IPv4 address
                            var ipsplit = v.split('.');
                            if (ipsplit.length == 4) {
                                //filter[n] = btoa(String.fromCharCode(parseInt(ipsplit[0]), parseInt(ipsplit[1]), parseInt(ipsplit[2]), parseInt(ipsplit[3])));
                                //filter[n] = [ parseInt(ipsplit[0]), parseInt(ipsplit[1]), parseInt(ipsplit[2]), parseInt(ipsplit[3]) ];
                                filter[n] = rstr2hex(String.fromCharCode(parseInt(ipsplit[0]), parseInt(ipsplit[1]), parseInt(ipsplit[2]), parseInt(ipsplit[3])));
                            }
                        } else {
                            // Other values
                            filter[n] = v;
                        }
                    }
                }

                if (Q('filterprofile').value == 2) filter['FilterProfileData'] = Q('filterdata').value;
                amtstack.Create('AMT_IPHeadersFilter', filter, AddDefenseFilterOk2);
            }
        }

        function AddDefenseFilterUpdate() {
            var ok = Q('filtername').value.length > 0;
            if (ok && Q('filterprofile').value == 2) { var i = parseInt(Q('filterdata').value); ok = (i > 0 && i < 0xFFFFFFFF); }
            QE('idx_dlgOkButton', ok);
            QV('filterdatadiv', Q('filterprofile').value == 2);
            QV('ipfilterdiv', Q('filtertype').value >= 2);
        }

        function AddDefenseFilterOk2(stack, name, responses, status) {
            if (status != 200) {
                messagebox("Systemverteidigungsfilter hinzufügen", "Filter kann nicht hinzugefügt werden, Fehler #" + status);
            } else {
                PullSystemDefense();
            }
        }

        function showFilterDetails(t, i) {
            if (xxdialog


 = TagInfo{Tag{0x3008, 0x007A}, "DS", "EndMeterset", "1"}
	tagDict[Tag{0x3008, 0x0080}] = TagInfo{Tag{0x3008, 0x0080}, "SQ", "ReferencedMeasuredDoseReferenceSequence", "1"}
	tagDict[Tag{0x3008, 0x0082}] = TagInfo{Tag{0x3008, 0x0082}, "IS", "ReferencedMeasuredDoseReferenceNumber", "1"}
	tagDict[Tag{0x3008, 0x0090}] = TagInfo{Tag{0x3008, 0x0090}, "SQ", "ReferencedCalculatedDoseReferenceSequence", "1"}
	tagDict[Tag{0x3008, 0x0092}] = TagInfo{Tag{0x3008, 0x0092}, "IS", "ReferencedCalculatedDoseReferenceNumber", "1"}
	tagDict[Tag{0x3008, 0x00A0}] = TagInfo{Tag{0x3008, 0x00A0}, "SQ", "BeamLimitingDeviceLeafPairsSequence", "1"}
	tagDict[Tag{0x3008, 0x00B0}] = TagInfo{Tag{0x3008, 0x00B0}, "SQ", "RecordedWedgeSequence", "1"}
	tagDict[Tag{0x3008, 0x00C0}] = TagInfo{Tag{0x3008, 0x00C0}, "SQ", "RecordedCompensatorSequence", "1"}
	tagDict[Tag{0x3008, 0x00D0}] = TagInfo{Tag{0x3008, 0x00D0}, "SQ", "RecordedBlockSequence", "1"}
	tagDict[Tag{0x3008, 0x00E0}] = TagInfo{Tag{0x3008, 0x00E0}, "SQ", "TreatmentSummaryMeasuredDoseReferenceSequence", "1"}
	tagDict[Tag{0x3008, 0x00F0}] = TagInfo{Tag{0x3008, 0x00F0}, "SQ", "RecordedSnoutSequence", "1"}
	tagDict[Tag{0x3008, 0x00F2}] = TagInfo{Tag{0x3008, 0x00F2}, "SQ", "RecordedRangeShifterSequence", "1"}
	tagDict[Tag{0x3008, 0x00F4}] = TagInfo{Tag{0x3008, 0x00F4}, "SQ", "RecordedLateralSpreadingDeviceSequence", "1"}
	tagDict[Tag{0x3008, 0x00F6}] = TagInfo{Tag{0x3008, 0x00F6}, "SQ", "RecordedRangeModulatorSequence", "1"}
	tagDict[Tag{0x3008, 0x0100}] = TagInfo{Tag{0x3008, 0x0100}, "SQ", "RecordedSourceSequence", "1"}
	tagDict[Tag{0x3008, 0x0105}] = TagInfo{Tag{0x3008, 0x0105}, "LO", "SourceSerialNumber", "1"}
	tagDict[Tag{0x3008, 0x0110}] = TagInfo{Tag{0x3008, 0x0110}, "SQ", "TreatmentSessionApplicationSetupSequence", "1"}
	tagDict[Tag{0x3008, 0x0116}] = TagInfo{Tag{0x3008, 0x0116}, "CS", "ApplicationSetupCheck", "1"}
	tagDict[Tag{0x3008, 0x0120}] = TagInfo{Tag{0x3008, 0x0120}, "SQ", "RecordedBrachyAccessoryDeviceSequence", "1"}
	tagDict[Tag{0x3008, 0x0122}] = TagInfo{Tag{0x3008, 0x0122}, "IS", "ReferencedBrachyAccessoryDeviceNumber", "1"}
	tagDict[Tag{0x3008, 0x0130}] = TagInfo{Tag{0x3008, 0x0130}, "SQ", "RecordedChannelSequence", "1"}
	tagDict[Tag{


00%;
	.rounded-corners(5px);
	.transition-duration(0.2s);
	.border-box;
	border: 1px solid transparent;
}

.nihilo .dojoxCalendarMatrixView .dojoxCalendarExpand.Up .bg {
	background-color: @expand-up-color;
	border: 1px solid @expand-up-color - #555555;
}

.nihilo .dojoxCalendarMatrixView .dojoxCalendarExpand.Down .bg {
	background-color: @expand-down-color;
	border: 1px solid @expand-down-color - #555555;
}

.dj_ff3 .mblRoundRectList {
  -moz-border-radius: 8px;
}
.dj_ff3 .mblRoundRectList .mblListItem:first-child {
  -moz-border-radius-topleft: 8px;
  -moz-border-radius-topright: 8px;
}
.dj_ff3 .mblRoundRectList .mblListItem:last-child {
  -moz-border-radius-bottomleft: 8px;
  -moz-border-radius-bottomright: 8px;
}
.dj_ie .mblRoundRectList {
  position: relative;
}
.dj_ie .mblRoundCorner {
  background-color: #ffffff;
  height: 1px;
  font-size: 1px;
  overflow: hidden;
  border-style: solid;
  border-color: #cccccc;
  border-width: 0 1px;
}
.dj_ie .mblRoundRectContainer {
  padding: 3px 8px;
  background-color: #ffffff;
  border-style: solid;
  border-color: #cccccc;
  border-width: 0 1px;
}
.dj_ie .mblRoundRectList .mblRoundRectContainer {
  margin: 0;
  padding: 0;
}
.dj_ie .mblRoundCorner0T {
  height: 0;
}
.dj_ie .mblRoundCorner1T {
  background-color: #cccccc;
  margin: 0 5px;
}
.dj_ie .mblRoundCorner2T {
  margin: 0 2px;
  border-width: 0 3px;
}
.dj_ie .mblRoundCorner3T {
  margin: 0 1px;
  border-width: 0 2px;
}
.dj_ie .mblRoundCorner4T {
  margin: 0 1px;
}
.dj_ie .mblRoundCorner5T {
  margin: 0 1px;
}
.dj_ie .mblRoundCorner0B {
  height: 0;
}
.dj_ie .mblRoundCorner1B {
  margin: 0 1px;
}
.dj_ie .mblRoundCorner2B {
  margin: 0 1px;
}
.dj_ie .mblRoundCorner3B {
  margin: 0 1px;
  border-width: 0 2px;
}
.dj_ie .mblRoundCorner4B {
  margin: 0 2px;
  border-width: 0 3px;
}
.dj_ie .mblRoundCorner5B {
  background-color: #cccccc;
  margin: 0 5px;
}

.mblSpinWheel {
  position: relative;
  overflow: hidden;
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0, #313137), color-stop(0.05, #73747d), color-stop(0.07, #92939b), color-stop(0.09, #ababb5), color-stop(0.12, #c5c6ce), color-stop(0.16, #dfe0e4), color-stop(0.22, #f4f5f6), color-stop(0.35, #fbfcfc), color-stop(0.5, #fbfcfc), color-stop(0.61, #fbfcfc), color-stop(0.61, #b4c1c7), color-stop(0.65, #fbfcfc), color-stop(0.78, #f4f5f6), color-stop(0.84, #dfe0e4), color-stop(0.88, #c5c6ce), color-stop(0.91, #ababb5), color-stop(0.93, #92939


rror occured'))
                return False

        return True

    def createCharacter(self):
        name = self.charControl.inpCharName.value

        if len(name) >= 3:
            if self.isStringLegal(name):
                g.tcpConn.sendAddChar(name, "male", self.classIndex, (g.gameEngine.menuChar.charIndex-1))
                g.gameEngine.setState(MENU_CHAR)

    def updateClassSelection(self):
        if self.classIndex > (g.maxClasses-1):
            self.classIndex = 0
        elif self.classIndex < 0:
            self.classIndex = (g.maxClasses-1)

        self.charControl.lblClassName.set_text(Class[self.classIndex].name)

        self.labelHP.setText("HP: " + str(Class[self.classIndex].vital[Vitals.hp]))
        self.labelMP.setText("MP: " + str(Class[self.classIndex].vital[Vitals.mp]))
        self.labelSP.setText("SP: " + str(Class[self.classIndex].vital[Vitals.sp]))

        self.labelStr.setText("Strength: " + str(Class[self.classIndex].stat[Stats.strength]))
        self.labelDef.setText("Defense: " + str(Class[self.classIndex].stat[Stats.defense]))
        self.labelSpd.setText("Speed: " + str(Class[self.classIndex].stat[Stats.speed]))
        self.labelMag.setText("Magic: " + str(Class[self.classIndex].stat[Stats.magic]))

        self.updateCharSprite(Class[self.classIndex].sprite)

    def updateCharSprite(self, sprite):
        tempImage = pygame.image.load(g.dataPath + "/sprites/" + str(sprite) + ".png").convert_alpha()
        tempSprite = pygame.Surface((64, 64))

        tempSprite.blit(tempImage, (0, 0), (0, 128, 64, 64))

        self.spriteImage = pygame.transform.scale(tempSprite, (2*PIC_X * self.spriteScale, 2*PIC_Y * self.spriteScale))
        self.spriteImage.set_colorkey((0, 0, 0))


using Aevatar.Core.Tests.TestEvents;
using Aevatar.Core.Tests.TestGAgents;
using Aevatar.EventSourcing.Core;
using Aevatar.GAgents.Tests;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Orleans.EventSourcing;
using Shouldly;

namespace Aevatar.Core.Tests;

[Trait("Category", "BVT")]
[Collection("Non-Parallel Collection")]
public class EventSourcingTests : GAgentTestKitBase
{
    [Fact(DisplayName = "Implementation of LogViewAdaptor works.")]
    public async Task LogViewAdaptorTest()
    {
        // Arrange.
        var guid = Guid.NewGuid();
        var logViewGAgent = await Silo.CreateGrainAsync<LogViewAdaptorTestGAgent>(guid);
        var groupGAgent = await CreateGroupGAgentAsync(logViewGAgent);
        var publishingGAgent = await CreatePublishingGAgentAsync(groupGAgent);

        AddProbesByGrainId(publishingGAgent, groupGAgent, logViewGAgent);

        // Act: First event.
        await publishingGAgent.PublishEventAsync(new NaiveTestEvent
        {
            Greeting = "First event"
        });

        // Act: Deactivate and re-activate the logViewGAgent.
        // TODO: Modify this, because Aevatar.TestKit cannot execute OnActivateAsync.
        //await Silo.DeactivateAsync(logViewGAgent);
        logViewGAgent = await Silo.CreateGrainAsync<LogViewAdaptorTestGAgent>(guid);

        // Act: Second event.
        await publishingGAgent.PublishEventAsync(new NaiveTestEvent
        {
            Greeting = "Second event"
        });

        // Assert.
        {
            await TestHelper.WaitUntilAsync(_ => CheckCount(logViewGAgent, 2));
            (await logViewGAgent.GetStateAsync()).Content.Count.ShouldBe(2);
        }

        // Act: Third event.
        await publishingGAgent.PublishEventAsync(new NaiveTestEvent
        {
            Greeting = "Third event"
        });

        // Assert.
        {
            await TestHelper.WaitUntilAsync(_ => CheckCount(logViewGAgent, 3));
            (await logViewGAgent.GetStateAsync()).Content.Count.ShouldBe(3);
        }

        const int minimum = 1; // SetParent or AddChildren event.
        // Asset: Check the log storage.
        InMemoryLogConsistentStorage.Storage.Count.ShouldBeGreaterThanOrEqualTo(3);
        InMemoryLogConsistentStorage.Storage.ShouldContainKey(GetStreamName(logViewGAgent.GetGrainId()));
        InMemoryLogConsistentStorage.Storage[GetStreamName(logViewGAgent.GetGrainId())].Count.ShouldBe(minimum + 3);
        InMemoryLo


t &gps, const p_data_hdr_t &hdr, const string didName)	cInertialSenseDisplay

DataToStringRTOS(const rtos_info_t &info, const p_data_hdr_t &hdr)	cInertialSenseDisplay

DataToStringSensorsADC(const sys_sensors_adc_t &sensorsADC, const p_data_hdr_t &hdr)	cInertialSenseDisplay

DataToStringSurveyIn(const survey_in_t &survey, const p_data_hdr_t &hdr)	cInertialSenseDisplay

DataToStringSysParams(const sys_params_t &sys, const p_data_hdr_t &hdr)	cInertialSenseDisplay

DataToStringSysSensors(const sys_sensors_t &sensors, const p_data_hdr_t &hdr)	cInertialSenseDisplay

DMODE_PRETTY enum value	cInertialSenseDisplay

DMODE_QUIET enum value	cInertialSenseDispla


a_blobs.iter().for_each(|b| {
                    let blob = b.read().unwrap();
                    sock.send_to(&blob.data[..blob.meta.size], &peer.tvu)
                        .unwrap();
                });
                fake_coding_blobs.iter().for_each(|b| {
                    let blob = b.read().unwrap();
                    sock.send_to(&blob.data[..blob.meta.size], &peer.tvu)
                        .unwrap();
                });
            } else {
                data_blobs.iter().for_each(|b| {
                    let blob = b.read().unwrap();
                    sock.send_to(&blob.data[..blob.meta.size], &peer.tvu)
                        .unwrap();
                });
                coding_blobs.iter().for_each(|b| {
                    let blob = b.read().unwrap();
                    sock.send_to(&blob.data[..blob.meta.size], &peer.tvu)
                        .unwrap();
                });
            }
        });

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::contact_info::ContactInfo;
    use solana_sdk::pubkey::Pubkey;
    use std::net::{IpAddr, Ipv4Addr, SocketAddr};

    #[test]
    fn test_tvu_peers_ordering() {
        let mut cluster = ClusterInfo::new_with_invalid_keypair(ContactInfo::new_localhost(
            &Pubkey::new_rand(),
            0,
        ));
        cluster.insert_info(ContactInfo::new_with_socketaddr(&SocketAddr::new(
            IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1)),
            8080,
        )));
        cluster.insert_info(ContactInfo::new_with_socketaddr(&SocketAddr::new(
            IpAddr::V4(Ipv4Addr::new(192, 168, 1, 2)),
            8080,
        )));
        cluster.insert_info(ContactInfo::new_with_socketaddr(&SocketAddr::new(
            IpAddr::V4(Ipv4Addr::new(192, 168, 1, 3)),
            8080,
        )));
        cluster.insert_info(ContactInfo::new_with_socketaddr(&SocketAddr::new(
            IpAddr::V4(Ipv4Addr::new(192, 168, 1, 4)),
            8080,
        )));

        let tvu_peers1 = cluster.tvu_peers();
        (0..5).for_each(|_| {
            cluster
                .tvu_peers()
                .iter()
                .zip(tvu_peers1.iter())
                .for_each(|(v1, v2)| {
                    assert_eq!(v1, v2);
                });
        });
    }
}
use std::fmt;
use std::rc::{Rc, Weak};
use std::cell::RefCell;
use crate::parser::Ast;
use std::collections::HashMap;
use super::environment::{Scope, Environment};
use super::eval_class::Class;

#[derive(Clone, PartialEq, Copy)]
pub enum CallingContext {
    Constructor, SelfCall, Public
}

#[derive(Clone)]
pub enum Values {
    Int(i32),
    Float(f64),
    Str(String),
    Unit,
    Bool(bool),
    Func(Vec<(String, bool, Option<Ast>)>, Ast, Rc<RefCell<Scope>>, Option<Ast>),
    Array(Box<Vec<Values>>),
    Tuple(Box<Vec<Values>>),
    Range(Box<Values>, Box<Values>),
    Map(Box<HashMap<String, Values>>),
    Placeholder,
    Ref(Rc<RefCell<Values>>, bool),
    WeakRef(Weak<RefCell<Values>>, bool), //Invariant: weak ref must always be valid
    RustFunc(Rc<dyn Fn(Vec<Values>) -> Res>, usize),
    Object(Rc<RefCell<Class>>, CallingContext),
    Type(Rc<Class>),
}

#[derive(PartialEq, Debug, Clone)]
pub enum Res {
    Vl(Values),
    Exn(


r warnings.
  factory SpeechGrammar._() { throw new UnsupportedError("Not supported"); }

  @DomName('SpeechGrammar.SpeechGrammar')
  @DocsEditable()
  factory SpeechGrammar() {
    return SpeechGrammar._create_1();
  }
  static SpeechGrammar _create_1() => JS('SpeechGrammar', 'new SpeechGrammar()');

  @DomName('SpeechGrammar.src')
  @DocsEditable()
  String src;

  @DomName('SpeechGrammar.weight')
  @DocsEditable()
  num weight;
}
// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

@DocsEditable()
@DomName('SpeechGrammarList')
// https://dvcs.w3.org/hg/speech-api/raw-file/tip/speechapi.html#dfn-speechgrammarlist
@Experimental()
class SpeechGrammarList extends Interceptor with ListMixin<SpeechGrammar>, ImmutableListMixin<SpeechGrammar> implements JavaScriptIndexingBehavior, List<SpeechGrammar> native "SpeechGrammarList" {
  // To suppress missing implicit constructor warnings.
  factory SpeechGrammarList._() { throw new UnsupportedError("Not supported"); }

  @DomName('SpeechGrammarList.SpeechGrammarList')
  @DocsEditable()
  factory SpeechGrammarList() {
    return SpeechGrammarList._create_1();
  }
  static SpeechGrammarList _create_1() => JS('SpeechGrammarList', 'new SpeechGrammarList()');

  @DomName('SpeechGrammarList.length')
  @DocsEditable()
  int get length => JS("int", "#.length", this);

  SpeechGrammar operator[](int index) {
    if (JS("bool", "# >>> 0 !== # || # >= #", index,
        index, index, length))
      throw new RangeError.range(index, 0, length);
    return JS("SpeechGrammar", "#[#]", this, index);
  }
  void operator[]=(int index, SpeechGrammar value) {
    throw new UnsupportedError("Cannot assign element of immutable List.");
  }
  // -- start List<SpeechGrammar> mixins.
  // SpeechGrammar is the element type.

  void set length(int value) {
    throw new UnsupportedError("Cannot resize immutable List.");
  }

  SpeechGrammar get first {
    if (this.length > 0) {
      return JS('SpeechGrammar', '#[0]', this);
    }
    throw new StateError("No elements");
  }

  SpeechGrammar get last {
    int len = this.length;
    if (len > 0) {
      return JS('SpeechGrammar', '#[#]', this, len - 1);
    }
    throw new StateError("No elements");
  }

  SpeechGrammar get single {
    int len = this.length;
    if (len == 1) {
      return JS('SpeechGrammar', '#[0]', this);
    }
    if (len == 0) throw new StateError("No elements");
    throw new StateError("More than one element");
  }

  SpeechGrammar elementAt(int index) => this[index];
  // -- end List<SpeechGrammar> mixins.

  @DomName('SpeechGrammarList.addFromString')
  @DocsEditable()
  void addFromString(String string, [num weight]) native;

  @DomName('SpeechGrammarList.addFromUri')
  @DocsEditable()
  void addFromUri(String src, [num weight]) native;

  @DomName('SpeechGrammarList.item')
  @DocsEditable()
  SpeechGrammar item(int index) native;
}
// Copyright (c) 2012, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

@DocsEditable()
@DomName('SpeechInputEvent')


user else 'Unknown'} - {close_code}")
        except Exception as e:
            logger.error(f"断开连接时出错: {str(e)}")
            print(f"[InterviewConsumer] disconnect error: {e}")

    async def receive(self, text_data):
        """接收WebSocket消息"""
        try:
            data = json.loads(text_data)
            message_type = data.get('type')

            if message_type == 'start_interview':
                await self.handle_start_interview(data)
            elif message_type == 'audio_frame':
                await self.handle_audio_frame(data)
            elif message_type == 'video_frame':
                await self.handle_video_frame(data)
            elif message_type == 'request_next_question':
                await self.handle_request_next_question()
            elif message_type == 'disconnect':
                await self.handle_disconnect(data)
            else:
                await self.send(text_data=json.dumps({
                    'type': 'error',
                    'text': f'未知的消息类型: {message_type}'
                }))

        except json.JSONDecodeError:
            print("[InterviewConsumer] receive JSON decode error")
            await self.send(text_data=json.dumps({
                'type': 'error',
                'text': '无效的JSON格式'
            }))
        except Exception as e:
            logger.error(f"处理消息时出错: {str(e)}")
            print(f"[InterviewConsumer] receive error: {e}")
            await self.send(text_data=json.dumps({
                'type': 'error',
                'text': f'处理消息时出错: {str(e)}'
            }))

    async def handle_start_interview(self, data):
        """处理开始面试请求"""
        try:
            interview_id = data.get('interview_id')
            if not interview_id:
                await self.send(text_data=json.dumps({
                    'type': 'error',
                    'text': '缺少面试ID'
                }))
                return

            # 获取面试记录
            self.interview = await self.get_interview(interview_id)
            if not self.interview:
                await self.send(text_data=json.dumps({
                    'type': 'error',
                    'text': '面试记录不存在'
                }))
                return

            await self.send(text_data=json.dumps({
                'type': 'interview_started',
                'interview_id': interview_id,
                'text': '面试已开始'
            }))

        except Exception as e:
            logger.error(f"开始面试失败: {str(e)}")
            await self.send(text_data=json.dumps({
                'type': 'error',
                'text': f'开始面试失败: {str(e)}'
            }))

    async def handle_video_frame(self, data):
        """处理视频帧数据，集成YOLOv11和原生PyTorch情绪识别"""
        # 检查interview是否已初始化
        if not hasattr(self, 'interview') or self.interview is None:
            await self.send(text_data=json.dumps({
                'type': 'error',
                'text': '未初始化面试，请先开始面试'
            }))
            return
        try:
            frame_data = data.get('frame_data')
            frame_type = data.get('frame_type', 'keyframe')
            if not frame_data:
                await self.send(text_data=json.dumps({
                    'type': 'error',
                    'text': '缺少帧数据'
                }))
                return
            # 处理data:image/jpeg;base64,前缀，确保为纯base64字符串
            if isinstance(frame_data, str):
                if frame_data.startswith('data:image'):
                    frame_data = frame_data.split(',', 1)[-1]
                img_bytes = base64.b64decode(frame_data)
            elif isinstance(frame_data, bytes):
                img_bytes = base64.b64decode(frame_data)
            else:
                raise ValueError("frame_data类型错误，必须为str或bytes")
            np_arr = np.frombuffer(img_bytes, np.uint8)
            img = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)
            if img is None:
                await self.send(text_data=json.dumps({
                    'type': 'error',
                    'text': '无法解码图像数据'
                }))
                return
            # 1. YOLOv11检测人数（只加载一次模型）
            if not hasattr(self, 'yolo_model'):
                self.yolo_model = YOLO('yolo11n.pt')
            results = self.yolo_model(img)
            persons = [b for b in results[0].boxes.data.cpu().numpy() if int(b[5]) == 0]
            if len(persons) > 1:
                await self.send(text_data=json


! { keyberon::action::Action::MultipleKeyCodes(&[keyberon::key_code::KeyCode::LShift, keyberon::key_code::KeyCode::Kb9]), }),
        "')'" => out.extend(quote! { keyberon::action::Action::MultipleKeyCodes(&[keyberon::key_code::KeyCode::LShift, keyberon::key_code::KeyCode::Kb0]), }),
        "'{'" => out.extend(quote! { keyberon::action::Action::MultipleKeyCodes(&[keyberon::key_code::KeyCode::LShift, keyberon::key_code::KeyCode::LBracket]), }),
        "'}'" => out.extend(quote! { keyberon::action::Action::MultipleKeyCodes(&[keyberon::key_code::KeyCode::LShift, keyberon::key_code::KeyCode::RBracket]), }),
        "'_'" => out.extend(quote! { keyberon::action::Action::MultipleKeyCodes(&[keyberon::key_code::KeyCode::LShift, keyberon::key_code::KeyCode::Minus]), }),

        s if s.starts_with('\'') => emit_error!(l, "Literal could not be parsed as a keycode"; help = "Maybe try without quotes?"),

        s if s.starts_with('\"')  => {
            if s.len() == 3 {
                emit_error!(l, "Typing strings on key press is not yet supported"; help = "Did you mean to use apostrophes instead of quotes?");
            } else {
                emit_error!(l, "Typing strings on key press is not yet supported");
            }
        }
        _ => emit_error!(l, "Literal could not be parsed as a keycode")
    }
}/*
	Define a struct
*/

struct Greeting {
	name: String
}

fn main() {
	let greeting = Greeting {
		name: "abhijit".to_string()
	};

	println!("Hello, {}", greeting.name);
}<reponame>mhuesch/holochain<filename>crates/kitsune_p2p/proxy/src/bin/kitsune-p2p-proxy/opt.rs
/// Option Parsing
#[derive(structopt::StructOpt, Debug)]
#[structopt(name = "kitsune-p2p-proxy")]
pub struct Opt {
    /// Generate a new self-signed certificate file/priv key and exit.
    /// Danger - this cert is written unencrypted to disk.
    #[structopt(long)]
    pub danger_gen_unenc_cert: Option<std::path::PathBuf>,

    /// Use a dangerous unencryted tls cert/priv key for this proxy.
    #[structopt(long)]
    pub danger_use_unenc_cert: Option<std::path::PathBuf>,

    /// To which network interface / port should we bind?
    /// Default: "kitsune-quic://0.0.0.0:0".
    #[structopt(short = "b", long)]
    pub bind_to: Option<String>,

    /// If you have port-forwarding set up,
    /// or wish to apply a vanity domain name,
    /// you may need to override the local NIC ip.
    /// Default: None = use NIC ip.
    #[structopt(short = "h", long)]
    pub override_host: Option<String>,
}

impl From<&Opt> for kitsune_p2p_transport_quic::ConfigListenerQuic {
    fn from(o: &Opt) -> Self {
        let mut out = Self::default();
        if let Some(b) = &o.bind_to {
            out = out.set_bind_to(Some(kitsune_p2p_types::dependencies::url2::url2!("{}", b)));
        }
        if let Some(h) = &o.override_host {
            out = out.set_override_host(Some(h));


#ifndef  __DE_CLOCK_H__
#define  __DE_CLOCK_H__

#include "ebios_de.h"

typedef enum
{
	CLK_NONE = 0,

	SYS_CLK_PLL3 = 1,
	SYS_CLK_PLL7 = 2,
	SYS_CLK_PLL9 = 3,
	SYS_CLK_PLL10 = 4,
	SYS_CLK_PLL3X2 = 5,
	SYS_CLK_PLL6 = 6,
	SYS_CLK_PLL6x2 = 7,
	SYS_CLK_PLL7X2 = 8,
	SYS_CLK_MIPIPLL = 9,

	MOD_CLK_DEBE0 = 16,
	MOD_CLK_DEBE1 = 17,
	MOD_CLK_DEFE0 = 18,
	MOD_CLK_DEFE1 = 19,
	MOD_CLK_LCD0CH0 = 20,
	MOD_CLK_LCD0CH1 = 21,
	MOD_CLK_LCD1CH0 = 22,
	MOD_CLK_LCD1CH1 = 23,
	MOD_CLK_HDMI = 24,
	MOD_CLK_HDMI_DDC = 25,
	MOD_CLK_MIPIDSIS = 26,
	MOD_CLK_MIPIDSIP = 27,
	MOD_CLK_IEPDRC0 = 28,
	MOD_CLK_IEPDRC1 = 29,
	MOD_CLK_IEPDEU0 = 30,
	MOD_CLK_IEPDEU1 = 31,
	MOD_CLK_LVDS = 32,
	MOD_CLK_EDP  = 33,
	MOD_CLK_DEBE2 = 34,
	MOD_CLK_DEFE2 = 35,
	MOD_CLK_SAT0 = 36,
	MOD_CLK_SAT1 = 37,
	MOD_CLK_SAT2 = 38,
	MOD_CLK_MERGE = 39,
}__disp_clk_id_t;

typedef struct
{
	__disp_clk_id_t       id;     /* clock id         */
	char        *name;  /* clock name       */
	char *src_name;
	u32 freq;
	struct clk  *hdl;
}__disp_clk_t;

extern __disp_clk_t disp_clk_pll_tbl[3];
extern __disp_clk_t disp_clk_mod_tbl[8];

#endif   //__DE_CLOCK_H__


tItemInSection));
		}
	}

	int itemsInSection = 0;

	public int ItemsInSection
	{
		get => itemsInSection;
		set
		{
			itemsInSection = value;
			this.Resources[nameof(ItemsInSection)] = itemsInSection;
			this.OnPropertyChanged(nameof(ItemsInSection));
		}
	}

	int numberOfSections = 0;
	public int NumberOfSections
	{
		get => numberOfSections;
		set
		{
			numberOfSections = value;
			this.Resources[nameof(NumberOfSections)] = numberOfSections;
			this.OnPropertyChanged(nameof(NumberOfSections));
		}
	}

	bool isGlobalHeader = false;
	public bool IsGlobalHeader
	{
		get => isGlobalHeader;
		set
		{
			isGlobalHeader = value;
			this.Resources[nameof(IsGlobalHeader)] = IsGlobalHeader;
			this.OnPropertyChanged(nameof(IsGlobalHeader));
		}
	}

	bool isGlobalFooter = false;
	public bool IsGlobalFooter
	{
		get => isGlobalFooter;
		set
		{
			isGlobalFooter = value;
			this.Resources[nameof(IsGlobalFooter)] = isGlobalFooter;
			this.OnPropertyChanged(nameof(IsGlobalFooter));
		}
	}

	bool isSectionHeader = false;
	public bool IsSectionHeader
	{
		get => isSectionHeader;
		set
		{
			isSectionHeader = value;
			this.Resources[nameof(IsSectionHeader)] = isSectionHeader;
			this.OnPropertyChanged(nameof(IsSectionHeader));
		}
	}

	bool isSectionFooter = false;
	public bool IsSectionFooter
	{
		get => isSectionFooter;
		set
		{
			isSectionFooter = value;
			this.Resources[nameof(IsSectionFooter)] = isSectionFooter;
			this.OnPropertyChanged(nameof(IsSectionFooter));
		}
	}

	PositionKind kind = PositionKind.Item;
	public PositionKind Kind
	{
		get => kind;
		set
		{
			kind = value;
			this.Resources[nameof(Kind)] = kind;
			this.OnPropertyChanged(nameof(Kind));
		}
	}

	public bool IsLastItemInSection => ItemIndex >= ItemsInSection - 1;
	public bool IsNotLastItemInSection => !IsLastItemInSection;
	public bool IsFirstItemInSection => ItemIndex == 0;
	public bool IsNotFirstItemInSection => !IsFirstItemInSection;

	void UpdateBackground()
	{
		var c = IsSelected ? SelectedBackground : UnselectedBackground;
		Background = c;
	}
}


       lm.AntDir .. "/3rd/bx/include",
        lm.os == "windows" and {
            lm.compiler == "msvc"
            and { lm.AntDir .. "/3rd/bx/include/compat/msvc" }
            or { lm.AntDir .. "/3rd/bx/include/compat/mingw" },
        }
    }
}

lm.builddir = ("build/%s/%s"):format(plat, lm.mode)
lm.bindir = ("bin/%s/%s"):format(plat, lm.mode)

if lm.sanitize then
    lm.builddir = ("build/%s/sanitize"):format(plat)
    lm.bindir = ("bin/%s/sanitize"):format(plat)
    lm:conf {
        mode = "debug",
        flags = "-fsanitize=address",
        gcc = {
            ldflags = "-fsanitize=address"
        },
        clang = {
            ldflags = "-fsanitize=address"
        }
    }
    lm:msvc_copydll "copy_asan" {
        type = "asan",
        outputs = lm.bindir,
    }
end

lm:import "runtime/make.lua"

lm:runlua "compile_ecs" {
    script = "clibs/ecs/ecs_compile.lua",
    args = {
        lm.AntDir,
        "$out",
        "@pkg",
    },
    inputs = lm.AntDir.."/pkg/**/*.ecs",
    outputs = "clibs/ecs/ecs/component.hpp",
}

if lm.os ~= "ios" and lm.os ~= "android" then
    lm:phony "tools" {
        deps = {
            "gltf2ozz",
            "shaderc",
            "texturec",
            "tools_version",
        }
    }
    lm:phony "all" {
        deps = {
            "ant",
            "tools",
        }
    }
end

lm:default {
    "ant",
    lm.os == "windows" and "lua54",
    lm.compiler == "msvc" and lm.sanitize and "copy_asan",
}