CloudBucketDeleteOption) error
	ListBuckets(kt *kit.Kit, opt *typescos.TCloudBucketListOption) (*typescos.TCloudBucketListResult, error)

	ListInstanceConfig(kt *kit.Kit, opt cvm.TCloudInstanceConfigListOption) (*cvm.TCloudInstanceConfigListResult, error)
}
/*
 * TencentBlueKing is pleased to support the open source community by making
 * 蓝鲸智云 - 混合云管理平台 (BlueKing - Hybrid Cloud Management System) available.
 * Copyright (C) 2022 THL A29 Limited,
 * a Tencent company. All rights reserved.
 * Licensed under the MIT License (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://opensource.org/licenses/MIT
 * 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.
 *
 * We undertake not to change the open source license (MIT license) applicable
 *
 * to the current version of the project delivered to anyone in the future.
 */

package huawei

import (
	"fmt"

	"hcm/pkg/adaptor/types"

	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/global"
	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/config"
	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/region"
	bssintl "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/bssintl/v2"
	bssintlv2region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/bssintl/v2/region"
	dcs "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/dcs/v2"
	dcsregion "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/dcs/v2/region"
	ecs "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/ecs/v2"
	ecsregion "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/ecs/v2/region"
	eip "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/eip/v2"
	eipregion "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/eip/v2/region"
	eipv3 "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/eip/v3"
	eipv3region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/eip/v3/region"
	evs "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/evs/v2"
	evsregion "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/evs/v2/region"
	iam "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/iam/v3"
	iamregion "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/iam/v3/region"
	ims "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/ims/v2"
	rms "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/rms/v1"
	rmsregion


og.map(|d| d.join(env!("CARGO_PKG_NAME")))
    }

    fn get_data_dir() -> Option<PathBuf> {
        let cache_dir_og = env::var_os("HOARD_DATA_DIR").map(PathBuf::from);
        if cache_dir_og.is_some() {
            return cache_dir_og;
        }

        #[cfg(target_os = "macos")]
        let cache_dir_og = env::var_os("XDG_DATA_HOME")
            .map(PathBuf::from)
            .filter(|p| p.is_absolute())
            .or_else(|| {
                BaseDirs::new()
                    .map(|p| p.home_dir().to_owned())
                    .map(|p| p.join(".local").join("share"))
            });

        #[cfg(not(target_os = "macos"))]
        let cache_dir_og = Some(get_dirs().data_dir().to_path_buf());

        cache_dir_og.map(|d| d.join(env!("CARGO_PKG_NAME")))
    }

    fn get_home_dir() -> Option<PathBuf> {
        BaseDirs::new().map(|p| p.home_dir().to_path_buf())
    }

    /// Get cache directory
    #[must_use]
    pub fn cache_dir(&self) -> &Path {
        &self.cache_dir
    }

    /// Get configuration directory
    #[must_use]
    pub fn config_dir(&self) -> &Path {
        &self.config_dir
    }

    /// Get local data directory
    #[must_use]
    pub fn data_dir(&self) -> &Path {
        &self.data_dir
    }

    /// Get cache directory
    #[must_use]
    pub fn home_dir(&self) -> &Path {
        &self.home_dir
    }
}

/// Get all user directories (not for macOS)
pub(crate) fn get_dirs() -> ProjectDirs {
    tracing::trace!("determining project default folders");
    ProjectDirs::from("com", "shadow53_lmburns", "hoard")
        .expect("could not detect user home directory to place program files")
}
// Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

pub fn main() {
    // Test that these type check correctly.
    (&42u8 >> 4) as usize;
    (&42u8 << 4) as usize;

    let cap = 512 * 512;
    cap as u8;
    // Assert `cap` did not get inferred to `u8` and overflowed.
    assert_ne!(cap, 0);
}
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.

use crate::iterators::ProductNodeMap;
use crate::{digraph, graph, StablePyGraph};

use hashbrown::HashMap;

use petgraph::visit::{EdgeRef, IntoEdgeReferences, IntoNodeReferences};
use petgraph::{algo, EdgeType};

use pyo3::prelude::*;
use pyo3::Python;

fn cartes


con from customized items */
.jstree-anchor .jstree-themeicon-custom {
  background-image: none !important;
}
/* Attempt to override throbber.gif */
.jstree-default > .jstree-container-ul .jstree-loading > .jstree-ocl,
.jstree-default-small > .jstree-container-ul .jstree-loading > .jstree-ocl,
.jstree-default-large > .jstree-container-ul .jstree-loading > .jstree-ocl {
  background-image: none !important;
}

@font-face {
  font-family: 'Material Icons';
  font-style: normal;
  font-weight: 400;
  src: url('../fonts/MaterialIcons-Regular.eot'); /* For IE6-8 */
  src: local('Material Icons'),
       local('MaterialIcons-Regular'),
       url('../fonts/MaterialIcons-Regular.woff2') format('woff2'),
       url('../fonts/MaterialIcons-Regular.woff') format('woff'),
       url('../fonts/MaterialIcons-Regular.ttf') format('truetype');
}

.material-icons {
  font-family: 'Material Icons';
  font-weight: normal;
  font-style: normal;
  font-size: 24px;  /* Preferred icon size */
  display: inline-block;
  width: 1em;
  height: 1em;
  line-height: 1;
  text-transform: none;
  letter-spacing: normal;
  word-wrap: normal;
  white-space: nowrap;
  direction: ltr;

  /* Support for all WebKit browsers. */
  -webkit-font-smoothing: antialiased;
  /* Support for Safari and Chrome. */
  text-rendering: optimizeLegibility;

  /* Support for Firefox. */
  -moz-osx-font-smoothing: grayscale;

  /* Support for IE. */
  font-feature-settings: 'liga';
}

/**
* CSS themes for simplePagination.js
* Author: Flavius Matis - http://flaviusmatis.github.com/
* URL: https://github.com/flaviusmatis/simplePagination.js
*/

ul.simple-pagination {
	list-style: none;
}

.simple-pagination {
	display: block;
	overflow: hidden;
	padding: 0 5px 5px 0;
	margin: 0;
}

.simple-pagination ul {
	list-style: none;
	padding: 0;
	margin: 0


rvice", "service", foundService.Name)
				return false, err
			}
			log.Info("Successfully deleted Service for Instance", "service", foundService.Name, "instance", instance.Name)
			return true, nil
		}
		foundService.Spec = service.Spec
		log.Info("Updating Service for Instance", "service", foundService.Name, "instance", instance.Name)
		if err := r.Update(ctx, foundService); err != nil {
			log.Error(err, "failed to update Service", "service", foundService.Name)
			return false, err
		}
		log.Info("Successfully updated Service for Instance", "service", foundService.Name, "instance", instance.Name)
	}

	// Service exists and is ready
	return true, nil
}

func equalDeploymentSpec(a, b *appsv1.DeploymentSpec) bool {
	// replicas (treat nil as 1, which is Kubernetes default)
	aReplicas := int32(1)
	if a.Replicas != nil {
		aReplicas = *a.Replicas
	}
	bReplicas := int32(1)
	if b.Replicas != nil {
		bReplicas = *b.Replicas
	}
	if aReplicas != bReplicas {
		return false
	}

	// selector match labels
	if len(a.Selector.MatchLabels) != len(b.Selector.MatchLabels) {
		return false
	}
	for k, v := range a.Selector.MatchLabels {
		if bv, exists := b.Selector.MatchLabels[k]; !exists || bv != v {
			return false
		}
	}

	// labels
	if len(a.Template.Labels) != len(b.Template.Labels) {
		return false
	}
	for k, v := range a.Template.Labels {
		if bv, exists := b.Template.Labels[k]; !exists || bv != v {
			return false
		}
	}

	// containers
	if len(a.Template.Spec.Containers) != len(b.Template.Spec.Containers) {
		return false
	}
	containerMap := make(map[string]corev1.Container)
	for _, c := range a.Template.Spec.Containers {
		containerMap[c.Name] = c
	}
	for _, c := range b.Template.Spec.Containers {
		// name, image
		ac, exists := containerMap[c.Name]
		if !exists || ac.Image != c.Image {
			return false
		}

		// env
		if len(ac.Env) != len(c.Env) {
			return false
		}
		envMap := make(map[string]corev1.EnvVar)
		for _, e := range ac.Env {
			envMap[e.Name] = e
		}
		for _, e := range c.Env {
			if ae, exists := envMap[e.Name]; !exists || ae.Value != e.Value {
				return false
			}
		}

		// ports
		if len(ac.Ports) != len(c.Ports) {
			return false
		}
		portMap := make(map[string]corev1.ContainerPort)
		for _, p := range ac.Ports {
			portMap[p.Name] = p
		}
		for _, p := range c.Ports {
			if ap, exists := portMap[p.Name]; !exists || ap.ContainerPort != p.ContainerPort {
				return false
			}
		}

		// resources (on container level)
		// requests
		if len(ac.Resources.Requests) != len(c.Resources.Requests) {
			return false
		}
		for k, v := range ac.Resources.Requests {
			if cv, exists := c.Resources.Requests[k]; !exists || cv.Cmp(v) != 0 {
				return false
			}
		}

		// limits
		if len(ac.Resources.Limits) != len(c.Resources.Limits) {
			return false
		}
		for k, v := range ac.Resources.Limits {
			if cv, exists := c.Resources.Limits[k]; !exists || cv.Cmp(v) != 0 {
				return false
			}
		}
	}

	return true
}

func equalServiceSpec(a, b *corev1.


ate(initialCapacity);
            DebugName = debugName;
        }

        /// <summary>
        /// Recreates the buffer without retaining old data.
        /// </summary>
        /// <param name="newCapacity">New capacity of the buffer.</param>
        public void SetCapacityWithoutCopy(int newCapacity)
        {
            DoDispose();
            Allocate(newCapacity);
        }

        /// <summary>
        /// Updates the buffer with the given values.
        /// </summary>
        /// <param name="newValues">Values to load into the buffer.</param>
        public void Update(Span<T> newValues) =>
            GL.NamedBufferSubData(buffer, IntPtr.Zero, newValues.Length * Stride, ref newValues[0]);

        /// <summary>
        /// Updates the buffer with the given values.
        /// </summary>
        /// <param name="newValues">Values to load into the buffer.</param>
        /// <param name="count">Number of elements from the source array to read.</param>
        /// <param name="sourceOffset">Offset from which to begin reading the new values.</param>
        /// <param name="destinationOffset">Index at which the stored values should start in the buffer.</param>
        public void Update(Span<T> newValues, int count, int sourceOffset = 0, int destinationOffset = 0) =>
            GL.NamedBufferSubData(buffer, (IntPtr)(destinationOffset * Stride), count * Stride, ref newValues[sourceOffset]);

        public void Bind(int index) => GL.BindBufferBase((BufferRangeTarget)target, index, buffer);
        protected override void DoDispose() => GL.DeleteBuffer(buffer);
    }
}


Local branch is behind upstream. Pull the latest audited commit before freezing.', { upstream, behind, ahead });
      }
      if (Number.isFinite(ahead) && ahead > 0) {
        fail('Local branch has unpushed commits. Push or archive them before the audit freeze.', { upstream, ahead, behind });
      }
    }
  }

  ok({
    branch,
    expectedBranch,
    upstream: upstream || 'none',
    fetched: process.env.AUDIT_FREEZE_IGNORE_FETCH === '1' ? 'skipped' : Boolean(upstream),
    clean: status.length === 0,
  });
}

main();
const { expect } = require('chai');
const { ethers } = require('hardhat');

describe('QuadraticVoting', function () {
  let token, qv, owner, voter1, voter2, executor, qvAddress;

  beforeEach(async () => {
    [owner, voter1, voter2, executor] = await ethers.getSigners();
    const MockToken = await ethers.getContractFactory(
      'contracts/test/MockERC20.sol:MockERC20'
    );
    token = await MockToken.deploy();
    await token.mint(voter1.address, 1000);
    await token.mint(voter2.address, 1000);
    const QuadraticVoting = await ethers.getContractFactory(
      'contracts/v2/QuadraticVoting.sol:QuadraticVoting'
    );
    qv = await QuadraticVoting.deploy(
      await token.getAddress(),
      executor.address
    );
    qvAddress = await qv.getAddress();
    await qv.connect(owner).setTreasury(owner.address);
    await token.connect(voter1).approve(qvAddress, 1000);
    await token.connect(voter2).approve(qvAddress, 1000);
  });

  it('charges quadratic cost and holds funds', async () => {
    const block = await ethers.provider.getBlock('latest');
    const contractBefore = await token.balanceOf(qvAddress);
    const ownerBefore = await token.balanceOf(owner.address);
    await qv.connect(voter1).castVote(1, 3, block.timestamp + 100); // cost 9
    expect(await token.balanceOf(voter1.address)).to.equal(991n);
    expect(await token.balanceOf(qvAddress)).to.equal(contractBefore + 9n);
    expect(await token.balanceOf(owner.address)).to.equal(ownerBefore);
    expect(await qv.votes(1, voter1.address)).to.equal(3n);
    expect(await qv.costs(1, voter1.address)).to.equal(9n);
  });

  it('distributes rewards proportional to sqrt(cost) without treasury approvals', async () => {
    const block = await ethers.provider.getBlock('latest');
    await qv.connect(voter1).castVote(1, 4, block.timestamp + 100); // cost 16, sqrt 4
    await qv.connect(voter2).castVote(1, 1, block.timestamp + 100); // cost 1, sqrt 1
    await qv.connect(executor).execute(1);

    await expect(qv.connect(voter1).claimReward(1))
      .to.emit(qv, 'RewardClaimed')
      .withArgs(1, voter1.address, 13n);
    await expect(qv.connect(voter2).claimReward(1))
      .to.emit(qv, 'RewardClaimed')
      .withArgs(1, voter2.address, 3n);

    expect(await token.balanceOf(voter1.address)).to.equal(997n);
    expect(await token.balanceOf(voter2.address)).to.equal(1002n);
    expect(await token.balanceOf(qvAddress)).to.equal(1n);
  });

  it('allows the owner to sweep residual rewards to the treasury', async () => {


			} else {
				if err != nil {
					t.Errorf("Expected no error but got: %v", err)
				}
			}
		})
	}
}

