k the value into
   */
  private void pokeInt(GPR reg, int idx) {
    int offset = BYTES_IN_STACKSLOT - BYTES_IN_INT + (idx << LOG_BYTES_IN_STACKSLOT);
    if (VM.VerifyAssertions) validateStackPush(-offset);
    asm.emitSTW(reg, spTopOffset + offset, FP);
  }

  /**
   * Emit the code to pop a char value from the expression stack into
   * the register 'reg' as an int.
   * @param reg register to pop the value into
   */
  private void popCharAsInt(GPR reg) {
    asm.emitLHZ(reg, spTopOffset + BYTES_IN_STACKSLOT - BYTES_IN_CHAR, FP);
    discardSlot();
  }

  /**
   * Emit the code to pop a short value from the expression stack into
   * the register 'reg' as an int.
   * @param reg register to pop the value into
   */
  private void popShortAsInt(GPR reg) {
    asm.emitLHA(reg, spTopOffset + BYTES_IN_STACKSLOT - BYTES_IN_SHORT, FP);
    discardSlot();
  }

  /**
   * Emit the code to pop a byte value from the expression stack into
   * the register 'reg' as an int.
   * @param reg register to pop the value into
   */
  private void popByteAsInt(GPR reg) {
    asm.emitLWZ(reg, spTopOffset + BYTES_IN_STACKSLOT - BYTES_IN_INT, FP);
    asm.emitEXTSB(reg, reg);
    discardSlot();
  }

  /**
   * Emit the code to pop an intlike (boolean, byte, char, short, int) value
   * from the expression stack into the register 'reg'. Sign extend on 64 bit platform.
   * @param reg register to pop the value into
   */
  private void popInt(GPR reg) {
    asm.emitLInt(reg, spTopOffset + BYTES_IN_STACKSLOT - BYTES_IN_INT, FP);
    discardSlot();
  }

  /**
   * Emit the code to pop a float value
   * from the expression stack into the register 'reg'.
   * @param reg register to pop the value into
   */
  private void popFloat(FPR reg) {
    asm.emitLFS(reg, spTopOffset + BYTES_IN_STACKSLOT - BYTES_IN_FLOAT, FP);
    discardSlot();
  }

  /**
   * Emit the code to pop a double value
   * from the expression stack into the register 'reg'.
   * @param reg register to pop the value into
   */
  private void popDouble(FPR reg) {
    asm.emitLFD(reg, spTopOffset + 2 * BYTES_IN_STACKSLOT - BYTES_IN_DOUBLE, FP);
    discardSlots(2);
  }

  /**
   * Emit the code to push a long value
   * contained in 'reg1' and 'reg2' onto the expression stack
   * @param reg1 register to pop,  the most significant 32 bits on 32bit arch (lowest address), not used on 64bit
   * @param reg2 register to pop,  the least significant 32 bits on 32bit arch (highest address), the whole value on 64bit
   */
  private void popLong(GPR reg1, GPR reg2) {
    if (VM.BuildFor64Addr) {
      asm.emitLD(reg2, spTopOffset + 2 * BYTES_IN_STACKSLOT - BYTES_IN_LONG, FP);
    } else {
      asm.emitLWZ(reg1, spTopOffset, FP);
      asm.emitLWZ(reg2, spTopOffset + BYTES_IN_STACKSLOT, FP);
    }
    discardSlots(2);
  }

  /**
   * Emit the code to pop a long value
   * from the expression stack into the register 'reg'.<p>
   *
   * NOTE: in 32 bit mode, reg is actually a FP register and
   * we


){

    }

    get name(){
        return this._name;
    }

    set name(value){
         this._name=value;
    }

    afficheContact(){
        console.log("name : "+this._name)
    }
}

let contact = new Contact();
contact.name= "soltana bourouina sandra";
contact.afficheContact();

import { Observable, OperatorFunction, Subject } from 'rxjs';
import { switchAll } from 'rxjs/operators';
import { coerceDistinctWith } from './coerceDistinctObservableWith';

/**
 * A factory function returning an object to handle the process of merging Observable next notifications into one
 *   Observable. This API takes away the clumsy handling of static values and Observable, reduces the number of
 *   emissions by:
 * - only merging distinct Observables
 * - only emit distinct values of the merged result
 *
 * You can next a Observable of `U` multiple times and merge them into the Observable exposed under one optimized
 *   `values$`
 *
 */
export function coerceAllFactory<U, R = U>(
  subjectFactory?: () => Subject<Observable<U> | U>,
  flattenOperator?: OperatorFunction<Observable<U>, R>
): {
  values$: Observable<R>;
  next(observable: Observable<U> | U): void;
} {
  const observablesSubject = subjectFactory ? subjectFactory() : new Subject();
  flattenOperator = flattenOperator || (switchAll() as any);
  const values$ = observablesSubject.pipe(
    coerceDistinctWith(flattenOperator as any)
  ) as Observable<R>;

  return {
    next(observable: Observable<U> | U) {
      observablesSubject.next(observable);
    },
    values$,
  };
}
import { State, DEFAULT_STATE } from "./State";
import { Reducer, createReducer, Hooks } from "./Reducer";
import { Dispatch } from "./Action";

export interface Reducers {
  graphviz: (hooks: Hooks) => Reducer;
}

export interface Stores {
  graphviz: {
    state: State;
    dispatch: Dispatch;
  };
}

export const createReducers = (state: State = DEFAULT_STATE): Reducers => {
  return {
    graphviz: createReducer(state),
  };
};
class PlayerTanK extends TanK
{
	public constructor(vo:TanKVo)
	{
		super(vo)
	}

	public destroy():void
	{
		super.destroy();
	}

	public move():void
	{
		this.vo.moveX = this.x;
		this.vo.moveY = this.y;

		if(this.vo.direction == GameData.TANKDIR_UP)
		{
			this.vo.moveY -= this.vo.speed;
		}else if(this.vo.direction == GameData.TANKDIR_RIGHT)
		{
			this.vo.moveX += this.vo.speed;
		}else if(this.vo.direction == GameData.TANKDIR_DOWN)
		{
			this.vo.moveY += this.vo.speed;
		}else if(this.vo.direction == GameData.TANKDIR_LEFT)
		{
			this.vo.moveX -= this.vo.speed;
		}
		this.vo.isHit = Collision.tankMapCollision(this);
		if(!this.vo.isHit)
		{
			this.x = this.vo.moveX;
			this.y = this.vo.moveY;
		}
	}

}import { ConfigServiceProvider } from '../providers/config-service/config-service';
import { AvatarModel } from './avatar.model';
import { ItemModel } from './item.model';

