S.toBuilder()
            .shift(27, 2)
            .shift(31, 7)
            .insert(37, CommandParam.BLOCK_POSITION)
            .shift(46, 1)
            .build();

    protected static final TypeMap<EntityEventType> ENTITY_EVENTS = Bedrock_v361.ENTITY_EVENTS.toBuilder()
            .insert(74, EntityEventType.FINISHED_CHARGING_ITEM)
            .build();

    protected static final TypeMap<LevelEventType> LEVEL_EVENTS = Bedrock_v361.LEVEL_EVENTS.toBuilder()
            .insert(LEVEL_EVENT_PARTICLE + 24, LevelEvent.PARTICLE_POINT_CLOUD)
            .insert(LEVEL_EVENT_PARTICLE + 25, LevelEvent.PARTICLE_EXPLOSION)
            .insert(LEVEL_EVENT_PARTICLE + 26, LevelEvent.PARTICLE_BLOCK_EXPLOSION)
            .build();

    protected static final TypeMap<SoundEvent> SOUND_EVENTS = Bedrock_v361.SOUND_EVENTS.toBuilder()
            .replace(274, SoundEvent.AMBIENT_IN_RAID)
            .insert(275, SoundEvent.UI_CARTOGRAPHY_TABLE_USE)
            .insert(276, SoundEvent.UI_STONECUTTER_USE)
            .insert(277, SoundEvent.UI_LOOM_USE)
            .insert(278, SoundEvent.SMOKER_USE)
            .insert(279, SoundEvent.BLAST_FURNACE_USE)
            .insert(280, SoundEvent.SMITHING_TABLE_USE)
            .insert(281, SoundEvent.SCREECH)
            .insert(282, SoundEvent.SLEEP)
            .insert(283, SoundEvent.FURNACE_USE)
            .insert(284, SoundEvent.MOOSHROOM_CONVERT)
            .insert(285, SoundEvent.MILK_SUSPICIOUSLY)
            .insert(286, SoundEvent.CELEBRATE)
            .insert(287, SoundEvent.UNDEFINED)
            .build();

    protected static final TypeMap<ResourcePackType> RESOURCE_PACK_TYPES = Bedrock_v361.RESOURCE_PACK_TYPES.toBuilder()
            .replace(1, ResourcePackType.ADDON)
            .replace(2, ResourcePackType.CACHED)
            .replace(3, ResourcePackType.COPY_PROTECTED)
            .replace(4, ResourcePackType.DATA_ADD_ON)
            .replace(5, ResourcePackType.PERSONA_PIECE)
            .replace(6, ResourcePackType.RESOURCES)
            .replace(7, ResourcePackType.SKINS)
            .insert(8, ResourcePackType.WORLD_TEMPLATE)
            .build();

    public static final BedrockCodec CODEC = Bedrock_v361.CODEC.toBuilder()
            .protocolVersion(388)
            .minecraftVersion("1.13.0")
            .helper(() -> new BedrockCodecHelper_v388(ENTITY_DATA, GAME_RULE_TYPES))
            .deregisterPacket(ExplodePacket.class)
            .updateSerializer(ResourcePackDataInfoPacket.class, new ResourcePackDataInfoSerializer_v361(RESOURCE_PACK_TYPES))
            .updateSerializer(ResourcePackStackPacket.class, ResourcePackStackSerializer_v388.INSTANCE)
            .updateSerializer(StartGamePacket.class, StartGameSerializer_v388.INSTANCE)
            .updateSerializer(AddPlayerPacket.class, AddPlayerSerializer_v388.INSTANCE)
            .updateSerializer(InteractPacket.class, InteractSerializer_v388.INSTANCE)
            .updateSerializer(RespawnPacket.class, RespawnSerializer_v388.INSTANCE)
            .updateSerializer(CraftingDataPacket.class, CraftingDataSerializer_v388.INSTANCE)
            .updateSerializer(PlayerListPacket.class, PlayerListSerializer_v388.INSTANCE)
            .updateSerializer(EventPacket.class, EventSerializer_v388.INSTANCE)
            .updateSerializer(AvailableCommandsPacket.class, new AvailableCommandsSerializer_v388(COMMAND_PARAMS))
            .updateSerializer(ResourcePackChunkDataPacket.class, ResourcePackChunkDataSer


    /// Defaults to 60000ms (60 seconds).
    #[serde(default = "ExchangeRateConfig::default_poll_interval")]
    pub poll_interval: u64,
    /// The number of consecutive failed polls to the exchange rate provider
    /// that the connector will tolerate before invalidating the exchange rate cache.
    #[serde(default = "ExchangeRateConfig::default_poll_failure_tolerance")]
    pub poll_failure_tolerance: u32,
    /// API to poll for exchange rates. Currently the supported options are:
    /// - [CoinCap](https://docs.coincap.io)
    /// - [CryptoCompare](https://cryptocompare.com) (note this requires an API key)
    /// If this value is not set, the node will not poll for exchange rates and will
    /// instead use the rates configured via the HTTP API.
    #[serde(default)]
    pub provider: Option<ExchangeRateProvider>,
    /// Spread, as a fraction, to add on top of the exchange rate.
    /// This amount is kept as the node operator's profit, or may cover
    /// fluctuations in exchange rates.
    /// For example, take an incoming packet with an amount of 100. If the
    /// exchange rate is 1:2 and the spread is 0.01, the amount on the
    /// outgoing packet would be 198 (instead of 200 without the spread).
    #[serde(default)]
    pub spread: f64,
}

impl Default for ExchangeRateConfig {
    fn default() -> Self {
        // FIXME: we cannot (efficiently) use the serde defaults for a Default derive so we are
        // left with this. We could deserialize an empty serde_json::Value.
        Self {
            poll_interval: Self::default_poll_interval(),
            poll_failure_tolerance: Self::default_poll_failure_tolerance(),
            provider: Default::default(),
            spread: Self::default_spread(),
        }
    }
}

impl ExchangeRateConfig {
    pub(crate) fn default_poll_interval() -> u64 {
        60_000
    }
    pub(crate) fn default_poll_failure_tolerance() -> u32 {
        5
    }
    pub(crate) fn default_spread() -> f64 {
        0.0
    }
}

/// An all-in-one Interledger node that includes sender and receiver functionality,
/// a connector, and a management API.
/// Will connect to the database at the given URL; see the crate features defined in
/// Cargo.toml to see a list of all supported stores.
#[derive(Deserialize, Clone, PartialEq, Debug)]
pub struct InterledgerNode {
    /// ILP address of the node
    #[serde(deserialize_with = "deserialize_optional_address")]
    #[serde(default)]
    pub ilp_address: Option<Address>,
    /// Root secret used to derive encryption keys
    #[serde(deserialize_with = "deserialize_32_bytes_hex")]
    pub secret_seed: [u8; 32],
    /// HTTP Authorization token for the node admin (sent as a Bearer token)
    pub admin_auth_token: String,
    /// Data store URI (for example, "redis://127.0.0.1:6379" or "redis+unix:/tmp/redis.sock")
    #[serde(
        default = "default_database_url",
        // temporary alias for backwards compatibility
        alias = "redis_url"
    )]
    pub database_url: String,
    /// Database prefix which can be used in case a db instance is shared by multiple nodes
    #[serde(default)]
    pub database_prefix: String,
    /// IP address and port to listen for HTTP connections
    /// This is used for both the API and ILP over HTTP packets
    #[serde(default = "default_http_bind_address")]
    pub http_bind_address: SocketAddr,
    /// IP address and port to listen for the Settlement Engine API
    #[serde(default = "default_settlement_api_bind_address")]
    pub settlement_api_bind_address: SocketAddr,
    /// When SPSP payments are sent to the root domain, the payment pointer is resolved
    ///


        let stock_data = StockData::new(QuoteType::CryptoCurrency, Symbol::Btc, 3000.0, 1000.0, 100.0, Currency::USD);

        let json = serde_json::to_string(&stock_data);
        match json {
            Ok(json) => {
                println!("json = {}", json)
            }
            Err(e) => {
                println!("error = {}", e);
                panic!()
            }
        }
    }

    #[test]
    fn test_create_stock_data_deserialize() {
        let stock_data = StockData::new(QuoteType::CryptoCurrency, Symbol::Btc, 3000.0, 1000.0, 100.0, Currency::USD);

        let json = serde_json::to_string(&stock_data);
        match json {
            Ok(json) => {
                //println!("json = {}", json);
                let stock: StockData = serde_json::from_str(&json).unwrap();
                match stock.quote_type {
                    QuoteType::CryptoCurrency => {
                        println!("ok");
                    }
                    _ => {}
                }
            }
            Err(e) => {
                println!("error = {}", e);
                panic!()
            }
        }
    }

    #[tokio::test]
    async fn test_create_stock_data_fetch_api() {
        let api = YahooApi::new();
        let name = format!("");
        let value = format!("BTC-USD");
        let option = api.fetch(&name,&value).await;
        match option {
            None => { panic!() }
            Some(data) => {
                println!("stock = {:?}", data)
            }
        }
    }
}<gh_stars>10-100
// Copyright 2017-2021 <NAME> <<EMAIL>>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

use mhost::nameserver::NameServerConfig;
use mhost::resolver::{MultiQuery, Resolver, ResolverConfig, UniQuery};
use mhost::RecordType;
use std::env;
use std::net::SocketAddr;