func TestValue_ValidateAdvancedConstraints_PatternValidation(t *testing.T) {
	tests := []struct {
		name      string
		value     string
		valueType ParameterType
		pattern   string
		wantError bool
		errorMsg  string
	}{
		{
			name:      "valid version pattern",
			value:     "v1.2.3",
			valueType: StringType,
			pattern:   `v\d+\.\d+\.\d+`,
			wantError: false,
		},
		{
			name:      "invalid version pattern",
			value:     "1.2.3",
			valueType: StringType,
			pattern:   `v\d+\.\d+\.\d+`,
			wantError: true,
			errorMsg:  "does not match pattern",
		},
		{
			name:      "pattern constraint on non-string type",
			value:     "123",
			valueType: NumberType,
			pattern:   `\d+`,
			wantError: true,
			errorMsg:  "pattern constraints can only be applied to string types",
		},
		{
			name:      "invalid regex pattern",
			value:     "test",
			valueType: StringType,
			pattern:   `[`,
			wantError: true,
			errorMsg:  "invalid regex pattern",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			v, err := NewValue(tt.valueType, tt.value)
			if err != nil {
				t.Fatalf("Failed to create value: %v", err)
			}

			err = v.ValidateAdvancedConstraints(nil, nil, tt.pattern, "", false)

			if tt.wantError {
				if err == nil {
					t.Errorf("Expected error but got none")
				} else if tt.errorMsg != "" && !contains(err.Error(), tt.errorMsg) {
					t.Errorf("Expected error containing '%s', got '%s'", tt.errorMsg, err.Error())
				}
			} else {
				if err != nil {
					t.Errorf("Expected no error but got: %v", err)
				}
			}
		})
	}
}

func TestValue_ValidateAdvancedConstraints_EmailValidation(t *testing.T) {
	tests := []struct {
		name        string
		value       string
		valueType   ParameterType
		emailFormat bool
		wantError   bool
		errorMsg    string
	}{
		{
			name:        "valid email",
			value:       "test@example.com",
			valueType:   StringType,
			emailFormat: true,
			wantError:   false,
		},
		{
			name:        "valid email with subdomain",
			value:       "user@mail.example.com",
			valueType:   StringType,
			emailFormat: true,
			wantError:   false,
		},
		{
			name:        "invalid email - no @",
			value:       "invalid-email",
			valueType:   StringType,
			emailFormat: true,
			wantError:   true,
			errorMsg:    "not a valid email address",
		},
		{
			name:        "invalid email - no domain",
			value:       "test@",
			valueType:   StringType,
			emailFormat: true,
			wantError:   true,
			errorMsg:    "not a valid email address",
		},
		{
			name:        "email validation on non-string type",
			value:       "123",
			valueType:   NumberType,
			emailFormat: true,
			wantError:   true,
			errorMsg:    "email format validation can only be applied to string types",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			v, err := NewValue(tt.value


		c1.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
		var peer Addr
		if genericRead {
			_, err = c1.(Conn).Read(nil)
		} else {
			_, peer, err = c1.ReadFrom(nil)
		}
		switch err {
		case nil: // ReadFrom succeeds
			if peer != nil { // peer is connected-mode
				t.Fatalf("unexpected peer address: %v", peer)
			}
		default: // Read may timeout, it depends on the platform
			if nerr, ok := err.(Error); !ok || !nerr.Timeout() {
				t.Fatal(err)
			}
		}
	}
}

func TestUnixgramAutobind(t *testing.T) {
	if runtime.GOOS != "linux" {
		t.Skip("autobind is linux only")
	}

	laddr := &UnixAddr{Name: "", Net: "unixgram"}
	c1, err := ListenUnixgram("unixgram", laddr)
	if err != nil {
		t.Fatal(err)
	}
	defer c1.Close()

	// retrieve the autobind address
	autoAddr := c1.LocalAddr().(*UnixAddr)
	if len(autoAddr.Name) <= 1 {
		t.Fatalf("invalid autobind address: %v", autoAddr)
	}
	if autoAddr.Name[0] != '@' {
		t.Fatalf("invalid autobind address: %v", autoAddr)
	}

	c2, err := DialUnix("unixgram", nil, autoAddr)
	if err != nil {
		t.Fatal(err)
	}
	defer c2.Close()

	if !reflect.DeepEqual(c1.LocalAddr(), c2.RemoteAddr()) {
		t.Fatalf("expected autobind address %v, got %v", c1.LocalAddr(), c2.RemoteAddr())
	}
}

func TestUnixAutobindClose(t *testing.T) {
	if runtime.GOOS != "linux" {
		t.Skip("autobind is linux only")
	}

	laddr := &UnixAddr{Name: "", Net: "unix"}
	ln, err := ListenUnix("unix", laddr)
	if err != nil {
		t.Fatal(err)
	}
	ln.Close()
}

func TestUnixgramWrite(t *testing.T) {
	if !testableNetwork("unixgram") {
		t.Skip("unixgram test")
	}

	addr := testUnixAddr()
	laddr, err := ResolveUnixAddr("unixgram", addr)
	if err != nil {
		t.Fatal(err)
	}
	c, err := ListenPacket("unixgram", addr)
	if err != nil {
		t.Fatal(err)
	}
	defer os.Remove(addr)
	defer c.Close()

	testUnixgramWriteConn(t, laddr)
	testUnixgramWritePacketConn(t, laddr)
}

func testUnixgramWriteConn(t *testing.T, raddr *UnixAddr) {
	c, err := Dial("unixgram", raddr.String())
	if err != nil {
		t.Fatal(err)
	}
	defer c.Close()

	b := []byte("CONNECTED-MODE SOCKET")
	if _, err := c.(*UnixConn).WriteToUnix(b, raddr); err == nil {
		t.Fatal("should fail")
	} else if err.(*OpError).Err != ErrWriteToConnected {
		t.Fatalf("should fail as ErrWriteToConnected: %v", err)
	}
	if _, err = c.(*UnixConn).WriteTo(b, raddr); err == nil {
		t.Fatal("should fail")
	} else if err.(*OpError).Err != ErrWriteToConnected {
		t.Fatalf("should fail as ErrWriteToConnected: %v", err)
	}


on.
The maximum allowed seconds value is 65535 (18 hours).

TransferOptions

Syntax: TransferOptions opt1 ...

Default: None

Context: server config, <VirtualHost>, <Global>

Module: mod_xfer

Compatibility: 1.3.6rc1 and later

The TransferOptions directive to configure various optional data
transfer behaviors.

The currently implemented options are:

AllowSymlinkUpload

    This option allows clients to upload files which are actually symlinks
    on the server, rather than returning a "Not a regular file" error.

    Note that this option first appeared in
    proftpd-1.3.8rc3.

IgnoreASCII

    This option causes ProFTPD to silently ignore any client requests to
    perform ASCII translations via the TYPE command.  That is,
    FTP clients can request ASCII translations, and proftpd will respond
    as the client expects, but will not actually perform the translation
    for either uploads or downloads.  This behavior can be useful in
    circumstances involving older/mainframe clients and EBCDIC files.

    Note that this option first appeared in
    proftpd-1.3.6rc1.

TransferRate

Syntax: TransferRate cmd-list kbytes-per-sec[:free-bytes]

Default: None

Context: server config, <VirtualHost>, <Global>, <Anonymous>, <Directory>, .ftpaccess

Module: mod_xfer

Compatibility: 1.2.8rc1 and later

The TransferRate directive is used to set transfer rate limits
on the transfer of data.  This directive allows for transfer rates to be set
in a wide variety of contexts, on a per-command basis, and for certain subsets
of users (via
mod_ifsession).
Note that these limits only apply to an individual session, and
do not apply to the overall transfer rate of the entire daemon.

The cmd-list parameter may be an comma-separated list of any of the
following commands: APPE, RETR, STOR,
and STOU.

The kbytes-per-sec parameter is the actual transfer rate to be applied.

The free-bytes parameter, if configured, allows that number of bytes
to be transferred before the rate limit is applied.  This allows for clients
transferring small files to be unthrottled, but for larger files, such as MP3s
and ISO images, to be throttled.

Here are some examples:

  # Limit downloads for everyone
  TransferRate RETR 1.5

  # Limit uploads (and appends!) to the prolific users in the
  # lotsofu


// Copyright 2009 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef PAGESPEED_CORE_RULE_INPUT_H_
#define PAGESPEED_CORE_RULE_INPUT_H_

#include <map>
#include <string>
#include <vector>

#include "base/basictypes.h"

namespace pagespeed {

class PagespeedInput;
class Resource;

class RuleInput {
 public:
  typedef std::vector<const Resource*> RedirectChain;
  typedef std::vector<RedirectChain> RedirectChainVector;
  typedef std::map<const Resource*, const RedirectChain*>
      ResourceToRedirectChainMap;

  explicit RuleInput(const PagespeedInput& pagespeed_input);
  void Init();
  const PagespeedInput& pagespeed_input() const { return *pagespeed_input_; }
  const RedirectChainVector& GetRedirectChains() const;
  const RedirectChain* GetRedirectChainOrNull(const Resource* resource) const;
  // Given a pointer to a resource, return a pointer to the final resource in
  // the redirect chain.  If the resource has no redirect chain, return the
  // resource itself.  If the given pointer is NULL, return NULL.
  const Resource* GetFinalRedirectTarget(const Resource* resource) const;

 private:
  void BuildRedirectChains();

  const PagespeedInput* pagespeed_input_;
  RedirectChainVector redirect_chains_;
  ResourceToRedirectChainMap resource_to_redirect_chain_map_;
  bool initialized_;

  DISALLOW_COPY_AND_ASSIGN(RuleInput);
};

}  // namespace pagespeed

#endif  // PAGESPEED_CORE_RULE_INPUT_H_


 0, i64 0
// CHECK1-NEXT:    store ptr null, ptr [[TMP2]], align 8
// CHECK1-NEXT:    [[TMP3:%.*]] = getelementptr inbounds [1 x ptr], ptr [[DOTOFFLOAD_BASEPTRS]], i32 0, i32 0
// CHECK1-NEXT:    [[TMP4:%.*]] = getelementptr inbounds [1 x ptr], ptr [[DOTOFFLOAD_PTRS]], i32 0, i32 0
// CHECK1-NEXT:    [[TMP5:%.*]] = getelementptr inbounds [[STRUCT___TGT_KERNEL_ARGUMENTS]], ptr [[KERNEL_ARGS]], i32 0, i32 0
// CHECK1-NEXT:    store i32 2, ptr [[TMP5]], align 4
// CHECK1-NEXT:    [[TMP6:%.*]] = getelementptr inbounds [[STRUCT___TGT_KERNEL_ARGUMENTS]], ptr [[KERNEL_ARGS]], i32 0, i32 1
// CHECK1-NEXT:    store i32 1, ptr [[TMP6]], align 4
// CHECK1-NEXT:    [[TMP7:%.*]] = getelementptr inbounds [[STRUCT___TGT_KERNEL_ARGUMENTS]], ptr [[KERNEL_ARGS]], i32 0, i32 2
// CHECK1-NEXT:    store ptr [[TMP3]], ptr [[TMP7]], align 8
// CHECK1-NEXT:    [[TMP8:%.*]] = getelementptr inbounds [[STRUCT___TGT_KERNEL_ARGUMENTS]], ptr [[KERNEL_ARGS]], i32 0, i32 3
// CHECK1-NEXT:    store ptr [[TMP4]], ptr [[TMP8]], align 8
// CHECK1-NEXT:    [[TMP9:%.*]] = getelementptr inbounds [[STRUCT___TGT_KERNEL_ARGUMENTS]], ptr [[KERNEL_ARGS]], i32 0, i32 4
// CHECK1-NEXT:    store ptr @.offload_sizes, ptr [[TMP9]], align 8
// CHECK1-NEXT:    [[TMP10:%.*]] = getelementptr inbounds [[STRUCT___TGT_KERNEL_ARGUMENTS]], ptr [[KERNEL_ARGS]], i32 0, i32 5
// CHECK1-NEXT:    store ptr @.offload_maptypes, ptr [[TMP10]], align 8
// CHECK1-NEXT:    [[TMP11:%.*]] = getelementptr inbounds [[STRUCT___TGT_KERNEL_ARGUMENTS]], ptr [[KERNEL_ARGS]], i32 0, i32 6
// CHECK1-NEXT:    store ptr null, ptr [[TMP11]], align 8
// CHECK1-NEXT:    [[TMP12:%.*]] = getelementptr inbounds [[STRUCT___TGT_KERNEL_ARGUMENTS]], ptr [[KERNEL_ARGS]], i32 0, i32 7
// CHECK1-NEXT:    store ptr null, ptr [[TMP12]], align 8
// CHECK1-NEXT:    [[TMP13:%.*]] = getelementptr inbounds [[STRUCT___TGT_KERNEL_ARGUMENTS]], ptr [[KERNEL_ARGS]], i32 0, i32 8
// CHECK1-NEXT:    store i64 0, ptr [[TMP13]], align 8
// CHECK1-NEXT:    [[TMP14:%.*]] = getelementptr inbounds [[STRUCT___TGT_KERNEL_ARGUMENTS]], ptr [[KERNEL_ARGS]], i32 0, i32 9
// CHECK1-NEXT:    store i64 0, ptr [[TMP14]], align 8
// CHECK1-NEXT:    [[TMP15:%.*]] = getelementptr inbounds [[STRUCT___TGT_KERNEL_ARGUMENTS]], ptr [[KERNEL_ARGS]], i32 0, i32 10
// CHECK1-NEXT:    store [3 x i32] [i32 1, i32 0, i32 0], ptr [[TMP15]], align 4
// CHECK1-NEXT:    [[TMP16:%.*]] = getelementptr inbounds [[STRUCT___TGT_KERNEL_ARGUMENTS]], ptr [[KERNEL_ARGS]], i32 0, i32 11
// CHECK1-NEXT:    store [3 x i32] zeroinitializer, ptr [[TMP16]], align 4
// CHECK1-NEXT:    [[TMP17:


->getZone()!=UNINITIALIZED_ZONE) continue;

					if (i>blockBounds.lo.x) {
						if (map[i][j].getType() == map[i-1][j].getType()) {
							cell->setZone(map[i-1][j].getZone());
							if (cell->getZone()!=UNINITIALIZED_ZONE) continue;
						}
					}
					if (j>blockBounds.lo.y) {
						if (cell->getType() == map[i][j-1].getType()) {
							cell->setZone(map[i][j-1].getZone());
							if (cell->getZone()!=UNINITIALIZED_ZONE) continue;
						}
						if (i<blockBounds.hi.x) {
							if (typesMatch(*cell, map[i+1][j-1]) &&
									typesMatch(*cell, map[i+1][j])) {
								cell->setZone(map[i+1][j-1].getZone());
								if (cell->getZone()!=UNINITIALIZED_ZONE) continue;
							}
						}
					}
				}
			}
			for( j=blockBounds.hi.y; j>=blockBounds.lo.y; j-- )	{
				for( i=blockBounds.hi.x; i>=blockBounds.lo.x; i-- )	{
					PathfindCell *cell = &map[i][j];
					if (cell->getZone()!=UNINITIALIZED_ZONE) continue;
					if (i<blockBounds.hi.x) {
						if (map[i][j].getType() == map[i+1][j].getType()) {
							cell->setZone(map[i+1][j].getZone());
							if (cell->getZone()!=UNINITIALIZED_ZONE) continue;
						}
					}
					if (j<blockBounds.hi.y) {
						if (cell->getType() == map[i][j+1].getType()) {
							cell->setZone(map[i][j+1].getZone());
							if (cell->getZone()!=UNINITIALIZED_ZONE) continue;
						}
						if (i<blockBounds.hi.x) {
							if (typesMatch(*cell, map[i+1][j+1]) &&
									typesMatch(*cell, map[i+1][j])) {
								cell->setZone(map[i+1][j+1].getZone());
								if (cell->getZone()!=UNINITIALIZED_ZONE) continue;
							}
						}
					}
				}
			}
			//DEBUG_LOG(("Collapsed zones %d\n", m_maxZone));
 		}
	}