export class PlayerModel {
  public nombre: string;
  public icono: st


()
        end
        print_mutstate("Potion test try " .. i .. ", ")
        sum = sum + you.how_mutated(true, true, true)
    end
    mean = sum / tries
    if not silent then
        crawl.stderr("Mean resulting mutations: " .. mean .. eol)
    end
end

-- relies largely an asserts in the mutation code.
local function test_random_mutations(tries, iterations, chance_temporary, chance_clear)
    for i=1, tries do
        you.delete_all_mutations("mutation test")
        assert(you.how_mutated(true, true, true) == 0,
                "Clearing mutations failed, currently: " .. you.mutation_overview())
        for j=1, iterations do
            if crawl.x_chance_in_y(chance_clear, 100) then
                if crawl.coinflip() then


this\$0",
        description = """
          In Android 11 DP 2 ApplicationPackageManager.HasSystemFeatureQuery was an inner class.
          Introduced in https://cs.android.com/android/_/android/platform/frameworks/base/+/89608118192580ffca026b5dacafa637a556d578
          Fixed in https://cs.android.com/android/_/android/platform/frameworks/base/+/1f771846c51148b7cb6283e6dc82a216ffaa5353
          Related blog: https://dev.to/pyricau/beware-packagemanager-leaks-223g
        """.trimIndent()
      ) {
        sdkInt == 29
      }
    }
  },

  // ######## Manufacturer specific known leaks ########

  // SAMSUNG

  SPEN_GESTURE_MANAGER {
    override fun add(
      references: MutableList<ReferenceMatcher>
    ) {
      references += staticFieldLeak(
        "com.samsung.android.smartclip.SpenGestureManager", "mContext",
        description =
        "SpenGestureManager has a static mContext field that leaks a reference to the" + " activity. Yes, a STATIC mContext field."
      ) {
        manufacturer == SAMSUNG && sdkInt == 19
      }
    }
  },

  CLIPBOARD_UI_MANAGER__SINSTANCE {
    override fun add(
      references: MutableList<ReferenceMatcher>
    ) {
      references += instanceFieldLeak(
        "android.sec.clipboard.ClipboardUIManager", "mContext",
        description =
        "ClipboardUIManager is a static singleton that leaks an activity context."
          + " Fix: trigger a call to ClipboardUIManager.getInstance() in Application.onCreate()"
          + " , so that the ClipboardUIManager instance gets cached with a reference to the"
          + " application context. Example: https://gist.github.com/cypressious/"
          + "91c4fb1455470d803a602838dfcd5774"
      ) {
        manufacturer == SAMSUNG && sdkInt in 19..21
      }
    }
  },

  SEM_CLIPBOARD_MANAGER__MCONTEXT {
    override fun add(
      references: MutableList<ReferenceMatcher>
    ) {
      val description = """
         SemClipboardManager inner classes are held by native references due to IPC calls
      """.trimIndent()
      references += nativeGlobalVariableLeak(
        "com.samsung.android.content.clipboard.SemClipboardManager$1", description
      ) {
        manufacturer == SAMSUNG && sdkInt in 19..28
      }
      references += nativeGlobalVariableLeak(
        "com.samsung.android.content.clipboard.SemClipboardManager$3", description
      ) {
        manufacturer == SAMSUNG && sdkInt in 19..28
      }
    }
  },

  CLIPBOARD_EX_MANAGER {
    override fun add(
      references: MutableList<ReferenceMatcher>
    ) {
      references += instanceFieldLeak(
        "android.sec.clipboard.ClipboardExManager", "mContext",
        description = "android.sec.clipboard.ClipboardExManager\$IClipboardDataPasteEventImpl\$1" +
          " is a native callback that holds IClipboardDataPasteEventImpl which holds" +
          " ClipboardExManager which has a destroyed activity as mContext"
      ) {
        manufacturer == SAMSUNG && sdkInt == 23
      }
      references += instanceFieldLeak(
        "android.sec.clipboard.ClipboardExManager", "mPersonaManager",
        description = "android.sec.clipboard.ClipboardExManager\$IClipboardDataPasteEventImpl\$1" +
          " is a native callback that holds IClipboardDataPasteEventImpl which holds" +
          " ClipboardExManager which holds PersonaManager which has a des


): RealmResults<E>
    fun onJSON(t: E): List<T>
    fun onConversion(t: T): Any
}

interface FlatRealmReadConversionObjectInterface<T, E, R> {
    fun query(realm: Realm): RealmResults<E>
    fun onJSON(t: E): T
    fun onConversion(t: T?): R?
}package com.shuyu.github.kotlin.model.conversion

import android.content.Context
import com.shuyu.github.kotlin.R
import com.shuyu.github.kotlin.common.utils.CommonUtils
import com.shuyu.github.kotlin.common.utils.HtmlUtils
import com.shuyu.github.kotlin.model.bean.*
import com.shuyu.github.kotlin.model.ui.FileUIModel
import com.shuyu.github.kotlin.model.ui.PushUIModel
import com.shuyu.github.kotlin.model.ui.ReposUIModel

/**
 * 仓库相关实体转换
 * Created by guoshuyu
 * Date: 2018-10-29
 */
object ReposConversion {

    fun trendToReposUIModel(trendModel: TrendingRepoModel): ReposUIModel {
        val reposUIModel = ReposUIModel()
        reposUIModel.hideWatchIcon = true
        reposUIModel.ownerName = trendModel.name
        reposUIModel.ownerPic = trendModel.contributors[0]
        reposUIModel.repositoryDes = trendModel.description
        reposUIModel.repositoryName = trendModel.reposName
        reposUIModel.repositoryFork = trendModel.forkCount
        reposUIModel.repositoryStar = trendModel.starCount
        reposUIModel.repositoryWatch = trendModel.meta
        reposUIModel.repositoryType = trendModel.language
        return reposUIModel
    }

    fun reposToReposUIModel(context: Context, repository: Repository?): ReposUIModel {
        val reposUIModel = ReposUIModel()
        reposUIModel.hideWatchIcon = true
        reposUIModel.ownerName = repository?.owner?.login ?: ""
        reposUIModel.ownerPic = repository?.owner?.avatarUrl ?: ""
        reposUIModel.repositoryDes = repository?.description ?: ""
        reposUIModel.repositoryName = repository?.name ?: ""
        reposUIModel.repositoryFork = repository?.forksCount?.toString() ?: ""
        reposUIModel.repositoryStar = repository?.stargazersCount?.toString() ?: ""
        reposUIModel.repositoryWatch = repository?.subscribersCount?.toString() ?: ""
        reposUIModel.repositoryType = repository?.language ?: ""
        reposUIModel.repositorySize = (((repository?.size
                ?: 0) / 1024.0)).toString().substring(0, 3) + "M"
        reposUIModel.repositoryLicense = repository?.license?.name ?: ""

        val createStr = if (repository != null && repository.fork)
            context.getString(R.string.forked_at) + (repository.parent?.name ?: "") + "\n"
        else
            context.getString(R.string.created_at) + CommonUtils.getDateStr(repository?.createdAt) + "\n"

        reposUIModel.repositoryAction = createStr
        reposUIModel.repositoryIssue = repository?.openIssuesCount?.toString() ?: ""
        return reposUIModel
    }

    fun fileListToFileUIList(list: ArrayList<FileModel>): ArrayList<Any> {
        val result = ArrayList<Any>()
        val dirs = ArrayList<Any>()
        val files = ArrayList<Any>()

        list.forEach {
            val fileUIModel = FileUIModel()
            fileUIModel.title = it.name ?: ""
            fileUIModel.type = it.type ?: ""
            if (it.type == "file") {
                fileUIModel.icon = "{GSY-RE


import difflib

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

jobs = pd.read_csv("jobs.csv")
jobs["technologies"] = jobs["technologies"].str.lower()

tech = (
    jobs["technologies"]
    .str.split(",\s*", expand=True)
    .stack()
    .reset_index(level=1, drop=True)
    .rename("technology")
)
jobs_split = jobs.drop("technologies", axis=1).join(tech)

tech_group = {}
for technology in jobs_split["technology"].unique():
    similar_tech = difflib.get_close_matches(
        technology, tech_group.keys(), n=1, cutoff=0.8
    )
    if similar_tech:
        tech_group[similar_tech[0]] += jobs_split[
            jobs_split["technology"] == technology
        ].shape[0]
    else:
        tech_group[technology] = (
            jobs_split[jobs_split["technology"] == technology].shape[0]
        )

tech_count = pd.Series(tech_group)
tech_count.sort_values(ascending=False, inplace=True)

plt.figure(figsize=(10, 6))
tech_count.head(30).plot(kind="bar", color="skyblue")
plt.title("Top 30 Popular Technologies in Job Vacancies")
plt.xlabel("Technologies")
plt.ylabel("Count")
plt.xticks(rotation=90, ha="right")
plt.tight_layout()
plt.show()


		runnerOpts = append(runnerOpts, igrunner.WithFlags(fmt.Sprintf("-r=%s", utils.Runtime), "--timeout=5"))
	case utils.KubectlGadgetTestComponent:
		runnerOpts = append(runnerOpts, igrunner.WithFlags(fmt.Sprintf("-n=%s", ns), "--timeout=5"))
		testingOpts = append(testingOpts, igtesting.WithCbBeforeCleanup(utils.PrintLogsFn(ns)))
		commonDataOpts = append(commonDataOpts, utils.WithK8sNamespace(ns))
	}

	runnerOpts = append(runnerOpts, igrunner.WithValidateOutput(
		func(t *testing.T, output string) {
			expectedEntry := &traceSNIEvent{
				CommonData: utils.BuildCommonData(containerName, commonDataOpts...),
				Proc:       utils.BuildProc("wget", 1000, 1111),
				Name:       "inspektor-gadget.io",

				// Check the existence of the following fields
				Timestamp: utils.NormalizedStr,
				NetNs:     utils.NormalizedInt,
			}

			normalize := func(e *traceSNIEvent) {
				utils.NormalizeCommonData(&e.CommonData)
				utils.NormalizeString(&e.Timestamp)
				utils.NormalizeInt(&e.NetNs)
				utils.NormalizeProc(&e.Proc)
			}

			match.MatchEntries(t, match.JSONMultiObjectMode, output, normalize, expectedEntry)
		},
	))

	traceSNICmd := igrunner.New("trace_sni", runnerOpts...)

	igtesting.RunTestSteps([]igtesting.TestStep{traceSNICmd}, t, testingOpts...)
}
// Copyright 2024 The Inspektor Gadget authors
//
// 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 tests

import (
	"fmt"
	"testing"
	"time"

	"github.com/stretchr/testify/require"

	gadgettesting "github.com/inspektor-gadget/inspektor-gadget/gadgets/testing"
	igtesting "github.com/inspektor-gadget/inspektor-gadget/pkg/testing"
	"github.com/inspektor-gadget/inspektor-gadget/pkg/testing/containers"
	igrunner "github.com/inspektor-gadget/inspektor-gadget/pkg/testing/ig"
	"github.com/inspektor-gadget/inspektor-gadget/pkg/testing/match"
	"github.com/inspektor-gadget/inspektor-gadget/pkg/testing/utils"
)

type traceloopEvent struct {
	utils.CommonData

	MntnsID    uint64 `json:"mntns_id"`
	CPU        uint16 `json:"cpu"`
	PID        uint32 `json:"pid"`
	Comm       string `json:"comm"`
	Syscall    string `json:"syscall"`
	Parameters string `json:"parameters"`
	Ret        string `json:"ret"`
}

func TestTraceloop(t *testing.T) {
	gadgettesting.RequireEnvironmentVariables(t)
	utils.InitTest(t)

	containerFactory, err := containers.NewContainerFactory(utils.Runtime)
	require.NoError(t, err, "new container factory")
	containerName := "test-traceloop"
	containerImage := gadgettesting.BusyBoxImage

	var ns string
	containerOpts := []containers.ContainerOption{
		cont


Clerk)
            gClerk = nil
        end
    end
end

function F_PartialCleanupShop()
    SoundEnableSpeech_ActionTree()
    gHACKClothesCam = false
    CameraSetActive(1, 100, false)
end

function F_CleanupShop()
    F_PartialCleanupShop()
    ToggleHUDComponentLocked(40, false)
    ToggleHUDComponentVisibility(14, false)
    HUDRestoreVisibility()
    PedSetActionNode(gPlayer, "/Global/Ambient/MissionSpec/Clothing/Finished", "Act/Anim/Ambient.act")
end

function F_AddClothes()
    ClothingStoreAdd(0, "S_Bhat2", 350)
    ClothingStoreAdd(0, "S_Bhat3", 350)
    ClothingStoreAdd(0, "S_Sunvisor1", 350)
    ClothingStoreAdd(0, "S_Sunvisor2", 350)
    ClothingStoreAdd(0, "S_Sunvisor3", 350)
    ClothingStoreAdd(1, "S_SSleeves1", 350)
    ClothingStoreAdd(1, "S_SSleeves2", 350)
    ClothingStoreAdd(1, "S_SSleeves3", 350)
    ClothingStoreAdd(1, "S_SSleeves4", 350)
    ClothingStoreAdd(1, "S_SSleeves5", 350)
    ClothingStoreAdd(1, "S_SSleeves6", 350)
    ClothingStoreAdd(1, "S_SSleeves7", 350)
    ClothingStoreAdd(1, "S_SSleeves8", 350)
    ClothingStoreAdd(1, "S_LSleeves1", 600)
    ClothingStoreAdd(1, "S_LSleeves2", 600)
    ClothingStoreAdd(1, "S_LSleeves3", 800)
    ClothingStoreAdd(1, "S_LSleeves4", 800)
    ClothingStoreAdd(1, "S_Sweater1", 700)
    ClothingStoreAdd(1, "S_Sweater2", 700)
    ClothingStoreAdd(1, "S_Jacket3", 1100)
    ClothingStoreAdd(1, "S_Jacket4", 1100)
    ClothingStoreAdd(4, "S_Pants3", 700)
    ClothingStoreAdd(4, "S_Shorts1", 500)
    ClothingStoreAdd(4, "S_Shorts4", 500)
    ClothingStoreAdd(4, "S_Shorts5", 500)
    ClothingStoreAdd(4, "S_Shorts6", 500)
    ClothingStoreAdd(2, "S_Wristband1", 200)
    ClothingStoreAdd(3, "S_Wristband2", 200)
    ClothingStoreAdd(3, "S_Wristband3", 200)
    ClothingStoreAdd(2, "S_Wristband4", 200)
    ClothingStoreAdd(3, "S_Wristband5", 200)
    ClothingStoreAdd(2, "S_Wristband6", 200)
    ClothingStoreAdd(5, "S_Sneakers1", 600)
    ClothingStoreAdd(5, "S_Sneakers2", 1000)
end

function F_DispersePatrolPrefects()
    --print("DISPERSING_________(#*^$(*^")
    DockerSetOverrideActiveSetting(SchoolDocker, true)
    AreaSetDockerPatrolPedReception(SchoolDocker, true)
    DockerSetMaximumRange(SchoolDocker, 100)
    DockerSetUseFacingCheck(SchoolDocker, false)
    AreaSetDockerRunPercentage(SchoolDocker, 100)
    DockerSetOverrideActiveSetting(ExitDocker, true)
    AreaSetDockerPatrolPedReception(ExitDocker, true)
    DockerSetMaximumRange(ExitDocker, 100)
    DockerSetUseFacingCheck(ExitDocker, false)
    AreaSetDockerRunPercentage(ExitDocker, 100)
end

function F_RestoreSchoolSpawners()
    DockerClearOverrideActiveSetting(SchoolDocker)
    AreaSetDockerPatrolPedReception(SchoolDocker, false)
    DockerS


grid: {
					hoverable: true,
					clickable: true
				}
			});

			setCode([
				"$.plot('#placeholder', data, {",
				"    series: {",
				"        pie: {",
				"            show: true",
				"        }",
				"    },",
				"    grid: {",
				"        hoverable: true,",
				"        clickable: true",
				"    }",
				"});"
			]);

			placeholder.bind("plothover", function(event, pos, obj) {

				if (!obj) {
					return;
				}

				var percent = parseFloat(obj.series.percent).toFixed(2);
				$("#hover").html("" + obj.series.label + " (" + percent + "%)");
			});

			placeholder.bind("plotclick", function(event, pos, obj) {

				if (!obj) {
					return;
				}

				percent = parseFloat(obj.series.percent).toFixed(2);
				alert(""  + obj.series.label + ": " + percent + "%");
			});
		});

		// Show the initial default chart

		$("#example-1").click();

		// Add the Flot version string to the footer

		$("#footer").prepend("Flot " + $.plot.version + " – ");
	});

	// A custom label formatter used by several of the plots

	function labelFormatter(label, series) {
		return "
" + label + "
" + Math.round(series.percent) + "%
";
	}

	//

	function setCode(lines) {
		$("#code").text(lines.join("\n"));
	}

	</script>

Pie Charts

				<button id="example-1">Default Options</button>
				<button id="example-2">Without Legend</button>
				<button id="example-3">Label Formatter</button>
				<button id="example-4">Label Radius</button>
				<button id="example-5">Label Styles #1</button>
				<button id="example-6">Label Styles #2</button>
				<button id="example-7">Hidden Labels</button>
				<button id="example-8">Combined Slice</button>
				<button id="example-9">Rectangular Pie</button>
				<button id="example-10">Tilted Pie</button>
				<button id="example-11">Donut Hole</button>
				<button id="example-12">Interactivity</button>

Source Code

Pie Options

option: default value - Description of option

show: false - Enable the plugin and draw as a pie.

radius: 'auto' - Sets the radius of the pie. If value is between 0 and 1 (inclusive) then it will use that as a percentage of the available space (size of the container), otherwise it will use the value as a direct pixel length. If set to 'auto', it will be set to 1 if the legend is enabled and 3/4 if not.

innerRadius: 0 - Sets the radius of the donut hole. If value is between 0 and 1 (inclusive) then it will use that as a percentage of the radius, oth


些不影响实际渲染效果的内容。有一个专门的词来形容这种压缩： uglify 。~~倒是非常形象，毕竟从结果来看确实是变丑了。~~

我以前使用过 gulp.js 和对应的插件来处理这些工作，应该 Webpack 和 rollup 也能处理这些，但我没有再继续深入了解过了。

#### 图片优化与懒加载

存储格式优化：一般现在网上流通比较多的图片多是 JPEG 或 PNG 格式，这两种格式的压缩率都不如 WebP 这种新型的格式，但新格式的普及需要付出不小的时间和各方的努力配合。有一种思路，就是在尽可能能使用 WebP 格式的时候使用它，以减小不必要的流量传输，加快图片的加载速度以提升终端用户的浏览体验。

缩略图：如果上传的是一张清晰度较高的图片，但在实际使用的时候默认会显示一张尺寸较小的版本，那么就可以使用缩略图代理优化——在缩略图加载的时候仅加载较小尺寸的图片，在需要加载完整图片的场合再去加载原始文件。

懒加载：在没有浏览到图片的时候就加载它会导致不必要的资源浪费，考虑到并不是所有的读者都一定会看完所有的文本和图片，所以仅在读者将要浏览到对应图片的时候再去实际加载就成了一个效果不错的优化方案。可以将这个优化方案和上面提到的缩略图相结合，在加载完成清晰的图片之前，使用一张缩略图作为加载中的示意。

#### 模块化代码与延迟加载

加载执行 JS 代码的过程会阻塞浏览器的渲染线程，如果页面上需要执行的代码非常多的话，可能会导致页面的渲染卡顿。并不是所有的 JS 代码都在网页初始化的时候就全部都会被执行到，所以可以将非必需立刻执行的代码拆到单独的组件中去，并使用 script 标签的 [async](https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/script#async) 及 [defer](https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/script#defer) 属性来处理。

同时，这也意味着如果 JS 的执行线程被卡住了，那么渲染线程也会跟着卡住。要尽可能减轻这个问题导致的性能影响，除了使用不容易阻塞的算法外，有一种常用的方法是先让页面向后渲染一段再执行耗时操作。例如可以使用 setTimeout 将它们包一层，并设置延时为一个较小的数值；或是使用 [requestIdleC


tLabel");
					["_Region"] = Instance.new("TextLabel");
					["_DropShadowHolder"] = Instance.new("Frame");
					["_DropShadow"] = Instance.new("ImageLabel");
				}

				Converted["_SessionInfo"].ZIndexBehavior = Enum.ZIndexBehavior.Sibling
				Converted["_SessionInfo"].Name = "SessionInfo"
				Converted["_SessionInfo"].Parent = plrgui
				Converted["_SessionInfo"].ResetOnSpawn = false

				Converted["_Background"].BackgroundColor3 = Color3.fromHSV(0, 0, 0)
				Converted["_Background"].BackgroundTransparency = 0.800000011920929
				Converted["_Background"].BorderColor3 = Color3.fromRGB(0, 0, 0)
				Converted["_Background"].BorderSizePixel = 0
				Converted["_Background"].Position = UDim2.new(0.0116598075, 0, 0.375, 0)
				Converted["_Background"].Size = UDim2.new(0.128257886, 0, 0.16310975, 0)
				Converted["_Background"].Name = "Background"
				Converted["_Background"].Parent = Converted["_SessionInfo"]

				Converted["_UICorner"].Parent = Converted["_Background"]

				Converted["_SessionInfoLabel"].Font = Enum.Font.SourceSansBold
				Converted["_SessionInfoLabel"].Text = "Session Info"
				Converted["_SessionInfoLabel"].TextColor3 = Color3.fromRGB(255, 255, 255)
				Converted["_SessionInfoLabel"].TextScaled = true
				Converted["_SessionInfoLabel"].TextSize = 14
				Converted["_SessionInfoLabel"].TextWrapped = true
				Converted["_SessionInfoLabel"].TextXAlignment = Enum.TextXAlignment.Left
				Converted["_SessionInfoLabel"].BackgroundColor3 = Color3.fromRGB(255, 255, 255)
				Converted["_SessionInfoLabel"].BackgroundTransparency = 1
				Converted["_SessionInfoLabel"].BorderColor3 = Color3.fromRGB(0, 0, 0)
				Converted["_SessionInfoLabel"].BorderSizePixel = 0
				Converted["_SessionInfoLabel"].Position = UDim2.new(0.0374331549, 0, 0, 0)
				Converted["_SessionInfoLabel"].Size = UDim2.new(1, 0, 0.242990658, 0)
				Converted["_SessionInfoLabel"].Name = "SessionInfoLabel"
				Converted["_SessionInfoLabel"].Parent = Converted["_Background"]

				Converted["_TimePlayed"].Font = Enum.Font.SourceSans
				Converted["_TimePlayed"].Text = "Time Played: 00:00"
				Converted["_TimePlayed"].TextColor3 = Color3.fromRGB(255, 255, 255)
				Converted["_TimePlayed"].TextScaled = true
				Converted["_TimePlayed"].TextSize = 14
				Converted["_TimePlayed"].TextWrapped = true
				Converted["_TimePlayed"].TextXAlignment = Enum.TextXAlignment.Left
				Converted["_TimePlayed"].BackgroundColor3 = Color3.fromRGB(255, 255, 255)
				Converted["_TimePlayed"].BackgroundTransparency = 1
				Converted["_TimePlayed"].BorderColor3 = Color3.fromRGB(0, 0, 0)
				Converted["_TimePlayed"].BorderSizePixel = 0
				Converted["_TimePlayed"].Position = UDim2.new(0.0374331549, 0, 0.275288522, 0)
				Converted["_TimePlayed"].Size = UDim2.new(1, 0, 0.168224305, 0)
				Converted["_TimePlayed"].Name = "TimePlayed"
				Converted["_TimePlayed"].Parent = Converted["_Background"]

				Converted["_Kills"].Font = Enum.Font.SourceSans
				Converted["_Kills"].Text = "Kills: 0"
				Converted["_Kills"].TextColor3 = Color3.fromRGB(255, 255, 255)
				Converted["_Kills


 != f {
			return errors.New("not an integer value")
		}
	} else {
		if err := json.Unmarshal(data, &i); err != nil {
			return errors.New("cannot be unmarshaled into an int")
		}
	}
	// Ensure behavior is the same on both 32-bit and 64-bit systems.
	if i < math.MinInt32 || i > math.MaxInt32 {
		return errors.New("integer is out of range")
	}
	*ip = integer(i)
	return nil
}