#[tokio::main]
async fn main() {
    let name = env::args().nth(1).unwrap_or_else(|| "www.example.com".to_string());

    let sock_addr: SocketAddr = "8.8.8.8:53".parse().unwrap();
    let name_server_config = NameServerConfig::udp(sock_addr);
    let config = ResolverConfig::new(name_server_config);

    let resolver = Resolver::new(config, Default::default())
        .await
        .expect("Failed to create resolver");

    let query = UniQuery::new(name, RecordType::A).expect("Failed to create query");
    let one_lookup = resolver.lookup(query).await.expect("failed to execute lookups");
    println!("Lookup result: #{} {:?}", one_lookup.len(), &one_lookup);

    let mq = MultiQuery::multi_record(
        "www.example.com",
        vec![RecordType::A, RecordType::AAAA, RecordType::TXT],
    )
    .expect("Failed to create multi-query");
    let lookups = resolver.lookup(mq).await.expect("failed to execute lookups");

    //println!("Multi-Lookup results: {:#?}", multi_lookup);

    let successes = lookups.iter().filter(|x| x.result().is_response()).count();


/*-------------------------------------------------------------------------
 *
 * matview.h
 *	  prototypes for matview.c.
 *
 *
 * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 * src/include/commands/matview.h
 *
 *-------------------------------------------------------------------------
 */
#ifndef MATVIEW_H
#define MATVIEW_H

#include "catalog/objectaddress.h"
#include "fmgr.h"
#include "nodes/params.h"
#include "nodes/parsenodes.h"
#include "tcop/dest.h"
#include "utils/relcache.h"

extern void SetMatViewPopulatedState(Relation relation, bool newstate);

extern void SetMatViewIVMState(Relation relation, bool newstate);

extern ObjectAddress ExecRefreshMatView(RefreshMatViewStmt *stmt, const char *queryString,
										ParamListInfo params, QueryCompletion *qc);

extern DestReceiver *CreateTransientRelDestReceiver(Oid transientoid);

extern bool MatViewIncrementalMaintenanceIsEnabled(void);

extern Datum IVM_immediate_before(PG_FUNCTION_ARGS);
extern Datum IVM_immediate_maintenance(PG_FUNCTION_ARGS);
extern Datum IVM_visible_in_prestate(PG_FUNCTION_ARGS);
extern Query* rewrite_query_for_exists_subquery(Query *query);
extern void AtAbort_IVM(void);
extern char *getColumnNameStartWith(RangeTblEntry *rte, char *str, int *attnum);
extern bool isIvmName(const char *s);

#endif							/* MATVIEW_H */


 */	li r4, 0
/* 802AEE58 002AAAB8  38 E0 00 0C */	li r7, 0xc
/* 802AEE5C 002AAABC  39 20 00 00 */	li r9, 0
/* 802AEE60 002AAAC0  39 00 02 FF */	li r8, 0x2ff
/* 802AEE64 002AAAC4  7C 09 03 A6 */	mtctr r0
lbl_802AEE68:
/* 802AEE68 002AAAC8  54 8B 06 3E */	clrlwi r11, r4, 0x18
/* 802AEE6C 002AAACC  54 8A 15 BA */	rlwinm r10, r4, 2, 0x16, 0x1d
/* 802AEE70 002AAAD0  55 66 0F FE */	srwi r6, r11, 0x1f
/* 802AEE74 002AAAD4  54 80 07 FE */	clrlwi r0, r4, 0x1f
/* 802AEE78 002AAAD8  7D 6B 50 50 */	subf r11, r11, r10
/* 802AEE7C 002AAADC  54 8C FE 7E */	rlwinm r12, r4, 0x1f, 0x19, 0x1f
/* 802AEE80 002AAAE0  54 8A 0D FA */	rlwinm r10, r4, 1, 0x17, 0x1d
/* 802AEE84 002AAAE4  7C 00 32 78 */	xor r0, r0, r6
/* 802AEE88 002AAAE8  7D 65 5A 14 */	add r11, r5, r11
/* 802AEE8C 002AAAEC  7D 6C 58 50 */	subf r11, r12, r11
/* 802AEE90 002AAAF0  7D 4A 62 14 */	add r10, r10, r12
/* 802AEE94 002AAAF4  7C 06 00 51 */	subf. r0, r6, r0
/* 802AEE98 002AAAF8  8B EB 00 00 */	lbz r31, 0(r11)
/* 802AEE9C 002AAAFC  7C C5 52 14 */	add r6, r5, r10
/* 802AEEA0 002AAB00  89 8B 00 01 */	lbz r12, 1(r11)
/* 802AEEA4 002AAB04  8B C6 00 02 */	lbz r30, 2(r6)
/* 802AEEA8 002AAB08  40 82 00 44 */	bne lbl_802AEEEC
/* 802AEEAC 002AAB0C  80 C3 00 00 */	lwz r6, 0(r3)
/* 802AEEB0 002AAB10  54 80 1D 78 */	rlwinm r0, r4, 3, 0x15, 0x1c
/* 802AEEB4 002AAB14  7F EB 07 34 */	extsh r11, r31
/* 802AEEB8 002AAB18  57 CA 25 AE */	rlwinm r10, r30, 4, 0x16, 0x17
/* 802AEEBC 002AAB1C  7D 6A 53 78 */	or r10, r11, r10
/* 802AEEC0 002AAB20  7C C6 02 14 */	add r6, r6, r0
/* 802AEEC4 002AAB24  B1 46 00 08 */	sth r10, 8(r6)
/* 802AEEC8 002AAB28  7D 8A 07 34 */	extsh r10, r12
/* 802AEECC 002AAB2C  57 C6 15 AE */	rlwinm r6, r30, 2, 0x16, 0x17
/* 802AEED0 002AAB30  7D 4A 33 78 */	or r10, r10, r6
/* 802AEED4 002AAB34  80 C3 00 00 */	lwz r6, 0(r3)
/* 802AEED8


=-1;jj<2;jj++) {
                            if(seen[j+jj]) {
                                const seenMaybe = seen[j+jj][i+ii];
                                if (seenMaybe && this.lightPasses(seenMaybe)) {
                                    toSee.push({
                                        tile:seenMaybe.getNeighbour([-ii,-jj]),
                                        displayPosition:[
                                            i-this.range,
                                            j-this.range,
                                        ]
                                    })
                                }
                            }
                        }
                    }
                }
            });
        });

        toSee.forEach(seeMe=>{
            if (seeMe.tile && !this.lightPasses(seeMe.tile)) {
                this.seeTile(seeMe.displayPosition, seeMe.tile);
            }
        });

    }
}import { isValidBST } from '../98.验证二叉搜索树'
import { TreeNode } from '../commons/Tree'

describe('98. Validate Binary Search Tree', () => {
  it('should work', () => {
    expect(isValidBST(TreeNode.fromArray([5, 1, 4, null, null, 3, 6])!))
      .toBe(false)
    expect(isValidBST(TreeNode.fromArray([2, 1, 3])!))
      .toBe(true)
    expect(isValidBST(TreeNode.fromArray([3, 2, 5, 1, null, 4, 7])!))
      .toBe(true)
    expect(isValidBST(TreeNode.fromArray([3, 2, 5, 1, null, 9, 7])!))
      .toBe(false)
  })
})
/* Generated from Java with JSweet 1.2.0 - http://www.jsweet.org */
namespace com.jme3.scene {
    import FastMath = com.jme3.math.FastMath;

    import Renderer = com.jme3.renderer.Renderer;

    import BufferUtils = com.jme3.util.BufferUtils;

    import NativeObject = com.jme3.util.NativeObject;

    import IOException = java.io.IOException;

    /**
     * A VertexBuffer contains a particular type of geometry
     * data used by {@link Mesh}es. Every VertexBuffer set on a Mesh
     * is sent as an attribute to the vertex shader to be processed.
     *

     * Several terms are used throughout the javadoc for this class, explanation:
     *

     *
Element - A single element is the largest individual object
     * inside a VertexBuffer. E.g. if the VertexBuffer is used to store 3D position
     * data, then an element will be a single 3D vector.

     *
Component - A component represents the parts inside an element.
     * For a 3D vector, a single component is one of the dimensions, X, Y or Z.

     *

     */
    export class VertexBuffer extends NativeObject implements Savable, java.lang.Cloneable {
        offset : number;

        lastLimit : number;

        stride : number;

        components : number;

        /**
         * derived from components * format.getComponentSize()
         */
        componentsLength : number;

        data : Buffer;

        usage : VertexBuffer.Usage;

        bufType : VertexBuffer.Type;

        format : VertexBuffer.Format;

        normalized : boolean;

        instanceSpan : number;

        dataSizeChanged : boolean;

        /**
         * Creates an empty, uninitialized buffer.
         * Must call setupData() to initialize.
         */
        public constructor(type? : any) {
            if(((typeof type === 'number') || type === null)) {
                let __args = Array.prototype.slice.call(arguments);
                super();
                this.offset = 0;
                this.lastLimit = 0;
                this.stride = 0;
                this.components = 0;
                this.componentsLength = 0;
                this.data = null;
                this.normalized = false;
                this.instanceSpan = 0;
                this.dataSizeChanged = false;
                (() => {
                    this.bufType = type;
                })();
            } else if(((typeof type === 'number') || type === null))


n=448ad700c9f893adf568cadaff497d7b&subscene=0)
  - [ ] [OpenAI布局社交平台，对标马斯克的 X；特斯拉或即将曝 Model Q 细节；苹果将分析用户数据提升AI能力 | 极客早知道](https://mp.weixin.qq.com/s?__biz=MTMwNDMwODQ0MQ==&mid=2653077659&idx=1&sn=27bab532b70d41243858f118f1cbf66a&subscene=0)
- 补天平台
  - [ ] [奖金限时翻倍 | 补天专属厂商“合合SRC”发布活动！](https://mp.weixin.qq.com/s?__biz=MzI2NzY5MDI3NQ==&mid=2247508125&idx=1&sn=a63b4fb3dfd5fc1dc3c261cee592ba5b&subscene=0)
- 默安科技
  - [ ] [【落地有声】专栏第三期：开发安全建设融入业务场景的重难点解析与应对](https://mp.weixin.qq.com/s?__biz=MzIzODQxMjM2NQ==&mid=2247500737&idx=1&sn=573d5237bfbceadaf32b34a96cbf692b&subscene=0)
- 数世咨询
  - [ ] [SaaS 安全要点：如何降低云应用程序的风险？](https://mp.weixin.qq.com/s?__biz=MzkxNzA3MTgyNg==&mid=2247538498&idx=1&sn=18bb373ca9bf03a7d31969f926fad938&subscene=0)
- 安全圈
  - [ ] [【安全圈】“五一”购票高峰，12306崩了：网友反映抢不到票](https://mp.weixin.qq.com/s?__biz=MzIzMzE4NDU1OQ==&mid=2652069101&idx=1&sn=c8deb4b52b800fb059e1feec16b25688&subscene=0)
- 火绒安全
  - [ ] [信息盗取的隐性威胁：Rhadamanthys木马无痕窃密](https://mp.weixin.qq.com/s?__biz=MzI3NjYzMDM1Mg==&mid=2247524902&idx=1&sn=901d1ad1f7125f83dfded17b42a5304e&subscene=0)
  - [ ] [诚邀渠道合作伙伴共启新征程](https://mp.weixin.qq.com/s?__biz=MzI3NjYzMDM1Mg==&mid=2247524902&idx=2&sn=285f27ec2f776492f8dbfff41ce12775&subscene=0)
- 百度安全应急响应中心
  - [ ] [八大年度奖项揭晓！2024 BSRC年度盛典沙龙圆满举办](https://mp.weixin.qq.com/s?__biz=MzA4ODc0MTIwMw==&mid=2652542593&idx=1&sn=b3442064198e7298271964449691be62&subscene=0)
- 深信服千里目安全技术中心
  - [ ]


     })
        .collect();

    let pro_error_2 = pre::ProcessError::new(&times, values)
        .set_title("increasing error")
        .to_owned();

    let mut comparison = pro_error_1 + pro_error_2;

    comparison
        .set_title("Various processes with error margin")
        .set_xlabel("index")
        .set_ylabel("value")
        .plot("my_identifier")?;

    Ok(())
}
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::{
    app::MessageInternal,
    message::Message,
    view::{
        scenic_present, scenic_present_done,
        strategies::base::{ViewStrategy, ViewStrategyPtr},
        ScenicResources, ViewAssistantContext, ViewAssistantPtr, ViewDetails,
    },
};
use async_trait::async_trait;
use fidl_fuchsia_ui_views::ViewToken;
use fuchsia_scenic::SessionPtr;
use fuchsia_zircon::{ClockId, Time};
use futures::channel::mpsc::UnboundedSender;

pub(crate) struct ScenicViewStrategy {
    scenic_resources: ScenicResources,
}

impl ScenicViewStrategy {
    pub(crate) fn new(
        session: &SessionPtr,
        view_token: ViewToken,
        app_sender: UnboundedSender<MessageInternal>,
    ) -> ViewStrategyPtr {
        let scenic_resources = ScenicResources::new(session, view_token, app_sender);
        Box::new(ScenicViewStrategy { scenic_resources })
    }

    fn make_view_assistant_context(&self, view_details: &ViewDetails) -> ViewAssistantContext<'_> {
        ViewAssistantContext {
            key: view_details.key,
            logical_size: view_details.logical_size,
            size: view_details.physical_size,
            metrics: view_details.metrics,
            presentation_time: Time::get(ClockId::Monotonic),
            messages: Vec::new(),
            scenic_resources: Some(&self.scenic_resources),
            canvas: None,
            buffer_count: None,
            wait_event: None,
            image_id: 0,
            image_index: 0,
        }
    }
}

#[async_trait(?Send)]
impl ViewStrategy for ScenicViewStrategy {
    fn setup(&mut self, view_details: &ViewDetails, view_assistant: &mut ViewAssistantPtr) {
        let context = self.make_view_assistant_context(view_details);
        view_assistant.setup(&context).unwrap_or_else(|e| panic!("Setup error: {:?}", e));
    }

    async fn update(&mut self, view_details: &ViewDetails, view_assistant: &mut ViewAssistantPtr) {
        let context = self.make_view_assistant_context(view_details);
        view_assistant.update(&context).unwrap_or_else(|e| panic!("Update error: {:?}", e));
    }

    fn present(&mut self, view_details: &ViewDetails) {
        scenic_present(&mut self.scenic_resources, view_details.key);
    }

    fn present_done(
        &mut self,
        _view_details: &ViewDetails,
        _view_assistant: &mut ViewAssistantPtr,
    ) {
        scenic_present_done(&mut self.scenic_resources);
    }

    fn handle_input_event(
        &mut self,
        view_details: &ViewDetails,
        view_assistant: &mut ViewAssistantPtr,
        event: &fidl_fuchsia_ui_input::InputEvent,
    ) -> Vec<Message> {
        let mut context = self.make_view_assistant_context(view_details);

        view_assistant
            .handle_input_event(&mut context, &event)
            .unwrap_or_else(|e| eprintln!("handle_event: {:?}", e));

        context.messages


event: InventoryClickEvent) {
        withHolder(event.inventory.holder) {
            val valueHandler = ValueHandler()
            runtime.interactionHandler.onClick(event, valueHandler)
            event.isCancelled = true

            runtime.viewportl.scafall.scheduler.syncTask(runtime.viewportl.scafall.corePlugin) {
                (runtime.reactiveSource as ReactiveGraph).runEffects()
            }
        }
    }

    @EventHandler(priority = EventPriority.HIGH)
    fun onItemDrag(event: InventoryDragEvent) {
        withHolder(event.inventory.holder) {
            if (event.rawSlots.stream()
                    .anyMatch { rawSlot -> event.view.getInventory(rawSlot) != event.view.topInventory }
            ) {
                event.isCancelled = true
                return@withHolder
            }
            if (runtime.window == null) return@withHolder
            val valueHandler = ValueHandler()
            runtime.interactionHandler.onDrag(event, valueHandler)

            if (!event.isCancelled) {
                runtime.viewportl.scafall.scheduler.syncTask(runtime.viewportl.scafall.corePlugin) {
                    for (rawSlot in event.rawSlots) {
                        if (rawSlot < event.inventory.size) {
                            valueHandler.callSlotValueUpdate(rawSlot, event.inventory.getItem(rawSlot))
                        }
                    }
                }
            }

            runtime.viewportl.scafall.scheduler.syncTask(runtime.viewportl.scafall.corePlugin) {
                (runtime.reactiveSource as ReactiveGraph).runEffects()
            }
        }
    }

    @EventHandler(priority = EventPriority.HIGH)
    fun onClose(event: InventoryCloseEvent) {
        withHolder(event.inventory.holder) {
            runtime.window?.apply { close() }
        }
    }
}

data class ValueHandler(
    val listeners: Multimap<Int, (ItemStack?) -> Unit> = Multimaps.newListMultimap(mutableMapOf()) { mutableListOf() }
) {

    fun callSlotValueUpdate(slot: Int, item: ItemStack?) {
        listeners[slot].forEach {
            it(item)
        }
    }

}

data class Slot(
    val index: Int
)package top.yogiczy.mytv.data.utils

/**
 * 常量
 */
object Constants {
    /**
     * 应用 标题
     */
    const val APP_TITLE = "我的电视"

    /**
     * 应用 代码仓库
     */
    const val APP_REPO = "https://github.com/yaoxieyoulei/mytv-android"

    /**
     * IPTV源地址
     */
    const val IPTV_SOURCE_URL =
        "https://mirror.ghproxy.com/https://raw.githubusercontent.com/fanmingming/live/main/tv/m3u/ipv6.m3u"

    /**
     * IPTV源缓存时间（毫秒）
     */
    const val IPTV_SOURCE_CACHE_TIME = 1000 * 60 * 60 * 24L // 24小时

    /**
     * 节目单XML地址


tainer:t}):t={},a(t)?t={container:t}:t="string"==typeof(e=t).nodeName&&"function"==typeof e.appendChild&&"function"==typeof e.getBoundingClientRect?{container:t}:function(t){return"function"==typeof t.drawArrays||"function"==typeof t.drawElements}(t)?{gl:t}:n(t,{container:"container target element el canvas holder parent parentNode wrapper use ref root node",gl:"gl context webgl glContext",attrs:"attributes attrs contextAttributes",pixelRatio:"pixelRatio pxRatio px ratio pxratio pixelratio",width:"w width",height:"h height"},!0),t.pixelRatio||(t.pixelRatio=r.pixelRatio||1),t.gl)return t.gl;if(t.canvas&&(t.container=t.canvas.parentNode),t.container){if("string"==typeof t.container){var s=document.querySelector(t.container);if(!s)throw Error("Element "+t.container+" is not found");t.container=s}a(t.container)?(t.canvas=t.container,t.container=t.canvas.parentNode):t.canvas||(t.canvas=o(),t.container.appendChild(t.canvas),i(t))}else if(!t.canvas){if("undefined"==typeof document)throw Error("Not DOM environment. Use headless-gl.");t.container=document.body||document.documentElement,t.canvas=o(),t.container.appendChild(t.canvas),i(t)}return t.gl||["webgl","experimental-webgl","webgl-experimental"].some((function(e){try{t.gl=t.canvas.getContext(e,t.attrs)}catch(t){}return t.gl})),t.gl}}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"pick-by-alias":248}],222:[function(t,e,r){e.exports=function(t){"string"==typeof t&&(t=[t]);for(var e=[].slice.call(arguments,1),r=[],n=0;n<t.length-1;n++)r.push(t[n],e[n]||"");return r.push(t[n]),r.join("")}},{}],223:[function(t,e,r){(function(r){(function(){"use strict";var n,i=t("is-browser");n="function"==typeof r.matchMedia?!r.matchMedia("(hover: none)").matches:i,e.exports=n}).call(this)}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"is-browser":227}],224:[function(t,e,r){"use strict";var n=t("is-browser");e.exports=n&&function(){var t=!1;try{var e=Object.defineProperty({},"passive",{get:function(){t=!0}});window.addEventListener("test",null,e),window.removeEventListener("test",null,e)}catch(e){t=!1}return t}()},{"is-browser":227}],225:[function(t,e,r){
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
r.read=function(t,e,r,n,i){var a,o,s=8*i-n-1,l=(1<<s)-1,c=l>>1,u=-7,f=r?i-1:0,h=r?-1:1,p=t[e+f];for(f+=h,a=p&(1<<-u)-1,p>>=-u,u+=s;u>0;a=256*a+t[e+f],f+=h,u-=8);for(o=a&(1<<-u)-1,a>>=-u,u+=n;u>0;o=256*o+t[e+f],f+=h,u-=8);if(0===a)a=1-c;else{if(a===l)return o?NaN:1/


export type Restaurant_Chain_Arr_Rel_Insert_Input = {
  data: Array<Restaurant_Chain_Insert_Input>;
  on_conflict?: Maybe<Restaurant_Chain_On_Conflict>;
};

/** aggregate avg on columns */
export type Restaurant_Chain_Avg_Fields = {
  __typename?: 'restaurant_chain_avg_fields';
  id?: Maybe<Scalars['Float']>;
};

/** order by avg() on columns of table "restaurant_chain" */
export type Restaurant_Chain_Avg_Order_By = {
  id?: Maybe<Order_By>;
};

/** Boolean expression to filter rows from the table "restaurant_chain". All fields are combined with a logical 'AND'. */
export type Restaurant_Chain_Bool_Exp = {
  _and?: Maybe<Array<Maybe<Restaurant_Chain_Bool_Exp>>>;
  _not?: Maybe<Restaurant_Chain_Bool_Exp>;
  _or?: Maybe<Array<Maybe<Restaurant_Chain_Bool_Exp>>>;
  id?: Maybe<Int_Comparison_Exp>;
  name?: Maybe<String_Comparison_Exp>;
  restaurants?: Maybe<Restaurant_Bool_Exp>;
};

/** unique or primary key constraints on table "restaurant_chain" */
export enum Restaurant_Chain_Constraint {
  /** unique or primary key constraint */
  PkD2a509385c30a3ea44dc032009e = 'PK_d2a509385c30a3ea44dc032009e'
}

/** input type for incrementing integer column in table "restaurant_chain" */
export type Restaurant_Chain_Inc_Input = {
  id?: Maybe<Scalars['Int']>;
};

/** input type for inserting data into table "restaurant_chain" */
export type Restaurant_Chain_Insert_Input = {
  id?: Maybe<Scalars['Int']>;
  name?: Maybe<Scalars['String']>;
  restaurants?: Maybe<Restaurant_Arr_Rel_Insert_Input>;
};

/** aggregate max on columns */
export type Restaurant_Chain_Max_Fields = {
  __typename?: 'restaurant_chain_max_fields';
  id?: Maybe<Scalars['Int']>;
  name?: Maybe<Scalars['String']>;
};

/** order by max() on columns of table "restaurant_chain" */
export type Restaurant_Chain_Max_Order_By = {
  id?: Maybe<Order_By>;
  name?: Maybe<Order_By>;
};

/** aggregate min on columns */
export type Restaurant_Chain_Min_Fields = {
  __typename?: 'restaurant_chain_min_fields';
  id?: Maybe<Scalars['Int']>;
  name?: Maybe<Scalars['String']>;
};

/** order by min() on columns of table "restaurant_chain" */
export type Restaurant_Chain_Min_Order_By = {
  id?: Maybe<Order_By>;
  name?: Maybe<Order_By>;
};

/** response of any mutation on the table "restaurant_chain" */
export type Restaurant_Chain_Mutation_Response = {
  __typename?: 'restaurant_chain_mutation_response';
  /** number of affected rows by the mutation */
  affected_rows: Scalars['Int'];
  /** data of the affected rows by the mutation */
  returning: Array<Restaurant_Chain>;
};

/** input type for inserting object relation for remote table "restaurant_chain" */
export type Restaurant_Chain_Obj_Rel_Insert_Input = {
  data: Restaurant_Chain_Insert_Input;
  on_conflict?: Maybe<Restaurant_Chain_On_Conflict>;
};

/** on conflict condition type for table "restaurant_chain" */
export type Restaurant_Chain_On_Conflict = {
  constraint: Restaurant_Chain_Constraint;
  update_columns: Array<Restaurant_Chain_Update_Column>;
  where?: Maybe<Restaurant_Chain_Bool_Exp>;
};

/** ordering options when selecting data from "restaurant_chain" */
export type Restaurant_Chain_Order_By = {
  id?:


using System;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Threading;
using WaveTracker.Midi.Interop.Linux;

namespace WaveTracker.Midi {
    /// <summary>
    /// Represents a MIDI in device
    /// </summary>
    [SupportedOSPlatform("Linux")]
    public class MidiInLinux : IMidiIn, IDisposable {
        private bool disposeIsRunning = false; // true while the Dispose() method run.
        private bool disposed = false;

        private int inPort;
        private int outClient;
        private int outPort;

        private bool isListening;

        private Thread listenThread;

        private static nint __seqHandle = 0;
        private static nint inClient;

        private static nint SeqHandle {
            get {
                if (__seqHandle == 0) {
                    unsafe {
                        nint seqHandle;
                        Alsa.snd_seq_open(&seqHandle, "default", Alsa.SND_SEQ_OPEN_INPUT, Alsa.SND_SEQ_NONBLOCK);
                        Alsa.snd_seq_set_client_name(seqHandle, "WaveTracker MIDI");
                        __seqHandle = seqHandle;
                        inClient = Alsa.snd_seq_client_id(seqHandle);
                        return seqHandle;
                    }
                }
                else {
                    return __seqHandle;
                }
            }
        }

        /// <summary>
        /// Called when a MIDI message is received
        /// </summary>
        public event EventHandler<MidiInMessageEventArgs> MessageReceived;

        /// <summary>
        /// An invalid MIDI message
        /// </summary>
        public event EventHandler<MidiInMessageEventArgs> ErrorReceived;

        /// <summary>
        /// Called when a Sysex MIDI message is received
        /// </summary>
        public event EventHandler<MidiInSysexMessageEventArgs> SysexMessageReceived;

        /// <summary>
        /// Opens a specified MIDI in device
        /// </summary>
        public MidiInLinux(int outClient, int outPort) {
            unsafe {
                // TODO: error handling?

                uint caps = Alsa.SND_SEQ_PORT_CAP_WRITE | Alsa.SND_SEQ_PORT_CAP_SUBS_WRITE;
                this.inPort = Alsa.snd_seq_create_simple_port(SeqHandle, "input", caps, Alsa.SND_SEQ_PORT_TYPE_APPLICATION);

                Alsa.snd_seq_connect_from(SeqHandle, inPort, outClient, outPort);
            }
        }

        /// <summary>
        /// Closes this MIDI in device
        /// </summary>
        public void Dispose() {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        /// <summary>
        /// Start the MIDI in device
        /// </summary>
        public void Start() {
            isListening = true;
            listenThread = new Thread(listenLoop);
            listenThread.Start();
        }

        /// <summary>
        /// Stop the MIDI in device
        /// </summary>
        public void Stop() {
            isListening = false;
            listenThread?.Join();
        }

        private void listenLoop() {
            while (true) {
                unsafe {
                    Alsa.snd_seq_event* seqEvent = null;
                    int pollStatus = Alsa.snd_seq_event_input(SeqHandle, &seqEvent);
                    if (pollStatus == -Alsa.EAGAIN || seqEvent == null) {
                        if (!isListening)
                            break;
                        Thread.Sleep(1);


 set = getSmallSet();
    int count = 0;
    for (final i in set) {
      if (i < 4) continue;
      count += i;
    }
    Expect.equals(4, count);
  }

  static void testClosure() {
    Set<int> set = getSmallSet();
    List<Function> closures = new List(set.length);
    int index = 0;
    for (var i in set) {
      closures[index++] = () => i;
    }

    Expect.equals(index, set.length);
    Expect.equals(7, closures[0]() + closures[1]() + closures[2]());
  }
}

main() {
  ForInTest.testMain();
}
// Copyright (c) 2011, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import "package:expect/expect.dart";

main() {
  testLowerUpper();
  testSpecialCases();
}

void testLowerUpper() {
  var a = "Stop! Smell the Roses.";
  var allLower = "stop! smell the roses.";
  var allUpper = "STOP! SMELL THE ROSES.";
  Expect.equals(allUpper, a.toUpperCase());
  Expect.equals(allLower, a.toLowerCase());
}

void testSpecialCases() {
  // Letters in Latin-1 where the upper case is not in Latin-1.

  // German sharp s. Upper case variant is "SS".
  Expect.equals("SS", "\xdf".toUpperCase());                  /// 01: ok
  Expect.equals("\xdf", "\xdf".toLowerCase());
  Expect.equals("ss", "\xdf".toUpperCase().toLowerCase());    /// 01: continued
  // Micro sign (not same as lower-case Greek letter mu, U+03BC).
  Expect.equals("\u039c", "\xb5".toUpperCase());              /// 02: ok
  Expect.equals("\xb5", "\xb5".toLowerCase());
  Expect.equals("\u03Bc",                                     /// 02: continued
                "\xb5".toUpperCase().toLowerCase());          /// 02: continued
  // Small letter y diaresis.
  Expect.equals("\u0178", "\xff".toUpperCase());              /// 03: ok
  Expect.equals("\xff", "\xff".toLowerCase());
  Expect.equals("\xff", "\xff".toUpperCase().toLowerCase());  /// 03: continued
  // Zero.
  Expect.equals("\x00", "\x00".toLowerCase());
  Expect.equals("\x00", "\x00".toUpperCase());

  // Test all combinations of ordering of lower-case, upper-case and
  // special-when-upper-cased characters.
  Expect.equals("AA\u0178", "Aa\xff".toUpperCase());          /// 03: continued
  Expect.equals("AA\u0178", "aA\xff".toUpperCase());          /// 03: continued
  Expect.equals("A\u0178A", "A\xffa".toUpperCase());          /// 03: continued
  Expect.equals("A\u0178A", "a\xffA".toUpperCase());          /// 03: continued
  Expect.equals("\u0178AA", "\xffAa".toUpperCase());          /// 03: continued
  Expect.equals("\u0178AA", "\xffaA".toUpperCase());          /// 03: continued

  Expect.equals("aa\xff", "Aa\xff".toLowerCase());
  Expect.equals("aa\xff", "aA\xff".toLowerCase());
  Expect.equals("a\xffa", "A\xffa".toLowerCase());
  Expect.equals("a\xffa", "a\xffA".toLower


ng build/app/outputs/flutter-apk/$apk...',
    );

    _findNextMatcherInList(
      stdout,
      (String line) => line.contains('Quit (terminate the application on the device).'),
      'q Quit (terminate the application on the device)',
    );

    _findNextMatcherInList(
      stdout,
      (String line) => line == 'Application finished.',
      'Application finished.',
    );

    return TaskResult.success(null);
  }
}

class WindowsRunOutputTest extends DesktopRunOutputTest {
  WindowsRunOutputTest(
    super.testDirectory,
    super.testTarget, {
    required super.release,
    super.allowStderr = false,
  });

  final String arch = Abi.current() == Abi.windowsX64 ? 'x64' : 'arm64';

  static final RegExp _buildOutput = RegExp(
    r'Building Windows application\.\.\.\s*\d+(\.\d+)?(ms|s)',
    multiLine: true,
  );
  static final RegExp _builtOutput = RegExp(
    r'Built build\\windows\\(x64|arm64)\\runner\\(Debug|Release)\\\w+\.exe( \(\d+(\.\d+)?MB\))?',
  );

  @override
  void verifyBuildOutput(List<String> stdout) {
    _findNextMatcherInList(stdout, _buildOutput.hasMatch, 'Building Windows application...');

    final String buildMode = release ? 'Release' : 'Debug';
    _findNextMatcherInList(stdout, (String line) {
      if (!_builtOutput.hasMatch(line) || !line.contains(buildMode)) {
        return false;
      }

      return true;
    }, '√ Built build\\windows\\$arch\\runner\\$buildMode\\ui.exe');
  }
}

class DesktopRunOutputTest extends RunOutputTask {
  DesktopRunOutputTest(
    super.testDirectory,
    super.testTarget, {
    required super.release,
    this.allowStderr = false,
  });

  /// Whether `flutter run` is expected to produce output on stderr.
  final bool allowStderr;

  @override
  bool isExpectedStderr(String line) => allowStderr;

  @override
  TaskResult verify(List<String> stdout, List<String> stderr) {
    _findNextMatcherInList(
      stdout,
      (String line) =>
          line.startsWith('Launching $testTarget on ') &&
          line.endsWith(' in ${release ? 'release' : 'debug'} mode...'),
      'Launching $testTarget on',
    );

    verifyBuildOutput(stdout);

    _findNextMatcherInList(
      stdout,
      (String line) => line.contains('Quit (terminate the application on the device).'),
      'q Quit (terminate the application on the device)',
    );

    _findNextMatcherInList(
      stdout,
      (String line) => line == 'Application finished.',
      'Application finished.',
    );

    return TaskResult.success(null);
  }

  /// Verify the output from `flutter run`'s build step.
  void verifyBuildOutput(List<String> stdout) {}
}

/// Test that the output of `flutter run` is expected.
abstract class RunOutputTask {
  RunOutputTask(this.testDirectory, this.testTarget, {required this.release});

  static final RegExp _engineLogRegex = RegExp(r'\[(VERBOSE|INFO|WARNING|ERROR|FATAL):.+\(\d+\)\]');

  /// The directory where the app under test is defined.
  final String testDirectory;

  /// The main entry-point file of the application, as run on the device.
  final String testTarget;

  /// Whether to run the app in release mode.
  final bool release;

  Future<TaskResult> call() {
    return inDirectory<TaskResult>(testDirectory, () async {
      final Device device = await devices.workingDevice;
      await


locity Tuning](/config_rover/velocity_tuning.md)
      - [Position Tuning](/config_rover/position_tuning.md)
    - [Complete Vehicles](/complete_vehicles_rover/index.md)
      - [Aion Robotics R1](/complete_vehicles_rover/aion_r1.md)
  - [Submarines (experimental)](/frames_sub/index.md)
    - [BlueROV2](/frames_sub/bluerov2.md)
  - [Airframes Reference](/airframes/airframe_reference.md)
  - [Assembly (Generic-Vehicle)](/assembly/index.md)
  - [Flight Modes](/flight_modes/index.md)
    - [Return Mode (Generic/All)](/flight_modes/return.md)
    - [Offboard Mode (Generic/All)](/flight_modes/offboard.md)

- [Розробка](/development/development.md)
  - [Початок роботи](/dev_setup/getting_started.md)
    - [Рекомендоване залізо та налаштування](/dev_setup/config_initial.md)
    - [Інсталяція тулчейну](/dev_setup/dev_env.md)
      - [Налаштування під Ubuntu](/dev_setup/dev_env_linux_ubuntu.md)
      - [Налаштування під Windows](/dev_setup/dev_env_windows_wsl.md)
      - [Налаштування під MacOS](/dev_setup/dev_env_mac.md)
      - [Visual Studio Code IDE](/dev_setup/vscode.md)
      - [QGC Daily Build](/dev_setup/qgc_daily_build.md)
    - [Збірка коду](/dev_setup/building_px4.md)
    - [Пишемо ваш перший додаток](/modules/hello_sky.md)
    - [Шаблон додатку/модуля](/modules/module_template.md)
  - [Поняття](/concept/index.md)
    - [Архітектура системи PX4](/concept/px4_systems_architecture.md)
    - [Архітектура польотного стеку PX4](/concept/architecture.md)
      - [Діаграми контролера](/flight_stack/controller_diagrams.md)
    - [Параметри та налаштування](/advanced/parameters_and_configurations.md)
    - [Інтерфейс подій](/concept/events_interface.md)
    - [Flight Modes](/concept/flight_modes.md)
    - [Польотні завдання](/concept/flight_tasks.md)
    - [Control Allocation](/concept/control_allocation.md)
    - [PWM limit state machine](/concept/pwm_limit.md)
    - [Запуск системи](/concept/system_startup.md)
    - [SD Card Layout](/concept/sd_card_layout.md)
  - [Моделювання](/simulation/index.md)
    - [Симуляції Gazebo](/sim_gazebo_gz/index.md)
      - [Vehicles](/sim_gazebo_gz/vehicles.md)
        - [Advanced Lift Drag Tool](/sim_gazebo_gz/tools_avl_automation.md)
      - [Worlds](/sim_gazebo_gz/worlds.md)
      - [Plugins](/sim_gazebo_gz/plugins.md)
      - [Gazebo Models Repository](/sim_gazebo_gz/gazebo_models.md)
      - [Багатотранспортний Sim](/sim


/compress the blocks.
    Zlib = 2,
    /// Use the [`lz4_flex`] crate to de/compress the blocks.
    Lz4 = 3,
    /// Use the [`zstd`] crate to de/compress the blocks.
    Zstd = 4,
    /// Use the [`snap`] crate to de/compress the blocks.
    Snappy = 5,
}

impl CompressionType {
    pub(crate) fn from_u8(value: u8) -> Option<CompressionType> {
        match value {
            0 => Some(CompressionType::None),
            1 => Some(CompressionType::SnappyPre05),
            2 => Some(CompressionType::Zlib),
            3 => Some(CompressionType::Lz4),
            4 => Some(CompressionType::Zstd),
            5 => Some(CompressionType::Snappy),
            _ => None,
        }
    }
}

impl FromStr for CompressionType {
    type Err = InvalidCompressionType;

    fn from_str(name: &str) -> Result<Self, Self::Err> {
        match name {
            "snappy-pre-0.5" => Ok(CompressionType::SnappyPre05),
            "zlib" => Ok(CompressionType::Zlib),
            "lz4" => Ok(CompressionType::Lz4),
            "zstd" => Ok(CompressionType::Zstd),
            "snappy" => Ok(CompressionType::Snappy),
            _ => Err(InvalidCompressionType),
        }
    }
}

impl Default for CompressionType {
    fn default() -> CompressionType {
        CompressionType::None
    }
}

/// An invalid compression type have been read and the block can't be de/compressed.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct InvalidCompressionType;

impl fmt::Display for InvalidCompressionType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("Invalid compression type")
    }
}

impl Error for InvalidCompressionType {}

pub fn decompress<R>(typ: CompressionType, mut data: R, out: &mut Vec<u8>) -> io::Result<()>
where
    R: io::Read,
{
    match typ {
        CompressionType::None => data.read_to_end(out).map(drop),
        CompressionType::Zlib => zlib_decompress(data, out),
        CompressionType::SnappyPre05 => snappy_pre_05_decompress(data, out),
        CompressionType::Lz4 => lz4_decompress(data, out),
        CompressionType::Zstd => zstd_decompress(data, out),
        CompressionType::Snappy => snappy_decompress(data, out),
    }
}

pub fn compress(type_: CompressionType, level: u32, data: &[u8]) -> io::Result<Cow<[u8]>> {
    match type_ {
        CompressionType::None => Ok(Cow::Borrowed(data)),
        CompressionType::Zlib => zlib_compress(data, level),
        CompressionType::SnappyPre05 => snappy_pre_05_compress(data, level),
        CompressionType::Lz4 => lz4_compress(data, level),
        CompressionType::Zstd => zstd_compress(data, level),
        CompressionType::Snappy => snappy_compress(data, level),
    }
}

// --------- zlib ---------

#[cfg(feature = "zlib")]
fn zlib_decomp


bool updateShouldNotify(PhotoViewGestureDetectorScope oldWidget) {
    return axis != oldWidget.axis;
  }
}
import 'dart:io';

import 'package:flutter/material.dart';

import 'unzip_mamager.dart';

///
typedef UnzipLayoutBuilder = Widget Function(
    BuildContext context, File file);

///
class UnzipContainer extends StatefulWidget {
  ///
  final String fileKey;

  ///
  final String filePath;

  ///
  final String findFileName;

  ///
  final UnzipLayoutBuilder builder;
  ///
  final Widget initChild;

  ///
  UnzipContainer({
    @required this.fileKey,
    @required this.filePath,
    @required this.findFileName,
    @required this.builder,
    this.initChild,
  });

  @override
  State<UnzipContainer> createState() => _UnzipContainerState();
}

class _UnzipContainerState extends State<UnzipContainer> {
  String get fileKey => widget.fileKey;

  String get zipPath => widget.filePath;

  String get findFileName => widget.findFileName;

  UnzipLayoutBuilder get builder => widget.builder;

  Widget get initChild => widget.initChild;

  bool unzipFinish = false;
  String unzipFilePath = "";

  @override
  void initState() {
    super.initState();
    _unzip();
  }

  ///
  void _unzip() async {
    UnzipManager.getInstance().toUnzip(zipPath, fileKey, findFileName, (unzipFilePath) {
      if(mounted){
        this.unzipFilePath = unzipFilePath;
        setState(() {
          unzipFinish = true;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return unzipFinish ? builder(context, File(unzipFilePath)) :  initChild ?? Container();
  }
}
import 'dart:async';
import 'dart:math';
import 'dart:ui';

import 'package:flutter/material.dart';

typedef BigImagesPopCallback = void Function();

typedef BigImagesBuilder<T> = Widget Function(
  BuildContext context
//     , {
//   // 是否正在执行动画
//   bool widgetMove,
//   // 更新需要返回的值
//   Function(T) valueUpdate,
//   // 关闭时候的rect
//   Function(Rect) rectUpdate,
// }

);

typedef BigImagesExtraBuilder = Widget Function(
  BuildContext context, {
  Function popFunc,
});

class BigImagesContainerCopy<T> extends StatefulWidget {
  final BigImagesBuilder<T> builder;

  final BigImagesPopCallback pop;

  final Rect startRect;

  /// 需要pop时候的frame
  final List<Rect> endRectList;

  final BigImagesExtraBuilder extraBuilder;

  BigImagesContainerCopy({
    this.builder,
    this.pop,
    this.startRect,
    this.endRectList,
    this.extraBuilder,
    Key key,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() => BigImagesContainerState<T>();
}

class BigImagesContainerState<T> extends State<BigImagesContainerCopy<T>>
    with SingleTickerProviderStateMixin {
  /// push和pop动画
  Animation<double> _animation;
  AnimationController _controller;
  AnimationController get controller => _controller;
  // push和pop的动画
  bool _inPushAnimate = false;
  bool _inPopAnimate = false;

  // 拖动
  bool _inDrag = false;
  bool get inDrag => _inDrag;
  double _dragDisX = 0.0;
  double _dragDisY = 0.0;

  // 拖动释放之后的动画
  bool _popAnimateAfterDrag = false;
  bool _resumeAnimateAfterDrag = false;
  double _dargEndTop;
  double _dargEndLeft;
  double _dargEndWidth;


(||)`具有内置的标识元素。`&&`操作符为true，`||`操作符为false。

对于逗号表达式来说，其标识元素为`void()`。

为了更好的理解这特性，让我们可以使用这个特性来实现的辅助函数。

**匹配范围内的单个元素**

如何告诉函数在一定范围内，我们提供的可变参数至少包含一个值：

```c++
template <typename R, typename ... Ts>
auto matches(const R& range, Ts ... ts)
{
	return (std::count(std::begin(range), std::end(range), ts) + ...);
}
```

辅助函数中使用STL中的`std::count`函数。这个函数需要三个参数：前两个参数定义了迭代器所要遍历的范围，第三个参数则用于与范围内的元素进行比较。`std::count`函数会返回范围内与第三个参数相同元素的个数。

在我们的折叠表达式中，我们也会将开始和结束迭代器作为确定范围的参数传入`std::count`函数。不过，对于第三个参数，我们将会每次从参数包中放入一个不同参数。最后，函数会将结果相加返回给调用者。

可以这样使用:

```c++
std::vector<int> v{1, 2, 3, 4, 5};

matches(v, 2, 5); // return 2
matches(v, 100, 200); // return 0
matches("abcdefg", 'x', 'y', 'z'); // return 0
matches("abcdefg", 'a', 'b', 'f'); // return 3
```

如我们所见，`matches`辅助函数十分灵活——可以直接传入`vector`或`string`直接调用。其对于初始化列表也同样适用，也适用于`std::list`，`std::array`，`std::set`等STL容器的实例。

**检查集合中的多个插入操作是否成功**

我们完成了一个辅助函数，用于将任意数量参数插入`std::set`实例中，并且返回是否所有插入操作都成功完成：

```c++
template <typename T, typename ... Ts>
bool insert_all(T &set, Ts ... ts)
{
	return (set.insert(ts).second && ...);
}
```

那么这个函数如何工作呢？`std::set`的`insert`成员函数声明如下：

```c++
std::pair<iterator, bool> insert(const value_type& value);
```

手册上所述，当我们使用`insert`函数插入一个元素时，该函数会使用一个包含一个迭代器和一个布尔值的组对作为返回值。当该操作成功，那么迭代器指向的就是新元素


trol.NO_ONE
      } else if (id.isV1) {
        GroupAccessControl.ALL_MEMBERS
      } else {
        GroupAccessControl.ONLY_ADMINS
      }
    }

  /** Who is allowed to modify the attributes of this group, name/avatar/timer etc. */
  val attributesAccessControl: GroupAccessControl
    get() {
      return if (isV2Group) {
        if ((requireV2GroupProperties().decryptedGroup.accessControl ?: AccessControl()).attributes == AccessControl.AccessRequired.MEMBER) {
          GroupAccessControl.ALL_MEMBERS
        } else {
          GroupAccessControl.ONLY_ADMINS
        }
      } else if (isV1Group) {
        GroupAccessControl.NO_ONE
      } else {
        GroupAccessControl.ALL_MEMBERS
      }
    }

  val actionableRequestingMembersCount: Int by lazy {
    if (isV2Group && memberLevel(Recipient.self()) == GroupTable.MemberLevel.ADMINISTRATOR) {
      requireV2GroupProperties()
        .decryptedGroup
        .requestingMembers.size
    } else {
      0
    }
  }

  val gv1MigrationSuggestions: List<RecipientId> by lazy {
    if (!isActive || !isV2Group || isPendingMember(Recipient.self())) {
      emptyList()
    } else {
      unmigratedV1Members
        .filterNot { members.contains(it) }
        .map { Recipient.resolved(it) }
        .filter { it.isAutoMigratable() }
        .map { it.id }
    }
  }

  fun hasAvatar(): Boolean {
    return avatarId != 0L
  }

  fun requireV2GroupProperties(): GroupTable.V2GroupProperties {
    return v2GroupProperties ?: throw AssertionError()
  }

  fun isAdmin(recipient: Recipient): Boolean {
    return isV2Group && requireV2GroupProperties().isAdmin(recipient)
  }

  fun memberLevel(recipient: Recipient): GroupTable.MemberLevel {
    return if (isV2Group) {
      val memberLevel = requireV2GroupProperties().memberLevel(recipient.serviceId)
      if (recipient.isSelf && memberLevel == GroupTable.MemberLevel.NOT_A_MEMBER) {
        requireV2GroupProperties().memberLevel(Optional.ofNullable(SignalStore.account.pni))
      } else {
        memberLevel
      }
    } else if (isMms && recipient.isSelf) {
      GroupTable.MemberLevel.FULL_MEMBER
    } else if (members.contains(recipient.id)) {
      GroupTable.MemberLevel.FULL_MEMBER
    } else {
      GroupTable.MemberLevel.NOT_A_MEMBER
    }
  }

  /**
   * Whether or not the recipient is a pending member.
   */
  fun isPendingMember(recipient: Recipient): Boolean {
    if (isV2Group) {
      val serviceId = recipient.serviceId
      if (serviceId.isPresent) {
        return DecryptedGroupUtil.findPendingByServiceId(requireV2GroupProperties().decryptedGroup.pendingMembers, serviceId.get())
          .isPresent
      }
    }
    return false
  }

  companion object {
    /**
     * True if the user meets all the requirements to be auto-migrated, otherwise false.
     */
    private fun Recipient.isAutoMigratable(): Boolean {
      return hasServiceId && registered === RecipientTable.RegisteredState.REGISTERED && profileKey != null
    }
  }
}
/*
 * Copyright 2024 Signal Messenger, LLC
 * SPDX-License-Identifier: AGPL-3.0-only
 */

package org.thoughtcrime.securesms.database.helpers.migration

import android.app.Application
import org.signal.core.util.Stopwatch
import org.signal.core.util.logging.Log
import org.thoughtcrime.securesms.database.SQLiteDatabase

/**
 * A while back we added an account


ng: string; }[];
    currentWordIndex: number;

    constructor() {
        super();
        this.currentWordIndex = 0;
        this.wordRepo = [
            {
                word: "Balacobaco",
                meaning: "festa, qualidade ou beleza excepcionais."
            },
            {
                word: "Birosca",
                meaning: "pequena venda simples, misto de mercearia e bar.."
            },
            {
                word: "Bugiganga",
                meaning: "objeto de pouco ou nenhum valor, quinquilharia."
            },
            {
                word: "Bulhufas",
                meaning: "coisa alguma, nada."
            },
            {
                word: "Chumbrega",
                meaning: "de má qualidade, comum."
            },
            {
                word: "Espelunca",
                meaning: "lugar mal frequentado, sem asseio."
            },
            {
                word: "Faniquito",
                meaning: "chilique."
            },
            {
                word: "Galalau",
                meaning: "homem de estatura elevada, galalão."
            },
            {
                word: "Gororoba",
                meaning: "homem de estatura elevada, galalão."
            },
            {
                word: "Mequetrefe",
                meaning: "indivíduo sem importância, inútil."
            },
            {
                word: "Mixuruca",
                meaning: "de pouca qualidade, ruim."
            },
            {
                word: "Pindaíba",
                meaning: "condição de falta de dinheiro."
            },
            {
                word: "Sacripanta",
                meaning: "aquele que é velhaco, patife, indigno."
            },
            {
                word: "Salamaleque",
                meaning: "saudação cerimonial entre os muçulmanos, cumprimento exagerado (figurado informal)."
            },
            {
                word: "Serelepe",
                meaning: "esperto, vivo."
            },
            {
                word: "Songamonga",
                meaning: "mula de médico (origem), pessoa sonsa."
            },
            {
                word: "Tribufu",
                meaning: "pessoa feia."
            },
            {
                word: "Urucubaca",
                meaning: "má sorte, feitiço."
            },
            {
                word: "Xexelento",
                meaning: "de pouco valor."
            },
            {
                word: "Ziquizira",
                meaning: "má sorte, feitiço, doença vaga ou de causa não esclarecida."
            },
        ]
    }

    get() {
        return this.wordRepo[this.currentWordIndex++]
    }
}

export default WordChooserService;/// <reference path="../idl/IURI.ts" />
/// <reference path="../idl/IDataURI.ts" />
/// <reference path="../logger.ts" />
/// <reference path="../path/path.ts" />

module akra.uri {

	class URI implements IURI {
		private sScheme: string = null;
		private sUserinfo: string = null;
		private sHost: string = null;
		private nPort: uint = 0;
		private sPath: string = null


    /**
     * 构造Frameworks
     */
    private fun buildFrameworks(frameworkAssemblies: MutableList<FrameworkAssembly>): Set<String> {
        if (frameworkAssemblies.isNotEmpty()) {
            val values = hashSetOf<String>()
            val iterator = frameworkAssemblies.iterator()
            while (iterator.hasNext()) {
                val frameworkAssembly = iterator.next()
                values.add(getFrameworkValue(frameworkAssembly))
            }
            return values
        }
        return emptySet()
    }

    fun getFrameworkValue(frameworkAssembly: FrameworkAssembly): String {
        with(frameworkAssembly) {
            return targetFramework?.let {
                StringJoiner(":").add(assemblyName).add(it).toString()
            } ?: assemblyName
        }
    }

    /**
     * 构造references
     */
    private fun buildReferences(references: MutableList<Any>): Set<String> {
        if (references.isNotEmpty()) {
            val values = hashSetOf<String>()
            val iterator = references.iterator()
            while (iterator.hasNext()) {
                val reference = iterator.next()
                if (reference is Reference) {
                    values.add(reference.file)
                } else if (reference is ReferenceGroup) {
                    buildReferenceGroup(reference, values)
                }
            }
            return values
        }
        return emptySet()
    }

    private fun buildReferenceGroup(reference: ReferenceGroup, values: HashSet<String>) {
        val groupReferences = reference.references
        groupReferences?.let {
            val groupIterator = it.iterator()
            while (groupIterator.hasNext()) {
                val groupReference = groupIterator.next()
                values.add(groupReference.file)
            }
        }
    }

    /**
     * 构造dependencies
     */
    private fun buildDependencies(dependencies: List<Any>): Set<String> {
        if (dependencies.isNotEmpty()) {
            val values = hashSetOf<String>()
            val iterator = dependencies.iterator()
            while (iterator.hasNext()) {
                val dependency = iterator.next()
                if (dependency is Dependency) {
                    values.add(getDependencyValue(dependency, ""))
                } else if (dependency is DependencyGroup) {
                    buildDependencyGroup(dependency, values)
                }
            }
            return values
        }
        return emptySet()
    }

    private fun buildDependencyGroup(dependency: DependencyGroup, values: HashSet<String>) {
        val groupDependencies = dependency.dependencies
        groupDependencies?.let {
            val groupIterator = it.iterator()
            while (groupIterator.hasNext()) {
                val groupDependency = groupIterator.next()
                values.add(getDependencyValue(groupDependency, dependency.targetFramework))
            }
        } ?: values.add("::${dependency.targetFramework}")
    }

    fun getDependencyValue(dependency: Dependency, targetFramework: String?): String {
        return StringJoiner(":").add(dependency.id).add(dependency.version).add(targetFramework).toString()
    }

    // 删除包版本
    fun deleteVersion(userId: String, name: String, version: String, artifactInfo: NugetArtifactInfo) {
        val packageKey = PackageKeys.ofNuget(name)
        with(artifactInfo) {
            packageService.deleteVersion(projectId, repoName, packageKey, version, HttpContextHolder.getClientAddress())
                .apply {
                    logger.info(
                        "user: [$userId] delete package [$name] with version [$version] " +
                                "in repo [${artifactInfo.getRepoIdentify()}] success!"
                    )
                }
        }
    }

    companion object {
        val logger: Logger = LoggerFactory.getLogger(NugetPackageHandler::class.java)
    }
}
/*
 * Tencent is pleased to support the open source community by making BK-CI 蓝鲸持续集成平台 available.
 *
 * Copyright (C) 2022 Tencent.  All rights reserved.
 *
 * BK-CI


nsTitles3[];
//const char *consTitles4[];
//const char *consTitles5[];
//const char *consTitles6[];
//const char *consTitles7[];
//const char *consTitles8[];
//const char *consTitles9[];
//const char *consTitlesA[];
//const char *consTitlesB[];
//const char *consTitlesC[];
//const char *consTitlesD[];
//const char *consTitlesE[];
//const char *digitTitles0[];
//const char *digitTitles1[];
//const char *digitTitles2[];
//const char *aplphanumTitles0[];
//const char *aplphanumTitles1[];
//const char *aplphanumTitles2[];
//const char *medInstrTitles0[];
//const char *medInstrTitles1[];
//const char *medInstrTitles2[];
//const char *medInstrTitles3[];
//const char *medInstrTitles4[];

#endif //__HIDUSAGESTR_H__


).denominator(BigInteger.valueOf(2)).build();
    Ratio r2 = Ratio.builder().numerator(BigInteger.valueOf(1)).denominator(BigInteger.valueOf(4)).build();

    assertThat(r1.equalButMorePrecise((r2))).isFalse();
    assertThat(r2.equalButMorePrecise(r1)).isFalse();
  }

  ///////////
  // multiplyFloor
  ///////////

  @Test
  public void multiplyFloor() {
    Ratio r = Ratio.ONE;
    assertThat(r.multiplyFloor(BigInteger.valueOf(3L))).isEqualTo(BigInteger.valueOf(3L));
    assertThat(r.multiplyFloor(BigInteger.valueOf(5L))).isEqualTo(BigInteger.valueOf(5L));
    assertThat(r.multiplyFloor(BigInteger.ZERO)).isEqualTo(BigInteger.ZERO);
    assertThat(r.multiplyFloor(BigInteger.ONE)).isEqualTo(BigInteger.ONE);

    r = Ratio.ZERO;
    assertThat(r.multiplyFloor(BigInteger.valueOf(3L))).isEqualTo(BigInteger.ZERO);
    assertThat(r.multiplyFloor(BigInteger.valueOf(5L))).isEqualTo(BigInteger.ZERO);
    assertThat(r.multiplyFloor(BigInteger.ZERO)).isEqualTo(BigInteger.ZERO);
    assertThat(r.multiplyFloor(BigInteger.ONE)).isEqualTo(BigInteger.ZERO);

    r = Ratio.builder()
      .numerator(BigInteger.valueOf(1L))
      .denominator(BigInteger.valueOf(2L))
      .build();
    assertThat(r.multiplyFloor(BigInteger.valueOf(3L))).isEqualTo(BigInteger.ONE);
    assertThat(r.multiplyFloor(BigInteger.valueOf(5L))).isEqualTo(BigInteger.valueOf(2L));
    assertThat(r.multiplyFloor(BigInteger.ZERO)).isEqualTo(BigInteger.ZERO);
    assertThat(r.multiplyFloor(BigInteger.ONE)).isEqualTo(BigInteger.ZERO);

    r = Ratio.builder()
      .numerator(BigInteger.valueOf(3L))
      .denominator(BigInteger.valueOf(2L))
      .build();
    assertThat(r.multiplyFloor(BigInteger.valueOf(3L))).isEqualTo(BigInteger.valueOf(4L));
    assertThat(r.multiplyFloor(BigInteger.valueOf(5L))).isEqualTo(BigInteger.valueOf(7L));
    assertThat(r.multiplyFloor(BigInteger.ZERO)).isEqualTo(BigInteger.ZERO);
    assertThat(r.multiplyFloor(BigInteger.ONE)).isEqualTo(BigInteger.ONE);

    r = Ratio.builder()
      .numerator(BigInteger.valueOf(1L))
      .denominator(UnsignedLong.MAX_VALUE.bigIntegerValue())
      .build();
    assertThat(r.multiplyFloor(BigInteger.valueOf(3L))).isEqualTo(BigInteger.ZERO);
    assertThat(r.multiplyFloor(BigInteger.valueOf(5L))).isEqualTo(BigInteger.ZERO);
    assertThat(r.multiplyFloor(BigInteger.ZERO)).isEqualTo(BigInteger.ZERO);
    assertThat(r.multiplyFloor(BigInteger.ONE)).isEqualTo(BigInteger.ZERO);
  }

  @Test
  public void multiplyFloorBigIntegerLongWithOverflow() {
    Ratio r = Ratio.builder().numerator(BigInteger.TEN).denominator(BigInteger.ONE).build();
    assertThat(r.multiplyFloor(UnsignedLong.MAX_VALUE.bigIntegerValue()))
      .isEqualTo(new BigInteger("184467440737095516150"));
  }

  ///////////
  // multiplyFloorOrZero
  ///////////

  @Test
  public void multiplyFloorOrZero() {
    Ratio r = Ratio.ONE;
    assertThat(r.multiplyFloorOrZero(UnsignedLong.valueOf(3L))).isEqualTo(UnsignedLong.valueOf(3


 All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/*
 * @test
 * @run testng/othervm -Diters=10   -Xint                                                   VarHandleTestAccessShort
 *
 * @comment Set CompileThresholdScaling to 0.1 so that the warmup loop sets to 2000 iterations
 *          to hit compilation thresholds
 *
 * @run testng/othervm -Diters=2000 -XX:CompileThresholdScaling=0.1 -XX:TieredStopAtLevel=1 VarHandleTestAccessShort
 * @run testng/othervm -Diters=2000 -XX:CompileThresholdScaling=0.1                         VarHandleTestAccessShort
 * @run testng/othervm -Diters=2000 -XX:CompileThresholdScaling=0.1 -XX:-TieredCompilation  VarHandleTestAccessShort
 */

import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static org.testng.Assert.*;

public class VarHandleTestAccessShort extends VarHandleBaseTest {
    static final short static_final_v = (short)0x0123;

    static short static_v;

    final short final_v = (short)0x0123;

    short v;

    static final short static_final_v2 = (short)0x0123;

    static short static_v2;

    final short final_v2 = (short)0x0123;

    short v2;

    VarHandle vhFinalField;

    VarHandle vhField;

    VarHandle vhStaticField;

    VarHandle vhStaticFinalField;

    VarHandle vhArray;

    VarHandle[] allocate(boolean same) {
        List<VarHandle> vhs = new ArrayList<>();

        String postfix = same ? "" : "2";
        VarHandle vh;
        try {
            vh = MethodHandles.lookup().findVarHandle(
                    VarHandleTestAccessShort.class, "final_v" + postfix, short.class);
            vhs.add(vh);

            vh = MethodHandles.lookup().findVarHandle(
                    VarHandleTestAccessShort.class, "v" + postfix, short.class);
            vhs.add(vh);

            vh = MethodHandles.lookup().findStaticVarHandle(
                VarHandleTestAccessShort.class, "static_final_v" + postfix, short.class);
            vhs.add(vh);

            vh = MethodHandles.lookup().findStaticVarHandle(
                VarHandleTestAccessShort.class, "static_v" + postfix, short.class);
            vhs.add(vh);

            if (same) {
                vh = MethodHandles.arrayElementVarHandle(short[].class);
            }
            else {
                vh = MethodHandles.arrayElementVarHandle(String[].class);


if (isValidEscape$1(code, getCharCode(source, offset + 1))) {
	            // Consume an escaped code point. Append the returned code point to result.
	            offset = consumeEscaped(source, offset) - 1;
	            continue;
	        }

	        // anything else
	        // Reconsume the current input code point. Return result.
	        break;
	    }

	    return offset;
	}

	// §4.3.12. Consume a number
	function consumeNumber(source, offset) {
	    var code = source.charCodeAt(offset);

	    // 2. If the next input code point is U+002B PLUS SIGN (+) or U+002D HYPHEN-MINUS (-),
	    // consume it and append it to repr.
	    if (code === 0x002B || code === 0x002D) {
	        code = source.charCodeAt(offset += 1);
	    }

	    // 3. While the next input code point is a digit, consume it and append it to repr.
	    if (isDigit$1(code)) {
	        offset = findDecimalNumberEnd(source, offset + 1);
	        code = source.charCodeAt(offset);
	    }

	    // 4. If the next 2 input code points are U+002E FULL STOP (.) followed by a digit, then:
	    if (code === 0x002E && isDigit$1(source.charCodeAt(offset + 1))) {
	        // 4.1 Consume them.
	        // 4.2 Append them to repr.
	        code = source.charCodeAt(offset += 2);

	        // 4.3 Set type to "number".
	        // TODO

	        // 4.4 While the next input code point is a digit, consume it and append it to repr.

	        offset = findDecimalNumberEnd(source, offset);
	    }

	    // 5. If the next 2 or 3 input code points are U+0045 LATIN CAPITAL LETTER E (E)
	    // or U+0065 LATIN SMALL LETTER E (e), ... , followed by a digit, then:
	    if (cmpChar(source, offset, 101 /* e */)) {
	        var sign = 0;
	        code = source.charCodeAt(offset + 1);

	        // ... optionally followed by U+002D HYPHEN-MINUS (-) or U+002B PLUS SIGN (+) ...
	        if (code === 0x002D || code === 0x002B) {
	            sign = 1;
	            code = source.charCodeAt(offset + 2);
	        }

	        // ... followed by a digit
	        if (isDigit$1(code)) {
	            // 5.1 Consume them.
	            // 5.2 Append them to repr.

	            // 5.3 Set type to "number".
	            // TODO

	            // 5.4 While the next input code point is a digit, consume it and append it to repr.
	            offset = findDecimalNumberEnd(source, offset + 1 + sign + 1);
	        }
	    }

	    return offset;
	}

	// § 4.3.14. Consume the remnants of a bad url
	// ... its sole use is to consume enough of the input stream to reach a recovery point
	// where normal tokenizing can resume.
	function consumeBadUrlRemnants(source, offset) {
	    // Repeatedly consume the next input code point from the stream:
	    for (; offset < source.length; offset++) {
	        var code = source.charCodeAt(offset);

	        // U+0029 RIGHT PARENTHESIS ())
	        // EOF
	        if (code === 0x0029) {
	            // Return.
	            offset++;
	            break;
	        }

	        if (isValidEscape$1(code, getCharCode(source, offset + 1))) {
	            // Consume an escaped code point.
	            // Note: This allows an escaped right parenthesis ("\)") to be encountered
	            // without ending the <bad-url-token>. This is otherwise identical to
	            // the "anything else" clause.
	            offset = consumeEscaped(source, offset);
	        }
	    }

	    return offset;
	}

	var utils = {
	    consumeEscaped: consumeEscaped,
	    consumeName: consumeName,
	    consumeNumber: consumeNumber,
	    consumeBadUrlRemnants: consumeBadUrlRemnants,

	    cmpChar: cmpChar,
	    cmpStr: cmpStr,


.repositoryHashId,
                        repositoryName = EnvUtils.parseEnv(element.repositoryName, variables),
                        repositoryType = element.repositoryType ?: RepositoryType.ID
                    )

                    element is CodeSvnElement -> RepositoryConfig(
                        repositoryHashId = element.repositoryHashId,
                        repositoryName = EnvUtils.parseEnv(element.repositoryName, variables),
                        repositoryType = element.repositoryType ?: RepositoryType.ID
                    )

                    element is CodeGitlabElement -> RepositoryConfig(
                        repositoryHashId = element.repositoryHashId,
                        repositoryName = EnvUtils.parseEnv(element.repositoryName, variables),
                        repositoryType = element.repositoryType ?: RepositoryType.ID
                    )

                    element is GithubElement -> RepositoryConfig(
                        repositoryHashId = element.repositoryHashId,
                        repositoryName = EnvUtils.parseEnv(element.repositoryName, variables),
                        repositoryType = element.repositoryType ?: RepositoryType.ID
                    )

                    element is MarketBuildAtomElement && element.getAtomCode() in repoCheckoutAtomCodes -> {
                        val input = element.data["input"]
                        if (input !is Map<*, *>) return@e
                        getMarketBuildRepoConfig(input = input, variables = variables) ?: return@e
                    }

                    else -> return@e
                }
                repoPipelineRefInfos.add(
                    RepoPipelineRefInfo(
                        projectId = projectId,
                        pipelineId = pipelineId,
                        pipelineName = pipelineName,
                        repositoryConfig = repositoryConfig,
                        taskId = element.id!!,
                        taskName = element.name,
                        taskParams = getTaskParams(element),
                        atomCode = element.getAtomCode(),
                        atomVersion = element.version,
                        atomCategory = RepoAtomCategoryEnum.TASK.name
                    )
                )
            }
        }
    }

    private fun getMarketBuildRepoConfig(input: Map<*, *>, variables: Map<String, String>): RepositoryConfig? {
        val taskRepoType = input["repositoryType"] as String?
        // URL/SELF指定代码库，无需关联代码库;
        if (taskRepoType == "URL" || taskRepoType == "SELF") {
            return null
        }
        val repositoryType = RepositoryType.parseType(taskRepoType)
        val repositoryId = when (repositoryType) {
            RepositoryType.ID -> EnvUtils.parseEnv(input["repositoryHashId"] as String?, variables)
            RepositoryType.NAME -> EnvUtils.parseEnv(input["repositoryName"] as String?, variables)
            else -> return null
        }
        return RepositoryConfigUtils.buildConfig(repositoryId, repositoryType)
    }
}
/*
 * Tencent is pleased to support the open source community by making BK-CI 蓝鲸持续集成平台 available.
 *
 * Copyright (C) 2019 Tencent.  All rights reserved.
 *
 * BK-CI 蓝鲸持续集成平台 is licensed under the MIT license.
 *
 * A copy of the MIT License is included in this file.
 *
 *
 * Terms of the MIT License:
 * ---------------------------------------------------
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall b


 clicked")
            if label and label.UILabel then
                label.UILabel.text = current
                engine:request_redraw()
            end
        end)
    elseif meta and meta.name == "ClearButton" then
        engine:print("subscribing click for ClearButton")
        self:subscribe_event("clicked", function()
            engine:print("clear clicked")
            current = ""
            if label and label.UILabel then
                label.UILabel.text = ""
                engine:request_redraw()
            end
            if editor and editor.UITextEditor then
                editor.UITextEditor.text = ""
            end
        end)
    end
end

function update(engine, self, input, dt)
end


json_concat(json_string, json_string) -> String
```

Given 2 strings, parse them as JSON values and return a string representing their concatenation.
Concatenation rules are identical to PostgreSQL's [|| operator](https://www.postgresql.org/docs/14/functions-json.html):
* If both strings deserialize into JSON objects, then return an object with a union of the input key,
  taking values from the second object in the case of duplicates.
* If both strings deserialize into JSON arrays, then return the result of array concatenation.
* If at least one of the deserialized values is not an object, then convert non-array inputs to a
  single-element array and return the result of array concatenation.
* If at least one of the input strings is `NULL` or can't be deserialized as JSON, then return `NULL`.

Akin to PostgreSQL's `||` operator, this function merges only top-level object keys or arrays.

#### Examples

```
json_concat("{\"a\": 1}", "{\"b\": 2}") // returns "{\"a\": 1, \"b\": 2}"
json_concat("{\"a\": {\"5\": 6}}", "{\"a\": {\"3\": 4}}") // returns "{\"a\": {\"3\": 4}}"
json_concat("{}", "{}") // returns "{}"
json_concat("[1, 2]", "[3, 4]") // returns "[1,2,3,4]"
json_concat("[1, [2]]", "[[[3]], [[[4]]]]") // returns "[ 1, [2], [[3]], [[[4]]] ]"
json_concat("null", "null") // returns [null, null]
json_concat("[1, 2]", "{\"a\": 1}") // returns "[1, 2, {\"a\": 1}]"
json_concat("[1, 2]", "3") // returns "[1, 2, 3]"
json_concat("1", "2") // returns "[1, 2]"
json_concat("[]", "[]") // returns []
json_concat("abc", "[1]") // returns NULL
json_concat(NULL, "[1]") // returns NULL
```

#### Rejected alternatives

If one argument represents a valid JSON and the other one does not, then return the valid string
as a result of concatenation.

Given that concatenation of invalid JSON strings is an exceptional situation, we should return
`NULL` if any input is not a JSON. This way, we avoid ambiguity if a user needs to trace back how
they got certain results.

If this function returns the valid record in the case when the other one is invalid, from the user
perspective, there are 3 possibilities how they ended up with this result:
* The second object could have been empty.
* The second object could have had the same keys/values.
* The second object is invalid JSON.

By always returning `NULL` given an invalid JSON string we remove the third, the least obvious,
possibility which reduces cognitive load from the user.

### to_json_string

```
to_json_string(val) -> String
```

Given any ksqlDB type returns the equivalent JSON string.

#### Examples

**Primitives types**

```
to_json_string(1) // returns "1"
to_json_string(15.3) // returns "15.3"
to_json_string("abc") // returns "\"abc\""
to_json_string(true) // returns "true"
to_json_string(2021-10-11) // DATE type, returns "\"2021-10-11\""
to_json_string(13:25) // TIME type, returns "\"13:25\""
to_json_string(2021-06-31T12:18:39.446) // TIMESTAMP type, returns "\"2021-06-31T12:18:39.446\""
to_json_string(NULL) // returns "null"
```

**Compound types**
```
to_json_string(Array[1, 2, 3]) // returns "[1, 2, 3]"
to_json_string(Struct{id=1,name=A}) // returns "{\"id\": 1, \"name\": \"a\"}"
to_json_string(Map('c' := 2, 'd' := 4)) // returns "{\"c\": 2, \"d\": \"4\"}"
to_json_string(Array[Struct{json_key=1 json_value=Map('c' := 2, 'd' := true)}]) // returns "[{\"json_key\": 1, \"json_value\": {\"c\": 2, \"d\": true}}]"
```

Custom types are processed in the same way as the types they alias.

#### Rejected alternatives

Return `NULL` given `NULL` as input. Although, it might make sense from the `NULL` propagation point
of view, th


tooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothGattService;
import android.hardware.usb.UsbDevice;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.os.*;

//import com.android.internal.util.HexDump;

import java.lang.Runnable;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.UUID;

class HIDDeviceBLESteamController extends BluetoothGattCallback implements HIDDevice {

    private static final String TAG = "hidapi";
    private HIDDeviceManager mManager;
    private BluetoothDevice mDevice;
    private int mDeviceId;
    private BluetoothGatt mGatt;
    private boolean mIsRegistered = false;
    private boolean mIsConnected = false;
    private boolean mIsChromebook = false;
    private boolean mIsReconnecting = false;
    private boolean mFrozen = false;
    private LinkedList<GattOperation> mOperations;
    GattOperation mCurrentOperation = null;
    private Handler mHandler;

    private static final int TRANSPORT_AUTO = 0;
    private static final int TRANSPORT_BREDR = 1;
    private static final int TRANSPORT_LE = 2;

    private static final int CHROMEBOOK_CONNECTION_CHECK_INTERVAL = 10000;

    static public final UUID steamControllerService = UUID.fromString("100F6C32-1735-4313-B402-38567131E5F3");
    static public final UUID inputCharacteristic = UUID.fromString("100F6C33-1735-4313-B402-38567131E5F3");
    static public final UUID reportCharacteristic = UUID.fromString("100F6C34-1735-4313-B402-38567131E5F3");
    static private final byte[] enterValveMode = new byte[] { (byte)0xC0, (byte)0x87, 0x03, 0x08, 0x07, 0x00 };

    static class GattOperation {
        private enum Operation {
            CHR_READ,
            CHR_WRITE,
            ENABLE_NOTIFICATION
        }

        Operation mOp;
        UUID mUuid;
        byte[] mValue;
        BluetoothGatt mGatt;
        boolean mResult = true;

        private GattOperation(BluetoothGatt gatt, GattOperation.Operation operation, UUID uuid) {
            mGatt = gatt;
            mOp = operation;
            mUuid = uuid;
        }

        private GattOperation(BluetoothGatt gatt, GattOperation.Operation operation, UUID uuid, byte[] value) {
            mGatt = gatt;
            mOp = operation;
            mUuid = uuid;
            mValue = value;
        }

        public void run() {
            // This is executed in main thread
            BluetoothGattCharacteristic chr;

            switch (mOp) {
                case CHR_READ:
                    chr = getCharacteristic(mUuid);
                    //Log.v(TAG, "Reading characteristic " + chr.getUuid());
                    if (!mGatt.readCharacteristic(chr)) {
                        Log.e(TAG, "Unable to read characteristic " + mUuid.toString());
                        mResult = false;
                        break;
                    }
                    mResult = true;
                    break;
                case CHR_WRITE:
                    chr = getCharacteristic(mUuid);
                    //Log.v(TAG, "Writing characteristic " + chr.getUuid() + " value=" + HexDump.toHexString(value));
                    chr.setValue(mValue);
                    if (!mGatt.writeCharacteristic(chr)) {


text = self.text,
      font = md.sys.typescale.body_medium.font
          .. ' ' .. md.sys.typescale.body_medium.size,
      widget = wibox.widget.textbox
    },
    widget = self:padding()
  }
end

function card:padding()
  return wibox.widget {
    margins = dpi(16),
    widget = wibox.container.margin
  }
end

function card:container()
  return wibox.widget {
    bg = md.sys.color.surface,
    shape = self.shape,
    shape_border_width = 1,
    shape_border_color = md.sys.color.outline_variant,
    widget = wibox.container.background
  }
end

function card:state()
  self.state = wibox.widget {
    bg = md.sys.color.on_surface .. '00',
    shape = self.shape,
    widget = wibox.container.background
  }
end

function card:container_elevation()
  self.container_elevation = wibox.widget {
    bg = md.sys.color.surface_tint_color .. '00',
    shape = self.shape,
    widget = wibox.container.background
  }
end

function card:add_signals()
  self.widget:connect_signal('mouse::enter', function()
    self.state.bg = md.sys.color.surface_tint_color
      .. md.sys.state.hover_state_layer_opacity
    self.container_elevation.bg = md.sys.color.surface_tint_color
      .. md.sys.elevation.level1
  end)
  self.widget:connect_signal('mouse::leave', function()
    self.state.bg = md.sys.color.surface_tint_color .. '00'
    self.container_elevation.bg = md.sys.color.surface_tint_color .. '00'
  end)
  self.widget:connect_signal('button::press', function()
    if self.on_click and type(self.on_click) == 'function' then
      self.on_click()
    end
  end)
end

return card


/*
 * Copyright (c) 1995 - 2001 Kungliga Tekniska Högskolan
 * (Royal Institute of Technology, Stockholm, Sweden).
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the Institute nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include "hash.h"
#include "md4.h"

#define A m->counter[0]
#define B m->counter[1]
#define C m->counter[2]
#define D m->counter[3]
#define X data

/* Vector Crays doesn't have a good 32-bit type, or more precisely,
   int32_t as defined by <bind/bitypes.h> isn't 32 bits, and we don't
   want to depend in being able to redefine this type.  To cope with
   this we have to clamp the result in some places to [0,2^32); no
   need to do this on other machines.  Did I say this was a mess?
   */

#ifdef _CRAY
#define CRAYFIX(X) ((X) & 0xffffffff)
#else
#define CRAYFIX(X) (X)
#endif

static uint32_t cshift (uint32_t x, unsigned int n)
{
    x = CRAYFIX(x);
    return CRAYFIX((x << n) | (x >> (32 - n)));
}

void
MD4_Init (struct md4 *m)
{
  m->sz[0] = 0;
  m->sz[1] = 0;
  D = 0x10325476;
  C = 0x98badcfe;
  B = 0xefcdab89;
  A = 0x67452301;
}

#define F(x,y,z) CRAYFIX((x & y) | (~x & z))
#define G(x,y,z) ((x & y) | (x & z) | (y & z))
#define H(x,y,z) (x ^ y ^ z)

#define DOIT(a,b,c,d,k,s,i,OP) \
a = cshift(a + OP(b,c,d) + X[k] + i, s)

#define DO1(a,b,c,d,k,s,i) DOIT(a,b,c,d,k,s,i,F)
#define DO2(a,b,c,d,k,s,i) DOIT(a,b,c,d,k,s,i,G)
#define DO3(a,b,c,d,k,s,i) DOIT(a,b,c,d,k,s,i,H)

static void
calc (struct md4 *m, uint32_t *data)
{
  uint32_t AA, BB, CC, DD;

  AA = A;
  BB = B;
  CC = C;
  DD = D;

  /* Round 1 */

  DO1(A,B,C,D,0,3,0);
  DO1(D,A,B,C,1,7,0);
  DO1(C,D,A,B,2,11,0);
  DO1(B,C,D,A,3,19,0);

  DO1(A,B,C,D,4,3,0);
  DO1(D,A,B,C,5,7,0);
  DO1(C,D,A,B,6,11,0);
  DO1(B,C,D,A,7,19,0);

  DO1(A,B,C,D,8,3,0);
  DO1(D,A,B,C,9,7,0);
  DO1(C,D,A,B,10,11,0);
  DO1(B,C,D,A,11,19,0);

  DO1(A,B,C,D,12,3,0);
  DO1(D,A,B,C,13,7,0);
  DO1(C,D,A,B,14,11,0);
  DO1(B,C,D,A,15,19,0);

  /* Round 2 */

  DO2(A,B,C,D,0,3,0x5A827999);
  DO2(D,A,B,C,4,5,0x5A827999);
  DO2(C,D,A,B,8,9,0x5A827999);
  DO2(B,C,D,A,12,13,0x5A827999);

  DO2(A,B,C,D,1,3,0x5A827999);
  DO2(D,A,B,C,5,5,0x5A827999);
  DO2(C,D,A,B,9,9,0x5A827999);
  DO2(B,C,D,A,13,13,0x5A827999);

  DO2(A,B,C,D,2,3,0x5A827999);
  DO2(D,A,B,C,6,5,0x5A827999);
  DO2(C,D,A,B,10,9,0x5A827999);
  DO2(B,C,D,A,14,13,0x5A827999);

  DO2(A,B,C,D,3,3,0x5A827999);
  DO2(D,A,B,C,7,5,0x5A827999);
  DO2(C,D,A,B,11,9,0x5A827999);
  DO2(B,C,D,A,15,13,0x5A827999);

  /* Round 3 */

  DO3(A,B,C,D,0,3,0x6ED9EBA1);
  DO3(D,A,B,C,8,9,0x6ED9EBA1);
  DO3(C,D,A,B,4,11,0x6ED9EBA1);
  DO3(B,C,D,A,12,15,0x6ED9EBA1);

  DO3(A,B,C,D,2,3,0x6ED9EBA1);
  DO3(D,A,B,C,10,9,0x6ED9EBA1);
  DO3(C,D,A,B,6,11,0x6ED9EBA1);
  DO3(B,C,D,A,14,15,0x6ED9EBA1);

  DO3(A,B,C,D,1,3,0x6ED9EBA1);
  DO3(D,A,B,C,9,9,0x6ED9EBA1);
  DO3(C,D,A,B,5,11,0x6ED9EBA1);
  DO3(B,C,D,A,13,15,0x6ED9EBA1);

  DO3(A,B,C,D,3,3,0x6ED9EBA1);
  DO3(D,A,B,C,11,9,0x6ED9EBA1);
  DO3(C,D,A,B,7,11,0x6ED9EBA1);
  DO3(B,C,D,A,15,15,0x6ED9EBA1);

  A += AA;
  B += BB;
  C += CC;
  D += DD;
}

/*
 * From `Performance analysis of MD5' by Joseph


t, when);
  }

  public void unscheduleDrawable(@NonNull Drawable who, @NonNull Runnable what) {
    this.unscheduleSelf(what);
  }

  protected boolean onLevelChange(int level) {
    return this.mDrawable.setLevel(level);
  }

  public void setAutoMirrored(boolean mirrored) {
    DrawableCompat.setAutoMirrored(this.mDrawable, mirrored);
  }

  public boolean isAutoMirrored() {
    return DrawableCompat.isAutoMirrored(this.mDrawable);
  }

  public void setTint(int tint) {
    DrawableCompat.setTint(this.mDrawable, tint);
  }

  public void setTintList(ColorStateList tint) {
    DrawableCompat.setTintList(this.mDrawable, tint);
  }

  public void setTintMode(@NonNull PorterDuff.Mode tintMode) {
    DrawableCompat.setTintMode(this.mDrawable, tintMode);
  }

  public void setHotspot(float x, float y) {
    DrawableCompat.setHotspot(this.mDrawable, x, y);
  }

  public void setHotspotBounds(int left, int top, int right, int bottom) {
    DrawableCompat.setHotspotBounds(this.mDrawable, left, top, right, bottom);
  }

  public Drawable getWrappedDrawable() {
    return this.mDrawable;
  }

  public void setWrappedDrawable(Drawable drawable) {
    if (this.mDrawable != null) {
      this.mDrawable.setCallback(null);
    }

    this.mDrawable = drawable;
    if (drawable != null) {
      drawable.setCallback(this);
    }
  }
}
/*
 * Copyright 2016 Hippo Seven
 *
 * 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.
 */

package com.hippo.preference;

import android.preference.Preference;
import android.preference.PreferenceManager;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public final class PreferenceUtils {
    private PreferenceUtils() {}

    private static final Method mRegisterOnActivityDestroyListener;
    private static final Method mUnregisterOnActivityDestroyListener;

    static {
        Method method;
        Class<?> clazz = PreferenceManager.class;

        method = null;
        try {
            method = clazz.getDeclaredMethod("registerOnActivityDestroyListener",
                    PreferenceManager.OnActivityDestroyListener.class);
            if (null != method) {
                method.setAccessible(true);
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        mRegisterOnActivityDestroyListener = method;

        method = null;
        try {
            method = clazz.getDeclaredMethod("unregisterOnActivityDestroyListener",
                    PreferenceManager.OnActivityDestroyListener.class);
            if (null != method) {
                method.setAccessible(true);
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        mUnregisterOnActivityDestroyListener = method;
    }

    @SuppressWarnings("TryWithIdenticalCatches")
    public static void registerOnActivityDestroyListener(Preference preference,
            PreferenceManager.OnActivityDestroyListener listener) {
        if (null == mRegisterOnActivityDestroyListener ||


;

// Global flag for critical errors - stop benchmark immediately when any error
// occurs
static std::atomic<bool> g_critical_error(false);
static std::string g_error_details;
static std::mutex g_error_mutex;

// Thread-safe logging to prevent output interleaving
static std::mutex g_log_mutex;

// Thread-safe file writing to prevent concurrent file access
static std::mutex g_file_mutex;

// Macro for thread-safe logging
#define SAFE_LOG(stream, msg) \
    do { \
        std::ostringstream oss; \
        oss << msg; \
        std::lock_guard<std::mutex> log_lock(g_log_mutex); \
        stream << oss.str(); \
    } while (0)

// Function to set critical error and stop benchmark immediately
static void set_critical_error(const std::string &error_msg)
{
    std::lock_guard<std::mutex> error_lock(g_error_mutex);
    if (!g_critical_error.load()) {
        g_error_details = error_msg;
        g_critical_error.store(true);

        // Log error immediately
        SAFE_LOG(std::cerr, "\n" << std::string(80, '=') << "\n");
        SAFE_LOG(std::cerr, "CRITICAL ERROR DETECTED - STOPPING BENCHMARK "
                            "IMMEDIATELY\n");
        SAFE_LOG(std::cerr, std::string(80, '=') << "\n");
        SAFE_LOG(std::cerr, error_msg << "\n");
        SAFE_LOG(std::cerr, std::string(80, '=') << "\n");
    }
}

static void signal_handler(int signal)
{
    if (signal == SIGINT) {
        // Only use async-signal-safe operations in signal handler
        // No I/O operations here - they're not async-signal-safe
        g_interrupted = 1;
    }
}

static void apply_config(const BenchmarkConfig &cfg)
{
    // Apply to global gameOptions
    gameOptions.setSkillLevel(cfg.skillLevel);
    gameOptions.setMoveTime(cfg.moveTimeSec);
    gameOptions.setAlgorithm(cfg.algorithm);
    gameOptions.setIDSEnabled(cfg.idsEnabled);
    gameOptions.setDepthExtension(cfg.depthExtension);
    gameOptions.setOpeningBook(cfg.openingBook);
    gameOptions.setShufflingEnabled(cfg.shuffling);
    // For benchmark, force AiIsLazy=false for both sides to ensure fair
    // comparison Both Traditional AI and Perfect DB should use non-lazy mode
    // for consistent evaluation
    gameOptions.setAiIsLazy(false);
    // For benchmark, disable Perfect DB in traditional search engine to ensure
    // pure comparison. Traditional side: pure traditional search algorithms
    // (Alpha-Beta, PVS, MTD(f), MCTS, etc.) Perfect DB side: pure database
    // lookup via direct perfect_search() calls This ensures we're truly
    // comparing "Traditional Search vs Perfect DB" not "Hybrid vs Pure DB"
    gameOptions.setUsePerfectDatabase(false);
    gameOptions.setPerfectDatabasePath(cfg.perfectDbPath);

    // Apply N-move rule configuration to global rule
    // This is essential for 50-move rule to work properly in benchmark
    rule.nMoveRule = cfg.nMoveRule;

    // Ensure threefold repetition rule is active for benchmark games.
    // Some front-ends may toggle this, but benchmark should always enforce it
    // to avoid endless oscillations in the moving phase.
    rule.threefoldRepetitionRule = true;

    // CRITICAL: Force AutoRestart=false for benchmark
    // We handle gam


/", userId))
{}
// THIS FILE IS GENERATED - ANY EDITS WILL BE OVERWRITTEN

#include "threads_list.h"

using namespace Quotient;

auto queryToGetThreadRoots(const QString& include, std::optional<int> limit, const QString& from)
{
    QUrlQuery _q;
    addParam<IfNotEmpty>(_q, u"include"_s, include);
    addParam<IfNotEmpty>(_q, u"limit"_s, limit);
    addParam<IfNotEmpty>(_q, u"from"_s, from);
    return _q;
}

QUrl GetThreadRootsJob::makeRequestUrl(const HomeserverData& hsData, const QString& roomId,
                                       const QString& include, std::optional<int> limit,
                                       const QString& from)
{
    return BaseJob::makeRequestUrl(hsData,
                                   makePath("/_matrix/client/v1", "/rooms/", roomId, "/threads"),
                                   queryToGetThreadRoots(include, limit, from));
}

GetThreadRootsJob::GetThreadRootsJob(const QString& roomId, const QString& include,
                                     std::optional<int> limit, const QString& from)
    : BaseJob(HttpVerb::Get, u"GetThreadRootsJob"_s,
              makePath("/_matrix/client/v1", "/rooms/", roomId, "/threads"),
              queryToGetThreadRoots(include, limit, from))
{
    addExpectedKey(u"chunk"_s);
}
// THIS FILE IS GENERATED - ANY EDITS WILL BE OVERWRITTEN

#include "message_pagination.h"

using namespace Quotient;

auto queryToGetRoomEvents(const QString& from, const QString& to, const QString& dir,
                          std::optional<int> limit, const QString& filter)
{
    QUrlQuery _q;
    addParam<IfNotEmpty>(_q, u"from"_s, from);
    addParam<IfNotEmpty>(_q, u"to"_s, to);
    addParam(_q, u"dir"_s, dir);
    addParam<IfNotEmpty>(_q, u"limit"_s, limit);
    addParam<IfNotEmpty>(_q, u"filter"_s, filter);
    return _q;
}

QUrl GetRoomEventsJob::makeRequestUrl(const HomeserverData& hsData, const QString& roomId,
                                      const QString& dir, const QString& from, const QString& to,
                                      std::optional<int> limit, const QString& filter)
{
    return BaseJob::makeRequestUrl(hsData,
                                   makePath("/_matrix/client/v3", "/rooms/", roomId, "/messages"),
                                   queryToGetRoomEvents(from, to, dir, limit, filter));
}

GetRoomEventsJob::GetRoomEventsJob(const QString& roomId, const QString& dir, const QString& from,
                                   const QString& to, std::optional<int> limit,
                                   const QString& filter)
    : BaseJob(HttpVerb::Get, u"GetRoomEventsJob"_s,
              makePath("/_matrix/client/v3", "/rooms/", roomId, "/messages"),
              queryToGetRoomEvents(from, to, dir, limit, filter))
{
    addExpectedKey(u"start"_s);
    addExpectedKey(u"chunk"_s);
}
// THIS FILE IS GENERATED - ANY EDITS WILL BE OVERWRITTEN

#include "device_management.h"

using namespace Quotient;

QUrl GetDevicesJob::makeRequestUrl(const HomeserverData& hsData)
{
    return BaseJob::makeRequestUrl(hsData, makePath("/_matrix/client/v3", "/devices"));
}

GetDevicesJob::GetDevicesJob()
    : BaseJob(HttpVerb::Get, u"GetDevicesJob"_s, makePath("/_mat