 [$sp, 4]
        add    $sp, $sp, 20
.endm

.macro  push5   a, b, c, d, e
        sub     $sp, $sp, 24
        str32   \a, [$sp, 4]
        str32   \b, [$sp, 8]
        str32   \c, [$sp, 12]
        str32   \d, [$sp, 16]
        str32   \e, [$sp, 20]
.endm

.macro  pop5    a, b, c, d, e
        ldr32   \e, [$sp, 20]
        ldr32   \d, [$sp, 16]
        ldr32   \c, [$sp, 12]
        ldr32   \b, [$sp, 8]
        ldr32   \a, [$sp, 4]
        add    $sp, $sp, 24
.endm

.macro  push6   a, b, c, d, e, f
        sub     $sp, $sp, 28
        str32   \a, [$sp, 4]
        str32   \b, [$sp, 8]
        str32   \c, [$sp, 12]
        str32   \d, [$sp, 16]
        str32   \e, [$sp, 20]
        str32   \f, [$sp, 24]
.endm

.macro  pop6    a, b, c, d, e, f
        ldr32   \f, [$sp, 24]
        ldr32   \e, [$sp, 20]
        ldr32   \d, [$sp, 16]
        ldr32   \c, [$sp, 12]
        ldr32   \b, [$sp, 8]
        ldr32   \a, [$sp, 4]
        add    $sp, $sp, 28
.endm


("icon-image"),s=("constant"!==a.value.kind||a.value.value.length>0)&&("constant"!==i.value.kind||i.value.value.length>0),l="constant"!==o.value.kind||o.value.value&&o.value.value.length>0;if(this.features=[],s||l){for(var c=e.iconDependencies,u=e.glyphDependencies,f=new Lr(this.zoom),h=0,p=t;h<p.length;h+=1){var d=p[h],g=d.feature,v=d.index,m=d.sourceLayerIndex;if(r._featureFilter(f,g)){var y=void 0;s&&(y=Da(y=r.getValueAndResolveTokens("text-field",g),r,g));var x=void 0;if(l&&(x=r.getValueAndResolveTokens("icon-image",g)),y||x){var b={text:y,icon:x,index:v,sourceLayerIndex:m,geometry:Fn(g),properties:g.properties,type:Ba[g.type]};if(void 0!==g.id&&(b.id=g.id),this.features.push(b),x&&(c[x]=!0),y)for(var _=i.evaluate(g).join(","),w=u[_]=u[_]||{},k="map"===n.get("text-rotation-alignment")&&"line"===n.get("symbol-placement"),T=xr(y),A=0;A<y.length;A++)if(w[y.charCodeAt(A)]=!0,k&&T){var M=Pa[y.charAt(A)];M&&(w[M.charCodeAt(0)]=!0)}}}}"line"===n.get("symbol-placement")&&(this.features=function(t){var e={},r={},n=[],i=0;function a(e){n.push(t[e]),i++}function o(t,e,i){var a=r[t];return delete r[t],r[e]=a,n[a].geometry[0].pop(),n[a].geometry[0]=n[a].geometry[0].concat(i[0]),a}function s(t,r,i){var a=e[r];return delete e[r],e[t]=a,n[a].geometry[0].shift(),n[a].geometry[0]=i[0].concat(n[a].geometry[0]),a}function l(t,e,r){var n=r?e[0][e[0].length-1]:e[0][0];return t+":"+n.x+":"+n.y}for(var c=0;c<t.length;c++){var u=t[c],f=u.geometry,h=u.text;if(h){var p=l(h,f),d=l(h,f,!0);if(p in r&&d in e&&r[p]!==e[d]){var g=s(p,d,f),v=o(p,d,n[g].geometry);delete e[p],delete r[d],r[l(h,n[v].geometry,!0)]=v,n[g].geometry=null}else p in r?o(p,d,f):d in e?s(p,d,f):(a(c),e[p]=i-1,r[d]=i-1)}else a(c)}return n.filter(function(t){return t.geometry})}(this.features))}},qa.prototype.isEmpty=function(){return 0===this.symbolInstances.length},qa.prototype.upload=function(t){this.text.upload(t,this.sortFeaturesByY),this.icon.upload(t,this.sortFeaturesByY),this.collisionBox.upload(t),this.collisionCircle.upload(t)},qa.prototype.destroy=function(){this.text.destroy(),this.icon.destroy(),this.collisionBox.destroy(),this.collisionCircle.destroy()},qa.prototype.addToLineVertexArray=function(t,e){var r=this.lineVertexArray.length;if(void 0!==t.segment){for(var n=t.dist(e[t.segment+1]),i=t.dist(e[t.segment]),a={},o=t.segment+1;o<e.length;o++)a[o]={x:e[o].x,y:e[o].y,tileUnitDistanceFromAnchor:n},o<e.length-1&&(n+=e[o+1].dist(e[o]));for(var s=t.segment||0;s>=0;s--)a[s]={x:e[s].x,y:e[s].y,tileUnitDistanceFrom


// Copyright Karel Kroeze, 2020-2021.
// WorkTab/WorkTab/DefOf.cs

using RimWorld;
using Verse;

namespace WorkTab
{
    [DefOf]
    public static class PawnColumnDefOf
    {
        public static                      PawnColumnDef CopyPasteDetailedWorkPriorities;
        public static                      PawnColumnDef CopyPasteWorkPriorities;
        public static                      PawnColumnDef Faction;
        public static                      PawnColumnDef Favourite;
        [MayRequireIdeology] public static PawnColumnDef Guest;
        [MayRequireIdeology] public static PawnColumnDef Ideo;
        public static                      PawnColumnDef Job;
        public static                      PawnColumnDef Label;
        public static                      PawnColum


class13/group}description"/>
 *         <element ref="{http://www.ebu.ch/ebucore/smpte/class13/group}spatial"/>
 *         <element ref="{http://www.ebu.ch/ebucore/smpte/class13/group}audioContent"/>
 *         <element ref="{http://www.ebu.ch/ebucore/smpte/class13/group}technicalAttributeUInt32"/>
 *         <element ref="{http://www.ebu.ch/ebucore/smpte/class13/group}audioPackFormat"/>
 *         <element ref="{http://www.ebu.ch/ebucore/smpte/class13/group}compoundName"/>
 *         <element ref="{http://www.ebu.ch/ebucore/smpte/class13/group}language"/>
 *         <element ref="{http://www.ebu.ch/ebucore/smpte/class13/group}hash"/>
 *         <element ref="{http://www.ebu.ch/ebucore/smpte/class13/group}publicationMedium"/>
 *         <element ref="{http://www.ebu.ch/ebucore/smpte/class13/group}audioMXFLookup"/>
 *         <element ref="{http://www.ebu.ch/ebucore/smpte/class13/group}rating"/>
 *         <element ref="{http://www.ebu.ch/ebucore/smpte/class13/group}ancillaryData"/>
 *         <element ref="{http://www.ebu.ch/ebucore/smpte/class13/group}coordinates"/>
 *         <element ref="{http://www.ebu.ch/ebucore/smpte/class13/group}coreMetadata"/>
 *         <element ref="{http://www.ebu.ch/ebucore/smpte/class13/group}timecodeFormat"/>
 *         <element ref="{http://www.ebu.ch/ebucore/smpte/class13/group}department"/>
 *         <element ref="{http://www.ebu.ch/ebucore/smpte/class13/group}audioBlockFormat"/>
 *         <element ref="{http://www.ebu.ch/ebucore/smpte/class13/group}basicLink"/>
 *         <element ref="{http://www.ebu.ch/ebucore/smpte/class13/group}technicalAttributeInt64"/>
 *         <element ref="{http://www.ebu.ch/ebucore/smpte/class13/group}containerFormat"/>
 *         <element ref="{http://www.ebu.ch/ebucore/smpte/class13/group}dateType"/>
 *         <element ref="{http://www.ebu.ch/ebucore/smpte/class13/group}technicalAttributeBoolean"/>
 *         <element ref="{http://www.ebu.ch/ebucore/smpte/class13/group}address"/>
 *         <element ref="{http://www.ebu.ch/ebucore/smpte/class13/group}identifier"/>
 *         <element ref="{http://www.ebu.ch/ebucore/smpte/class13/group}rational"/>
 *         <element ref="{http://www.smpte-ra.org/reg/395/2014/13/1/aaf}NameValue"/>
 *         <element ref="{http://www.smpte-ra.org/reg/395/2014/13/1/aaf}Project"/>
 *         <element ref="{http://www.smpte-ra.org/reg/395/2014/13/1/aaf}Processing"/>
 *         <element ref="{http://www.smpte-ra.org/reg/395/2014/13/1/aaf}Titles"/>
 *         <el


list li, div.orderedlist li {
  margin-left: -0.8em;
  margin-top: 0.5em;
}

ul, ol {
    list-style-position: outside;
}

div.sidebar ul, div.sidebar ol {
    margin-left: 2.8em;
}

div.itemizedlist p.title,
div.orderedlist p.title,
div.variablelist p.title
{
  margin-bottom: -0.8em;
}

div.revhistory table {
  border-collapse: collapse;
  border: none;
}
div.revhistory th {
  border: none;
  color: #527bbd;
  font-family: Arial,Helvetica,sans-serif;
}
div.revhistory td {
  border: 1px solid silver;
}

/* Keep TOC and index lines close together. */
div.toc dl, div.toc dt,
div.list-of-figures dl, div.list-of-figures dt,
div.list-of-tables dl, div.list-of-tables dt,
div.indexdiv dl, div.indexdiv dt
{
  line-height: normal;
  margin-top: 0;
  margin-bottom: 0;
}

/*
  Table styling does not work because of overriding attributes in
  generated HTML.
*/
div.table table,
div.informaltable table
{
    margin-left: 0;
    margin-right: 5%;
    margin-bottom: 0.8em;
}
div.informaltable table
{
    margin-top: 0.4em
}
div.table thead,
div.table tfoot,
div.table tbody,
div.informaltable thead,
div.informaltable tfoot,
div.informaltable tbody
{
    /* No effect in IE6. */
    border-top: 3px solid #527bbd;
    border-bottom: 3px solid #527bbd;
}
div.table thead, div.table tfoot,
div.informaltable thead, div.informaltable tfoot
{
    font-weight: bold;
}

div.mediaobject img {
    margin-bottom: 0.8em;
}
div.figure p.title,
div.table p.title
{
  margin-top: 1em;
  margin-bottom: 0.4em;
}

div.calloutlist p
{
  margin-top: 0em;
  margin-bottom: 0.4em;
}

a img {
  border-style: none;
}

@media print {
  div.navheader, div.navfooter { display: none; }
}

span.aqua { color: aqua; }
span.black { color: black; }
span.blue { color: blue; }
span.fuchsia { color: fuchsia; }
span.gray { color: gray; }
span.green { color: green; }
span.lime { color: lime; }
span.maroon { color: maroon; }
span.navy { color: navy; }
span.olive { color: olive; }
span.purple { color: purple; }
span.red { color: red; }
span.silver { color: silver; }
span.teal { color: teal; }
span.white { color: white; }
span.yellow { color: yellow; }

span.aqua-background { background: aqua; }
span.black-background { background: black; }
span.blue-background { background: blue; }
span.fuchsia-background { background: fuchsia; }
span.gray-background { background: gray; }
span.green-background { background: green; }
span.lime-background { background: lime; }
span.maroon-background { background: maroon; }
span.navy-background { background: navy; }
s


:= &utilmock.Client{}
	ctx := prepareTestContext(context.Background(), clientMock, nil)
	clientMock.On("Get", ctx, client.ObjectKey{
		Name: cluster.Namespace,
	}, &actualNamespace).Return(nil).Run(func(args mock.Arguments) {
		arg := args.Get(2).(*corev1.Namespace)
		arg.Labels = map[string]string{util.LabelName: fmt.Sprintf(util.LabelValue, "Project", cluster.Namespace)}
	}).Once()
	_, err := ValidateClusterCreate(ctx, cluster)
	require.Nil(t, err)
	clientMock.AssertExpectations(t)
}

func testValidateClusterGeolocationPassOnUpdate(t *testing.T) {
	cluster := &controllerv1alpha1.Cluster{
		Spec: controllerv1alpha1.ClusterSpec{ClusterProperty: controllerv1alpha1.ClusterProperty{GeoLocation: controllerv1alpha1.GeoLocation{CloudProvider: "", CloudRegion: "", Latitude: "23.43345", Longitude: "83.43345"}}},
	}
	clientMock := &utilmock.Client{}
	ctx := prepareTestContext(context.Background(), clientMock, nil)
	_, err := ValidateClusterUpdate(ctx, cluster, runtime.Object(cluster))
	require.Nil(t, err)
	clientMock.AssertExpectations(t)
}
/*
 * 	Copyright (c) 2022 Avesha, Inc. All rights reserved. # # SPDX-License-Identifier: Apache-2.0
 *
 * 	Licensed under the Apache License, Version 2.0 (the "License");
 * 	you may not use this file except in compliance with the License.
 * 	You may obtain a copy of the License at
 *
 * 	http://www.apache.org/licenses/LICENSE-2.0
 *
 * 	Unless required by applicable law or agreed to in writing, software
 * 	distributed under the License is distributed on an "AS IS" BASIS,
 * 	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * 	See the License for the specific language governing permissions and
 * 	limitations under the License.
 */

package service

import (
	"context"
	"errors"
	"github.com/kubeslice/kubeslice-controller/metrics"
	metricMock "github.com/kubeslice/kubeslice-controller/metrics/mocks"
	"testing"

	"github.com/kubeslice/kubeslice-monitoring/pkg/events"
	"k8s.io/apimachinery/pkg/runtime"

	"github.com/dailymotion/allure-go"
	controllerv1alpha1 "github.com/kubeslice/kubeslice-controller/apis/controller/v1alpha1"
	ossEvents "github.com/kubeslice/kubeslice-controller/events"

	"github.com/kubeslice/kubeslice-controller/service/mocks"
	"github.com/kubeslice/kubeslice-controller/util"
	utilMock "github.com/kubeslice/kubeslice-controller/util/mocks"
	"github.com/stretchr/testify/mock"
	"github.com/stretchr/testify/require"
	k8sError "k8s.io/apimachinery/pkg/api/errors"
	k8sapimachinery "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/types"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

func TestServiceExportConfigSuite(t *testing.T) {
	for k, v := range ServiceExportConfigTestBed {
		t.Run(k, func(t *testing.T) {
			allure.Test(t, allure.Name(k),
				allure.Action(func() {
					v(t)
				}))
		})
	}
}

var ServiceExportConfigTestBed =


 periodically _test_ those snapshots by performing
a real recovery!  It is all too common for organizations to make routine backups but
never test their recovery strategy.  Often you'll find a glaring deficiency
the first time you perform a real recovery (such as users being unaware of which
drive to mount).  It's better to work these bugs out of your process with
routine testing, rather than at 3 a.m. when there is a crisis.
#### 自定义_all字段

在[元数据：_all字段](../070_Index_Mgmt/32_Metadata_all.md)中，我们解释了特殊的_all字段会将其它所有字段中的值作为一个大字符串进行索引。尽管将所有字段的值作为一个字段进行索引并不是非常灵活。如果有一个自定义的_all字段用来索引人名，另外一个自定义的_all字段用来索引地址就更好了。

ES通过字段映射中的copy_to参数向我们提供了这一功能：

```Javascript
PUT /my_index
{
    "mappings": {
        "person": {
            "properties": {
                "first_name": {
                    "type":     "string",
                    "copy_to":  "full_name" <1>
                },
                "last_name": {
                    "type":     "string",
                    "copy_to":  "full_name" <1>
                },
                "full_name": {
                    "type":     "string"
                }
            }
        }
    }
}
```
// SENSE: 110_Multi_Field_Search/45_Custom_all.json

<1> first_name和last_name字段中的值会被拷贝到full_name字段中。

有了这个映射，我们可以通过first_name字段查询名字，last_name字段查询姓氏，或者full_name字段查询姓氏和名字。

> 提示：first_name和last_name字段的映射和full_name字段的索引方式的无关。full_name字段会从其它两个字段中拷贝字符串的值，然后仅根据full_name字段自身的映射进行索引。

<!--
[[custom-all]]
=== Custom _all Fields

In <<all-field>>, we explained that the special `_all` field indexes the values
from all other fields as one big string.((("_all field", sortas="all field")))((("multifield search", "custom _all fields"))) Having all fields indexed into one
field is not terribly flexible, though.  It would be nice to have one custom
`_all` field for the person's name, and another custom `_all` field for the
address.

Elasticsearch provides us with this functionality via the `copy_to` parameter
in a field ((("copy_to parameter")))((("mapping (types)", "copy_to parameter")))mapping:

[source,js]
--------------------------------------------------
PUT /my_index
{
    "mappings": {
        "person": {
            "properties": {
                "first_name": {
                    "type":     "string",
                    "copy_to":  "full_name" <1>
                },
                "last_name": {
                    "type":     "string",
                    "copy_to":  "full_name" <1>
                },
                "full_name": {
                    "type":     "string"
                }
            }
        }
    }
}
--------------------------------------------------
// SENSE: 110_Multi_Field_Search/45_Custom_all.json

<1> The values in the `first_name` and `last_name` fields
    are also copied to the `full_name` field.


 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.
 */

import com.google.protobuf.gradle.id

plugins {
    id("com.android.application")
    id("com.google.devtools.ksp")
    id("com.google.protobuf")
    id("dagger.hilt.android.plugin")
    kotlin("android")
    alias(libs.plugins.compose.compiler)
}

android {
    compileSdk = 36

    defaultConfig {
        applicationId = "com.google.android.horologist.datalayer.sample"
        // Min because of Tiles
        minSdk = 26
        targetSdk = 34

        versionCode = 1
        versionName = "1.0"

        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        debug {
            applicationIdSuffix = ".debug"
            manifestPlaceholders["schemeSuffix"] = "-debug"
        }
        release {
            manifestPlaceholders["schemeSuffix"] = ""

            isMinifyEnabled = true
            isShrinkResources = true
            proguardFiles(
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "proguard-rules.pro",
            )

            signingConfig = signingConfigs.getByName("debug")
        }
    }

    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_17
        targetCompatibility = JavaVersion.VERSION_17
    }

    buildFeatures {
        buildConfig = true
    }

    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_17.majorVersion

        // Allow for widescale experimental APIs in Alpha libraries we build upon
        freeCompilerArgs = freeCompilerArgs +
            listOf(
                "-opt-in=com.google.android.horologist.annotations.ExperimentalHorologistApi",
            )
    }

    testOptions {
        unitTests {
            isIncludeAndroidResources = true
        }
        animationsDisabled = true
    }

    lint {
        // https://buganizer.corp.google.com/issues/328279054
        disable.add("UnsafeOptInUsageError")
    }

    namespace = "com.google.android.horologist.datalayer.sample"
}

sourceSets {
    create("main") {
        java {
            srcDirs(
                "build/generated/source/proto/debug/java",
                "build/generated/source/proto/debug/grpc",
                "build/generated/source/proto/debug/kotlin",
                "build/generated/source/proto/debug/grpckt",
            )
        }
    }
}

protobuf {
    protoc {
        artifact = libs.protobuf.protoc.stnd.get().toString()
    }
    plugins {
        id("javalite") {
            artifact = libs.protobuf.protoc.gen.javalite.get().toString()
        }
    }
    generateProtoTasks {
        all().forEach { task ->
            task.builtins {
                create("java") {
                    option("lite")
                }
                create("kotlin") {
                    option("lite")
                }
            }
        }
    }
}

dependencies {
    api(projects.annotations)

    implementation(projects.composables)
    implementation(projects.composeLayout)
    implementation(projects.composeMaterial)
    implementation(projects.datalayer.core)
    implementation(projects.datalayer.grpc)
    implementation(projects.datalayer.sample.share


ast .swal2-success .swal2-success-fix{width:7px;height:90px;left:28px;top:8px}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line]{height:5px}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line][class$=tip]{width:12px;left:3px;top:18px}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line][class$=long]{width:22px;right:3px;top:15px}.swal2-popup.swal2-toast .swal2-animate-success-line-tip{-webkit-animation:animate-toast-success-tip .75s;animation:animate-toast-success-tip .75s}.swal2-popup.swal2-toast .swal2-animate-success-line-long{-webkit-animation:animate-toast-success-long .75s;animation:animate-toast-success-long .75s}.swal2-popup:focus{outline:0}.swal2-popup.swal2-loading{overflow-y:hidden}.swal2-popup .swal2-title{color:#595959;font-size:30px;text-align:center;font-weight:600;text-transform:none;position:relative;margin:0 0 .4em;padding:0;display:block;word-wrap:break-word}.swal2-popup .swal2-buttonswrapper{-webkit-box-align:center;-ms-flex-align:center;align-items:center;-webkit-box-pack:center;-ms-flex-pack:center;justify-content:center;margin-top:15px}.swal2-popup .swal2-buttonswrapper:not(.swal2-loading) .swal2-styled[disabled]{opacity:.4;cursor:no-drop}.swal2-popup .swal2-buttonswrapper.swal2-loading .swal2-styled.swal2-confirm{-webkit-box-sizing:border-box;box-sizing:border-box;border:4px solid transparent;border-color:transparent;width:40px;height:40px;padding:0;margin:7.5px;vertical-align:top;background-color:transparent!important;color:transparent;cursor:default;border-radius:100%;-webkit-animation:rotate-loading 1.5s linear 0s infinite normal;animation:rotate-loading 1.5s linear 0s infinite normal;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.swal2-popup .swal2-buttonswrapper.swal2-loading .swal2-styled.swal2-cancel{margin-left:30px;margin-right:30px}.swal2-popup .swal2-buttonswrapper.swal2-loading :not(.swal2-styled).swal2-confirm::after{display:inline-block;content:'';margin-left:5px;vertical-align:-1px;height:15px;width:15px;border:3px solid #999;-webkit-box-shadow:1px 1px 1px #fff;box-shadow:1px 1px 1px #fff;border-right-color:transparent;border-radius:50%;-webkit-animation:rotate-loading 1.5s linear 0s infinite normal;animation:rotate-loading 1.5s linear 0s infinite normal}.swal2-popup .swal2-styled{border:0;border-radius:3px;-webkit-box-shadow:none;box-shadow:none;color:#fff;cursor:pointer;font-size:17px;font-weight:500;margin:15px 5px 0;padding:10px 32px}.swal2-popup .swal2-styled:focus{outl


    Ping,
    Pong,
    Publish,
    Connect,
    Message,
    Subscribe,
    Unsubscribe,
}

impl TryFrom<&[u8]> for Op {
    type Error = InvalidOp;

    #[inline]
    fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
        Ok(match value {
            // hottest
            [b'p' | b'P', b'u' | b'U', b'b' | b'B'] => Op::Publish,
            [b'm' | b'M', b's' | b'S', b'g' | b'G'] => Op::Message,
            //
            [b's' | b'S', b'u' | b'U', b'b' | b'B'] => Op::Subscribe,
            [b'i' | b'I', b'n' | b'N', b'f' | b'F', b'o' | b'O'] => Op::Info,
            [b'p' | b'P', b'i' | b'I', b'n' | b'N', b'g' | b'G'] => Op::Ping,
            [b'p' | b'P', b'o' | b'O', b'n' | b'N', b'g' | b'G'] => Op::Pong,
            [b'u' | b'U', b'n' | b'N', b's' | b'S', b'u' | b'U', b'b' | b'B'] => Op::Unsubscribe,
            [b'c' | b'C', b'o' | b'O', b'n' | b'N', b'n' | b'N', b'e' | b'E', b'c' | b'C', b't' | b'T'] => {
                Op::Connect
            }

            [b'+', b'o' | b'O', b'k' | b'K'] => Op::Ok,
            [b'-', b'e' | b'E', b'r' | b'R', b'r' | b'R'] => Op::Err,
            _ => return Err(invalid_op(value)),
        })
    }
}

