mapillary_type = "CityscapesDataset"
mapillary_root = "./data/mapillary/"
mapillary_crop_size = (512, 512)
mapillary_train_pipeline = [
    dict(type="LoadImageFromFile", imdecode_backend="pillow"),
    dict(type="LoadAnnotations", imdecode_backend="pillow"),
    dict(type="Resize", scale=(1024, 512)),
    dict(type="RandomCrop", crop_size=mapillary_crop_size, cat_max_ratio=0.75),
    dict(type="RandomFlip", prob=0.5),
    dict(type="PhotoMetricDistortion"),
    dict(type="PackSegInputs"),
]
mapillary_test_pipeline = [
    dict(type="LoadImageFromFile", imdecode_backend="pillow"),
    dict(type="Resize", scale=(1024, 512), keep_ratio=True),
    # add loading annotation after ``Resize`` because ground truth
    # does not need to do resize data transform
    dict(type="LoadAnnotations", imdecode_backend="pillow"),
    dict(type="PackSegInputs"),
]
train_mapillary = dict(
    type=mapillary_type,
    data_root=mapillary_root,
    data_prefix=dict(
        img_path="training/images",
        seg_map_path="cityscapes_trainIdLabel/train/label",
    ),
    img_suffix=".jpg",
    seg_map_suffix=".png",
    pipeline=mapillary_train_pipeline,
)
val_mapillary = dict(
    type=mapillary_type,
    data_root=mapillary_root,
    data_prefix=dict(
        img_path="half/val_img",
        seg_map_path="half/val_label",
    ),
    img_suffix=".jpg",
    seg_map_suffix=".png",
    pipeline=mapillary_test_pipeline,
)


2);

            if (Dim == 2){
                exact_hess(0,0) = 2.0 * std::pow(x2,2) + 2.0 * std::pow(x3,2) + 2.0 * x2 + 2.0 * x3 + 2.0;
                exact_hess(0,1) = 4.0 * x1 * x2 + 2.0 * x1 + 2.0 * x2 + x3 + 1.0;
                exact_hess(1,0) = 4.0 * x1 * x2 + 2.0 * x1 + 2.0 * x2 + x3 + 1.0;
                exact_hess(1,1) = 2.0 * std::pow(x1,2) + 2.0 * std::pow(x3,2) + 2.0 * x1 + 2.0 * x3 + 2.0;
            }
            else if (Dim == 3){
                exact_hess(0,0) = 2.0 * std::pow(x2,2) + 2.0 * std::pow(x3,2) + 2.0 * x2 + 2.0 * x3 + 2.0;
                exact_hess(0,1) = 4.0 * x1 * x2 + 2.0 * x1 + 2.0 * x2 + x3 + 1.0;
                exact_hess(0,2) = 4.0 * x1 * x3 + 2.0 * x1 + 2.0 * x3 + x2 + 1.0;
                exact_hess(1,0) = 4.0 * x1 * x2 + 2.0 * x1 + 2.0 * x2 + x3 + 1.0;
                exact_hess(1,1) = 2.0 * std::pow(x1,2) + 2.0 * std::pow(x3,2) + 2.0 * x1 + 2.0 * x3 + 2.0;
                exact_hess(1,2) = 4.0 * x2 * x3 + 2.0 * x2 + 2.0 * x3 + x1 + 1.0;
                exact_hess(2,0) = 4.0 * x1 * x3 + 2.0 * x1 + 2.0 * x3 + x2 + 1.0;
                exact_hess(2,1) = 4.0 * x3 * x2 + 2.0 * x3 + 2.0 * x2 + x1 + 1.0;
                exact_hess(2,2) = 2.0 * std::pow(x1,2) + 2.0 * std::pow(x2,2) + 2.0 * x1 + 2.0 * x2 + 2.0;
            }

            for (unsigned int d = 0; d < Dim; ++d){
                for (unsigned int e = 0; e < Dim; ++e){
                    if ((hess(d,e) - exact_hess(d,e)) >= 1e-10){
                        rErrorMessage << " error: shape function second derivatives are wrongly calculated in function ShapeFunctionsIntegrationPointsSecondDerivatives: hess(d,e) " << hess(d,e) << " vs " << exact_hess(d,e) << std::endl;
                        return false;
                    }
                }
            }

        }

    return true;
}

/***********************************************************************************/
/***********************************************************************************/

std::string GeometryTesterUtility::GetIntegrationName(
    GeometryType& rGeometry,
    GeometryType::IntegrationMethod ThisMethod
    )
{
    switch(ThisMethod)
    {
    case GeometryData::IntegrationMethod::GI_GAUSS_1 :
        return std::string("GI_GAUSS_1");
    case GeometryData::IntegrationMethod::GI_GAUSS_2 :
        return std::string("GI_GAUSS_2");
    case GeometryData::IntegrationMethod::GI_GAUSS_3 :
        return std::string("GI_GAUSS_3");
    case GeometryData::IntegrationMethod::GI_GAUSS_4 :
        return std::string("GI_GAUSS_4");
    case GeometryData::IntegrationMethod::GI_GAUSS_5 :
        return std::string("GI_GAUSS_5");
    case GeometryData::IntegrationMethod::GI_LOBATTO_1 :
        return std::string("GI_LOBATTO_1");
    case GeometryData::IntegrationMethod::NumberOfIntegrationMethods :
        return std::string("NumberOfIntegrationMethods");
    };

    return std::string("UnknownIntegrationMethod");
}