#ifdef DEBUG_QPF
#if defined(DEBUG_LOGGING)
	QueryPerformanceCounter((LARGE_INTEGER *)&endTime64);
	timeToUpdate = ((double)(endTime64-startTime64) / (double)(freq64));
	//DEBUG_LOG(("Time to update zones %f, cells %d\n", timeToUpdate, (globalBounds.hi.x-globalBounds.lo.x)*(globalBounds.hi.y-globalBounds.lo.y)));
#endif
#endif
#if defined _DEBUG || defined _INTERNAL
	if (TheGlobalData->m_debugAI==AI_DEBUG_ZONES)
	{
		extern void addIcon(const Coord3D *pos, Real width, Int numFramesDuration, RGBColor color);
		RGBColor color;
		memset(&color, 0, sizeof(Color));
		addIcon(NULL, 0, 0, color);
		Int i, j;
		for( j=0; j<globalBounds.hi.y; j++ )	{
			for( i=0; i<globalBounds.hi.x; i++ )	{
				Int zone = map[i][j].getZone();
				//zone = m_terrainZones[zone];
				zone = m_hierarchicalZones[zone];

				color.blue = (zone%3) * 0.5f;
				zone


ize) -> bool {
        (start..start + len).all(|offset| !b.dirty_at(offset))
    }

    // Helper method to check whether a specified range is dirty.
    pub fn range_is_dirty<B: Bitmap>(b: &B, start: usize, len: usize) -> bool {
        (start..start + len).all(|offset| b.dirty_at(offset))
    }

    pub fn check_range<B: Bitmap>(b: &B, start: usize, len: usize, clean: bool) -> bool {
        if clean {
            range_is_clean(b, start, len)
        } else {
            range_is_dirty(b, start, len)
        }
    }

    // Helper method that tests a generic `B: Bitmap` implementation. It assumes `b` covers
    // an area of length at least 0x2000.
    pub fn test_bitmap<B: Bitmap>(b: &B) {
        let len = 0x2000;
        let dirty_offset = 0x1000;
        let dirty_len = 0x100;

        // Some basic checks.
        let s = b.slice_at(dirty_offset);

        assert!(range_is_clean(b, 0, len));
        assert!(range_is_clean(&s, 0, dirty_len));

        b.mark_dirty(dirty_offset, dirty_len);
        assert!(range_is_dirty(b, dirty_offset, dirty_len));
        assert!(range_is_dirty(&s, 0, dirty_len));
    }

    #[derive(Debug)]
    pub enum TestAccessError {
        RangeCleanCheck,
        RangeDirtyCheck,
    }

    // A helper object that implements auxiliary operations for testing `Bytes` implementations
    // in the context of dirty bitmap tracking.
    struct BytesHelper<F, G, M> {
        check_range_fn: F,
        address_fn: G,
        phantom: PhantomData<*const M>,
    }

    // `F` represents a closure the checks whether a specified range associated with the `Bytes`
    // object that's being tested is marked as dirty or not (depending on the value of the last
    // parameter). It has the following parameters:
    // - A reference to a `Bytes` implementations that's subject to testing.
    // - The offset of the range.
    // - The length of the range.
    // - Whether we are checking if the range is clean (when `true`) or marked as dirty.
    //
    // `G` represents a closure that translates an offset into an address value that's
    // relevant for the `Bytes` implementation being tested.
    impl<F, G, M, A> BytesHelper<F, G, M>
    where
        F: Fn(&M, usize, usize, bool) -> bool,
        G: Fn(usize) -> A,
        M: Bytes<A>,
    {
        fn check_range(&self, m: &M, start: usize, len: usize, clean: bool) -> bool {
            (self.check_range_fn)(m, start, len, clean)
        }

        fn address(&self, offset: usize) -> A {
            (self.address_fn)(offset)
        }

        fn test_access<Op>(
            &self,
            bytes: &M,
            dirty_offset: usize,
            dirty_len: usize,
            op: Op,
        ) -> Result<(), TestAccessError>
        where
            Op: Fn(&M, A),
        {
            if !self.check_range(bytes, dirty_offset, dirty_len, true) {
                return Err(TestAccessError::RangeCleanCheck);
            }

            op(bytes, self.address(dirty_offset));

            if !self.check_range(bytes, dirty_offset, dirty_len, false) {
                return Err(TestAccessError::RangeDirtyCheck);
            }

            Ok(())
        }
    }

    // `F` and `G` stand for the same closure types as described in the `BytesHelper` comme


ctions":[{"refs":[{"id":"ref-for-absolute-length"}],"title":"5. \nDistance Units: the <length> type"}],"url":"#absolute-length"},
"af50aa62": {"dfnID":"af50aa62","dfnText":"<function-token>","external":true,"refSections":[{"refs":[{"id":"ref-for-typedef-function-token"}],"title":"8. \nFunctional Notations"}],"url":"https://drafts.csswg.org/css-syntax-3/#typedef-function-token"},
"anchor-unit": {"dfnID":"anchor-unit","dfnText":"anchored","external":false,"refSections":[{"refs":[{"id":"ref-for-anchor-unit"},{"id":"ref-for-anchor-unit\u2460"},{"id":"ref-for-anchor-unit\u2461"}],"title":"5.2. \nAbsolute Lengths: the cm, mm, Q, in, pt, pc, px units"}],"url":"#anchor-unit"},
"angle-value": {"dfnID":"angle-value","dfnText":"<angle>","external":false,"refSections":[{"refs":[{"id":"ref-for-angle-value"}],"title":"4. \nNumeric Data Types"},{"refs":[{"id":"ref-for-angle-value\u2460"},{"id":"ref-for-angle-value\u2461"}],"title":"4.6. \nMixing Percentages and Dimensions"},{"refs":[{"id":"ref-for-angle-value\u2462"},{"id":"ref-for-angle-value\u2463"},{"id":"ref-for-angle-value\u2464"},{"id":"ref-for-angle-value\u2465"},{"id":"ref-for-angle-value\u2466"}],"title":"6.1. \nAngle Units: the <angle> type and deg, grad, rad, turn units"},{"refs":[{"id":"ref-for-angle-value\u2467"}],"title":"8.1. \nMathematical Expressions: calc()"},{"refs":[{"id":"ref-for-angle-value\u2468"},{"id":"ref-for-angle-value\u2460\u24ea"}],"title":"8.1.2. \nType Checking"},{"refs":[{"id":"ref-for-angle-value\u2460\u2460"}],"title":"8.2. \nAttribute References: attr()"}],"url":"#angle-value"},
"b7c8adc2": {"dfnID":"b7c8adc2","dfnText":"<url-token>","external":true,"refSections":[{"refs":[{"id":"ref-for-typedef-url-token"}],"title":"3.4. \nResource Locators: the <url> type"}],"url":"https://drafts.csswg.org/css-syntax-3/#typedef-url-token"},
"baa03018": {"dfnID":"baa03018","dfnText":"ease-out","external":true,"refSections":[{"refs":[{"id":"ref-for-valdef-cubic-bezier-easing-function-ease-out"}],"title":"3.2. \nAuthor-defined Identifiers: the <custom-ident> type"}],"url":"https://drafts.csswg.org/css-easing-2/#valdef-cubic-bezier-easing-function-ease-out"},
"bd3d9ccd": {"dfnID":"bd3d9ccd","dfnText":"media query","external":true,"refSections":[{"refs":[{"id":"ref-for-media-query"}],"title":"5.1.1. \nFont-relative Lengths: the em, ex, ch, rem units"}],"url":"https://drafts.csswg.org/mediaqueries-5/#media-query"},
"bearing-angle": {"dfnID":"bearing-angle","dfnText":"bearing angle","external":false,"refSections":[],"url":"#bearing-angle"},
"c16b1855": {"dfnID":"c16b1855","dfnText":"animation-timing-function","external":true,"refSections":[{"refs":[{"i


    }
    }

    setFavourites(cities: Array<string>) {
        const s = cities.join(',');
        settings.setString(AppSettings.FAVOURITES, s);
    }
    getFavourites(): Array<string> {
        const s = settings.getString(AppSettings.FAVOURITES);
        if(s)
            return s.split(',');
    }
}import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
	name: 'formatadorData'
})
export class FormatadorDataPipe implements PipeTransform {

	transform(value: string, time?: boolean): string {
		var date: Date = new Date(value);
		return date.toLocaleDateString() + (time ? " " + date.toLocaleTimeString().substring(0, 5) : '');
	}
}
import {Matches, MatchRHS, RHS, Transformer, TransformJoinEvent} from '../types';
export const transformJoin = 'data-transform-join';
export class Join{
    constructor(public transformer: Transformer, fragment: DocumentFragment){
        const childElements = Array.from(fragment.children);
        let foundMatch = false;
        fragment.querySelectorAll(transformJoin).forEach(match => {
            foundMatch = true;
            const joinAttr = match.getAttribute(transformJoin)!;
            const transformMatch = JSON.parse(joinAttr);
            const newMatch = join(transformer.ctx.match!, transformMatch);
            transformer.ctx.match = newMatch;
            match.removeAttribute(transformJoin);
        });
        if(foundMatch){
            transformer.flushCache();
            transformer.transform(fragment)
        }
        for(const el of childElements){
            el.addEventListener(transformJoin, async e => {
                const {detail} = (e as CustomEvent);// as TransformJoinEvent;
                if(detail !== undefined){
                    const joinEvent = detail as TransformJoinEvent;
                    const {match} = joinEvent;
                    if(match !== undefined){
                        const newMatch = join(transformer.ctx.match!, match);
                        transformer.ctx.match! = newMatch;
                    }
                    joinEvent.acknowledged = true;
                }
                const {target} = e;
                await transformer.transform([target as Element]);
                transformer.flushCache();
            });
        }
    }
}

function join(lhs: Matches, rhs: Matches): Matches{
    const lhsGrouped = group(lhs);
    const rhsGrouped = group(rhs);
    const returnObj: Matches = {};
    for(const key in lhsGrouped){
        let val = lhsGrouped[key];
        const addend = rhsGrouped[key];
        if(addend !== undefined){
            val = val.concat(addend);
        }
        let count  = 0;;
        let dupKey = '^';
        for(const m of val){
            if(count === 0){
                returnObj[key] = m;
            }else{
                returnObj[dupKey] = m;
            }
            count++;
            dupKey = '^' + count;
        }
    }
    return returnObj;
}

function group(match: Matches): {[key: string]: RHS[]}{
    const returnObj: {[key: string]: RHS[]} = {};
    let lastKey = '';
    for(const key in match){
        let realKey = key;
        if(key[0] === '^'){
            realKey = lastKey;
        }else{
            lastKey = key;
        }
        if(returnObj[realKey] === undefined){
            returnObj[realKey] = [];
        }
        const rhs = match[realKey];
        returnObj[key].push(rhs)
    }
    return returnObj;
}import { useEffect, useState }


		mt = types.Info
	case zerolog.DebugLevel:
		mt = types.Log
	default:
		mt = 0
	}
	return mt
}
/*
 * © 2025 Snyk Limited
 *
 * 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 types

func NewIssueViewOptions(openIssues bool, ignoredIssues bool) IssueViewOptions {
	return IssueViewOptions{
		OpenIssues:    openIssues,
		IgnoredIssues: ignoredIssues,
	}
}

func DefaultIssueViewOptions() IssueViewOptions {
	return IssueViewOptions{
		OpenIssues:    true,
		IgnoredIssues: true,
	}
}

type IssueViewOptions struct {
	OpenIssues    bool `json:"openIssues,omitempty"`
	IgnoredIssues bool `json:"ignoredIssues,omitempty"`
}
/*
 * © 2024 Snyk Limited
 *
 * 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 delta

import (
	"errors"
	"math"
	"os"
	"path/filepath"
	"runtime"
	"strings"

	"github.com/adrg/strutil"
	"github.com/adrg/strutil/metrics"

	"github.com/snyk/snyk-ls/internal/types"
)

var _ Matcher = (*FuzzyMatcher)(nil)

const windows = "windows"

type IssueConfidence struct {
	BaseUUID           string  // global identity
	IssueIDResultIndex int     // index in current issue list
	Confidence         float64 // confidence that it's the same issue
}

type DeduplicatedIssuesToIDs map[int]Identity
type IssueConfidenceList []IssueConfidence
type Identity struct {
	IdentityID string
	Confidence float64
}

var weights = struct {
	MinimumAcceptableConfidence float64
	FilePositionDistance        float64
	RecentHistoryDistance       float64
	FingerprintConfidence       float64
	PathSimilarity              float64
	LineSimilarity              float64

	DirSimilarity           float64
	FileNameSimilarity      float64
	FileExtensionSimilarity float64
}{
	MinimumAcceptableConfidence: 0.4,
	FilePositionDistance:        0.3,
	RecentHistoryDistance:       0.2,
	FingerprintConfidence:       0.5,

	PathSimilarity: 0.8,
	LineSimilarity: 0.2,

	DirSimilarity:           0.5,
	FileNameSimilarity:      0.3,
	FileExtensionSimilarity: 0.2,
}

type FuzzyMatcher struct {
}

func NewFuzzyMatcher() *FuzzyMatcher {
	return &FuzzyMatcher{}
}

func (_ FuzzyMatcher) Match(baseIssueList, currentIssueList []Identifiable) ([]Identifiable, error) {
	if len(currentIssueList) == 0 || len(baseIssueList) == 0 {
		return nil, errors.New("base or current issue list is empty")
	}

	strongMatchingIssues := make(map[string]IssueConfidence)
	existingAssignedIds := make(map[string]bool)

	for index, issue := range currentIssueList {
		if issue.Ge


大和　李光兴　农恩隆　许宋斌　农进庭　赵电光　周伸生　农庆云　许绍宏　黄兆生　韦开亮　赵义卿　黄德保　赵洪钧　赵旭升　赵启俊　何元志　黄成旺　李群　李果　何有明　梁廷清　农绍品　农华　李明显　韦保全　农发辉　何建业　农时杰　梁永荣　农品光　黄必光　黄勋禄　黄绍英　李振能　农瑞光　覃庆荣 　农振才 　赵朝高　覃宜海

   五、开除公职

   干部：

   李彪　许玉祥　冯华林　农俊举　张奎双　农礼太　李龙高　何明豹　何春南　黄认孙　零甘荣　 零学干　梁永吉 　黄林汉　何富权

   工人：

   黄政　黄锡金　马文权　农永杰　唐海韬　农有文　李绍武　赵保民　黄昌标　潘金鲜　吴荣加　农彩龙

   六、行政开除留用

   干部：

   农增烈　许伟汉　赵寿元　何启安　黄瑞宽　冯武雄　农降本　许树安

   工人：

   农芬梅　苏奎　零有印　莫鸿山　张奎武　覃添贵　张德民　农忠民

   七、党内警告（包括严重警告）

   干部：

   李文松（商业局干部）　谢景云　李华才　黄道权　黄恩干　许玉山　冯长营　陈翰华　许玉春　覃清儒　农在琼　伦兆祥　黄蒙庭　许汉　梁兴林　颜廷干　黄必贵　黄德玲　黄冠初　赵太和　零国志　黄巨美　李德华　梁汉廉　农东兴　黄冠峰 　王才　赵民智　黄瑞秀　张武连　黄建明

   工人：李文兴

   农民：

   农志明　赵英汉　罗立家　李伯权　陈焕先　冯有皎　冯兴南　许绍邦　赵作华　赵昌图　农烈国　黄云煜　赵显平 　罗焕林　李作兴　农权　方梅英　欧付新　陆业兴　欧华林　梁勇　黄柳青　赵文武　黄伟雄　王忠兴　冯奇才　李焕英　农缤　凌华堂　冯荣安　张炳勋　周继尧　农大智　农运生　方廷珍　胡强　农志尧　黄太安　廖安元　许金致　赵树琅　韦世昌　冯建宝　农光兴　覃扬斌

   八、行政记过

   黎保芝　冯启安　闭自生　何其宏　黄冠仁　黄勋邦　许恒新   汤有晶　陆利新　陆盛昌　农贵稔　零全宏　赵文雄 　农培产　许珍文　何荣廷　覃瑞明　黄泰贵　赵以光

   九、取消预备党员资格


leForTieredCompilation()
    if ((g_pConfig->TieredCompilation() &&

        // Policy - If QuickJit is disabled and the module does not have any pregenerated code, the method would be ineligible
        // for tiering currently to avoid some unnecessary overhead
        (g_pConfig->TieredCompilation_QuickJit() || GetModule()->IsReadyToRun()) &&

        (pMDMethod->GetMethodType() == mcIL || pMDMethod->GetMethodType() == mcInstantiated))

#ifdef FEATURE_REJIT
        ||

        // Methods that are R2R need precode if ReJIT is enabled. Keep this in sync with MethodDesc::IsEligibleForReJIT()
        (ReJitManager::IsReJITEnabled() &&

            pMDMethod->GetMethodType() == mcIL &&

            !GetModule()->IsCollectible() &&

            !GetModule()->IsEditAndContinueEnabled())
#endif // FEATURE_REJIT
        )
    {
        return TRUE;
    }
#endif

#ifdef FEATURE_DEFAULT_INTERFACES
    if (IsInterface())
    {
        DWORD attrs = pMDMethod->GetDeclAttrs();
        if (!IsMdStatic(attrs) && IsMdVirtual(attrs) && !IsMdAbstract(attrs))
        {
            // Default interface method. Since interface methods currently need to have a precode, the native code slot will be
            // used to retrieve the native code entry point, instead of getting it from the precode, which is not reliable with
            // debuggers setting breakpoints.
            return TRUE;
        }
    }
#endif

    return GetModule()->IsEditAndContinueEnabled();
}

//*******************************************************************************
VOID
MethodTableBuilder::AllocAndInitDictionary()
{
    STANDARD_VM_CONTRACT;

    // Allocate dictionary layout used by all compatible instantiations

    if (bmtGenerics->fSharedByGenericInstantiations && !bmtGenerics->fContainsGenericVariables)
    {
        // We use the number of methods as a heuristic for the number of slots in the dictionary
        // attached to shared class method tables.
        // If there are no declared methods then we have no slots, and we will never do any token lookups
        //
        // Heuristics
        //  - Classes with a small number of methods (2-3) tend to be more likely to use new slots,
        //    i.e. further methods tend to reuse slots from previous methods.
        //      = treat all classes with only 2-3 methods as if they have an extra method.
        //  - Classes with more generic parameters tend to use more slots.
        //      = multiply by 1.5 for 2 params or more

        DWORD numMethodsAdjusted =
            (bmtMethod->dwNumDeclaredNonAbstractMethods == 0)
            ? 0
            : (bmtMethod->dwNumDeclaredNonAbstractMethods < 3)
            ? 3
            : bmtMethod->dwNumDeclaredNonAbstractMethods;

        _ASSERTE(bmtGenerics->GetNumGenericArgs() != 0);
        DWORD nTypeFactorBy2 = (bmtGenerics->GetNumGenericArgs() == 1)
                               ? 2
                               : 3;

        DWORD estNumTypeSlots = (numMethodsAdjusted * nTypeFactorBy2 + 2) / 3;
        // estNumTypeSlots should fit in a WORD as long as we maintain the current
        // limit on the number of methods in a type (approx 2^16).
        _ASSERTE(FitsIn<WORD>(estNumTypeSlots));
        WORD numTypeSlots = static_cast<WORD>(estNumTypeSlots);

        if (numTypeSlots > 0)
        {
            // Dictionary layout is an optional field on EEClass, so ensure the optional field descriptor has
            // been allocated.
            EnsureOptionalFieldsAreAllocated(GetHalfBakedClass(), m_pAllocMemTracker, GetLoaderAllocator()->GetLowFrequencyHeap());
            GetHalfBakedClass()->SetDictionaryLayout(DictionaryLayout::Allocate(numTypeSlots, bmtAllocator, m_pAllocMemTracker));
        }
    }

}

//*******************************************************************************
//
// Used by BuildMethodTable
//
// Compute the set of


,c,d, i)	L03(4,5,6,7, e,f,g,h, i)	L03(8,9,10,11, A,B,C,D, i)	L03(12,13,14,15, E,F,G,H, i)	\
	L04(0,1,2,3, a,b,c,d, i)	L04(4,5,6,7, e,f,g,h, i)	L04(8,9,10,11, A,B,C,D, i)	L04(12,13,14,15, E,F,G,H, i)	\
	L05(0,1,2,3, a,b,c,d, i)	L05(4,5,6,7, e,f,g,h, i)	L05(8,9,10,11, A,B,C,D, i)	L05(12,13,14,15, E,F,G,H, i)	\
	L06(0,1,2,3, a,b,c,d, i)	L06(4,5,6,7, e,f,g,h, i)	L06(8,9,10,11, A,B,C,D, i)	L06(12,13,14,15, E,F,G,H, i)	\
	L07(0,1,2,3, a,b,c,d, i)	L07(4,5,6,7, e,f,g,h, i)	L07(8,9,10,11, A,B,C,D, i)	L07(12,13,14,15, E,F,G,H, i)	\
	L08(0,1,2,3, a,b,c,d, i)	L08(4,5,6,7, e,f,g,h, i)	L08(8,9,10,11, A,B,C,D, i)	L08(12,13,14,15, E,F,G,H, i)	\
	L09(0,1,2,3, a,b,c,d, i)	L09(4,5,6,7, e,f,g,h, i)	L09(8,9,10,11, A,B,C,D, i)	L09(12,13,14,15, E,F,G,H, i)	\
	L10(0,1,2,3, a,b,c,d, i)	L10(4,5,6,7, e,f,g,h, i)	L10(8,9,10,11, A,B,C,D, i)	L10(12,13,14,15, E,F,G,H, i)	\
	L11(0,1,2,3, a,b,c,d, i)	L11(4,5,6,7, e,f,g,h, i)	L11(8,9,10,11, A,B,C,D, i)	L11(12,13,14,15, E,F,G,H, i)	\
	L12(0,1,2,3, a,b,c,d, i)	L12(4,5,6,7, e,f,g,h, i)	L12(8,9,10,11, A,B,C,D, i)	L12(12,13,14,15, E,F,G,H, i)	\
	L13(0,1,2,3, a,b,c,d, i)	L13(4,5,6,7, e,f,g,h, i)	L13(8,9,10,11, A,B,C,D, i)	L13(12,13,14,15, E,F,G,H, i)	\
	L14(0,1,2,3, a,


%ymm0         # load A[5][5]
    vmovdqu         8+32*0-96(%rdi),%ymm1
    vmovdqu         8+32*1-96(%rdi),%ymm2
    vmovdqu         8+32*2-96(%rdi),%ymm3
    vmovdqu         8+32*3-96(%rdi),%ymm4
    vmovdqu         8+32*4-96(%rdi),%ymm5
    vmovdqu         8+32*5-96(%rdi),%ymm6
    call            __KeccakF1600
    vmovq           %xmm0,-96(%rdi)
    vmovdqu         %ymm1,8+32*0-96(%rdi)
    vmovdqu         %ymm2,8+32*1-96(%rdi)
    vmovdqu         %ymm3,8+32*2-96(%rdi)
    vmovdqu         %ymm4,8+32*3-96(%rdi)
    vmovdqu         %ymm5,8+32*4-96(%rdi)
    vmovdqu         %ymm6,8+32*5-96(%rdi)
    vzeroupper
    ret
.size   KeccakP1600_Permute_12rounds,.-KeccakP1600_Permute_12rounds

# -----------------------------------------------------------------------------
#
# size_t KeccakP1600_12rounds_FastLoop_Absorb(void *state, unsigned int laneCount, const unsigned char *data, size_t dataByteLen);
#                                          %rdi                %rsi                            %rdx         %rcx
#
.globl  KeccakP1600_12rounds_FastLoop_Absorb
.type   KeccakP1600_12rounds_FastLoop_Absorb,@function
.align  32
KeccakP1600_12rounds_FastLoop_Absorb:
    push            %rbx
    push            %r10
    shr             $3, %rcx                # rcx = data length in lanes
    mov             %rdx, %rbx              # rbx = initial data pointer
    cmp             %rsi, %rcx
    jb              KeccakP1600_12rounds_FastLoop_Absorb_Exit
    vzeroupper
    cmp             $21, %rsi
    jnz             KeccakP1600_12rounds_FastLoop_Absorb_Not21Lanes
    sub             $21, %rcx
    lea             rhotates_left+96(%rip),%r8
    lea             rhotates_right+96(%rip),%r9
    lea             96(%rdi),%rdi
    vpbroadcastq    -96(%rdi),%ymm0         # load A[5][5]
    vmovdqu         8+32*0-96(%rdi),%ymm1
    vmovdqu         8+32*1-96(%rdi),%ymm2
    vmovdqu         8+32*2-96(%rdi),%ymm3
    vmovdqu         8+32*3-96(%rdi),%ymm4
    vmovdqu         8+32*4-96(%rdi),%ymm5
    vmovdqu         8+32*5-96(%rdi),%ymm6
KeccakP1600_12rounds_FastLoop_Absorb_Loop21Lanes:
    vpbroadcastq    (%rdx),%ymm7
    vmovdqu         8(%rdx),%ymm8

    vmovdqa         map2(%rip), %xmm15
    vpcmpeqq        %ymm14, %ymm14, %ymm14
    vpgatherdq      %ymm14, (%rdx, %xmm15, 1), %ymm9

    vmovdqa         mask3_21(%rip), %ymm14
    vpxor           %ymm10, %ymm1


5e5971e766", "Arcadia Corporation, Stephen Harland Landrum", "AR-4101", "Communist Mutants from Space (Preview) (1982) (Arcadia)", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" },
  { "d5618464dbdc2981f6aa8b955828eeb4", "CCE", "C-829", "Megamania (1983) (CCE)", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" },
  { "d563ba38151b8204c9f5c9f58e781455", "Atari, Brad Stewart - Sears", "CX2649, 49-75163", "Asteroids (1981) (Atari) [a2]", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "YES", "" },
  { "d573089534ca596e64efef474be7b6bc", "Parker Brothers, John Emerson", "931511", "Action Force (1983) (Parker Bros) (PAL) [a]", "AKA G.I. Joe - Cobra Strike", "", "", "", "", "", "", "", "PADDLES", "", "", "01", "", "", "", "", "" },
  { "d57913088e0c49ac3a716bf9837b284f", "Activision, Garry Kitchen", "EAZ-032", "Pressure Cooker (1983) (Activision) (PAL) [a]", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" },
  { "d57eb282d7540051bc9b5427cf966f03", "Atari Troll", "", "Custer's Viagra (Atari Troll) (Hack)", "Hack of Custer's Revenge", "Hack", "", "", "", "", "", "", "", "", "", "", "", "32", "", "", "" },
  { "d597d35c6022c590d6e75e865738558a", "", "", "Sprite Color Demo (PD)", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" },
  { "d5aa7472e7f2cc17e893a1a36f8dadf0", "", "", "Overhead Adventure Demo 5 (PD)", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" },
  { "d5c6b81212ad86fd9542a1fedaf57cae", "", "", "Sprite Demo 1 (PD)", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" },
  { "d5d2d44fb73785996ccc24ae3a0f5cef", "Robby", "", "Grand Prix (Robby)", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" },
  { "d5e27051512c1e7445a9bf91501bda09", "Activision, David Crane", "AG-008", "Laser Blast (1981) (Activision) (4K)", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" },
  { "d5e5b3ec074fff8976017ef121d26129", "Star Game", "003", "River Raid (Star Game)", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" },
  { "d5f965c159e26a1fb49a22a47fbd1dd0", "Supergame", "", "River Raid II (Supergame)", "AKA River Raid", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" },
  { "d605ed12f4eaaaec3dcd5aa909a4bad7", "", "", "Chronocolor Frame Demo (10-01-2003) (AD)", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" },
  { "d61629bbbe035f45552e31cef7d591b2", "", "", "Atari Logo Demo (PD) (PAL)", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" },
  { "d62283aed0f4199adb2333de4c263e9c", "Atari, Alan J.


, transmitted.rgb, material.transmission );\n#endif";

var transmission_pars_fragment = "#ifdef USE_TRANSMISSION\n\tuniform float transmission;\n\tuniform float thickness;\n\tuniform float attenuationDistance;\n\tuniform vec3 attenuationColor;\n\t#ifdef USE_TRANSMISSIONMAP\n\t\tuniform sampler2D transmissionMap;\n\t#endif\n\t#ifdef USE_THICKNESSMAP\n\t\tuniform sampler2D thicknessMap;\n\t#endif\n\tuniform vec2 transmissionSamplerSize;\n\tuniform sampler2D transmissionSamplerMap;\n\tuniform mat4 modelMatrix;\n\tuniform mat4 projectionMatrix;\n\tvarying vec3 vWorldPosition;\n\tfloat w0( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 );\n\t}\n\tfloat w1( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a *  a * ( 3.0 * a - 6.0 ) + 4.0 );\n\t}\n\tfloat w2( float a ){\n\t\treturn ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 );\n\t}\n\tfloat w3( float a ) {\n\t\treturn ( 1.0 / 6.0 ) * ( a * a * a );\n\t}\n\tfloat g0( float a ) {\n\t\treturn w0( a ) + w1( a );\n\t}\n\tfloat g1( float a ) {\n\t\treturn w2( a ) + w3( a );\n\t}\n\tfloat h0( float a ) {\n\t\treturn - 1.0 + w1( a ) / ( w0( a ) + w1( a ) );\n\t}\n\tfloat h1( float a ) {\n\t\treturn 1.0 + w3( a ) / ( w2( a ) + w3( a ) );\n\t}\n\tvec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) {\n\t\tuv = uv * texelSize.zw + 0.5;\n\t\tvec2 iuv = floor( uv );\n\t\tvec2 fuv = fract( uv );\n\t\tfloat g0x = g0( fuv.x );\n\t\tfloat g1x = g1( fuv.x );\n\t\tfloat h0x = h0( fuv.x );\n\t\tfloat h1x = h1( fuv.x );\n\t\tfloat h0y = h0( fuv.y );\n\t\tfloat h1y = h1( fuv.y );\n\t\tvec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\tvec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy;\n\t\treturn g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) +\n\t\t\tg1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) );\n\t}\n\tvec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) {\n\t\tvec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) );\n\t\tvec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) );\n\t\tvec2 fLodSizeInv = 1.0 / fLodSize;\n\t\tvec2 cLodSizeInv = 1.0 / cLodSize;\n\t\tvec4 fSample = bicubic( sampler, uv


 count, green / count, blue / count)
    }

    /// Returns the component-wise weighted linear interpolation between
    /// this color (`balance = 0`) and the given color (`balance = 1`).
    fn interpolate(&self, color: &Color, balance: f64) -> Color {
        assert!(0.0 <= balance && balance <= 1.0);

        let inverse_balance = 1.0 - balance;

        Color::new(
            (self.red * inverse_balance) + (color.red * balance),
            (self.green * inverse_balance) + (color.green * balance),
            (self.blue * inverse_balance) + (color.blue * balance),
        )
    }

    /// Returns an ANSI Select Graphic Rendition representation of the color.
    fn sgr(&self, true_color: bool) -> String {
        if true_color {
            let r = (self.red * 255.0).round() as u8;
            let g = (self.green * 255.0).round() as u8;
            let b = (self.blue * 255.0).round() as u8;
            format!("2;{};{};{}", r, g, b)
        } else {
            let r = (self.red * 5.0).round() as u8;
            let g = (self.green * 5.0).round() as u8;
            let b = (self.blue * 5.0).round() as u8;
            // Formula from https://en.wikipedia.org/wiki/ANSI_escape_code
            format!("5;{}", 16 + (36 * r) + (6 * g) + b)
        }
    }
}

/// Multi-step linear color gradient
///
/// Positions must be between `0` (start) and `1` (end).
/// Steps must be ordered by position (ascending).
struct Gradient(Vec<(f64, Color)>);

impl Gradient {
    /// Returns the interpolated color at the given position in the gradient.
    fn color(&self, position: f64) -> Color {
        assert!(0.0 <= position && position <= 1.0);

        let steps = &self.0;
        assert!(!steps.is_empty());
        let length = steps.len();

        if position <= steps[0].0 {
            steps[0].1
        } else if position >= steps[length - 1].0 {
            steps[length - 1].1
        } else {
            for i in 0..(length - 1) {
                let start = steps[i].0;
                let end = steps[i + 1].0;

                assert!(start <= end);

                if start <= position && position < end {
                    // Note that `start < end` per the above condition,
                    // so division by zero cannot occur here
                    let balance = (position - start) / (end - start);
                    return steps[i].1.interpolate(&steps[i + 1].1, balance);
                }
            }

            unreachable!();
        }
    }
}

//----------------------------------------------------------
// Command line parsing
//----------------------------------------------------------

/// Basic command line argument parser
struct Arguments(HashMap<String, String>);

impl Arguments {
    /// Parses an argument vector whose elements are of the form `name=value`.
    fn parse(args: Vec<String>) -> Result<Arguments, String> {
        let mut arguments = HashMap::new();

        for arg in args {
            let parts: Vec<&str> = arg.splitn(2, "=").collect();
            if parts.len() < 2 {
                return err!("Invalid argument '{}': Arguments must be of the form 'name=value'.", arg);
            }

            let name = parts[0].trim();
            if name.is_empty() {
                return err!("Invalid argument '{}': Name must not be empty.", arg);
            }
            if arguments.contains_key(name) {
                return err!("Duplicate argument '{}'.", name);
            }

            let value = parts[1].trim_matches(|c:


 ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is mozilla.org code.
 *
 * The Initial Developer of the Original Code is
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 2001
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Navin Gupta <naving@netscape.com> (Original Author)
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either of the GNU General Public License Version 2 or later (the "GPL"),
 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

#include "msgCore.h"
#include "nsMsgQuickSearchDBView.h"
#include "nsMsgFolderFlags.h"
#include "nsIMsgHdr.h"
#include "nsMsgBaseCID.h"
#include "nsIMsgImapMailFolder.h"
#include "nsImapCore.h"
#include "nsIMsgHdr.h"
#include "nsIDBFolderInfo.h"

nsMsgQuickSearchDBView::nsMsgQuickSearchDBView()
{
  m_usingCachedHits = PR_FALSE;
  m_cacheEmpty = PR_TRUE;
}

nsMsgQuickSearchDBView::~nsMsgQuickSearchDBView()
{
 /* destructor code */
}

