]
//! Core structs and traits for paperclip.

#[cfg_attr(feature = "v2", macro_use)]
extern crate serde;

mod error;
pub mod im;
#[cfg(feature = "v2")]
pub mod v2;

pub use self::error::ValidationError;
use fern::{
    colors::{Color, ColoredLevelConfig}
};

/// Sets up regular logging
pub fn setup_log(verbose: bool) {
    let colors_line = ColoredLevelConfig::new()
        .error(Color::Red)
        .warn(Color::Yellow)
        .info(Color::Green)
        .debug(Color::White)
        .trace(Color::BrightBlack);
    let colors_level = colors_line.info(Color::Green);

    fern::Dispatch::new()
        .chain(
            fern::Dispatch::new()
                .level(if verbose {
                    log::LevelFilter::Debug
                } else {
                    log::LevelFilter::Info
                })
                .format(move |out, message, record| {
                    out.finish(format_args!(
                        "{color_line}[{date}][{target}][{level}{color_line}] {message}\x1B[0m",
                        color_line = format_args!(
                            "\x1B[{}m",
                            colors_line.get_color(&record.level()).to_fg_str()
                        ),
                        date = chrono::Local::now().format("%Y-%m-%d %H:%M:%S"),
                        target = record.target(),
                        level = colors_level.color(record.level()),
                        message = message,
                    ));
                })
                .chain(std::io::stdout()),
        )
        .apply()
        .unwrap();
}pub mod misc;
pub mod linalg;
pub mod msbf;
pub mod sphr;
//! A Rust library for parsing the SOME/IP network protocol (without payload interpretation).
//!
//! # Usage
//!
//! Add the following to your `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! someip_parse = "0.3.1"
//! ```
//!
//! # Example
//! [examples/print_messages.rs](https://github.com/JulianSchmid/someip-parse-rs/blob/0.2.0/examples/print_messages.rs):
//! ```
//! # let mut udp_payload = Vec::<u8>::new();
//! # {
//! #     use someip_parse::*;
//! #     let header = SomeIpHeader{
//! #         message_id: 0x1234_8234,
//! #         length: SOMEIP_LEN_OFFSET_TO_PAYLOAD + 4,
//! #         request_id: 1,
//! #         interface_version: 1,
//! #         message_type: MessageType::Notification,
//! #         return_code: ReturnCode::Ok.into(),
//! #         tp_header: None
//! #     };/*
//! #     header.write_raw(&mut udp_payload).unwrap();
//! #     udp_payload.extend_from_slice(&[1,2,3,4]);*/
//! # }
//! use someip_parse::SliceIterator;
//!
//! //trying parsing some ip messages located in a udp payload
//! for someip_message in SliceIterator::new(&udp_payload) {
//!     match someip_message {
//!         Ok(value) => {
//!             if value.is_someip_sd() {
//!                 println!("someip service discovery packet");
//!             } else {
//!                 println!("0x{:x} (service id: 0x{:x}, method/event id: 0x{:x})",
//!                          value.message_id(),
//!                          value.service_id(),
//!                          value.event_or_method_id());
//!             }
//!             println!("  with payload {:?}", value.payload())
//!


 fs = require('fs');
import path = require('path');
import childProcess = require('child_process');

const examplesDir = path.join(__dirname, '../examples');
const examples = fs.readdirSync(examplesDir).filter(ex => /^\d/.exec(ex));

/** get rid of any untracked files, including newly-created migrations and the sqlite db file, so that each run is from scratch and has the same output (give or take timings etc.) */
const cleanup = (cwd: string) => {
	childProcess.execSync('git checkout migrations && git clean migrations seeders db.sqlite -fx', {
		cwd,
		stdio: 'inherit',
	});
};

examples.forEach(ex => {
	test(`example ${ex}`, async () => {
		const dir = path.join(examplesDir, ex);
		const readmeFile = fs.readdirSync(dir).find(f => f.toLowerCase() === 'readme.md');
		const readme = fs.readFileSync(path.join(dir, readmeFile!)).toString();
		const bash = readme.split('```bash')[1].split('```')[0].trim();

		cleanup(dir);

		const stdout = bash
			.split('\n')
			.map(line => line.split('#')[0].trim())
			.filter(Boolean)
			.flatMap(cmd => {
				let output = childProcess.execSync(`sh -c "${cmd} 2>&1"`, { cwd: dir }).toString().trim();
				output = cmd.startsWith('npm') || cmd.endsWith('--help') ? '...' : output; // npm commands and `--help` are formatted inconsistently and aren't v relevant
				output = output.split(process.cwd()).join('<<cwd>>'); // cwd varies by machine
				output = output.replace(/durationSeconds: .*/g, 'durationSeconds: ???'); // migrations durations vary by a few milliseconds
				output = output.replace(/\d{4}.\d{2}.\d{2}T\d{2}.\d{2}.\d{2}/g, '<<timestamp>>'); // the river of time flows only in one direction
				return [`\`${cmd}\` output:`, output];
			})
			.join('\n\n');

		expect(stdout).toMatchSnapshot();
	});
});
module Lgs {
	export class snowing extends egret.DisplayObjectContainer{
		/**mode boom snowing*/
		public constructor(mode:string) {
			super();
			this.mode = mode;
			this.once(egret.Event.ADDED_TO_STAGE,this.onAddToStage,this);
			this.once(egret.Event.REMOVED_FROM_STAGE,this.removedFun,this);
		}
		/**数量 */
		public csNums = 34;
		/**最小缩放大小 +1*/
		public scale1 = 0.4;
		/**最远距离 */
		public maxJuli = gh*0.65;
		/**最小下降速度 */
		public minSudu = gh*0.0015;
		/**最大下降速度 minSudu+maxSudu*/
		public maxSudu = gh*0.0035;
		/**x范围 */
		public csw = gw*0.9;

		/**是否可以刮风 */
		public canWind = false;
		/**横向风速 */
		public windSpeed = 0;
		/**横向风速2  */
		public windSpeed2 = 0;
		/**刮风间隔 */
		public windCount = 3000;
		/**false 风速开始减小 */
		private windAdd


USTIVE_SUCCESS(schema, instance, 3);

  EVALUATE_TRACE_PRE(0, LoopProperties, "/additionalProperties",
                     "#/additionalProperties", "");
  EVALUATE_TRACE_PRE(1, AssertionTypeStrict, "/additionalProperties/type",
                     "#/additionalProperties/type", "/foo");
  EVALUATE_TRACE_PRE_ANNOTATION(2, "/additionalProperties",
                                "#/additionalProperties", "");

  EVALUATE_TRACE_POST_SUCCESS(0, AssertionTypeStrict,
                              "/additionalProperties/type",
                              "#/additionalProperties/type", "/foo");
  EVALUATE_TRACE_POST_ANNOTATION(1, "/additionalProperties",
                                 "#/additionalProperties", "", "foo");
  EVALUATE_TRACE_POST_SUCCESS(2, LoopProperties, "/additionalProperties",
                              "#/additionalProperties", "");