fn invalid_op(value: &[u8]) -> InvalidOp {
    let invalid_op = String::from_utf8_lossy(value).to_string();

    InvalidOp(invalid_op)
}

#[cfg(test)]
#[test]
fn test_op_try_from() {
    assert_eq!(Ok(Op::Ok), Op::try_from(&b"+ok"[..]));
    assert_eq!(Ok(Op::Ok), Op::try_from(&b"+OK"[..]));

    assert_eq!(Ok(Op::Err), Op::try_from(&b"-err"[..]));
    assert_eq!(Ok(Op::Err), Op::try_from(&b"-ERR"[..]));

    assert_eq!(Ok(Op::Info), Op::try_from(&b"info"[..]));
    assert_eq!(Ok(Op::Info), Op::try_from(&b"INFO"[..]));

    assert_eq!(Ok(Op::Ping), Op::try_from(&b"ping"[..]));
    assert_eq!(Ok(Op::Ping), Op::try_from(&b"PING"[..]));

    assert_eq!(Ok(Op::Pong), Op::try_from(&b"pong"[..]));
    assert_eq!(Ok(Op::Pong), Op::try_from(&b"PONG"[..]));

    assert_eq!(Ok(Op::Publish), Op::try_from(&b"pub"[..]));
    assert_eq!(Ok(Op::Publish), Op::try_from(&b"PUB"[..]));

    assert_eq!(Ok(Op::Connect), Op::try_from(&b"connect"[..]));
    assert_eq!(Ok(Op::Connect), Op::try_from(&b"CONNECT"[..]));

    assert_eq!(Ok(Op::Subscribe), Op::try_from(&b"sub"[..]));
    assert_eq!(Ok(Op::Subscribe), Op::try_from(&b"SUB"[..]));

    assert_eq!(Ok(Op::Unsubscribe), Op::try_from(&b"unsub"[..]));
    assert_eq!(Ok(Op::Unsubscribe), Op::try_from(&b"UNSUB"[..]));

    assert_eq!(Err(InvalidOp("invalid".into())), Op::try_from(&b"invalid"[..]));
}
use anyhow::Result;

use async_std::net::UdpSocket;
use flexi_logger::Logger;
use log::{info, warn};
use phorcys_osc::p


s:number[] = []

    linesStr.map(lineStr => {
        if (lineStr == "x") {
            lines.push(0)
        } else {
            lines.push(parseInt(lineStr))
        }
    })

    var t = offset
    while(t % lines[0] != 0) {
        t = t + 1
    }

    var match = false
    while (!match) {
        match = true
        for (var i = 0; i < lines.length; i ++) {
            if (lines[i] > 0) {
                if (!((t + i) % lines[i] == 0)) {
                    match = false
                    break
                }
            }
        }
        if (match == true) {
            break
        }
        t = t + lines[0]
    }
    return t
}
// console.log(`solution (task2) = ${task2("41,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,37,x,x,x,x,x,541,x,x,x,x,x,x,x,23,x,x,x,x,13,x,x,x,17,x,x,x,x,x,x,x,x,x,x,x,29,x,983,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,19".split(","), 100000000000000)}`)
import {SimpleObject} from "../interfaces";
import {isString} from "../Util";
import {Renderable} from "../core/Renderable";
import {StringLiteral} from "../core/StringLiteral";
import {TemplateParser} from "../core/TemplateParser";

/**
 * The If class renders a Renderable based on a condition.
 */
export class If extends Renderable {
    private readonly condition: boolean | string;
    private ifRenderable: Renderable;
    private elseRenderable?: Renderable;
    private elifRenderable?: Renderable;

    /**
     * Constructor
     * @param condition The condition that determines if the renderable gets rendered.
     * @param toRenderIf The renderable to render if the condition is true.
     * @param toRenderElse The renderable to render if the condition is false (and no truthy elif exists).
     */
    constructor(condition: boolean | string, toRenderIf?: Renderable | string, toRenderElse?: Renderable | string) {
        super();
        this.condition = condition;

        if (toRenderIf) {
            this.then(toRenderIf);
        }
        if (toRenderElse) {
            this.else(toRenderElse);
        }
    }

    /**
     * Sets the if renderable.
     * @param toRender The renderable to render if the condition is true (and no truthy elif exists).
     */
    then(toRender: Renderable | string): If {
        this.ifRenderable = isString(toRender) ? new StringLiteral(toRender) : toRender;
        return this;
    }