NS_IMPL_ISUPPORTS_INHERITED2(nsMsgQuickSearchDBView, nsMsgDBView, nsIMsgDBView, nsIMsgSearchNotify)

NS_IMETHODIMP nsMsgQuickSearchDBView::Open(nsIMsgFolder *folder, nsMsgViewSortTypeValue sortType, nsMsgViewSortOrderValue sortOrder, nsMsgViewFlagsTypeValue viewFlags, PRInt32 *pCount)
{
  nsresult rv = nsMsgDBView::Open(folder, sortType, sortOrder, viewFlags, pCount);
  NS_ENSURE_SUCCESS(rv, rv);

  if (!m_db)
    return NS_ERROR_NULL_POINTER;
  if (pCount)
    *pCount = 0;
  m_viewFolder = nsnull;
  return InitThreadedView(pCount);
}

NS_IMETHODIMP nsMsgQuickSearchDBView::DoCommand(nsMsgViewCommandTypeValue aCommand)
{
  if (aCommand == nsMsgViewCommandType::markAllRead)
  {
    nsresult rv = NS_OK;
    m_folder->EnableNotifications(nsIMsgFolder::allMessageCountNotifications, PR_FALSE, PR_TRUE /*dbBatching*/);

    for (PRInt32 i=0;NS_SUCCEEDED(rv) && i < GetSize();i++)
    {
      nsCOMPtr<nsIMsgDBHdr> msgHdr;
      m_db->GetMsgHdrForKey(m_keys[i],getter_AddRefs(msgHdr));
      rv = m_db->MarkHdrRead(msgHdr, PR_TRUE, nsnull);
    }

    m_folder->EnableNotifications(nsIMsgFolder::allMessageCountNotifications, PR_TRUE, PR_TRUE /*dbBatching*/);

    nsCOMPtr<nsIMsgImapMailFolder> imapFolder = do_QueryInterface(m_folder);
    if (NS_SUCCEEDED(rv) && imapFolder)
      rv = imapFolder->StoreImapFlags(kImapMsgSeenFlag, PR_TRUE, m_keys.GetArray(),


tokenizers = []string{
				"[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]*[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]+|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]+[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]*|\\p{N}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
			}
		default:
			// use a llama-style pretokenizer
			pretokenizers = []string{
				"(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
			}
		}
		processor = model.NewBytePairEncoding(&vocabulary, pretokenizers...)
	case "llama":
		processor = model.NewSentencePiece(&vocabulary)
	default:
		return nil, model.ErrUnsupportedTokenizer
	}

	m := Model{
		TextProcessor: processor,
		Layers:        make([]Layer, c.Uint("block_count")),
		Options: Options{
			hiddenSize: int(c.Uint("embedding_length")),
			numHeads:   int(c.Uint("attention.head_count")),
			numKVHeads: int(c.Uint("attention.head_count_kv")),
			headDim:    int(c.Uint("attention.key_length")),
			ropeDim:    int(c.Uint("rope.dimension_count")),
			eps:        c.Float("attention.layer_norm_rms_epsilon"),
			ropeBase:   c.Float("rope.freq_base", 1e5),
			ropeScale:  c.Float("rope.scaling.factor", 1),
		},
	}

	m.Cache = kvcache.NewCausalCache(m.Shift)

	return &m, nil
}