// Ptr returns a pointer to a new variable whose value is x.
func Ptr[T any](x T) *T { return &x }

// every applies f preorder to every schema under s including s.
// The second argument to f is the path to the schema appended to the argument path.
// It stops when f returns false.
func (s *Schema) every(f func(*Schema) bool) bool {
	return f(s) && s.everyChild(func(s *Schema) bool { return s.every(f) })
}

// everyChild reports whether f is true for every immediate child schema of s.
func (s *Schema) everyChild(f func(*Schema) bool) bool {
	v := reflect.ValueOf(s)
	for _, info := range schemaFieldInfos {
		fv := v.Elem().FieldByIndex(info.sf.Index)
		switch info.sf.Type {
		case schemaType:
			// A field that contains an individual schema. A nil is valid: it just means the field isn't present.
			c := fv.Interface().(*Schema)
			if c != nil && !f(c) {
				return false
			}

		case schemaSliceType:
			slice := fv.Interface().([]*Schema)
			for _, c := range slice {
				if !f(c) {
					return false
				}
			}

		case schemaMapType:
			// Sort keys for determinism.
			m := fv.Interface().(map[string]*Schema)
			for _, k := range slices.Sorted(maps.Keys(m)) {
				if !f(m[k]) {
					return false
				}
			}
		}
	}
	return true
}

// all wraps every in an iterator.
func (s *Schema) all() iter.Seq[*Schema] {
	return func(yield func(*Schema) bool) { s.every(yield) }
}

// children wraps everyChild in an iterator.
func (s *Schema) children() iter.Seq[*Schema] {
	return func(yield func(*Schema) bool) { s.everyChild(yield) }
}

var (
	schemaType      = reflect.TypeFor[*Schema]()
	schemaSliceType = reflect.TypeFor[[]*Schema]()
	schemaMapType   = reflect.TypeFor[map[string]*Schema]()
)

type structFieldInfo struct {
	sf       reflect.StructField
	jsonName string
}

var (
	// the visible fields of Schema that have a JSON name, sorted by that name
	schemaFieldInfos []structFieldInfo
	// map from JSON name to field
	schemaFieldMap = map[string]reflect.StructField{}
)

func init() {
	for _, sf := range reflect.VisibleFields(reflect.TypeFor[Schema]()) {
		info := fieldJSONInfo(sf)
		if !info.omit {
			schemaFieldInfos = append(schemaFieldInfos, structFieldInfo{sf, info.name})
		}
	}
	slices.SortFunc(schemaFieldInfos, func(i1, i2 structFieldInfo) int {
		return cmp.Compare(i1.jsonName, i2.jsonName)
	})
	for _, info := range schemaFieldInfos {
		schemaFieldMap[info.jsonName] = info.sf
	}
}
// Copyright 2021 Google LLC
//
// 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 a


  writeNotNull('type', _$VideoBufferTypeEnumMap[instance.type]);
  writeNotNull('format', _$VideoPixelFormatEnumMap[instance.format]);
  writeNotNull('stride', instance.stride);
  writeNotNull('height', instance.height);
  writeNotNull('cropLeft', instance.cropLeft);
  writeNotNull('cropTop', instance.cropTop);
  writeNotNull('cropRight', instance.cropRight);
  writeNotNull('cropBottom', instance.cropBottom);
  writeNotNull('rotation', instance.rotation);
  writeNotNull('timestamp', instance.timestamp);
  writeNotNull('eglType', _$EglContextTypeEnumMap[instance.eglType]);
  writeNotNull('textureId', instance.textureId);
  writeNotNull('fenceObject', instance.fenceObject);
  writeNotNull('matrix', instance.matrix);
  writeNotNull('metadataSize', instance.metadataSize);
  writeNotNull('fillAlphaBuffer', instance.fillAlphaBuffer);
  writeNotNull(
      'alphaStitchMode', _$AlphaStitchModeEnumMap[instance.alphaStitchMode]);
  writeNotNull('d3d11Texture2d', instance.d3d11Texture2d);
  writeNotNull('textureSliceIndex', instance.textureSliceIndex);
  writeNotNull('hdr10MetadataInfo', instance.hdr10MetadataInfo?.toJson());
  writeNotNull('colorSpace', instance.colorSpace?.toJson());
  return val;
}

const _$VideoBufferTypeEnumMap = {
  VideoBufferType.videoBufferRawData: 1,
  VideoBufferType.videoBufferArray: 2,
  VideoBufferType.videoBufferTexture: 3,
};

const _$VideoPixelFormatEnumMap = {
  VideoPixelFormat.videoPixelDefault: 0,
  VideoPixelFormat.videoPixelI420: 1,
  VideoPixelFormat.videoPixelBgra: 2,
  VideoPixelFormat.videoPixelNv21: 3,
  VideoPixelFormat.videoPixelRgba: 4,
  VideoPixelFormat.videoPixelNv12: 8,
  VideoPixelFormat.videoTexture2d: 10,
  VideoPixelFormat.videoTextureOes: 11,
  VideoPixelFormat.videoCvpixelNv12: 12,
  VideoPixelFormat.videoCvpixelI420: 13,
  VideoPixelFormat.videoCvpixelBgra: 14,
  VideoPixelFormat.videoCvpixelP010: 15,
  VideoPixelFormat.videoPixelI422: 16,
  VideoPixelFormat.videoTextureId3d11texture2d: 17,
  VideoPixelFormat.videoPixelI010: 18,
};

const _$EglContextTypeEnumMap = {
  EglContextType.eglContext10: 0,
  EglContextType.eglContext14: 1,
};

const _$AlphaStitchModeEnumMap = {
  AlphaStitchMode.noAlphaStitch: 0,
  AlphaStitchMode.alphaStitchUp: 1,
  AlphaStitchMode.alphaStitchBelow: 2,
  AlphaStitchMode.alphaStitchLeft: 3,
  AlphaStitchMode.alphaStitchRight: 4,
};