    /**
     * Sets the else renderable.
     * @param toRender The renderable to render if the condition is false (and no truthy elif exists).
     */
    else(toRender: Renderable | string): If {
        this.elseRenderable = isString(toRender) ? new StringLiteral(toRender) : toRender;
        return this;
    }

    /**
     * Adds a new elif block.
     * @param condition The condition that determines if the renderable gets rendered.
     * @param toRender The renderable to render if the condition is true (and the if renderable is false


import hdbscan
from sentence_transformers import SentenceTransformer
import pandas as pd

class OutlierDetector:
    def __init__(self, min_cluster_size=6, min_samples=5, threshold=0.3):
        self.min_cluster_size = min_cluster_size
        self.min_samples = min_samples
        self.threshold = threshold
        self.clusterer = hdbscan.HDBSCAN(min_cluster_size=self.min_cluster_size, min_samples=self.min_samples, prediction_data=True)

    def embed_texts(self, texts):
        st_model = SentenceTransformer('all-MiniLM-L6-v2')
        embeddings = st_model.encode(texts, show_progress_bar=True)
        return embeddings

    def detect_outliers(self, embeddings):
        cluster_labels = self.clusterer.fit_predict(embeddings)
        outlier_scores = self.clusterer.outlier_scores_
        detected_outliers = outlier_scores > self.threshold
        return cluster_labels, outlier_scores, detected_outliers

def rule_based_outlier_check(df):
    answer_keywords = ["chapter", "?", "syllabus", "unit", "paragraph", "para", "case", "act"]
    question_keywords = ["chapter","chapter?", "syllabus", "unit", "paragraph", "para", "case", "act"]

    rule_outliers = []

    for i in range(len(df)):

        question_words = df.iloc[i]['question'].lower().split()
        answer_words = df.iloc[i]['answer'].lower().split()
        question_words = df.iloc[i]['Question'].lower().split()
        answer_words = df.iloc[i]['Answer'].lower().split()

        question_has_noise = any(k in question_words for k in question_keywords)
        answer_has_noise = any(k in answer_words for k in answer_keywords)

        rule_outliers.append(question_has_noise or answer_has_noise)

    return rule_outliers


hêm một phần tử mới tại vị trí của chỉ mục, điều chỉnh lại chỉ mục và đưa các phần tử còn lại dịch chuyển theo
        - [ ] prepend(item) - Thêm tại vị trí chỉ mục 0, hay đầu tiên
        - [ ] pop() - trả về phần tử cuối cùng
        - [ ] delete(index) - Xóa phần tử tại chỉ mục, dịch chuyển lại các phần tử trong mảng
        - [ ] remove(item) - Tìm theo giá trị của phần tử và xóa chỉ mục đang lưu trữ cho phần tử này (áp dụng với việc nhiều phần tử có cùng giá trị)
        - [ ] find(item) - Tìm theo giá trị của phần tử và trả về chỉ mục đầu tiên tìm được, -1 nếu không tìm thấy
        - [ ] resize(new_capacity) // private function
            - Khi tới giới hạn của mảng, tăng gấp đôi giá trị độ dài mảng để thay đổi kích thước
            - Khi xóa 1 thành phần, nếu kích thước hiện tại chỉ bằng 1/4 kích thước được cấp phát, thay đổi thành 1/2
    - [ ] Thời gian thực thi
        - O(1) để thêm/xóa tại vị trí cuối (tính luôn cả cấp phát lại để có thêm không gian lưu trữ), đánh chỉ mục, hay cập nhật
        - O(n) để thêm/xóa tại bất cứ đâu
    - [ ] Không gian
        - Liên tục trong bộ nhớ, giúp cải thiện hiệu suất
        - Không gian cần thiết = (Kích cở của mảng, thường >= n)* kích thước của 1 phần tử, cho dù là 2n, vẫn xem như O(n)

- ### Linked Lists
    - [ ] Miêu tả:
        - [ ] [Singly Linked Lists - Danh sách liên kết (video)](https://www.coursera.org/learn/data-structures/lecture/kHhgK/singly-linked-lists)
        - [ ] [CS 61B - Linked Lists - Danh sách liên kết (video)](https://www.youtube.com/watch?v=sJtJOtXCW_M&list=PL-XXv-cvA_iAlnI-BQr9hjqADPBtujFJd&index=5)
    - [ ] [C Code (video)](https://www.youtube.com/watch?v=QN6FPiD0Gzo)
            - Không cần xem toàn bộ video, chỉ phần cấu trúc Node và cấp phát vùng nhớ.
    - [ ] Danh sách liên kết so sánh với Mảng:
        - [Core Linked Lists Vs Arrays - Danh sách liên kết Vs Mảng (video)](https://www.coursera.org/learn/data-structures-optimizing-performance/lecture


(165, m.Instance(), GetObjectUintptr(Node), uintptr(Column), uintptr(Direction), PascalBool(DoInit))
}

func (m *TBaseVirtualTree) SortTree(Column TColumnIndex, Direction TSortDirection, DoInit bool) {
	baseVirtualTreeImportAPI().SysCallN(166, m.Instance(), uintptr(Column), uintptr(Direction), PascalBool(DoInit))
}

func (m *TBaseVirtualTree) ToggleNode(Node IVirtualNode) {
	baseVirtualTreeImportAPI().SysCallN(167, m.Instance(), GetObjectUintptr(Node))
}

func (m *TBaseVirtualTree) UpdateHorizontalRange() {
	baseVirtualTreeImportAPI().SysCallN(172, m.Instance())
}

func (m *TBaseVirtualTree) UpdateHorizontalScrollBar(DoRepaint bool) {
	baseVirtualTreeImportAPI().SysCallN(173, m.Instance(), PascalBool(DoRepaint))
}

func (m *TBaseVirtualTree) UpdateRanges() {
	baseVirtualTreeImportAPI().SysCallN(174, m.Instance())
}

func (m *TBaseVirtualTree) UpdateScrollBars(DoRepaint bool) {
	baseVirtualTreeImportAPI().SysCallN(175, m.Instance(), PascalBool(DoRepaint))
}

func (m *TBaseVirtualTree) UpdateVerticalRange() {
	baseVirtualTreeImportAPI().SysCallN(176, m.Instance())
}

func (m *TBaseVirtualTree) UpdateVerticalScrollBar(DoRepaint bool) {
	baseVirtualTreeImportAPI().SysCallN(177, m.Instance(), PascalBool(DoRepaint))
}

func (m *TBaseVirtualTree) ValidateChildren(Node IVirtualNode, Recursive bool) {
	baseVirtualTreeImportAPI().SysCallN(178, m.Instance(), GetObjectUintptr(Node), PascalBool(Recursive))
}

func (m *TBaseVirtualTree) ValidateNode(Node IVirtualNode, Recursive bool) {
	baseVirtualTreeImportAPI().SysCallN(179, m.Instance(), GetObjectUintptr(Node), PascalBool(Recursive))
}

var (
	baseVirtualTreeImport       *imports.Imports = nil
	baseVirtualTreeImportTables                  = []*imports.Table{
		/*0*/ imports.NewTable("BaseVirtualTree_AbsoluteIndex", 0),
		/*1*/ imports.NewTable("BaseVirtualTree_AddChild", 0),
		/*2*/ imports.NewTable("BaseVirtualTree_AddFromStream", 0),
		/*3*/ imports.NewTable("BaseVirtualTree_BeginSynch", 0),
		/*4*/ imports.NewTable("BaseVirtualTree_BeginUpdate", 0),
		/*5*/ imports.NewTable("BaseVirtualTree_BottomNode", 0),
		/*6*/ imports.NewTable("BaseVirtualTree_CanEdit", 0),
		/*7*/ imports.NewTable("BaseVirtualTree_CancelCutOrCopy", 0),
		/*8*/ imports.NewTable("BaseVirtualTree_CancelEditNode", 0),
		/*9*/ imports.NewTable("BaseVirtualTree_CancelOperation", 0),
		/*10*/ imports.NewTable("BaseVirtualTree_CheckImages", 0),
		/*11*/ imports.NewTable("BaseVirtualTree_CheckState", 0),
		/*12*/ imports.NewTable("BaseVirtualTree_CheckType", 0),
		/*13*/ imports.NewTable("BaseVirtualTree_CheckedCount", 0),
		/*14*/ imports.NewTable("BaseVirtualTree_CheckedNodes", 0),
		/*15*/ imports.NewTable("BaseVirtualTree_ChildCount", 0),
		/*16*/ imports.NewTable("BaseVirtualTree_ChildNodes", 0),
		/*17*/ imports.NewTable("BaseVirtualTree_ChildrenInitialized", 0),
		/*18*/ imports.NewTable("BaseVirtualTree_Class", 0),
		/*19*/ imports.NewTable("BaseVirtualTree_Clear", 0),
		/*20*/ imports.NewTable("BaseVirtualTree_ClearChecked", 0),
		/*21*/ imports.NewTable("BaseVirtualTree_ClearSelection", 0),
		/*22*/ imports.NewTable("BaseVirtualTree_CopyTo", 0),
		/*23*/ i


eofday",
		"Setuid",
		"Setxattr",
		"Shutdown",
		"SidTypeAlias",
		"SidTypeComputer",
		"SidTypeDeletedAccount",
		"SidTypeDomain",
		"SidTypeGroup",
		"SidTypeInvalid",
		"SidTypeLabel",
		"SidTypeUnknown",
		"SidTypeUser",
		"SidTypeWellKnownGroup",
		"Signal",
		"SizeofBpfHdr",
		"SizeofBpfInsn",
		"SizeofBpfProgram",
		"SizeofBpfStat",
		"SizeofBpfVersion",
		"SizeofBpfZbuf",
		"SizeofBpfZbufHeader",
		"SizeofCmsghdr",
		"SizeofICMPv6Filter",
		"SizeofIPMreq",
		"SizeofIPMreqn",
		"SizeofIPv6MTUInfo",
		"SizeofIPv6Mreq",
		"SizeofIfAddrmsg",
		"SizeofIfAnnounceMsghdr",
		"SizeofIfData",
		"SizeofIfInfomsg",
		"SizeofIfMsghdr",
		"SizeofIfaMsghdr",
		"SizeofIfmaMsghdr",
		"SizeofIfmaMsghdr2",
		"SizeofInet4Pktinfo",
		"SizeofInet6Pktinfo",
		"SizeofInotifyEvent",
		"SizeofLinger",
		"SizeofMsghdr",
		"SizeofNlAttr",
		"SizeofNlMsgerr",
		"SizeofNlMsghdr",
		"SizeofRtAttr",
		"SizeofRtGenmsg",
		"SizeofRtMetrics",
		"SizeofRtMsg",
		"SizeofRtMsghdr",
		"SizeofRtNexthop",
		"SizeofSockFilter",
		"SizeofSockFprog",
		"SizeofSockaddrAny",
		"SizeofSockaddrDatalink",
		"SizeofSockaddrInet4",
		"SizeofSockaddrInet6",
		"SizeofSockaddrLinklayer",
		"SizeofSockaddrNetlink",
		"SizeofSockaddrUnix",
		"SizeofTCPInfo",
		"SizeofUcred",
		"SlicePtrFromStrings",
		"SockFilter",
		"SockFprog",
		"Sockaddr",
		"SockaddrDatalink",
		"SockaddrGen",
		"SockaddrInet4",
		"SockaddrInet6",
		"SockaddrLinklayer",
		"SockaddrNetlink",
		"SockaddrUnix",
		"Socket",
		"SocketControlMessage",
		"SocketDisableIPv6",
		"Socketpair",
		"Splice",
		"StartProcess",
		"StartupInfo",
		"Stat",
		"Stat_t",
		"Statfs",
		"Statfs_t",
		"Stderr",
		"Stdin",
		"Stdout",
		"StringBytePtr",
		"StringByteSlice",
		"StringSlicePtr",
		"StringToSid",
		"StringToUTF16",
		"StringToUTF16Ptr",
		"Symlink",
		"Sync",
		"SyncFileRange",
		"SysProcAttr",
		"SysProcIDMap",
		"Syscall",
		"Syscall12",
		"Syscall15",
		"Syscall18",
		"Syscall6",
		"Syscall9",
		"Sysctl",
		"SysctlUint32",
		"Sysctlnode",
		"Sysinfo",
		"Sysinfo_t",
		"Systemtime",
		"TCGETS",
		"TCIFLUSH",
		"TCIOFLUSH",
		"TCOFLUSH",
		"TCPInfo",
		"TCPKeepalive",
		"TCP_CA_NAME_MAX",
		"TCP_CONGCTL",


 = new createjs.Sprite(managers.Assets.atlas, "upperPipe");
            this.lowerImage = new createjs.Sprite(managers.Assets.atlas, "lowerPipe");
            this.width = this.upperImage.getBounds().width;
            this.height = this.upperImage.getBounds().height;
            this.upperImage.regX = this.width / 2;
            this.upperImage.regY = this.height / 2;
            this.lowerImage.regX = this.width / 2;
            this.lowerImage.regY = this.height / 2;

            this.reset();

            game.addChild(this.upperImage);
            game.addChild(this.lowerImage);
        }

        update() {
            this.upperImage.x -= this.dx;
            this.lowerImage.x -= this.dx;

            if (this.upperImage.x < (0 - this.width) && this.lowerImage.x < (0 - this.width)) {
                this.reset();
            }
        }

        reset() {
            var upperY: number = Math.floor((Math.random() * (this.stage.canvas.height - 200)) + 300);

            switch(gameMode)
            {
                case 1:
                    var lowerY: number = upperY + constants.EASY_GAP;
                    this.upperImage.y = upperY - this.upperImage.getBounds().height;
                    this.lowerImage.y = lowerY;
                    break;
                case 2:
                    var lowerY: number = upperY + constants.MEDIUM_GAP;
                    this.upperImage.y = upperY - this.upperImage.getBounds().height;
                    this.lowerImage.y = lowerY;
                    break;
                case 3:
                    var lowerY: number = upperY + constants.HARD_GAP;
                    this.upperImage.y = upperY - this.upperImage.getBounds().height;
                    this.lowerImage.y = lowerY;
                    break;
            }

            this.upperImage.x = (this.stage.canvas.width + this.width);
            this.lowerImage.x = (this.stage.canvas.width + this.width);

            this.dx = 5;
        }

        destroy() {
            game.removeChild(this.upperImage);
            game.removeChild(this.lowerImage);
        }
    }

}import envConfig from "../config"
import { EUROPEAN_UNION } from "utils/eu-list";
import { TCommissionRateParams, TCustomerInfo } from "types/commission-rate";
import { get } from "utils/request";
import { logger } from "config/logger";