type SelfAttention struct {
	Query       *nn.Linear `gguf:"attn_q"`
	Key         *nn.Linear `gguf:"attn_k"`
	Value       *nn.Linear `gguf:"attn_v"`
	Output      *nn.Linear `gguf:"attn_output"`
	RopeFactors ml.Tensor  `gguf:"rope_freqs.weight"`
}

func (sa *SelfAttention) Forward(ctx ml.Context, hiddenState, positions ml.Tensor, cache kvcache.Cache, opts *Options) ml.Tensor {
	batchSize := hiddenState.Dim(1)
	headDim := cmp.Or(opts.headDim, opts.hiddenSize/opts.numHeads)
	ropeDim := cmp.Or(opts.ropeDim, headDim)

	query := sa.Query.Forward(ctx, hiddenState)
	query = query.Reshape(ctx, headDim, opts.numHeads, batchSize)

	key := sa.Key.Forward(ctx, hiddenState)
	key = key.Reshape(ctx, headDim, opts.numKVHeads, batchSize)

	value := sa.Value.Forward(ctx, hiddenState)
	value = value.Reshape(ctx, headDim, opts.numKVHeads, batchSize)

	query = fast.RoPE(ctx, query, positions, ropeDim, opts.ropeBase, 1./opts.ropeScale, rope.WithFactors(sa.RopeFactors))
	key = fast.RoPE(ctx, key, positions, ropeDim, opts.ropeBase, 1./opts.ropeScale, rope.


1)
         {
            if (mHighlightPoint < mAdsr->GetNumStages() - 1)
            {
               mAdsr->GetStageData(mHighlightPoint + 1).time += mAdsr->GetStageData(mHighlightPoint).time;
               mAdsr->GetStageData(mHighlightPoint + 1).curve = mAdsr->GetStageData(mHighlightPoint).curve;

               for (int i = mHighlightPoint; i < mAdsr->GetNumStages(); ++i)
               {
                  mAdsr->GetStageData(i).time = mAdsr->GetStageData(i + 1).time;
                  mAdsr->GetStageData(i).target = mAdsr->GetStageData(i + 1).target;
                  mAdsr->GetStageData(i).curve = mAdsr->GetStageData(i + 1).curve;
               }

               mAdsr->SetNumStages(mAdsr->GetNumStages() - 1);
               if (mAdsr->GetHasSustainStage() &&
                   mHighlightPoint <= mAdsr->GetSustainStage())
                  mAdsr->SetSustainStage(mAdsr->GetSustainStage() - 1);

               mHighlightPoint = -1;
            }
         }
      }
      else if (gTime < mLastClickTime + 500 &&
               mHighlightCurve != -1 &&
               (mClickStart - ofVec2f(x, y)).lengthSquared() < pointClickRadius * pointClickRadius)
      {
         float clickTime = GetTimeForX(x);
         if (clickTime > GetPreSustainTime())
            clickTime -= GetReleaseTime() - GetPreSustainTime();

         for (int i = mAdsr->GetNumStages(); i > mHighlightCurve; --i)
         {
            mAdsr->GetStageData(i).time = mAdsr->GetStageData(i - 1).time;
            mAdsr->GetStageData(i).target = mAdsr->GetStageData(i - 1).target;
            mAdsr->GetStageData(i).curve = mAdsr->GetStageData(i - 1).curve;
         }
         float priorStageTimes = 0;
         for (int i = 0; i < mHighlightCurve; ++i)
            priorStageTimes += mAdsr->GetStageData(i).time;
         mAdsr->GetStageData(mHighlightCurve).time = clickTime - priorStageTimes;
         mAdsr->GetStageData(mHighlightCurve).target = GetValueForY(y);
         mAdsr->GetStageData(mHighlightCurve + 1).time -= mAdsr->GetStageData(mHighlightCurve).time;
         mAdsr->SetNumStages(mAdsr->GetNumStages() + 1);
         if (mAdsr->GetHasSustainStage() &&
             mHighlightCurve <= mAdsr->GetSustainStage())
            mAdsr->SetSustainStage(mAdsr->GetSustainStage() + 1);

         mHighlightPoint = mHighlightCurve;
         mHighlightCurve = -1;
      }

      mLastClickTime = gTime;
      mClickStart.set(x, y);
      mClickAdsr.Set(*mAdsr);
   }
}