/*******************


  steal_enable = true
                end
            end
            if Config.StealDead and dist < 2.5 then
                if IsEntityDead(steal_ped) then
                    steal_enable = true
                end
            end

            -- Verifica se o personagem está com as mãos levantadas
            local isHandsUp = IsEntityPlayingAnim(steal_ped, "script_proc@robberies@shop@rhodes@gunsmith@inside_upstairs",
                "handsup_register_owner", 3)

            if Config.StealHandsUp and dist < 2.5 and not IsEntityDead(steal_ped) and isHandsUp then
                steal_enable = true
            end
        end

        data_steal[#data_steal + 1] = {
            steal_enable = steal_enable,
            steal_source = steal_source,
            steal_ped = steal_ped,
        }

        if not steal_enable and StealPrompt[steal_ped] then
            Citizen.InvokeNative(0x00EDE88D4D13CF59, StealPrompt[steal_ped]) -- UiPromptDelete
            StealPrompt[steal_ped] = nil
        end
    end
    return data_steal
end

AddEventHandler('onResourceStop', function(resourceName)
    if (GetCurrentResourceName() ~= resourceName) then
        return
    end

    for _, v in pairs(StealPrompt) do
        Citizen.InvokeNative(0x00EDE88D4D13CF59, v) -- UiPromptDelete
    end

    MenuData.CloseAll()

    if IsPedActiveInScenario(PlayerPedId()) then
        ClearPedTasksImmediately(PlayerPedId())
    end
end)


import warnings

import pytest

from pandas.util._exceptions import rewrite_warning

import pandas._testing as tm

@pytest.mark.parametrize(
    "target_category, target_message, hit",
    [
        (FutureWarning, "Target message", True),
        (FutureWarning, "Target", True),
        (FutureWarning, "get mess", True),
        (FutureWarning, "Missed message", False),
        (DeprecationWarning, "Target message", False),
    ],
)
@pytest.mark.parametrize(
    "new_category",
    [
        None,
        DeprecationWarning,
    ],
)
def test_rewrite_warning(target_category, target_message, hit, new_category):
    new_message = "Rewritten message"
    if hit:
        expected_category = new_category if new_category else target_category
        expected_message = new_message
    else:
        expected_category = FutureWarning
        expected_message = "Target message"
    with tm.assert_produces_warning(expected_category, match=expected_message):
        with rewrite_warning(
            target_message, target_category, new_message, new_category
        ):
            warnings.warn(message="Target message", category=FutureWarning)


1H - Shadowmoon Grunt",
[32612] = "Monster - Black Temple - Axe, 2H - Shadowmoon Houndmaster",
[32613] = "Monster - Black Temple - Bow, 2H - Shadowmoon Houndmaster",
[32614] = "Monster - Black Temple - Sword, 2H - Shadowmoon Weapon Master",
[32615] = "Monster - Black Temple - Sword, 1H - Shadowmoon Soldier",
[32616] = "Яйцо Эгберта",
[32617] = "Вилли-соня",
[32618] = "[DEPRECATED]Crystalforged Darkrune",
[32619] = "Консервированный фрукт",
[32620] = "Затерянный во времени свиток",
[32621] = "Полупереваренная рука",
[32622] = "Дрессировочный ошейник элекка",
[32623] = "Запчасти Босси",
[32624] = "Большая железная метаморфозная жеода",
[32625] = "Малая железная метафорфозная жеода",
[32626] = "Большая медная метаморфозная жеода",
[32627] = "Малая медная метаморфозная жеода",
[32628] = "Большая серебряная метаморфозная жеода",
[32629] = "Большая золотая метаморфозная жеода",
[32630] = "Малая золотая метаморфозная жеода",
[32631] = "Малая серебряная метаморфозная жеода",
[32632] = "Monster - Glavie, Illidan - Black Temple (Right Hand)",
[32633] = "Monster - Glavie, Illidan - Black Temple (Left Hand)",
[32634] = "Изменчивый аметист",
[32635] = "Вневременной аметист",
[32636] = "Очищенный аметист",
[32637] = "Смертоносный цитрин",
[32638] = "Тревожный цитрин",
[32639] = "Зазубренный моховик",
[32640] = "Плотный неуравновешенный алмаз",
[32641] = "Глубокий неуравновешенный алмаз",
[32642] = "Изначальная темная руна",
[32643] = "Темная руна",
[32644] = "Monster - Staff, 1H - Chief Overseer Mudlump",
[32645] = "Кристаллический арбалет",
[32646] = "Медальон Карабора",
[32647] = "Наручи из связанных осколков",
[32648] = "Сапоги-вихреходы",
[32649] = "Медальон Карабора",
[32650] = "Небесно-голубой хрустальный жезл",
[32651] = "Хрустальная сфера Просвещения",
[32652] = "Эгида Огри'ла",
[32653] = "Апекситовый плащ",
[3


       assert_eq!(
            junk_server.inner.lock().unwrap().log2.len(),
            nrpcs,
            "wrong number of RPCs delivered"
        );

        let n = net.count(server.name());
        assert_eq!(n, total, "wrong count() {}, expected {}", n, total);
    }

    // regression: an RPC that's delayed during Enabled=false
    // should not delay subsequent RPCs (e.g. after Enabled=true).
    #[test]
    fn test_regression1() {
        init_logger();

        let (net, server, junk_server) = junk_suit();
        let server_name = server.name();

        let client_name = "client";
        let client = JunkClient::new(net.create_client(client_name.to_owned()));
        net.connect(client_name, server_name);

        // start some RPCs while the Client is disabled.
        // they'll be delayed.
        net.enable(client_name, false);

        let pool = futures_cpupool::CpuPool::new_num_cpus();
        let (tx, rx) = mpsc::channel::<bool>();
        let nrpcs = 20;
        for i in 0..20 {
            let sender = tx.clone();
            let client_ = client.clone();
            pool.spawn_fn(move || {
                let x = i + 100;
                // this call ought to return false.
                let _ = client_.handler2(&JunkArgs { x });
                sender.send(true)
            })
            .forget();
        }

        // FIXME: have to sleep 300ms to pass the test
        //        in my computer (i5-4200U, 4 threads).
        thread::sleep(time::Duration::from_millis(100 * 3));

        let t0 = time::Instant::now();
        net.enable(client_name, true);
        let x = 99;
        let reply = client.handler2(&JunkArgs { x }).wait().unwrap();
        assert_eq!(reply.x, format!("handler2-{}", x));
        let dur = t0.elapsed();
        assert!(
            dur < time::Duration::from_millis(30),
            "RPC took too long ({:?}) after Enable",
            dur
        );

        for _ in 0..nrpcs {
            rx.recv().unwrap();
        }

        let len = junk_server.inner.lock().unwrap().log2.len();
        assert!(
            len == 1,
            "wrong number ({}) of RPCs delivered, expected 1",
            len
        );

        let n = net.count(server.name());
        assert!(n == 1, "wrong count() {}, expected 1", n);
    }

    // if an RPC is stuck in a server, and the server
    // is killed with DeleteServer(), does the RPC
    // get un-stuck?
    #[test]
    fn test_killed() {
        init_logger();

        let (net, server, _junk_server) = junk_suit();
        let server_name = server.name();

        let client_name = "client";
        let client = JunkClient::new(net.create_client(client_name.to_owned()));
        net.connect(client_name, &server_name);
        net.enable(client_name, true);
        let (tx, rx) = mpsc::channel();
        client.spawn(client.handler3(&JunkArgs { x: 99 }).then(move |reply| {
            tx.send(reply).unwrap();
            Ok(())
        }));
        thread::sleep(time::Duration::from_secs(1));
        rx.recv_timeout(time::Duration::from_millis(100))
            .unwrap_err();

        net.delete_server(server_name);
        let reply = rx.recv_timeout(time::Duration::from_millis(100)).unwrap();
        assert_eq!(reply, Err(Error::Stopped));
    }

    struct Hooks {
        drop_req: AtomicBool,
        drop_resp: AtomicBool,
    }


cycle && lifecycle.setup) {
                    lifecycle.setup();
                }
            },
            teardown : function () {
                moment.locale('en');
                if (lifecycle && lifecycle.teardown) {
                    lifecycle.teardown();
                }
            }
        });
    }

    localeModule('my');

    test('parse', function (assert) {
        var tests = 'ဇန်နဝါရီ ဇန်_ဖေဖော်ဝါရီ ဖေ_မတ် မတ်_ဧပြီ ပြီ_မေ မေ_ဇွန် ဇွန်_ဇူလိုင် လိုင်_သြဂုတ် သြ_စက်တင်ဘာ စက်_အောက်တိုဘာ အောက်_နိုဝင်ဘာ နို_ဒီဇင်ဘာ ဒီ'.split('_'),
            i;

        function equalTest (input, mmm, i) {
            assert.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1));
        }
        for (i = 0; i < 12; i++) {
            tests[i] = tests[i].split(' ');
            equalTest(tests[i][0], 'MMM', i);
            equalTest(tests[i][1], 'MMM', i);
            equalTest(tests[i][0], 'MMMM', i);
            equalTest(tests[i][1], 'MMMM', i);
            equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i);
            equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i);
            equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i);
            equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i);
        }
    });

    test('format', function (assert) {
        var a = [
                ['dddd, MMMM Do YYYY, h:mm:ss a', 'တနင်္ဂနွေ, ဖေဖော်ဝါရီ ၁၄ ၂၀၁၀, ၃:၂၅:၅၀ pm'],
                ['ddd, hA', 'နွေ, ၃PM'],
                ['M Mo MM MMMM MMM', '၂ ၂ ၀၂ ဖေဖော်ဝါရီ ဖေ'],
                ['YYYY YY', '၂၀၁၀ ၁၀'],
                ['D Do DD', '၁၄ ၁၄ ၁၄'],
                ['d do dddd ddd dd', '၀ ၀ တနင်္ဂနွေ နွေ နွေ'],
                ['DDD DDDo DDDD', '၄၅ ၄၅ ၀၄၅'],
                ['w wo ww', '၆ ၆ ၀၆'],
                ['h hh', '၃ ၀၃'],
                ['H HH', '၁၅ ၁၅'],
                ['m mm', '၂၅ ၂၅'],
                ['s ss', '၅၀ ၅၀'],
                ['a A', 'pm PM'],
                ['[နှစ်၏] DDDo [ရက်မြောက်]', 'နှစ်၏ ၄၅ ရက်မြောက်'],
                ['LTS', '၁၅:၂၅:၅၀'],
                ['L', '၁၄/၀၂/၂၀၁၀'],
                ['LL', '၁၄ ဖေဖော်ဝါရီ ၂၀၁၀'],
                ['LLL', '၁၄ ဖေဖော်ဝါရီ ၂၀၁၀ ၁၅:၂၅'],
                ['LLLL', 'တနင်္ဂနွေ ၁၄ ဖေဖော်ဝါရီ ၂၀၁၀ ၁၅:၂၅'],
                ['l', '၁၄/၂/၂၀၁၀'],
                ['ll', '၁၄ ဖေ ၂၀၁၀'],
                ['lll', '၁


  br i1 [[TMP933]], label [[UCX_ATOMIC_EXIT91:%.*]], label [[UCX_ATOMIC_CONT92:%.*]]
// CHECK:       ucx.atomic.cont92:
// CHECK-NEXT:    store i8 [[TMP932]], ptr [[UCV]], align 1
// CHECK-NEXT:    br label [[UCX_ATOMIC_EXIT91]]
// CHECK:       ucx.atomic.exit91:
// CHECK-NEXT:    [[TMP934:%.*]] = extractvalue { i8, i1 } [[TMP931]], 1
// CHECK-NEXT:    [[TMP935:%.*]] = zext i1 [[TMP934]] to i8
// CHECK-NEXT:    store i8 [[TMP935]], ptr [[UCR]], align 1
// CHECK-NEXT:    call void @__kmpc_flush(ptr @[[GLOB1]])
// CHECK-NEXT:    [[TMP936:%.*]] = load i16, ptr [[SE]], align 2
// CHECK-NEXT:    [[TMP937:%.*]] = atomicrmw max ptr [[SX]], i16 [[TMP936]] monotonic, align 2
// CHECK-NEXT:    store i16 [[TMP937]], ptr [[SV]], align 2
// CHECK-NEXT:    [[TMP938:%.*]] = load i16, ptr [[SE]], align 2
// CHECK-NEXT:    [[TMP939:%.*]] = atomicrmw min ptr [[SX]], i16 [[TMP938]] monotonic, align 2
// CHECK-NEXT:    store i16 [[TMP939]], ptr [[SV]], align 2
// CHECK-NEXT:    [[TMP940:%.*]] = load i16, ptr [[SE]], align 2
// CHECK-NEXT:    [[TMP941:%.*]] = atomicrmw min ptr [[SX]], i16 [[TMP940]] monotonic, align 2
// CHECK-NEXT:    store i16 [[TMP941]], ptr [[SV]], align 2
// CHECK-NEXT:    [[TMP942:%.*]] = load i16, ptr [[SE]], align 2
// CHECK-NEXT:    [[TMP943:%.*]] = atomicrmw max ptr [[SX]], i16 [[TMP942]] monotonic, align 2
// CHECK-NEXT:    store i16 [[TMP943]], ptr [[SV]], align 2
// CHECK-NEXT:    [[TMP944:%.*]] = load i16, ptr [[SE]], align 2
// CHECK-NEXT:    [[TMP945:%.*]] = load i16, ptr [[SD]], align 2
// CHECK-NEXT:    [[TMP946:%.*]] = cmpxchg ptr [[SX]], i16 [[TMP944]], i16 [[TMP945]] monotonic monotonic, align 2
// CHECK-NEXT:    [[TMP947:%.*]] = extractvalue { i16, i1 } [[TMP946]], 0
// CHECK-NEXT:    store i16 [[TMP947]], ptr [[SV]], align 2
// CHECK-NEXT:    [[TMP948:%.*]] = load i16, ptr [[SE]], align 2
// CHECK-NEXT:    [[TMP949:%.*]] = load i16, ptr [[SD]], align 2
// CHECK-NEXT:    [[TMP950:%.*]] = cmpxchg ptr [[SX]], i16 [[TMP948]], i16 [[TMP949]] monotonic monotonic, align 2
// CHECK-NEXT:    [[TMP951:%.*]] = extractvalue { i16, i1 } [[TMP950]], 0
// CHECK-NEXT:    store i16 [[TMP951]], ptr [[SV]], align 2
// CHECK-NEXT:    [[TMP952:%.*]] = load i16, ptr [[SE]], align 2
// CHECK-NEXT:    [[TMP953:%.*]] = atomicrmw max ptr [[SX]], i16 [[TMP952]] monotonic, align 2
// CHECK-NEXT:    [[TMP954:%.*]] = icmp sgt i16 [[TMP953]], [[TMP952]]
// CHECK-NEXT:    [[TMP955:%.*]] = select


, encryptionAlg);
    }

    public byte[] generateCertReq(String dn, String password, String transactionId, X509Certificate ca, Extensions exts,
            final X509Certificate senderCertificate, final PrivateKey signatureKey, ASN1ObjectIdentifier encryptionAlg) throws OperatorCreationException, CertificateException,
            IOException, CMSException {
        this.cacert = ca;
        this.reqdn = dn;
        // Generate keys

        // Create challenge password attribute for PKCS10
        // Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }}
        //
        // Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE {
        //    type    ATTRIBUTE.&id({IOSet}),
        //    values  SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{\@type})
        // }
        ASN1EncodableVector challpwdattr = new ASN1EncodableVector();
        // Challenge password attribute
        challpwdattr.add(PKCSObjectIdentifiers.pkcs_9_at_challengePassword);
        ASN1EncodableVector pwdvalues = new ASN1EncodableVector();
        pwdvalues.add(new DERUTF8String(password));
        challpwdattr.add(new DERSet(pwdvalues));
        ASN1EncodableVector extensionattr = new ASN1EncodableVector();
        extensionattr.add(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
        extensionattr.add(new DERSet(exts));
        // Complete the Attribute section of the request, the set (Attributes) contains two sequences (Attribute)
        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(new DERSequence(challpwdattr));
        v.add(new DERSequence(extensionattr));
        DERSet attributes = new DERSet(v);
        // Create PKCS#10 certificate request
        final PKCS10CertificationRequest p10request = CertTools.genPKCS10CertificationRequest("SHA256WithRSA",
                CertTools.stringToBcX500Name(reqdn), keys.getPublic(), attributes, keys.getPrivate(), null);

        // wrap message in pkcs#7
        return wrap(p10request.getEncoded(), Integer.toString(ScepRequestMessage.SCEP_TYPE_PKCSREQ), transactionId, senderCertificate, signatureKey, encryptionAlg);
    }

    public byte[] generateGetCertInitial(String dn, String transactionId, X509Certificate caCertificate, final X509Certificate senderCertificate,
            final PrivateKey signatureKey, ASN1ObjectIdentifier encryptionAlg) throws CertificateEncodingException, CMSException, IOException {
        this.cacert = caCertificate;
        this.reqdn = dn;

        // pkcsGetCertInitial issuerAndSubject ::= {
        //	    issuer "the certificate authority issuer name"
        //	    subject "the requester subject name as given in PKCS#10"
        //	}
        ASN1EncodableVector vec = new ASN1EncodableVector();
        vec.add(CertTools.stringToBcX500Name(caCertificate.getIssuerDN().getName()));
        vec.add(CertTools.stringToBcX500Name(dn));
        DERSequence seq = new DERSequence(vec);

        // wrap message in pkcs#7
        return wrap(seq.getEncoded(), Integer.toString(ScepRequestMessage.SCEP_TYPE_GETCERTINITIAL), transactionId, senderCertificate, signatureKey, encryptionAlg);
    }

    /**
     * @param encryptionAlg SMIMECapability.dES_CBC (DES) or SMIMECapability.dES_EDE3_CBC (3DES)
     */
    private CMSEnvelopedData envelope(CMSTypedData envThis, ASN1ObjectIdentifier encryptionAlg) throws CMSException, CertificateEncodingException {
        CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
        // Envelope the CMS message
        edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(cacert).setProvider(BouncyCastleProvider.PROVIDER_NAME));
        JceCMSContentEncryptorBuilder jceCMSContentEncryptorBuilder = new JceCMSContentEncryptorBuilder(encrypt


Redis 服务不可用的情况：**

1. 采用 Redis 集群，避免单机出现问题整个缓存服务都没办法使用。
2. 限流，避免同时处理大量的请求。

**针对热点缓存失效的情况：**

1. 设置不同的失效时间比如随机设置缓存的失效时间。
2. 缓存永不失效。

#### 如何保证缓存和数据库数据的一致性？

细说的话可以扯很多，但是我觉得其实没太大必要（小声 BB：很多解决方案我也没太弄明白）。我个人觉得引入缓存之后，如果为了短时间的不一致性问题，选择让系统设计变得更加复杂的话，完全没必要。

下面单独对 **Cache Aside Pattern（旁路缓存模式）** 来聊聊。

Cache Aside Pattern 中遇到写请求是这样的：更新 DB，然后直接删除 cache 。

如果更新数据库成功，而删除缓存这一步失败的情况的话，简单说两个解决方案：

1. **缓存失效时间变短（不推荐，治标不治本）** ：我们让缓存数据的过期时间变短，这样的话缓存就会从数据库中加载数据。另外，这种解决办法对于先操作缓存后操作数据库的场景不适用。
2. **增加 cache 更新重试机制（常用）**： 如果 cache 服务当前不可用导致缓存删除失败的话，我们就隔一段时间进行重试，重试次数可以自己定。如果多次重试还是失败的话，我们可以把当前更新失败的 key 存入队列中，等缓存服务可用之后，再将缓存中对应的 key 删除即可。

相关文章推荐：[缓存和数据库一致性问题，看这篇就够了 - 水滴与银弹](https://mp.weixin.qq.com/s?__biz=MzIyOTYxNDI5OA==&mid=2247487312&idx=1&sn=fa19566f5729d6598155b5c676eee62d&chksm=e8beb8e5dfc931f3e35655da9da0b61c79f2843101c130cf38996446975014f958a6481aacf1&scene=178&cur_album_id=1699766580538032128#rd)

------

# 5. 常用框架

> [JavaGuide](https://javaguide.cn/) ：「Java学习+面试指南」一份涵


struct.Filter.html\" title=\"struct futures_util::stream::Filter\">Filter<St, Fut, F>where\n    St: Stream + Debug,\n    St::Item: Debug,\n    Fut: Debug,"],["impl<Fut> Debug for FuturesUnordered<Fut>"],["impl<T, E: Debug> Debug for TryReadyChunksError<T, E>"],["impl<'a, R: Debug + ?Sized> Debug for ReadUntil<'a, R>"],["impl Debug for Repeat"],["impl<F> Debug for <a class=\"struct\" href=\"futures_util/future/struct.TryJoinAll.html\" title=\


	var shortcut = config.pdfExportShortcut || 'E';
			window.addEventListener( 'keydown', function( e ){
				if( e.target.nodeName.toUpperCase() == 'BODY'
					&& ( e.key.toUpperCase() == shortcut.toUpperCase() || e.keyCode == shortcut.toUpperCase().charCodeAt( 0 ) ) ){
					e.preventDefault();
					togglePdfExport();
					return false;
				}
			}, true );
		}
	}

	function isPrintingPDF(){
		return ( /print-pdf/gi ).test( window.location.search );
	}

	function togglePdfExport(){
		var url_doc = new URL( document.URL );
		var query_doc = new URLSearchParams( url_doc.searchParams );
		if( isPrintingPDF() ){
			query_doc.delete( 'print-pdf' );
		}else{
			query_doc.set( 'print-pdf', '' );
		}
		url_doc.search = ( query_doc.toString() ? '?' + query_doc.toString() : '' );
		window.location.href = url_doc.toString();
	}

	function installKeyBindings(){
		var config = Reveal.getConfig();
		var shortcut = config.pdfExportShortcut || 'E';
		Reveal.addKeyBinding({
			keyCode: shortcut.toUpperCase().charCodeAt( 0 ),
			key: shortcut.toUpperCase(),
			description: 'PDF export mode'
		}, togglePdfExport );
		installAltKeyBindings();
	}

	function install(){
		installKeyBindings();
		setStylesheet( isPrintingPDF() );
	}

	var Plugin = {
	}

	if( Reveal && Reveal.VERSION && Reveal.VERSION.length && Reveal.VERSION[ 0 ] == '3' ){
		// reveal 3.x
		setStylesheet = setStylesheet3;
		installAltKeyBindings = installAltKeyBindings3;
		install();
	}else{
		// must be reveal 4.x
		setStylesheet = setStylesheet4;
		installAltKeyBindings = installAltKeyBindings4;
		Plugin.id = 'pdf-export';
		Plugin.init = function( _Reveal ){
			Reveal = _Reveal;
			install();
		};
	}

	return Plugin;

})( Reveal );
const mongoose = require('mongoose');
require('dotenv').config();
const Book = require('./models/Book');