const dateInLastWeekOfMonth = (dateString: string) => {
    const date = dateString.substring(0, 10)
    const [year, month, day] = date.split("-")

    // The Unary plus (+) operator converts its operand to a number
    const dateObject = new Date(+year, +month, 0);
    const daysDifference = dateObject.getDate() - (+day)
    return daysDifference <= 7 ? true : false
}

const updateCommissionRate = (oldRate: number, newRate: number) => {
    return `${oldRate + newRate}`
}

export function getCustomerInfoBySaleId(saleId: number): Promise<TCustomerInfo>{
    const url = envConfig.JETTI_SALES_URL
    return get(`${url}/${saleId}.json`)
}

export async function getRateBasedOnLocation(commissionRateParams: TCommissionRateParams){
    let { saleItem, commissionRate } = commissionRateParams;
    const { saleId } = saleItem

    const { billingCountry, dateOrdered } = await getCustomerInfoBySaleId(saleId)

    if (billingCountry.toLowerCase() in EUROPEAN_UNION) {
        logger.info("Customer country in EU")
        commissionRate = updateCommissionRate


PROX(m1.cwise().abs().cwise().log().cwise().exp() , m1.cwise().abs());

    VERIFY_IS_APPROX(m1.cwise().pow(2), m1.cwise().square());
    m3 = (m1.cwise().abs().cwise()<=RealScalar(0.01)).select(mones,m1);
    VERIFY_IS_APPROX(m3.cwise().pow(-1), m3.cwise().inverse());
    m3 = m1.cwise().abs();
    VERIFY_IS_APPROX(m3.cwise().pow(RealScalar(0.5)), m3.cwise().sqrt());

//     VERIFY_IS_APPROX(m1.cwise().tan(), m1.cwise().sin().cwise() / m1.cwise().cos());
    VERIFY_IS_APPROX(mones, m1.cwise().sin().cwise().square() + m1.cwise().cos().cwise().square());
    m3 = m1;
    m3.cwise() /= m2;
    VERIFY_IS_APPROX(m3, m1.cwise() / m2);
  }

  // check min
  VERIFY_IS_APPROX( m1.cwise().min(m2), m2.cwise().min(m1) );
  VERIFY_IS_APPROX( m1.cwise().min(m1+mones), m1 );
  VERIFY_IS_APPROX( m1.cwise().min(m1-mones), m1-mones );

  // check max
  VERIFY_IS_APPROX( m1.cwise().max(m2), m2.cwise().max(m1) );
  VERIFY_IS_APPROX( m1.cwise().max(m1-mones), m1 );
  VERIFY_IS_APPROX( m1.cwise().max(m1+mones), m1+mones );

  VERIFY( (m1.cwise() == m1).all() );
  VERIFY( (m1.cwise() != m2).any() );
  VERIFY(!(m1.cwise() == (m1+mones)).any() );
  if (rows*cols>1)
  {
    m3 = m1;
    m3(r,c) += 1;
    VERIFY( (m1.cwise() == m3).any() );
    VERIFY( !(m1.cwise() == m3).all() );
  }
  VERIFY( (m1.cwise().min(m2).cwise() <= m2).all() );
  VERIFY( (m1.cwise().max(m2).cwise() >= m2).all() );
  VERIFY( (m1.cwise().min(m2).cwise() < (m1+mones)).all() );
  VERIFY( (m1.cwise().max(m2).cwise() > (m1-mones)).all() );

  VERIFY( (m1.cwise()<m1.unaryExpr(bind2nd(plus<Scalar>(), Scalar(1)))).all() );
  VERIFY( !(m1.cwise()<m1.unaryExpr(bind2nd(minus<Scalar>(), Scalar(1)))).all() );
  VERIFY( !(m1.cwise()>m1.unaryExpr(bind2nd(plus<Scalar>(), Scalar(1)))).any() );
}

void test_eigen2_cwiseop()
{
  for(int i = 0; i < g_repeat ; i++) {
    CALL_SUBTEST_1( cwiseops(Matrix<float, 1, 1>()) );
    CALL_SUBTEST_2( cwiseops(Matrix4d()) );
    CALL_SUBTEST_3( cwiseops(MatrixXf(3, 3)) );
    CALL_SUBTEST_3( cwiseops(MatrixXf(22, 22)) );
    CALL_SUBTEST_4( cwiseops(MatrixXi(8, 12)) );
    CALL_SUBTEST_5( cwiseops(MatrixXd(20, 20)) );
  }
}
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2010 Manuel Yguel <manuel.yguel@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed


            log(TAG) { "Map: now=$now, lastProStateAt=$lastProStateAt, data=${data}" }

            when {
                data?.purchases?.isNotEmpty() == true -> {
                    // If we are pro refresh timestamp
                    billingCache.lastProStateAt.value(now)
                    Info(billingData = data)
                }

                (now - lastProStateAt) < 7 * 24 * 60 * 1000L -> { // 7 days
                    log(TAG, VERBOSE) { "We are not pro, but were recently, did GPlay try annoy us again?" }
                    Info(gracePeriod = true, billingData = null)
                }

                else -> {
                    Info(billingData = data)
                }
            }
        }
        .distinctUntilChanged()
        .retryWhen { error, attempt ->
            // Ignore Google Play errors if the last pro state was recent
            val now = System.currentTimeMillis()
            val lastProStateAt = billingCache.lastProStateAt.value()
            log(TAG) { "Catch: now=$now, lastProStateAt=$lastProStateAt, attempt=$attempt, error=$error" }
            if ((now - lastProStateAt) < 7 * 24 * 60 * 1000L) { // 7 days
                log(TAG, VERBOSE) { "We are not pro, but were recently, and just and an error, what is GPlay doing???" }
                emit(Info(gracePeriod = true, billingData = null))
            } else {
                emit(Info(error = error, billingData = null))
            }
            delay(30_000L * 2.0.pow(attempt.toDouble()).toLong())
            true
        }
        .setupCommonEventHandlers(TAG) { "upgradeInfo2" }
        .shareIn(scope, SharingStarted.WhileSubscribed(3000L, 0L), replay = 1)

    suspend fun launchBillingFlow(activity: Activity, sku: Sku, offer: Sku.Subscription.Offer?) {
        log(TAG) { "launchBillingFlow($activity,$sku)" }
        val resultChannel = Channel<Result<Unit>>()

        scope.launch {
            try {
                billingManager.startIapFlow(activity, sku, offer)
                resultChannel.send(Result.success(Unit))
            } catch (e: Exception) {
                log(TAG) { "startIapFlow failed:${e.asLog()}" }
                resultChannel.send(Result.failure(e))
            }
        }

        val result = resultChannel.receive()
        result.getOrThrow()
    }

    suspend fun querySkus(vararg skus: Sku): Collection<SkuDetails> = billingManager.querySkus(*skus)

    override suspend fun refresh() {
        log(TAG) { "refresh()" }
        billingManager.refresh()
    }

    data class Info(
        private val gracePeriod: Boolean = false,
        private val billingData: BillingData?,
        override val error: Throwable? = null,
    ) : UpgradeRepo.Info {

        override val type: UpgradeRepo.Type = UpgradeRepo.Type.GPLAY

        val upgrades: Collection<PurchasedSku> = billingData?.purchases
            ?.map { purchase ->
                purchase.products.mapNotNull { productId ->
                    val sku = OurSku.PRO_SKUS.singleOrNull { it.id == productId }
                    if (sku == null) {
                        log(TAG, ERROR) { "Unknown product: $productId ($purchase)" }
                        return@mapNotNull null
                    } else {
                        log(TAG) { "Mapped $productId to $sku ($purchase)" }
                    }
                    PurchasedSku(sku, purchase)
                }
            }
            ?.flatten()
            ?: emptySet()

        override val isUpgraded: Boolean = upgrades.isNotEmpty() || gracePeriod

        override val upgradedAt: Ins


strong>(...)

<tt>D.itervalues() -> an iterator over the values of D</tt>

keys(...)

<tt>D.keys() -> list of D's keys</tt>

pop(...)

<tt>D.pop(k[,d]) -> v, remove specified key and return the corresponding value

If key is not found, d is returned if given, otherwise KeyError is raised</tt>

popitem(...)

<tt>D.popitem() -> (k, v), remove and return some (key, value) pair as a

2-tuple; but raise KeyError if D is empty</tt>

setdefault(...)

<tt>D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D</tt>

update(...)

<tt>D.update(E, **F) -> None.  Update D from E and F: for k in E: D[k] = E[k]

(if E has keys else: for (k, v) in E: D[k] = v) then: for k in F: D[k] = F[k]</tt>

values(...)

<tt>D.values() -> list of D's values</tt>

Data and other attributes inherited from __builtin__.dict:

__hash__ = None

__new__ = <built-in method __new__ of type object at 0x7569a0>
<tt>T.__new__(S, ...


ServerData();
            Snackbar.Add($"{ConstantString.ImportSuccess}", Severity.Info);
        }
        else
        {
            foreach (var msg in result.Errors)
            {
                Snackbar.Add($"{msg}", Severity.Error);
            }
        }
        _uploading = false;
    }

    private async Task ShowProductEditFormDialog(string title, AddEditProductCommand command)
    {
        var parameters = new DialogParameters<ProductFormDialog>
        {
            { x => x.Refresh, () => _productsGrid.ReloadServerData() },
            { x => x._model, command }
        };
        var options = new DialogOptions { CloseButton = true, MaxWidth = MaxWidth.Medium, FullWidth = true };
        var dialog = await DialogService.ShowAsync<ProductFormDialog>(title, parameters, options);
        var state = await dialog.Result;
        if (state is not null && !state.Canceled)
        {
            await _productsGrid.ReloadServerData();
            _selectedItems.Clear();
        }
    }
}
```

### 6.2 Component Guidelines
- **Size Limit**: Keep components under 300 lines. Split larger components into smaller ones
- **State Management**: Use `@bind` for two-way data binding
- **Error Handling**: Always wrap async operations in try-catch blocks
- **Loading States**: Show loading indicators for async operations
- **Accessibility**: Include proper ARIA labels and keyboard navigation
- **Responsive Design**: Use MudBlazor's grid system for responsive layouts
- **MudBlazor Standards**: Always use standard MudBlazor components without custom CSS styling. Maintain consistency and simplicity by leveraging built-in component properties, themes, and variants instead of adding custom styles

### 6.3 MudBlazor Usage Examples

```razor
<!-- ✅ Good: Keep components simple, use MudGlobal for defaults -->
<MudButton StartIcon="Icons.Material.Filled.Add">
    Add Product
</MudButton>

<MudTextField T="string"
              Label="Product Name"
              @bind-Value="ProductName"
              For="@(() => ProductName)" />

<MudDataGrid Items="@products"
             Filterable="true"
             SortMode="SortMode.Multiple">
    <Columns>
        <PropertyColumn Property="x => x.Name" Title="Name" />
        <PropertyColumn Property="x => x.Price" Title="Price" Format="C" />
    </Columns>
</MudDataGrid>

<!-- ❌ Bad: Don't add custom styles -->
<MudButton style="background-color: red; padding: 20px;">
    Custom Styled Button
</MudButton>

<div class="my-custom-grid-wrapper">
    <MudDataGrid class="custom-grid-style" Items="@products">
        <!-- Custom CSS defeats MudBlazor's theming -->
    </MudDataGrid>
</div>

<!-- ✅ Good: Use MudBlazor spacing classes when needed -->
<MudButton Color="Color.Error" Class="ma-2">
    Delete
</MudButton>

<MudPaper Class="pa-4 ma-2">
    <MudText Typo="Typo.h6">Product Details</MudText>
    <MudDivider Class="my-2" />
    <MudText>Content goes here</MudText>
</MudPaper>
```

---

## 7  Advanced Caching Strategy

### 7.1 Cache Key Patterns
```csharp
// Entity-based caching
public static class CacheKeys
{
    public static string Product(int id) => $"product:{id}";
    public static string ProductList(string filter = "") => $"products:list:{filter.GetHashCode()}";
    public static string UserProfile(Guid userId) => $"user:profile:{userId}";
    public static string UserPermissions(Guid userId) => $"user:permissions:{userId}";
}

// Cache invalidation
public class ProductCreatedEventHandler : INotificationHandler<ProductCreatedEvent>
{
    private readonly IFusionCache _cache;

    public ProductCreatedEventHandler(IFusionCache cache)
    {
        _cache = cache;
    }