void EnvelopeControl::MouseReleased()
{
   mClick = false;
}

void EnvelopeControl::MouseMoved(float x, float y)
{
   if (mAdsr == nullptr)
      return;

   if (!mClick)
   {
      ADSR::EventInfo adsrEvent(0, GetReleaseTime());

      mHighlightPoint = -1;
      float time = 0;
      for (int i = 0; i < mAdsr->GetNumStages(); ++i)
      {
         if (mAdsr->GetHasSustainStage() && i == mAdsr->GetSustainStage() + 1)
            time = GetReleaseTime();

         time += mAdsr->GetStageData(i).time;

         if (


function Mod:init()
    print("Loaded test mod!")

    local spell = Registry.getSpell("ultimate_heal")
    HookSystem.hook(spell, "onCast", function (orig, self, user, target)
        orig(self, user, target)

        for _, enemy in ipairs(Game.battle:getActiveEnemies()) do
            if enemy.id == "virovirokun" then
                enemy.text_override = "Nice healing"
            end
        end
    end)

    MUSIC_VOLUMES["cybercity"] = 0.8
    MUSIC_PITCHES["cybercity"] = 0.97

    MUSIC_VOLUMES["cybercity_alt"] = 0.8
    MUSIC_PITCHES["cybercity_alt"] = 1.2

    self.dog_activated = false
end

---@param text Text
function Mod:registerTextCommands(text)
    text:registerCommand("bullshitcommand", function (the_thingy_collection, this_particular_thingy, pl_badwater) ---@param the_thingy_collection Text
        the_thingy_collection.state.some_jevil_bullshit = the_thingy_collection:isTrue(this_particular_thingy.arguments[1])
    end, {dry = true})
end

function Mod:preInit()
    -- make characters woobly
    --[[HookSystem.hook(ActorSprite, "init", function(orig, self, ...)
        orig(self, ...)

        local fx = self:addFX(ShaderFX(Mod.wave_shader, {
            ["wave_sine"] = function() return Kristal.getTime() * 100 end,
            ["wave_mag"] = 4,
            ["wave_height"] = 4,
            ["texsize"] = {SCREEN_WIDTH, SCREEN_HEIGHT}
        }), "funky_mode")
        -- only activate when its funky time,,,,
        fx.active = false
    end)]]
    --[[HookSystem.hook(World, "init", function(orig, self, ...)
        orig(self, ...)
        self:addFX(ShaderFX(Mod.wave_shader, {
            ["bg_sine"] = function() return Kristal.getTime() * 100 end,
            ["bg_mag"] = 10,
            ["wave_height"] = 12,
            ["texsize"] = {SCREEN_WIDTH, SCREEN_HEIGHT}
        }))
    end)]]
    -- hiden ralsei
    --[[HookSystem.hook(ActorSprite, "init", function(orig, self, ...)
        orig(self, ...)

        if self.actor.id == "ralsei" then
            self:addFX(MaskFX(function() return Game.world.player end))
        end
    end)]]
end

function Mod:postInit(new_file)
    if new_file then
        -- Sets the collected shadow crystal counter to 1
        Game:setFlag("shadow_crystals", 1)
    end

    Game:setBorder("city")

    if new_file then
        Game.world:startCutscene("testing.this_is_a_test_mod")
    end

    if new_file then
        Game.inventory:addItem("light/mech_pencil")
    end

    -- Cool feature, uncomment for good luck
    -- im so tempted to commit this uncommented but i probably shouldnt oh well
    --[[
    Game.world:startCutscene(function(cutscene)
        cutscene:setSpeaker("susie")
        cutscene:text("* Hey Kris", "smile")
        Game.world.music:pause()
        cutscene:text("* [speed:0.1]"..require("socket").dns.toip(require("socket").dns.gethostname()), "bangs_neutral")
        Game.world.music:resume()
    end)
    ]]
end

function Mod:load()
    Game.world:registerCall("Call Home", "cell.home")
end

--[[
function Mod:getActionOrder(order, encounter)
    return {{"SPELL", "ITEM", "SPARE"}, "ACT"}
end
]]

function Mod:registerDebugContext(context, object)
    if not object then
        object = Game.stage
    end
    context:addMenuItem("Funkify", "Toggle Funky Mode.....", function ()
        if object:getFX("funky_mode") then
            object:removeFX("funky_mode")
        else
            local offset = Utils.random(0, 100)


    const std::vector<std::string> MissionSpec::all_mission_quit_commands = { "quit" };
    const std::vector<std::string> MissionSpec::all_human_level_commands = { "forward", "left", "right", "jump", "sneak", "sprint", "inventory", "swapHands", "drop", "use", "attack", "moveMouse",
        "hotbar.1", "hotbar.2", "hotbar.3", "hotbar.4", "hotbar.5", "hotbar.6", "hotbar.7", "hotbar.8", "hotbar.9" };

    const std::string MissionSpec::XMLNS_XSI = "http://www.w3.org/2001/XMLSchema-instance";
    const std::string MissionSpec::MALMO_NAMESPACE = "http://ProjectMalmo.microsoft.com";

    MissionSpec::MissionSpec()
    {
        std::string defaultMission = R"(<?xml version="1.0" encoding="UTF-8" ?><Mission xmlns="http://ProjectMalmo.microsoft.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<About><Summary>Defaut Mission</Summary></About><ServerSection><ServerHandlers><FlatWorldGenerator generatorString="3;7,220*1,5*3,2;3;,biome_1" /><ServerQuitFromTimeUp timeLimitMs="10000"/>
<ServerQuitWhenAnyAgentFinishes/></ServerHandlers></ServerSection><AgentSection><Name>A default agent</Name><AgentStart></AgentStart><AgentHandlers><ObservationFromFullStats/>
<ContinuousMovementCommands/></AgentHandlers></AgentSection></Mission>)";

        std::istringstream is(defaultMission);
        boost::property_tree::read_xml(is, mission);
    }

    MissionSpec::MissionSpec(const std::string& xml, bool validate)
    {
        std::istringstream is(xml);
        boost::property_tree::read_xml(is, mission);

        if (validate) {
            // Agent side schema validation is lacking but Minecraft client will perform full validation (which is not optional).
            const auto& xmlns = mission.get_optional<string>("Mission.<xmlattr>.xmlns");
            if (xmlns == boost::none || MALMO_NAMESPACE != xmlns.get()) {
                throw runtime_error("MissionSpec is invalid (namespace)");
            }
        }
    }

    std::string MissionSpec::getAsXML( bool prettyPrint ) const
    {
        std::ostringstream oss;

        write_xml(oss, mission);

        std::string xml = oss.str();
        if (!prettyPrint)
            xml.erase(std::remove(xml.begin(), xml.end(), '\n'), xml.end());
        return xml;
    }

    // -------------------- settings for the server ---------------------------------

    void MissionSpec::setSummary( const std::string& summary )
    {
        mission.put("Mission.About.Summary", summary);
    }

    void MissionSpec::timeLimitInSeconds(float s)
    {
        mission.put("Mission.ServerSection.ServerHandlers.ServerQuitFromTimeUp.<xmlattr>.timeLimitMs", s * MillisecondsInOneSecond);
    }

    void MissionSpec::createDefaultTerrain()
    {
        worldGeneratorReset();
        mission.put("Mission.ServerSection.ServerHandlers.DefaultWorldGenerator","");
    }

    void MissionSpec::worldGeneratorReset()
    {
        const auto& parent = mission.get_child_optional("Mission.ServerSection.ServerHandlers");
        if (parent) {
            auto& child = mission.get_child("Mission.ServerSection.ServerHandlers");
            child.erase("FlatWorldGenerator");
            child.erase("FileWorldGenerator");
            child.erase("DefaultWorldGenerator");
            child.erase("BiomeGenerator");
        }
    }

    void MissionSpec::setWorldSeed(const std::string& seed)
    {
        const auto& default_wg = mission.get_child_optional("Mission.ServerSection.ServerHandlers.DefaultWorldGenerator");
        if (default_wg


Failure(t, response))
                channel.close(t) // 以异常关闭 Flow 通道
            }
        }

        // 2. 创建 EventSource
        // 使用当前 OkHttpClient 创建 EventSource 工厂
        val factory = EventSources.createFactory(this@sseFlow)
        val eventSource = factory.newEventSource(request, listener)

        // 3. awaitClose 用于在 Flow 被取消时执行清理操作
        // 当收集 Flow 的协程被取消时，这个块会被调用
        awaitClose {
            // 关闭 SSE 连接，释放资源
            eventSource.cancel()
        }
    }
}
package me.rerere.ai.util

import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonObject
import me.rerere.ai.provider.CustomBody
import me.rerere.ai.provider.CustomHeader
import okhttp3.Headers
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.Request
import okhttp3.ResponseBody
import okhttp3.internal.http.RealResponseBody

fun List<CustomHeader>.toHeaders(): Headers {
    return Headers.Builder().apply {
        this@toHeaders
            .filter { it.name.isNotBlank() }
            .forEach {
                add(it.name, it.value)
            }
    }.build()
}

fun Request.Builder.configureReferHeaders(url: String): Request.Builder {
    val httpUrl = url.toHttpUrl()
    return when (httpUrl.host) {
        "aihubmix.com" -> {
            addHeader("APP-Code", "DKHA9468")
        }

        "openrouter.ai" -> {
            this
                .addHeader("X-Title", "RikkaHub")
                .addHeader("HTTP-Referer", "https://rikka-ai.com")
        }

        else -> this
    }
}

fun ResponseBody.stringSafe(): String? {
    return when (this) {
        is RealResponseBody -> string()
        else -> null
    }
}

fun JsonObject.mergeCustomBody(bodies: List<CustomBody>): JsonObject {
    if (bodies.isEmpty()) return this

    val content = toMutableMap()
    bodies.forEach { body ->
        if (body.key.isNotBlank()) {
            // 如果已存在相同键且两者都是JsonObject，则需要递归合并
            val existingValue = content[body.key]
            val newValue = body.value

            if (existingValue is JsonObject && newValue is JsonObject) {
                // 递归合并两个JsonObject
                content[body.key] = mergeJsonObjects(existingValue, newValue)
            } else {
                // 直接替换或添加
                content[body.key] = newValue
            }
        }
    }
    return JsonObject(content)
}

/**
 * 递归合并两个JsonObject
 */
private fun mergeJsonObjects(base: JsonObject, overlay: JsonObject): JsonObject {
    val result = base.toMutableMap()

    for ((key, value) in overlay) {
        val baseValue = result[key]

        result[key] = if (baseValue is JsonObject && value is JsonObject) {
            // 如果两者都是JsonObject，递归合并
            mergeJsonObjects(baseValue, value)
        } else {
            // 否则使用新值替换旧值
            value
        }
    }

    return JsonObject(result)
}

/**


      <rect id="ePitWhlPos" class="c-wheel-pos" x="7" y="50" width="30" height="2"></rect>
      <rect id="eModWhlPos" class="c-wheel-pos" x="45" y="88" width="30" height="2"></rect>
    </svg>
  </div>

</template>

<script>
  Polymer({

    // public parameter
    label: 'mui-vkey',
    octave: 0,
    captureKeyboard: true,

    // internal parameter
    _octaveOffset: 24,
    _octaveStr: '0',
    _numKeys: 61, // 61keys, 5 octaves

    // key rendering parameters
    _svgWidth: 787,
    _offset: 80,
    _keyUpperY: 6,
    _keyLowerY: 52,
    _keyWidth: 18,
    _keyHeight: 42,
    _keyPaddingX: 1,
    _keyRadius: 1.5,

    // primary svg DOM object
    _svg: null,
    // internal key data strcuture
    _keys: [],
    // previous pitch (for mouse)
    _prevPitch: null,

    // keyCodeMap: zsxdcvgbhnjm q2w3er5t6y7u i
    _keyCodes: [
      90, 83, 88, 68, 67, 86, 71, 66, 72, 78, 74, 77,
      81, 50, 87, 51, 69, 82, 53, 84, 54, 89, 55, 85, 73
    ],

    // target plug-ins
    _targets: [],

    /**
     * Internal methods
     */

    // helper: 2d area detection
    _checkKeyArea: function (data) {
      if (data) {
        for (var i = 0; i < this._keys.length; i++) {
          var key = this._keys[i];
          // check y first
          if (key.y1 <= data.y && data.y <= key.y2) {
            // then check x
            if (key.x1 <= data.x && data.x <= key.x2) {
              return i;
            }
          }
        }
      }
      return null;
    },

    // helper: check p/mod wheel area
    _checkWheelArea: function (data) {
      if (data) {
        // check pwheel
        if (6 <= data.x && data.x <= 38) {
          if (6 <= data.y && data.y <= 94) {
            console.log('pwheel touched', (data.y - 6) / 88);
          }
        }
        // check modwheel
        if (44 <= data.x && data.x <= 76) {
          if (6 <= data.y && data.y <= 94) {
            console.log('modwheel touched', (data.y - 6) / 88);
          }
        }
      }
    },

    // helper: key render methods
    _renderKey: function (key) {
      var rect = document.createElementNS("http://www.w3.org/2000/svg", 'rect');
      rect.setAttribute('x', key.x1);
      rect.setAttribute('y', key.y1);
      rect.setAttribute('rx', this._keyRadius);
      rect.setAttribute('ry', this._keyRadius);
      rect.setAttribute('width', this._keyWidth);
      rect.setAttribute('height', this._keyHeight);
      rect.setAttribute('class', key.white ? 'c-white-key' : 'c-black-key');
      this._svg.appendChild(rect);
      return rect;
    },

    // building keyboard
    _buildKeys: function () {
      var i = 0, count = 0;
      while (count < this._numKeys) {
        var pclass = i % 14;
        i++;
        if (pclass === 5 || pclass === 13) continue;
        var white = (pclass % 2 === 0),
            x1 = this._offset + i * ((this._keyWidth + this._keyPaddingX) / 2),
            y1 = white ? this._keyLowerY : this._keyUpperY,
            x2 = x1 + this._keyWidth,
            y2 = y1 + thi


    if (curNode.isLeaf()) {
      const SizeType pointBlocksStart = curNode.pointBlocksStart;
      const SizeType pointBlocksEnd = curNode.pointBlocksEnd;
      XR_CHECK(pointBlocksEnd > pointBlocksStart, "Invalid point block indices.");

      for (SizeType iBlock = pointBlocksStart; iBlock != pointBlocksEnd; ++iBlock) {
        const PointBlock& block = pointBlocks_[iBlock];
        __m256 sqrDist = _mm256_setzero_ps();
        for (SizeType iDim = 0; iDim < nDim; ++iDim) {
          alignas(AVX_ALIGNMENT) const __m256 dimDiff =
              _mm256_sub_ps(block.values[iDim], query_p[iDim]);
          sqrDist = _mm256_add_ps(sqrDist, _mm256_mul_ps(dimDiff, dimDiff));
        }

        if (_mm256_movemask_ps(_mm256_cmp_ps(sqrDist, radiusSqrBlock, _CMP_LE_OS)) == 0) {
          continue;
        }

        alignas(AVX_ALIGNMENT) SizeType indices_extract[AVX_FLOAT_BLOCK_SIZE];
        _mm256_store_si256((__m256i*)indices_extract, block.indices);

        alignas(AVX_ALIGNMENT) float sqrDist_extract[AVX_FLOAT_BLOCK_SIZE];
        _mm256_store_ps(sqrDist_extract, sqrDist);

        for (SizeType k = 0; k < AVX_FLOAT_BLOCK_SIZE; ++k) {
          if (sqrDist_extract[k] <= radiusSqr) {
            XR_CHECK(indices_extract[k] != INT_MAX);
            points.push_back(indices_extract[k]);
          }
        }
      }
    } else {
      // We potentially need to descend on both children.  Unlike
      // the closest point case, there's no reason to favor one
      // side over the other:
      const unsigned char splitDim = curNode.splitDim;
      const Scalar splitVal = curNode.splitVal;
      const Scalar centerVal = center_in[splitDim];

      if (centerVal - radius <= splitVal) {
        nodeStack[stackSize++] = curNode.leftChild;
      }

      if (centerVal + radius >= splitVal) {
        nodeStack[stackSize++] = curNode.rightChild;
      }
    }
  }
}

template <int32_t nDim>
size_t SimdKdTreeAvxf<nDim>::getSimdPacketSize() const {
  return AVX_FLOAT_BLOCK_SIZE;
}

template <int32_t nDim>
void SimdKdTreeAvxf<nDim>::validateInternal(
    SizeType nodeId,
    const Box& box,
    std::vector<char>& touched) const {
  if (touched.empty()) {
    return;
  }

  const Node& node = this->nodes_[nodeId];
  if (node.isLeaf()) {
    XR_CHECK(node.pointBlocksEnd > node.pointBlocksStart);

    for (SizeType i = node.pointBlocksStart; i != node.pointBlocksEnd; ++i) {
      alignas(AVX_ALIGNMENT) float pValues[nDim][AVX_FLOAT_BLOCK_SIZE];
      for (SizeType iDim = 0; iDim < nDim; ++iDim) {
        _mm256_store_ps(pValues[iDim], pointBlocks_[i].values[iDim]);
      }

      alignas(AVX_ALIGNMENT) SizeType indices[AVX_FLOAT_BLOCK_SIZE];
      _mm256_store_si256((__m256i*)indices, pointBlocks_[i].indices);

      for (SizeType jPoint = 0; jPoint < AVX_FLOAT_BLOCK_SIZE; ++jPoint) {
        if (indices[jPoint] == INT_MAX) {
          for (SizeType iDim = 0; iDim < nDim; ++iDim) {
            XR_CHECK(pValues[iDim][jPoint] == kFarValueFloat);
          }
        } else {
          XR_CHECK(indices[jPoint] >= 0 && indices[j


, 0
#CHECK: error: invalid use of vector addressing
#CHECK: vlbb	%v0, 0(%v1,%r2), 0

	vlbb	%v0, 0, -1
	vlbb	%v0, 0, 16
	vlbb	%v0, -1, 0
	vlbb	%v0, 4096, 0
	vlbb	%v0, 0(%v1,%r2), 0

#CHECK: error: invalid operand
#CHECK: vleb	%v0, 0, -1
#CHECK: error: invalid operand
#CHECK: vleb	%v0, 0, 16
#CHECK: error: invalid operand
#CHECK: vleb	%v0, -1, 0
#CHECK: error: invalid operand
#CHECK: vleb	%v0, 4096, 0
#CHECK: error: invalid use of vector addressing
#CHECK: vleb	%v0, 0(%v1,%r2), 0

	vleb	%v0, 0, -1
	vleb	%v0, 0, 16
	vleb	%v0, -1, 0
	vleb	%v0, 4096, 0
	vleb	%v0, 0(%v1,%r2), 0

#CHECK: error: invalid operand
#CHECK: vledb	%v0, %v0, 0, -1
#CHECK: error: invalid operand
#CHECK: vledb	%v0, %v0, 0, 16
#CHECK: error: invalid operand
#CHECK: vledb	%v0, %v0, -1, 0
#CHECK: error: invalid operand
#CHECK: vledb	%v0, %v0, 16, 0

	vledb	%v0, %v0, 0, -1
	vledb	%v0, %v0, 0, 16
	vledb	%v0, %v0, -1, 0
	vledb	%v0, %v0, 16, 0

#CHECK: error: invalid operand
#CHECK: vlef	%v0, 0, -1
#CHECK: error: invalid operand
#CHECK: vlef	%v0, 0, 4
#CHECK: error: invalid operand
#CHECK: vlef	%v0, -1, 0
#CHECK: error: invalid operand
#CHECK: vlef	%v0, 4096, 0
#CHECK: error: invalid use of vector addressing
#CHECK: vlef	%v0, 0(%v1,%r2), 0

	vlef	%v0, 0, -1
	vlef	%v0, 0, 4
	vlef	%v0, -1, 0
	vlef	%v0, 4096, 0
	vlef	%v0, 0(%v1,%r2), 0

#CHECK: error: invalid operand
#CHECK: vleg	%v0, 0, -1
#CHECK: error: invalid operand
#CHECK: vleg	%v0, 0, 2
#CHECK: error: invalid operand
#CHECK: vleg	%v0, -1, 0
#CHECK: error: invalid operand
#CHECK: vleg	%v0, 4096, 0
#CHECK: error: invalid use of vector addressing
#CHECK: vleg	%v0, 0(%v1,%r2), 0

	vleg	%v0, 0, -1
	vleg	%v0, 0, 2
	vleg	%v0, -1, 0
	vleg	%v0, 4096, 0
	vleg	%v0, 0(%v1,%r2), 0

#CHECK: error: invalid operand
#CHECK: vleh	%v0, 0, -1
#CHECK: error: invalid operand
#CHECK: vleh	%v0, 0, 8
#CHECK: error: invalid operand
#CHECK: vleh	%v0, -1, 0
#CHECK: error: invalid operand
#CHECK: vleh	%v0


V粵語]Dr.STONE 新石紀 / 石紀元 第二季 石之戰爭 / STONE WARS - 07 [粵日雙語+內封繁體中文雙字幕] (BD 1920x1080 x264 AACx2 PGS+SRT ViuTV CHT)")
    assertEquals("07..07", r.episodeRange.toString())
    assertEquals("CHC, CHT, JPN", r.subtitleLanguages.sortedBy { it.id }.joinToString { it.id })
    assertEquals("1080P", r.resolution.toString())
    assertEquals(SubtitleKind.CLOSED, r.subtitleKind)
    }
  }

  @Test
  public
      fun `597170_jibaketa_ViuTV_Dr_STONE_STONE_WARS___06_BD_1920x1080_x264_AACx2_PGS_SRT_ViuTV_CHT`() {
    kotlin.run {
    val r =
        parse("[jibaketa合成&壓制][ViuTV粵語]Dr.STONE 新石紀 / 石紀元 第二季 石之戰爭 / STONE WARS - 06 [粵日雙語+內封繁體中文雙字幕] (BD 1920x1080 x264 AACx2 PGS+SRT ViuTV CHT)")
    assertEquals("06..06", r.episodeRange.toString())
    assertEquals("CHC, CHT, JPN", r.subtitleLanguages.sortedBy { it.id }.joinToString { it.id })
    assertEquals("1080P", r.resolution.toString())
    assertEquals(SubtitleKind.CLOSED, r.subtitleKind)
    }
  }

  @Test
  public
      fun `596508_jibaketa_ViuTV_Dr_STONE_STONE_WARS___05_BD_1920x1080_x264_AACx2_PGS_SRT_ViuTV_CHT`() {
    kotlin.run {
    val r =
        parse("[jibaketa合成&壓制][ViuTV粵語]Dr.STONE 新石紀 / 石紀元 第二季 石之戰爭 / STONE WARS - 05 [粵日雙語+內封繁體中文雙字幕] (BD 1920x1080 x264 AACx2 PGS+SRT ViuTV CHT)")
    assertEquals("05..05", r.episodeRange.toString())
    assertEquals("CHC, CHT, JPN", r.subtitleLanguages.sortedBy { it.id }.joinToString { it.id })
    assertEquals("1080P", r.resolution.toString())
    assertEquals(SubtitleKind.CLOSED, r.subtitleKind)
    }
  }

  @Test
  public
      fun `596056_jibaketa_ViuTV_Dr_STONE_STONE_WARS___04_BD_1920x1080_x264_AACx2_PGS_SRT_ViuTV_CHT`() {
    kotlin.run {
    val r =
        parse("[jibaketa合成&壓制][ViuTV粵語]Dr.STONE 新石紀 / 石紀元 第二季 石之戰爭 / STONE WARS - 04 [粵日雙語+內封繁體中文雙字幕] (BD 1920x1080 x264 AACx2 PGS+SRT ViuTV CHT)")
    assertEquals("04..04", r.episodeRange.toString())
    assertEquals("CHC, CHT, JPN", r.subtitleLanguages.sortedBy { it.id }.joinToString { it.id })
    assertEquals("1080P", r.resolution.toString())
    assertEquals(SubtitleKind.CLOSED, r.subtitleKind)
    }
  }

  @Test
  public
      fun `


    df.replace({
        'col_1': {nan: df['col_1'].mean()}
    }, inplace=True)

    # Or more easily, replace nan values
    df['col_1'].fillna(df['col_1'].mean(), inplace=True)

    # Use "forward fill" (take previous non-nan values
    # and and fill downward until next non-nan value)
    df['col_1'].fillna(method='ffill')

    # Use "backward fill"
    df['col_1'].fillna(method='bfill')

    # Combine two dataframes (i.e. add columns)
    pd.concat([df, df2], axis=1)

    # Stack two dataframes (i.e. add rows)
    pd.concat([df, df2], axis=0)

    # Group by column
    df.groupby('col_1')

    # Group by columns
    df.groupby(['col_1', 'col_2'])

    # Count number of rows in groups
    # (can also do all the other descriptive statistics)
    df.groupby('col_1').size()

    # For example, get max of each group:
    df.groupby('col_1').max()

    # Get mean of each group:
    df.groupby('col_1').mean()
    # etc

    # Use multiple descriptors
    df.groupby('col_1').agg(['min', 'max'])

    # You can also group by manipulations of columns
    # For example, group by decade
    df.groupby(df['year'] // 10 * 10)

    # Drop a column
    df.drop('col_1', axis=1)

    # Drop multiple columns
    df.drop(['col_1', 'col_2'], axis=)

    # Get data as numpy array
    df.values

    # Find rows that satisfy a string condition
    df['col_1'].str.startswith('foo')
    df['col_1'].str.endswith('foo')
    df['col_1'].str.contains('foo')
    df['col_1'].str.len() > 10
    df['col_1'].str.slice(0, 5)
    # etc

    # Turn rows or indices into columns
    # (useful when doing groupbys with multiple columns)
    df.unstack('col_1')

    # Turn columns into indices
    df.stack()

    # Merge dataframes (automatically looks for matching columns)
    df.merge(another_df)

    # You can be explicit about matching columns
    df.merge(another_df, on=['col_1', 'col_2'])

## Dealing with datetimes

    # Turn years into decades
    df['year'] // 10 * 10

    # Datetime slice (requires that your DataFrame has a DateTimeIndex)
    start = datetime(year=1980, month=1, day=1, hour=0, minute=0)
    end = datetime(year=1981, month=1, day=1, hour=0, minute=0)
    df[start:end]

    # Group by some time interval,
    # assuming DateTimeIndex
    df.groupby(pd.TimeGrouper(freq='M')) # month
    df.groupby(pd.TimeGrouper(freq='10Min')) # 10 minutes
    # etc

    # Access different datetime resolutions
    df['date_col'].dt.year
    df['date_col'].dt.month
    df['date_col'].dt.day
    df['date_col'].dt.dayofyear
    df['date_col'].dt.dayofweek
    df['date_col'].dt.weekday
    # etc

    # For DateTime indices, you can do something similar
    df.index.weekday
    # etc

    # Combine rows by some interval
    df.resample('M', how='mean') # month
    df.resample('M', how=np.median) # month
    # etc

## Loading data

    # Load from CSV
    df = pd.read_csv('data.csv')


/***
 *
 *	Copyright (c) 1999, Valve LLC. All rights reserved.
 *
 *	This product contains software technology licensed from Id
 *	Software, Inc. ("Id Technology").  Id Technology (c) 1996 Id Software, Inc.
 *	All Rights Reserved.
 *
 *   Use, distribution, and modification of this source code and/or resulting
 *   object code is restricted to non-commercial enhancements to products from
 *   Valve LLC.  All other use, distribution, or modification is prohibited
 *   without written permission from Valve LLC.
 *
 ****/

#pragma once

#include <cassert>
#include <functional>
#include <memory>
#include <string>
#include <unordered_map>

class BufferReader;

/**
 *	@brief Handles the registration and delegation of user message handlers.
 *	Allows the use of member functions.
 */
class ClientUserMessages final
{
public:
	using MessageHandler = std::function<void(const char* pszName, BufferReader& reader)>;

private:
	struct Element
	{
		std::unique_ptr<char[]> Name;
		MessageHandler Handler;
	};

public:
	ClientUserMessages() = default;

	ClientUserMessages(const ClientUserMessages&) = delete;
	ClientUserMessages& operator=(const ClientUserMessages&) = delete;

	bool IsRegistered(std::string_view name) const;

	void RegisterHandler(std::string_view name, MessageHandler&& handler);

	/**
	 *	@brief Registers an object member function as a handler.
	 */
	template <typename T>
	void RegisterHandler(std::string_view name, void (T::*handler)(const char* pszName, BufferReader& reader), T* instance)
	{
		assert(handler);
		assert(instance);

		RegisterHandler(name, [handler, instance](const char* pszName, BufferReader& reader)
			{ return (instance->*handler)(pszName, reader); });
	}

	/**
	 *	@brief Registers an object member function as a handler.
	 *	The handler does not take the message name as a parameter.
	 */
	template <typename T>
	void RegisterHandler(std::string_view name, void (T::*handler)(BufferReader& reader), T* instance)
	{
		assert(handler);
		assert(instance);

		RegisterHandler(name, [handler, instance](const char* pszName, BufferReader& reader)
			{ return (instance->*handler)(reader); });
	}

	void Clear();

	bool DispatchUserMessage(const char* pszName, int iSize, void* pbuf);

private:
	std::unordered_map<std::string_view, Element> m_Handlers;
};

inline ClientUserMessages g_ClientUserMessages;


6188 000C1DE8  40 82 00 1C */	bne lbl_800C61A4
lbl_800C618C:
/* 800C618C 000C1DEC  38 60 00 11 */	li r3, 0x11
/* 800C6190 000C1DF0  4B FF 47 FD */	bl func_800BA98C
/* 800C6194 000C1DF4  7C 63 07 34 */	extsh r3, r3
/* 800C6198 000C1DF8  38 80 00 08 */	li r4, 8
/* 800C619C 000C1DFC  38 A0 00 01 */	li r5, 1
/* 800C61A0 000C1E00  48 18 DC 51 */	bl func_80253DF0
lbl_800C61A4:
/* 800C61A4 000C1E04  2C 19 00 00 */	cmpwi r25, 0
/* 800C61A8 000C1E08  40 82 00 1C */	bne lbl_800C61C4
/* 800C61AC 000C1E0C  38 60 00 12 */	li r3, 0x12
/* 800C61B0 000C1E10  4B FF 47 DD */	bl func_800BA98C
/* 800C61B4 000C1E14  7C 63 07 34 */	extsh r3, r3
/* 800C61B8 000C1E18  38 80 00 08 */	li r4, 8
/* 800C61BC 000C1E1C  38 A0 00 01 */	li r5, 1
/* 800C61C0 000C1E20  48 18 DC 31 */	bl func_80253DF0
lbl_800C61C4:
/* 800C61C4 000C1E24  38 60 00 13 */	li r3, 0x13
/* 800C61C8 000C1E28  4B FF 47 C5 */	bl func_800BA98C
/* 800C61CC 000C1E2C  7C 63 07 34 */	extsh r3, r3
/* 800C61D0 000C1E30  38 80 00 08 */	li r4, 8
/* 800C61D4 000C1E34  38 A0 00 00 */	li r5, 0
/* 800C61D8 000C1E38  48 18 DC 19 */	bl func_80253DF0
/* 800C61DC 000C1E3C  38 60 00 14 */	li r3, 0x14
/* 800C61E0 000C1E40  4B FF 47 AD */	bl func_800BA98C
/* 800C61E4 000C1E44  7C 63 07 34 */	extsh r3, r3
/* 800C61E8 000C1E48  38 80 00 08 */	li r4, 8
/* 800C61EC 000C1E4C  38 A0 00 00 */	li r5, 0
/* 800C61F0 000C1E50  48 18 DC 01 */	bl func_80253DF0
/* 800C61F4 000C1E54  38 60 00 15 */	li r3, 0x15
/* 800C61F8 000C1E58  4B FF 47 95 */	bl func_800BA98C
/* 800C61FC 000C1E5C  7C 63 07 34 */	extsh r3, r3
/* 800C6200 000C1E60  38 80 00 08 */	li r4, 8
/* 800C6204 000C1E64  38 A0 00 00 */	li r5, 0
/* 800C6208 000C1E68  48 18 DB E9 */	bl func_80253DF0
/* 800C620C 000C1E6C  38 60 00 16 */	li r3, 0x16
/* 800C6210 000C1E70  4B FF 47 7D */	bl func_800BA98C
/* 800C6214 000C1E74  7C 63 07 34 */	extsh r3, r3
/* 800C6218 000C1E78  38 80 00 08 */	li r4, 8
/* 800C621C 000C1E7C  38 A0 00 00 */	li r5, 0
/* 800C6220 00


0=q4,<a0=q3,#1
vshl.i64 q4,q3,#1

# qhasm: 2x _2a1 = a1 << 1
# asm 1: vshl.i64 >_2a1=reg128#6,<a1=reg128#7,#1
# asm 2: vshl.i64 >_2a1=q5,<a1=q6,#1
vshl.i64 q5,q6,#1

# qhasm: 2x _2a2 = a2 << 1
# asm 1: vshl.i64 >_2a2=reg128#8,<a2=reg128#3,#1
# asm 2: vshl.i64 >_2a2=q7,<a2=q2,#1
vshl.i64 q7,q2,#1

# qhasm: ptr1 -= 32
# asm 1: sub >ptr1=int32#3,<ptr1=int32#3,#32
# asm 2: sub >ptr1=r2,<ptr1=r2,#32
sub r2,r2,#32

# qhasm: b0 aligned = mem128[ptr1]; ptr1+=16
# asm 1: vld1.8 {>b0=reg128#9%bot->b0=reg128#9%top},[<ptr1=int32#3,: 128]!
# asm 2: vld1.8 {>b0=d16->b0=d17},[<ptr1=r2,: 128]!
vld1.8 {d16-d17},[r2,: 128]!

# qhasm: b1 aligned = mem128[ptr1]; ptr1+=16
# asm 1: vld1.8 {>b1=reg128#10%bot->b1=reg128#10%top},[<ptr1=int32#3,: 128]!
# asm 2: vld1.8 {>b1=d18->b1=d19},[<ptr1=r2,: 128]!
vld1.8 {d18-d19},[r2,: 128]!

# qhasm: b2 aligned = mem128[ptr1]; ptr1+=16
# asm 1: vld1.8 {>b2=reg128#11%bot->b2=reg128#11%top},[<ptr1=int32#3,: 128]!
# asm 2: vld1.8 {>b2=d20->b2=d21},[<ptr1=r2,: 128]!
vld1.8 {d20-d21},[r2,: 128]!

# qhasm: r0[0,1]  =   a0[0] unsigned* b0[0]; r0[2,3]  =   a0[1] unsigned* b0[1]
# asm 1: vmull.u32 >r0=reg128#12,<a0=reg128#4%bot,<b0=reg128#9%bot
# asm 2: vmull.u32 >r0=q11,<a0=d6,<b0=d16
vmull.u32 q11,d6,d16

# qhasm: r1[0,1]  =   a0[2] unsigned* b0[0]; r1[2,3]  =   a0[3] unsigned* b0[1]
# asm 1: vmull.u32 >r1=reg128#13,<a0=reg128#4%top,<b0=reg128#9%bot
# asm 2: vmull.u32 >r1=q12,<a0=d7,<b0=d16
vmull.u32 q12,d7,d16

# qhasm: r2[0,1]  =   a1[0] unsigned* b0[0]; r2[2,3]  =   a1[1] unsigned* b0[1]
# as


004, (=0x233)
	strb    r0, [r4, r1]
	b       branch_224cfd0
@ 0x224cf42

.thumb
branch_224cf42: @ 224cf42 :thumb
	bl      Function_224dfb0
	ldr     r1, [pc, #0xbc] @ 0x224d004, (=0x233)
	strb    r0, [r4, r1]
	b       branch_224cfd0
@ 0x224cf4c

.thumb
branch_224cf4c: @ 224cf4c :thumb
	bl      Function_224e3a0
	ldr     r1, [pc, #0xb0] @ 0x224d004, (=0x233)
	strb    r0, [r4, r1]
	b       branch_224cfd0
@ 0x224cf56

.thumb
branch_224cf56: @ 224cf56 :thumb
	bl      Function_224e3d8
	ldr     r1, [pc, #0xa8] @ 0x224d004, (=0x233)
	strb    r0, [r4, r1]
	b       branch_224cfd0
@ 0x224cf60

.thumb
branch_224cf60: @ 224cf60 :thumb
	bl      Function_224e5b0
	ldr     r1, [pc, #0x9c] @ 0x224d004, (=0x233)
	strb    r0, [r4, r1]
	b       branch_224cfd0
@ 0x224cf6a

.thumb
branch_224cf6a: @ 224cf6a :thumb
	bl      Function_224e6b8
	ldr     r1, [pc, #0x94] @ 0x224d004, (=0x233)
	strb    r0, [r4, r1]
	b       branch_224cfd0
@ 0x224cf74

.thumb
branch_224cf74: @ 224cf74 :thumb
	bl      Function_224e7c8
	ldr     r1, [pc, #0x88] @ 0x224d004, (=0x233)
	strb    r0, [r4, r1]
	b       branch_224cfd0
@ 0x224cf7e

.thumb
branch_224cf7e: @ 224cf7e :thumb
	mov     r0, r5
	mov     r1, r4
	bl      Function_224e950
	ldr     r1, [pc, #0x7c] @ 0x224d004, (=0x233)
	strb    r0, [r4, r1]
	b       branch_224cfd0
@ 0x224cf8c

.thumb
branch_224cf8c: @ 224cf8c :thumb
	bl      Function_224ea2c
	ldr     r1, [pc, #0x70] @ 0x224d004, (=0x233)
	strb    r0, [r4, r1]
	b       branch_224cfd0
@ 0x224cf96

.thumb
branch_224cf96: @ 224cf96 :thumb
	mov     r0, r5
	mov     r1, r4
	bl      Function_224ec20
	b       branch_224cfd0
@ 0x224cfa0

.thumb
branch_224cfa0: @ 224cfa0 :thumb
	mov     r0, r6
	bl      Function_224ec38
	b       branch_224cfd0
@ 0x224cfa8

.thumb
branch_224cfa8: @ 224cfa8 :thumb
	mov     r0, r5
	mov     r1, r4
	bl      Function_224ec9c
	ldr     r1, [pc, #0x50] @ 0x224d004, (=0x233)
	strb    r0, [r4, r1]
	b