const sampleBooks = [
  {
    title: "Włam się do mózgu",
    author: "Radek Kotarski",
    cover: "/images/wlam_sie_do_mozgu_book.svg",
    category: "Poradniki",
    price: 39.99,
    isPopular: true,
    isNewRelease: false,
    isBestseller: false,
    format: "paperback",
    inStock: 100,
    description: "Czy kiedykolwiek zastanawiałeś się, dlaczego niektóre metody nauki działają, a inne sprawiają, że jedynie tracisz czas? Radek Kotarski w swojej książce 'Włam się do mózgu' zabiera czytelników w fascynującą podróż po tajnikach efektywnego uczenia się. Książka oparta na licznych badaniach naukowych oraz osobistych doświadczeniach autora prezentuje sprawdzone techniki, k


'*',
  command = [[if &nu | set nornu | endif]],
  group = vimrc_group,
})

vim.filetype.add({
  pattern = {
    ['.env*'] = 'conf',
    ['*.mjml'] = 'html',
    ['.*waybar/config'] = 'jsonc',
  },
})

return settings


 */
    explicit Array(const std::vector<JS::Any>& data);
    /** @brief Constructor for properties with a given set of properties */
    explicit Array(const JS::Properties& properties);
    ///@}

    /** @brief The destructor for the object defaulted */
    ~Array() override = default;

    /**
     * @name Methods that override internal methods of the Object
     */
    ///@{
    /**
     * @brief Define a property in the Array object.
     * https://262.ecma-international.org/5.1/#sec-15.4.5.1
     */
    bool defineOwnProperty(const std::u16string& key, JS::Attribute attribute, bool is_throw = false) final;
    ///@}

    /**
     * @name Prototype methods of the Array object built-in
     */
    ///@{
    /** @brief Returns a string representing the specified object. https://262.ecma-international.org/5.1/#sec-15.4.4.2
     */
    static JS::Any toString(const JS::Any& thisArg, const JS::Any& args);
    /** @brief Returns the locale string of it. https://262.ecma-international.org/5.1/#sec-15.4.4.3 */
    static JS::Any toLocaleString(const JS::Any& thisArg, const JS::Any& args);
    /** @brief Concatenates the array with other values. https://262.ecma-international.org/5.1/#sec-15.4.4.4 */
    static JS::Any concat(const JS::Any& thisArg, const JS::Any& args);
    /** @brief Joins all elements of the array into a string. https://262.ecma-international.org/5.1/#sec-15.4.4.5 */
    static JS::Any join(const JS::Any& thisArg, const JS::Any& args);
    /** @brief Removes the last element from the array and returns it.
     * https://262.ecma-international.org/5.1/#sec-15.4.4.6 */
    static JS::Any pop(const JS::Any& thisArg, const JS::Any& args);
    /** @brief Adds one or more elements to the end of the array and returns the new length.
     * https://262.ecma-international.org/5.1/#sec-15.4.4.7 */
    static JS::Any push(const JS::Any& thisArg, const JS::Any& args);
    /** @brief Reverses the order of the elements in the array. https://262.ecma-international.org/5.1/#sec-15.4.4.8 */
    static JS::Any reverse(const JS::Any& thisArg, const JS::Any& args);
    /** @brief Removes the first element from the array and returns it.
     * https://262.ecma-international.org/5.1/#sec-15.4.4.9 */
    static JS::Any shift(const JS::Any& thisArg, const JS::Any& args);
    /** @brief Returns a shallow copy of a portion of the array. https://262.ecma-international.org/5.1/#sec-15.4.4.10
     */
    static JS::Any slice(const JS::Any& thisArg, const JS::Any& args);
    /** @brief Sorts the elements of the array in place. https://262.ecma-international.org/5.1/#sec-15.4.4.11 */
    static JS::Any sort(const JS::Any& thisArg, const JS::Any& args);
    /** @brief Changes the contents of the array by removing or replacing elements.
     * https://262.ecma-international.org/5.1/#sec-15.4.4.12 */
    static JS::Any splice(const JS::Any& thisArg, const JS::Any& args);
    /** @brief Adds one or more elements to the beginning of the array and returns the new length.
     * https://262.ecma-international.org/5.1/#sec-15.4.4.13 */
    static JS::Any unshift(const JS::Any& thisArg, const JS::Any& args);
    /** @brief Returns the first index at which a given element can be found.


s_BaseNeuralNode">BaseNeuralNode 方法

SetChildNode 方法

BaseNeuralNodeSetChildNode 方法

Senparc.Weixin SDK 官方教程《微信开发深度解析》已出版，支持中国开源事业，请【购买正版】！

《微信公众号+小程序》视频课程已经上线，【点击这里】学习！

NeuChar（纽插）已经上线，为开发者提供一站式跨平台管理枢纽，并可将应用入驻到 NeuChar 应用商店！新功能正在不断增加中，快来使用吧！ https://www.neuchar.com

在线动态微信接口 Swagger WebApi 文档： https://weixin.senparc.com:8039

            设置子节点

        命名空间：
     Senparc.NeuChar.NeuralSystems

        程序集：
     Senparc.NeuChar (在 Senparc.NeuChar.dll 中) 版本：1.4.400+9276a4a7db0d8fb887fc6634357928e7b33f68fa
语法

C#
<div id="


tType::put__MediaFormatType (tuner.h)
description: The put__MediaFormatType method sets the DirectShow media format type.
helpviewer_keywords: ["IComponentType interface [Microsoft TV Technologies]","put__MediaFormatType method","IComponentType.put__MediaFormatType","IComponentType::put__MediaFormatType","IComponentTypeput__MediaFormatType","mstv.icomponenttype_put__mediaformattype","put__MediaFormatType","put__MediaFormatType method [Microsoft TV Technologies]","put__MediaFormatType method [Microsoft TV Technologies]","IComponentType interface","tuner/IComponentType::put__MediaFormatType"]
old-location: mstv\icomponenttype_put__mediaformattype.htm
tech.root: mstv
ms.assetid: 37baa69e-d942-41d6-b497-bf37d6b0d57b
ms.date: 12/05/2018
ms.keywords: IComponentType interface [Microsoft TV Technologies],put__MediaFormatType method, IComponentType.put__MediaFormatType, IComponentType::put__MediaFormatType, IComponentTypeput__MediaFormatType, mstv.icomponenttype_put__mediaformattype, put__MediaFormatType, put__MediaFormatType method [Microsoft TV Technologies], put__MediaFormatType method [Microsoft TV Technologies],IComponentType interface, tuner/IComponentType::put__MediaFormatType
req.header: tuner.h
req.include-header:
req.target-type: Windows
req.target-min-winverclnt: WindowsXP [desktop apps only]
req.target-min-winversvr: None supported
req.kmdf-ver:
req.umdf-ver:
req.ddi-compliance:
req.unicode-ansi:
req.idl: Tuner.idl
req.max-support:
req.namespace:
req.assembly:
req.type-library:
req.lib:
req.dll:
req.irql:
targetos: Windows
req.typenames:
req.redist:
ms.custom: 19H1
f1_keywords:
 - IComponentType::put__MediaFormatType
 - tuner/IComponentType::put__MediaFormatType
dev_langs:
 - c++
topic_type:
 - APIRef
 - kbSyntax
api_type:
 - COM
api_location:
 - tuner.h
api_name:
 - IComponentType.put__MediaFormatType
---

# IComponentType::put__MediaFormatType

## -description

\[The feature associated with this page, [Microsoft TV Technologies](/previous-versions/windows/desktop/mstv/microsoft-tv-technologies-portal), is a legacy feature. Microsoft strongly recommends that new code does not use this feature.\]

The put__MediaFormatType method sets the DirectShow media format type.

## -parameters

### -param MediaFormatTypeGuid [in]

REFCLSID that specifies the media format type.

## -returns

Returns S_OK if successful. If the method fails, error information can be retrieved using the standard COM IErrorInfo interface.

## -remarks

This method is available through C++ only. Note the two underscores in the method name as compared to the one underscore for the method that uses a BSTR as a parameter.

## -see-also

AM_MEDIA_TYPE

IComponentType Interface---
UID: NN:tuner.IPersistTuneXmlUtility2
title: IPersistTuneXmlUtility2 (tuner.h)
description: Defines utility methods for serializing tuning requests (objects that implement the ITuneRequest interface) to XML tuning request strings.
helpviewer_keywords: ["


{
    var searchString = window.location.search.substring(1),
      i,
      val,
      params = searchString.split('&');

    for (i = 0; i < params.length; i++) {
      val = params[i].split('=');
      if (val[0] == paramName) {
        return val[1];
      }
    }
    return null;
  }

  static isNumber(n): boolean {
    return !isNaN(parseFloat(n)) && isFinite(n);
  }
}
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Rx';
import { Task } from '../model/task';
import { Const } from '../utils/const';

@Injectable()
export class TaskServiceProvider {
  baseURL = `${Const.API_BASE_URL}${Const.API_VERSION}`;

  constructor(public http: Http) {
  }

  /**
   * 全タスクを取得
   */
  getTasks(): Observable<Task[]> {
    return this.http.get(`${this.baseURL}/tasks`)
      .map(res => res.json() as Task[]);
  }
  /**
   * ID指定でタスクを取得
   */
  getTaskById(task_id: number): Observable<Task> {
    return this.http.get(`${this.baseURL}/task/${task_id}`)
      .map(res => res.json() as Task);
  }
  /**
   * 新規タスクを登録
   */
  addTask(task: Task): Observable<Task> {
    return this.http.post(`${this.baseURL}/task`, task)
      .map(res => null);
  }
  /**
   * タスクを削除
   */
  delTask(task_id: number): Observable<boolean> {
    return this.http.delete(`${this.baseURL}/task/${task_id}`)
      .map(res => res.json() as boolean);
  }
  /**
   * タスクのステータスを更新
   */
  updTask(task_id: number, status: number): Observable<boolean> {
    return this.http.put(`${this.baseURL}/task/${task_id}`, { status: status })
      .map(res => res.json() as boolean);
  }
  /**
   * タスクを更新
   */
  edtTask(task: Task): Observable<boolean> {
    return this.http.put(`${this.baseURL}/task/${task.task_id}`, { task: task })
      .map(res => res.json() as boolean);
  }
}
export default class LevelData {
    title: string;
    nodes: NodeData[];
    edges: LevelEdgeData[];
}

export class NodeData {
    x: number;
    y: number;
    type: NodeType;
    level: number;
    api?: NodeAPIType
}

export type Point = [number, number];
export interface PointObj {
    x: number;
    y: number
}

type LevelEdgeData = [Point, Point, LevelEdgeDirection];

export enum LevelEdgeDirection {
    LTR = "ltr",
    RTL = "rtl",
    BI = "bid"
}

export enum NodeType {
    API = "api",
    DATA = "data",
    ENTRY = "entry",
    EXIT = "exit",
    FOLDER = "folder",
    SERVER = "server"
}

enum NodeAPIType {
    CLEARANCE = "clearance",
    SPAM = "spam",
    SOFTEN = "soften",
    TRANSFER = "transfer"
}
/*
 * @lc app=leetcode.cn id=347 lang=typescript
 *
 * [347] 前 K 个高频元素
 */

// @lc code=start
function topKFrequent(nums: number[], k: number): number[] {
    nums.sort((a, b) => a - b);
    let map = new Map();
    for (let i = 0; i < nums.length; i++) {
        let key = nums[i];
        let count = 1;
        if (map.has(key)) {
            count += map.get(key);
        }
        map.set(key, count)
    }
    let


>";
            public const string i_phonelink_lock = "<path d=\"M0 0h24v24H0V0z\" fill=\"none\"/><path d=\"M19 1H9c-1.1 0-2 .9-2 2v3h2V4h10v16H9v-2H7v3c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm-8.2 10V9.5C10.8 8.1 9.4 7 8 7S5.2 8.1 5.2 9.5V11c-.6 0-1.2.6-1.2 1.2v3.5c0 .7.6 1.3 1.2 1.3h5.5c.7 0 1.3-.6 1.3-1.2v-3.5c0-.7-.6-1.3-1.2-1.3zm-1.3 0h-3V9.5c0-.8.7-1.3 1.5-1.3s1.5.5 1.5 1.3V11z\"/>";
            public const string i_phonelink_off = "<path d=\"M0 0h24v24H0V0zm0 0h24v24H0V0z\" fill=\"none\"/><path d=\"M22 6V4H7.39l2 2zm2 13V9c0-.55-.45-1-1-1h-6c-.55 0-1 .45-1 1v3.61l2 2V10h4v7h-1.61l2.93 2.93c.39-.13.68-.49.68-.93zM2.06 1.51L.65 2.92l1.82 1.82C2.18 5.08 2 5.52 2 6v11H0v3h17.73l2.35 2.35 1.41-1.41L2.06 1.51zM4 17V6.27L14.73 17H4z\"/>";
            public const string i_phonelink_ring = "<path d=\"M0 0h24v24H0V0z\" fill=\"none\"/><path d=\"M20.1 7.7l-1 1c1.8 1.8 1.8 4.6 0 6.5l1 1c2.5-2.3 2.5-6.1 0-8.5zM18 9.8l-1 1c.5.7.5 1.6 0 2.3l1 1c1.2-1.2 1.2-3 0-4.3zM14 1H4c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 19H4V4h10v16z\"/>";
            public const string i_phonelink_setup = "<path d=\"M0 0h24v24H0V0z\" fill=\"none\"/><path d=\"M7 3v3h2V4h10v16H9v-2H7v3c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2H9c-1.1 0-2 .9-2 2zm2.5 12.5c.29-.12.55-.29.8-.48l-.02.03 1.01.39c.23.09.49 0 .61-.22l.84-1.46c.12-.21.07-.49-.12-.64l-.85-.68-.02.03c.02-.16.05-.32.05-.48s-.03-.32-.05-.48l.02.03.85-.68c.19-.15.24-.43.12-.64l-.84-1.46c-.12-.21-.38-.31-.61-.22l-1.01.39.02.03c-.25-.17-.51-.34-.8-.46l-.17-1.08C9.3 7.18


.value.Size; n++)
                    {
                        if (close_queue.value[n].Dirty)
                            close_queue.value[n].DoSave();
                        close_queue.value[n].DoForceClose();
                    }
                    close_queue.value.clear();
                    ImGui.CloseCurrentPopup();
                }
                ImGui.SameLine();
                if (ImGui.Button("No", button_size))
                {
                    for (let n = 0; n < close_queue.value.Size; n++)
                        close_queue.value[n].DoForceClose();
                    close_queue.value.clear();
                    ImGui.CloseCurrentPopup();
                }
                ImGui.SameLine();
                if (ImGui.Button("Cancel", button_size))
                {
                    close_queue.value.clear();
                    ImGui.CloseCurrentPopup();
                }
                ImGui.EndPopup();
            }
        }
    }

    ImGui.End();
}