  EVALUATE_TRACE_POST_DESCRIBE(instance, 0,
                               "The value was expected to be of type string");
  EVALUATE_TRACE_POST_DESCRIBE(
      instance, 1,
      "The object property \"foo\" successfully validated against the "
      "additional properties subschema");
  EVALUATE_TRACE_POST_DESCRIBE(
      instance, 2,
      "The object properties not covered by other adjacent object keywords "
      "were expected to validate against this subschema");
}

TEST(Evaluator_2020_12, cross_id_1) {
  const sourcemeta::core::JSON schema{sourcemeta::core::parse_json(R"JSON({
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "$ref": "#/$defs/schema/items",
    "$defs": {
      "schema": {
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "$id": "https://www.example.com",
        "items": {
          "type": "string"
        }
      }
    }
  })JSON")};

  const sourcemeta::core::JSON instance{"foo bar"};
  EVALUATE_WITH_TRACE_FAST_SUCCESS(schema, instance, 1);

  EVALUATE_TRACE_PRE(0, AssertionTypeStrict, "/$ref/type",
                     "https://www.example.com#/items/type", "");
  EVALUATE_TRACE_POST_SUCCESS(0, AssertionTypeStrict, "/$ref/type",
                              "https://www.example.com#/items/type", "");
  EVALUATE_TRACE_POST_DESCRIBE(instance, 0,
                               "The value was expected to be of type string");
}

TEST(Evaluator_2020_12, propertyNames_1) {
  const sourcemeta::core::JSON schema{sourcemeta::core::parse_json(R"JSON({
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "propertyNames": {
      "title": "Test",
      "description": "Test",
      "default": "Test",
      "deprecated": true,
      "examples": [ "foo" ],
      "readOnly": true,
      "writeOnly": true,

      "x-foo": "bar",

      "format": "email",

      "contentEncoding": "base64",
      "contentMediaType": "application/json",
      "contentSchema": true,

      "prefixItems": [ { "type": "string" } ],
      "items": { "type": "string" },
      "unevaluatedItems": { "type": "string" },
      "contains": { "type": "string" },

      "properties": { "foo": { "type": "string" } },
      "patternProperties": { "^f": { "type": "string" } },
      "additionalProperties": { "type": "string" },
      "unevaluatedProperties": { "type": "string" }
    }
  })JSON")};

  const sourcemeta::core::JSON instance{
      sourcemeta::core::parse_json("{ \"foo\"


9, $s2, 0x80
/* 01120C 8001060C 1320000D */  beqz  $t9, .L80010644_ovl0
/* 011210 80010610 8FA8009C */   lw    $t0, 0x9c($sp)
/* 011214 80010614 15000004 */  bnez  $t0, .L80010628_ovl0
/* 011218 80010618 02602025 */   move  $a0, $s3
/* 01121C 8001061C 0C00265E */  jal   func_80009978
/* 011220 80010620 24050020 */   li    $a1, 32
/* 011224 80010624 AFA2009C */  sw    $v0, 0x9c($sp)
.L80010628_ovl0:
/* 011228 80010628 8E690070 */  lw    $t1, 0x70($s3)
/* 01122C 8001062C 8FAB009C */  lw    $t3, 0x9c($sp)
/* 011230 80010630 8D2A0000 */  lw    $t2, ($t1)
/* 011234 80010634 AD6A0020 */  sw    $t2, 0x20($t3)
/* 011238 80010638 8E6C0070 */  lw    $t4, 0x70($s3)
/* 01123C 8001063C 258D0004 */  addiu $t5, $t4, 4
/* 011240 80010640 AE6D0070 */  sw    $t5, 0x70($s3)
.L80010644_ovl0:
/* 011244 80010644 1000002E */  b     .L80010700_ovl0
/* 011248 80010648 C6620074 */   lwc1  $f2, 0x74($s3)
/* 01124C 8001064C 8E62006C */  lw    $v0, 0x6c($s3)
/* 011250 80010650 C6620074 */  lwc1  $f2, 0x74($s3)
/* 011254 80010654 3C018004 */  lui   $at, %hi(D_80040958) # $at, 0x8004
/* 011258 80010658 5040000E */  beql  $v0, $zero, .L80010694_ovl0
/* 01125C 8001065C E662007C */   swc1  $f2, 0x7c($s3)
/* 011260 80010660 904E0005 */  lbu   $t6, 5($v0)
.L80010664_ovl0:
/* 011264 80010664 51C00008 */  beql  $t6, $zero, .L80010688_ovl0
/* 011268 80010668 8C420000 */   lw    $v0, ($v0)
/* 01126C 8001066C C6640078 */  lwc1  $f4, 0x78($s3)
/* 011270 80010670 C450000C */  lwc1  $f16, 0xc($v0)
/* 011274 80010674 46022200 */  add.s $f8, $f4, $f2
/* 011278 80010678 46088280 */  add.s $f10, $f16, $f8
/* 01127C 8001067C E44A000C */  swc1  $f10, 0xc($v0)
/* 011280 80010680 C6620074 */  lwc1  $f2, 0x74($s3)
/* 011284 80010684 8C420000 */  lw    $v0, ($v0)
.L80010688_ovl0:
/* 011288 80010688 5440FFF6 */  bnezl $v0, .L80010664_ovl0
/* 01128C 8001068C 904E0005 */   lbu   $t6, 5($v0)
/* 011290 80010690 E66


iner a.leaflet-popup-close-button{position:absolute;top:0;right:0;padding:4px 4px 0 0;text-align:center;width:18px;height:14px;font:16px/14px Tahoma,Verdana,sans-serif;color:#c3c3c3;text-decoration:none;font-weight:700;background:0 0}.leaflet-container a.leaflet-popup-close-button:hover{color:#999}.leaflet-popup-scrolled{overflow:auto;border-bottom:1px solid #ddd;border-top:1px solid #ddd}.leaflet-oldie .leaflet-popup-content-wrapper{zoom:1}.leaflet-oldie .leaflet-popup-tip{width:24px;margin:0 auto;-ms-filter:"progid:DXImageTransform.Microsoft.Matrix(M11=0.70710678, M12=0.70710678, M21=-0.70710678, M22=0.70710678)";filter:progid:DXImageTransform.Microsoft.Matrix(M11=.70710678, M12=.70710678, M21=-.70710678, M22=.70710678)}.leaflet-oldie .leaflet-popup-tip-container{margin-top:-1px}.leaflet-oldie .leaflet-control-zoom,.leaflet-oldie .leaflet-control-layers,.leaflet-oldie .leaflet-popup-content-wrapper,.leaflet-oldie .leaflet-popup-tip{border:1px solid #999}.leaflet-div-icon{background:#fff;border:1px solid #666}.marker-cluster-small{background-color:rgba(181,226,140,.6)}.marker-cluster-small div{background-color:rgba(110,204,57,.6)}.marker-cluster-medium{background-color:rgba(241,211,87,.6)}.marker-cluster-medium div{background-color:rgba(240,194,12,.6)}.marker-cluster-large{background-color:rgba(253,156,115,.6)}.marker-cluster-large div{background-color:rgba(241,128,23,.6)}.leaflet-oldie .marker-cluster-small{background-color:#b5e28c}.leaflet-oldie .marker-cluster-small div{background-color:#6ecc39}.leaflet-oldie .marker-cluster-medium{background-color:#f1d357}.leaflet-oldie .marker-cluster-medium div{background-color:#f0c20c}.leaflet-oldie .marker-cluster-large{background-color:#fd9c73}.leaflet-oldie .marker-cluster-large div{background-color:#f18017}.marker-cluster{background-clip:padding-box;border-radius:20px}.marker-cluster div{width:30px;height:30px;margin-left:5px;margin-top:5px;text-align:center;border-radius:15px;font:12px "Helvetica Neue",Arial,Helvetica,sans-serif}.marker-cluster span{line-height:30px}.leaflet-cluster-anim .leaflet-marker-icon,.leaflet-cluster-anim .leaflet-marker-shadow{-webkit-transition:-webkit-transform .3s ease-out,opacity .3s ease-in;-moz-transition:-moz-transform .3s ease-out,opacity .3s ease-in;-o-transition:-o-transform .3s ease-out,opacity .3s ease-in;transition:transform .3s ease-out,opacity .3s ease-in}.bootstrap-tagsinput{background-color:#fff;border:1px solid #ccc;box-shadow:inset 0 1px 1px rgba(0,0,0,.075);display:inline-block;padding:4px 6px;margin-bottom:10px;color:#555;vertical-align:middle;border-radius:4px;max-width:100%;line-height:22px;cursor:text}.bootstrap-tagsinput input{border:none;box-shadow:none;outline:0;background-color:transparent;padding:0;margin:0;width:auto!important;max-width:inherit}.bootstrap-tagsinput input:focus{border:none;box-shadow:


 "g4skins",
    "gameodds.gg",
    "duckfuck.com",
    "crysishosting.com",
    "crysishosting",
    "key-drop.com",
    "key-drop.pl",
    "skinhub.com",
    "skinhub",
    "casedrop.eu",
    "casedrop",
    "cs.money",
    "rustypot.com",
    "rampage.lt",
    "?",
    "xcasecsgo.com",
    "xcasecsgo",
    "csgocases.com",
    "csgocases",
    "K9GrillzUK.co.uk",
    "moat.gg",
    "princevidz.com",
    "princevidz",
    "pvpro.com",
    "Pvpro",
    "ez.krimes.ro",
    "loot.farm",
    "arma3fisherslife.net",
    "arma3fisherslife",
    "egamers.io",
    "ifn.gg",
    "key-drop",
    "sups.gg",
    "tradeit.gg",
    "§",
    "csgotraders.net",
    "csgotraders",
    "hurtfun.com",
    "hurtfun",
    "gamekit.com",
    "t.tv",
    "yandex.ru",
    "yandex",
    "csgofly.com",
    "csgofly",
    "pornhub.com",
    "pornhub",
    "cs.deals",
    "twat",
    "STRESS.PW"
}


   "errorOccuredAlert": "Vyskytla sa chyba!",
    "link": "Prepojiť",
    "customInsSelectMsg": "Vyberte vlastnú inštanciu",
    "restore": "Obnoviť",
    "closeApp": "Zavrieť aplikáciu",
    "restoring": "Obnovovanie...",
    "restoreMsg": "Úspešne obnovené!\nZmeny sa aplikujú pri reštarte",
    "backFilesFound": "databázy nájdené",
    "backupMsg": "Záloha úspešne uložená!",
    "restoreSettingsAndPlaylistsDes": "Obnoví všetky nastavenia, prihlasovacie údaje a playlisty zo záložného súboru. Prepíše všetky aktuálne údaje",
    "restoreSettingsAndPlaylists": "Obnoviť nastavenia a playlisty",
    "backupSettingsAndPlaylistsDes": "Uloží všetky nastavenia, playlisty a prihlasovacie údaje do záložného súboru",
    "backupSettingsAndPlaylists": "Zálohovať nastavenia a playlisty",
    "cacheHomeScreenDataDes": "Zapnite ukladanie údajov obsahu domovskej obrazovky do medzipamäte, Ak je táto možnosť povolená, domovská obrazovka sa načíta okamžite",
    "stopMusicOnTaskClearDes": "Prehrávanie hudby sa zastaví, keď sa aplikácia odstráni preč zo správcu úloh",
    "disableTransitionAnimation": "Vypnúť prechodovú animáciu",
    "deleteDownloadData": "Odstrániť zo stiahnutých",
    "local": "Lokálny",
    "goToDownloadPage": "Ak chcete prejsť na stránku sťahovania, kliknite sem",
    "unlinkAlert": "Odpojené úspešne!",
    "downloads": "Stiahnuté",
    "upNext": "Nasledujúce",
    "discover": "Doporučené",
    "plain": "Obyčajný",
    "deleteDownloadedDataAlert": "Úspešne odstránené zo stiahnutých!",
    "linkPipedDes": "Prepojte s Piped pre playlisty",
    "playNext": "Prehrať ďalej",
    "unLink": "Odpojiť",
    "linkAlert": "Prepojené úspešne!",
    "dismiss": "Odmietnuť",
    "processFiles": "Spracovanie súborov...",
    "includeDownloadedFiles": "Zahrnúť stiahnuté skladby",
    "backupInProgress": "Prebieha zálohovanie...",
    "restoreAppData": "Obnoviť dáta aplikácie",
    "backup": "Zálohovať",
    "backupAppData": "Zálohovať dáta aplikácie",
    "letsStrart": "Začíname...",
    "audioCodec": "Audio kodek",
    "duration": "Dĺžka",
    "title": "Názov",
    "id": "ID",
    "songInfo": "Informácie o skladbe",
    "bitrate": "Bitrate",
    "loudnessDb": "Hlasitosť (Db)",
    "restartApp": "Reštartovať aplikáciu",
    "downloadError2": "Požadovanú skladbu nie je možné stiahnuť z dôvodu obmedzenia servera. Môžete to skúsiť znova",
    "download": "Stiahnuť",
    "downloadError3": "Sťahovanie zlyhalo z dô


),
        defined!("__FLT_HAS_DENORM__", "1"),
        defined!("__FLT_HAS_INFINITY__", "1"),
        defined!("__FLT_HAS_QUIET_NAN__", "1"),
        defined!("__FLT_MANT_DIG__", "24"),
        defined!("__FLT_MAX_10_EXP__", "38"),
        defined!("__FLT_MAX_EXP__", "128"),
        defined!("__FLT_MAX__", "3.40282347e+38F"),
        defined!("__FLT_MIN_10_EXP__", "(-37)"),
        defined!("__FLT_MIN_EXP__", "(-125)"),
        defined!("__FLT_MIN__", "1.17549435e-38F"),
        defined!("__FLT_RADIX__", "2"),
        defined!("__FXSR__", "1"),
        defined!("__GCC_ASM_FLAG_OUTPUTS__", "1"),
        defined!("__GCC_ATOMIC_BOOL_LOCK_FREE", "2"),
        defined!("__GCC_ATOMIC_CHAR16_T_LOCK_FREE", "2"),
        defined!("__GCC_ATOMIC_CHAR32_T_LOCK_FREE", "2"),
        defined!("__GCC_ATOMIC_CHAR_LOCK_FREE", "2"),
        defined!("__GCC_ATOMIC_INT_LOCK_FREE", "2"),
        defined!("__GCC_ATOMIC_LLONG_LOCK_FREE", "2"),
        defined!("__GCC_ATOMIC_LONG_LOCK_FREE", "2"),
        defined!("__GCC_ATOMIC_POINTER_LOCK_FREE", "2"),
        defined!("__GCC_ATOMIC_SHORT_LOCK_FREE", "2"),
        defined!("__GCC_ATOMIC_TEST_AND_SET_TRUEVAL", "1"),
        defined!("__GCC_ATOMIC_WCHAR_T_LOCK_FREE", "2"),
        defined!("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_1", "1"),
        defined!("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_2", "1"),
        defined!("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4", "1"),
        defined!("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8", "1"),
        defined!("__GNUC_MINOR__", "2"),
        defined!("__GNUC_PATCHLEVEL__", "1"),
        defined!("__GNUC_STDC_INLINE__", "1"),
        defined!("__GNUC__", "4"),
        defined!("__GXX_ABI_VERSION", "1002"),
        defined!("__INT16_C_SUFFIX__", ""),
        defined!("__INT16_FMTd__", "\"hd\""),
        defined!("__INT16_FMTi__", "\"hi\""),
        defined!("__INT16_MAX__", "32767"),
        defined!("__INT16_TYPE__", "short"),
        defined!("__INT32_C_SUFFIX__", ""),
        defined!("__INT32_FMTd__", "\"d\""),
        defined!("__INT32_FMTi__", "\"i\""),
        defined!("__INT32_MAX__", "2147483647"),
        defined!("__INT32_TYPE__", "int"),
        defined!("__INT64_C_SUFFIX__", "L"),
        defined!("__INT64_FMTd__", "\"ld\""),
        defined!("__INT64_FMTi__", "\"li\""),
        defined!("__INT64_MAX__", "9223372036854775807L"),
        defined!("__INT64_TYPE__", "long int"),
        defined!("__INT8_C_SUFFIX__", ""),
        defined!("__INT8_FMTd__", "\"hhd\""),
        defined!("__INT8_FMTi__", "\"hhi\""),


者：《新山大》

   《新山大》

   小助教的意见党委置之不理。党组织已三年未找我谈话

   贺永功：党委(此处一字辨认不出)日对我们小助教的意见就不当会事。如评级评薪的付作用很大，过去工作热情很高，评后就不高了。当时我向党委提出意见，但轩之不理。

   外文系党组织力量虽薄弱，但起的影响很大。自己想脱离落后圈子，又得不到支持，外文系党组织已三年没找我谈话。我要求听党课，答覆说不需要，考虑考虑，当头一棒。后来荣幸被批准听。

   总支书记来系后，对我始终不过问，在科学研究方面也不给鼓励。在生活上也如此，最近我两个孩子有病，预借工资二十元，这月发薪时都扣歪点子，当时只剩下九分钱，没钱给孩子治病。我是感不到党的温暖的，党团员有病有困难。这个人向那个人问，而群众就没有人过问。

   在教育界五年为什么不算工龄?人事科长谈话很难说服人

   林文蔚：前两个月我曾给杨付校长写了一封信，反映我爱人工资问题，过了一个月才答覆转到人事科，人事科长的谈话很难说服人。在教育界五年为什么不算工龄?为什么有的就算?我的工资被评为助教最低的一级12级，我在教育界也五年多。我们有意见反映情况，就扣个个人主义的帽子，一棒子打的人抬不起头来。

   旧画报包书，变成了“崇拜希特勒”。工资改革冤声载道

   李蕴：肃反在山大搞的热火朝天，结果搞错了，数学系有的教授走了，马列室教授也离开了。我在肃反写了七次检讨材料。外文系陈家咏是党棍子，东打西打，对人非常冷酷，全系在斗我，最后党派人宣布无政治问题，而大谈其我的缺点。四年来党委从未找我谈过话，斗完就完了。我希望这些党员应开


*args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

class WMTSTileSource(MercatorTileSource):
    ''' Behaves much like ``TMSTileSource`` but has its tile-origin in the
    top-left.

    This is the most common used tile source for web mapping applications.
    Such companies as Google, MapQuest, Stamen, Esri, and OpenStreetMap provide
    service which use the WMTS specification e.g. ``http://c.tile.openstreetmap.org/{Z}/{X}/{Y}.png``.

    '''

    # explicit __init__ to support Init signatures
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

class QUADKEYTileSource(MercatorTileSource):
    ''' Has the same tile origin as the ``WMTSTileSource`` but requests tiles using
    a `quadkey` argument instead of X, Y, Z e.g.
    ``http://your.quadkey.tile.host/{Q}.png``

    '''

    # explicit __init__ to support Init signatures
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

class BBoxTileSource(MercatorTileSource):
    ''' Has the same default tile origin as the ``WMTSTileSource`` but requested
    tiles use a ``{XMIN}``, ``{YMIN}``, ``{XMAX}``, ``{YMAX}`` e.g.
    ``http://your.custom.tile.service?bbox={XMIN},{YMIN},{XMAX},{YMAX}``.

    '''

    # explicit __init__ to support Init signatures
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

    use_latlon = Bool(default=False, help="""
    Flag which indicates option to output ``{XMIN}``, ``{YMIN}``, ``{XMAX}``, ``{YMAX}`` in meters or latitude and longitude.
    """)

#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------

#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------


ector3 image(1320.3, 1740, 1);
  CHECK(assert_equal((Vector)intrinsic,(Vector)K.calibrate(image)));
}

/* ************************************************************************* */
Point2 uncalibrate_(const Cal3_S2& k, const Point2& pt) { return k.uncalibrate(pt); }
TEST( Cal3_S2, Duncalibrate1)
{
  Matrix computed; K.uncalibrate(p, computed, boost::none);
  Matrix numerical = numericalDerivative21(uncalibrate_, K, p);
  CHECK(assert_equal(numerical,computed,1e-8));
}

/* ************************************************************************* */
TEST( Cal3_S2, Duncalibrate2)
{
  Matrix computed; K.uncalibrate(p, boost::none, computed);
  Matrix numerical = numericalDerivative22(uncalibrate_, K, p);
  CHECK(assert_equal(numerical,computed,1e-9));
}

/* ************************************************************************* */
TEST( Cal3_S2, assert_equal)
{
  CHECK(assert_equal(K,K,1e-9));

  Cal3_S2 K1(500, 500, 0.1, 640 / 2, 480 / 2);
  CHECK(assert_equal(K,K1,1e-9));
}

/* ************************************************************************* */
TEST( Cal3_S2, retract)
{
  Cal3_S2 expected(500+1, 500+2, 0.1+3, 640 / 2+4, 480 / 2+5);
  Vector d(5);
  d << 1,2,3,4,5;
  Cal3_S2 actual = K.retract(d);
  CHECK(assert_equal(expected,actual,1e-7));
  CHECK(assert_equal(d,K.localCoordinates(actual),1e-7));
}

/* ************************************************************************* */
TEST(Cal3_S2, between) {
  Cal3_S2 k1(5, 5, 5, 5, 5), k2(5, 6, 7, 8, 9);
  Matrix H1, H2;

  EXPECT(assert_equal(Cal3_S2(0,1,2,3,4), k1.between(k2, H1, H2)));
  EXPECT(assert_equal(-eye(5), H1));
  EXPECT(assert_equal(eye(5), H2));

}

/* ************************************************************************* */
int main() {
  TestResult tr;
  return TestRegistry::runAllTests(tr);
}
/* ************************************************************************* */

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

 * GTSAM Copyright 2010, Georgia Tech Research Corporation,
 * Atlanta, Georgia 30332-0415
 * All Rights Reserved
 * Authors: Frank Dellaert, et al. (see THANKS for the full author list)

 * See LICENSE for the license information

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

/**
 * @file    testStereoCamera.cpp
 * @brief   Unit test for StereoCamera
 * single camera
 * @author  Chris Beall
 */

#include <CppUnitLite/TestHarness.h>
#include <gtsam/base/Testable.h>
#include <gtsam/base/numericalDerivative.h>
#include <gtsam/geometry/StereoCamera.h>

using namespace std;
using namespace gtsam;

GTSAM_CONCEPT_TESTABLE_INST(StereoCamera)
GTSAM_CONCEPT_MANIFOLD_INST(StereoCamera)

/* ************************************************************************* */
TEST( StereoCamera, operators)
{
  StereoPoint2 a(1, 2, 3), b(4, 5, 6), c(5, 7, 9), d(3, 3, 3);
  CHECK(assert_equal(c,a+b));
  CHECK(assert_equal(d,b-a));
}

/* ************************************************************************* */
TEST( StereoCamera, project)
{
  // create a Stereo camera at the origin with focal length 1500, baseline 0.5m
  // and principal point 320, 240 (for a hypothetical 640x480 sensor)
  Cal3_S2Stereo::shared_ptr


        sin_theta, cos_theta = dr.sincos(30.0 / 180.0 * dr.pi)
        ray = mi.Ray3f(mi.Point3f(0, 0, 1), -mi.Vector3f(sin_theta, 0, cos_theta), 0.0, mi.Color0f())

        # Case 1: Rotate based on the internal `theta` angle parameter.
        scene_theta = mi.load_dict({
            'type': 'rectangle',
            'bsdf': {
                'type': 'polarizer',
                'theta': {'type': 'spectrum', 'value': angle}
            }
        })

        si_theta = scene_theta.ray_intersect(ray)
        bsdf_theta = si_theta.bsdf(ray)
        bs_theta, M_theta = bsdf_theta.sample(ctx, si_theta, 0.0, [0.0, 0.0])
        M_theta = si_theta.to_world_mueller(M_theta, -si_theta.wi, bs_theta.wo)
        wo_theta = si_theta.to_world(bs_theta.wo)

        # Case 2: Rotate the actual geometry of the polarizer.
        scene_rot = mi.load_dict({
            'type': 'rectangle',
            'bsdf': {
                'type': 'polarizer',
                'theta': {'type': 'spectrum', 'value': 0.0}
            },
            'to_world': mi.ScalarTransform4f().rotate(axis=(0, 0, 1), angle=-angle)
        })

        si_rot = scene_rot.ray_intersect(ray)
        bsdf_rot = si_rot.bsdf(ray)
        bs_rot, M_rot = bsdf_rot.sample(ctx, si_rot, 0.0, [0.0, 0.0])
        M_rot = si_rot.to_world_mueller(M_rot, -si_rot.wi, bs_rot.wo)
        wo_rot = si_rot.to_world(bs_rot.wo)

        stokes_theta = M_theta @ stokes_in
        stokes_rot = M_rot @ stokes_in

        assert dr.allclose(stokes_theta, stokes_rot, atol=1e-3)


t : number;
  minimumPosition : number | undefined;
  maximumPosition : number | undefined;
}

export default class SegmentBufferGraph {
  /** Link buffered Representation to their corresponding color. */
  private readonly _colorMap : WeakMap<Representation, string>;

  /** Current amount of colors chosen to represent the various Representation. */
  private _currNbColors : number;

  /** Canvas that will contain the buffer graph itself. */
  private readonly _canvasElt : HTMLCanvasElement;

  private readonly _canvasCtxt : CanvasRenderingContext2D | null;

  constructor(canvasElt : HTMLCanvasElement) {
    this._colorMap = new WeakMap();
    this._currNbColors = 0;
    this._canvasElt = canvasElt;
    this._canvasCtxt = this._canvasElt.getContext("2d");
    this.clear();
  }

  public clear() {
    if (this._canvasCtxt !== null) {
      this._canvasCtxt.clearRect(0, 0, this._canvasElt.width, this._canvasElt.height);
    }
  }

  public update(data : ISegmentBufferGrapUpdateData) : void {
    if (this._canvasCtxt === null) {
      return;
    }
    const {
      inventory,
      currentTime,
      width,
      height,
    } = data;
    this._canvasElt.style.width = `${width}px`;
    this._canvasElt.style.height = `${height}px`;
    this._canvasElt.width = width;
    this._canvasElt.height = height;
    this.clear();
    let minimumPoint : number;
    if (data.minimumPosition !== undefined) {
      if (inventory.length > 0) {
        minimumPoint = Math.min(data.minimumPosition, inventory[0].start);
      } else {
        minimumPoint = data.minimumPosition;
      }
    } else {
      minimumPoint = inventory[0]?.start ?? 0;
    }
    let maximumPoint : number;
    if (data.maximumPosition !== undefined) {
      if (inventory.length > 0) {
        maximumPoint = Math.max(data.maximumPosition,
                                inventory[inventory.length - 1].end);
      } else {
        maximumPoint = data.maximumPosition;
      }
    } else {
      maximumPoint = inventory[inventory.length - 1]?.end ??
        1000;
    }
    minimumPoint = Math.min(currentTime, minimumPoint);
    maximumPoint = Math.max(currentTime, maximumPoint);

    let minimumPosition;
    let maximumPosition;
    if (maximumPoint - minimumPoint > BUFFER_WIDTH_IN_SECONDS) {
      if (currentTime === undefined) {
        minimumPosition = minimumPoint;
        maximumPosition = maximumPoint;
      } else if (maximumPoint - currentTime < BUFFER_WIDTH_IN_SECONDS / 2) {
        maximumPosition = maximumPoint;
        minimumPosition = maximumPoint - BUFFER_WIDTH_IN_SECONDS;
      } else if (currentTime - minimumPoint < BUFFER_WIDTH_IN_SECONDS / 2) {
        minimumPosition = minimumPoint;
        maximumPosition = minimumPoint + BUFFER_WIDTH_IN_SECONDS;
      } else {
        minimumPosition = currentTime - BUFFER_WIDTH_IN_SECONDS / 2;
        maximumPosition = currentTime + BUFFER_WIDTH_IN_SECONDS / 2;
      }
    } else {
      minimumPosition = minimumPoint;
      maximumPosition = maximumPoint;
    }
    if (minimumPosition >= maximumPosition) {
      this.clear();
      return;
    }

    const currentRangesScaled = scaleSegments(


l c = Completer<T?>();
    final progress = getValue<T>(format, (value) {
      c.complete(value);
    }, onError: (e) {
      c.completeError(e);
    });
    if (progress == null) {
      c.complete(null);
    }
    return c.future;
  }

  Future<Uint8List?>? readFile(FileFormat format) {
    final c = Completer<Uint8List?>();
    final progress = getFile(format, (file) async {
      try {
        final all = await file.readAll();
        c.complete(all);
      } catch (e) {
        c.completeError(e);
      }
    }, onError: (e) {
      c.completeError(e);
    });
    if (progress == null) {
      c.complete(null);
    }
    return c.future;
  }
}

/// Builds widget containing information for data reader.
Future<Widget> _buildWidgetForReader(
  BuildContext context,
  ReaderInfo reader,
  int index,
) async {
  final itemFormats = reader.reader.getFormats([
    ...Formats.standardFormats,
    formatCustom,
  ]);

  // Request all data before awaiting
  final futures =
      itemFormats.map((e) => _widgetForFormat(context, e, reader.reader));

  // Now await all futures
  final widgets = await Future.wait(futures);
  final children = widgets
      .where((element) => element != null)
      .cast<_RepresentationWidget>()
      .toList(growable: true);

  // remove duplicate widgets
  final formats = <DataFormat>{};
  children.retainWhere((element) => formats.add(element.format));

  // build list of native formats with virtual/synthetized flags
  final nativeFormats = reader._formats.map((e) {
    final attributes = [
      if (e.virtual) 'virtual',
      if (e.synthetized) 'synthetized',
    ].join(', ');
    return attributes.isNotEmpty ? '${e.format} ($attributes)' : e.format;
  }).toList(growable: false);

  return _ReaderWidget(
    itemName: 'Data item $index',
    suggestedFileName: reader.suggestedName ?? 'null',
    representations: children,
    nativeFormats: nativeFormats,
  );
}

class _ReaderWidget extends StatelessWidget {
  const _ReaderWidget({
    required this.itemName,
    required this.suggestedFileName,
    required this.representations,
    required this.nativeFormats,
  });

  final String itemName;
  final String suggestedFileName;
  final List<Widget> representations;
  final List<String>? nativeFormats;

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          _HeaderWidget(
              itemName: itemName, suggestedFileName: suggestedFileName),
          ...representations.intersperse(const SizedBox(height: 2)),
          if (nativeFormats != null) ...[
            const SizedBox(height: 2),
            _FooterWidget(nativeFormats: nativeFormats!),
          ]
        ],
      ),
    );
  }
}

class _HeaderWidget extends StatelessWidget {
  const _HeaderWidget({
    required this.itemName,
    required this.suggestedFileName,
  });