    public async Task Handle(ProductCreatedEvent notifi


EXTRACT_OWNER			(0x0001)
/* Default: Do obey umask, do not restore SUID/SGID/SVTX bits. */
#define	ARCHIVE_EXTRACT_PERM			(0x0002)
/* Default: Do not restore mtime/atime. */
#define	ARCHIVE_EXTRACT_TIME			(0x0004)
/* Default: Replace existing files. */
#define	ARCHIVE_EXTRACT_NO_OVERWRITE 		(0x0008)
/* Default: Try create first, unlink only if create fails with EEXIST. */
#define	ARCHIVE_EXTRACT_UNLINK			(0x0010)
/* Default: Do not restore ACLs. */
#define	ARCHIVE_EXTRACT_ACL			(0x0020)
/* Default: Do not restore fflags. */
#define	ARCHIVE_EXTRACT_FFLAGS			(0x0040)
/* Default: Do not restore xattrs. */
#define	ARCHIVE_EXTRACT_XATTR 			(0x0080)
/* Default: Do not try to guard against extracts redirected by symlinks. */
/* Note: With ARCHIVE_EXTRACT_UNLINK, will remove any intermediate symlink. */
#define	ARCHIVE_EXTRACT_SECURE_SYMLINKS		(0x0100)
/* Default: Do not reject entries with '..' as path elements. */
#define	ARCHIVE_EXTRACT_SECURE_NODOTDOT		(0x0200)
/* Default: Create parent directories as needed. */
#define	ARCHIVE_EXTRACT_NO_AUTODIR		(0x0400)
/* Default: Overwrite files, even if one on disk is newer. */
#define	ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER	(0x0800)
/* Detect blocks of 0 and write holes instead. */
#define	ARCHIVE_EXTRACT_SPARSE			(0x1000)
/* Default: Do not restore Mac extended metadata. */
/* This has no effect except on Mac OS. */
#define	ARCHIVE_EXTRACT_MAC_METADATA		(0x2000)
/* Default: Use HFS+ compression if it was compressed. */
/* This has no effect except on Mac OS v10.6 or later. */
#define	ARCHIVE_EXTRACT_NO_HFS_COMPRESSION	(0x4000)
/* Default: Do not use HFS+ compression if it was not compressed. */
/* This has no effect except on Mac OS v10.6 or later. */
#define	ARCHIVE_EXTRACT_HFS_COMPRESSION_FORCED	(0x8000)
/* Default: Do not reject entries with absolute paths */
#define ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS (0x10000)
/* Default: Do not clear no-change flags when unlinking object */
#define	ARCHIVE_EXTRACT_CLEAR_NOCHANGE_FFLAGS	(0x20000)
/* Default: Do not extract atomically (using rename) */
#define	ARCHIVE_EXTRACT_SAFE_WRITES		(0x40000)

__LA_DECL int archive_read_extract(struct archive *, struct archive_entry *,
		     int flags);
__LA_DECL int archive_read_extract2(struct archive *, struct archive_entry *,
		     struct archive * /* dest */);
__LA_DECL void	 archive_read_extract_set_progress_callback(struct archive *,
		     void (*_progress_func)(void *), void *_user_data);

/* Record the dev/ino of a file that will not be written.  This is
 * generally set to the dev/ino of the archive being read. */
__LA_DECL void		archive_read_extract_set_skip_file(struct archive *,
		     la_int64_t, la_int64_t);

/* Close the file and release most resources. */
__LA_DECL int		 archive_read_close(struct archive *);
/* Release all resources and destroy the object. */
/* Note that archive_read_free will call archive_read_close for you. */
__LA_DECL int		 archive_read_free(struct archive *);
#if ARCHIVE_VERSION_NUMBER < 4000000
/* Synonym for archive_read_free() for backwards compatibilit


// Copyright (C) 2018 go-nebulas authors
//
// This file is part of the go-nebulas library.
//
// the go-nebulas library is free software: you can redistribute it and/or
// modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// the go-nebulas library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with the go-nebulas library.  If not, see
// <http://www.gnu.org/licenses/>.
//
#pragma once
#include "common/byte.h"
#include "common/common.h"

namespace neb {
namespace fs {
enum storage_open_flag {
  storage_open_for_readwrite,
  storage_open_for_readonly,
  storage_open_default = storage_open_for_readonly,
};

struct storage_general_failure : public std::exception {
  inline storage_general_failure(const std::string &msg) : m_msg(msg) {}
  inline const char *what() const throw() { return m_msg.c_str(); }
protected:
  std::string m_msg;
};
struct storage_exception_no_such_key : public std::exception {
  inline const char *what() const throw() { return "no such key in storage"; }
};
struct storage_exception_no_init : public std::exception {
  inline const char *what() const throw() { return "storage no initialized"; }
};

class storage {
public:
  template <typename T, typename KT>
  auto get(const KT &key) -> typename std::enable_if<
      std::is_arithmetic<T>::value && std::is_arithmetic<KT>::value, T>::type {
    return byte_to_number<T>(get_bytes(number_to_byte<bytes>(key)));
  }

  template <typename T, typename KT>
  auto put(const KT &key, const T &val) ->
      typename std::enable_if<std::is_arithmetic<T>::value &&
                                  std::is_arithmetic<KT>::value,
                              void>::type {
    put_bytes(number_to_byte<bytes>(key), number_to_byte<bytes>(val));
  }
  template <typename KT>
  auto del(const KT &key) ->
      typename std::enable_if<std::is_arithmetic<KT>::value, void>::type {
    del_by_bytes(number_to_byte<bytes>(key));
  }

  bytes get(const std::string &key) { return get_bytes(string_to_byte(key)); }
  void put(const std::string &key, const bytes &value) {
    return put_bytes(string_to_byte(key), value);
  }
  void del(const std::string &key) { del_by_bytes(string_to_byte(key)); }

  virtual bytes get_bytes(const bytes &key) = 0;
  virtual void put_bytes(const bytes &key, const bytes &val) = 0;
  virtual void del_by_bytes(const bytes &key) = 0;

  virtual void enable_batch() = 0;
  virtual void disable_batch() = 0;
  virtual void flush() = 0;
};
}
}


3, 2, 3);
  matplotlibcpp::ylabel("da_2");
  matplotlibcpp::subplot(3, 2, 4);
  matplotlibcpp::ylabel("da_5");
  matplotlibcpp::subplot(3, 2, 5);
  matplotlibcpp::ylabel("da_3");
  matplotlibcpp::xlabel("dataset time (s)");
  matplotlibcpp::subplot(3, 2, 6);
  matplotlibcpp::ylabel("da_6");
  matplotlibcpp::xlabel("dataset time (s)");
  matplotlibcpp::tight_layout();
  matplotlibcpp::show(false);

  //=====================================================
  //=====================================================

  // Plot this figure
  // NOTE: display is row-based not column-based
  matplotlibcpp::figure_size(1400, 500);
  plot_9errors(error_tg[0], error_tg[3], error_tg[6], error_tg[1], error_tg[4], error_tg[7], error_tg[2], error_tg[5], error_tg[8],
               colors.at(0), stdcolor);

  // Update the title and axis labels
  matplotlibcpp::subplot(3, 3, 1);
  matplotlibcpp::title("IMU Tg Error (1:3)");
  matplotlibcpp::ylabel("tg_1");
  matplotlibcpp::subplot(3, 3, 2);
  matplotlibcpp::title("IMU Tg Error (4:6)");
  matplotlibcpp::ylabel("tg_4");
  matplotlibcpp::subplot(3, 3, 3);
  matplotlibcpp::title("IMU Tg Error (7:9)");
  matplotlibcpp::ylabel("tg_7");
  matplotlibcpp::subplot(3, 3, 4);
  matplotlibcpp::ylabel("tg_2");
  matplotlibcpp::subplot(3, 3, 5);
  matplotlibcpp::ylabel("tg_5");
  matplotlibcpp::subplot(3, 3, 6);
  matplotlibcpp::ylabel("tg_8");
  matplotlibcpp::subplot(3, 3, 7);
  matplotlibcpp::ylabel("tg_3");
  matplotlibcpp::xlabel("dataset time (s)");
  matplotlibcpp::subplot(3, 3, 8);
  matplotlibcpp::ylabel("tg_6");
  matplotlibcpp::xlabel("dataset time (s)");
  matplotlibcpp::subplot(3, 3, 9);
  matplotlibcpp::ylabel("tg_9");
  matplotlibcpp::xlabel("dataset time (s)");
  matplotlibcpp::tight_layout();
  matplotlibcpp::show(false);

  //=====================================================
  //=====================================================

  // Finally plot
  if (imu_model == 0) {

    // Kalibr model
    // Plot this figure
    matplotlibcpp::figure_size(800, 500);
    plot_3errors(error_wtoI[0], error_wtoI[1], error_wtoI[2], colors.at(0), stdcolor);

    // Update the title and axis labels
    matplotlibcpp::subplot(3, 1, 1);
    matplotlibcpp::title("IMU R_GYROtoIMU Error");
    matplotlibcpp::ylabel("x-error (deg)");
    matplotlibcpp::subplot(3, 1, 2);
    matplotlibcpp::ylabel("y-error (deg)");
    matplotlibcpp::subplot(3, 1, 3);
    matplotlibcpp::ylabel("z-error (deg)");
    matplotlibcpp::xlabel("dataset time (s)");
    matplotlibcpp::tight_layout();
    matplotlibcpp::show(false);

  } else {

    // RPNG model
    // Plot this figure
    matplotlibcpp::figure_size(800, 500);
    plot_3errors(error_atoI[0], error_atoI[1], error_atoI[2], colors.at(0), stdcolor);

    // Update the title and axis labels
    matplotlibcpp::subplot(3, 1, 1);
    matplotlibcpp::title("IMU R_ACCtoIMU Err


InfoRegionWidth,
            height = seasonInfoRegionHeight,
            scale = textScale,
            lineSpacing = 5,
            alignCenter = false,
            drawShadow = true,
            scrollOffset = seasonScrollOffset
        )
        seasonInfoRenderer.render(context, textRenderer)

        // 渲染排行榜信息文本（支持滚动）
        leaderboardRenderer = FancyMultilineTextRenderer(
            lines = leaderboardLines,
            x = leaderboardRegionX,
            y = leaderboardRegionY,
            width = leaderboardRegionWidth,
            height = leaderboardRegionHeight,
            scale = textScale,
            lineSpacing = 5,
            alignCenter = false,
            drawShadow = true,
            scrollOffset = leaderboardScrollOffset
        )
        leaderboardRenderer.render(context, textRenderer)

        super.render(context, mouseX, mouseY, delta)

        NotificationManager.render(context, client!!.window.scaledWidth, client.window.scaledHeight, textRenderer)

        // 添加右下角制作信息
        val scaleFactor = 0.5f
        val madeByText = Text.literal("By Kurt")
        val textWidth = (textRenderer.getWidth(madeByText) * scaleFactor).toInt()
        val textHeight = (textRenderer.fontHeight * scaleFactor).toInt()
        val madeByX = width - textWidth - (10 * scaleX).toInt() - 2
        val madeByY = height - textHeight - (10 * scaleY).toInt() - 2

        context.matrices.push()
        context.matrices.translate(madeByX.toFloat(), madeByY.toFloat(), 0f)
        context.matrices.scale(scaleFactor, scaleFactor, 1f)
        context.drawText(textRenderer, madeByText, 0, 0, 0xAAAAAA, true)
        context.matrices.pop()
    }

    private fun requestInfo(type: RequestType) {
        val payload = when (type) {
            RequestType.PLAYER -> RequestPlayerRankPayload(type, format = mode)
            RequestType.LEADERBOARD -> RequestPlayerRankPayload(
                type,
                format = mode,
                extra = leaderboardPage.toString() // 发送当前页码
            )
            RequestType.SEASON -> RequestPlayerRankPayload(type, format = mode)
        }
        ClientPlayNetworking.send(payload)
    }

    private fun sendCommand(command: String) {
        val trimmedCommand = command.removePrefix("/")
        client?.player?.networkHandler?.sendChatCommand(trimmedCommand)
    }

    fun getLocalizedText(zh: String, en: String): String {
        return if (lang == "zh_cn") zh else en
    }

    private fun isInRegion(mouseX: Double, mouseY: Double, x: Int, y: Int, width: Int, height: Int): Boolean {
        return mouseX >= x && mouseX <= x + width && mouseY >= y && mouseY <= y + height
    }

    override fun mouseScrolled(
        mouseX: Double,
        mouseY: Double,
        horizontalAmount: Double,
        verticalAmount: Double
    ): Boolean {
        return when {
            isInRegion(
                mouseX,
                mouseY,
                leaderboardRegionX,
                leaderboardRegionY,
                leaderboardRegionWidth,
                leaderboardRegionHeight
            ) -> {
                leaderboardScrollOffset = leaderboardRenderer.handleScrollAndReturnOffset(verticalAmount, textRenderer)
                true
            }

            isInRegion(
                mouseX,
                mouseY,
                playerInfoRegionX,
                playerInfoRegionY,
                playerInfoRegionWidth,
                playerInfoRegionHeight
            ) -> {
                playerScrollOffset = playerInfoRenderer.handleScrollAndReturnOffset(verticalAmount, textRenderer)
                true
            }

            isInRegion(
                mouseX,
                mouseY,
                seasonInfoRegionX,


 buffer reference a given data plane is stored in.
 *
 * @param plane index of the data plane of interest in frame->extended_data.
 *
 * @return the buffer reference that contains the plane or NULL if the input
 * frame is not valid.
 */
AVBufferRef *av_frame_get_plane_buffer(AVFrame *frame, int plane);

/**
 * Add a new side data to a frame.
 *
 * @param frame a frame to which the side data should be added
 * @param type type of the added side data
 * @param size size of the side data
 *
 * @return newly added side data on success, NULL on error
 */
AVFrameSideData *av_frame_new_side_data(AVFrame *frame,
                                        enum AVFrameSideDataType type,
                                        int size);

/**
 * @return a pointer to the side data of a given type on success, NULL if there
 * is no side data with such type in this frame.
 */
AVFrameSideData *av_frame_get_side_data(const AVFrame *frame,
                                        enum AVFrameSideDataType type);

/**
 * If side data of the supplied type exists in the frame, free it and remove it
 * from the frame.
 */
void av_frame_remove_side_data(AVFrame *frame, enum AVFrameSideDataType type);

/**
 * @return a string identifying the side data type
 */
const char *av_frame_side_data_name(enum AVFrameSideDataType type);

/**
 * @}
 */

#endif /* AVUTIL_FRAME_H */


"

	"github.com/VictoriaMetrics/VictoriaMetrics/app/vmselect/netstorage"
	"github.com/VictoriaMetrics/VictoriaMetrics/app/vmselect/searchutils"
	"github.com/VictoriaMetrics/VictoriaMetrics/lib/auth"
	"github.com/VictoriaMetrics/VictoriaMetrics/lib/bytesutil"
	"github.com/VictoriaMetrics/VictoriaMetrics/lib/cgroup"
	"github.com/VictoriaMetrics/VictoriaMetrics/lib/decimal"
	"github.com/VictoriaMetrics/VictoriaMetrics/lib/logger"
	"github.com/VictoriaMetrics/VictoriaMetrics/lib/memory"
	"github.com/VictoriaMetrics/VictoriaMetrics/lib/storage"
)

var (
	disableCache           = flag.Bool("search.disableCache", false, "Whether to disable response caching. This may be useful during data backfilling")
	maxPointsPerTimeseries = flag.Int("search.maxPointsPerTimeseries", 30e3, "The maximum points per a single timeseries returned from /api/v1/query_range. "+
		"This option doesn't limit the number of scanned raw samples in the database. The main purpose of this option is to limit the number of per-series points "+
		"returned to graphing UI such as Grafana. There is no sense in setting this limit to values bigger than the horizontal resolution of the graph")
	noStaleMarkers = flag.Bool("search.noStaleMarkers", false, "Set this flag to true if the database doesn't contain Prometheus stale markers, so there is no need in spending additional CPU time on its handling. Staleness markers may exist only in data obtained from Prometheus scrape targets")
)

// The minimum number of points per timeseries for enabling time rounding.
// This improves cache hit ratio for frequently requested queries over
// big time ranges.
const minTimeseriesPointsForTimeRounding = 50

// ValidateMaxPointsPerTimeseries checks the maximum number of points that
// may be returned per each time series.
//
// The number mustn't exceed -search.maxPointsPerTimeseries.
func ValidateMaxPointsPerTimeseries(start, end, step int64) error {
	points := (end-start)/step + 1
	if uint64(points) > uint64(*maxPointsPerTimeseries) {
		return fmt.Errorf(`too many points for the given step=%d, start=%d and end=%d: %d; cannot exceed -search.maxPointsPerTimeseries=%d`,
			step, start, end, uint64(points), *maxPointsPerTimeseries)
	}
	return nil
}

// AdjustStartEnd adjusts start and end values, so response caching may be enabled.
//
// See EvalConfig.mayCache for details.
func AdjustStartEnd(start, end, step int64) (int64, int64) {
	if *disableCache {
		// Do not adjust start and end values when cache is disabled.
		// See https://github.com/VictoriaMetrics/VictoriaMetrics/issues/563
		return start, end
	}
	points := (end-start)/step + 1
	if points < minTimeseriesPointsForTimeRounding {
		// Too small number of points for rounding.
		return start, end
	}

	// Round start and end to values divisible by step in order
	// to enable response caching (see EvalConfig.mayCache).
	start, end = alignStartEnd(start, end, step)

	// Make sure that the new number of points is the same as the initial number of points.
	newPoints := (end-start)/step + 1
	for newPoints > points {
		end -= step
		newPoints--
	}

	return start, end
}

func alignStartEnd(start, end, step int64) (int64, int64) {
	// Round start to the nearest smalle


return -1;  // 寻找from名的过程发生错误

                    if (strTargetListValue != "")
                        strTargetListValue += ";";

                    Debug.Assert(strOutputDbName != "", "");

                    strTargetListValue += strOutputDbName + ":" + strFrom;
                }