// End of Demo code
// #else

// function /*ImGui.*/ShowAboutWindow(p_open: ImGui.Access<boolean>): void {}
// function /*ImGui.*/ShowDemoWindow(p_open: ImGui.Access<boolean>): void {}
// function /*ImGui.*/ShowUserGuide(): void {}
// function /*ImGui.*/ShowStyleEditor(style: ImGui.Style): void {}

// #endif

// #endif // #ifndef IMGUI_DISABLE
import { fit, FuriganaMatch } from 'furigana';
import { toRomaji } from 'wanakana';
import { z } from 'zod';

// Jisho API types

export const JishoApiEntrySchema = z
  .object({
    slug: z.string(),
    senses: z.array(
      z
        .object({
          english_definitions: z.array(z.string()),
          parts_of_speech: z.array(z.string())
        })
        .nonstrict()
    ),
    japanese: z.array(
      z
        .object({
          word: z.string().optional(),
          reading: z.string().optional()
        })
        .nonstrict()
    ),
    is_common: z.boolean().optional()
  })
  .nonstrict();

export type JishoApiEntry = z.infer<typeof JishoApiEntrySchema>;

const JishoApiResponseSchema = z.object({
  data: z.array(JishoApiEntrySchema)
});

// Fetches a word from Jisho

export async function fetchWord(word: string): Promise<JishoApiEntry | null> {
  const response = await fetch(`https://jisho.org/api/v1/search/words?keyword=${word}`);
  const json = await response.json();

  const validation = JishoApiResponseSchema.parse(json);

  // TODO test error here

  // Jisho returns multiple entries.
  // First, we look for the entry with the searched text (not necessarily the first one).
  // If not found, we fallback to the first entry if it exists.
  return validation.data.find((entry) => entry.slug === word) ?? validation.data[0] ?? null;
}

export function entryToRomaji(entry: JishoApiEntry): string | null {
  const kanas = entry.japanese[0]?.reading;
  return kanas ? toRomaji(kanas) : null;
}

export function entryToFurigana(entry: JishoApiEntry): FuriganaMatch[] {
  // Retrieve an entry that matches the slug

  const readingWriting = entry.japanese.find(
    (j) => j.word === entry.slug || j.reading === entry.slug
  );

  // Both writing and reading provided: try to fit them into a furigana

  if (readingWriting?.word && readingWriting?.reading) {
    const fitted = fit(readingWr


  disconnect( The::engineController(), &EngineController::audioDataReady, m_worker, &Worker::receiveData );
}

void
Analyzer::Base::drawNeedChanged( const bool drawingNeeded )
{
    // Optimization for at least X11/Linux desktops:
    // Don't update the analyzer if Amarok is not on the active virtual desktop or otherwise not visible.

    if( drawingNeeded )
    {
        connectSignals();
        QTimer::singleShot( 0, m_worker, [=]() { m_worker->setHibernate( false ); } );
    }
    else
    {
        disconnectSignals();
        QTimer::singleShot( 0, m_worker, [=]() { m_worker->setHibernate( true ); } );
    }
}

void
Analyzer::Base::refreshSampleRate()
{
    const auto currentTrack = The::engineController()->currentTrack();
    int sampleRate = currentTrack ? currentTrack->sampleRate() : 44100;

    if( m_sampleRate == sampleRate )
        return;

    m_sampleRate = sampleRate;

    Q_EMIT calculateExpFactorNeeded( m_minFreq, m_maxFreq, m_sampleRate );
}

KConfigGroup
Analyzer::Base::config() const
{
    return Amarok::config( QStringLiteral( "Context" ) ).group( QStringLiteral("Analyzer") );
}

void
Analyzer::Base::setScopeSize( int scopeSize )
{
    if( scopeSize <= 0 )
    {
        debug() << "Scope size must be greater than zero";
        return;
    }

    if( m_scopeSize == scopeSize )
        return;

    m_scopeSize = scopeSize;
    Q_EMIT scopeSizeChanged( scopeSize );
    Q_EMIT calculateExpFactorNeeded( m_minFreq, m_maxFreq, m_sampleRate );
}

void
Analyzer::Base::setMaxFreq( qreal maxFreq )
{
    DEBUG_BLOCK

    debug() << "Set maximum frequency to:" << maxFreq;

    if( m_maxFreq == maxFreq || maxFreq < 0.0 )
        return;

    config().writeEntry( "maxFreq", maxFreq );
    m_maxFreq = maxFreq;
    Q_EMIT maxFreqChanged();
    Q_EMIT calculateExpFactorNeeded( m_minFreq, m_maxFreq, m_sampleRate );
}

void
Analyzer::Base::setMinFreq( qreal minFreq )
{
    DEBUG_BLOCK

    debug() << "Set minimum frequency to:" << minFreq;

    if( m_minFreq == minFreq || minFreq <= 0.0 )
        return;

    config().writeEntry( "minFreq", minFreq );
    m_minFreq = minFreq;
    Q_EMIT minFreqChanged();
    Q_EMIT calculateExpFactorNeeded( m_minFreq, m_maxFreq, m_sampleRate );
}

Analyzer::Base::WindowFunction
Analyzer::Base::windowFunction() const
{
    return (WindowFunction)config().readEntry( "windowFunction", (int)Hann );
}

void
Analyzer::Base::setWindowFunction( WindowFunction windowFunction )
{
    DEBUG_BLOCK

    debug() << "Set window function to:" << windowFunction;

    config().writeEntry( "windowFunction", (int)windowFunction );
    Q_EMIT windowFunctionChanged( windowFunction );
}

int Analyzer::Base::sampleSize() const
{
    return config().readEntry( "sampleSize", 2048 );
}

void
Analyzer::Base::setSampleSize( uint sampleSize )
{
    DEBUG_BLOCK

    debug() << "Set sample size to:" << sampleSize;

    if( sampleSize < (int) EngineController::DATAOUTPUT_DATA_SIZE )
    {
        warning() << "Sample size must be at least" << EngineController::DATAOUTPUT_DATA_SIZE;
        sampleSize = EngineController::DATAOUTPUT_DATA_SIZE;
    }

    config().writeEntry( "sampleSize", sampleSize );
    Q_EMIT sampleSizeChanged( sampleSize );
    Q_EMIT calculateExpFactorNeeded( m_minFreq, m_maxFreq, m


e:{}),r.add("modern",function(e){return Ji.setup(e),$t(e)})}(window);/*
 * 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.
 */
//@flow
import React from "react";

type Props = {
    titles: string[],
    urls?: string[],
    current?: number,
    path?: string,
}

type State = {
    noConnection: boolean,
    lightShown: boolean,
    info: ?any,
    lastSuccess: number,
    modalShown: boolean,
    errorText: ?string,
}

function ClusterResourceGroupNavBar({titles, urls, current = 0} : Props) {
    const classNames = ['navbar-brand inactive', 'navbar-brand'];
    const navBarItems = titles.map( (title, index) => {
        const classNameIdx = (current === index || !urls?.length) ? 0 : 1;
        return (

                    { classNameIdx ? {title} : title}

        );
    });
    return (
        <>{navBarItems}</>
    );
}

function isOffline() {
    return window.location.protocol === 'file:';
}

export class PageTitle extends React.Component<Props, State> {
    timeoutId: TimeoutID;

    constructor(props: Props) {
        super(props);
        this.state = {
            noConnection: false,
            lightShown: false,
            info: null,
            lastSuccess: Date.now(),
            modalShown: false,
            errorText: null,
        };
    }

    refreshLoop: () => void = () => {
        clearTimeout(this.timeoutId);
        fetch("/v1/info")
            .then(response => response.json())
            .then(info => {
                this.setState({
                    info: info,
                    noConnection: false,
                    lastSuccess: Date.now(),
                    modalShown: false,
                });
                //$FlowFixMe$ Bootstrap 5 plugin
                $('#no-connection-modal').hide();
                this.resetTimer();
            })
            .catch(error => {
                this.setState({
                    noConnection: true,
                    lightShown: !this.state.lightShown,
                    errorText: error
                });
                this.resetTimer();

                if (!this.state.modalShown && (error || (Date.now() - this.state.lastSuccess) > 30 * 1000)) {
                    //$FlowFixMe$ Bootstrap 5 plugin
                    $('#no-connection-modal').


= rand::thread_rng();

  let mut gg: Graph<u64> = Graph::new();

  for i in 0..10 {

    gg.add_vtx( i, rng.gen_range(0,2000000) as u64 );

    let jb = rng.gen_range(0,5);
    for _ in 0..jb {

      gg.add_edge( i, rng.gen_range(0,10) as u64 );

    }

  }
  gg.print();

}
<reponame>jwinarske/rs-ambiq-apollo3
#[doc = "Reader of register SHADOWVALID"]
pub type R = crate::R<u32, super::SHADOWVALID>;
#[doc = "Writer for register SHADOWVALID"]
pub type W = crate::W<u32, super::SHADOWVALID>;
#[doc = "Register SHADOWVALID `reset()`'s with value 0x07"]
impl crate::ResetValue for super::SHADOWVALID {
    type Type = u32;
    #[inline(always)]
    fn reset_value() -> Self::Type {
        0x07
    }
}
#[doc = "Indicates whether info0 contains valid data\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum INFO0_VALID_A {
    #[doc = "1: Flash info0 (customer) space contains valid data. value."]
    VALID = 1,
}
impl From<INFO0_VALID_A> for bool {
    #[inline(always)]
    fn from(variant: INFO0_VALID_A) -> Self {
        variant as u8 != 0
    }
}
#[doc = "Reader of field `INFO0_VALID`"]
pub type INFO0_VALID_R = crate::R<bool, INFO0_VALID_A>;
impl INFO0_VALID_R {
    #[doc = r"Get enumerated values variant"]
    #[inline(always)]
    pub fn variant(&self) -> crate::Variant<bool, INFO0_VALID_A> {
        use crate::Variant::*;
        match self.bits {
            true => Val(INFO0_VALID_A::VALID),
            i => Res(i),
        }
    }
    #[doc = "Checks if the value of the field is `VALID`"]
    #[inline(always)]
    pub fn is_valid(&self) -> bool {
        *self == INFO0_VALID_A::VALID
    }
}
#[doc = "Write proxy for field `INFO0_VALID`"]
pub struct INFO0_VALID_W<'a> {
    w: &'a mut W,
}
impl<'a> INFO0_VALID_W<'a> {
    #[doc = r"Writes `variant` to the field"]
    #[inline(always)]
    pub fn variant(self, variant: INFO0_VALID_A) -> &'a mut W {
        {
            self.bit(variant.into())
        }
    }
    #[doc = "Flash info0 (customer) space contains valid data. value."]
    #[inline(always)]
    pub fn valid(self) -> &'a mut W {
        self.variant(INFO0_VALID_A::VALID)
    }
    #[doc = r"Sets the field bit"]
    #[inline(always)]
    pub fn set_bit(self) -> &'a mut W {
        self.bit(true)
    }
    #[doc = r"Clears the field bit"]
    #[inline(always)]
    pub fn clear_bit(self) -> &'a mut W {
        self.bit(false)
    }
    #[doc = r"Writes raw bits to the field"]
    #[inline(always)]
    pub fn bit(self, value: bool) -> &'a mut W {
        self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
        self.w
    }
}
#[doc = "Indicates whether the bootloader should sleep or deep sleep if no image loaded.\n\nValue on reset: 1"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum BLDSLEEP_A {
    #[doc = "1: Bootloader will go to deep sleep if no flash image loaded value."]


N)
{
    const size_t numPoints = xval.size();
    if(fval.size() != numPoints)
        throw std::length_error("CubicSpline: input arrays are not equal in length");
    if(numPoints < 2)
        return std::vector<double>(numPoints,
            isFinite(derivLeft) ? derivLeft : isFinite(derivRight) ? derivRight : 0);

    // construct and solve the linear system for first derivatives
    std::vector<double> rhs(numPoints);
    BandMatrix<double>  mat(numPoints, 1, 0.);
    for(size_t i = 0; i < numPoints-1; i++) {
        const double
        dxi = 1 / (xval[i+1] - xval[i]),
        dyx = (fval[i+1] - fval[i]) * pow_2(dxi);
        mat(i,  i)   += 2 * dxi;  // diag current row
        mat(i+1,i+1) += 2 * dxi;  // diag next row
        mat(i,  i+1)  = dxi;      // above-diag current
        mat(i+1,i)    = dxi;      // below-diag next
        rhs[i]       += 3 * dyx;
        rhs[i+1]     += 3 * dyx;
    }
    if(isFinite(derivLeft)) {   // for a clamped spline, the derivative at the endpoint is already known
        mat(0,0) = 1;           // diag
        mat(0,1) = 0;           // above
        rhs[0]   = derivLeft;
    }
    if(isFinite(derivRight)) {
        mat(numPoints-1,numPoints-1) = 1; // diag
        mat(numPoints-1,numPoints-2) = 0; // below
        rhs[numPoints-1] = derivRight;
    }
    std::vector<double> fder = solveBand(mat, rhs);

    // check if the input nodes and values are symmetric w.r.t. grid center -
    // if yes, make the derivatives exactly antisymmetric too
    bool symmetric = true;
    for(size_t i=0; symmetric && i<(numPoints+1)/2; i++)
        symmetric &= xval[i] == -xval[numPoints-1-i] && fval[i] == fval[numPoints-1-i];
    if(symmetric) {
        for(size_t i=0; i<numPoints/2; i++)
            fder[i] = -fder[numPoints-1-i];
        if(numPoints%2==1)
            fder[numPoints/2] = 0.;
    }

    return fder;
}