  final String itemName;
  final String suggestedFileName;

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.blueGrey.shade100,
      padding: const EdgeInsets.all(10),
      child: Row(
        children: [
          Text(
            itemName,
            style: const TextStyle(fontWeight: FontWeight.bold),
          ),


t_address += size;
        }

        ret
    }

    /// Test iterative subnet generation
    #[test]
    fn test_generate_iterative_subnet() {
        // Complex subnet example
        let net: IpNetwork = "2602:FBAD::/40".parse().unwrap();
        let ret = generate_iterative_client_subnet(net, 0, 64);
        assert_eq!("2602:FBAD::/64".parse::<IpNetwork>().unwrap(), ret.unwrap());

        let net: IpNetwork = "2602:FBAD::/40".parse().unwrap();
        let ret = generate_iterative_client_subnet(net, 1, 64);
        assert_eq!(
            "2602:FBAD:0:1::/64".parse::<IpNetwork>().unwrap(),
            ret.unwrap()
        );

        let net: IpNetwork = "2602:FBAD::/40".parse().unwrap();
        let ret = generate_iterative_client_subnet(net, 50, 64);
        assert_eq!(
            "2602:FBAD:0:32::/64".parse::<IpNetwork>().unwrap(),
            ret.unwrap()
        );

        let net: IpNetwork = "2602:FBAD::/40".parse().unwrap();
        let ret = generate_iterative_client_subnet(net, 2_u64.pow(24), 64);
        assert!(ret.is_err());

        let net: IpNetwork = "2602:FBAD::/40".parse().unwrap();
        let ret = generate_iterative_client_subnet(net, 0, 30);
        assert!(ret.is_err());

        // Simple subnet example
        let net: IpNetwork = "fd00::1337/120".parse().unwrap();
        let ret = generate_iterative_client_subnet(net, 0, 124);
        assert_eq!("fd00::1300/124".parse::<IpNetwork>().unwrap(), ret.unwrap());

        let net: IpNetwork = "fd00::1337/120".parse().unwrap();
        let ret = generate_iterative_client_subnet(net, 2, 124);
        assert_eq!("fd00::1320/124".parse::<IpNetwork>().unwrap(), ret.unwrap());

        let net: IpNetwork = "fd00::1337/120".parse().unwrap();
        let ret = generate_iterative_client_subnet(net, 15, 124);
        assert_eq!("fd00::13f0/124".parse::<IpNetwork>().unwrap(), ret.unwrap());

        let net: IpNetwork = "fd00::1337/120".parse().unwrap();
        let ret = generate_iterative_client_subnet(net, 16, 124);
        assert!(ret.is_err());
    }

    #[test]
    fn test_reclaiming_ips() {
        let str = "";
        let str2 = "2";
        let str3 = "1,2,5,10,92";
        let vec = str.rsplit_once(',');
        println!("{:?}", vec);

        let vec = str2.rsplit_once(',');
        println!("{:?}", vec);

        let vec = str3.rsplit_once(',');
        println!("{:?}", vec);
    }