                if (i != 0)
                    strQueryXml += "<operator value='OR' />";

                strQueryXml += "<target list='" + strTargetListValue + "'>"
                + "<item><word>"
                + StringUtil.GetXmlStringSimple(strTerm)
                + "</word><match>left</match><relation>=</relation><dataType>string</dataType>"
                + "<maxCount>" + nMaxResultCount.ToString() + "</maxCount></item>"
                + "<lang>zh</lang></target>";
            }

            // 如果有多个props，则需要在检索XML外面包裹一个<target>元素，以作为一个整体和其他部件进行逻辑操作
            if (prop_groups.Count > 1)
                strQueryXml = "<target>" + strQueryXml + "</target>";

            return 0;
        }

#if NOOOOOOOOOOOOOOOOOOO
        // 构造一个检索词的XML检索式局部
        int BuildOneXml(
            List<string> dbnames,
            string strTerm,
            long lAttritueValue,
            out string strQueryXml,
            out string strError)
        {
            strQueryXml = "";
            strError = "";

            if (dbnames.Count == 0)
            {
                strError = "一个数据库名也未曾指定";
                return -1;
            }

            // string strFrom = "";    // 根据nAttributeType nAttributeValue得到检索途径名

            // 先评估一下，是不是每个数据库都有一样的maxResultCount参数。
            // 如果是，则可以把这些数据库都组合为一个<target>；
            // 如果不是，则把相同的挑选出来成为一个<target>，然后多个<target>用OR组合起来

            // 为此，可以先把数据库属性对象按照maxResultCount参数排序，以便聚合是用<target>。
            // 但是这带来一个问题：最后发生的检索库的先后顺序，就不是用户要求的那个顺序了。
            // 看来，还得按照用户指定的数据库顺序来构造<item>。那么，就不得不降低聚合的可能，
            // 而仅仅聚合相邻的、maxResultCount值相同的那些

            int nPrevMaxResultCount = -1;   // 前一个MaxResultCount参数值
            List<List<BiblioDbProperty>> prop_groups = new List<List<BiblioDbProperty>>();

            List<BiblioDbProperty> props = new List<BiblioDbProperty>();
            for (int i = 0; i < dbnames.Count; i++)
            {
                string strDbName = dbnames[i];

                BiblioDbProperty prop = this.m_service.GetDbProperty(strDbName);
                if (prop == null)
                {
                    strError = "数据库 '" + strDbName + "' 不存在";
                    return -1;
                }

                // 如果当前库的MaxResultCount参数和前面紧邻的不一样了，则需要推入当前正在使用的props，新起一个props
                if (prop.MaxResultCount != nPrevMaxResultCount
                    && props.Count != 0)
                {
                    Debug.Assert(props.Count > 0, "不为空的props才能推入 (1)");
                    prop_groups.Add(props);
                    props = new List<BiblioDbProperty>();   // 新增加一个props
                }

                props.Add(prop);
            }

            Debug.Assert(props.Count > 0, "不为空的props才能推入 (2)");
            prop_groups.Add(props); // 将最后一个props加入到group数组中

            for (int i = 0; i < prop_groups.Count; i++)
            {


atrix C
    ldrd r32,[r2,#0]
    ldrd r34,[r2,#1]
    ldrd r36,[r2,#2]
    ldrd r38,[r2,#3]
    ldrd r40,[r2,#4]
    ldrd r42,[r2,#5]
    ldrd r44,[r2,#6]
    ldrd r46,[r2,#7]
    ldrd r48,[r2,#8]
    ldrd r50,[r2,#9]
    ldrd r52,[r2,#10]
    ldrd r54,[r2,#11]
    ldrd r56,[r2,#12]
    ldrd r58,[r2,#13]
    ldrd r60,[r2,#14]
    ldrd r62,[r2,#15]

    ;Matrix C - Setting values of intermediate C to 0
    ;Commented to accomodate multicore version
    ;mov r32,#0
    ;mov r33,#0
    ;mov r34,#0
    ;mov r35,#0
    ;mov r36,#0
    ;mov r37,#0
    ;mov r38,#0
    ;mov r39,#0
    ;mov r40,#0
    ;mov r41,#0
    ;mov r42,#0
    ;mov r43,#0
    ;mov r44,#0
    ;mov r45,#0
    ;mov r46,#0
    ;mov r47,#0
    ;mov r48,#0
    ;mov r49,#0
    ;mov r50,#0
    ;mov r51,#0
    ;mov r52,#0
    ;mov r53,#0
    ;mov r54,#0
    ;mov r55,#0
    ;mov r56,#0
    ;mov r57,#0
    ;mov r58,#0
    ;mov r59,#0
    ;mov r60,#0
    ;mov r61,#0
    ;mov r62,#0
    ;mov r63,#0

.Lb:
    ;Start accumulating
    ;Move r0 to point to next row of Matrix A
    ;add r0,r0,#stride
    ;ldr r15,[r0,#3]
    doMult 11,0,15,3
    ;Start loading next row of Matrix A into r11,r12... for the next iteration
    ;ldr r11,[r0,#4]
    doMult 12,1 * stride/2,11,4
    ;ldr r12,[r0,#5]
    doMult 14,2 * stride/2,12,5
    ;ldr r14,[r0,#6]
    doMult 15,3 * stride/2,14,6
    ;ldr r15,[r0,#7]
    doMult 11,4 * stride/2,15,7
    ;ldr r11,[r0,#8]
    doMult 12,5 * stride/2,11,8
    ;ldr r12,[r0,#9]
    doMult 14,6 * stride/2,12,9
    ;ldr r14,[r0,#10]
    doMult 15,7 * stride/2,14,10
    ;ldr r15,[r0,#11]
    doMult 11,8 * stride/2,15,11
    ;ldr r11,[r0,#12]
    doMult 12,9 * stride/2,11,12
    ;ldr r12,[r0,#13]
    doMult 14,10 * stride/2,12,13
    ;ldr r14,[r0,#14]
    doMult 15,11 * stride/2,14,14
    ;ldr r15,[r0,#15]
    doMult 11,12 * stride/2,15,15
    ;ldr r11,[r0,#16]
    doMult 12,13 * stride/2,11,16
    ;ldr r12,[r0,#17]
    doMult 14,14 * stride/2,12,17
    ;ldr r14,[r0,#18]
    doMult 15,15 * stride/2,14,18


: u32) -> CBOptionalString {
  unsafe { (*Core).readCachedString.unwrap()(id) }
}

pub fn writeCachedString1(id: u32, string: &'static str) -> CBOptionalString {
  unsafe { (*Core).writeCachedString.unwrap()(id, string.as_ptr() as *const std::os::raw::c_char) }
}

pub fn deriveType(var: &Var, data: &InstanceData) -> DerivedType {
  let t = unsafe { (*Core).deriveTypeInfo.unwrap()(var as *const _, data as *const _) };
  DerivedType(t)
}

macro_rules! cbccstr {
  ($string:literal) => {
    if cfg!(debug_assertions) {
      crate::core::writeCachedString1(compile_time_crc32::crc32!($string), cstr!($string))
    } else {
      crate::core::readCachedString1(compile_time_crc32::crc32!($string))
    }
  };
}

pub fn referenceMutVariable(context: &CBContext, name: CBString) -> &mut CBVar {
  unsafe {
    let ctx = context as *const CBContext as *mut CBContext;
    let cbptr = (*Core).referenceVariable.unwrap()(ctx, name);
    cbptr.as_mut().unwrap()
  }
}

pub fn referenceVariable(context: &CBContext, name: CBString) -> &CBVar {
  unsafe {
    let ctx = context as *const CBContext as *mut CBContext;
    let cbptr = (*Core).referenceVariable.unwrap()(ctx, name);
    cbptr.as_mut().unwrap()
  }
}

pub fn releaseMutVariable(var: &mut CBVar) {
  unsafe {
    let v = var as *mut CBVar;
    (*Core).releaseVariable.unwrap()(v);
  }
}

pub fn releaseVariable(var: &CBVar) {
  unsafe {
    let v = var as *const CBVar as *mut CBVar;
    (*Core).releaseVariable.unwrap()(v);
  }
}

//--------------------------------------------------------------------------------------------------

unsafe extern "C" fn do_blocking_c_call(context: *mut CBContext, arg2: *mut c_void) -> CBVar {
  let trait_obj_ref: &mut &mut dyn FnMut() -> Result<CBVar, &'static str> =
    { &mut *(arg2 as *mut _) };
  match trait_obj_ref() {
    Ok(value) => value,
    Err(error) => {
      cblog_debug!("do_blocking failure detected"); // in case error leads to crash
      cblog_debug!("do_blocking failure: {}", error);
      abortChain(&(*context), error);
      Var::default()
    }
  }
}

pub fn do_blocking<F>(context: &CBContext, f: F) -> CBVar
where
  F: FnMut() -> Result<CBVar, &'static str>,
{
  unsafe {
    let ctx = context as *const CBContext as *mut CBContext;
    let mut trait_obj: &dyn FnMut() -> Result<CBVar, &'static str> = &f;
    let trait_obj_ref = &mut trait_obj;
    let closure_pointer_pointer = trait_obj_ref as *mut _ as *mut c_void;
    (*Core).asyncActivate.unwrap()(ctx, closure_pointer_pointer, Some(do_blocking_c_call), None)
  }
}

//--------------------------------------------------------------------------------------------------

pub trait BlockingBlock {
  fn activate_blocking(&mut self, context: &Context, input: &Var) -> Result<Var, &str>;
  fn cancel_activation(&mut self, _context: &Context) {}
}

struct AsyncCallData<T: BlockingBlock> {
  caller: *mut T,
  input: *const CBVar,
}

unsafe extern "C"


�ର୍ଥ ହେବେ ନାହିଁ |",
  "thisAccountIsClosed": "ଏହି ଖାତା ବନ୍ଦ ଅଛି",
  "search": "ସନ୍ଧାନ କର",
  "advancedSearch": "ଉନ୍ନତ ସନ୍ଧାନ",
  "opponentName": "ବିରୋଧୀ ନାମ",
  "loser": "ପରାଜିତ",
  "from": "ଠାରୁ",
  "to": "କୁ",
  "humanOrComputer": "ଖେଳାଳିଙ୍କ ପ୍ରତିଦ୍ୱନ୍ଦ୍ୱୀ ମଣିଷ କି କମ୍ପ୍ୟୁଟର ଥିଲେ",
  "aiLevel": "A.I. ସ୍ତର",
  "source": "ଉତ୍ସ",
  "nbTurns": "ଟର୍ନର ସଂଖ୍ୟା",
  "result": "ଫଳାଫଳ",
  "winnerColor": "ବିଜେତା ରଙ୍ଗ",
  "date": "ତାରିଖ",
  "sortBy": "ଦ୍ୱାରା ସର୍ଟ କରନ୍ତୁ",
  "onlyAnalysed": "କେବଳ ଖେଳ ଗୁଡିକ ଜାହାର ଏକ କମ୍ପ୍ୟୁଟର ବିଶ୍ଳେଷଣ ଉପଲବ୍ଧ",
  "color": "ରଙ୍ଗ",
  "xGamesFound:one": "ଖେଳ ଟିଏ ମିଳିଲା",
  "xGamesFound:other": "%s ଖେଳଗୁଡିକ ମିଳିଲା",
  "team": "Team",
  "teams": "ଦଳଗୁଡ଼ିକ",
  "allTeams": "ସମସ୍ତ ଦଳ",
  "newTeam": "ନୂତନ ଦଳ",
  "myTeams": "ମୋର ଦଳଗୁଡିକ",
  "noTeamFound": "କୋଣସି ଦଳ ମିଳିଲା ନାହିଁ",
  "joinTeam": "ଦଳରେ ଯୋଗ ଦିଅନ୍ତୁ"


(userService, 'findOneByEmail')
      .mockRejectedValueOnce(new NotFoundException());

    expect(
      await service.validateUser(mockUser.email, 'supersecret'),
    ).toBeNull();
  });

  it("#validateUser should return null if passwords don't match", async () => {
    jest.spyOn(bcrypt, 'compare').mockImplementationOnce(() => false);
    jest
      .spyOn(userService, 'findOneByEmail')
      .mockImplementationOnce(async () => mockUser);

    expect(
      await service.validateUser(mockUser.email, 'supersecret'),
    ).toBeNull();
  });

  it('#login should generate a token for the user', async () => {
    jest
      .spyOn(jwtService, 'signAsync')
      .mockImplementationOnce(async () => 'signed.token');
    const mockReqUser = {
      id: mockUser.id,
      email: mockUser.email,
      admin: mockUser.role === 'administrator',
      name: mockUser.name,
    };
    expect(await service.login(mockReqUser)).toEqual({
      token: 'signed.token',
    });
    expect(jwtService.signAsync).toHaveBeenCalledWith({
      sub: mockUser.id,
      name: mockUser.name,
      email: mockUser.email,
      admin: false,
    });
  });
});
import { Resolver, Query, Arg } from 'type-graphql';
import { Country } from '../entities/Country';

@Resolver()
export class CountryResolver {
    @Query(()=> [Country])
    countries(): Promise<Country[]> {
        return Country.find();
    }

    @Query(()=>Country, { nullable: true })
    country(
        @Arg('name') name:string
    ):Promise<Country | undefined>{
        return Country.findOne({where: name = name})
    }

}export default class CityPicker {
  private first: any = []; /* 省，直辖市 */
  private second: any = []; /* 市 */
  private third: any = []; /* 镇 */
  private selectedIndex: any = [0, 0, 0]; /* 默认选中的地区 */
  private checked: any = [0, 0, 0]; /* 已选选项 */
  private picker: any; /* 已选选项 */

  constructor() {
    let selectedIndex = this.selectedIndex;
    let first = this.first;
    let second = this.second;
    let third = this.third;
    let checked = this.checked;

    function creatList(obj, list){
      obj.forEach(function(item, index, arr){
        var temp = {text:item.name,value:index};
        list.push(temp);
      })
    }
    creatList(city, first);

    if (city[selectedIndex[0]].hasOwnProperty('child')) {
      creatList(city[selectedIndex[0]].child, second);
    } else {
      second = [{text: '', value: 0}];
    }

    if (city[selectedIndex[0]].child[selectedIndex[1]].hasOwnProperty('child')) {
      creatList(city[selectedIndex[0]].child[selectedIndex[1]].child, third);
    } else {
      third = [{text: '', value: 0}];
    }

    let picker = new Picker({
      data: [first, second, third],
      selectedIndex: selectedIndex,
      title: '地址选择'
    });

    this.picker = picker;

    picker.on('picker.change', function (index, selectedIndex) {
      if (index === 0){
        firstChange();
      } else if (index === 1) {
        secondChange();
      }

      function firstChange() {
        second = [];
        third = [];
        checked[0] = selectedIndex;
        var firstCity = city[selectedIndex];
        if (firstCity.hasOwnProperty('child')) {
          creatList(firstCity.child, second);


#######################################################
#   global descriptor table (GDT)
##############################################################################

        .p2align 4                      # make GDT 16-byte align

GDT_BASE:

# null descriptor
NULL_SEL          = .-GDT_BASE          # Selector [0x0]
        .short 0             # limit 15:0
        .short 0             # base 15:0
        .byte 0              # base 23:16
        .byte 0              # type
        .byte 0              # limit 19:16, flags
        .byte 0              # base 31:24

# linear data segment descriptor
LINEAR_SEL        = .-GDT_BASE          # Selector [0x8]
        .short 0x0FFFF       # limit 0xFFFFF
        .short 0             # base 0
        .byte 0
        .byte 0x092          # present, ring 0, data, expand-up, writable
        .byte 0x0CF          # page-granular, 32-bit
        .byte 0

# linear code segment descriptor
LINEAR_CODE_SEL   = .-GDT_BASE          # Selector [0x10]
        .short 0x0FFFF       # limit 0xFFFFF
        .short 0             # base 0
        .byte 0
        .byte 0x09A          # present, ring 0, code, expand-up, writable
        .byte 0x0CF          # page-granular, 32-bit
        .byte 0

# system data segment descriptor
SYS_DATA_SEL      = .-GDT_BASE          # Selector [0x18]
        .short 0x0FFFF       # limit 0xFFFFF
        .short 0             # base 0
        .byte 0
        .byte 0x092          # present, ring 0, data, expand-up, writable
        .byte 0x0CF          # page-granular, 32-bit
        .byte 0

# system code segment descriptor
SYS_CODE_SEL      = .-GDT_BASE          # Selector [0x20]
        .short 0x0FFFF       # limit 0xFFFFF
        .short 0             # base 0
        .byte 0
        .byte 0x09A          # present, ring 0, code, expand-up, writable
        .byte 0x0CF          # page-granular, 32-bit
        .byte 0

# spare segment descriptor
SPARE3_SEL        = .-GDT_BASE          # Selector [0x28]
        .short 0
        .short 0
        .byte 0
        .byte 0
        .byte 0
        .byte 0

# system data segment descriptor
SYS_DATA64_SEL      = .-GDT_BASE          # Selector [0x30]
        .short 0x0FFFF      # limit 0xFFFFF
        .short 0            # base 0
        .byte 0
        .byte 0x092         # present, ring 0, data, expand-up, writable
        .byte 0x0CF         # page-granular, 32-bit
        .byte 0

# system code segment descriptor
SYS_CODE64_SEL      = .-GDT_BASE          # Selector [0x38]
        .short 0x0FFFF      # limit 0xFFFFF
        .short 0            # base 0
        .byte 0
        .byte 0x09A         # present, ring 0, code, expand-up, writable
        .byte 0x0AF         # page-granular, 64-bit
        .byte 0

# spare segment descriptor
SPARE4_SEL    = .-


z >z1=int32#15,<x17=stack32#36
# asm 2: lwz >z1=17,<x17=140(1)
lwz 17,140(1)

# qhasm: p01 = 4080 & (y0 <<< 20)
# asm 1: rlwinm >p01=int32#16,<y0=int32#12,20,4080
# asm 2: rlwinm >p01=18,<y0=14,20,4080
rlwinm 18,14,20,4080

# qhasm: z2 = x18
# asm 1: lwz >z2=int32#17,<x18=stack32#37
# asm 2: lwz >z2=19,<x18=144(1)
lwz 19,144(1)

# qhasm: p02 = 4080 & (y0 <<< 28)
# asm 1: rlwinm >p02=int32#18,<y0=int32#12,28,4080
# asm 2: rlwinm >p02=20,<y0=14,28,4080
rlwinm 20,14,28,4080

# qhasm: z3 = x19
# asm 1: lwz >z3=int32#19,<x19=stack32#38
# asm 2: lwz >z3=21,<x19=148(1)
lwz 21,148(1)

# qhasm: p03 = 4080 & (y0 <<< 4)
# asm 1: rlwinm >p03=int32#12,<y0=int32#12,4,4080
# asm 2: rlwinm >p03=14,<y0=14,4,4080
rlwinm 14,14,4,4080

# qhasm: p00 = *(uint32 *) (table0 + p00)
# asm 1: lwzx >p00=int32#14,<table0=int32#6,<p00=int32#14
# asm 2: lwzx >p00=16,<table0=8,<p00=16
lwzx 16,8,16

# qhasm: p10 = 4080 & (y1 <<< 12)
# asm 1: rlwinm >p10=int32#20,<y1=int32#10,12,4080
# asm 2: rlwinm >p10=22,<y1=12,12,4080
rlwinm 22,12,12,4080

# qhasm: p01 = *(uint32 *) (table1 + p01)
# asm 1: lwzx >p01=int32#16,<table1=int32#7,<p01=int32#16
# asm 2: lwzx >p01=18,<table1=9,<p01=18
lwzx 18,9,18

# qhasm: p11 = 4080 & (y1 <<< 20)
# asm 1: rlwinm >p11=int32#21,<y1=int32#10,20,4080
# asm 2: rlwinm >p11=23,<y1=12,20,4080
rlwinm 23,12,20,4080

# qhasm: p02 = *(uint32 *) (table2 + p02)
# asm 1: lwzx >p02=int32#18,<table2=int32#8,<p02=int32#18
# asm 2: lwzx >p02=20,<table2=10,<p02=20
lwzx 20,10,20

# qhasm: p12 = 4080 & (y1 <<< 28)
# asm 1: rlwinm >p12=int32#22,<y1=int32#10,28,4080
# asm 2: rlwinm >p12=24,<y1=12,28


怪念头, 想象",
"phantasies":"(phantasy 的复数) n. 幻想, 怪念头, 想象\\nvt.vi. 幻想, 怪念头, 想象",
"phantasize":"v. 梦想, 幻想",
"phantasm":"n. 幻影, 梦境, 幽灵, 心像, 幻像\\n[医] 幻象",
"phantasma":"n. 幻觉, 幽灵, 幻想, 幻影",
"phantasmagoria":"n. 千变万化的情景, 幻灯的一种, 幻影汇集, 幻觉效应",
"phantasmagorial":"a. 幻影似的, 变幻不定的",
"phantasmagorias":"n. 千变万化的风景, 幻灯的一种( phantasmagoria的复数形式 )",
"phantasmagoric":"a. 幻影似的, 变幻不定的",
"phantasmagorical":"a. 变化无常的；梦幻般的",
"phantasmagorically":"[网络] 幻想",
"phantasmagoricals":"(phantasmagorical 的第三人称 -s形式) adj. 变化无常的；梦幻般的",
"phantasmagory":"n. 千变万化的风景, 幻灯的一种",
"phantasmal":"a. 幻影的, 玄虚的, 幽灵的",
"phantasmata":"n. 幻象，幻影，幽灵( phantasma的名词复数 )",
"phantasmatic":"a. 幻影的, 幽灵的",
"phantasmatology":"[医] 幻象学",
"phantasmatomoria":"童样幻想, 幻想性童样痴呆",
"phantasmic":"a. 幻影的, 玄虚的, 幽灵的\\n[医] 幻象的",
"phantasmography":"[网络] 漫画",
"phantasmology":"[医] 幻象学",
"phantasmoscopia":"[医] 视幻象",
"phantasms":"(phantasm 的复数) n. 幻影, 梦境, 幽灵, 心像, 幻像\\n[医] 幻象",
"phantast":"n. 幻想家, 梦想家",
"phantastic":"a. phantasy的变形",
"phantastic confabulation":"[医] 幻想性虚谈症, 幻想性虚构症",
"phantastical":"a. phantasy的变形",
"phantastran":"[电] 幻形复振器",
"phantastron":"[电] 幻管",
"phantasy":"n. 幻想, 怪念头, 想象\\nvt.vi. 幻想, 怪念头, 想象",
"phantasy life":"[网络] 幻想生活",
"phantasy world":"[网络] 幻想世界",
"phantem channel":"[电] 幻波道",
"phantigrade":"跖行性",
"phantom":"n. 幻影, 虚位, 幽灵, 化身, 令人恐惧的事物, 骇人的想法\\na. 幻觉的, 幻影的, 幽灵的, 虚无飘渺的, 捉摸不定的, 有名无实的",
"phantom aneurysm":"[医] 虚幻性腹主动脉瘤",
"phantom a


icense 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 biz_test

import (
	"context"
	"testing"

	"github.com/chainloop-dev/chainloop/app/controlplane/pkg/biz"
	"github.com/chainloop-dev/chainloop/app/controlplane/pkg/biz/testhelpers"
	backends "github.com/chainloop-dev/chainloop/pkg/blobmanager"
	blobM "github.com/chainloop-dev/chainloop/pkg/blobmanager/mocks"
	"github.com/chainloop-dev/chainloop/pkg/blobmanager/oci"
	creds "github.com/chainloop-dev/chainloop/pkg/credentials/mocks"
	"github.com/google/go-cmp/cmp"
	"github.com/google/go-cmp/cmp/cmpopts"
	"github.com/google/uuid"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/mock"
	"github.com/stretchr/testify/require"
	"github.com/stretchr/testify/suite"
)

const location = "my-location"
const backendType = oci.ProviderID

var description = "my-description"

func (s *CASBackendIntegrationTestSuite) TestUniqueNameDuringCreate() {
	orgID, err := uuid.Parse(s.orgOne.ID)
	require.NoError(s.T(), err)

	testCases := []struct {
		name       string
		opts       *biz.CASBackendCreateOpts
		wantErrMsg string
	}{
		{
			name:       "org missing",
			opts:       &biz.CASBackendCreateOpts{Name: "name"},
			wantErrMsg: "required",
		},
		{
			name:       "name missing",
			opts:       &biz.CASBackendCreateOpts{CASBackendOpts: &biz.CASBackendOpts{OrgID: orgID}},
			wantErrMsg: "required",
		},
		{
			name:       "invalid name",
			opts:       &biz.CASBackendCreateOpts{Name: "this/not/valid", CASBackendOpts: &biz.CASBackendOpts{OrgID: orgID}},
			wantErrMsg: "RFC 1123",
		},
		{
			name:       "another invalid name",
			opts:       &biz.CASBackendCreateOpts{Name: "this-not valid", CASBackendOpts: &biz.CASBackendOpts{OrgID: orgID}},
			wantErrMsg: "RFC 1123",
		},
		{
			name: "can create it with just the name and the org",
			opts: &biz.CASBackendCreateOpts{Name: "name", CASBackendOpts: &biz.CASBackendOpts{OrgID: orgID}},
		},
	}

	for _, tc := range testCases {
		s.Run(tc.name, func() {
			var orgID string
			if tc.opts.CASBackendOpts != nil && tc.opts.OrgID != uuid.Nil {
				orgID = tc.opts.OrgID.String()
			}

			got, err := s.CASBackend.Create(context.Background(), orgID, tc.opts.Name, location, description, backendType, nil, true, nil)
			if tc.wantErrMsg != "" {
				s.ErrorContains(err, tc.wantErrMsg)
				return
			}

			require.NoError(s.T(), err)
			s.NotEmpty(got.ID)
			s.Equal(tc.opts.Name, got.Name)
		})
	}
}

func (s *CASBackendIntegrationTestSuite) TestCreate() {
	assert := assert.


= new ReportItemProcessing();
			reportItemProcessing.DefinitionName = DefinitionName;
			reportItemProcessing.Label = Label;
			reportItemProcessing.Bookmark = Bookmark;
			reportItemProcessing.Tooltip = Tooltip;
			if (Height != null)
			{
				reportItemProcessing.Height = Height.DeepClone();
			}
			if (Width != null)
			{
				reportItemProcessing.Width = Width.DeepClone();
			}
			if (Top != null)
			{
				reportItemProcessing.Top = Top.DeepClone();
			}
			if (Left != null)
			{
				reportItemProcessing.Left = Left.DeepClone();
			}
			reportItemProcessing.ZIndex = ZIndex;
			reportItemProcessing.Hidden = Hidden;
			reportItemProcessing.SharedHidden = SharedHidden;
			Global.Tracer.Assert(SharedStyles == null && NonSharedStyles == null);
			return reportItemProcessing;
		}
	}
}


	    if (pGC->fillStyle == FillSolid)
	    {
		if (devPriv->rop == GXcopy)
		    pGC->ops->PolyGlyphBlt = cfbPolyGlyphBlt8;
		else
#ifdef FOUR_BIT_CODE
		    pGC->ops->PolyGlyphBlt = cfbPolyGlyphRop8;
#else
		    pGC->ops->PolyGlyphBlt = miPolyGlyphBlt;
#endif
	    }
	    else
#endif
		pGC->ops->PolyGlyphBlt = miPolyGlyphBlt;
            /* special case ImageGlyphBlt for terminal emulator fonts */
#if !defined(WriteBitGroup) || PSZ == 8
	    if (TERMINALFONT(pGC->font) &&
		(pGC->planemask & PMSK) == PMSK
#ifdef FOUR_BIT_CODE
		&& FONTMAXBOUNDS(pGC->font,characterWidth) >= PGSZB
#endif
		)
	    {
		pGC->ops->ImageGlyphBlt = useTEGlyphBlt;
	    }
            else
#endif
	    {
#ifdef WriteBitGroup
		if (devPriv->rop == GXcopy &&
		    pGC->fillStyle == FillSolid &&
		    (pGC->planemask & PMSK) == PMSK)
		    pGC->ops->ImageGlyphBlt = cfbImageGlyphBlt8;
		else
#endif
		    pGC->ops->ImageGlyphBlt = miImageGlyphBlt;
	    }
        }
    }

    if (new_fillspans) {
	switch (pGC->fillStyle) {
	case FillSolid:
	    switch (devPriv->rop) {
	    case GXcopy:
		pGC->ops->FillSpans = cfbSolidSpansCopy;
		break;
	    case GXxor:
		pGC->ops->FillSpans = cfbSolidSpansXor;
		break;
	    default:
		pGC->ops->FillSpans = cfbSolidSpansGeneral;
		break;
	    }
	    break;
	case FillTiled:
	    if (devPriv->pRotatedPixmap)
	    {
		if (pGC->alu == GXcopy && (pGC->planemask & PMSK) == PMSK)
		    pGC->ops->FillSpans = cfbTile32FSCopy;
		else
		    pGC->ops->FillSpans = cfbTile32FSGeneral;
	    }
	    else
		pGC->ops->FillSpans = cfbUnnaturalTileFS;
	    break;
	case FillStippled:
#ifdef FOUR_BIT_CODE
	    if (devPriv->pRotatedPixmap)
		pGC->ops->FillSpans = cfb8Stipple32FS;
	    else
#endif
		pGC->ops->FillSpans = cfbUnnaturalStippleFS;
	    break;
	case FillOpaqueStippled:
#ifdef FOUR_BIT_CODE
	    if (devPriv->pRotatedPixmap)
		pGC->ops->FillSpans = cfb8OpaqueStipple32FS;
	    else
#endif
		pGC->ops->FillSpans = cfbUnnaturalStippleFS;
	    break;
	default:
	    FatalError("p9000ValidateGC: illegal fillStyle\n");
	}
    } /* end of new_fillspans */

    if (new_fillarea) {
#ifndef FOUR_BIT_CODE
	pGC->ops->PolyFillRect = miPolyFillRect;
	if (pGC->fillStyle == FillSolid || pGC->fillStyle == FillTiled)
	{
	    pGC->ops->PolyFillRect = cfbPolyFillRect;
	}
        if (pGC->fillStyle == FillSolid)
        {
            pGC->ops->PolyFillRect = p9000PolyFillRect;
        }
#endif
#ifdef FOUR_BIT_CODE
	pGC->ops->PushPixels = mfbPushPixels;
	if (pGC->fillStyle == FillSolid && devPriv->rop == GXcopy)
	    pGC->ops->PushPixels = cfbPushPixels8;
#endif
	pGC->ops->PolyFillArc = miPolyFillArc;
	if (pGC->fillStyle == FillSolid)
	{
	    switch (devPriv->rop)
	    {
	    case GXcopy:
		pGC->ops->PolyFillArc = cfbPolyFillArcSolidCopy;
		break;
	    default:
		pGC->ops->PolyFillArc = cfbPolyFillArcSolidGeneral;
		break;
	    }
	}
    }
}

#endif /* P9000_ACCEL */


            RegionId::Z2 => qiniu_ng_region_id_t::qiniu_ng_region_z2,
            RegionId::AS0 => qiniu_ng_region_id_t::qiniu_ng_region_as0,
            RegionId::NA0 => qiniu_ng_region_id_t::qiniu_ng_region_na0,
        }
    }
}

impl From<qiniu_ng_region_id_t> for RegionId {
    fn from(region_id: qiniu_ng_region_id_t) -> Self {
        match region_id {
            qiniu_ng_region_id_t::qiniu_ng_region_z0 => RegionId::Z0,
            qiniu_ng_region_id_t::qiniu_ng_region_z1 => RegionId::Z1,
            qiniu_ng_region_id_t::qiniu_ng_region_z2 => RegionId::Z2,
            qiniu_ng_region_id_t::qiniu_ng_region_as0 => RegionId::AS0,
            qiniu_ng_region_id_t::qiniu_ng_region_na0 => RegionId::NA0,
        }
    }
}

impl From<qiniu_ng_region_id_t> for *const c_char {
    fn from(region_id: qiniu_ng_region_id_t) -> Self {
        region_id.as_cstr().as_ptr()
    }
}

/// @brief 获取区域 ID 的名称
/// @param[in] region_id 区域 ID
/// @retval *char 区域名称
/// @warning 对于返回的区域名称字符串，请勿释放其内存
#[no_mangle]
pub extern "C" fn qiniu_ng_region_id_name(region_id: qiniu_ng_region_id_t) -> *const c_char {
    region_id.into()
}

/// @brief 区域生成器
/// @details 用于配置并生成区域实例
/// @note
///   * 调用 `qiniu_ng_region_builder_new()` 函数创建 `qiniu_ng_region_builder_t` 实例。
///   * 调用一系列方法修改 `qiniu_ng_region_builder_t` 实例的数据。
///   * 调用 `qiniu_ng_region_build()` 生成 `qiniu_ng_region_t` 实例。
///   * 当通过 `qiniu_ng_region_builder_t` 生成 `qiniu_ng_region_t` 完毕后
///     - 当需要继续生成其他区域实例时，可以调用 `qiniu_ng_region_builder_reset()` 方法重置生成器。
///     - 当没有其他生成需求时，请务必调用 `qiniu_ng_region_builder_free()` 方法释放内存。
/// @note
///   该结构体不可以跨线程使用
/// @note
///   注意，该结构体仅用于在 SDK 中配置生成区域实例，而非在七牛云服务器上创建新的区域。
#[repr(C)]
#[derive(Copy, Clone)]
pub struct qiniu_ng_region_builder_t(*mut c_void);

impl Default for qiniu_ng_region_builder_t {
    #[inline]
    fn default() -> Self {
        Self(null_mut())
    }
}

impl qiniu_ng_region_builder_t {
    #[inline]
    pub fn is_null(self) -> bool {
        self.0.is_null()
    }
}

impl From<qiniu_ng_region_builder_t> for Option<Box<RegionBuilder>> {
    fn from(bu


i$(()=>process.env[qc6]||fc.join($c6.getHomeDir(),".aws","config"),"getConfigFilepath"),Kc6=TP(),Ec6="AWS_SHARED_CREDENTIALS_FILE",Jc6=i$(()=>process.env[Ec6]||fc.join(Kc6.getHomeDir(),".aws","credentials"),"getCredentialsFilepath"),Mc6=TP(),Cc6=/^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/,zc6=["__proto__","profile __proto__"],JwA=i$((A)=>{let D={},w,Y;for(let $ of A.split(/\r?\n/)){let q=$.split(/(^|\s)[;#]/)[0].trim();if(q[0]==="["&&q[q.length-1]==="]"){w=void 0,Y=void 0;let E=q.substring(1,q.length-1),J=Cc6.exec(E);if(J){let[,M,,I]=J;if(Object.values(Rc.IniSectionType).includes(M))w=[M,I].join(LG)}else w=E;if(zc6.includes(E))throw new Error(`Found invalid profile name "${E}"`)}else if(w){let E=q.indexOf("=");if(![0,-1].includes(E)){let[J,M]=[q.substring(0,E).trim(),q.substring(E+1).trim()];if(M==="")Y=J;else{if(Y&&$.trimStart()===$)Y=void 0;D[w]=D[w]||{};let I=Y?[Y,J].join(LG):J;D[w][I]=M}}}}return D},"parseIni"),y11=KwA(),k11=i$(()=>({}),"swallowError"),LG=".",d11=i$(async(A={})=>{let{filepath:D=Jc6(),configFilepath:w=x11()}=A,Y=Mc6.getHomeDir(),$="~/",q=D;if(D.startsWith("~/"))q=fc.join(Y,D.slice(2));let K=w;if(w.startsWith("~/"))K=fc.join(Y,w.slice(2));let E=await Promise.all([y11.slurpFile(K,{ignoreCache:A.ignoreCache}).then(JwA).then(Yc6).catch(k11),y11.slurpFile(q,{ignoreCache:A.ignoreCache}).then(JwA).catch(k11)]);return{configFile:E[0],credentialsFile:E[1]}},"loadSharedConfigFiles"),Ic6=i$((A)=>Object.entries(A).filter(([D])=>D.startsWith(Rc.IniSectionType.SSO_SESSION+LG)).reduce((D,[w,Y])=>({...D,[w.substring(w.indexOf(LG)+1)]:Y}),{}),"getSsoSessionData"),Hc6=KwA(),Xc6=i$(()=>({}),"swallowError"),Wc6=i$(async(A={})=>Hc6.slurpFile(A.configFilepath??x11()).then(JwA).then(Ic6).catch(Xc6),"loadSsoSessionData"),Nc6=i$((...A)=>{let D={};for(let w of A)for(let[Y,$]of Object.entries(w))if(D[Y]!==void 0)Object.assign(D[Y],$);else D[Y]=$;return D},"mergeConfigFiles"),_c6=i$(async(A)=>{let D=await d11(A);return Nc6(D.configFile,D.credentialsFile)},"parseKnownFiles")});var Nz=G((ff0,u11)=>{var{defineProperty:vc,getOwnPropertyDescriptor:Gc6,getOwnPropertyNames:Vc6}=Object,Zc6=Object.prototype.hasOwnProperty,LP=(A,D)=>vc(A,"name",{value:D,configurable:!0}),Qc6=(A,D)=>{for(var w in D)vc(A,w,{get


 on the bottom floor of the big building, next to a bonfire.',
  [15400] = 'H|아라텔 선포지|Standing on a platform balcony type thing, next to 2 big ramps on the side of the building.',
  [15401] = 'H|맥지기 벨라니아|Standing on the side of the road, at the base of a big tree.',
  [15402] = 'H|수습생 미르베다|Standing at the top of some white steps.',
  [15403] = 'H|앨돈 선브랜드|Standing to the left of the entrance to the big building.',
  [15404] = 'H|벨렌드리스 화이트몬|In a small camp, standing in front of 2 tall blue tents.',
  [15405] = 'H|맥지기 케이다니스|Standing to the right of the entrance to the tall building.',
  [15406] = 'H|벤자쉬|Laying down in a yellow cage in the back of the camp.',
  [15407] = '?|족장 줄마로쉬|',
  [15408] = '?|창제작자 오템베|',
  [15409] = '?|늙은 흰나무껍질|',
  [15416] = 'H|순찰자 자엘라|Standing in a group of people.',
  [15417] = 'H|벨란 브라이트오크|Off to the side of the road, next to a cart.',
  [15418] = 'H|마법학자 자로니스|Standing next to a huge fountain.',
  [15420] = 'H|조사단 앤빌워드|Standing to the right of the entrance to the tall building.',
  [15431] = '?|하사관 칸스|',
  [15432] = '?|남작부인 트윈브레이드|',
  [15433] = 'H|여관주인 델라니엘|Standing inside the inn, to the left as you enter.',
  [15434] = '?|병사 드랙슬게이지|',
  [15437] = '?|수석 연금술사 나이트송|',
  [15443] = '?|자넬라 스타우트해머|',
  [15444] = '?|비전술사 노즐스프링|',
  [15445] = '?|선임하사 저메인|',
  [15446] = '?|보니 스톤플레이어|',
  [15448] = '?|병사 포터|',
  [15449] = '?|하이브조라 증오의 쐐기|',
  [15450] = '?|마사 파인스핀들|',
  [15451] = '?|파수꾼 실버스카이|',
  [15452