// compute the 2nd derivative at each grid node from the condition that the 3rd derivative
// is continuous at all interior nodes, and the 4th derivative is zero at the boundary nodes
// (this differs from Dehnen's original pspline, where the 3rd derivative was set to zero at boundary)
std::vector<double> constructQuinticSpline(const std::vector<double>& xval,
    const std::vector<double>& fval, const std::vector<double>& fder)
{
    size_t numPoints = xval.size();
    if(numPoints < 2)
        return std::vector<double>(numPoints, 0);
    BandMatrix<double>  mat(numPoints, 1, 0.);
    std::vector<double> rhs(numPoints);
    for(size_t i = 0; i < numPoints; i++) {
        if(i > 0) {
            double hi = 1 / (xval[i] - xval[i-1]);
            mat(i,i) += hi * 3;  // diagonal element
            mat(i-1,i)= -hi;     // above-diagonal


ntWriter createXMLEventWriter(final Result out) throws XMLStreamException {
        return FACTORY.createXMLEventWriter(out);
    }

    /**
     * Creates a new writer for the JAXP result.
     * Note that this method is identified as optional in JSE javadoc.
     * It is caller's responsibility to close the given stream writer after usage
     * (it will not be done by {@link XMLEventWriter#close()}).
     *
     * @param  out  where to write to.
     * @return the writer.
     * @throws XMLStreamException if the writer cannot be created.
     */
    public static XMLEventWriter createXMLEventWriter(final XMLStreamWriter out) throws XMLStreamException {
        return FACTORY.createXMLEventWriter(new StAXResult(new StreamWriterDelegate(out) {
            @Override public void close() throws XMLStreamException {
                /*
                 * Do not close the XMLStreamWriter because user may continue writing to it.
                 * Do not flush neither; the default XMLStreamWriterImpl does nothing more
                 * than forwarding to java.io.Writer.flush() and flushing an output stream
                 * have a performance impact. If the user really wants to flush, (s)he can
                 * invoke XMLStreamWriter.flush() himself.
                 */
            }
        }));
    }
}
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.apache.plc4x.java.bacnetip;

import org.junit.jupiter.api.Test;

import static org.apache.plc4x.java.bacnetip.Utils.PAYLOAD_START_INDEX;
import static org.apache.plc4x.java.bacnetip.Utils.tryParseBytes;

public class TrickyPackagesTest {

    // from plugfest-tridium-1.pcap
    @Test
    public void testTridium255() throws Exception {
        int[] rawBytesAsInts = new int[]{
            /*0000*/   0x00, 0x1d, 0x09, 0xbc, 0x43, 0x5f, 0x00, 0x01, 0xf0, 0x8c, 0x11, 0x50, 0x08, 0x00, 0x45, 0x00,
            /*0010*/   0x01, 0xfc, 0x7e, 0x47, 0x00, 0x00, 0x40, 0x11, 0x27, 0x92, 0xac, 0x10, 0x24, 0xcd, 0xac, 0x10,
            /*0020*/   0x56, 0x2a, 0xba, 0xc0, 0xba, 0xc0, 0x01, 0xe8, 0x24, 0xd9, 0x81, 0x0a, 0x01, 0xe0, 0x01, 0x00,
            /*0030*/   0x30, 0x6e, 0x0e, 0x0c, 0x04, 0x40, 0x00, 0x01, 0x1e, 0x29, 0x4b, 0x4e, 0xc4, 0x04, 0x40, 0x00,
            /*0040*/   0x01, 0x4f, 0x29, 0x4d, 0x4e, 0x75, 0x13, 0x00, 0x53, 0x63, 0x68, 0x65, 0x64, 0x2e, 0x45, 0x6e,
            /*0050*/   0x75, 0x6d, 0x53, 0x63, 0x68, 0x65, 0x64, 0x75, 0x6c, 0x65, 0x4f, 0x29, 0x4f, 0x4e, 0x91, 0x11,
            /*0060*/


# -*- coding: utf-8 -*- #
# Copyright 2023 Google LLC. All Rights Reserved.
#
# 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.
"""Resource definitions for Cloud Platform Apis generated from apitools."""

import enum

BASE_URL = 'https://configdelivery.googleapis.com/v1alpha/'
DOCS_URL = 'https://cloud.google.com/anthos-config-management/config-delivery/private-preview-user-guide'

class Collections(enum.Enum):
  """Collections for all supported apis."""

  PROJECTS = (
      'projects',
      'projects/{projectsId}',
      {},
      ['projectsId'],
      True
  )
  PROJECTS_LOCATIONS = (
      'projects.locations',
      '{+name}',
      {
          '':
              'projects/{projectsId}/locations/{locationsId}',
      },
      ['name'],
      True
  )
  PROJECTS_LOCATIONS_FLEETPACKAGES = (
      'projects.locations.fleetPackages',
      '{+name}',
      {
          '':
              'projects/{projectsId}/locations/{locationsId}/fleetPackages/'
              '{fleetPackagesId}',
      },
      ['name'],
      True
  )
  PROJECTS_LOCATIONS_FLEETPACKAGES_ROLLOUTS = (
      'projects.locations.fleetPackages.rollouts',
      '{+name}',
      {
          '':
              'projects/{projectsId}/locations/{locationsId}/fleetPackages/'
              '{fleetPackagesId}/rollouts/{rolloutsId}',
      },
      ['name'],
      True
  )
  PROJECTS_LOCATIONS_OPERATIONS = (
      'projects.locations.operations',
      '{+name}',
      {
          '':
              'projects/{projectsId}/locations/{locationsId}/operations/'
              '{operationsId}',
      },
      ['name'],
      True
  )
  PROJECTS_LOCATIONS_RESOURCEBUNDLES = (
      'projects.locations.resourceBundles',
      '{+name}',
      {
          '':
              'projects/{projectsId}/locations/{locationsId}/resourceBundles/'
              '{resourceBundlesId}',
      },
      ['name'],
      True
  )
  PROJECTS_LOCATIONS_RESOURCEBUNDLES_RELEASES = (
      'projects.locations.resourceBundles.releases',
      '{+name}',
      {
          '':
              'projects/{projectsId}/locations/{locationsId}/resourceBundles/'
              '{resourceBundlesId}/releases/{releasesId}',
      },
      ['name'],
      True
  )
  PROJECTS_LOCATIONS_RESOURCEBUNDLES_RELEASES_VARIANTS = (
      'projects.locations.resourceBundles.releases.variants',
      '{+name}',
      {
          '':
              'projects/{projectsId}/locations/{locationsId}/resourceBundles/'
              '{resourceBundlesId}/releases/{releasesId}/variants/'
              '{variantsId}',
      },
      ['name'],
      True
  )

  def __init__(self, collection_name, path, flat_paths, params,
               enable_uri_parsing):
    self.collection_name = collection_name
    self.path = path
    self.flat_paths = flat_paths
    self.params = params
    self.enable_uri_parsing = enable_uri_parsing


iv>
)

// Standard typography styles for questions
const questionStyles = {
	title: "text-xl md:text-2xl text-white font-medium leading-relaxed",
	description:
		"text-sm md:text-base text-neutral-400 mt-3 max-w-2xl mx-auto leading-relaxed",
	container:
		"min-h-[100px] md:min-h-[120px] flex items-center justify-center w-full"
}

// --- Onboarding Data ---

const questions = [
	{
		id: "user-name",
		question: "First, what should I call you?",
		type: "text-input",
		required: true,
		placeholder: "Your name"
	},
	{
		id: "timezone",
		question: "What's your timezone?",
		type: "select",
		required: true,
		options: [
			{ value: "", label: "Select your timezone..." },
			{ value: "UTC", label: "(GMT+00:00) Coordinated Universal Time" },
			{
				value: "America/New_York",
				label: "(GMT-04:00) Eastern Time (US & Canada)"
			},
			{
				value: "America/Chicago",
				label: "(GMT-05:00) Central Time (US & Canada)"
			},
			{
				value: "America/Denver",
				label: "(GMT-06:00) Mountain Time (US & Canada)"
			},
			{
				value: "America/Los_Angeles",
				label: "(GMT-07:00) Pacific Time (US & Canada)"
			},
			{ value: "America/Anchorage", label: "(GMT-08:00) Alaska" },
			{ value: "America/Phoenix", label: "(GMT-07:00) Arizona" },
			{ value: "Pacific/Honolulu", label: "(GMT-10:00) Hawaii" },
			{ value: "America/Sao_Paulo", label: "(GMT-03:00) Brasilia" },
			{
				value: "America/Buenos_Aires",
				label: "(GMT-03:00) Buenos Aires"
			},
			{
				value: "Europe/London",
				label: "(GMT+01:00) London, Dublin, Lisbon"
			},
			{
				value: "Europe/Berlin",
				label: "(GMT+02:00) Amsterdam, Berlin, Paris, Rome"
			},
			{
				value: "Europe/Helsinki",
				label: "(GMT+03:00) Helsinki, Kyiv, Riga, Sofia"
			},
			{
				value: "Europe/Moscow",
				label: "(GMT+03:00) Moscow, St. Petersburg"
			},
			{ value: "Africa/Cairo", label: "(GMT+02:00) Cairo" },
			{ value: "Africa/Johannesburg", label: "(GMT+02:00) Johannesburg" },
			{ value: "Asia/Dubai", label: "(GMT+04:00) Abu Dhabi, Muscat" },
			{ value: "Asia/Kolkata", label: "(GMT+05:30) India Standard Time" },
			{
				value: "Asia/Shanghai",
				label: "(GMT+08:00) Beijing, Hong Kong, Shanghai"
			},
			{ value: "Asia/Singapore", label: "(GMT+08:00) Singapore" },
			{ value: "Asia/Tokyo", label: "(GMT+09:00) Tokyo, Seoul" },
			{
				value: "Australia/Sydney",
				label: "(GMT+10:00) Sydney, Melbourne"
			},
			{ value: "Australia/Brisbane", label: "(GMT+10:00) Brisbane" },
			{ value: "Australia/Adelaide", label: "(GMT+09:30) Adelaide" },
			{ value: "Australia/Perth", label: "(GMT+08:00) Perth" },
			{
				value: "Pacific/Auckland",
				label: "(GMT+12:00) Auckland, Wellington"


self.uiBinder.Ref:SetVisible(self.confirmBtn_, self.exchangeItemData_.isUnlock)
  self.uiBinder.Ref:SetVisible(self.upperlimitLab_, self.exchangeItemData_.isUnlock)
  if self.exchangeItemData_.isUnlock then
    self.uiBinder.Ref:SetVisible(self.uiBinder.node_currency_cost, false)
  end
  self.uiBinder.btn_preview_btn:RemoveAllListeners()
  local exchangeItemRow = Z.TableMgr.GetTable("ExchangeItemTableMgr").GetRow(self.exchangeItemData_.goodsId)
  if exchangeItemRow ~= nil then
    local itemConfigId = exchangeItemRow.GetItemId
    local itemCfg = Z.TableMgr.GetTable("ItemTableMgr").GetRow(itemConfigId)
    if itemCfg then
      self.uiBinder.lab_item_name.text = itemCfg.Name
      self.uiBinder.rimg_item_icon:SetImage(itemCfg.Icon)
      self.uiBinder.img_name_quality_bg:SetImage(qualityPath .. itemCfg.Quality)
    end
    self.uiBinder.Ref:SetVisible(self.uiBinder.img_bind, exchangeItemRow.Bind == 1)
    local canPreview = self.fashionVm_.CheckIsFashion(itemConfigId)
    self.uiBinder.Ref:SetVisible(self.uiBinder.btn_preview, canPreview)
    self:AddClick(self.uiBinder.btn_preview_btn, function()
      self.preview_.GotoPreview(itemConfigId)
    end)
  end
  self.uiBinder.Ref:SetVisible(self.uiBinder.lab_info, self.exchangeItemData_.isUnlock)
  self:refreshNumShowState(self.exchangeItemData_)
  if self.exchangeItemData_.isUnlock then
    self:refreshMaterialsData()
    self:refreshGoodsExchangeNum()
    self:refreshExchangeBtn()
    self:setRightLimitDes()
  end
end

function Exchange_mainView:setRightLimitDes()
  local exchangeItemRow = Z.TableMgr.GetTable("ExchangeItemTableMgr").GetRow(self.exchangeItemData_.goodsId)
  if exchangeItemRow == nil then
    return
  end
  local itemId = exchangeItemRow.GetItemId
  local complete = self.exchangeChance_ <= 0
  local itemVM = Z.VMMgr.GetVM("items")
  local isFashion = self.fashionVm_.CheckIsFashion(itemId)
  local count = itemVM.GetItemTotalCount(itemId)
  local fashionComplete = isFashion and (0 < count or complete)
  self.upperlimitLab_.text = fashionComplete and Lang("ExchangeFashionNumLimit") or Lang("ExchangeNumLimit")
end

function Exchange_mainView:SelectConsumeItem(configId)
  self:showItemInfoTips(configId)
end

function Exchange_mainView:GetCacheData()
  return table.zclone(self.viewData)
end

function Exchange_mainView:OnActive()
  Z.UIMgr:FadeIn({
    IsInstant = true,
    TimeOut = Z.UICameraHelperFadeTime
  })
  self:inituiBinders()
  self:initBtns()
  if self.numMod_ then
    self.numMod_:Active({SetWidth = 510}, self.numModRootTrans_.transform)
  end
  Z.UIMgr:SetUIViewInputIgnore(self.viewConfigKey, 4294967295, true)
  self.curNum_ = 1
  self.maxNum_ = 0
  self.minNum_ = 0
  self.canExchangeMinNum_ = 0
  self.shopId_ = self.viewData.shopId
  self.npcId = self.viewData.npcId
  self.shopInfo_ = Z.ContainerMgr.CharSerialize.exchangeItems.exchangeInfo[self.shopId_]
  self.exchangeItemData_ = {}
  self.exchangeChance_ = 0
  self.isConsumeItemEnough_ = false
  self.i


)
        .put(AnonymousTag, true)
        .put(AnonymousTag, false)
        .put(AnonymousTag, true)
        .endArray()
        .endStructure()
        .put(ContextSpecificTag(7), 0.0f)
        .endStructure()
        .validateTlv()
        .getEncoded()
    val json =
      """
      {
        "value:0:INT": 42,
        "value:1:BYTES": "VGVzdCBhcnJheSBtZW1iZXIgMA==",
        "value:2:DOUBLE": 156.398,
        "value:3:UINT": "73709551615",
        "value:4:BOOL": true,
        "value:5:NULL": null,
        "value:6:STRUCT": {
          "name:1:STRING": "John",
          "age:2:UINT": 34,
          "approved:3:BOOL": true,
          "kids:4:ARRAY-INT": [
            5,
            9,
            10
          ],
          "names:5:ARRAY-STRING": [
            "Ammy",
            "David",
            "Larry"
          ],
          "6:ARRAY-BOOL": [
            true,
            false,
            true
          ]
        },
        "value:7:FLOAT": 0.0
      }
      """
    val expectedJson =
      """
      {
        "0:INT": 42,
        "1:BYTES": "VGVzdCBhcnJheSBtZW1iZXIgMA==",
        "2:DOUBLE": 156.398,
        "3:UINT": "73709551615",
        "4:BOOL": true,
        "5:NULL": null,
        "6:STRUCT": {
          "1:STRING": "John",
          "2:UINT": 34,
          "3:BOOL": true,
          "4:ARRAY-INT": [
            5,
            9,
            10
          ],
          "5:ARRAY-STRING": [
            "Ammy",
            "David",
            "Larry"
          ],
          "6:ARRAY-BOOL": [
            true,
            false,
            true
          ]
        },
        "7:FLOAT": 0.0
      }
      """

    checkValidConversion(json, encoding, expectedJson)
  }

  @Test
  fun convertArray_UIntMinMax() {
    // Array of Unsigned Integers, where each element represents MAX possible value for unsigned
    // integere
    // types UByte, UShort, UInt, and ULong: [0xFF, 0xFFFF, 0xFFFFFFFF, 0xFFFFFFFF_FFFFFFFF]
    val encoding =
      TlvWriter()
        .startStructure(AnonymousTag)
        .startArray(ContextSpecificTag(0))
        .put(AnonymousTag, UByte.MAX_VALUE)
        .put(AnonymousTag, UShort.MAX_VALUE)
        .put(AnonymousTag, UInt.MAX_VALUE)
        .put(AnonymousTag, ULong.MAX_VALUE)
        .endArray()
        .endStructure()
        .validateTlv()
        .getEncoded()
    val json =
      """
      {
        "0:ARRAY-UINT": [
          255,
          65535,
          4294967295,
          "18446744073709551615"
        ]
      }
      """

    checkValidConversion(json, encoding)
  }

  @Test
  fun convertArray_IntMinMax() {
    // Array of Integers, where each element represents MIN or MAX possible value for integere
    // types Byte, Short, Int, and Long
    val encoding =
      TlvWriter()
        .startStructure(AnonymousTag)
        .startArray(ContextSpecificTag(0))
        .put(AnonymousTag, Byte.MIN_VALUE)
        .put(AnonymousTag, Byte.MAX_VALUE)
        .put(AnonymousTag, Short.MIN_VALUE)
        .put(AnonymousTag, Short.MAX_VALUE)
        .put(AnonymousTag, Int.MIN_VALUE)
        .put(AnonymousTag, Int.MAX


,0,0,0,1,0,1,0,0,0,1],"am":["1","1","1","0","0","0","0","0","0","0","0","0","0","0","0","0","0","1","1","1","0","0","0","0","0","1","1","1","1","1","1","1"],"gear":[4,4,4,3,3,3,3,4,4,4,4,3,3,3,3,3,3,4,4,4,3,3,3,3,3,4,5,5,5,5,5,4],"carb":[4,4,1,1,2,1,4,2,2,4,4,3,3,3,4,4,4,1,2,1,1,2,2,4,2,1,2,2,4,6,8,2],"am1":["0","0","0","0","1","0","0","0","0","0","0","0","0","1","0","0","0","0","0","1","0","0","1","0","0","0","0","0","0","0","0","0"],"am2":["1","0","1","1","0","1","1","1","0","1","1","1","1","1","0","0","0","0","0","1","0","1","0","1","0","0","1","1","0","0","0","0"],"am3":["0","1","1","1","0","1","1","0","1","1","1","1","1","1","1","0","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1","1"]},"queue":[{"sender":"server","target":"scene","type":"add-plot","data":{"type":"scatter","variables":["wt","mpg"],"id":"1097ada1-963d-448f-ba87-a5234f2210e2"}},{"sender":"server","target":"scene","type":"add-plot","data":{"type":"histo","variables":["wt"],"id":"b49870b6-1644-44bc-8917-37cd73af5572"}},{"sender":"server","target":"scene","type":"set-parameters","data":{"id":"plot1","width":1,"anchor":0.5}}],"options":null},"evals":[],"jsHooks":[]}</script>

(notice that the boundaries of the bins are aligned with the
midpoints of the axis labels)

For 2D histograms, we need to specify which axis we want to set the
parameters to:

names(airquality) <- c("ozone", "solar radiation", "wind",
                       "temperature", "month", "day")

create_schema(airquality) |>
  add_histogram2d(


L方法展示了令人印象深刻的性能，但它们依赖于乐观的假设:1)PTM的整个参数集是可用的，2)为微调配备了足够大的内存容量。然而，在大多数现实世界的应用程序中，ptm被用作黑盒API或专有软件，没有明确的参数可访问性。此外，现代ptm很难满足大容量的内存需求。在这项工作中，我们提出了黑盒视觉提示(BlackVIP)，它可以在不了解模型体系结构和参数的情况下有效地适应ptm。BlackVIP有两个组成部分;1)协调器和2)梯度校正同步摄动随机逼近(SPSA-GC)。协调器设计了依赖于输入的图像形视觉提示，提高了对分布/位置移动的少镜头适应性和鲁棒性。SPSA-GC可以有效地估计目标模型的梯度来更新协调器。在16个数据集上进行的大量实验表明，BlackVIP能够在不访问PTMs参数的情况下对不同领域进行鲁棒适应，并且内存需求最小。**黑盒调优，零阶优化**
28. From Images to Textual Prompts: Zero-Shot Visual Question Answering With Frozen Large Language Models https://openaccess.thecvf.com/content/CVPR2023/papers/Guo_From_Images_to_Textual_Prompts_Zero-Shot_Visual_Question_Answering_With_CVPR_2023_paper.pdf
    大型语言模型(llm)已经证明了对新语言任务的出色的零样本泛化。然而，有效利用LLM进行零样本视觉问答(VQA)仍然具有挑战性，主要是由于LLM和VQA任务之间的模态脱节和任务脱节。对多模态数据的端到端训练可以弥合这种脱节，但不灵活且计算成本高。为了解决这个问题，我们提出了Img2LLM，这是一个即插即用模块，它提供LLM提示，使LLM能够在没有端到端培训的情况下执行零样本VQA任务。我们开发了与LLM无关的模型，将图像内容描述为示例问答对，这被证明是有效的LLM提示。**LLM，VQA，LLM提示**
29. Visual Prompt Multi-Modal Tracking https://arxiv.org/pdf/2303.10826.pdf
    可见模态目标跟踪产生了一系列下游多模态跟踪分支。为了继承基础模型的强大表示，多模态跟踪的自然操作方式是对基于rgb的参数进行全面微调。这种方式虽然有效，但由于下游数据的稀缺性和可移植性差等原因，并不是最优的。在本文中，受提示学习在语言模型中最近取得的成功的启发，我们开发


relatedlink">进行以礼物的形式进行发送，主要用处就是提高主播曝光率，并且主播也不会收到猫粮礼物，也不能直接进行兑换提现使用。

还有一种作用就是当主播开启一些竞猜活动的时候可以直接使用猫粮进行参与。快手是由快手科技开发的一款短视频软件，可以用照片和短视频记录生活的点滴，也可以通过直播与粉丝实时互动。

让母猫繁殖需要做什么准备？

1、准备好产箱、碘酒、卫生垫和医用剪刀。在背后足够的一次性手套和小猫喝的奶粉和奶瓶，以备不时之需。而接生的时候呢你要注意一下嗯可以在网上搜一些相关的视频。

2、新出生的小猫脐带，�


c) 2020, 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.