    #[test]
    fn test_subnet_to_index() {
        let exit_sub: IpNetwork = "fd00::1000/120".parse().unwrap();
        let sub: IpNetwork = "fd00::1000/124".parse().unwrap();

        let exit_sub_mig: IPAddress = IPAddress::parse(exit_sub.to_string())
            .expect("Paniced while migrating IpNetwork -> IPAddress");
        let sub_mig: IPAddress = IPAddress::parse(sub.to_string())
            .expect("Paniced while parsing IpNetwork -> IPAddress");

        let net = sub_mig.network();
        println!("net: {:?}", net);
        let size = net.size();
        println!("size: {:?}", size);

        let test = (sub_mig.host_address - exit_sub_mig.host_address) /


      }
   }

   if (closed) {
      for (Int d = 0; d <= dim; ++d) {
         for (const auto n : HD.nodes_of_rank(d+1)) {
            const Set<Int> face = HD.face(n);

            if (d==0) {    // face is a vertex
               const Int v = face.front();
               if (v >= verts)
                  verts = v+1;
            }

            if (d==dim) {  // each facet is an option
               the_facets.insert(face);
               raw_options[d].insert(face, Set<Int>());

            } else {
               Set<Int> V;
               accumulate_in(link_in_HD(HD, n), operations::add(), V);

               if (V.size()+face.size()==dim+2)   // face is raw option
                  raw_options[d].insert(face,V);
            }
         }
      }
   }
}

Int BistellarComplex::find_move(const Int dim_min, const Int dim_max)
{
   for (Int d = dim_min; d <= dim_max; ++d) {
      const RandomPermutation< Array<option> > P(raw_options[d].options(), random_source);

      for (auto opt = P.begin(); !opt.at_end(); ++opt)
         if ((allow_rev_move || incl(opt->first,rev_move) != 0) &&
             (d == dim || the_facets.findSupersets(opt->second).at_end())) {
            next_move = *opt;
            return opt->first.size()-1;
         }
   }

   throw std::runtime_error("BistellarComplex: No move found.");
}

bool BistellarComplex::is_option(const Set<Int>& f, Set<Int>& V) const
{
   if (!closed && f.size()==1 && f.front()==apex)  // apex is not an option
      return false;

   for (FacetList::superset_iterator star = the_facets.findSupersets(f);
        !star.at_end(); ++star)
      V += *star;
   V -= f;

   return V.size()+f.size()==dim+2;
}

void BistellarComplex::execute_move()
{
   const Set<Int> face = next_move.first;
   const Int face_dim = face.size()-1;
   if (face_dim==dim)  // allocate an index for the new vertex
      next_move.second = scalar2set(verts++);
   const Set<Int> co_face = next_move.second;
   if (!allow_rev_move)  rev_move = co_face;

   if (verbose)
      cout << "BistellarComplex: executing move of dim "
           << face.size()-1 << ": (" << face << "," << co_face << ")\n";

   // update the_flip_vector
   if (dim%2==1 || face_dim!=dim/2) {
      if (face_dim < (dim+1)/2)
         --the_flip_vector[face_dim];
      else
         ++the_flip_vector[dim-face_dim];
   }

   // remove star(face) from raw_options and the_facets
   std::list<Set<Int>> star;
   the_facets.eraseSupersets(face, std::back_inserter(star));

   Lattice<BasicDecoration> star_HD = hasse_diagram_from_facets(Array<Set<Int>>(star));
   for (Int d = 0; d <= dim; ++d)
      for (const auto n : star_HD.nodes_of_rank(d+1))
         raw_options[d].remove(star_HD.face(n));

   // add co_face * boundary(face)
   std::list<Set<Int>> new_facets;
   for (auto w=entire(face); !w.at_end(); ++w) {
      Set<Int> f = face;
      f -= *w;
      f += co_face;

      the_facets.insert(f);
      new_facets.push_back(f);
   }

   // find new raw_options
   Lattice<BasicDecoration> local_HD = hasse_diagram_from_facets(Array<Set<Int>>(new_facets));


   # Set up data
        loader = LoaderInterface(rag_config, embedding_service)
        query_interface = QueryInterface(rag_config, embedding_service)

        doc_data = DocumentData(content="Document with special chars: @#$%^&*()")
        await loader.load_document(doc_data, generate_embedding=True)

        # Query with special characters
        results = await query_interface.query("@#$%", top_k=5, similarity_threshold=-1.0)

        assert len(results) == 1
        assert "special chars" in results[0]["content"]

    async def test_query_unicode_characters(self, rag_config, embedding_service):
        """Test querying with unicode characters."""
        # Set up data
        loader = LoaderInterface(rag_config, embedding_service)
        query_interface = QueryInterface(rag_config, embedding_service)

        doc_data = DocumentData(content="Document with unicode: 你好世界 🌍")
        await loader.load_document(doc_data, generate_embedding=True)

        # Query with unicode
        results = await query_interface.query("你好", top_k=5)

        assert len(results) == 1
        assert "你好世界" in results[0]["content"]


_len|Per token latency eager (ms)|Per token latency SDPA (ms)|Speedup (%)|Mem eager (MB)|Mem BT (MB)|Mem saved (%)|
|----------|-------|----------------------------|---------------------------|-----------|--------------|-----------|-------------|
|1         |128    |5.736                       |4.987                      |15.022     |282.661       |282.924    |-0.093       |
|1         |256    |5.689                       |4.945                      |15.055     |298.686       |298.948    |-0.088       |
|2         |128    |6.154                       |4.982                      |23.521     |314.523       |314.785    |-0.083       |
|2         |256    |6.201                       |4.949                      |25.303     |347.546       |347.033    |0.148        |
|4         |128    |6.049                       |4.987                      |21.305     |378.895       |379.301    |-0.107       |
|4         |256    |6.285                       |5.364                      |17.166     |443.209       |444.382    |-0.264       |

## Resources

A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with BERT. If you're interested in submitting a resource to be included here, please feel free to open a Pull Request and we'll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource.

<PipelineTag pipeline="text-classification"/>

- A blog post on [BERT Text Classification in a different language](https://www.philschmid.de/bert-text-classification-in-a-different-language).
- A notebook for [Finetuning BERT (and friends) for multi-label text classification](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/BERT/Fine_tuning_BERT_(and_friends)_for_multi_label_text_classification.ipynb).
- A notebook on how to [Finetune BERT for multi-label classification using PyTorch](https://colab.research.google.com/github/abhimishra91/transformers-tutorials/blob/master/transformers_multi_label_classification.ipynb). 🌎
- A notebook on how to [warm-start an EncoderDecoder model with BERT for summarization](https://colab.research.google.com/github/patrickvonplaten/notebooks/blob/master/BERT2BERT_for_CNN_Dailymail.ipynb).
- [`BertForSequenceClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/pytorch/text-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification.ipynb).
- [`TFBertForSequenceClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/tensorflow/text-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification-tf.ipynb).
- [`FlaxBertForSequenceClassification`] is supported by this [example script](https://github.com/huggingface/transformers/tree/main/examples/flax/text-classification) and [notebook](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/text_classification_flax.ipynb).
- [Text classification task guide](../tasks/sequence_classification)

<PipelineTag pipeline="token-classification"/>

- A blog post on how to use [Hugging Face Transformers with Keras: Fine-tune a


s;
	if (len > length)
		return length;
	*eof = 1;
	return len;
}

/* Device FIFO addresses and default DMA modes - 2nd bank */
static const struct dma_dev dma_dev_table_bank2[DMA_NUM_DEV_BANK2] = {
	{ AU1100_SD0_PHYS_ADDR + 0x00, DMA_DS | DMA_DW8 },		/* coherent */
	{ AU1100_SD0_PHYS_ADDR + 0x04, DMA_DS | DMA_DW8 | DMA_DR },	/* coherent */
	{ AU1100_SD1_PHYS_ADDR + 0x00, DMA_DS | DMA_DW8 },		/* coherent */
	{ AU1100_SD1_PHYS_ADDR + 0x04, DMA_DS | DMA_DW8 | DMA_DR }	/* coherent */
};

void dump_au1000_dma_channel(unsigned int dmanr)
{
	struct dma_chan *chan;

	if (dmanr >= NUM_AU1000_DMA_CHANNELS)
		return;
	chan = &au1000_dma_table[dmanr];

	printk(KERN_INFO "Au1000 DMA%d Register Dump:\n", dmanr);
	printk(KERN_INFO "  mode = 0x%08x\n",
	       au_readl(chan->io + DMA_MODE_SET));
	printk(KERN_INFO "  addr = 0x%08x\n",
	       au_readl(chan->io + DMA_PERIPHERAL_ADDR));
	printk(KERN_INFO "  start0 = 0x%08x\n",
	       au_readl(chan->io + DMA_BUFFER0_START));
	printk(KERN_INFO "  start1 = 0x%08x\n",
	       au_readl(chan->io + DMA_BUFFER1_START));
	printk(KERN_INFO "  count0 = 0x%08x\n",
	       au_readl(chan->io + DMA_BUFFER0_COUNT));
	printk(KERN_INFO "  count1 = 0x%08x\n",
	       au_readl(chan->io + DMA_BUFFER1_COUNT));
}

/*
 * Finds a free channel, and binds the requested device to it.
 * Returns the allocated channel number, or negative on error.
 * Requests the DMA done IRQ if irqhandler != NULL.
 */
int request_au1000_dma(int dev_id, const char *dev_str,
		       irq_handler_t irqhandler,
		       unsigned long irqflags,
		       void *irq_dev_id)
{
	struct dma_chan *chan;
	const struct dma_dev *dev;
	int i, ret;

	if (alchemy_get_cputype() == ALCHEMY_CPU_AU1100) {
		if (dev_id < 0 || dev_id >= (DMA_NUM_DEV + DMA_NUM_DEV_BANK2))
			return -EINVAL;
	} else {
		if (dev_id < 0 || dev_id >= DMA_NUM_DEV)
			return -EINVAL;
	}

	for (i = 0; i < NUM_AU1000_DMA_CHANNELS; i++)
		if (au1000_dma_table[i].dev_id < 0)
			break;

	if (i == NUM_AU1000_DMA_CHANNELS)
		return -ENODEV;

	chan = &au1000_dma_table[i];

	if (dev_id >= DMA_NUM_DEV) {
		dev_id -= DMA_NUM_DEV;
		dev = &dma_dev_table_bank2[dev_id];
	} else
		dev = &dma_dev_table[dev_id];

	if (irqhandler) {
		chan->irq_dev = irq_dev_id;
		ret = request_irq(chan->irq, irqhandler, irqflags, dev_str,
				  chan->irq_dev);
		if (ret) {
			chan->irq_dev = NULL;
			return ret;
		}
	} else {
		chan->irq_dev = NULL;
	}

	/* fill it in */
	chan->io = KSEG1ADDR(AU1000_DMA_PHYS_ADDR) + i * DMA_CHANNEL_LEN;
	chan->dev_id = dev_id;
	chan->dev_str = dev_str;
	chan->fifo_addr = dev->fifo_addr;
	chan->mode = dev->dma_mode;

	/* initialize the channel before returning */
	init_dma(i);

	return i;
}
EXPORT_SYMBOL(request_au1000_dma);

void free_au1000_dma(unsigned int dmanr)
{
	struct dma_chan *chan = get_dma_chan(dmanr);

	if (!chan) {
		printk(KERN_ERR "Error trying to free DMA%d\n", dmanr);
		return;
	}

	disable_dma(dmanr);
	if (chan->irq_dev)
		free_irq(chan->irq, chan->irq_dev);

	chan->irq_dev = NULL;
	chan->dev_id = -1;
}
EXPORT_SYMBOL(free_au1000_dma);

static int __init au1000_dma_init(void)
{
	int base, i;

	switch (alchemy_get_cputype()) {
	case ALCHEMY_CPU_AU1000:
		base = AU1000_DMA_INT_BASE;
		break;
	case ALCHEMY_CPU_AU1500:
		base = AU1500_DMA_INT_BASE;
		break;
	case ALCHEMY_CPU_AU1100:
		base = AU1100_DMA_INT_BASE;
		break;
	default:
		goto out;
	}

	for (i = 0; i < NUM_AU1000_DMA_CHANNELS; i++)
		au1000_dma_table[i].irq = base + i;

	printk(KERN_INFO "Alchemy DMA initialized\n");

out:
	return 0;
}
arch_initcall(au1000_dma_init);


1},8,["action"])])),_:1})])),_:1},8,["model"])]),c("div",B,[u(i,{bg:"",text:"",style:{width:"40%",padding:"20px 0","background-color":"#F4F4F5",color:"#20295A","border-radius":"8px"},onClick:t[6]||(t[6]=e=>Y.value=!1)},{default:p((()=>t[13]||(t[13]=[m("取消 ")]))),_:1}),u(i,{bg:"",text:"",style:{width:"40%",padding:"20px 0","background-color":"#3B82F6",color:"#FFF","border-radius":"8px"},type:"primary",onClick:K},{default:p((()=>t[14]||(t[14]=[m(" 确定 ")]))),_:1})])])),_:1},8,["modelValue"])])}}});"function"==typeof _&&_(Y);const q=h(Y,[["__scopeId","data-v-3f0b9977"]]);export{q as default};

/**
 * 由 Fantastic-admin 提供技术支持
 * Powered by Fantastic-admin
 * Gitee  https://gitee.com/hooray/fantastic-admin
 * Github https://github.com/hooray/fantastic-admin
 */