VideoFrame _$VideoFrameFromJson(Map<String, dynamic> json) => VideoFrame(
      type: $enumDecodeNullable(_$VideoPixelFormatEnumMap, json['type']),
      width: (json['width'] as num?)?.toInt(),
      height: (json['height'] as num?)?.toInt(),
      yStride: (json['yStride'] as num?)?.toInt(),
      uStride: (json['uStride'] as num?)?.toInt(),
      vStride: (json['vStride'] as num?)?.toInt(),
      rotation: (json['rotation'] as num?)?.toInt(),
      renderTimeMs: (json['renderTimeMs'] as num?)?.toInt(),
      avsyncType: (json['avsync_type'] as num?)?.toInt(),
      metadataSize: (json['metadata_size'] as num?)?.toInt(),
      textureId: (json['textureId'] as num?)?.toInt(),
      matrix: (json['matrix'] as List<dynamic>?)
          ?.map((e) => (e as num).toDouble())
          .toList(),
      alphaStitchMode: $enumDecodeNullable(
          _$AlphaStitchModeEnumMap, json['alphaSt


     GetPkmnData

	ldr     r1, [sp, #0x2c]
	lsl     r2, r5, #2
	ldr     r1, [r1, r2]
	ldr     r2, [sp, #0x40]
	sub     r0, r0, r1
	str     r0, [sp, #0xb8]
	mov     r0, #0x2
	str     r0, [sp, #0xd0]
	mov     r0, #0x50
	str     r0, [sp, #0x0]
	lsl     r0, r5, #4
	str     r0, [sp, #0x4]
	mov     r0, #0x2
	str     r0, [sp, #0x8]
	mov     r0, #0x1c
	str     r0, [sp, #0xc]
	mov     r0, #0x0
	str     r0, [sp, #0x10]
	ldr     r0, [r4, #0x0]
	mov     r1, r7
	add     r3, sp, #0xb4
	bl      Function_223fb78_ShowBattleMsg

	ldr     r0, [sp, #0x50]
	.hword  0x1c40 @ add r0, r0, #0x1
	str     r0, [sp, #0x50]
	cmp     r0, #0x6
	blt     branch_2249416

	mov     r0, #0xb
	add     sp, #0xd8
	str     r0, [r4, #0x28]
	pop     {r3-r7,pc}

branch_22494a0: @ 22494a0 :thumb
	ldr     r3, [pc, #0x15c] @ 0x2249600, (=0x226e5d8)
	add     r2, sp, #0x54
	ldmia   r3!, {r0,r1}
	stmia   r2!, {r0,r1}
	ldmia   r3!, {r0,r1}
	stmia   r2!, {r0,r1}
	ldmia   r3!, {r0,r1}
	stmia   r2!, {r0,r1}

	ldr     r0, [r4, #0x0]
	mov     r1, #0x1
	bl      Function_223df04

	mov     r1, #0x24
	str     r1, [sp, #0x0]
	mov     r1, #0x60
	str     r1, [sp, #0x4]

	mov     r1, #0xf
	mov     r2, #0x50
	mov     r3, #0x0
	mov     r7, r0
	bl      Function_201ae78

	mov     r1, #0x0
	str     r1, [sp, #0x50]
	add     r5, sp, #0xb4
branch_22494d2: @ 22494d2 :thumb
	ldr     r0, [pc, #0x130] @ 0x2249604, (=0x3b5)
	lsl     r2, r1, #2
	add     r1, sp, #0x54
	strh    r0, [r5, #BattleMsg_2]
	mov     r0, #0x7
	ldr     r1, [r1, r2]
	strb    r0, [r5, #BattleMsg_1]
	mov     r0, r6
	mov     r2, #0x0
	bl      GetPkmnData
	str     r0, [sp, #0xb8]

	mov     r0, #0x3
	str     r0, [sp, #0xd0]
	mov     r0, #0x48
	str     r0, [sp, #0x0]
	ld


		for (segment_index_t b = blocks.first; b < blocks.second; ++b) {
			if ((*my_table)[b] == nullptr)
				return false;
		}

		return true;
	}

private:
	using block_range = std::pair<segment_index_t, segment_index_t>;

	/**
	 * @return block indexes [begin, end) for corresponding segment
	 */
	static block_range
	segment_blocks(segment_index_t seg)
	{
		segment_index_t begin = first_block_in_segment(seg);

		return block_range(begin, begin + blocks_in_segment(seg));
	}

	void
	enable_first_block(pool_base &pop)
	{
		assert(my_seg == embedded_segments);
		{
			transaction::manual tx(pop);

			size_type sz =
				segment_size(first_block) - embedded_buckets;
			(*my_table)[my_seg] =
				make_persistent<bucket_type[]>(sz);

			persistent_ptr<bucket_type> base =
				(*my_table)[embedded_segments].raw();

			for (segment_index_t s = my_seg + 1; s < first_block;
			     ++s) {
				std::ptrdiff_t off =
					static_cast<std::ptrdiff_t>(
						segment_base(s) -
						segment_base(my_seg));

				(*my_table)[s] = (base + off).raw();
			}

			transaction::commit();
		}
	}

	void
	enable_big_segment(pool_base &pop)
	{
		block_range blocks = segment_blocks(my_seg);
#if LIBPMEMOBJ_CPP_CONCURRENT_HASH_MAP_USE_ATOMIC_ALLOCATOR
		for (segment_index_t b = blocks.first; b < blocks.second; ++b) {
			if ((*my_table)[b] == nullptr)
				make_persistent_atomic<bucket_type[]>(
					pop, (*my_table)[b], block_size(b));
		}
#else
		{
			transaction::manual tx(pop);

			for (segment_index_t b = blocks.first;
			     b < blocks.second; ++b) {
				assert((*my_table)[b] == nullptr);
				(*my_table)[b] = make_persistent<bucket_type[]>(
					block_size(b));
			}

			transaction::commit();
		}
#endif
	}

	/** Pointer to the table of blocks */
	table_pointer my_table;

	/** Segment index */
	segment_index_t my_seg;
}; /* End of class segment_facade_impl */

/**
 * Base class of concurrent_hash_map.
 * Implements logic not dependant to Key/Value types.
 */
class hash_map_base {
public:
	/** Size type. */
	using size_type = size_t;

	/** Type of a hash code. */
	using hashcode_t = size_t;

	/** Node base type. */
	using node_base = hash_map_node_base;

	/** Node base pointer. */
	using node_base_ptr_t = detail::persistent_pool_ptr<node_base>;

	/** tmp node pointer. */
	using tmp_node_ptr_t = persistent_ptr<node_base>;

	/** Bucket type. */
	struct bucket {
#if LIBPMEMOBJ_CPP_USE_TBB_RW_MUTEX
		/** Mutex type for buckets. */
		using mutex_t = pmem::obj::experimental::v<tbb::spin_rw_mutex>;

		/** Scoped lock type for mutex. */
		using scoped_t = tbb::spin_rw_mutex::scoped_lock;
#else
		/** Mutex type. */
		using mutex_t = pmem::obj::shared_mutex;

		/** Scoped lock type for mutex. */
		using scoped_t = shared_mutex_scoped_lock;
#endif

		/** Bucket mutex. */
		mutex_t mutex;

		/** Atomic flag to indicate if bucket rehashed */
		p<std::atomic<bool>> rehashed;

		/** List of the nodes stored


 400600:	b9460842 	ldr	w2, [x2, #1544]
  400604:	f9400021 	ldr	x1, [x1]
  400608:	9278dc21 	and	x1, x1, #0xffffffffffffff00
  40060c:	f9000001 	str	x1, [x0]
  400610:	34000cc2 	cbz	w2, 4007a8 <__libc_start_main+0x348>
  400614:	f00004e0 	adrp	x0, 49f000 <__sys_errlist_internal+0x320>
  400618:	f9468c00 	ldr	x0, [x0, #3352]
  40061c:	b4000040 	cbz	x0, 400624 <__libc_start_main+0x1c4>
  400620:	d503201f 	nop
  400624:	f00004e1 	adrp	x1, 49f000 <__sys_errlist_internal+0x320>
  400628:	f00004e0 	adrp	x0, 49f000 <__sys_errlist_internal+0x320>
  40062c:	f9431021 	ldr	x1, [x1, #1568]
  400630:	f9400421 	ldr	x1, [x1, #8]
  400634:	f9008c01 	str	x1, [x0, #280]
  400638:	b40000b5 	cbz	x21, 40064c <__libc_start_main+0x1ec>
  40063c:	d2800002 	mov	x2, #0x0                   	// #0
  400640:	d2800001 	mov	x1, #0x0                   	// #0
  400644:	aa1503e0 	mov	x0, x21
  400648:	9400172c 	bl	4062f8 <__cxa_atexit>
  40064c:	f00004e2 	adrp	x2, 49f000 <__sys_errlist_internal+0x320>
  400650:	b9406fa0 	ldr	w0, [x29, #108]
  400654:	f94033a1 	ldr	x1, [x29, #96]
  400658:	f9462c42 	ldr	x2, [x2, #3160]
  40065c:	f9400042 	ldr	x2, [x2]
  400660:	94007aa4 	bl	41f0f0 <__libc_init_first>
  400664:	b40000b4 	cbz	x20, 400678 <__libc_start_main+0x218>
  400668:	d2800002 	mov	x2, #0x0                   	// #0
  40066c:	d2800001 	mov	x1, #0x0                   	// #0
  400670:	aa1403e0 	mov	x0, x20
  400674:	94001721 	bl	4062f8 <__cxa_atexit>
  400678:	f00004e0 	adrp	x0, 49f000 <__sys_errlist_internal+0x320>
  40067c:	f9463c00 	ldr	x0, [x0, #3192]
  400680:	b9400000 	ldr	w0, [x0]
  400684:	34000040 	cbz	w0, 40068c <__libc_start_main+0x22c>
  400688:	94000090 	bl	4008c8 <__libc_check


 = DB.Self.Exec(
					`REPLACE INTO tb_passwords(
						ip, port, bk_cloud_id, bk_biz_id, username, password, component, operator, lock_until
					) VALUES (?, ?, ?, ?, ?, ?, ?, ?, date_add(now(), INTERVAL ? hour))`,
					address.Ip, address.Port, *cluster.BkCloudId, *cluster.BkBizId,
					m.UserName, encrypt, m.Component, m.Operator, m.LockHour,
				)
			} else {
				result = DB.Self.Exec(
					`REPLACE INTO tb_passwords(
						ip, port, bk_cloud_id, bk_biz_id, username, password, component, operator
					) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
					address.Ip, address.Port, *cluster.BkCloudId, *cluster.BkBizId,
					m.UserName, encrypt, m.Component, m.Operator,
				)
			}
			if result.Error != nil {
				notOK.Addresses = append(notOK.Addresses, address)
				slog.Error("msg", "replace into tb_passwords error", result.Error)
				AddError(errMsg, hostPort, result.Error)
				continue
			}
			// 录入正确日志
			ok.Addresses = append(ok.Addresses, address)
		}
		if len(ok.Addresses) > 0 {
			successList = append(successList, ok)
		}
		if len(notOK.Addresses) > 0 {
			failList = append(failList, notOK)
		}
	}
	if len(successList) > 0 {
		AddResource(success, OneCluster{cluster.BkCloudId, cluster.ClusterType, cluster.BkBizId,
			successList})
	}
	if len(failList) > 0 {
		AddResource(fail, OneCluster{cluster.BkCloudId, cluster.ClusterType, cluster.BkBizId,
			failList})
	}
}

// ModifyAdminPasswordForMysql 专属mysql 修改admin密码函数
func (m *ModifyAdminUserPasswordPara) ModifyAdminPasswordForMysql(
	psw string,
	encrypt string,
	cluster OneCluster,
	errMsg *Err,
	success *Resource,
	fail *Resource,
) {
	var successList []InstanceList
	var failList []InstanceList
	for _, instanceList := range cluster.MultiRoleInstanceLists {
		var base []string
		ok := InstanceList{instanceList.Role, []IpPort{}}
		notOK := InstanceList{instanceList.Role, []IpPort{}}
		role := instanceList.Role
		if *cluster.ClusterType == tendbcluster && role == tdbctl {
			base = append(base /*flushPriv,*/, setBinlogOff, setTcAdminOFF)
		} else {
			base = append(base /*flushPriv,*/, setBinlogOff)
		}
		for _, address := range instanceList.Addresses {
			// 获取修改密码的语句
			sqls := base
			hostPort := fmt.Sprintf("%s:%d", address.Ip, address.Port)
			mysqlVersion, err := GetMySQLVersion(hostPort, *cluster.BkCloudId)
			if err != nil {
				notOK.Addresses = append(notOK.Addresses, address)
				slog.Error("mysqlVersion", err)
				AddError(errMsg, hostPort, err)
				continue
			}
			userLocalhost := fmt.Sprintf("GRANT ALL PRIVILEGES ON *.* TO '%s'@'localhost' "+
				"IDENTIFIED BY '%s' WITH GRANT OPTION", m.UserName, psw)
			userIp := fmt.Sprintf("GRANT ALL


128#36,<g9=reg128#1,>r9=reg128#2
# asm 2: vpmuludq <f2_stack=560(%rsp),<g9=%xmm0,>r9=%xmm1
vpmuludq 560(%rsp),%xmm0,%xmm1

# qhasm: 2x m1 += r9
# asm 1: paddq <r9=reg128#2,<m1=reg128#6
# asm 2: paddq <r9=%xmm1,<m1=%xmm5
paddq %xmm1,%xmm5

# qhasm: 2x r9 = g9 * f3_2_stack
# asm 1: vpmuludq <f3_2_stack=stack128#38,<g9=reg128#1,>r9=reg128#2
# asm 2: vpmuludq <f3_2_stack=592(%rsp),<g9=%xmm0,>r9=%xmm1
vpmuludq 592(%rsp),%xmm0,%xmm1

# qhasm: 2x m2 += r9
# asm 1: paddq <r9=reg128#2,<m2=reg128#8
# asm 2: paddq <r9=%xmm1,<m2=%xmm7
paddq %xmm1,%xmm7

# qhasm: 2x r9 = g9 * f4_stack
# asm 1: vpmuludq <f4_stack=stack128#40,<g9=reg128#1,>r9=reg128#2
# asm 2: vpmuludq <f4_stack=624(%rsp),<g9=%xmm0,>r9=%xmm1
vpmuludq 624(%rsp),%xmm0,%xmm1

# qhasm: 2x m3 += r9
# asm 1: paddq <r9=reg128#2,<m3=reg128#9
# asm 2: paddq <r9=%xmm1,<m3=%xmm8
paddq %xmm1,%xmm8

# qhasm: 2x r9 = g9 * f5_2_stack
# asm 1: vpmuludq <f5_2_stack=stack128#42,<g9=reg128#1,>r9=reg128#2
# asm 2: vpmuludq <f5_2_stack=656(%rsp),<g9=%xmm0,>r9=%xmm1
vpmuludq 656(%rsp),%xmm0,%xmm1

# qhasm: 2x m4 += r9
# asm 1: paddq <r9=reg128#2,<m4=reg128#10
# asm 2: paddq <r9=%xmm1,<m4=%xmm9
paddq %xmm1,%xmm9

# qhasm: 2x r9 = g9 * f6_stack
# asm 1: vpmuludq <f6_stack=stack128#44,<g9=reg128#1,>r9=reg128#2
# asm 2: vpmuludq <f6_stack=688(%rsp),<g9=%xmm0,>r9=%xmm1
vpmuludq 688(%rsp),%xmm0,%xmm1

# qhasm: 2x m5 += r9
# asm 1: paddq <r9=reg128#2,<m5=reg128#11
# asm 2: paddq <r9=%xmm1,<m5=%xmm10
paddq %xmm1,%xmm10

# qhasm: 2x r9 = g9 * f7_2_stack
# asm 1: vpmuludq <f7_2_stack=stack128#46,<g9=reg128#1,>r9=reg128#2
# asm 2: vpmuludq <f7_2_stack=720(%rsp),<g9=%xmm0,>r9=%xmm1
vpmuludq 720(%rsp),%xmm0,%xmm1

# qhasm: 2x m6 += r9
# asm 1: paddq <r9=reg128#2,


Entry } from "../../../../interface/core/operator";

class CPUUnary extends OperatorImpl {
  constructor(
    private op: (value: number) => number,
    private allowDataTypes: DataType[]
  ) {
    super("cpu");
  }

  async run(context: WebDNNCPUContext, inputs: Tensor[]): Promise<Tensor[]> {
    context.assertsCPUTensorArray(inputs);
    const input = inputs[0];
    if (!this.allowDataTypes.includes(input.dataType)) {
      throw new Error(`Unary: DataType ${input.dataType} not supported`);
    }
    const newData = new DataArrayConstructor[input.dataType](input.data.length),
      { op } = this;
    for (let i = 0; i < newData.length; i++) {
      newData[i] = op(input.data[i]);
    }
    const output = context.emptyTensor(input.dims, input.dataType, newData);
    return [output];
  }
}

export function getOpEntries(): OperatorEntry[] {
  return [
    {
      opType: "Abs",
      backend: "cpu",
      opsetMin: 1,
      factory: () =>
        new CPUUnary((value) => Math.abs(value), ["float32", "int32"]),
    },
    {
      opType: "Acos",
      backend: "cpu",
      opsetMin: 1,
      factory: () => new CPUUnary((value) => Math.acos(value), ["float32"]),
    },
    {
      opType: "Acosh",
      backend: "cpu",
      opsetMin: 1,
      factory: () => new CPUUnary((value) => Math.acosh(value), ["float32"]),
    },
    {
      opType: "Asin",
      backend: "cpu",
      opsetMin: 1,
      factory: () => new CPUUnary((value) => Math.asin(value), ["float32"]),
    },
    {
      opType: "Asinh",
      backend: "cpu",
      opsetMin: 1,
      factory: () => new CPUUnary((value) => Math.asinh(value), ["float32"]),
    },
    {
      opType: "Atan",
      backend: "cpu",
      opsetMin: 1,
      factory: () => new CPUUnary((value) => Math.atan(value), ["float32"]),
    },
    {
      opType: "Atanh",
      backend: "cpu",
      opsetMin: 1,
      factory: () => new CPUUnary((value) => Math.atanh(value), ["float32"]),
    },
    {
      opType: "Ceil",
      backend: "cpu",
      opsetMin: 1,
      factory: () => new CPUUnary((value) => Math.ceil(value), ["float32"]),
    },
    {
      opType: "Cos",
      backend: "cpu",
      opsetMin: 1,
      factory: () => new CPUUnary((value) => Math.cos(value), ["float32"]),
    },
    {
      opType: "Cosh",
      backend: "cpu",
      opsetMin: 1,
      factory: () => new CPUUnary((value) => Math.cosh(value), ["float32"]),
    },
    {
      opType: "Exp",
      backend: "cpu",
      opsetMin: 1,
      factory: () => new CPUUnary((value) => Math.exp(value), ["float32"]),
    },
    {
      opType: "Floor",
      backend: "cpu",
      opsetMin: 1,
      factory: () => new CPUUnary((value) => Math.floor(value), ["float32"]),
    },
    {
      opType: "HardSwish",
      backend: "cpu",
      opsetMin: 1,
      factory: () =>
        new CPUUnary(
          (value) => {
            if (value <= -3) {
              return 0;
            } else if (value >= 3) {
              return value;
            } else {
              return (value * (value + 3)) / 6;
            }
          },
          ["float32"]
        ),
    },


# Copyright (C) 2022-2025 Intel Corporation
# LIMITED EDGE SOFTWARE DISTRIBUTION LICENSE

"""This module contains helpers for the media repo"""

from typing import Any

from iai_core.entities.image import Image, NullImage
from iai_core.entities.video import NullVideo, Video
from iai_core.repos.mappers.mongodb_mappers.id_mapper import IDToMongo

from geti_types import ID

def get_paginated_media_aggr_query(
    page_size: int,
    skip_token: ID,
    skip_object: Image | Video,
) -> Any:
    """
    Build a MongoDB aggregation pipeline to fetch media with pagination.

    The query does:
        - exclude elements before the skip object
        - sort the elements
        - limit to page size

    :param page_size: max number of elements to return
    :param skip_token: ID for pagination; only retrieve media with ID > skiptoken
    :param skip_object: object corresponding ot the skiptoken
    """
    match_dict = {}

    if not isinstance(skip_object, NullImage | NullVideo):
        skip_item = skip_object.name
        match_dict = {
            "$or": [
                # after skip item
                {"name": {"$gt": skip_item}},
                # same as skip item, but greater ID
                {
                    "$and": [
                        {"name": {"$eq": skip_item}},
                        {"_id": {"$gt": IDToMongo.forward(skip_token)}},
                    ]
                },
            ]
        }

    return [
        {"$match": match_dict},
        {"$sort": {"name": 1, "_id": 1}},
        {"$limit": page_size},
    ]


 make(map[types.FileContractID]struct{})
	for _, s := range ss {
		for _, shard := range s.Shards {
			for _, fcids := range shard.Contracts {
				for _, fcid := range fcids {
					if _, exists := added[fcid]; !exists {
						added[fcid] = struct{}{}
						usedContracts = append(usedContracts, fcid)
					}
				}
			}
		}
	}
	return usedContracts
}

// stripedSplit splits data into striped data shards, which must have sufficient
// capacity.
func stripedSplit(data []byte, dataShards [][]byte) {
	buf := bytes.NewBuffer(data)
	for off := 0; buf.Len() > 0; off += rhpv4.LeafSize {
		for _, shard := range dataShards {
			copy(shard[off:], buf.Next(rhpv4.LeafSize))
		}
	}
}

// stripedJoin joins the striped data shards, writing them to dst. The first 'skip'
// bytes of the recovered data are skipped, and 'writeLen' bytes are written in
// total.
func stripedJoin(dst io.Writer, dataShards [][]byte, skip, writeLen int) error {
	for off := 0; writeLen > 0; off += rhpv4.LeafSize {
		for _, shard := range dataShards {
			if len(shard[off:]) < rhpv4.LeafSize {
				return reedsolomon.ErrShortData
			}
			shard = shard[off:][:rhpv4.LeafSize]
			if skip >= len(shard) {
				skip -= len(shard)
				continue
			} else if skip > 0 {
				shard = shard[skip:]
				skip = 0
			}
			if writeLen < len(shard) {
				shard = shard[:writeLen]
			}
			n, err := dst.Write(shard)
			if err != nil {
				return err
			}
			writeLen -= n
		}
	}
	return nil
}
package stores

import (
	"context"
	"errors"
	"fmt"
	"path/filepath"
	"strings"
	"testing"
	"time"

	"go.sia.tech/core/types"
	"go.sia.tech/renterd/v2/api"
	isql "go.sia.tech/renterd/v2/internal/sql"
	"go.sia.tech/renterd/v2/object"
	"go.sia.tech/renterd/v2/stores/sql"
	"go.sia.tech/renterd/v2/stores/sql/mysql"
	"go.sia.tech/renterd/v2/stores/sql/sqlite"
	"go.uber.org/zap"

	"lukechampine.com/frand"
)

// BenchmarkArchiveContract benchmarks the performance of archiving a contract.
//
// cpu: Apple M1 Max
// BenchmarkArchiveContract-10         6087            220385 ns/op            2591 B/op         68 allocs/op
func BenchmarkArchiveContract(b *testing.B) {
	// define parameters
	contractSize := 1 << 30 // 1 GiB contract
	sectorSize := 4 << 20   // 4 MiB sector
	numSectors := contractSize / sectorSize

	// create database
	db, err := newTestDB(context.Background(), b.TempDir())
	if err != nil {
		b.Fatal(err)
	}

	// prepare host
	hk := types.PublicKey{1}
	err = insertHost(db.DB(), hk)
	if err != nil {
		b.Fatal(err)
	}

	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		b.StopTimer()
		fcid := generateFileContractID(i)
		if _, err := insertContract(db.DB(), hk, fcid, numSectors); err != nil {
			b.Fatal(err)
		}
		b.StartTimer()

		if err := db.T


ition: absolute;
    top: 0;
    left: 0;
    height: 20px;
    width: 20px;
    background-color: #DDE6ED;
}

.filter-checkbox:hover input~.checkmark {
    background-color: #9DB2BF;
}

.filter-checkbox input:checked~.checkmark {
    background-color: #DDE6ED;
}

.checkmark:after {
    content: "";
    position: absolute;
    display: none;
}

.filter-checkbox input:checked~.checkmark:after {
    display: block;
}

/* Style the checkmark/indicator */
.filter-checkbox .checkmark:after {
    left: 6px;
    top: 1px;
    width: 5px;
    height: 10px;
    border: solid #526D82;
    border-width: 0 3px 3px 0;
    -webkit-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    transform: rotate(45deg);
}

.toggle-container {
    width: 180px !important;
    text-align: center;
    padding-bottom: 55px;
    display: flex;
    justify-content: center;
}

/* Style toggle between ad-hoc and dropdown search */
.toggle-container,
.toggle-switch {
    cursor: pointer;
    width: 160px;
    height: 45px;
    font-size: 14px;
}

.toggle-container input[type="checkbox"] {
    display: none;
}

.toggle-container input[type="checkbox"]:checked~label .toggle-switch:before {
    content: attr(data-unchecked);
    left: 0;
}

.toggle-container input[type="checkbox"]:checked~label .toggle-switch:after {
    content: attr(data-checked);
    -webkit-transform: translate3d(100%, 0, 0);
    transform: translate3d(100%, 0, 0);
}

.toggle-switch {
    position: relative;
    background: #DDE6ED;
    border-radius: 5px;
    box-shadow: 0 0 0px #DDE6ED;
    transition: all 1s ease-in-out;
}

.toggle-switch:before,
.toggle-switch:after {
    position: absolute;
    height: calc(100% - 4px);
    width: calc(50% - 2px);
    top: 2px;
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
}

.toggle-switch:before {
    content: attr(data-checked);
    color: #526D82;
    left: 50%;
    font-family: 'Montserrat', sans-serif;
}

.toggle-switch:after {
    content: attr(data-unchecked);
    left: 2px;
    border-radius: 5px;
    z-index: 1;
    background: #27374D;
    transform: translate3d(0, 0, 0);
    transition: transform 0.3s cubic-bezier(0, 1, 0.5, 1);
    color: #DDE6ED;
    font-family: 'Montserrat', sans-serif;
}

.toggle-switch:hover:after {
    box-shadow: 0 0 7.5px #DDE6ED;
}/**
 * Admonition-based toggles
 */

/* Visibility of the target */
.admonition.toggle .admonition-title ~ * {
    transition: opacity .3s, height .3s;
}

/* Toggle buttons inside admonitions so we see the title */
.admonition.toggle {
    position: relative;
}

/* Titles should cut off earlier to avoid overlapping w/ button */
.admonition.toggle .admonition-title {
    padding-right: 25%;
    cursor: pointer


rrow

    let (body, incr) = parse_expression(&tokens[idx..]);
    if let Err(body) = body {
        return (Err(body), 0);
    }
    idx += incr;

    (
        Ok(Node::FunctionLiteralNode {
            arguments,
            body: Box::new(body.unwrap()),
            position: tokens[0].position,
        }),
        idx,
    )
}

fn parse_function_call(function: Node, tokens: &[lexer::Tok]) -> (Result<Node, error::Err>, usize) {
    let mut idx = 1;
    let mut arguments: Vec<Node> = Vec::new();

    guard_unexpected_input_end!(tokens, idx);

    while tokens[idx].kind != lexer::Token::RightParen {
        let (expr, incr) = parse_expression(&tokens[idx..]);
        if let Err(expr) = expr {
            return (Err(expr), 0);
        }

        idx += incr;
        arguments.push(expr.unwrap());

        guard_unexpected_input_end!(tokens, idx);
    }

    idx += 1; // GoInk: RightParen

    (
        Ok(Node::FunctionCallNode {
            function: Box::new(function),
            arguments,
        }),
        idx,
    )
}
<reponame>skatsuta/rust-book
fn main() {
    iterator_sum();

    {
        let v1 = vec![1, 2, 3];
        let v2: Vec<_> = v1.iter().map(|x| x + 1).collect();
        assert_eq!(v2, vec![2, 3, 4]);
    }
}

fn iterator_sum() {
    let v1 = vec![1, 2, 3];
    let total: i32 = v1.iter().sum();
    assert_eq!(total, 6);
}
<filename>day-13/part-1/jd.rs
use std::env::args;
use std::time::Instant;

fn main() {
    let now = Instant::now();
    let output = run(&args().nth(1).expect("Please provide an input"));
    let elapsed = now.elapsed();
    println!("_duration:{}", elapsed.as_secs_f64() * 1000.);
    println!("{}", output);
}

fn run(input: &str) -> usize {
    let mut lines = input.lines();
    let start = lines.next().unwrap().parse::<usize>().unwrap();

    let (closest_id, waiting_time) = lines
        .next()
        .unwrap()
        .split(',')
        .filter(|&item| item != "x")
        .map(|id| id.parse::<usize>().unwrap())
        .map(|id| (id, ((start / id) + (start % id != 0) as usize) * id - start))
        .min_by(|x, y| x.1.cmp(&y.1))
        .unwrap();

    closest_id * waiting_time
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn run_test() {
        let input = "939
7,13,x,x,59,x,31,19";

        assert_eq!(run(input), 295)
    }
}
use crate::{scu::Scu, time::Bps};
use core::marker::PhantomData;
use core::ops::Deref;
use xmc1100;

pub trait Dout0Pin<USIC> {}

pub trait Dx0Pin<USIC> {
    fn number() -> u8;
}
pub trait Dx1Pin<USIC> {
    fn number() -> u8;
}
pub trait Dx2Pin<USIC> {
    fn number() -> u8;
}
pub trait Dx3Pin<USIC> {
    fn number() -> u8;
}
pub trait Dx4Pin<USIC> {
    fn number() -> u8;
}
pub trait Dx5Pin<USIC> {
    fn number() -> u8;
}

pub struct Dx0Dx3Pin<PIN, USIC> {
    _pin: PIN,
    phantom: PhantomData<USIC>,
}

impl<USIC, PIN> Dx0Pin<USIC> for Dx0Dx3Pin<PIN, USIC> {
    fn number() -> u8 {
        6
    }
}
// Common register
pub(crate) type UsicRegisterBlock = xmc1100::usic0_ch0::RegisterBlock;

pub fn dx3pin_to_dx0pin<USIC, PIN>(pin: PIN, usic: &mut USIC) -> Dx0Dx3Pin<PIN, USIC>
where
    USIC: Deref<Target = UsicRegisterBlock>,
    PIN: Dx3Pin<USIC>,
{
    usic.dx3cr.write(|w| w.dsel().bits(PIN::number()));
    Dx0Dx3Pin {
        _pin: pin,
        phantom: Phantom


�令的方法

bug梳理：
1. 思维导图保存的文件每次打开主题又会变成默认主题
2. 公网版部署udp转发和文件上传存储等
3. 内网聊天功能，如果是装了虚拟机的电脑，会出现多个虚拟网卡，内网可以看到用户但是IP不对着，发消息收不到的
4. 建议开启webDav
5. web 的甘特图保存不了
6. 场景适用性：系统默认连接gitee远程软件安装包，缺少默认读取本地安装包路径的json配置文件的打包设置选项（比如在安装时自动读取安装U盘当前目录中/或已直接打包进安装包中的mysql/nginx/php/python本地离线安装包、以及企业自用OA WebApp的本地离线安装包，无需联网，直接同步离线安装）
7. 功能完整性：安装的服务型应用（如mysql/nginx/php/python）没有跟随软件环境启动后自动启动的设置选项，依赖于服务型应用的AI Web UI、php /python应用没有创建桌面快捷方式/菜单快捷方式的入口（即：AI Web UI、php /python应用无法安装和自动开箱即用）。
8. excel读取原始文件兼容性问题
9. word读取原始文件兼容性

### 后续开发：
1. 优化内网聊天
2. 新增 权限管理 文件加密 以及远程存储服务端（企业版本）
3. 应用商店重构 陆续会新增php/node/go/java
4. 文档可上传图片

5. 文件搜索功能
6. 应用商店添加我的世界https://mc.163.com/exp/
7. 文件点存储按钮，需选择存储目录
8. 开发文档增加docker部署
9. word格式问题以及导出名字不对
10. 美化日程提醒弹窗
## GodoOS应用商店开发教程

### 快速开始
1. 下载[mysql5.7的zip包](https://downloads.mysql.com/archives/get/p/23/file/mysql-5.7.44-winx64.zip)，并解压到用户目录.godoos/run/windows/目录下，文件夹命名为mysql5.7
2. 复制本程序docs/demo/mysql5.7到用户目录.godoos/run/windows/mysql5.7目录下
3. 打开应用商店，添加应用，选择开发模式，本地路径输入mysql5.7，点击确定

### 开发条件

1. 会简单的html开发
2. 熟悉可执行文件的启动流程，然后根据如下的流程配置json文件

### 如何添加一个应用

1. 在用户目录.godoos/run/windows/下建立一个应用文件夹。
2. 一个应用需要包含两个配置文件，在应用根目录下创建`install.json`和`store.json`两个文件。 配置文件格式如下：
- install.json [样本](./demo/mysql5.7/install.json)
```json
{
    "name": "",             // string, 应用程序名称。
    "url": "",              // string, 应用程序下载地址或适配包的下载地址。
    "pkg": "",              // string, 应用程序的官方下载地址。可为空。
    "webUrl":"",            // string, 如何设置，应用程序将显示到桌面。
    "isDev": true,          // boolean, 是否为开发环境。如果设置为true将不会下载数据。
    "version": "1.0.0",     // stri


 format if format is not specified', () => {
      registry.setDefaultKey('.1f');
      const formatter = registry.get();
      expect(formatter(100)).toEqual('100.0');
    });
    it('falls back to default format if format is null', () => {
      registry.setDefaultKey('.1f');
      // @ts-ignore
      const formatter = registry.get(null);
      expect(formatter(100)).toEqual('100.0');
    });
    it('falls back to default format if format is undefined', () => {
      registry.setDefaultKey('.1f');
      const formatter = registry.get(undefined);
      expect(formatter(100)).toEqual('100.0');
    });
    it('falls back to default format if format is empty string', () => {
      registry.setDefaultKey('.1f');
      const formatter = registry.get('');
      expect(formatter(100)).toEqual('100.0');
    });
    it('removes leading and trailing spaces from format', () => {
      const formatter = registry.get(' .2f');
      expect(formatter(100)).toEqual('100.00');
      const formatter2 = registry.get('.2f ');
      expect(formatter2(100)).toEqual('100.00');
      const formatter3 = registry.get(' .2f ');
      expect(formatter3(100)).toEqual('100.00');
    });
  });
  describe('.format(format, value)', () => {
    it('return the value with the specified format', () => {
      expect(registry.format('.2f', 100)).toEqual('100.00');
      expect(registry.format(',d', 100)).toEqual('100');
    });
    it('falls back to the default formatter if the format is undefined', () => {
      expect(registry.format(undefined, 1000)).toEqual('1k');
    });
  });
});
import { AnswerQuestion } from './checklist.model';

describe('AnswerQuestion model', () => {
    it('should be able to set the question text based on key', () => {
        const answer = new AnswerQuestion('ANY_OTHER_CIRCUMSTANCES', 'no', 'Citizen');
        expect(answer.Question).toContain('Is there anything the court');
    });

    it('should throw exception on unsupported role', () => {
        let question: AnswerQuestion = null;
        expect(() => {
            question = new AnswerQuestion('ANY_OTHER_CIRCUMSTANCES', 'no', 'Judge');
        }).toThrow(new Error('Cannot find question text for unsupported role: Judge'));
    });

    it('should gracefully fall back to question key if no text exists', () => {
        const questionKey = 'ANY_OTHER_CIRCUMSTANCES_NEW';
        const answer = new AnswerQuestion(questionKey, 'no', 'Citizen');
        expect(answer.Question).toBe(questionKey);
    });
});
import {DropDownItem} from "@app/shared/components/drop-down/drop-down.component";

export class User {
  id: string;
  name: string;
  externalUserId?: string | null;
}

export function usersToDropDown(users: User[]): DropDownItem[] | null {
  if (!users) return null;
  return users.map(u => ({
    id: u.id,
    value: u.name,
  }))
}
import geodist from 'geodist';
import { DirectionsService } from "../lib/mapbox";
import { API_KEY } from "../config/mapboxConfig";
import app from '../config/firebaseConfig';
import { firestore } from "firebase";


local self = {}
GLib.Net.Layer5.SingleEndpointConnectionChannel = GLib.MakeConstructor (self, GLib.Net.ISingleEndpointChannel)

--[[
	Events:
		ConnectionActivityStateChanged (Connection connection, hasUndispatchedPackets)
			Fired when a connection's undispatched packet count decreases to 0 or increases to 1.
		ConnectionCreated (Connection connection)
			Fired when a connection has been created.
		ConnectionOpened (Connection connection)
			Fired when a connection has been opened.
		ConnectionClosed (Connection connection)
			Fired when a connection has been closed.
		ConnectionTimeoutChanged (Connection connection, timeout)
			Fired when a connection's timeout period has changed.
]]

function self:ctor (innerChannel)
	-- Identity
	self.InnerChannel = innerChannel
	self.Name = nil

	-- Packets
	self.Connections = {}

	-- Handlers
	self.OpenHandler   = handler or GLib.NullCallback
	self.PacketHandler = GLib.NullCallback

	self.InnerChannel:SetHandler (
		function (sourceId, inBuffer)
			self:HandlePacket (inBuffer)
		end
	)
end

function self:dtor ()
	self:CloseConnections ()
end

-- Identity
function self:GetInnerChannel ()
	return self.InnerChannel
end

function self:GetName ()
	return self.Name or self.InnerChannel:GetName ()
end

function self:GetRemoteId ()
	return self.InnerChannel:GetRemoteId ()
end

function self:SetRemoteId (remoteId)
	self.InnerChannel:SetRemoteId (remoteId)
	return self
end

-- State
function self:IsOpen ()
	return self.InnerChannel:IsOpen ()
end

function self:SetOpen (open)
	self.InnerChannel:SetOpen (open)
	return self
end

-- Packets
function self:CloseConnections (closureReason)
	for _, connection in pairs (self.Connections) do
		connection:Close (closureReason)
	end
end

function self:Connect (packet)
	-- New connection
	local connection = GLib.Net.Connection (self:GetRemoteId (), self:GenerateConnectionId (), self)
	connection:SetInitiator (GLib.Net.ConnectionEndpoint.Local)

	-- Register connection
	self:RegisterConnection (connection)

	-- Write packet
	if packet then
		connection:Write (packet)
	end

	return connection
end

function self:DispatchPacket (packet)
	return self:Connect (packet)
end

function self:GetMTU ()
	return self.InnerChannel:GetMTU () - 13
end

function self:HandlePacket (inBuffer)
	local connectionId = inBuffer:UInt32 ()

	local connection = self.Connections [connectionId]

	if not connection then
		-- New connection
		connection = GLib.Net.Connection (self:GetRemoteId (), connectionId, self)
		connection:SetInitiator (GLib.Net.ConnectionEndpoint.Remote)

		-- Register connection
		self:RegisterConnection (connection)
	end

	connection:HandlePacket (inBuffer)
end

-- Handlers
function self:GetHandler ()
	return self:GetOpenHandler ()
end

function self:GetOpenHandler ()
	return self.OpenHandler
end

function self:GetPacketHandler ()
	return self.PacketHandler
end

function self:SetHandler (handler)
	return self:SetOpenHandler (handler)
end

function self:SetOpenHandler (openHandler)
	self.OpenHandle


date,
      fileName
    );
    console.log({ rawData });
  }

  // console.log(`row: ${rawData.row} ${rawData.hour}:${rawData.minute}`);
  return rawData;
}

function extractCells(
  worksheet: WorkSheet,
  row: number,
  settings: MonthlyInterruptionSettings
): MonthlyInterruptionCells {
  //Builds the raw cell location {column, row}
  let dateAddress = { c: settings.dateCol, r: row };
  let feederAddress = { c: settings.feederCol, r: row };
  let durationAddress = { c: settings.durationCol, r: row };

  //Builds the encoded cell location {"A1", "B2"} to extract from worksheet
  let dateRef = XLSX.utils.encode_cell(dateAddress);
  let feederRef = XLSX.utils.encode_cell(feederAddress);
  let durationRef = XLSX.utils.encode_cell(durationAddress);

  return {
    feeder: worksheet[feederRef],
    date: worksheet[dateRef],
    duration: worksheet[durationRef],
    row,
  };
}

const MonthlyInterruptionExcelUtil = Object.freeze({
  extractRawDatasFromWorkbook,
});

export default MonthlyInterruptionExcelUtil;
import { ValueOf } from 'typeHelpers';
import { GameMessages, GameStates, Messages } from '../constants';
import { AppDispatch } from './types';

export const ActionTypes = {
  Restart: 'game/Restart',
  // Called when a new pattern is being generated
  SetPattern: 'game/SetPattern',
  StartPlayback: 'game/StartPlayback',
  AwaitInput: 'game/AwaitInput',
  // this calls middleware?
  // Specific action to update user square choice during game play
  UpdateUserInput: 'game/UpdateUserInput',
  // Generic action to update some field on the game state
  UpdateGameField: 'game/UpdateGameField',
  UpdateGame: 'game/UpdateGame',
  PatternMatchError: 'game/PatternMatchError',
  IncrementPattern: 'game/incrementPattern',
};

export type AppAction = {
  type: ValueOf<typeof ActionTypes>;
  payload: Record<string, any>;
};

// Action creators
export const buildAppActions = (dispatch: AppDispatch) => {
  const actions = {
    restart() {
      dispatch({ type: ActionTypes.Restart, payload: {} });
    },
    awaitUserInput() {
      dispatch({
        type: ActionTypes.UpdateGame,
        payload: {
          update: {
            gameState: GameStates.Input,
            gameMessage: Messages[GameMessages.Input],
          },
        },
      });
    },
    initializePattern() {
      dispatch({ type: ActionTypes.SetPattern, payload: {} });
      dispatch({
        type: ActionTypes.UpdateGame,
        payload: {
          update: {
            gameState: GameStates.PlayBackPattern,
            gameMessage: Messages[GameMessages.PlayingBack],
          },
        },
      });
    },
    incrementPattern() {
      dispatch({ type: ActionTypes.IncrementPattern, payload: {} });
      dispatch({
        type: ActionTypes.UpdateGame,
        payload: {
          update: {
            gameState: GameStates.PlayBackPattern,
            gameMessage: Messages[GameMessages.PlayingBack],
          },
        },
      });
    },
    setPlayback() {
      dispatch({
        type: ActionTypes.UpdateGame,
        payload: {
          update: {
            gameState: GameStates.PlayBackPattern,
            gameMessage: Messages[GameMessages.PlayingBack],
          },
        },
      });
    },
    patternMatchError() {
      dispatch({
        type: ActionTypes.PatternMatchError,
        payload: {
          gameState: GameStates.PatternMatchError,


05f-b22d-a900758123a0"
	m["/18-year-old-nymph361s-1st-live-3some/"] = "5084adb9-2568-5f27-abff-d72c2f7d9df6"
	m["/mini-mitzi-has-hot-outift-for-fuck/"] = "7b86871d-7be3-5cbd-af85-fde6029b3e9b"
	m["/trans-magic-glasses/"] = "e8ea4e1e-2ad2-599c-bcc8-0569165f172f"
	m["/slippery-when-wet-tight-horny-chicks-vr-threesome/"] = "16a59c09-fe7d-55a3-be24-81731306edcc"
	m["/sabdeluxe-sauna-fun/"] = "5ed8d3ea-d06f-530a-9cc0-0adc7939cfb1"
	m["/red-light-special-part-1/"] = "e302392e-b0a9-50d0-a2d4-451d0a7ac012"
	m["/tamsin-messy-custard-madness/"] = "15eabce0-f7b2-530b-81eb-0714e4003bbd"
	m["/my-hero-academia-thick-rumi-usagiyama-missionary/"] = "98c392ce-c0ab-56ca-a454-735b849497a4"
	m["/i-dream-of-tiffany/"] = "9e4e8916-614d-5218-a8ca-fba117ffc367"
	m["/mina-k-satin-nightie/"] = "dba605ec-7b07-5a3b-a681-6de93f0e41aa"
	m["/lazy-student-gets-sex-chance/"] = "ff454ed4-e0d7-5b51-aa1a-32e7ff1e2924"
	m["/my-hot-little-stepsister-tries-on-her-short-shorts-thongs-for-you/"] = "7f088e05-d9a0-5545-bf2a-598ecaf79737"
	m["/very-sweet-blowjob-with-novella-night/"] = "5a33c0df-88bb-56b9-9c21-546595f88dc7"
	m["/the-backpacking-trip-of-a-lifetime/"] = "571f4f9d-a3ce-55ab-bfc4-46424d8a3f40"
	m["/aloida-lets-bleika-bang-out-her-pussy-with-rainbow-dildo/"] = "1e622a50-b672-5f39-9736-54e227bec5ec"
	m["/the-best-blowjob-compilation/"] = "35985f1b-ae01-5d60-8c4e-0746f3d23470"
	m["/claire-teases-every-drop-out-of-your-cum-hardcore-directors-cut/"] = "2456ccf7-e4fb-5afe-96a3-fc72c2e6679d"
	m["/ashley-dark-solo/"] = "cad45a2e-fa0d-5260-972b-c26d4d723bf9"
	m["/skinny-french-babe-candie-luciani-gets-pounded/"] = "0417e982-b156-5859-9a82-16c6c9158c71"
	m["/febby-likes-to-show-off-her-curves/"] = "bf21f3fe-1eb2-5853-bd8e-eefff73f1e02"


}
};

static const AVClass dash_class = {
    .class_name = "dash",
    .item_name  = av_default_item_name,
    .option     = dash_options,
    .version    = LIBAVUTIL_VERSION_INT,
};

const FFInputFormat ff_dash_demuxer = {
    .p.name         = "dash",
    .p.long_name    = NULL_IF_CONFIG_SMALL("Dynamic Adaptive Streaming over HTTP"),
    .p.priv_class   = &dash_class,
    .p.flags        = AVFMT_NO_BYTE_SEEK,
    .priv_data_size = sizeof(DASHContext),
    .flags_internal = FF_INFMT_FLAG_INIT_CLEANUP,
    .read_probe     = dash_probe,
    .read_header    = dash_read_header,
    .read_packet    = dash_read_packet,
    .read_close     = dash_close,
    .read_seek      = dash_read_seek,
};


': 'Перенос с pay-as-you-go на контракт на фиксированные расходы.'
'keywords':
- 'marketplace'
- 'billing'
- 'PAYG'
- 'pay-as-you-go'
- 'committed spend contract'
'doc_type': 'guide'
---
# Перевод выставления счетов с pay-as-you-go (PAYG) на контракт с обязательными затратами в облачном маркетплейсе {#migrate-payg-to-committed}

Если ваша организация ClickHouse в данный момент выставляется счет через активную подписку (или заказ) pay-as-you-go (PAYG) в облачном маркетплейсе, и вы хотите перейти на выставление счетов через контракт с обязательными затратами в том же облачном маркетплейсе, пожалуйста, примите свое новое предложение, а затем выполните следующие шаги в зависимости от вашего облачного провайдера.

## Важные замечания {#important-notes}

Обратите внимание, что отмена вашей подписки PAYG в маркетплейсе не удаляет вашу учетную запись ClickHouse Cloud - только финансовые отношения через маркетплейс. После отмены наша система прекратит выставление счетов за услуги ClickHouse Cloud через маркетплейс. (Примечание: этот процесс не является мгновенным и может занять несколько минут).

После отмены вашей подписки в маркетплейсе, если у вашей организации ClickHouse есть кредитная карта в файле, мы спишем с этой карты средства в конце вашего расчетного периода - если только до этого времени не будет подключена новая подписка в маркетплейсе.

Если после отмены не будет настроена кредитная карта, у вас будет 14 дней, чтобы добавить либо действующую кредитную карту, либо новую подписку в облачном маркетплейсе для вашей организации. Если в этот период не будет настроен способ оплаты, ваши услуги будут приостановлены, и ваша организация будет считаться не соответствующей [требованиям выставления счетов](/manage/clickhouse-cloud-billing-compliance).

Любое использование, накопленное после отмены подписки, будет выставлено счет по следующему настроенному действительному способу оплаты - либо предоплаченной кредитной картой, подписке в маркетплейсе, либо кредитной карте в этом порядке.

Если у вас есть вопросы или требуется поддержка по настройке вашей организации на новую подписку в маркетплей


"Arikara es una criatura mortífera contra la que hay que actuar con rapidez. Para poder atraparla tendrás que encender el fuego sagrado de la vida, que hará que Arikara aparezca.","Ve y recoge pitas incendiarias, una planta poco común. Cuando tengas suficientes pitas, pide consejo a Magatha Tótem Siniestro en el Alto de los Ancestros de Cima del Trueno. Ella es una poderosa chamán que puede encantar la planta y obtener así unos polvos con los que encender el fuego.","Viaja en dirección noreste hasta Poza Hirviendo y recoge pitas incendiarias."}, {"Recoge 10 pitas incendiarias y después pide consejo a Magatha Tótem Siniestro en el Alto de los Ancestros de Cima del Trueno."}},
[5063] = {"Almete del Sabio Escarlata", {"No encontrarás un almete más delicado. ¡Con el pellejo de la Bestia prístino, nuestros expertos artesanos crearán el tocado más fantástico con el que podría soñar un prestidigitador!","Tráenos cincuenta piezas de oro y los objetos de la lista y tu cabeza será agraciada con el Almete del Sabio Escarlata.","*El pellejo de la Bestia prístino.","*Costuras desgarradas de abominación.","*Cristales Arcanos.","*Hilo escarlata encantado.","¡CONTÉMPLALO!"}, {"Para crear el Almete del Sabio Escarlata deberás llevarle los siguientes objetos a Malyfous Martilloscuro: 1 pellejo de la Bestia prístino; 5 costuras desgarradas de abominación; 8 cristales Arcanos; 5 hilos escarlata encantados.","También tendrás que pagar 50 piezas de oro para la elaboración del almete."}},
[5064] = {"Espiando a los Tótem Siniestro", {"<nombre>, nos has servido con diligencia en el pasado por lo que ahora te confío una importante misión. El clan Tótem Siniestro está tramando algo. Sabemos que tres agentes de origen desconocido se han estado reuniendo con los Tótem Siniestro durante las últimas semanas. Descubrimos que hay varios cofres en Cumbre de la Nube Negra que contienen mensajes reveladores.","<nombre>, si tienes éxito en esta peligrosa misión, te recompensaré debidamente."}, {"Busca y consigue las tres notas secretas en la Cumbre de la Nube Negra"}},
[5065] = {"Las tablillas perdidas Mosh'aru", {"El trol con el que has hablado no te ha dicho la verdad. Es cierto que las dos tablillas que conseguiste para él explican el modo de retener la esencia de Hakkar, pero la leyenda no acaba ahí. Llevo mucho tiempo investigando y he descubierto que existen seis tablillas Mosh'aru y no dos. ¡Seis!","Y mucho me temo que los secretos que albergan no serán de nuestro agrado...","Localiza la tercera y cuarta tablillas Mosh'aru. Se encuentran en las Tierras de la Peste del Este en posesión de los trols Fustamusgo. Encuéntralas y tráemelas aquí."}, {"Llévale la tercera y cuarta tablillas Mosh'aru al prospector Ferrobota, que está en Tanaris."}},
[5066] = {"Un llamamiento a las armas: las Tierras de la Peste", {"¡Atención, atención! ¡Atención todos los héroes!","¡El Reino de Ventormenta ha hecho una llamada a las armas! ¡Tomad


動',	'回民暴動'},
{'5769',	'噦',	'噦'},
{'5770',	'繢',	'繢'},
{'5771',	'毀滅步兵',	'毀滅步兵'},
{'5772',	'毀滅騎士',	'毀滅騎士'},
{'5773',	'毀滅射手',	'毀滅射手'},
{'5774',	'昏迷圖騰',	'昏迷圖騰'},
{'5775',	'混亂的圖騰',	'混亂的圖騰'},
{'5776',	'活動',	'活動'},
{'5777',	'擊倒圖騰',	'擊倒圖騰'},
{'5778',	'擊傷的圖騰',	'擊傷的圖騰'},
{'5779',	'鶏毛信文匯',	'鶏毛信文匯'},
{'5780',	'姬勝德',	'姬勝德'},
{'5781',	'積克館',	'積克館'},
{'5782',	'賈廷安',	'賈廷安'},
{'5783',	'賈育台',	'賈育台'},
{'5784',	'戔',	'戔'},
{'5785',	'監視塔',	'監視塔'},
{'5786',	'監視塔哨兵',	'監視塔哨兵'},
{'5787',	'監視塔哨兵隊長',	'監視塔哨兵隊長'},
{'5788',	'簡肇棟',	'簡肇棟'},
{'5789',	'建國黨',	'建國黨'},
{'5790',	'賤B',	'賤B'},
{'5791',	'賤bi',	'賤bi'},
{'5792',	'賤比',	'賤比'},
{'5793',	'賤貨',	'賤貨'},
{'5794',	'賤種',	'賤種'},
{'5795',	'江羅',	'江羅'},
{'5796',	'江綿恒',	'江綿恒'},
{'5797',	'江戲子',	'江戲子'},
{'5798',	'江則民',	'江則民'},
{'5799',	'江澤慧',	'江澤慧'},
{'5800',	'江賊',	'江賊'},
{'5801',	'江賊民',	'江賊民'},
{'5802',	'薑春雲',	'薑春雲'},
{'5803',	'將則民',	'將則民'},
{'5804',	'僵賊',	'僵賊'},
{'5805',	'僵賊民',	'僵賊民'},
{'5806',	'講法',	'講法'},
{'5807',	'降低命中的圖騰',	'降低命中的圖騰'},
{'5808',	'醬豬媳',	'醬豬媳'},
{'5809',	'撟',	'撟'},
{'5810',	'狡猾的達夫',	'狡猾的


bda = newImpulse - vcp.normalImpulse;
        vcp.normalImpulse = newImpulse;

        // Apply contact impulse
        double Px = normalx * lambda;
        double Py = normaly * lambda;

        // vA -= invMassA * P;
        vA.x -= Px * mA;
        vA.y -= Py * mA;
        wA -= iA * (vcp.rA.x * Py - vcp.rA.y * Px);

        // vB += invMassB * P;
        vB.x += Px * mB;
        vB.y += Py * mB;
        wB += iB * (vcp.rB.x * Py - vcp.rB.y * Px);
      } else {
        // Block solver developed in collaboration with Dirk Gregorius (back in 01/07 on
        // Box2D_Lite).
        // Build the mini LCP for this contact patch
        //
        // vn = A * x + b, vn >= 0, , vn >= 0, x >= 0 and vn_i * x_i = 0 with i = 1..2
        //
        // A = J * W * JT and J = ( -n, -r1 x n, n, r2 x n )
        // b = vn_0 - velocityBias
        //
        // The system is solved using the "Total enumeration method" (s. Murty). The complementary
        // constraint vn_i * x_i
        // implies that we must have in any solution either vn_i = 0 or x_i = 0. So for the 2D
        // contact problem the cases
        // vn1 = 0 and vn2 = 0, x1 = 0 and x2 = 0, x1 = 0 and vn2 = 0, x2 = 0 and vn1 = 0 need to be
        // tested. The first valid
        // solution that satisfies the problem is chosen.
        //
        // In order to account of the accumulated impulse 'a' (because of the iterative nature of
        // the solver which only requires
        // that the accumulated impulse is clamped and not the incremental impulse) we change the
        // impulse variable (x_i).
        //
        // Substitute:
        //
        // x = a + d
        //
        // a := old total impulse
        // x := new total impulse
        // d := incremental impulse
        //
        // For the current iteration we extend the formula for the incremental impulse
        // to compute the new total impulse:
        //
        // vn = A * d + b
        // = A * (x - a) + b
        // = A * x + b - A * a
        // = A * x + b'
        // b' = b - A * a;

        final VelocityConstraintPoint cp1 = vc.points[0];
        final VelocityConstraintPoint cp2 = vc.points[1];
        final Vector2 cp1rA = cp1.rA;
        final Vector2 cp1rB = cp1.rB;
        final Vector2 cp2rA = cp2.rA;
        final Vector2 cp2rB = cp2.rB;
        double ax = cp1.normalImpulse;
        double ay = cp2.normalImpulse;

        assert(ax >= 0.0 && ay >= 0.0);
        // Relative velocity at contact
        // Vec2 dv1 = vB + Cross(wB, cp1.rB) - vA - Cross(wA, cp1.rA);
        double dv1x = -wB * cp1rB.y + vB.x - vA.x + wA * cp1rA.y;
        double dv1y = wB * cp1rB.x + vB.y - vA.y - wA * cp1rA.x;

        // Vec2 dv2 = vB + Cross(wB, cp2.rB) - vA - Cross(wA, cp2.rA);
        double dv2x = -wB * cp2rB.y + vB.x - vA.x +


if (defined(LEFT) && !defined(TRANSA)) || (!defined(LEFT) && defined(TRANSA))
        ldr     L , K
        ldr     r3, KK
        sub     L , L, r3
        str     L , KKK
#else
        ldr     L , KK
#ifdef LEFT
        add     L , L , #1        // number of values in AO
#else
        add     L , L , #1        // number of values in BO
#endif
        str     L , KKK
#endif

	mov	K1, L
	asrs	L , K1, #3					// L = L / 8
	ble	_L1_M1_40

_L1_M1_22:
	KERNEL1x1_SUB
	KERNEL1x1_SUB
	KERNEL1x1_SUB
	KERNEL1x1_SUB

	KERNEL1x1_SUB
	KERNEL1x1_SUB
	KERNEL1x1_SUB
	KERNEL1x1_SUB

	subs	L, L, #1
	bgt	_L1_M1_22

_L1_M1_40:

	ands	L , K1, #7					// L = L % 8
	ble	_L1_M1_100

_L1_M1_42:

	KERNEL1x1_SUB

	subs	L, L, #1
	bgt	_L1_M1_42

_L1_M1_100:

	SAVE1x1

_L1_END:

_L999:

	sub	r3, fp, #128
	vldm	r3, { d8 - d15}					// restore floating point registers

	movs	r0, #0						// set return value
	sub	sp, fp, #24
	pop	{r4 - r9, fp}
	bx	lr

	EPILOGUE


u0440\u044c"
    ],
    "WEEKENDRANGE": [
      5,
      6
    ],
    "fullDate": "EEEE, d MMMM y '\u0433'.",
    "longDate": "d MMMM y '\u0433'.",
    "medium": "d MMM y '\u0433'. H:mm:ss",
    "mediumDate": "d MMM y '\u0433'.",
    "mediumTime": "H:mm:ss",
    "short": "dd.MM.yy H:mm",
    "shortDate": "dd.MM.yy",
    "shortTime": "H:mm"
  },
  "NUMBER_FORMATS": {
    "CURRENCY_SYM": "\u20b8",
    "DECIMAL_SEP": ",",
    "GROUP_SEP": "\u00a0",
    "PATTERNS": [
      {
        "gSize": 3,
        "lgSize": 3,
        "maxFrac": 3,
        "minFrac": 0,
        "minInt": 1,
        "negPre": "-",
        "negSuf": "",
        "posPre": "",
        "posSuf": ""
      },
      {
        "gSize": 3,
        "lgSize": 3,
        "maxFrac": 2,
        "minFrac": 2,
        "minInt": 1,
        "negPre": "-",
        "negSuf": "\u00a0\u00a4",
        "posPre": "",
        "posSuf": "\u00a0\u00a4"
      }
    ]
  },
  "id": "ru-kz",
  "localeID": "ru_KZ",
  "pluralCat": function(n, opt_precision) {  var i = n | 0;  var vf = getVF(n, opt_precision);  if (vf.v == 0 && i % 10 == 1 && i % 100 != 11) {    return PLURAL_CATEGORY.ONE;  }  if (vf.v == 0 && i % 10 >= 2 && i % 10 <= 4 && (i % 100 < 12 || i % 100 > 14)) {    return PLURAL_CATEGORY.FEW;  }  if (vf.v == 0 && i % 10 == 0 || vf.v == 0 && i % 10 >= 5 && i % 10 <= 9 || vf.v == 0 && i % 100 >= 11 && i % 100 <= 14) {    return PLURAL_CATEGORY.MANY;  }  return PLURAL_CATEGORY.OTHER;}
});
}]);
//! moment.js locale configuration
//! locale : Portuguese [pt]
//! author : Jefferson : https://github.com/jalex79

import moment from '../moment';

export default moment.defineLocale('pt', {
    months : 'Janeiro_Fevereiro_Março_Abril_Maio_Junho_Julho_Agosto_Setembro_Outubro_Novembro_Dezembro'.split('_'),
    monthsShort : 'Jan_Fev_Mar_Abr_Mai_Jun_Jul_Ago_Set_Out_Nov_Dez'.split('_'),
    weekdays : 'Domingo_Segunda-Feira_Terça-Feira_Quarta-Feira_Quinta-Feira_Sexta-Feira_Sábado'.split('_'),
    weekdaysShort : 'Dom_Seg_Ter_Qua_Qui_Sex_Sáb'.split('_'),
    weekdaysMin : 'Dom_2ª_3ª_4ª_5ª_6ª_Sáb'.split('_'),
    weekdaysParseExact : true,
    longDateFormat : {
        LT : 'HH:mm',
        LTS : 'HH:mm:ss',
        L : 'DD/MM/YYYY',
        LL : 'D [de] MMMM [de] YYYY',
        LLL : 'D [de] MMMM [de] YYYY HH:mm',
        LLLL : 'dddd, D [de] MMMM [de] YYYY HH:mm'
    },
    calendar : {
        sameDay: '[Hoje às] LT',


from typing import Dict, List, Optional, Set

import neo4j

from ...embeddings import EmbedderProtocol
from ...exceptions import CypherQueryNodesReadError
from .models import CypherIngestRecord, EmbedderResult
from .utils import batch_data

def embed_cypher_query_nodes(
    embedder: EmbedderProtocol,
    nodes_to_embed: List[Dict[str, str]],
    embedding_model_name: Optional[str] = None,
) -> EmbedderResult:
    result = list()
    errored = list()

    if embedding_model_name is None:
        try:
            model = embedder.model  # type: ignore[attr-defined]
        except Exception as _:
            model = None
    else:
        model = embedding_model_name

    for batch in batch_data(nodes_to_embed, 10):
        for task in batch:
            q = task.get("question")
            cql = task.get("cql")
            if q is not None and cql is not None:
                vector = embedder.embed_query(q)
                result.append(
                    CypherIngestRecord(
                        cypher_statement=cql,
                        question=q,
                        question_embedding=vector,
                        embedding_model=model,
                    )
                )
            else:
                errored.append(task)

    return {"nodes": result, "failed": errored}

def load_cypher_query_nodes(
    driver: neo4j.Driver, nodes: List[CypherIngestRecord], database: str = "neo4j"
) -> None:
    query = """
UNWIND $tasks as task
MERGE (n:CypherQuery {question: task.question})
SET
    n.cypherStatement = task.cypher_statement,
    n.embeddingModel = task.embedding_model
WITH task, n
CALL db.create.setNodeVectorProperty(n, 'questionEmbedding', task.question_embedding)
"""

    with driver.session(database=database) as session:
        for idx, batch in enumerate(batch_data(nodes, 10)):
            # print("batch: ", batch)
            session.run(
                query=query, parameters={"tasks": [node.model_dump() for node in batch]}
            )

def get_existing_questions(
    driver: neo4j.Driver,
    node_label: str = "CypherQuery",
    embedding_property_name: str = "cypherStatement",
    database: str = "neo4j",
) -> Set[str]:
    try:
        query = f"""
    MATCH (n:{node_label})
    WHERE n.{embedding_property_name} IS NOT NULL
    RETURN n.question AS question
    """
        with driver.session(database=database) as session:
            result = session.run(query=query)

            questions = {
                str(r.get("question"))
                for r in result.data()
                if r.get("question") is not None
            }

        return questions
    except Exception as e:
        raise CypherQueryNodesReadError(e)


SO

- How to get metadata: [kdb-meta-get(1)](kdb-meta-get.md)
- [elektra-metadata(7)](elektra-metadata.md) for an explanation of the metadata concepts.
- [elektra-key-names(7)](elektra-key-names.md) for an explanation of key names.
# kdb-stash -- Stash away KDB to be restored later

## SYNOPSIS

`kdb stash`

## DESCRIPTION

This command will stash away the `system`, `user` and `spec` configuration, i.e. it releases all mount points and reset Elektra to a clean state.
Afterwards a timestamp which can be used to restore everything will be printed.

The backup will be done in the `/var/tmp` directory, so make sure the backup is not deleted.

## EXAMPLES

```
kdb set user:/x foo
#>
#> Create a new key user:/x with string "foo"

kdb mount a.ini /a
kdb mount
#> a.ini on /a with name /a
#> none on system:/info/elektra/constants with name system:/info/elektra/constants
#> /usr/local/share/doc/elektra/CONTRACT.ini on system:/info/elektra/contract/#0 with name system:/info/elektra/contract/#0
#> none on system:/info/elektra/desktop with name system:/info/elektra/desktop
#> /usr/local/share/doc/elektra/METADATA.ini on system:/info/elektra/metadata/#0 with name system:/info/elektra/metadata/#0
#> none on system:/info/elektra/uname with name system:/info/elektra/uname

kdb backup
#> kdb restore 1500000000

kdb get user:/x
#> Did not find key

kdb mount

kdb restore 1500000000

kdb get user:/x
#> foo

kdb mount
#> a.ini on /a with name /a
#> none on system:/info/elektra/constants with name system:/info/elektra/constants
#> /usr/local/share/doc/elektra/CONTRACT.ini on system:/info/elektra/contract/#0 with name system:/info/elektra/contract/#0
#> none on system:/info/elektra/desktop with name system:/info/elektra/desktop
#> /usr/local/share/doc/elektra/METADATA.ini on system:/info/elektra/metadata/#0 with name system:/info/elektra/metadata/#0
#> none on system:/info/elektra/uname with name system:/info/elektra/uname
```

## SEE ALSO

- [kdb-restore(1)](kdb-restore.md)
- [kdb-backup(1)](kdb-backup.md)
# elektra-introduction(7) -- an introduction to Elektra

**Elektra** is a library implementing access to a global key database.
The **global key database** provides access to all configuration
files found on a system. To elektrify an application means to change
the application so that it uses Elektra afterwards.

Information on Elektra can be found on the
[website](https://www.libelektra.org).
For introduction in the terminology, make sure to read
[the glossary](elektra-glossary.md).

# Motivation

## Why Elektra?

Configurations settings are hierarchical data
structures of keys, each consisting of a name and a value. They can be
used to configure software for the user's needs. Because these settings
stay the same across restarts of the program, they need to be stored
permanently. In the beginning this was done with primitive text files.
Possibilities to structure the text were added later.

Nearly every system developed its own way to read configuration settings.
Some got a de facto standard for a desktop environment (kconfig,
gconfig) or even an operating system (Windows Registry, Open Directory).
But they have a common problem: they


ai := fmt.Sprintf("%sattr%s", oi, a.ID)
			// Loop the converted log sources
			for ls, m := range c.convertComplex(o, a) {
				// Get the log-source's scope
				scope, ok := os[ls]
				if !ok {
					scope = ObjectScope{Search: make(search.Search), Detection: sigma.Detection{Searches: make(map[string][]search.Searches)}}
				}
				// Apply selections on the scope by appending the searches
				if len(m.Selections) > 0 {
					scope.Detection.Condition = condition.AllOfPattern(fmt.Sprintf("%smapping*", ai)).And(scope.Detection.Condition)
					// Loop the searches
					for name, searches := range m.Selections {
						// Define the search identifier
						si := fmt.Sprintf("%smapping%s", ai, name)
						// Append the searches to the scope's detection
						scope.Detection.Searches[si] = []search.Searches{searches}
					}
				}
				// Apply the search on the scope by merging the keywords per field
				if len(m.Search) > 0 {
					for f, keyword := range m.Search {
						keywords, _ := scope.Search[f]
						scope.Search[f] = append(keywords, keyword)
					}
				}
				// Save the log-source's scope
				os[ls] = scope
			}
		}
		// Loop the os per log-source
		for ls, scope := range os {
			// If there is a search, merge it into the detection
			if len(scope.Search) > 0 {
				scope.Detection.Searches[oi] = []search.Searches{{scope.Search}}
				scope.Detection.Condition = condition.From(oi).And(scope.Detection.Condition)
			}
			// Merge the detection into the detections
			escope, _ := es[ls]
			escope.Detections = append(escope.Detections, scope.Detection)
			es[ls] = escope
		}
	}
	// Convert the detections into per-log-source rules
	for ls, scope := range es {
		// Convert any search into a detection
		if len(scope.Search) > 0 {
			var searches []search.Searches
			for name, words := range scope.Search {
				searches = append(searches, []search.Search{{name: words}})
			}
			scope.Detections = append(scope.Detections, sigma.Detection{
				Searches:  map[string][]search.Searches{ei: searches},
				Condition: condition.From(ei),
			})
		}
		// Define a global rule with the log-source
		rules = append(rules, &sigma.Rule{LogSource: ls, Action: "global"})
		// Follow-up with the detection rules
		for _, detection := range scope.Detections {
			// @TODO: Clean up double-nesting on single keyword fields, even-though the YAML is valid and functional.
			rules = append(rules, &sigma.Rule{Detection: detection})
		}
	}
	// Only return rules if we have at least a selection
	if len(rules) > 1 {
		return rules
	}
	return nil
}

type ObjectScope struct {
	Search    search.Search
	Detection sigma.Detection
}

type EventScope struct {
	Search     search.Search
	Detections []sigma.Detection
}

func (c *converter) convertStandalone(a *attribute.Attribute) map[sigma.LogSource]Mapping {
	switch a.Type {
	case attribute.TypeDomain:
		return map[sigma.LogSource]Mapping{
			sigma.LogSource{Category: sigma.CategoryProxy}: {
				Selections: search.Selections{
					"Domain": {
						{field.CURI.Contains(): {a.Value}},
						{field.CSReferrer.Contains(): {a.Value}},
						{field.RDNS.Contains(): {a.Value}},
					},
				},
			},
			sigma.LogSource{Category: sigma.CategoryWeb


 15px;
    right: 20px;
    padding: 0;
    width: 20px;
    height: 20px;
    cursor: pointer;
    outline: none;
    text-align: center;
    border-radius: 10px;
    border: none;
    text-indent: -9999px;
    background: transparent url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAABGdBTUEAALGPC/xhBQAAB8BJREFUWAnFWAtsU1UY/s+5XTcYYxgfvERQeQXxNeYLjVFxLVvb2xasKIgSVNQoREVI1GhmfC6ioijiNDo1vBxb19uVtRWUzAQ1+EowOkSQzTBAUJio27r2Hr9TLJTaa7vK4yTtvec///+f7/znf5xzGf2PZnVMKRHUczEJNpgYDSEdPzTB6GdG1EbE2sxk+qqxsW5rrtNAT+/aZLtrkiDdLYhUIcSwQ9KsA7DaAbKdEWOCQBckxwrkOGP0Lf7rTAqrW+vzbT4kk91/1gAB7BqdYlVC0KUAsQuANOKKjwYUNYfff//PdNNZ3O4zqEe/FguZykhUYFGFQKspnBYGNW1LOplUWkaANtvUc3pY5FUAKwewb4jzR0KaN8ikoXrRZs2aVbBr3/6bddKfhHUHAugys+j3eCCwYv9/qflPgFab83ps52ookxZ6OOT3regtsNTJHY45fSO05yGh6wsFsZ1cIVtI035M5Uv0DQFabY77BWOLsNrmQrPi8Xq9vyaEjsXT4pg6VuiRABZfzAVzhwK+T9Lp5emIFru6QCd6CXv4+sRLSizHGpycM+yvayng/S6Do7QIJtZZVXVyOiz/sqDV4XAKweoxsDjUqM1PJ3QsaeVz5+bHtrc2IjWVmky8tKmhYVuy/qMsWOZyXSR0Wo4IDVxRWrIgmfF4vTctWdINF7oJljwQ7dG9lpkzC5PnOgywsrKSU1R/Gz6xo7hPwXT0scsnpkkXEnncjTw6kvZ3vJI8q5Lo5BUV3YaAuFthyjStof6HBP1EPbe3tOweNWpMF0AuGHveuNqtLS375NxxC8rQB7inkOd8wcaGDScKVOo8/fvmLwWOPZFIrDIxFgcYEbtnA9wgk1lZmBgwetrtnqGTbapqNG5Et06ZMhhuYzIal/Ta2tpOlMVnEAOeCqfzfEmLA0SV8KB+bljr9Wbc2ijrujpGwmdxOB+SCrJpckGiu+enT7/85uZM/P375FcjDn6LxsRMycsrPJ5B2PerOLE1mYTleNDvX8k4W4xK8HyZ3XlvJpkym+qJEa1B1VjHRwz7IBM/rBjBNodhxXLJy6N/dbvlSz4nr3xm08J+7QHkyTdI6EssDsftRjJ


A== 111294
LWZhaXJl 111295
IGhvcm55 111296
IGZvcnRlbWVudA== 111297
z4HOsc+C 111298
IGhpa2Vz 111299
INis24HYp9q6 111300
X1NvdXJjZQ== 111301
IGVzY3JpYmnDsw== 111302
X2V4ZWN1dGU= 111303
YW55bA== 111304
LXVuZA== 111305
anVhbGFu 111306
15XXqteV 111307
5a6e5L2T 111308
KCk7Ci8= 111309
IHLDqW5vdmF0aW9u 111310
IGF2YW50YWdl 111311
2YrYp9mG2Kk= 111312
IHZlcmtsYQ== 111313
IHByb3BvbmU= 111314
4LC44LGN4LCk4LGB4LCk4LCC 111315
IFNLRg== 111316
44Ge 111317
LmR4 111318
IHJlY29ubmFpc3NhbmNl 111319
IHRpZGlnYXJl 111320
INee15XXng== 111321
IGVrcmFu 111322
IGluZGljYXI= 111323
TnBj 111324
INio2K/ZhA== 111325
IOC2seC3nA== 111326
eGJk 111327
YmxhdHQ= 111328
INmK2LPYp9i52K8= 111329
IGFwdWVzdGFz 111330
KCIsIg== 111331
KG1lZGlh 111332
UnVh 111333
0LDQttC90L4= 111334
X1BMQVRGT1JN 111335
YWxpdmU= 111336
INiq2LPYp9i52K8= 111337
IHNjYXJjZQ== 111338
INin2YTZhtmB2LM= 111339
0LTRjQ== 111340
YCku 111341
Zm9ybWVz 111342
IGNvbHVuYQ== 111343
IGFudGlnZW4= 111344
INC00LDQs9GL 111345
IFBhdHQ= 111346
IOGDoOGDkOGDog== 111347
IGNvbXBldGVk 111348
IFBBUks= 111349
IGFzcGVy 111350
4LmC4Lih4LiH 111351
IGJvb3N0ZWQ= 111352
4Kas4KeN4Kam 111353
IOGDoOGDkOGDl+GDkA== 111354
INit2YrYp9ip 111355
LnN3YXA= 111356
bWVyY2k= 111357
IGFsdQ== 111358
IFN1c3RhaW5hYmlsaXR5 111359
55u06JCl 111360
IGNvbnRyYXNlw7Fh 111361
IGRiZw== 111362
IGJpYXNhbnlh 111363
IGV4Y3Vyc2lvbnM= 111364
IGZseWVy 111365
IEhlbHBlcnM= 111366
QHk= 111367
IHNjaHJpZWI= 111368
IG9wdXM= 111369
TGF5 111370
IEFuZGFsdWM= 111371
IGpldW5lc3Nl 111372
IHNhxJ9sYXk= 111373
4oCZT3I= 111374
IGNyZWM= 111375
RGVsaW1pdGVy 111376
IFNpZ2h0 111377
IHBhdHJpbW9uaW8= 111378
4LKw4LOG4LKX4LOG 111379
Y3VsYQ== 111380
IGNhbWlvbg== 111381
IGdlcnVzdA== 111382
LyoqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKioqKi


 isRtl = currentDirection in rtl
            if (currentDirection !in ltr && !isRtl)
                continue
            if (previousDirection != isRtl)
                barriers.add(Pair(i, isRtl))
            previousDirection = isRtl
        }
        return barriers
    }

    @OptIn(UnstableApi::class)
    fun extractAndParseLyricsLegacy(
        metadata: Metadata,
        parserOptions: LrcParserOptions
    ): MutableList<LyricsEntry>? {
        for (i in 0..<metadata.length()) {
            val meta = metadata.get(i)
            val data =
                if (meta is VorbisComment && meta.key == "LYRICS") // ogg / flac
                    meta.value
                else if (meta is BinaryFrame && (meta.id == "USLT" || meta.id == "SYLT")) // mp3 / other id3 based
                    UsltFrameDecoder.decode(ParsableByteArray(meta.data))
                else if (meta is TextInformationFrame && (meta.id == "USLT" || meta.id == "SYLT")) // m4a
                    meta.values.joinToString("\n")
                else null
            val lyrics = data?.let {
                try {
                    parseLrcStringLegacy(it, parserOptions)
                } catch (e: Exception) {
                    Log.e(TAG, Log.getStackTraceString(e))
                    mutableListOf(LyricsEntry(timeStamp = 0L, content = parserOptions.errorText))
                }
            }
            return lyrics ?: continue
        }
        return null
    }

    @OptIn(UnstableApi::class)
    fun loadAndParseLyricsFileLegacy(
        musicFile: File?,
        parserOptions: LrcParserOptions
    ): MutableList<LyricsEntry>? {
        val lrcFile = musicFile?.let { File(it.parentFile, it.nameWithoutExtension + ".lrc") }
        return loadTextFile(lrcFile, parserOptions.errorText)?.let {
            try {
                parseLrcStringLegacy(it, parserOptions)
            } catch (e: Exception) {
                Log.e(TAG, Log.getStackTraceString(e))
                null
            }
        }
    }

    private fun parseLrcStringLegacy(
        lrcContent: String,
        parserOptions: LrcParserOptions
    ): MutableList<LyricsEntry>? {
        if (lrcContent.isBlank()) return null

        val timeMarksRegex = "\\[(\\d{2}:\\d{2})([.:]\\d+)?]".toRegex()
        val lyricsList = mutableListOf<LyricsEntry>()
        var foundNonNull = false
        var lyricsText: StringBuilder? = StringBuilder()

        lrcContent.lines().forEach { line ->
            val matches = timeMarksRegex.findAll(line).toList()
            if (matches.isEmpty()) return@forEach

            val lyricContent =
                line.substring(matches.last().range.last + 1)
                    .let { if (parserOptions.trim) it.trim() else it }

            matches.forEach { match ->
                val timeString = match.groupValues[1] + match.groupValues[2]
                val timestamp = parseTime(timeString)

                if (!foundNonNull && timestamp > 0) {
                    foundNonNull = true
                    lyricsText = null
                }

                val lyricLine = if (parserOptions.multiLine) {
                    val startIndex = lrcContent.indexOf(line) + match.value.length
                    val endIndex = findEndIndex(lrcContent, startIndex, timeMarksRegex)
                    lrcContent.substring(startIndex, endIndex)
                        .let { if (parserOptions.trim) it.trim() else it }
                } else {
                    lyricContent