class A {
  bool operator ==(covariant A other) => true;
}

class B extends A {
  bool operator ==(other) => true;
}

class C<T> {
  bool operator ==(covariant C<T> other) => true;
}

class D extends C<int> {}

main() {}

testNonNullable(A a, B b, C c_dynamic, C<int> c_int, C<String> c_string, D d) {
  a == a; // ok
  a == b; // ok
  a == c_dynamic; // error
  a == c_int; // error
  a == c_string; // error
  a == d; // error

  b == a; // ok
  b == b; // ok
  b == c_dynamic; // error
  b == c_int; // error
  b == c_string; // error
  b == d; // error

  c_dynamic == a; // error
  c_dynamic == b; // error
  c_dynamic == c_dynamic; // ok
  c_dynamic == c_int; // ok
  c_dynamic == c_string; // ok
  c_dynamic == d; // ok

  c_int == a; // error
  c_int == b; // error
  c_int == c_dynamic; // error
  c_int == c_int; // ok
  c_int == c_string; // error
  c_int == d; // ok}

  c_string == a; // error
  c_string == b; // error
  c_string == c_dynamic; // error
  c_string == c_int; // error
  c_string == c_string; // ok
  c_string == d; // error

  d == a; // error
  d == b; // error
  d == c_dynamic; // error
  d == c_int; // ok
  d == c_string; // error
  d == d; // ok
}