import{_ as e}from"../index/index.b30cdbc6.js";import{A as a}from"./sales.c24a6f67.js";import{d as l,r,C as t,U as o,e as i,ag as n,o as s,f as d,g as u,h as p,q as c,i as m,X as f,j as g,m as v,t as h,a1 as _}from"../main-527fe521.js";const b=["src"],w=l({__name:"records",setup(l){const _=r(),w=r(0),y=r(!1),z=t({orderPrice:null,orderId:null,page:1,size:10}),P=r([]);async function x(){try{y.value=!0;const e=await a.queryRecords(z);y.value=!1;const{rows:l,count:r}=e.data;w.value=r,P.value=l}catch(e){y.value=!1}}return o((()=>{x()})),(a,l)=>{const r=i("el-input"),t=i("el-form-item"),o=i("el-button"),I=i("el-form"),U=e,j=i("el-alert"),C=i("el-table-column"),V=i("el-tag"),A=i("el-table"),k=i("el-pagination"),D=i("el-row"),q=n("loading");return s(),d("div",null,[u(U,null,{default:p((()=>[u(I,{ref_key:"formRef",ref:_,inline:!0,model:z},{default:p((()=>[u(t,{label:"工单状态",prop:"orderPrice"},{default:p((()=>[u(r,{modelValue:z.orderPrice,"onUpdate:modelValue":l[0]||(l[0]=e=>z.orderPrice=e),placeholder:"订单金额"},null,8,["modelValue"])])),_:1}),u(t,{label:"订单ID",prop:"orderId"},{default:p((()=>[u(r,{modelValue:z.orderId,"onUpdate:modelValue":l[1]||(l[1]=e=>z.orderId=e),placeholder:"订单ID、模糊搜索"},null,8,["modelValue"])])),_:1}),u(t,null,{default:p((()=>[u(o,{type:"primary",onClick:x},{default:p((()=>l[5]||(l[5]=[c(" 查询 ")]))),_:1}),u(o,{onClick:l[2]||(l[2]=e=>{retur


))); return zonePtr->m_nodeToElemMap.get(); } ___465 ___4016::dataNodeToElemMapGetNumElems(___2742 nodeToElemMap, ___2718 ___2709) const { REQUIRE(VALID_REF(nodeToElemMap)); REQUIRE(0 < ___2709 && ___2709 <= nodeToElemMap->m_nodeCount); return nodeToElemMap->m_elemIndex[___2709] - nodeToElemMap->m_elemIndex[___2709 - 1]; } ___465 ___4016::dataNodeToElemMapGetElem(___2742 nodeToElemMap, ___2718 ___2709, ___465 elemOffset) const { REQUIRE(VALID_REF(nodeToElemMap)); REQUIRE(0 < ___2709 && ___2709 <= nodeToElemMap->m_nodeCount); REQUIRE(0 < elemOffset && elemOffset <= nodeToElemMap->m_elemIndex[___2709] - nodeToElemMap->m_elemIndex[___2709 - 1]); return nodeToElemMap->m_elem[nodeToElemMap->m_elemIndex[___2709 - 1] + elemOffset - 1] + 1; } FaceNeighborMode_e ___4016::___836(___4636 ___4658) const { REQUIRE(m_tecioData.validZoneNum(___4658)); Zone_s const* zonePtr = m_tecioData.zonePtr(___4658); return zonePtr->___2458; } void ___4016::___837( ___1292 ___1274, ___2227 ___1144, int32_t face, int32_t ___2692, ___2227* ___2691, ___4636* ___2695) const { Zone_s const* zonePtr = reinterpret_cast<Zone_s const*>(___1274); REQUIRE(VALID_REF(zonePtr)); Zone_s::___458 ___457; ___457.first = static_cast<int32_t>(___1144); ___457.second = face; Zone_s::___1276::const_iterator iter = zonePtr->___2457.find(___457); ___478(iter != zonePtr->___2457.end()); ___478(0 < ___2692 && ___2692 <= (___2227)iter->second.___2678.size()); *___2691 = iter->second.___2678[___2692 - 1].second; *___2695 = iter->second.___2678[___2692 - 1].first; } ___372 ___4016::___835( ___1292 ___1274, ___2227 ___1144, int32_t face, ___3501 ___4) const { ___4278(___4); Zone_s const* zonePtr = reinterpret_cast<Zone_s const*>(___1274); REQUIRE(VALID_REF(zonePtr)); Zone_s::___458 ___457; ___457.first = static_cast<int32_t>(___1144); ___457.second = face; Zone_s::___1276::const_iterator iter = zonePtr->___2457.find(___457); if (iter == zonePtr->___2457.end()) return ___1305; else return iter->second.___2488; } int32_t ___4016::___838(___1292 ___1274, ___2227 ___1144, int32_t face, ___372*  ) const { Zone_s const* zonePtr = reinterpret_cast<Zone_s const*>(___1274); REQUIRE(VALID_REF(zonePtr)); Zone_s::___458 ___457; ___457.first = static_cast<int32_t>(___1144); ___457.second = face; Zone_s::___1276::const_iterator iter = zonePtr->___2457.find(___457); if (iter == zonePtr->___2457.end()) return 0; else return (int32_t)iter->second.___2678.size(); } ___1292 ___4016::___839(___4636 ___4658) const { REQUIRE(m_tecioData.validZoneNum(___4658)); Zone_s* zonePtr = m_tecioData.zonePtr(___4658); return reinterpret_cast<___1292>(zonePtr); } ___372 ___4016::set


hell, "firewalld", ServiceAction::Disable)?;
    }

    // Make sure libvirtd is running.
    crate::common::service(&ushell, "libvirtd", ServiceAction::Restart)?;

    Ok(())
}

/// Destroys any existing VM forcibly.
fn destroy_vm(ushell: &SshShell) -> Result<(), failure::Error> {
    let vagrant_path = &dir!(RESEARCH_WORKSPACE_PATH, VAGRANT_SUBDIRECTORY);

    with_shell! { ushell in vagrant_path =>
        cmd!("vagrant halt --force || [ ! -e Vagrantfile ]").use_bash(),
        cmd!("sudo virsh net-undefine vagrant-libvirt || [ ! -e Vagrantfile ]").use_bash(),
        cmd!("vagrant destroy --force || [ ! -e Vagrantfile ]").use_bash(),
    }

    Ok(())
}

/// Create the VM and install dependencies for the benchmarks/simulator. Returns root and user
/// shells to the VM.
fn init_vm<A>(
    ushell: &mut SshShell,
    cfg: &SetupConfig<'_, A>,
) -> Result<(SshShell, SshShell), failure::Error>
where
    A: std::net::ToSocketAddrs + std::fmt::Display + std::fmt::Debug + Clone,
{
    // Create the VM and add our ssh key to it.
    let vagrant_path = &dir!(RESEARCH_WORKSPACE_PATH, VAGRANT_SUBDIRECTORY);

    ushell.run(cmd!("cp Vagrantfile.bk Vagrantfile").cwd(vagrant_path))?;
    crate::common::gen_new_vagrantdomain(&ushell)?;

    gen_vagrantfile(&ushell, 20, 1)?;

    // Make sure to turn off skip_halt and lapic_adjust
    ZeroSim::skip_halt(&ushell, false)?;
    ZeroSim::lapic_adjust(&ushell, false)?;

    ushell.run(cmd!("vagrant halt").cwd(vagrant_path))?;
    ushell.run(cmd!("vagrant up").cwd(vagrant_path))?; // This creates the VM

    let ssh_location = format!(
        "{}/.ssh",
        std::env::var("HOME").context("finding location of .ssh directory")?
    );

    let key = std::fs::read_to_string(dir!(&ssh_location, "id_rsa.pub"))?;
    let key = key.trim();
    ushell.run(
        cmd!(
            "vagrant ssh -- 'echo {} >> /home/vagrant/.ssh/authorized_keys'",
            key
        )
        .cwd(vagrant_path),
    )?;
    ushell.run(cmd!("vagrant ssh -- sudo cp -r /home/vagrant/.ssh /root/").cwd(vagrant_path))?;

    // Old key will be cached for the VM, but it is likely to have changed
    let (host, _) = spurs_util::get_host_ip(&cfg.login.host);
    let _ = Command::new("ssh-keygen")
        .args(&[
            "-f",
            &dir!(&ssh_location, "known_hosts"),
            "-R",
            &format!("[{}]:{}", host, VAGRANT_PORT),
        ])
        .status()
        .unwrap();

    // Start vagrant
    let mut vrshell = start_vagrant(
        &ushell,
        &cfg.login.host,
        20,
        1,
        /* fast */ true,
        ZEROSIM_SKIP_HALT,
        ZEROSIM_LAPIC_ADJUST,
    )?;
    let mut vushell = connect_to_vagrant_as_user(&cfg.login.host)?;

    // Make sure we have an alternate way to get into the VM
    vrshell.run(cmd!("echo 0sim | passwd --stdin vagrant"))?;
    vrshell


ategory( NULL, CATEGORY_TEST );
    EXPECT_NULL( entry );
    EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
  }

  TEST( WelEntryEventIdTest, NullEntry ) {
    struct stumpless_entry *entry;

    entry = stumpless_set_wel_event_id( NULL, MSG_SIMPLE );
    EXPECT_NULL( entry );
    EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
  }

  TEST( WelEntryTypeTest, NullEntry ) {
    struct stumpless_entry *entry;

    entry = stumpless_set_wel_type( NULL, EVENTLOG_SUCCESS );
    EXPECT_NULL( entry );
    EXPECT_ERROR_ID_EQ( STUMPLESS_ARGUMENT_EMPTY );
  }

  TEST( WelEventSource, AddAndRemove ) {
    LPCSTR subkey_name = "StumplessTestSubkey";
    LPCWSTR subkey_name_w = L"StumplessTestSubkey";
    LPCSTR source_name = "StumplessTestSource";
    std::wstring source_name_w( L"StumplessTestSource" );
    DWORD category_count = 5;
    LPCSTR category_file = "%APPDATA%\\è\\category.dll";
    LPCWSTR category_file_w = L"%APPDATA%\\è\\category.dll";
    LPCSTR parameter_file = "%APPDATA%\\è\\parameter.dll";
    LPCWSTR parameter_file_w = L"%APPDATA%\\è\\parameter.dll";
    const struct stumpless_error *error;
    DWORD types_supported = EVENTLOG_ERROR_TYPE |
                              EVENTLOG_INFORMATION_TYPE |
                              EVENTLOG_WARNING_TYPE;
    LPCWSTR full_key = BASE_KEY L"\\StumplessTestSubkey\\StumplessTestSource";
    LPCWSTR subkey = BASE_KEY L"\\StumplessTestSubkey";
    LPCWSTR event_subkey = BASE_KEY L"\\StumplessTestSubkey"\
                            L"\\StumplessTestSource\\EventMessageFile";
    WCHAR lpcwstr_result[1024]{};
    LSTATUS reg_result;
    std::vector<std::wstring> *sources_vec;
    size_t source_name_count;
    DWORD dword_result;
    DWORD result_size;

    dword_result = stumpless_add_wel_event_source( subkey_name,
                                                   source_name,
                                                   category_count,
                                                   category_file,
                                                   NULL,
                                                   parameter_file,
                                                   types_supported );
    error = stumpless_get_error(  );
    if( error && error->code == ERROR_ACCESS_DENIED ) {
      SUCCEED(  ) << "not enough permissions to install, skipping test";
    } else {
      EXPECT_NO_ERROR;
      EXPECT_EQ( dword_result, ERROR_SUCCESS );
      EXPECT_TRUE( registry_key_exists( full_key ) );

      result_size = sizeof( lpcwstr_result );
      reg_result = RegGetValueW( HKEY_LOCAL_MACHINE,
                                 subkey,
                                 L"Sources",
                                 RRF_RT_REG_MULTI_SZ,
                                 NULL,
                                 lpcwstr_result,
                                 &result_size );
      EXPECT_EQ( reg_result, ERROR_SUCCESS );

      sources_vec = multi_sz_to_vector( lpcwstr_result );

      // std::count would be cleaner, but may not be available
      source_name_count = 0;
      for( std::wstring str : *sources_vec ) {
        if( str.compare( source_name_w ) == 0 ) {
          source_name_count++;
        }
      }

      EXPECT_EQ( source_name_count, 1 );
      delete sources_vec;
      ASSERT_EQ( source_name_count, 1 );

      result_size = sizeof(


/* Copyright 2016 Google Inc.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License. */

#ifndef NSYNC_PUBLIC_NSYNC_COUNTER_H_
#define NSYNC_PUBLIC_NSYNC_COUNTER_H_

#include <inttypes.h>
#include "nsync_cpp.h"
#include "nsync_mu.h"
#include "nsync_atomic.h"
#include "nsync_time.h"

NSYNC_CPP_START_

struct nsync_dll_element_s_;

/* An nsync_counter represents an unsigned integer that can count up and down,
   and wake waiters when zero.  */
typedef struct nsync_counter_s_ *nsync_counter;

/* Return a freshly allocated nsync_counter with the specified value,
   of NULL if an nsync_counter cannot be created.

   Any non-NULL returned value should be passed to nsync_counter_free() when no
   longer needed.  */
nsync_counter nsync_counter_new (uint32_t value);

/* Free resources associated with c.  Requires that c was allocated by
   nsync_counter_new(), and no concurrent or future operations are applied to
   c.  */
void nsync_counter_free (nsync_counter c);

/* Add delta to c, and return its new value.  It is a checkable runtime error
   to decrement c below 0, or to increment c (i.e., apply a delta > 0) after a
   waiter has waited.  */
uint32_t nsync_counter_add (nsync_counter c, int32_t delta);

/* Return the current value of c.  */
uint32_t nsync_counter_value (nsync_counter c);

/* Wait until c has value 0, or until abs_deadline, then return
   the value of c.  It is a checkable runtime error to increment c after
   a waiter may have been woken due to the counter reaching zero.
   If abs_deadline==nsync_time_no_deadline, the deadline
   is far in the future. */
uint32_t nsync_counter_wait (nsync_counter c, nsync_time abs_deadline);

NSYNC_COUNTER_CPP_OVERLOAD_
NSYNC_CPP_END_

#endif /*NSYNC_PUBLIC_NSYNC_COUNTER_H_*/


 себе нарезку цилиндра на множество тонких дисков. Мы можем сдвинуть эти диски, чтобы получить наклонный цилиндр. Объем отдельных дисков не изменяется, поэтому общий объем также остается постоянным:

::: column(width=240)

    x-solid(size=280 style="margin: -20px")

::: column(width=240)

    x-solid.slide-me(size=280 static style="margin: -20px")
    x-gesture(target=".slide-me" slide="60,0")

:::

---
> id: cylinder-surface

#### Площадь поверхности цилиндра

::: column.grow

Чтобы найти площадь поверхности цилиндра, нам нужно «развернуть» его в плоскую [развертку](gloss:net) . Вы можете попробовать сделать это сами, например, сняв этикетку с банки с едой.

Есть два [[круга|сферы|квадрата]] , один сверху и один снизу цилиндра. Боковая сторона на самом деле большой [[прямоугольник|квадрат|эллипс]]

* {.reveal(when="blank-0 blank-1")} Каждое из двух оснований имеют площадь _{x-equation.small(solution="π r^2" keys="+ × π sup" short-var)}_
* {.reveal(when="eqn-0")} Высота прямоугольника равна _{x-equation.small(solution="h" keys=" " short-var)}_ _{span.reveal(when="eqn-1")} , а ширина прямоугольника равна [[длине|диаметру|касательной]] окружности основания:_ _{x-equation.small.reveal(when="blank-2" solution="2 π r" keys="+ × π sup" short-var)}_

::: column(width=320)

    x-solid(size=340 style="margin: -10px;")
    x-slider(steps=100 speed=0.5)

:::

---
> id: cylinder-surface-1

Это означает, что общая площадь поверхности цилиндра с радиусом _r_ и высотой _h_ определяется как

{.text-center}`A =` _{x-equation(solution="2 π r^2 + 2 π r h" keys="+ − × ÷ π frac sup brackets" short-var)}_

---
> id: cylinder-real-life

    figure: x-img(src="images/cylinders.jpg" width=460 height=125)

Цилиндры можно найти повсюду в нашем мире - от банок содовой до туалетной бумаги или водопроводных труб. Можете ли вы вспомнить другие примеры?

_Газгольдер_ выше имел радиус 35 метров и высоту 120 метров. Теперь мы можем рассчитать, что его объем составляет примерно [[461,000 ± 1000]] `"m"^3` и его площадь поверхности составляет примерно [[34,080 ± 100]] `"m"^2` ,

---


Border(this, "TextField.border");
		//setPreferredSize(new Dimension (500,80)); // metas-tsa: NEVER set the preferred size, but let the layout do that

		//  Create Editor
		setForeground(AdempierePLAF.getTextColor_Normal());
		setBackground(AdempierePLAF.getFieldBackground_Normal());

		setMandatory(mandatory);
		m_columnName = columnName;

		if (isReadOnly || !isUpdateable)
			setReadWrite(false);
		addKeyListener(this);

		// Create and bind the context menu
		new EditorContextPopupMenu(this);
	}	//	VText

	/**
	 *  Dispose
	 */
	@Override
	public void dispose()
	{
	}   //  dispose

	private String				m_columnName;
	private String				m_oldText;
	private String				m_initialText;
	private volatile boolean	m_setting = false;
	private GridField m_mField;

//	/**	Logger			*/
//	private static Logger log = CLogMgt.getLogger(VTextLong.class);

	/**
	 *	Set Editor to value
	 *  @param value value
	 */
	@Override
	public void setValue(Object value)
	{
		if (value == null)
			m_oldText = "";
		else
			m_oldText = MADBoilerPlate.getPlainText(value.toString());
		if (m_setting)
			return;
		super.setValue(m_oldText);
		m_initialText = m_oldText;
		//	Always position Top
		setCaretPosition(0);
	}	//	setValue

	/**
	 *  Property Change Listener
	 *  @param evt event
	 */
	@Override
	public void propertyChange (PropertyChangeEvent evt)
	{
		if (evt.getPropertyName().equals(org.compiere.model.GridField.PROPERTY))
			setValue(evt.getNewValue());
		// metas: request focus (2009_0027_G131)
		if (evt.getPropertyName().equals(org.compiere.model.GridField.REQUEST_FOCUS))
			requestFocus();
		// metas end
	}   //  propertyChange

	/**
	 *  Action Listener Interface - NOP
	 *  @param listener listener
	 */
	@Override
	public void addActionListener(ActionListener listener)
	{
	}   //  addActionListener

	/**************************************************************************
	 *	Key Listener Interface
	 *  @param e event
	 */
	@Override
	public void keyTyped(KeyEvent e)	{}
	@Override
	public void keyPressed(KeyEvent e)	{}

	/**
	 * 	Key Released
	 *	if Escape restore old Text.
	 *  @param e event
	 */
	@Override
	public void keyReleased(KeyEvent e)
	{
		//  ESC
		if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
			setText(m_initialText);
		m_setting = true;
		try
		{
			fireVetoableChange(m_columnName, m_oldText, getText());
		}
		catch (PropertyVetoException pve)	{}
		m_setting = false;
	}	//	keyReleased

	/**
	 *  Set Field/WindowNo for ValuePreference
	 *  @param mField field model
	 */
	@Override
	public void setField (org.compiere.model.GridField mField)
	{
		m_mField = mField;

		EditorContextPopupMenu.onGridFieldSet(this);
	}   //  setField

	@Override
	public GridField getField() {
		return m_mField;
	}

	// metas
	@Override
	public boolean isAutoCommit()
	{
		return true;
	}
}	//	VTextLong
/******************************************************************************
 * Product: Adempiere ERP & CRM Smart Business Solution                       *
 * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved.                *
 * This program is free software; you can redistribute it and/or modify it    *
 * under the terms version 2 of the GNU General Public License as published   *
 * by the Free Software Foundation. This program is distributed in


poralStorageHandler(conf, false)
	if err != nil {
		t.Fatal(err)
	}

	if err := r.Init(); err != nil {
		t.Fatal("unable to connect", err.Error())
	}

	if connectorSingleton == nil {
		t.Fatal("connectorSingleton is nil")
	}

	t.Run("Connection already established", func(t *testing.T) {
		err := r.ensureConnection()
		assert.NoError(t, err, "Expected no error when connection is already established")
	})

	t.Run("Connection dropped, reconnecting", func(t *testing.T) {
		connectorSingleton = nil
		err := r.ensureConnection()
		assert.NoError(t, err, "Expected no error when reconnecting")
		assert.NotNil(t, connectorSingleton, "Expected connectorSingleton not to be nil after reconnecting")
	})
}

func TestTemporalStorageHandler_SetKey(t *testing.T) {
	conf := make(map[string]interface{})
	conf["host"] = "localhost"
	conf["port"] = 6379

	r, err := NewTemporalStorageHandler(conf, false)
	if err != nil {
		t.Fatal(err)
	}

	if err := r.Init(); err != nil {
		t.Fatal("unable to connect", err.Error())
	}

	if connectorSingleton == nil {
		t.Fatal("connectorSingleton is nil")
	}

	keyName := "testKey"
	session := "testSession"
	timeout := int64(60)

	err = r.SetKey(keyName, session, timeout)
	if err != nil {
		t.Fatal(err)
	}

	// Verify that the key was set correctly
	res, err := r.kv.Get(ctx, r.fixKey(keyName))
	if err != nil {
		t.Fatal(err)
	}

	if res != session {
		t.Fatalf("Expected value %s, got %s", session, res)
	}
}

func TestTemporalStorageHandler_GetName(t *testing.T) {
	conf := make(map[string]interface{})
	conf["host"] = "localhost"
	conf["port"] = 6379

	r, err := NewTemporalStorageHandler(conf, false)
	if err != nil {
		t.Fatal(err)
	}

	if err := r.Init(); err != nil {
		t.Fatal("unable to connect", err.Error())
	}

	if connectorSingleton == nil {
		t.Fatal("connectorSingleton is nil")
	}

	expected := "redis"
	result := r.GetName()

	if result != expected {
		t.Fatalf("Expected %s, but got %s", expected, result)
	}
}

func TestTemporalStorageHandler_Init(t *testing.T) {
	testCases := []struct {
		conf           map[string]interface{}
		errExpected    error
		name           string
		forceReconnect bool
	}{
		{
			name: "Valid configuration",
			conf: map[string]interface{}{
				"host": "localhost",
				"port": 6379,
			},
		},
		{
			name: "Invalid configuration",
			conf: map[string]interface{}{
				"host": "abc",
				"port": 6379,
				"type": "invalid",
			},
			forceReconnect: true,
			errExpected:    errors.New("unsupported database type: invalid"),
		},
	}

	for _, tc := range testCases {
		t.Run(tc.name, func(t *testing.T) {
			r, err := NewTemporalStorageHandler(tc.conf, tc.forceReconnect)
			if err != nil {
				t.Fatal(err)
			}

			err = r.Init()
			if err != nil {
				assert.Error(t, err, tc.errExpected)
				return
			}

			assert.NotNil(t, r.Config, "Expected Config not to be nil")
			assert.NotNil(t, connectorSingleton, "Expected


ro_dezembro'.split(
            '_'
        ),
        monthsShort: 'jan_fev_mar_abr_mai_jun_jul_ago_set_out_nov_dez'.split('_'),
        weekdays: 'Domingo_Segunda-feira_Terça-feira_Quarta-feira_Quinta-feira_Sexta-feira_Sábado'.split(
            '_'
        ),
        weekdaysShort: 'Dom_Seg_Ter_Qua_Qui_Sex_Sáb'.split('_'),
        weekdaysMin: 'Do_2ª_3ª_4ª_5ª_6ª_Sá'.split('_'),
        weekdaysParseExact: true,
        longDateFormat: {
            LT: 'HH:mm',
            LTS: 'HH:mm:ss',
            L: 'DD/MM/YYYY',
            LL: 'D [de] MMMM [de] YYYY',
            LLL: 'D [de] MMMM [de] YYYY HH:mm',
            LLLL: 'dddd, D [de] MMMM [de] YYYY HH:mm',
        },
        calendar: {
            sameDay: '[Hoje às] LT',
            nextDay: '[Amanhã às] LT',
            nextWeek: 'dddd [às] LT',
            lastDay: '[Ontem às] LT',
            lastWeek: function () {
                return this.day() === 0 || this.day() === 6
                    ? '[Último] dddd [às] LT' // Saturday + Sunday
                    : '[Última] dddd [às] LT'; // Monday - Friday
            },
            sameElse: 'L',
        },
        relativeTime: {
            future: 'em %s',
            past: 'há %s',
            s: 'segundos',
            ss: '%d segundos',
            m: 'um minuto',
            mm: '%d minutos',
            h: 'uma hora',
            hh: '%d horas',
            d: 'um dia',
            dd: '%d dias',
            w: 'uma semana',
            ww: '%d semanas',
            M: 'um mês',
            MM: '%d meses',
            y: 'um ano',
            yy: '%d anos',
        },
        dayOfMonthOrdinalParse: /\d{1,2}º/,
        ordinal: '%dº',
        week: {
            dow: 1, // Monday is the first day of the week.
            doy: 4, // The week that contains Jan 4th is the first week of the year.
        },
    });

    return pt;

})));
//! moment.js locale configuration
//! locale : Klingon [tlh]
//! author : Dominika Kruk : https://github.com/amaranthrose

;(function (global, factory) {
   typeof exports === 'object' && typeof module !== 'undefined'
       && typeof require === 'function' ? factory(require('../moment')) :
   typeof define === 'function' && define.amd ? define(['../moment'], factory) :
   factory(global.moment)
}(this, (function (moment) { 'use strict';

    //! moment.js locale configuration

    var numbersNouns = 'pagh_wa’_cha’_wej_loS_vagh_jav_Soch_chorgh_Hut'.split('_');

    function translateFuture(output) {
        var time = output;
        time =
            output.indexOf('jaj') !== -1
                ? time.slice(0, -3) + 'leS'
                : output.indexOf('jar') !== -1
                ? time.slice(0, -3) + 'waQ'
                : output.indexOf('DIS') !== -1
                ? time.slice(0, -3) + 'nem'
                : time + ' pIq';
        return time;
    }

    function translatePast(output) {
        var time = output;
        time =
            output.indexOf('jaj


gImage = b64;
    });

    const input = shadow.getElementById(`${NS}-input`);
    const sendBtn = shadow.getElementById(`${NS}-send`);
    const micBtn = shadow.getElementById(`${NS}-mic`);
    const micStopBtn = shadow.getElementById(`${NS}-mic-stop`);
    let media = { stream: null, rec: null, chunks: [] };
    let phAnim = { id: null, base: '' };
    let thinkAnim = { id: null };

    function focusInputSoon() {
      try { input.focus(); } catch {}
      setTimeout(() => { try { input.focus(); } catch {} }, 0);
      autoSizeInput();
    }

    input.addEventListener('keydown', (e) => {
      // Stop bubbling out to the page (prevents site hotkeys on Space etc.)
      e.stopPropagation();
      const isEnter = (e.key === 'Enter' || e.key === 'NumpadEnter');
      if (isEnter && !e.shiftKey && !e.isComposing) {
        e.preventDefault();
        const text = input.value.trim();
        send(text);
        focusInputSoon();
      }
    });
    input.addEventListener('keyup', (e) => { e.stopPropagation(); autoSizeInput(); });
    input.addEventListener('keypress', (e) => { e.stopPropagation(); });
    input.addEventListener('focus', () => { state.inputFocused = true; });
    input.addEventListener('blur', () => { state.inputFocused = false; });
    input.addEventListener('input', () => { autoSizeInput(); });

    function autoSizeInput() {
      try {
        input.style.height = 'auto';
        const max = 140;
        const h = Math.min(max, input.scrollHeight);
        input.style.height = h + 'px';
      } catch {}
    }

    // Handle pasted images
    panel.addEventListener('paste', async (e) => {
      const items = e.clipboardData?.items || [];
      for (const it of items) {
        if (it.type.startsWith('image/')) {
          const file = it.getAsFile();
          if (file) {
            const b64 = await fileToDataUrl(file);
            appendMessage('user', `(${t('status.imageInserted')})`);
            state.pendingImage = b64;
            e.preventDefault();
          }
        }
      }
    });

    async function startRecording() {
      try {
        if (!navigator.mediaDevices?.getUserMedia) throw new Error(t('errors.micUnavailable'));
        media.stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        media.chunks = [];
        media.rec = new MediaRecorder(media.stream);
        media.rec.ondataavailable = (e) => { if (e.data && e.data.size) media.chunks.push(e.data); };
        media.rec.start();
        micBtn.classList.add('hidden');
        micStopBtn.classList.remove('hidden');
        input.setAttribute('data-prev-ph', input.placeholder || '');
        startPlaceholderAnim(t('status.recording'));
      } catch (e) {
        appendMessage('bot', t('errors.microphoneError', { details: String(e.message || e) }));
      }
    }

    async function stopRecording() {
      try {
        if (!media.rec) return;
        await new Promise((resolve) => {
          media.rec.onstop = resolve;
          media.rec.stop();
        });
        micStopBtn.classList.add('hidden');
        startPlaceholderAnim(t('status.transcribing'));
        const blob = new Blob(media.chunks, { type: media.rec.mimeType || 'audio/webm' });
        cleanupStream();
        const dataUrl = await blobToDataUrl(blob);
        const resp = await chrome.runtime.sendMessage({ type: 'AUDIO_TRANSCRIBE', payload: { data


elf) -> SAR1_INV_R {
        SAR1_INV_R::new(((self.bits >> 9) & 0x01) != 0)
    }
    #[doc = "Bit 10 - 1: data to DIG ADC2 CTRL is inverted, otherwise not."]
    #[inline(always)]
    pub fn sar2_inv(&self) -> SAR2_INV_R {
        SAR2_INV_R::new(((self.bits >> 10) & 0x01) != 0)
    }
    #[doc = "Bit 11 - 1: select saradc timer 0: i2s_ws trigger"]
    #[inline(always)]
    pub fn timer_sel(&self) -> TIMER_SEL_R {
        TIMER_SEL_R::new(((self.bits >> 11) & 0x01) != 0)
    }
    #[doc = "Bits 12:23 - Set SAR ADC timer target."]
    #[inline(always)]
    pub fn timer_target(&self) -> TIMER_TARGET_R {
        TIMER_TARGET_R::new(((self.bits >> 12) & 0x0fff) as u16)
    }
    #[doc = "Bit 24 - Enable SAR ADC timer trigger."]
    #[inline(always)]
    pub fn timer_en(&self) -> TIMER_EN_R {
        TIMER_EN_R::new(((self.bits >> 24) & 0x01) != 0)
    }
}
impl W {
    #[doc = "Bit 0 - Enable limit times of SAR ADC sample."]
    #[inline(always)]
    pub fn meas_num_limit(&mut self) -> MEAS_NUM_LIMIT_W {
        MEAS_NUM_LIMIT_W { w: self }
    }
    #[doc = "Bits 1:8 - Set maximum conversion number."]
    #[inline(always)]
    pub fn max_meas_num(&mut self) -> MAX_MEAS_NUM_W {
        MAX_MEAS_NUM_W { w: self }
    }
    #[doc = "Bit 9 - 1: data to DIG ADC1 CTRL is inverted, otherwise not."]
    #[inline(always)]
    pub fn sar1_inv(&mut self) -> SAR1_INV_W {
        SAR1_INV_W { w: self }
    }
    #[doc = "Bit 10 - 1: data to DIG ADC2 CTRL is inverted, otherwise not."]
    #[inline(always)]
    pub fn sar2_inv(&mut self) -> SAR2_INV_W {
        SAR2_INV_W { w: self }
    }
    #[doc = "Bit 11 - 1: select saradc timer 0: i2s_ws trigger"]
    #[inline(always)]
    pub fn timer_sel(&mut self) -> TIMER_SEL_W {
        TIMER_SEL_W { w: self }
    }
    #[doc = "Bits 12:23 - Set SAR ADC timer target."]
    #[inline(always)]
    pub fn timer_target(&mut self) -> TIMER_TARGET_W {
        TIMER_TARGET_W { w: self }
    }
    #[doc = "Bit 24 - Enable SAR ADC timer trigger."]
    #[inline(always)]
    pub fn timer_en(&mut self) -> TIMER_EN_W {
        TIMER_EN_W { w: self }
    }
    #[doc = "Writes raw bits to the register."]
    #[inline(always)]
    pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
        self.0.bits(bits);
        self
    }
}
#[doc = "DIG ADC common configuration\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify).


CreateLocalEndpointOnDisk(string machineName, string path)
        {
            // we'll create local queues if required and they don't already exist
            if (machineName == LocalMachine && _config.AutoCreateLocalQueues)
            {
                if (MessageQueue.Exists(path)) { return; }

                // create and set permissions
                using (var queue = MessageQueue.Create(path, true))
                {
                    string adminName = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null).Translate(typeof(NTAccount)).ToString();
                    queue.SetPermissions(Thread.CurrentPrincipal.Identity.Name, MessageQueueAccessRights.GenericWrite);
                    queue.SetPermissions(adminName, MessageQueueAccessRights.FullControl);
                }
            }
        }

        void ValidateQueue(string machineName, string queueName, string path)
        {
            if (!QueueExists(machineName, queueName, path))
            {
                throw new QueueNotFoundException(
                    $"{queueName} doesn't exist {(machineName == LocalMachine ? "locally" : "on " + machineName)}. Did you type it correctly?");
            }
        }

        void CreateReadQueueFromPath(string path)
        {
            _readQueue = new MiniBusMessageQueue(new MessageQueue(path), _logger, _config.AutoPurgeSystemJournal);
        }

        void CreateWriteQueueFromPath(string path)
        {
            _writeQueues.Add(new MiniBusMessageQueue(new MessageQueue(path), _logger, _config.AutoPurgeSystemJournal));
        }

        void CreateQueueToPutErrorsOn(string machineName, string queueName, string path)
        {
            if (QueueExists(machineName, queueName, path))
            {
                _errorQueue = new MiniBusMessageQueue(new MessageQueue(path), _logger, _config.AutoPurgeSystemJournal);
            }
            else
            {
                throw new QueueNotFoundException(queueName + " doesn't exist. Did you type it correctly?");
            }
        }

        static bool QueueExists(string machineName, string queueName, string path)
        {
            bool isIpAddress = Regex.Match(machineName, Ipaddress).Success;

            if (isIpAddress)
            {
                return true; // assume valid as no means of retrieving queues when using ipaddress
            }

            if (machineName == LocalMachine)
            {
                return MessageQueue.Exists(path);
            }

            // MessageQueue.Exists doesn't work for remote machines
            var results = MessageQueue.GetPrivateQueuesByMachine(machineName);
            return results.Any(q => q.QueueName == $@"private$\{queueName}");
        }

        readonly List<IMessageQueue> _writeQueues = new List<IMessageQueue>();
        readonly IBusConfig _config;

        IMessageQueue _readQueue;
        IMessageQueue _errorQueue;
        ILogMessages _logger = new NullLogger();

        const string Ipaddress = @"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b";
        const string LocalMachine = ".";
    }

}


culateBoundingBox(tmpBox)
            bbox.ext(tmpBox)
        }
    }

    override fun dispose() {
        for (subMesh in subMeshes) {
            subMesh.mesh.dispose()
        }
    }

    companion object {
        private val tmpBox = BoundingBox()
    }
}
package com.github.quillraven.mysticwoods.ui

import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.TextureAtlas
import com.badlogic.gdx.scenes.scene2d.ui.Skin
import com.badlogic.gdx.scenes.scene2d.utils.Drawable
import ktx.assets.disposeSafely
import ktx.scene2d.Scene2DSkin
import ktx.style.*

enum class Drawables(
    val atlasKey: String,
) {
    CHAR_INFO_BGD("char_info"),
    PLAYER("player"),
    SLIME("slime"),
    LIFE_BAR("life_bar"),
    MANA_BAR("mana_bar"),
    FRAME_BGD("frame_bgd"),
    FRAME_FGD("frame_fgd"),
    INVENTORY_SLOT("inv_slot"),
    INVENTORY_SLOT_HELMET("inv_slot_helmet"),
    INVENTORY_SLOT_ARMOR("inv_slot_armor"),
    INVENTORY_SLOT_WEAPON("inv_slot_weapon"),
    INVENTORY_SLOT_BOOTS("inv_slot_boots"),
}

operator fun Skin.get(drawable: Drawables): Drawable = this.getDrawable(drawable.atlasKey)

enum class Fonts(
    val atlasRegionKey: String,
    val scaling: Float
) {
    DEFAULT("fnt_white", 0.25f),
    BIG("fnt_white", 0.5f),
    BIGGER("fnt_white", 0.75f);

    val skinKey = "Font_${this.name.lowercase()}"
    val fontPath = "ui/${this.atlasRegionKey}.fnt"
}

operator fun Skin.get(font: Fonts): BitmapFont = this.getFont(font.skinKey)

enum class Labels {
    FRAME,
    TITLE,
    LARGE;

    val skinKey = this.name.lowercase()
}

enum class Buttons {
    TEXT_BUTTON;

    val skinKey = this.name.lowercase()
}

fun loadSkin() {
    Scene2DSkin.defaultSkin = skin(TextureAtlas("ui/ui.atlas")) { skin ->
        loadFontSkin(skin)
        loadLabelSkin(skin)
        loadButtonSkin(skin)
    }
}

private fun loadFontSkin(skin: Skin) {
    Fonts.values().forEach { fnt ->
        skin[fnt.skinKey] =
            BitmapFont(Gdx.files.internal(fnt.fontPath), skin.getRegion(fnt.atlasRegionKey)).apply {
                data.markupEnabled = true
                data.setScale(fnt.scaling)
            }
    }
}

private fun @SkinDsl Skin.loadButtonSkin(skin: Skin) {
    textButton(Buttons.TEXT_BUTTON.skinKey) {
        font = skin[Fonts.DEFAULT]
    }
}

private fun @SkinDsl Skin.loadLabelSkin(skin: Skin) {
    label(Labels.FRAME.skinKey) {
        font = skin[Fonts.DEFAULT]
        background = skin[Drawables.FRAME_FGD].apply {
            leftWidth = 2f
            rightWidth = 2f
            topHeight = 1f
        }
    }
    label(Labels.TITLE.skinKey) {
        font = skin[Fonts.BIG]
        fontColor = Color.SLATE
        background = skin[Drawables.FRAME_FGD].apply {
            leftWidth = 2f
            rightWidth = 2f
            topHeight = 1f
        }
    }
    label(Labels.LARGE.skinKey) {
        font = skin[Fonts.BIGGER]
    }
}

fun disposeSkin() = Scene2DSkin.defaultSkin.disposeSafely()package com.github.quillraven.mysticwoods.system

import com.badlogic.g


_;
  }
  /**
   * .User operator = 4;
   */
  @java.lang.Override
  public cool.scx.live_room_watcher.impl.douyin_hack.proto_entity.webcast.data.UserOrBuilder getOperatorOrBuilder() {
    return operator_ == null ? cool.scx.live_room_watcher.impl.douyin_hack.proto_entity.webcast.data.User.getDefaultInstance() : operator_;
  }

  public static final int IS_SET_TO_ADMIN_FIELD_NUMBER = 5;
  private boolean isSetToAdmin_ = false;
  /**
   * bool is_set_to_admin = 5;
   * @return The isSetToAdmin.
   */
  @java.lang.Override
  public boolean getIsSetToAdmin() {
    return isSetToAdmin_;
  }

  public static final int IS_TOP_USER_FIELD_NUMBER = 6;
  private boolean isTopUser_ = false;
  /**
   * bool is_top_user = 6;
   * @return The isTopUser.
   */
  @java.lang.Override
  public boolean getIsTopUser() {
    return isTopUser_;
  }

  public static final int RANK_SCORE_FIELD_NUMBER = 7;
  private long rankScore_ = 0L;
  /**
   * int64 rank_score = 7;
   * @return The rankScore.
   */
  @java.lang.Override
  public long getRankScore() {
    return rankScore_;
  }

  public static final int TOP_USER_NO_FIELD_NUMBER = 8;
  private long topUserNo_ = 0L;
  /**
   * int64 top_user_no = 8;
   * @return The topUserNo.
   */
  @java.lang.Override
  public long getTopUserNo() {
    return topUserNo_;
  }

  public static final int ENTER_TYPE_FIELD_NUMBER = 9;
  private long enterType_ = 0L;
  /**
   * int64 enter_type = 9;
   * @return The enterType.
   */
  @java.lang.Override
  public long getEnterType() {
    return enterType_;
  }

  public static final int ACTION_FIELD_NUMBER = 10;
  private long action_ = 0L;
  /**
   * int64 action = 10;
   * @return The action.
   */
  @java.lang.Override
  public long getAction() {
    return action_;
  }

  public static final int ACTION_DESCRIPTION_FIELD_NUMBER = 11;
  @SuppressWarnings("serial")
  private volatile java.lang.Object actionDescription_ = "";
  /**
   * string action_description = 11;
   * @return The actionDescription.
   */
  @java.lang.Override
  public java.lang.String getActionDescription() {
    java.lang.Object ref = actionDescription_;
    if (ref instanceof java.lang.String) {
      return (java.lang.String) ref;
    } else {
      com.google.protobuf.ByteString bs =
          (com.google.protobuf.ByteString) ref;
      java.lang.String s = bs.toStringUtf8();
      actionDescription_ = s;
      return s;
    }
  }
  /**
   * string action_description = 11;
   * @return The bytes for actionDescription.
   */
  @java.lang.Override
  public com.google.protobuf.ByteString
      getActionDescriptionBytes() {
    java.lang.Object ref = actionDescription_;
    if (ref instanceof java.lang.String) {
      com.google.protobuf.ByteString b =
          com.google.protobuf.ByteString.copyFromUtf8(


/// In order to deploy the delegator smart contract we first
    /// have to manually put the code of the accumulator, adder
    /// and subber smart contracts, receive their code hashes from
    /// the signalled events and put their code hash into our
    /// delegator smart contract.
    struct Delegator {
        /// Says which of adder or subber is currently in use.
        which: storage::Value<Which>,
        /// The accumulator smart contract.
        accumulator: storage::Value<accumulator::Accumulator>,
        /// The adder smart contract.
        adder: storage::Value<adder::Adder>,
        /// The subber smart contract.
        subber: storage::Value<subber::Subber>,
    }

    impl Deploy for Delegator {
        /// Initializes the value to the initial value.
        fn deploy(
            &mut self,
            init_value: i32,
            accumulator_code_hash: Hash,
            adder_code_hash: Hash,
            subber_code_hash: Hash,
        ) {
            self.which.set(Which::Adder);
            let total_balance = env.balance();
            let accumulator = accumulator::Accumulator::new(accumulator_code_hash, init_value)
                .value(total_balance / 4)
                .create()
                .expect("failed at instantiating the accumulator contract");
            self.accumulator.set(accumulator.clone());
            self.adder.set(
                adder::Adder::new(adder_code_hash, accumulator.account_id())
                    .value(total_balance / 4)
                    .create()
                    .expect("failed at instantiating the adder contract")
            );
            self.subber.set(
                subber::Subber::new(subber_code_hash, accumulator.account_id())
                    .value(total_balance / 4)
                    .create()
                    .expect("failed at instantiating the subber contract")
            );
        }
    }

    impl Delegator {
        /// Delegates the call.
        pub(external) fn delegate(&mut self, by: i32) {
            match &*self.which {
                Which::Adder => self.adder.inc(by),
                Which::Subber => self.subber.dec(by),
            }
        }

        /// Switches the delegator.
        pub(external) fn switch(&mut self) {
            match *self.which {
                Which::Adder => {
                    *self.which = Which::Subber;
                }
                Which::Subber => {
                    *self.which = Which::Adder;
                }
            }
        }
    }
}
<filename>impl/src/ident_ext.rs
use proc_macro2::{Ident, Span};

/// Utilities for operating on `Ident` instances.
pub trait IdentExt {
    /// Creates a new Ident from the given `str`.
    fn from_str<T: AsRef<str>>(s: T) -> Ident {
        Ident::new(s.as_ref(), Span::call_site())
    }
}

impl IdentExt for Ident {}
#[doc = "Reader of register MISC_CONF_2"]
pub type R = crate::R<u32, super::MISC_CONF_2>;
#[doc = "Writer for register MISC_CONF_2"]
pub type W = crate::W<u32, super::MISC_CONF_2>;
#[doc = "Register MISC_CONF_2 `reset()`'s with value 0xffff_ff00"]
impl crate::ResetValue for super::MISC_CONF_2 {
    type Type = u32;
    #[inline(always)]
    fn reset_value() -> Self::Type {
        0xffff_ff00
    }
}
#[doc = "Reader of field `HPOSC_COMP_P3


l	(sp)+,d2-d4   * y1
		tst.b	d2
		bne	TYPEMIS
		move.w	d3,ptsin+2

		movem.l	(sp)+,d2-d4   * x1
		tst.b	d2
		bne	TYPEMIS
		move.w	d3,ptsin

		movem.l	(sp)+,d2-d4   * handle
		tst.b	d2
		bne	TYPEMIS
		move.w	d3,contrl6

		bsr	call_vdi

                move.l	RETURN,a0
                jmp	(a0)

v_show_c	move.l	(sp)+,RETURN
		cmpi.w	#0,d0
		bne	SYNTAX

		move.w	#77,control	graf_handle
		move.w	#0,control+2
		move.w	#5,control+4
		move.w	#0,control+6
		move.w	#0,control+8
		bsr	call_aes

		move.w	d0,current_handle

		move.w	#122,contrl
		clr.w	contrl1
		move.w	#1,contrl3
		move.w	current_handle,contrl6
		move.w	#0,intin
		bsr	call_vdi

                move.l	RETURN,a0
                jmp	(a0)

v_hide_c	move.l	(sp)+,RETURN

		cmpi	#0,d0
		bne	SYNTAX

		move.w	#77,control	graf_handle
		move.w	#0,control+2
		move.w	#5,control+4
		move.w	#0,control+6
		move.w	#0,control+8
		bsr	call_aes
		move.w	d0,current_handle

		move.w	#123,contrl
		clr.w	contrl1
		clr.w	contrl3
		move.w	current_handle,contrl6
		bsr	call_vdi

		move.l	RETURN,a0
		jmp	(a0)

v_pmarker	move.l	(sp)+,RETURN
		cmpi	#3,d0
		bne	SYNTAX

		movem.l	(sp)+,d2-d4	* pts
*		tst.b	d2
*		bne	TYPEMIS
*		move.w	ptsin

		movem.l	(sp)+,d2-d4	* n
		tst.b	d2
		bne	TYPEMIS
		move.w	d3,contrl1

		movem.l	(sp)+,d2-d4	* handle
		tst.b	d2
		bne	TYPEMIS
		move.w	d3,contrl6

		move.w	#7,contrl
		clr.w	contrl2
		clr.w	contrl3
		clr.w	contrl4
		clr.w	contrl5

		bsr	call_vdi

                move.l	RETURN,a0
                jmp	(a0)

v_fillarea	move.l	(sp)+,RETURN
		cmpi	#3,d0
		bne	SYNTAX

		movem.l	(sp)+,d2-d4	* pts
		tst.b	d2
		bne	TYPEMIS
*		move.w	d3,ptsin

		movem.l	(sp)+,d2-d4	* n
		tst.b	d2
		bne	TYPEMIS
		move.w	d3,contrl1

		movem.l	(sp


   *
             * This allows us to draw a strip,
             * rather then a single pixel,
             * which is significantly faster!
             */
            for (
              ;
              (nextX < endX) && (
                  sData[i+4] === cRed   &&
                  sData[i+5] === cGreen &&
                  sData[i+6] === cBlue  &&
                  sData[i+7] === ca
              );
               nextX += pixelWidth, i += 4
            ) { }

            dCtx.fillRect(
                nowDrawX,
                drawYI,
                ((0.5 + nextX) | 0) - nowDrawX,
                diffY
            );
          } else {
            dCtx.fillRect(
                nowDrawX,
                drawYI,
                ((0.5 + nextX) | 0) - nowDrawX,
                diffY
            );
          }
        }

        i += 4;
        drawX = nextX;
      }

      drawY = nextY;
    }
  }
}

var appendHTML = function( el, html ) {
  if ( typeof html === 'string' ) {
    el.insertAdjacentHTML( 'beforeend', html );
  } else if (
      ( html instanceof Array ) ||
      ( ('' + html) === '[object Arguments]' )
  ) {
    var htmlLen = html.length;

    for ( var i = 0; i < htmlLen; i++ ) {
      appendHTML( el, html[i] );
    }
  } else if ( html.jquery ) {
    el.appendChild( html.get(0) );
  } else if ( html instanceof Element ) {
    el.appendChild( html );
  } else {
    throw new Error( "unknown argument given, cannot add to element" );
  }

  return el;
}

/**
 * Creates a new JQuery wrapped Anchor, and returns it,
 * but with lots of defaults set.
 *
 * These include '#' for the href, and to prevent the default action
 * of following the link.
 *
 * You can also pass in more CSS classes after the 'text' parameter.
 *
 * @param text The text to appear on this anchor.
 * @return A jQuery wrapped anchor tag.
 */
var $a = function( text ) {
  var klass = '';

  for ( var i = 1; i < arguments.length; i++ ) {
    klass += ' ' + arguments[i];
  }

  var anchor = document.createElement( 'a' );
  anchor.setAttribute( 'href', '#' );
  anchor.className = klass;

  if ( text ) {
    anchor.innerHTML = text;
  }

  return $(anchor);
};

/**
 * A generic, reusable, horizontal slider.
 *
 * You can use the 'slide' method to attach functions to be called when this
 * slides.
 *
 * You can also add any classes to it.
 *
 * ASCII art impression of control:
 *
 *   -------[]---
 *
 * This will use the input 'range' type where available.
 *
 * @return A jQuery object (a div), which is pre-built and setup as a slider.
 */
/*
 * Ok, so how does this work? Either a HTML5 input range or a custom
 * slider gets generated.
 *
 * This then has an API directly pasted onto the object which is the
 * most *basic* API possible. Direct getters and setters, and visual
 * cues, that's it.
 *
 * They both have a more complex API built on top, which is the API
 * that does the 'slideUp', 'slideDown', setting and running of slide
 * events.
 *
 * The idea is to push the clever code up the stack, so it's shared,
 * and keep the lower code where it's different as basic as possible.
 */
var $slider = function() {
  var sliderBar;

  if ( $.support.input.range ) {
    var sliderBarInput = newInput( 'range', 'skybrush_slider_bar' );

    // default min/max/


					}
				}
				else
				{
					if(value==null || value.Trim()=="")
                    {
                        //Set the cells to null
                        Value = null;
                    }
                    else if (_fromRow == _toRow && _fromCol == _toCol)
					{
						Set_Formula(this, value, _fromRow, _fromCol);
					}
					else
					{
						Set_SharedFormula(this, value, this, false);
						if (Addresses != null)
						{
							foreach (var address in Addresses)
							{
								Set_SharedFormula(this, value, address, false);
							}
						}
					}
				}
			}
		}
		/// <summary>
		/// Gets or Set a formula in R1C1 format.
		/// </summary>
		public string FormulaR1C1
		{
			get
			{
				IsRangeValid("FormulaR1C1");
				return _worksheet.GetFormulaR1C1(_fromRow, _fromCol);
			}
			set
			{
				IsRangeValid("FormulaR1C1");
                if (value.Length > 0 && value[0] == '=') value = value.Substring(1, value.Length - 1); // remove any starting equalsign.

                if (value == null || value.Trim() == "")
                {
                    //Set the cells to null
                    _worksheet.Cells[ExcelCellBase.TranslateFromR1C1(value, _fromRow, _fromCol)].Value = null;
                }
				else if (Addresses == null)
				{
					Set_SharedFormula(this, ExcelCellBase.TranslateFromR1C1(value, _fromRow, _fromCol), this, false);
				}
				else
				{
					Set_SharedFormula(this, ExcelCellBase.TranslateFromR1C1(value, _fromRow, _fromCol), new ExcelAddress(WorkSheet, FirstAddress), false);
					foreach (var address in Addresses)
					{
						Set_SharedFormula(this, ExcelCellBase.TranslateFromR1C1(value, address.Start.Row, address.Start.Column), address, false);
					}
				}
			}
		}
		/// <summary>
		/// Set the hyperlink property for a range of cells
		/// </summary>
		public Uri Hyperlink
		{
			get
			{
				IsRangeValid("formulaR1C1");
				return _worksheet._hyperLinks.GetValue(_fromRow, _fromCol);
			}
			set
			{
				_changePropMethod(this, _setHyperLinkDelegate, value);
			}
		}
		/// <summary>
		/// If the cells in the range are merged.
		/// </summary>
		public bool Merge
		{
			get
			{
				IsRangeValid("merging");
				for (int col = _fromCol; col <= _toCol; col++)
				{
					for (int row = _fromRow; row <= _toRow; row++)
					{
                        if(_worksheet.MergedCells[row, col]==null)
                        {
                            return false;
                        }
					}
				}
				return true;
			}
			set
			{
				IsRangeValid("merging");
                _worksheet.MergedCells.Clear(this);
                if (value)
			    {
                    _worksheet.MergedCells.Add(new ExcelAddressBase(FirstAddress), true);
			        if (Addresses != null)
			        {
			            foreach (var address in Addresses)
			            {
                            _worksheet.MergedCells.Clear(address); //Fixes issue 15482
                            _worksheet.MergedCells.Add(address, true);
			            }
			        }
			    }
			    else
			    {
                    if (Addresses != null)
			        {
			            foreach (var