testNullable(
    A? a, B? b, C? c_dynamic, C<int>? c_int, C<String>? c_string, D? d) {
  // Since the receiver type is nullable, the calls are checked against the
  // Object member.

  a == a; // ok
  a == b; // ok
  // TODO(johnniwinther): Awaiting spec update about `==`. Before NNBD these
  // would cause an error but with the current (insufficient) specification for
  // `==` it is ok.
  a == c_dynamic; // ok or error ?
  a == c_int; // ok or error ?
  a == c_string; // ok or error ?
  a == d; // ok or error ?

  b == a; // ok
  b == b; // ok
  b == c_dynamic; // ok or error ?
  b == c_int; // ok or error ?
  b == c_string; // ok or error ?
  b == d; // ok or error ?

  c_dynamic == a; // ok or error ?
  c_dynamic == b; // ok or error ?
  c_dynamic == c_dynamic; // ok
  c_dynamic == c_int; // ok
  c_dynamic == c_string; // ok
  c_dynamic == d; // ok

  c_int == a; // ok or error ?
  c_int == b; // ok or error ?
  c_int == c_dynamic; // ok or error ?
  c_int == c_int; // ok
  c_int == c_string; // ok or error ?
  c_int == d; // ok}

  c_string == a; // ok or error ?
  c_string == b; // ok or error ?
  c_string == c_dynamic; // ok or error ?
  c_string == c_int; // ok or error ?
  c_string == c_string; // ok
  c_string == d; // ok or error ?

  d == a; // ok or error ?
  d == b; // ok or error ?
  d == c_dynamic; // ok or error ?
  d == c


": "?doc=filings/0001558370-23-010877/boot-20230607x8k.htm",
		"size": false,
		"sec": "https://www.sec.gov/Archives/edgar/data/1610250/000155837023010877/boot-20230607x8k.htm",
		"secUrl": "https://www.sec.gov/ix?doc=https://www.sec.gov/Archives/edgar/data/1610250/000155837023010877/boot-20230607x8k.htm",
		"devLink": "http://172.18.85.157:8080/ixviewer2plus/?doc=?doc=./../ixviewer-2-getter/filings/0001558370-23-010877/boot-20230607x8k.htm",
		"cik": "1610250",
		"accessionNum": "000155837023010877",
		"ticker": "boot",
		"dateString": "20230607x8k",
		"formType": "8-K",
		"factCount": 22
	},
	{
		"version": "2.2",
		"instance_file": "arcb-20230602x8k.htm",
		"link": "?doc=filings/0001558370-23-010879/arcb-20230602x8k.htm",
		"size": false,
		"sec": "https://www.sec.gov/Archives/edgar/data/894405/000155837023010879/arcb-20230602x8k.htm",
		"secUrl": "https://www.sec.gov/ix?doc=https://www.sec.gov/Archives/edgar/data/894405/000155837023010879/arcb-20230602x8k.htm",
		"devLink": "http://172.18.85.157:8080/ixviewer2plus/?doc=?doc=./../ixviewer-2-getter/filings/0001558370-23-010879/arcb-20230602x8k.htm",
		"cik": "894405",
		"accessionNum": "000155837023010879",
		"ticker": "arcb",
		"dateString": "20230602x8k",
		"formType": "8-K",
		"factCount": 22
	},
	{
		"version": "2.2",
		"instance_file": "tilt-20230606x8k.htm",
		"link": "?doc=filings/0001558370-23-010885/tilt-20230606x8k.htm",
		"size": false,
		"sec": "https://www.sec.gov/Archives/edgar/data/1761510/000155837023010885/tilt-20230606x8k.htm",
		"secUrl": "https://www.sec.gov/ix?doc=https://www.sec.gov/Archives/edgar/data/1761510/000155837023010885/tilt-20230606x8k.htm",
		"devLink": "http://172.18.85.157:8080/ixviewer2plus/?doc=?doc=./../ixviewer-2-getter/filings/0001558370-23-010885/tilt-20230606x8k.htm",
		"cik": "1761510",
		"accessionNum": "000155837023010885",
		"ticker": "tilt",
		"dateString": "20230606x8k",
		"formType": "8-K",
		"factCount": 20
	},
	{
		"version": "2.2",
		"instance_file": "fcel-20230608x8k.htm",
		"link": "?doc=filings/0001558370-23-010888/fcel-20230608x8k.htm",
		"size": false,
		"sec": "https://www.sec.gov/Archives/edgar/data/886128/00015583702


lues[2*nodedown+1]+=vb/connectivity[0];
		}
		delete gauss;
	}

	/*Clean up and return*/
	xDelete<int>(pairindices);
	xDelete<IssmDouble>(xyz_list);
	if(frictionlaw==5) delete friction;
	return pe;

}/*}}}*/
void           StressbalanceSIAAnalysis::GetSolutionFromInputs(Vector<IssmDouble>* solution,Element* element){/*{{{*/

	IssmDouble vx,vy;
	int       *doflist = NULL;

	/*Fetch number of nodes and initialize values*/
	int         numnodes = element->GetNumberOfNodes();
	int         numdof   = numnodes*2;
	IssmDouble* values   = xNew<IssmDouble>(numdof);

	/*Get dof list and inputs */
	element->GetDofList(&doflist,NoneApproximationEnum,GsetEnum);
	Input* vx_input=element->GetInput(VxEnum); _assert_(vx_input);
	Input* vy_input=element->GetInput(VyEnum); _assert_(vy_input);

	/*Ok, we have the velocities in inputs, fill in solution */
	Gauss* gauss=element->NewGauss();
	for(int i=0;i<numnodes;i++){
		gauss->GaussVertex(i);
		vx_input->GetInputValue(&vx,gauss);
		vy_input->GetInputValue(&vy,gauss);
		values[i*2+0]=vx;
		values[i*2+1]=vy;
	}

	/*Add value to global vector*/
	solution->SetValues(numdof,doflist,values,INS_VAL);

	/*Free resources:*/
	delete gauss;
	xDelete<int>(doflist);
	xDelete<IssmDouble>(values);
}/*}}}*/
void           StressbalanceSIAAnalysis::GradientJ(Vector<IssmDouble>* gradient,Element*  element,int control_type,int control_interp,int control_index){/*{{{*/
	_error_("Not implemented yet");
}/*}}}*/
void           StressbalanceSIAAnalysis::InputUpdateFromSolution(IssmDouble* solution,Element* element){/*{{{*/

	int         i,domaintype;
	IssmDouble  rho_ice,g;
	int*        doflist=NULL;
	IssmDouble* xyz_list=NULL;

	/*Fetch number of nodes and dof for this finite element*/
	int numnodes = element->GetNumberOfNodes();
	int numdof   = numnodes*2;

	/*Fetch dof list and allocate solution vectors*/
	element->GetDofListLocal(&doflist,NoneApproximationEnum,GsetEnum);
	IssmDouble* values    = xNew<IssmDouble>(numdof);
	IssmDouble* vx        = xNew<IssmDouble>(numdof);
	IssmDouble* vy        = xNew<IssmDouble>(numdof);
	IssmDouble* vz        = xNew<IssmDouble>(numdof);
	IssmDouble* vel       = xNew<IssmDouble>(numdof);
	IssmDouble* pressure  = xNew<IssmDouble>(numdof);
	IssmDouble* thickness = xNew<IssmDouble>(numdof);
	IssmDouble* surface   = xNew<IssmDouble>(numnodes);

	/*Use the dof list to index into the solution vector: */
	for(i=0;i<numdof;i++) values[i]=solution[doflist[i]];

	/*Transform solution in Cartesian Space*/
	element->TransformSolutionCoord(&values[0],XYEnum);

	/*Ok, we have vx and vy in values, fill in vx and vy arrays: */
	for(i=0;i<numnodes;


ンの頻度を上げるには障壁があるでしょうが、その障壁は開発プロセスを改善するためまさに克服するべき問題である事が多いです。

マージはブランチの難しい部分であるため、**マージを難しくしている原因に注意を払いましょう**。プロセスの問題であることもあれば、アーキテクチャの問題であることもあります。何であれ、ストックホルム症候群に屈してはいけません。マージの問題、特に危機を引き起こすような問題は、チームの有効性を向上させるための道しるべとなります。失敗は、そこから学んでこそ価値があるということを忘れないでください。

ここで説明したパターンは、私や同僚が仕事をする中で遭遇したブランチの一般的な構成を概説したものです。これらのパターンに名前を付け、説明し、そして何よりも、どのような時に役に立つのかを説明することで、どのような時にそれらを使うべきかを評価する手助けになればと思います。どんなパターンでもそうですが、一概に良いとか悪いとは言えないことを覚えておいてください。それぞれのパターンの価値はあなたのコンテキスト次第です。ブランチポリシー (Git-flow やトランクベース開発のようなよく知られたものであれ、開発組織で生まれたものであれ) に出会ったときに、その中のパターンを理解することで、それが自分の状況に合っているかどうかを判断したり、他のパターンを混ぜて使うと便利なものがあるかどうかを判断したりする助けになればと思います。

---

## 謝辞

Badri Janakiraman、Dave Farley、James Shore、Kent Beck、Kevin Yeung、Marcos Brizeno、Paul Hammant、Pete Hodgson、Tim Cochran がこの記事の草稿を読んでくれて、改善のためのフィードバックをくれました。

ピーター・ベッカーは、フォークもブランチの一形態であることを指摘するように思い出させてくれました。メインラインという名前は、Steve Berczuk 氏の[Software Configuration Management Patterns](https://www.amazon.co.jp/dp/4798112593/)から取ったものです。

## 更に知りたい方へ

ブランチについて書かれた資料はたくさんありますが、私はそのすべてを真面目に調査できる立場にはありません。しかし、Steve Berczuk の本、[Software Configuration Management Patterns](https://www.amazon.co.jp/dp/4798112593/)は注目に値します。Steve 氏の著作は、彼の貢献者である Brad Appleton 氏の著作と


.index,
      )];

  static int get fullScreenMode => _setting.get(
    SettingBoxKey.fullScreenMode,
    defaultValue: FullScreenMode.auto.index,
  );

  static int get btmProgressBehavior => _setting.get(
    SettingBoxKey.btmProgressBehavior,
    defaultValue: BtmProgressBehavior.alwaysShow.index,
  );

  static int get subtitlePreferenceV2 => _setting.get(
    SettingBoxKey.subtitlePreferenceV2,
    defaultValue: SubtitlePrefType.off.index,
  );

  static bool get useRelativeSlide =>
      _setting.get(SettingBoxKey.useRelativeSlide, defaultValue: false);

  static int get sliderDuration =>
      _setting.get(SettingBoxKey.sliderDuration, defaultValue: 90);

  static int get defaultVideoQa => _setting.get(
    SettingBoxKey.defaultVideoQa,
    defaultValue: VideoQuality.super8k.code,
  );

  static int get defaultVideoQaCellular => _setting.get(
    SettingBoxKey.defaultVideoQaCellular,
    defaultValue: VideoQuality.high1080.code,
  );

  static int get defaultAudioQa => _setting.get(
    SettingBoxKey.defaultAudioQa,
    defaultValue: AudioQuality.hiRes.code,
  );

  static int get defaultAudioQaCellular => _setting.get(
    SettingBoxKey.defaultAudioQaCellular,
    defaultValue: AudioQuality.k192.code,
  );

  static String get defaultDecode => _setting.get(
    SettingBoxKey.defaultDecode,
    defaultValue: VideoDecodeFormatType.values.last.codes.first,
  );

  static String get secondDecode => _setting.get(
    SettingBoxKey.secondDecode,
    defaultValue: VideoDecodeFormatType.AV1.codes.first,
  );

  static String get hardwareDecoding => _setting.get(
    SettingBoxKey.hardwareDecoding,
    defaultValue: Platform.isAndroid
        ? HwDecType.autoSafe.hwdec
        : HwDecType.auto.hwdec,
  );

  static String get videoSync =>
      _setting.get(SettingBoxKey.videoSync, defaultValue: 'display-resample');

  static String get defaultCDNService => _setting.get(
    SettingBoxKey.CDNService,
    defaultValue: CDNService.backupUrl.code,
  );

  static String get banWordForRecommend =>
      _setting.get(SettingBoxKey.banWordForRecommend, defaultValue: '');

  static String get banWordForReply =>
      _setting.get(SettingBoxKey.banWordForReply, defaultValue: '');

  static String get banWordForZone =>
      _setting.get(SettingBoxKey.banWordForZone, defaultValue: '');

  static bool get appRcmd =>
      _setting.get(SettingBoxKey.appRcmd, defaultValue: true);

  static String get systemProxyHost =>
      _setting.get(SettingBoxKey.systemProxyHost, defaultValue: '');

  static String get systemProxyPort =>
      _setting.get(SettingBoxKey.systemProxyPort, defaultValue: '');

  static int get defaultDynamicType =>
      _setting.get(SettingBoxKey.defaultDynamicType, defaultValue: 0);

  static double get blockLimit =>
      _setting.get(SettingBoxKey.blockLimit, defaultValue: 0.0);

  static double get refreshDragPercentage =>
      _setting.get(SettingBoxKey.refreshDragPercentage, defaultValue: 0.25);

  static double get refreshDisplacement => _setting.get(
    SettingBoxKey.refreshDisplacement,
    defaultValue: Utils.isMobile ? 20.0 : 40.0,
  );

  static String get blockUserID {
    String blockUserID = _setting.get(
      SettingBoxKey.blockUserID,
      defaultValue: '',
    );
    if (blockUserID.isEmpty) {
      blockUserID = const Uuid().v4().replaceAll('-', '


"""Numpy version of euclidean distance, etc.
Notice the input/output shape of methods, so that you can better understand
the meaning of these methods."""

import numpy as np
import torch

def normalize(nparray, order=2, axis=0):
    """Normalize a N-D numpy array along the specified axis."""
    norm = np.linalg.norm(nparray, ord=order, axis=axis, keepdims=True)
    return nparray / (norm + np.finfo(np.float32).eps)

def compute_dsr_dist(array1, array2, distmat, scores):
    """ Compute the sptial feature reconstruction of all pairs
     array: [M, N, C] M: the number of query, N: the number of spatial feature, C: the dimension of each spatial feature
     array2: [M, N, C] M: the number of gallery
    :return:
    numpy array with shape [m1, m2]
    """
    dist = 100 * torch.ones(len(array1), len(array2))
    dist = dist.cuda()
    kappa = 0.001
    index = np.argsort(distmat, axis=1)
    T = kappa * torch.eye(110)
    T = T.cuda()
    M = []
    for i in range(0, len(array2)):
        g = array2[i]
        g = torch.FloatTensor(g)
        g = g.view(g.size(0), g.size(1))
        g = g.cuda()
        Proj_M1 = torch.matmul(torch.inverse(torch.matmul(g.t(), g) + T), g.t())
        Proj_M1 = Proj_M1.cpu().numpy()
        M.append(Proj_M1)
    for i in range(0, len(array1)):
        q = torch.FloatTensor(array1[i])
        q = q.view(q.size(0), q.size(1))
        q = q.cuda()
        for j in range(0, 100):
            g = array2[index[i, j]]
            g = torch.FloatTensor(g)
            g = g.view(g.size(0), g.size(1))
            g = g.cuda()
            Proj_M = torch.FloatTensor(M[index[i, j]])
            Proj_M = Proj_M.cuda()
            a = torch.matmul(g, torch.matmul(Proj_M, q)) - q
            dist[i, index[i, j]] = ((torch.pow(a, 2).sum(0).sqrt()) * scores[i].cuda()).sum()
    dist = dist.cpu()
    dist = dist.numpy()

    return dist


mber} num 点个数
   * @param {Array} p1 点坐标
   * @param {Array} p2 点坐标
   * @param {Array} p3 点坐标
   * @param {Array} p4 点坐标
   * 如果参数是 num, p1, p2 为一阶贝塞尔
   * 如果参数是 num, p1, c1, p2 为二阶贝塞尔
   * 如果参数是 num, p1, c1, c2, p2 为三阶贝塞尔
   */
  getBezierPoints(num = 100, p1, p2, p3, p4) {
    let func: any = null
    const points: any[] = []
    if (!p3 && !p4) {
      func = this.oneBezier
    } else if (p3 && !p4) {
      func = this.twoBezier
    } else if (p3 && p4) {
      func = this.threeBezier
    }
    for (let i = 0; i < num; i++) {
      points.push(func(i / num, p1, p2, p3, p4))
    }
    if (p4) {
      points.push([...p4])
    } else if (p3) {
      points.push([...p3])
    }
    return points
  }

  /**
   * @desc 一阶贝塞尔
   * @param {number} t 当前百分比
   * @param {Array} p1 起点坐标
   * @param {Array} p2 终点坐标
   */
  oneBezier(t, p1, p2) {
    const [x1, y1] = p1
    const [x2, y2] = p2
    const x = x1 + (x2 - x1) * t
    const y = y1 + (y2 - y1) * t
    return [x, y]
  }

  /**
   * @desc 二阶贝塞尔
   * @param {number} t 当前百分比
   * @param {Array} p1 起点坐标
   * @param {Array} p2 终点坐标
   * @param {Array} cp 控制点
   */
  twoBezier(t, p1, cp, p2) {
    const [x1, y1] = p1
    const [cx, cy] = cp
    const [x2, y2] = p2
    const x = (1 - t) * (1 - t) * x1 + 2 * t * (1 - t) * cx + t * t * x2
    const y = (1 - t) * (1 - t) * y1 + 2 * t * (1 - t) * cy + t * t * y2
    return [x, y]
  }

  /**
   * @desc 三阶贝塞尔
   * @param {number} t 当前百分比
   * @param {Array} p1 起点坐标
   * @param {Array} p2 终点坐标
   * @param {Array} cp1 控制点1
   * @param {Array} cp2 控制点2
   */
  threeBezier(t, p1, cp1, cp2, p2) {
    const [x1, y1] = p1
    const [x2, y2] = p2
    const [cx1, cy1] = cp1
    const [cx2, cy2] = cp2
    const x =
      x1 * (1 - t) * (1 - t) * (1 - t) + 3 * cx1 * t * (1 - t) * (1 - t) + 3 * cx2 * t * t * (1 - t) + x2 * t * t * t
    const y =
      y1 * (1 - t) * (1 - t) * (1 - t) + 3 * cy1 * t * (1 - t) * (1 - t) + 3 * cy2 * t * t * (1 - t) + y2 * t * t * t
    return [x,


er is a pipelined system of schedulers and logic matchers which perform
// binary AND/OR operations on the bit-streams, creating a stream of potential
// blocks to inspect for data content.
type Matcher struct {
	sectionSize uint64 // Size of the data batches to filter on

	filters    [][]bloomIndexes    // Filter the system is matching for
	schedulers map[uint]*scheduler // Retrieval schedulers for loading bloom bits

	retrievers chan chan uint       // Retriever processes waiting for bit allocations
	counters   chan chan uint       // Retriever processes waiting for task count reports
	retrievals chan chan *Retrieval // Retriever processes waiting for task allocations
	deliveries chan *Retrieval      // Retriever processes waiting for task response deliveries

	running uint32 // Atomic flag whether a session is live or not
}

// NewMatcher creates a new pipeline for retrieving bloom bit streams and doing
// address and topic filtering on them. Setting a filter component to `nil` is
// allowed and will result in that filter rule being skipped (OR 0x11...1).
func NewMatcher(sectionSize uint64, filters [][][]byte) *Matcher {
	// Create the matcher instance
	m := &Matcher{
		sectionSize: sectionSize,
		schedulers:  make(map[uint]*scheduler),
		retrievers:  make(chan chan uint),
		counters:    make(chan chan uint),
		retrievals:  make(chan chan *Retrieval),
		deliveries:  make(chan *Retrieval),
	}
	// Calculate the bloom bit indexes for the groups we're interested in
	m.filters = nil

	for _, filter := range filters {
		// Gather the bit indexes of the filter rule, special casing the nil filter
		if len(filter) == 0 {
			continue
		}
		bloomBits := make([]bloomIndexes, len(filter))
		for i, clause := range filter {
			if clause == nil {
				bloomBits = nil
				break
			}
			bloomBits[i] = calcBloomIndexes(clause)
		}
		// Accumulate the filter rules if no nil rule was within
		if bloomBits != nil {
			m.filters = append(m.filters, bloomBits)
		}
	}
	// For every bit, create a scheduler to load/download the bit vectors
	for _, bloomIndexLists := range m.filters {
		for _, bloomIndexList := range bloomIndexLists {
			for _, bloomIndex := range bloomIndexList {
				m.addScheduler(bloomIndex)
			}
		}
	}
	return m
}

// addScheduler adds a bit stream retrieval scheduler for the given bit index if
// it has not existed before. If the bit is already selected for filtering, the
// existing scheduler can be used.
func (m *Matcher) addScheduler(idx uint) {
	if _, ok := m.schedulers[idx]; ok {
		return
	}
	m.schedulers[idx] = newScheduler(idx)
}

// Start starts the matching process and returns a stream of bloom matches in
// a given range of blocks. If there are no more matches in the range, the result
// channel is closed.
func (m *Matcher) Start(ctx context.Context, begin, end uint64, results chan uint64) (*MatcherSession, error) {
	// Make sure we're not creating concurrent sessions
	if atomic.SwapUint32(&m.running, 1) == 1 {
		return nil, errors.New("matcher already running")
	}
	defer atomic.StoreUint32(&m.running, 0)

	// Initiate a new matching round
	session := &MatcherSession


 MATRIX Authors
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php
package interest

import (
	"encoding/json"
	"fmt"
	"math/big"
	"strconv"
	"testing"

	"github.com/MatrixAINetwork/go-matrix/params/manparams"

	"github.com/MatrixAINetwork/go-matrix/core/state"

	"github.com/MatrixAINetwork/go-matrix/mandb"

	"bou.ke/monkey"
	"github.com/MatrixAINetwork/go-matrix/ca"
	"github.com/MatrixAINetwork/go-matrix/common"
	"github.com/MatrixAINetwork/go-matrix/core/matrixstate"
	"github.com/MatrixAINetwork/go-matrix/core/types"
	"github.com/MatrixAINetwork/go-matrix/core/vm"
	"github.com/MatrixAINetwork/go-matrix/log"
	"github.com/MatrixAINetwork/go-matrix/mc"
	"github.com/MatrixAINetwork/go-matrix/reward/util"
	. "github.com/smartystreets/goconvey/convey"
)

var (
	testData1 = `{
    "vipcfg":[
        {
            "MinMoney":"0",
            "InterestRate":250000,
            "ElectUserNum":0,
            "StockScale":100
        },
        {
            "MinMoney":"1000000",
            "InterestRate":500000,
            "ElectUserNum":0,
            "StockScale":100
        },
        {
            "MinMoney":"10000000",
            "InterestRate":1000000,
            "ElectUserNum":0,
            "StockScale":100
        }
    ],
    "node":[
        {
            "Reward":3333416193728519,
            "Stock":2,
            "Deposit":"814723686393178936357242054",
            "Interest":814723686393178936357242,
            "Address":"1"
        },
        {
            "Reward":3706019060969665,
            "Stock":1,
            "Deposit":"905791937075619224559898552",
            "Interest":905791937075619224559898,
            "Address":"2"
        },
        {
            "Reward":519562542359325,
            "Stock":2,
            "Deposit":"126986816293506055154541621",
            "Interest":126986816293506055154541,
            "Address":"3"
        },
        {
            "Reward":3737048425943429,
            "Stock":1,
            "Deposit":"913375856139019393085364978",
            "Interest":913375856139019393085364,
            "Address":"4"
        },
        {
            "Reward":2587277854843755,
            "Stock":2,
            "Deposit":"632359246225409510350979583",
            "Interest":632359246225409510350979,
            "Address":"5"
        },
        {
            "Reward":399083481919241,
            "Stock":2,
            "Deposit":"97540404999409524578888080",
            "Interest":97540404999409524578888,
            "Address":"6"
        },
        {
            "Reward":1139466653787643,
            "Stock":1,
            "Deposit":"278498218867048397132120406",
            "Interest":278498218867048397132120,
            "Address":"7"
        },
        {
            "Reward":2237548438341328,
            "Stock":1,
            "Deposit":"546881519204983845844260650",
            "Interest":546881519204983845844260,
            "Address":"8"
        },


set <var>scopeString</var> to serialized <var>scope</var> with the exclude fragment flag set.

Let <var>registration</var> be null.

        For each Record {[[key]], [[value]]} <var>entry</var> of its scope to registration map:

If <var>scopeString</var> matches <var>entry</var>.[[key]], set <var>registration</var> to <var>entry</var>.[[value]].

Return <var>registration</var>.

Get Newest Worker

Input

<var>registration</var>, a service worker registration

Output

<var>worker</var>, a service worker

Run the following steps atomically.

Let <var>newestWorker</var> be null.

If <var>registration</var>’s installing worker is not null, set <var>newestWorker</var> to <var>registration</var>’s installing worker.

Else if <var>registration</var>’s waiting worker is not null, set <var>newestWorker</var> to <var>registration</var>’s waiting worker.

Else if <var>registration</var>’s active worker is not null, set <var>newestWorker</var> to <var>registration</var>’s active worker.

Return <var>newestWorker</var>.

Create Client

Input

<var>client


dicted_m2_scaled[i]))
                    count_predicted_m1_for_common=count_predicted_m1_for_common+1
            #print(str(predicted_m2_scaled))
            #predicted_m2_scaled=predicted_m2*(max_m2-min_m2)+min_m2 #repeat because predicted_m2 changed - no need
        else:
            predicted_m2_scaled=[]
    elif not predict_both_models:
        print('do not use both models, only model 2, at the common area')
        if m2_x_eval.size > 0:
            #y_eval_m2=(m2_y_eval-min_m2)/(max_m2-min_m2)
            x_eval_m2=(m2_x_eval-min_input_m2)/(max_input_m2-min_input_m2)#
            predicted_m2=model2_load.predict(x_eval_m2)

            predicted_m2_scaled=predicted_m2*(max_m2-min_m2)+min_m2
        else:
            predicted_m2_scaled=[]
    else:
        print('wrong option, please choose if predict with both models on the common area')

    #y_eval_m1_kept=(m2_y_eval_kept-minimum_out)/(maximum_out-minimum_out)
    x_eval_m1_kept=(m2_x_eval_kept-min_input_m1)/(max_input_m1-min_input_m1)#
    predicted_test_m1_kept=model1_load.predict(x_eval_m1_kept)

    # coords_obs=np.row_stack((m2_data_coords,m2_data_coords_kept))

    predicted_m1_scaled=predicted_test_m1_kept*(maximum_out-minimum_out)+minimum_out

    y_modeled=np.exp(np.append(predicted_m2_scaled,predicted_m1_scaled))

    #no concentration value below zero
    y_modeled_zero = y_modeled.copy()
    y_modeled_zero[y_modeled_zero < 0] = 0

    #to make maps
    # y_mod_and_coord=np.column_stack((coords_obs,y_modeled_zero))

    # #save to csv file
    # makecsvname=(ann_ssc_model_outpath+'/'+'ssc_prediction'+'.csv')#
    # columns = ['lat', 'lon', 'date', 'SSC_modeled']
    # rownumber,foo=y_mod_and_coord.shape
    # with open(makecsvname, 'w', newline='') as f:
    #     writer = csv.writer(f)
    #     writer.writerow(columns)
    #     for row in range(0,rownumber):
    #         row_to_write=y_mod_and_coord[row]
    #         writer.writerow(row_to_write)

    return y_modeled_zero


tion_string = strdup(arg);
		} else if (strcmp(token, "v1_superblock") == 0) {
			journal_flags |= EXT2_MKJOURNAL_V1_SUPER;
			continue;
		} else
			journal_usage++;
	}
	if (journal_usage) {
		fputs(_("\nBad journal options specified.\n\n"
			"Journal options are separated by commas, "
			"and may take an argument which\n"
			"\tis set off by an equals ('=') sign.\n\n"
			"Valid journal options are:\n"
			"\tsize=<journal size in megabytes>\n"
			"\tdevice=<journal device>\n"
			"\tlocation=<journal location>\n\n"
			"The journal size must be between "
			"1024 and 10240000 filesystem blocks.\n\n"), stderr);
		free(buf);
		exit(1);
	}
	free(buf);
}

static inline int jsize_to_blks(ext2_filsys fs, int size)
{
	return (size * 1024) / (fs->blocksize / 1024);
}

/* Fast commit size is in KBs */
static inline int fcsize_to_blks(ext2_filsys fs, int size)
{
	return (size * 1024) / (fs->blocksize);
}

/*
 * Determine the number of journal blocks to use, either via
 * user-specified # of megabytes, or via some intelligently selected
 * defaults.
 *
 * Find a reasonable journal file size (in blocks) given the number of blocks in
 * the filesystem. For very small filesystems, it is not reasonable to have a
 * journal that fills more than half of the filesystem.
 */
void figure_journal_size(struct ext2fs_journal_params *jparams,
		int requested_j_size, int requested_fc_size, ext2_filsys fs)
{
	int total_blocks, ret;

	ret = ext2fs_get_journal_params(jparams, fs);
	if (ret) {
		fputs(_("\nFilesystem too small for a journal\n"), stderr);
		return;
	}

	if (requested_j_size > 0 ||
		(ext2fs_has_feature_fast_commit(fs->super) && requested_fc_size > 0)) {
		if (requested_j_size > 0)
			jparams->num_journal_blocks =
				jsize_to_blks(fs, requested_j_size);
		if (ext2fs_has_feature_fast_commit(fs->super) &&
			requested_fc_size > 0)
			jparams->num_fc_blocks =
				fcsize_to_blks(fs, requested_fc_size);
		else if (!ext2fs_has_feature_fast_commit(fs->super))
			jparams->num_fc_blocks = 0;
		total_blocks = jparams->num_journal_blocks + jparams->num_fc_blocks;
		if (total_blocks < 1024 || total_blocks > 10240000) {
			fprintf(stderr, _("\nThe total requested journal "
				"size is %d blocks; it must be\n"
				"between 1024 and 10240000 blocks.  "
				"Aborting.\n"),
				total_blocks);
			exit(1);
		}
		if ((unsigned int) total_blocks > ext2fs_free_blocks_count(fs->super) / 2) {
			fputs(_("\nTotal journal size too big for filesystem.\n"),
			      stderr);
			exit(1);
		}
	}
}

void print_check_message(int mnt, unsigned int check)
{
	if (mnt < 0)
		mnt = 0;
	if (!mnt && !check)
		return;
	printf(_("This filesystem will be automatically "
		 "checked every %d mounts or\n"
		 "%g days, whichever comes first.  "
		 "Use tune2fs -c or -i to override.\n"),
	       mnt, ((double) check) / (3600 * 24));
}

void dump_mmp_msg(struct mmp_struct *mmp, const char *msg)
{

	if (msg)
		printf("MMP check failed: %s\n", msg);
	if (mmp) {
		time_t t = mmp->mmp_time;

		printf("MMP error info: node: %.*s, device: %.*s, updated: %s",
		       EXT2_LEN_STR(mmp->mmp_nodename),
		       EXT2_LEN_STR(mmp->mmp_bdevname), ctime(&t));
	}
}


= {link = "Typedef"},
markdownFootnoteDefinition = {link = "Typedef"},
markdownIdDeclaration = {link = "Typedef"},
["@lsp.type.typeParameter"] = {link = "Typedef"},
["@type.definition"] = {link = "Typedef"},
Underlined = {underline = true},
["@text.underline"] = {link = "Underlined"},
["@text.uri"] = {link = "Underlined"},
Variable = {fg = "#ecddce", bold = false},
["@variable"] = {link = "Variable"},
VertSplit = {fg = "#000000"},
Visual = {bg = "#2d59a1"},
BookmarkAnnotationLine = {link = "Visual"},
BookmarkLine = {link = "Visual"},
BqfPreviewRange = {link = "Visual"},
TelescopeSelection = {link = "Visual"},
VisualNOS = {bg = "#2d59a1"},
WarningMsg = {fg = "#e0af68"},
["@text.danger"] = {link = "WarningMsg"},
WhichKey = {fg = "#7dcfff"},
WhichKeyDesc = {fg = "#bb9af7"},
WhichKeyFloat = {bg = "#16161e"},
WhichKeyGroup = {fg = "#7aa2f7"},
WhichKeySeparator = {},
WhichKeyValue = {fg = "#737aa2"},
Whitespace = {fg = "#3b4261"},
WildMenu = {bg = "#2d59a1", bold = true},
WinBar = {fg = "#c0caf5"},
WinBarNC = {link = "WinBar"},
WinSeparator = {fg = "#000000", bold = true},
lCursor = {fg = "#1a1b26", bg = "#c0caf5"},
luaNumber = {fg = "#ff849a", bold = false},
["lualine_a_18_command"] = {fg = "#16161e", bg = "#e0af68"},
["lualine_a_18_inactive"] = {fg = "#7aa2f7", bg = "#16161e"},
["lualine_a_18_insert"] = {fg = "#16161e", bg = "#9ece6a"},
["lualine_a_18_normal"] = {fg = "#16161e", bg = "#7aa2f7"},
["lualine_a_18_replace"] = {fg = "#16161e", bg = "#f7768e"},
["lualine_a_18_terminal"] = {fg = "#16161e", bg = "#7aa2f7"},
["lualine_a_18_visual"] = {fg = "#16161e", bg = "#bb9af7"},
["lualine_a_8_command"] = {fg = "#16161e", bg = "#e0af68"},
["lualine_a_8_inactive"] = {fg = "#7aa2f7", bg = "#16161e"},
["lualine_a_8_insert"] = {fg = "#16161e", bg = "#9ece6a"},
["lualine_a_8_normal"] = {fg = "#16161e", bg = "#7aa2f7"},
["lualine_a_8_replace"] = {fg = "#16161e", bg = "#f7768e"},
["lualine_a_8_terminal"] = {fg = "#16161e", bg = "#7aa2f7"},
["lualine_a_8_visual"] = {fg = "#16161e", bg = "#bb9af7"},
["lualine_a_command"] = {fg = "#16161e", bg = "#e0af68"},
["lualine_a_inactive"] = {fg = "#7aa2f7", bg = "#16161e"},
["lualine_a_insert"] = {fg = "#16161e", bg = "#9ece6a"},
["lualine_a_normal"] = {fg = "#16161e", bg = "