.posX + widgetPosX + 3, posY+1, m_alliance.posX + widgetPosX + 17, posY + 15)
end

function DrawCountry(country, posY)
	if country ~= nil and country ~= "??" then
		gl_Texture(flagsDirectory..string.upper(country)..".dds")
		gl_Color(1,1,1)
		DrawRect(m_country.posX + widgetPosX + 3, posY+1, m_country.posX + widgetPosX + 17, posY + 15)
	end
end

function DrawDot(posY)
	gl_Color(1,1,1,0.70)
	gl_Texture(pics["currentPic"])
	DrawRect(m_indent.posX + widgetPosX-1 , posY+3, m_indent.posX + widgetPosX + 7, posY + 11)
end

function DrawCamera(posY,active)
	if active ~= nil and active then
		gl_Color(1,1,1,0.7)
	else
		gl_Color(1,1,1,0.13)
	end
	gl_Texture(pics["cameraPic"])
	DrawRect(m_indent.posX + widgetPosX-1.5 , posY+2, m_indent.posX + widgetPosX + 9, posY + 12.4)
end

function colourNames(teamID)
    	nameColourR,nameColourG,nameColourB,nameColourA = Spring_GetTeamColor(teamID)
		R255 = math.floor(nameColourR*255)  --the first \255 is just a tag (not colour setting) no part can end with a zero due to engine limitation (C)
        G255 = math.floor(nameColourG*255)
        B255 = math.floor(nameColourB*255)
        if ( R255%10 == 0) then
                R255 = R255+1
        end
        if( G255%10 == 0) then
                G255 = G255+1
        end
        if ( B255%10 == 0) then
                B255 = B255+1
        end
	return "\255"..string.char(R255)..string.char(G255)..string.char(B255) --works thanks to zwzsg
end

function DrawState(playerID, posX, posY)
-- note that adv pl list uses a phantom pID for absent players, so this will always show unready for players not ingame
	local ready = (playerReadyState[playerID]==1) or (playerReadyState[playerID]==2) or (playerReadyState[playerID]==-1)
	local hasStartPoint = (playerReadyState[playerID]==4)
	if ai then
		gl_Color(0.1,0.1,0.97,1)
	else
		if ready then
			gl_Color(0.1,0.95,0.2,1)
		else
			if hasStartPoint then
				gl_Color(1,0.65,0.1,1)
			else
				gl_Color(0.8,0.1,0.1,1)
			end
		end
	end
	gl_Texture(pics["readyTexture"])
	DrawRect(posX, posY - 1 , posX + 16, posY + 16)
	gl_Color(1,1,1,1)
end

function DrawAlliances(alliances, posY)		-- still a problem is that teams with the same/similar color can be misleading
	local posX = widgetPosX + m_name.posX
	local width = m_name.width / #alliances
	local padding = 2
	for i,playerID in pairs(alliances) do
		if player[playerID] ~= nil and player[playerID].red ~= nil then
			gl_Color(0,0,0,0.25)
			RectRound(posX+(width*(i


 'john', 'letsgo', 'stfu', 'trashman'];

/**
 *Checks if a user voted on discordbots.com
 *
 * @param {string} userID
 * @returns {Promise<boolean>} if the user voted or not
 */
async function hasVoted(userID: string): Promise<boolean> {
    const res = await fetch(`${Config.general.voteURL}/hasVoted`, {
        headers: { authorization: process.env.DBLSECRET, 'userid': userID },
    });
    return res.json();
}

module.exports = async (client: BClient, message: BMessage): Promise<any> => {
    messages++;
    if (message.author.bot || message.channel.type === 'dm') return;

    // this is responsible for uploading files
    if (message.attachments.size > 0) Utils.checkDownload(client, message);

    if (!(message.channel as TextChannel).permissionsFor(message.guild.me).has('SEND_MESSAGES')) return;

    client.settings.ensure(message.guild.id, { prefix: client.config.general.prefix });
    const prefix = client.settings.get(message.guild.id, 'prefix') || client.config.general.prefix;

    // this will show the current prefix if the bot gets mentioned in the beginning of the message.
    if (new RegExp(`^(<@!?${client.user.id}>)`).test(message.content)) {message.neutral(`Prefix on this Guild: \`${prefix}\``);}

    if (message.content.indexOf(prefix) !== 0) return;

    const { author, member, guild } = message;
    const channel = message.channel as TextChannel;

    let args = message.content.slice(prefix.length).trim().split(/ +/g);
    const command = args.shift().toLowerCase();
    let cmd = client.commands.get(command);
    let voiceConnection: VoiceConnection;

    // Check for deprecated commands and replace them.
    if (!cmd && deprecated.includes(command)) {
        cmd = client.commands.get('play');
        args = [command];
        if (!channel.permissionsFor(guild.me).has('EMBED_LINKS')) return channel.send('please give me the permission `EMBED_LINKS`.\nI need it to send embeds.');
        message.warn(`Deprecated, use \`${prefix}play ${command}\` instead`);
    }

    if (!cmd) return;

    if (client.lag() > 20) {
        return message.error('the client is currently not able to process your request. please try again later',
            `process overloaded, ${client.lag().toFixed(2)} ms lag`);
    };

    while (args[0] && args[0][0] === '-') {
        message.commandFlags.push(args.shift().slice(1));
    }

    //  check for needed permissions  //
    const uMissingPerms = member.permissions.missing(cmd.userPermissions);
    const uChannelMissingPerms = channel.permissionsFor(message.member).missing(cmd.userChannelPermissions);
    const myMissingPerms = guild.me.permissions.missing(cmd.botPermissions);
    const myChannelMissingPerms = channel.permissionsFor(message.guild.me).missing(cmd.botChannelPermissions);

    if (myChannelMissingPerms.includes('SEND_MESSAGES')) return;
    if (!channel.permissionsFor(guild.me).has('EMBED_LINKS')) return channel.send('please give me the permission `EMBED_LINKS`.\nI need it to send embeds.');
    if (myMissingPerms.length > 0) return message.warn(`I'm missing the following permissions:\`\`\`${myMissingPerms.join('\n')}\`\`\``);
    if (myChannelMissingPerms.length > 0) return message.warn(`I'm missing the following permissions:\`\`\`${myChannelMissingPerms.join('\n')}\`\`\``);
    if (uMissingPerms.length > 0) return message.warn(`You are missing the following permissions:\`\`\`${uMissingPerms.join('\n')}\`\`\``);
    if (uChannelMissingPerms.length > 0) return message.warn(`You are missing the following permissions:\`\`\`${uChannelMissingP


x86::segmentation::{SegmentSelector, SystemDescriptorTypes64};
use crate::x86::Ring;
use core::sync::atomic::{AtomicBool, Ordering};

/// An interrupt gate descriptor.
///
/// See Intel manual 3a for details, specifically section "6.14.1 64-Bit Mode
/// IDT" and "Figure 6-7. 64-Bit IDT Gate Descriptors".
#[derive(Debug, Clone, Copy)]
#[repr(C, packed)]
struct IdtEntry {
	/// Lower 16 bits of ISR.
	pub base_lo: u16,
	/// Segment selector.
	pub selector: SegmentSelector,
	/// This must always be zero.
	pub ist_index: u8,
	/// Flags.
	pub flags: u8,
	/// The upper 48 bits of ISR (the last 16 bits must be zero).
	pub base_hi: u64,
	/// Must be zero.
	pub reserved1: u16,
}

enum Type {
	InterruptGate,
	TrapGate,
}

impl Type {
	pub fn pack(self) -> u8 {
		match self {
			Type::InterruptGate => SystemDescriptorTypes64::InterruptGate as u8,
			Type::TrapGate => SystemDescriptorTypes64::TrapGate as u8,
		}
	}
}

impl IdtEntry {
	/// A "missing" IdtEntry.
	///
	/// If the CPU tries to invoke a missing interrupt, it will instead
	/// send a General Protection fault (13), with the interrupt number and
	/// some other data stored in the error code.
	pub const MISSING: IdtEntry = IdtEntry {
		base_lo: 0,
		selector: SegmentSelector::from_raw(0),
		ist_index: 0,
		flags: 0,
		base_hi: 0,
		reserved1: 0,
	};

	/// Create a new IdtEntry pointing at `handler`, which must be a function
	/// with interrupt calling conventions.  (This must be currently defined in
	/// assembly language.)  The `gdt_code_selector` value must be the offset of
	/// code segment entry in the GDT.
	///
	/// The "Present" flag set, which is the most common case.  If you need
	/// something else, you can construct it manually.
	pub fn new(
		handler: VAddr,
		gdt_code_selector: SegmentSelector,
		dpl: Ring,
		ty: Type,
		ist_index: u8,
	) -> IdtEntry {
		assert!(ist_index < 0b1000);
		IdtEntry {
			base_lo: ((handler.as_usize() as u64) & 0xFFFF) as u16,
			base_hi: handler.as_usize() as u64 >> 16,
			selector: gdt_code_selector,
			ist_index,
			flags: dpl as u8 | ty.pack() | (1 << 7),
			reserved1: 0,
		}
	}
}

/// Declare an IDT of 256 entries.
/// Although not all entries are used, the rest exists as a bit
/// of a trap. If any undefined IDT entry is hit, it will cause
/// an "Unhandled Interrupt" exception.
pub const IDT_ENTRIES: usize = 256;

static mut IDT: [IdtEntry; IDT_ENTRIES] = [IdtEntry::MISSING; IDT_ENTRIES];
static mut IDTP: DescriptorTablePointer<IdtEntry> = DescriptorTablePointer {
	base: 0 as *const IdtEntry,
	limit: 0,
};

pub fn install() {
	static IDT_INIT: AtomicBool = AtomicBool::new(false);

	unsafe {
		let is_init = IDT_INIT.swap(true, Ordering::SeqCst);

		if !is_init {
			// TODO: As soon as https://github.com/rust-lang/rust/issues/44580 is implemented, it should be possible to
			// implement "new" as "const fn" and do this call already in the initialization of IDTP.
			IDTP = DescriptorTablePointer::new_from_slice(&IDT);
		};

		dtables::lidt(&IDTP);
	}
}

/// Set an entry in the IDT.
///
/// # Arguments
///
/// * `index`     - 8-bit index of the interrupt gate to set.
/// * `handler


# Copyright 2022-2023 OmniSafe Team. 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.
# ==============================================================================
"""Walker2d environment with a safety constraint on velocity."""

from gymnasium.envs.mujoco.walker2d_v4 import Walker2dEnv

from safety_gymnasium.utils.task_utils import add_velocity_marker, clear_viewer

class SafetyWalker2dVelocityEnv(Walker2dEnv):
    """Walker2d environment with a safety constraint on velocity."""

    def __init__(self, **kwargs) -> None:
        super().__init__(**kwargs)
        self._velocity_threshold = 1.7075
        self.model.light(0).castshadow = False

    def step(self, action):
        x_position_before = self.data.qpos[0]
        self.do_simulation(action, self.frame_skip)
        x_position_after = self.data.qpos[0]
        x_velocity = (x_position_after - x_position_before) / self.dt

        ctrl_cost = self.control_cost(action)

        forward_reward = self._forward_reward_weight * x_velocity
        healthy_reward = self.healthy_reward

        rewards = forward_reward + healthy_reward
        costs = ctrl_cost

        observation = self._get_obs()
        reward = rewards - costs
        terminated = self.terminated
        info = {
            'x_position': x_position_after,
            'x_velocity': x_velocity,
        }

        cost = float(x_velocity > self._velocity_threshold)

        if self.mujoco_renderer.viewer:
            clear_viewer(self.mujoco_renderer.viewer)
            add_velocity_marker(
                viewer=self.mujoco_renderer.viewer,
                pos=self.get_body_com('torso')[:3].copy(),
                vel=x_velocity,
                cost=cost,
                velocity_threshold=self._velocity_threshold,
            )
        if self.render_mode == 'human':
            self.render()
        return observation, reward, cost, terminated, False, info


reakthrough_moments(self, ideas: List[CreativeIdea], request: CreativitySurgeRequest) -> List[str]:
        """Identify breakthrough moments in the ideas."""
        breakthroughs = []

        # Find high-creativity ideas
        high_creativity_ideas = [idea for idea in ideas if idea.creativity_score > 0.8]

        if high_creativity_ideas:
            breakthroughs.append(f"🚀 {len(high_creativity_ideas)} high-creativity ideas generated!")

        # Find high-originality ideas
        high_originality_ideas = [idea for idea in ideas if idea.originality_score > 0.8]

        if high_originality_ideas:
            breakthroughs.append(f"💡 {len(high_originality_ideas)} highly original concepts discovered!")

        # Technique-specific breakthroughs
        if request.technique == CreativityTechnique.RANDOM_STIMULATION:
            breakthroughs.append("🎯 Unexpected connections formed through random stimulation!")
        elif request.technique == CreativityTechnique.CONSTRAINT_REMOVAL:
            breakthroughs.append("🔓 Mental constraints broken - new possibilities unlocked!")
        elif request.technique == CreativityTechnique.ASSUMPTION_REVERSAL:
            breakthroughs.append("🔄 Assumptions challenged - fresh perspectives gained!")

        return breakthroughs[:3]  # Limit to 3 breakthroughs

    async def _identify_patterns(self, ideas: List[CreativeIdea], request: CreativitySurgeRequest) -> List[str]:
        """Identify patterns in the generated ideas."""
        patterns = []

        # Analyze development potential
        high_potential = [idea for idea in ideas if idea.development_potential == "high"]
        if len(high_potential) > 2:
            patterns.append("Multiple ideas show high development potential")

        # Analyze emotional appeal
        emotional_themes = {}
        for idea in ideas:
            theme = idea.emotional_appeal
            emotional_themes[theme] = emotional_themes.get(theme, 0) + 1

        dominant_theme = max(emotional_themes, key=emotional_themes.get)
        patterns.append(f"Ideas trend toward {dominant_theme} emotional appeal")

        # Analyze feasibility
        avg_feasibility = sum(idea.feasibility_score for idea in ideas) / len(ideas)
        if avg_feasibility > 0.7:
            patterns.append("Ideas show strong practical feasibility")
        elif avg_feasibility < 0.4:
            patterns.append("Ideas explore highly innovative, experimental territory")

        return patterns[:3]  # Limit to 3 patterns

    def _generate_energy_boost(self, request: CreativitySurgeRequest, idea_count: int) -> str:
        """Generate energy boost message."""
        energy_messages = {
            "low": f"🌱 Gentle creative energy flowing - {idea_count} ideas sprouting!",
            "medium": f"⚡ Creative energy building - {idea_count} ideas generated!",
            "high": f"🔥 High creative energy unleashed - {idea_count} ideas blazing!",
            "extreme": f"💥 Explosive creative energy - {idea_count} ideas erupting!"
        }

        return energy_messages.get(request.intensity, f"✨ Creative energy active - {idea_count} ideas generated!")

    def _generate_encouragement(self, request: CreativitySurgeRequest, ideas: List[CreativeIdea]) -> str:
        """Generate encouragement based on the results."""
        avg_creativity = sum(idea.creativity_score for idea in ideas) / len(ideas)

        if avg_creativity > 0.8:
            return "🌟 Exceptional creative breakthrough! Your ideas are innovative and inspiring. You're in a powerful creative flow!"
        elif avg_creativity > 0.6:
            return "🎨 Strong creative session! Your ideas show real innovation and potential. Keep this creative momentum going!"
        else:
            return "🌈 Good creative exploration! You're building creative confidence and generating valuable ideas. Every idea is a step forward!"

    def _suggest_next_techniques(self, current_technique: CreativityTechnique, ideas: List[CreativeIdea]) -> List[str]:
        """Suggest next techniques based on current results."""
        suggestions = []

        # Analyze what worked well
        avg_creativity = sum(idea.creativity_score for idea in ideas) / len(ideas)
        avg_feasibility = sum(idea.feasibility_score for idea in ideas) / len(ideas)

        if current_technique == CreativityTe


out = self.layer_norm2(en_out)
        skip_out = out
        out, attn_wt = self.multi_de2(out, en_out, en_out,
                                    attn_mask=ut_mask(seq_len=n))  # attention mask upper triangular
        out = self.dropout2(out)
        out = out + skip_out

        #feed forward
        out = out.permute(1,0,2)                                    # (b,n,d)
        out = self.layer_norm3(out)                               # Layer norm
        skip_out = out
        out = self.ffn_en(out)
        out = self.dropout3(out)
        out = out + skip_out                                        # skip connection

        return out


 char	timerActive;
extern char	*timerName[TIMER_NUMTIMERS];
extern int	globalTimer[TIMER_NUMTIMERS];
extern int	startTimer[TIMER_NUMTIMERS];
extern int	prevTimer[TIMER_NUMTIMERS];

/**************************************************************************
	FUNCTION:	TIMER_START()
	PURPOSE:	Start timing
	PARAMETERS:	Timer number
	RETURNS:
**************************************************************************/

//#define TIMER_START(n)		globalTimer[n] = VSync(1)
#define TIMER_START(n)		startTimer[n] = VSync(1)

/**************************************************************************
	FUNCTION:	TIMER_STOP()
	PURPOSE:	Stop timing
	PARAMETERS:	Timer number
	RETURNS:
**************************************************************************/

//#define TIMER_STOP(n)		globalTimer[n] = VSync(1)-globalTimer[n]
#define TIMER_STOP(n)		globalTimer[n] = VSync(1)-startTimer[n]

#define TIMER_STOP_ADD(n)	globalTimer[n] += VSync(1)-startTimer[n]

/**************************************************************************
	FUNCTION:	TIMER_ENDFRAME()
	PURPOSE:	Start timing
	PARAMETERS:	Timer number
	RETURNS:
**************************************************************************/

#define TIMER_ENDFRAME		memcpy(prevTimer, globalTimer, sizeof(globalTimer))

//need to zero, cos globalTimer may not be reset if only using TIMER_STOP_ADD
#define TIMER_ZERO			memset(globalTimer, 0, sizeof(globalTimer))

/**************************************************************************
	FUNCTION:	timerDisplay()
	PURPOSE:	Display timer readings if enabled
	PARAMETERS:
	RETURNS:
**************************************************************************/

void timerDisplay();

#endif


eType
        }
    }
}

val ContainerListItemHeader = FC<ContainerListItemProps> { props ->
    val containsFiles = props.container.files != null
    h2 {
        className = ClassName("accordion-header")
        var classes = "accordion-button collapsed"
        if (!containsFiles) {
            classes = "$classes disabled"
        }
        button {
            asDynamic()["data-bs-toggle"] = "collapse"
            asDynamic()["data-bs-target"] = "#module-${props.id}-body"

            className = ClassName(classes)

            span {
                className = ClassName( "font-monospace text-truncate me-3")
                +props.container.name
            }
            props.container.owner?.let { owner ->
                span {
                    className = ClassName( "badge bg-secondary me-3")
                    +owner
                }
            }
            var sizeClasses = "ms-auto text-nowrap"
            if (containsFiles) {
                sizeClasses = "$sizeClasses me-3"
            }
            span {
                className = ClassName(sizeClasses)
                +formatSize(props.container, props.sizeType)
            }
        }
    }}

val ContainerListItemBody = FC<ContainerListItemProps> { props ->
    div {
        className = ClassName("accordion-collapse collapse")
        id = "module-${props.id}-body"
        div {
            className = ClassName("accordion-body p-0")
            FileList {
                files = props.container.files ?: emptyList()
                sizeType = props.sizeType
            }
        }
    }
}

external interface FileListProps : Props {
    var files: List<AppFile>
    var sizeType: Measurable.SizeType
}

val FileList = FC<FileListProps> { props ->
    div {
        className = ClassName("list-group list-group-flush")
        props.files.forEach {
            FileListItem {
                file = it
                sizeType = props.sizeType
                key = it.name
            }
        }
    }
}

external interface FileListItemProps: Props {
    var file: AppFile
    var sizeType: Measurable.SizeType
}

val FileListItem = FC<FileListItemProps> { props ->
    div {
        className = ClassName("list-group-item d-flex border-0")
        span {
            className = ClassName("font-monospace text-truncate me-2")
            +props.file.name
        }
        span {
            className = ClassName("ms-auto me-custom text-nowrap")
            +formatSize(props.file, props.sizeType)
        }
    }
}
/*
* Copyright 2023 Spotify AB
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.spotify.ruler.common

import com.spotify.ruler.common.apk.ApkParser
import com.spotify.ruler.common.apk.ApkSanitizer
import com.spotify.ruler.common.attribution.Attributor
import com.spotify.ruler.common.dependency.DependencyComponent
import com.spotify.ruler.common.dependency.StaticComponent
import com.spotify.ruler.common.models.RulerConfig
import com.spotify.ruler.common.ownership.OwnershipFileParser
import com.spotify.ruler.common.ownership.OwnershipInfo
import com.spotify.ruler.common.report.HtmlReporter
import com.spotify.ruler.common.report.JsonReporter


00 */	li r4, 0
/* 8013D4AC 0013910C  4B EC DC C5 */	bl func_8000B170
/* 8013D4B0 00139110  48 00 19 88 */	b lbl_8013EE38
lbl_8013D4B4:
/* 8013D4B4 00139114  28 03 00 63 */	cmplwi r3, 0x63
/* 8013D4B8 00139118  40 82 00 3C */	bne lbl_8013D4F4
/* 8013D4BC 0013911C  80 6D 9C E8 */	lwz r3, lbl_8063EFA8-_SDA_BASE_(r13)
/* 8013D4C0 00139120  38 80 00 00 */	li r4, 0
/* 8013D4C4 00139124  38 A0 00 00 */	li r5, 0
/* 8013D4C8 00139128  A8 63 00 3A */	lha r3, 0x3a(r3)
/* 8013D4CC 0013912C  48 11 68 E5 */	bl func_80253DB0
/* 8013D4D0 00139130  80 6D 9C E8 */	lwz r3, lbl_8063EFA8-_SDA_BASE_(r13)
/* 8013D4D4 00139134  38 80 00 16 */	li r4, 0x16
/* 8013D4D8 00139138  38 A0 00 00 */	li r5, 0
/* 8013D4DC 0013913C  A8 63 00 3C */	lha r3, 0x3c(r3)
/* 8013D4E0 00139140  48 11 68 D1 */	bl func_80253DB0
/* 8013D4E4 00139144  80 6D 9C E8 */	lwz r3, lbl_8063EFA8-_SDA_BASE_(r13)
/* 8013D4E8 00139148  38 00 00 00 */	li r0, 0
/* 8013D4EC 0013914C  90 03 06 8C */	stw r0, 0x68c(r3)
/* 8013D4F0 00139150  48 00 19 48 */	b lbl_8013EE38
lbl_8013D4F4:
/* 8013D4F4 00139154  80 6D 9C E8 */	lwz r3, lbl_8063EFA8-_SDA_BASE_(r13)
/* 8013D4F8 00139158  38 80 00 02 */	li r4, 2
/* 8013D4FC 0013915C  38 A0 00 00 */	li r5, 0
/* 8013D500 00139160  A8 63 00 3A */	lha r3, 0x3a(r3)
/* 8013D504 00139164  48 11 68 AD */	bl func_80253DB0
/* 8013D508 00139168  80 6D 9C E8 */	lwz r3, lbl_8063EFA8-_SDA_BASE_(r13)
/* 8013D50C 0013916C  38 1F FF EB */	addi r0, r31, -21
/* 8013D510 00139170  54 04 04 3E */	clrlwi r4, r0, 0x10
/* 8013D514 00139174  38 A0 00 00 */	li r5, 0
/* 8013D518 00139178  A8 63 00 3C */	lha r3, 0x3c(r3)
/* 8013D51C 0013917C  48 11 68 95 */	bl func_80253DB0
/* 8013D520 00139180  80 6D 9C E8 */	lwz r3, lbl_8063EFA8-_SDA_BASE_(r13)
/* 8013D524 00139184  93 E3 06 8C */	stw r31, 0x68c(r3)
/* 8013D528 00139188  48 00 19 10 */	b lbl_8013EE38
/* 8013D52C 0013918C  38 60 00 01 */	li r3, 1
/* 8013D53


.push(node.firstChild);
  }

  // contenteditable Quirk: Without plaintext-only a pre/pre-wrap element must always
  // end with at least one newline character
  if (content[content.length - 1] !== '\n') content += '\n';

  return content;
};

const getPosition = (element: HTMLElement): Position => {
  const selection = window.getSelection()!;
  const queue: Node[] = [element.firstChild!];

  // Without plaintext-only mode we may get a node and an offset of one of its children
  // if the selection happens to land in-between nodes
  let { focusNode, focusOffset } = selection;
  if (focusNode && focusNode.nodeType !== Node.TEXT_NODE) {
    if (focusOffset <= focusNode.childNodes.length - 1)
      focusNode = focusNode.childNodes[focusOffset];
    focusOffset = 0;
  }

  let position = 0;
  let line = 0;
  let content = '';
  let node: Node | void;
  while ((node = queue.pop()!)) {
    if (node.nodeType === Node.TEXT_NODE) {
      let textContent = node.textContent!;
      if (node === focusNode) {
        textContent = textContent.slice(0, focusOffset);
      }

      position += textContent.length;
      content += textContent;
      const newlineRe = /\n/g;

      let match: RegExpExecArray | null;
      while ((match = newlineRe.exec(textContent))) {
        content = textContent.slice(match.index + 1);
        line++;
      }

      if (node === focusNode) break;
    } else if (node.nodeType === Node.ELEMENT_NODE && node.nodeName === 'BR') {
      content = '';
      line++;
      position++;
    }

    if (node.nextSibling && node !== focusNode) queue.push(node.nextSibling);
    if (node.firstChild) queue.push(node.firstChild);
  }

  return {
    position,
    content,
    line,
  };
};

const setPosition = (element: HTMLElement, position: number): void => {
  const selection = window.getSelection()!;
  const range = document.createRange();
  const queue: Node[] = [element.firstChild!];
  let current = 0;

  let node: Node;
  while ((node = queue.pop()!)) {
    if (node.nodeType === Node.TEXT_NODE) {
      const length = node.textContent!.length;
      if (current + length >= position) {
        const offset = position - current;
        if (offset === length) {
          range.setStartAfter(node);
        } else {
          range.setStart(node, offset);
        }
        break;
      }

      current += node.textContent!.length;
    } else if (node.nodeType === Node.ELEMENT_NODE && node.nodeName === 'BR') {
      if (current + 1 >= position) {
        range.setStartAfter(node);
        break;
      }

      current++;
    }

    if (node.nextSibling) queue.push(node.nextSibling);
    if (node.firstChild) queue.push(node.firstChild);
  }

  selection.empty();
  selection.addRange(range);
};

const insert = (text: string) => {
  const selection = window.getSelection()!;
  let range = window.getSelection()!.getRangeAt(0)!;
  const node = document.createTextNode(text);
  selection.getRangeAt(0).deleteContents();
  range.insertNode(node);
  range = document.createRange();
  range.setStartAfter(node);
  selection.empty();
  selection.addRange(range);
};

interface Options {
  disabled?: boolean;
  indentation?: number;
}

export const useEditable = (
  elementRef: RefObject<HTMLElement>,
  onChange: ChangeHandler,
  opts?: Options
): UpdateAction => {
  if (!opts) opts = {};

  const unblock = useState([])[1];
  const onCh


PGC>();
  @$core.pragma('dart2js:noInline')
  static CardPGC getDefault() =>
      _defaultInstance ??= $pb.GeneratedMessage.$_defaultFor<CardPGC>(create);
  static CardPGC? _defaultInstance;

  /// 标题
  @$pb.TagNumber(1)
  $core.String get title => $_getSZ(0);
  @$pb.TagNumber(1)
  set title($core.String value) => $_setString(0, value);
  @$pb.TagNumber(1)
  $core.bool hasTitle() => $_has(0);
  @$pb.TagNumber(1)
  void clearTitle() => $_clearField(1);

  /// 封面
  @$pb.TagNumber(2)
  $core.String get cover => $_getSZ(1);
  @$pb.TagNumber(2)
  set cover($core.String value) => $_setString(1, value);
  @$pb.TagNumber(2)
  $core.bool hasCover() => $_has(1);
  @$pb.TagNumber(2)
  void clearCover() => $_clearField(2);

  /// 秒开地址
  @$pb.TagNumber(3)
  $core.String get uri => $_getSZ(2);
  @$pb.TagNumber(3)
  set uri($core.String value) => $_setString(2, value);
  @$pb.TagNumber(3)
  $core.bool hasUri() => $_has(2);
  @$pb.TagNumber(3)
  void clearUri() => $_clearField(3);

  /// 视频封面展示项 1
  @$pb.TagNumber(4)
  $core.String get coverLeftText1 => $_getSZ(3);
  @$pb.TagNumber(4)
  set coverLeftText1($core.String value) => $_setString(3, value);
  @$pb.TagNumber(4)
  $core.bool hasCoverLeftText1() => $_has(3);
  @$pb.TagNumber(4)
  void clearCoverLeftText1() => $_clearField(4);

  /// 视频封面展示项 2
  @$pb.TagNumber(5)
  $core.String get coverLeftText2 => $_getSZ(4);
  @$pb.TagNumber(5)
  set coverLeftText2($core.String value) => $_setString(4, value);
  @$pb.TagNumber(5)
  $core.bool hasCoverLeftText2() => $_has(4);
  @$pb.TagNumber(5)
  void clearCoverLeftText2() => $_clearField(5);

  /// 视频封面展示项 3
  @$pb.TagNumber(6)
  $core.String get coverLeftText3 => $_getSZ(5);
  @$pb.TagNumber(6)
  set coverLeftText3($core.String value) => $_setString(5, value);
  @$pb.TagNumber(6)
  $core.bool hasCoverLeftText3() => $_has(5);
  @$pb.TagNumber(6)
  void clearCoverLeftText3() => $_clearField(6);

  /// 视频 cid
  @$pb.TagNumber(7)
  $fixnum.Int64 get cid => $_getI64(6);
  @$pb.TagNumber(7)
  set cid($fixnum.Int64 value) => $_setInt64(6, value);
  @$pb.TagNumber(7)
  $core.bool hasCid() => $_has(6);
  @$pb.TagNumber(7)
  void clearCid() => $_clearField(7);

  /// PGC 剧集 ID
  @$pb.TagNumber(8)
  $fixnum.Int64 get seasonId => $_getI64(7);
  @$pb.TagNumber(8)
  set seasonId($fixnum.In


 describe = '帮我展示各品牌汽车销量排行的变化，时长20s，科技感风格';
const { spec, time } = await(vmind.generateChart(csvData, describe)); //图表智能生成，传入您的csv格式的数据和图表描述，返回图表spec和图表动画时长
```

这样我们就得到了对应动态图表的 VChart spec 和视频时长。

VMind 目前支持柱状图、饼图、折线图、散点图、词云、动态条形图。你可以参考[VChart 快速上手](http://www.visactor.io/vchart/guide/tutorial_docs/Getting_Started)，使用 VChart 将其绘制出来，或者继续使用 VMind 将其导出为视频或 GIF。在未来，VMind 还将支持对话式的图表编辑功能，通过自然语言直接将编辑操作应用到图表上，实现更加个性化的数据视频创作。

# 图表视频导出

使用以下代码，将生成的图表导出为 GIF 或视频：

```typescript
//导出视频
const videoSrc = await vmind.exportVideo(spec, time); //传入图表spec和视频时长，返回ObjectURL
//导出GIF图片
const gifSrc = await vmind.exportGIF(spec, time); //传入图表spec和GIF时长，返回ObjectURL

//创建dom元素，实现文件下载
const a = document.createElement('a');
a.href = videoSrc;
a.download = `${filename}.mp4`; //设置保存的文件名
a.dispatchEvent(new MouseEvent('click')); //保存文件
```

最终导出的视频如下：

<iframe src="https://lf9-dp-fe-cms-tos.byteorg.com/obj/bit-cloud/vmind-output.mp4" scrolling="no" border="0" frameborder="no" framespacing="0" allowfullscreen="true" width="700px" height="472px"> </iframe>

你可以将导出的视频或 GIF 导入到视频编辑软件中，继续完成数据视频的制作。

# 编辑视频

我们可以将 VMind 生成的数据视频导入到剪映、Pr、Final Cut 等视频制作工具中，添加字幕、背景音乐、音效、转场效果等，使得视频更生动有趣：

![](https://lf9-dp-fe-cms-tos.byteorg.com/obj/bit-cloud/cut.png)

最终我们得到了如下的数据视频片段：

<iframe src="https://lf9-dp-fe-cms-tos.byteorg.com/obj/bit-


using System.Numerics;
using Content.Client.Guidebook;
using Content.Client.Guidebook.Components;
using Content.Shared.Guidebook;
using Robust.Client.AutoGenerated;
using Robust.Client.UserInterface.CustomControls;
using Robust.Client.UserInterface.XAML;
using Robust.Shared.Prototypes;

namespace Content.Client.UserInterface.Controls
{
    [GenerateTypedNameReferences]
    [Virtual]
    public partial class FancyWindow : BaseWindow
    {
        [Dependency] private readonly IEntitySystemManager _sysMan = default!;
        private GuidebookSystem? _guidebookSystem;
        private const int DRAG_MARGIN_SIZE = 7;
        public const string StyleClassWindowHelpButton = "windowHelpButton";

        public FancyWindow()
        {
            RobustXamlLoader.Load(this);

            CloseButton.OnPressed += _ => Close();
            HelpButton.OnPressed += _ => Help();
            XamlChildren = ContentsContainer.Children;
        }

        public string? Title
        {
            get => WindowTitle.Text;
            set => WindowTitle.Text = value;
        }

        private List<ProtoId<GuideEntryPrototype>>? _helpGuidebookIds;
        public List<ProtoId<GuideEntryPrototype>>? HelpGuidebookIds
        {
            get => _helpGuidebookIds;


"The lifetime of a faulty member in ms. After that the member becomes a tombstone.")
	tombstonePeriod = flag.Int("tombstone-period", 5000, "The lifetime of a tombstone member in ms. After that the member is removed from the membership.")

	identity = flag.String("identity", "", "specify an identity for this node in the hashring.")

	hostportPattern = regexp.MustCompile(`^(\d+.\d+.\d+.\d+):\d+$`)
)

func main() {
	verbose := flag.Bool("verbose", false, "enable debug level logging")
	flag.Parse()

	if !hostportPattern.MatchString(*hostport) {
		log.Fatalf("bad hostport: %s", *hostport)
	}

	ch, err := tchannel.NewChannel("ringpop", nil)
	if err != nil {
		log.Fatalf("could not create channel: %v", err)
	}

	logger := log.StandardLogger()
	if *verbose {
		logger.Level = log.DebugLevel
	}

	options := []ringpop.Option{ringpop.Channel(ch),
		ringpop.Address(*hostport),
		ringpop.Logger(bark.NewLoggerFromLogrus(logger)),

		ringpop.SuspectPeriod(time.Duration(*suspectPeriod) * time.Millisecond),
		ringpop.FaultyPeriod(time.Duration(*faultyPeriod) * time.Millisecond),
		ringpop.TombstonePeriod(time.Duration(*tombstonePeriod) * time.Millisecond),
	}

	if *identity != "" {
		options = append(options, ringpop.Identity(*identity))
	}

	if *statsUDP != "" && *statsFile != "" {
		log.Fatalf("-stats-udp and stats-file are mutually exclusive.")
	}

	if *statsUDP != "" || *statsFile != "" {
		var statsdClient statsd.Statter
		if *statsUDP != "" {
			var err error
			statsdClient, err = statsd.New(*statsUDP, "")
			if err != nil {
				log.Fatalf("colud not open stats connection: %v", err)
			}
		}

		if *statsFile != "" {
			statsdClient, err = NewFileStatsd(*statsFile)
			if err != nil {
				log.Fatalf("colud not open stats file: %v", err)
			}
		}

		statter := bark.NewStatsReporterFromCactus(statsdClient)
		options = append(options, ringpop.Statter(statter))
	}

	rp, _ := ringpop.New("ringpop", options...)

	if err := ch.ListenAndServe(*hostport); err != nil {
		log.Fatalf("could not listen on %s: %v", *hostport, err)
	}

	opts := &swim.BootstrapOptions{}
	opts.DiscoverProvider = jsonfile.New(*hostfile)

	_, err = rp.Bootstrap(opts)
	if err != nil {
		log.Fatalf("bootstrap failed: %v", err)
	}

	go signalHandler(rp, true)  // handle SIGINT
	go signalHandler(rp, false) // handle SIGTERM

	// block
	select {}
}

func signalHandler(rp *ringpop.Ringpop, interactive bool) {
	sigchan := make(chan os.Signal, 1)

	var s os.Signal
	if interactive {
		s = syscall.SIGINT
	} else {
		s = syscall.SIGTERM
	}

	signal.Notify(sigchan, s)

	// wait on a signal
	receivedSignal := <-sigchan
	log.Printf("received signal %q, initiating self eviction\n", receivedSignal)

	if interactive {
		log.Error("triggered graceful shutdown. Press Ctrl+C again to force exit.")
		go func() {
			// exit on second signal
			<-sigchan
			log.Error("Force exiting...")
			os.Exit(2)
		}()
	}

	err := rp.SelfEvict()
	if err != nil {
		log.Errorf("Error during self-eviction: %v\n", err)
		os.Exit(1)
	}

	os.Exit(0)
}
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person


mation flags. The console server
     * doesn't support HANDLE_FLAG_PROTECT_FROM_CLOSE.
     */
    if (SetHandleInfoRequest->Mask & HANDLE_FLAG_INHERIT)
    {
        Entry->Inheritable = ((SetHandleInfoRequest->Flags & HANDLE_FLAG_INHERIT) != 0);
    }

    Status = STATUS_SUCCESS;

Quit:
    RtlLeaveCriticalSection(&ProcessData->HandleTableLock);

    ConSrvReleaseConsole(Console, TRUE);
    return Status;
}

CSR_API(SrvCloseHandle)
{
    NTSTATUS Status;
    PCONSOLE_CLOSEHANDLE CloseHandleRequest = &((PCONSOLE_API_MESSAGE)ApiMessage)->Data.CloseHandleRequest;
    PCONSOLE_PROCESS_DATA ProcessData = ConsoleGetPerProcessData(CsrGetClientThread()->Process);
    PCONSOLE Console;

    Status = ConSrvGetConsole(ProcessData, &Console, TRUE);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("Can't get console\n");
        return Status;
    }

    Status = ConSrvRemoveObject(ProcessData, CloseHandleRequest->Handle);

    ConSrvReleaseConsole(Console, TRUE);
    return Status;
}

CSR_API(SrvVerifyConsoleIoHandle)
{
    NTSTATUS Status;
    PCONSOLE_VERIFYHANDLE VerifyHandleRequest = &((PCONSOLE_API_MESSAGE)ApiMessage)->Data.VerifyHandleRequest;
    PCONSOLE_PROCESS_DATA ProcessData = ConsoleGetPerProcessData(CsrGetClientThread()->Process);
    PCONSOLE Console;

    HANDLE IoHandle = VerifyHandleRequest->Handle;
    ULONG Index = HandleToULong(IoHandle) >> 2;

    VerifyHandleRequest->IsValid = FALSE;

    Status = ConSrvGetConsole(ProcessData, &Console, TRUE);
    if (!NT_SUCCESS(Status))
    {
        DPRINT1("Can't get console\n");
        return Status;
    }

    RtlEnterCriticalSection(&ProcessData->HandleTableLock);

    // ASSERT( (ProcessData->HandleTable == NULL && ProcessData->HandleTableSize == 0) ||
    //         (ProcessData->HandleTable != NULL && ProcessData->HandleTableSize != 0) );

    if (!IsConsoleHandle(IoHandle)            ||
        Index >= ProcessData->HandleTableSize ||
        ProcessData->HandleTable[Index].Object == NULL)
    {
        DPRINT("SrvVerifyConsoleIoHandle failed\n");
    }
    else
    {
        VerifyHandleRequest->IsValid = TRUE;
    }

    RtlLeaveCriticalSection(&ProcessData->HandleTableLock);

    ConSrvReleaseConsole(Console, TRUE);
    return STATUS_SUCCESS;
}

/* EOF */


Add last_polled to deployment table
SQLite: `f3165ae0a213`
Postgres: `bfe653bbf62e`

# Make flow_run_id nullable on task_run and log tables
SQLite: `05ea6f882b1d`
Postgres: `05ea6f882b1d`

# Make slot_decay_per_second not nullable
SQLite: `8167af8df781`
Postgres: `4e9a6f93eb6c`

# Add heartbeat_interval_seconds to worker table
SQLite: `c2d001b7dd06`
Postgres: `50f8c182c3ca`

# Create Concurrency Limit V2 table
SQLite: `5b0bd3b41a23`
Postgres: `5f623ddbf7fe`

# Migrate Artifact data to Artifact Collection
SQLite: `2dbcec43c857`
Postgres: `15f5083c16bd`

# Add Variables Table
SQLite: `3d46e23593d6`
Postgres: `310dda75f561`

# Add pull steps to deployment table
SQLite: `340f457b315f`
Postgres: `43c94d4c7aa3`

# Add Artifact Collection columns
SQLite: `3e1eb8281d5e`
Postgres: `6a1eb3d442e4`

# Add index on log table
SQLite: `553920ec20e9`
Postgres: `3bf47e3ce2dd`

# Add Artifact index
SQLite: `422f8ba9541d`
Postgres: `46bd82c6279a`

# Add Artifact Collection table
SQLite: `b9aafc3ab936`
Postgres: `d20618ce678e`

# Remove Artifact unique constraint
SQLite: `1d7441c031d0`
Postgres: `aa84ac237ce8`

# Add Artifact description column
SQLite: `cf1159bd0d3c`
Postgres: `4a1a0e4f89de`

# Remove Flow Run foreign keys
SQLite: `f3df94dca3cc`
Postgres: `7d918a392297`

# Remove Artifact foreign keys
SQLite: `8d148e44e669`
Postgres: `cfdfec5d7557`

# Clean up work queue migration
SQLite: `bfe42b7090d6`
Postgres: `2a88656f4a23`

# Work queue data migration
SQLite: `1678f2fb8b33`
Postgres: `f98ae6d8e2cc`

# Expands Work Queue Table
SQLite: `b9bda9f142f1`
Postgres: `0a1250a5aa25`

# State data migration cleanup
SQLite: `f92143d30c27`
Postgres: `2882cd2df466`

# Migrates state data to the artifact table
SQLite: `f92143d30c26`
Postgres: `2882cd2df465`

# Add a helper index for the artifact data migration
SQLite: `f92143d30c25`
Postgres: `2882cd2df464`

# Initial schema migration for the artifacts/results table
SQLite: `f92143d30c24`
Postgres: `2882cd2df463`

This schema migration creates the artifact table with extra `state_id` columns in order speed up the data migration.

# Add `CANCELLING` to StateType enum
SQLite: None
Postgres: `9326a6aee18b`

# Add infrastructure_pid to flow runs
SQLite: `7201de756d85`
Postgres: `5d526270ddb4`

# Add index for partial work queue name match
SQLite: None
Postgres: `41e5ed9e1034`

# Add version to block schema
SQLite: `e757138e954a`
Postgres: `2d5e000696f1`

# Add work queue name to runs
SQLite: `575634b7acd4`
Postgres: `77eb737fc759`

## Add more fields to deployments

SQLite:


 updateString = sqlQueryObject.createSQLDelete();
			stmt = con.prepareStatement(updateString);
			stmt.setLong(1, idAccordo);
			stmt.setString(2, nomeAzione);
			stmt.executeUpdate();
			stmt.close();

		} catch (Exception se) {
			throw new DriverRegistroServiziException("[DriverRegistroServiziDB::" + nomeMetodo + "] Exception: " + se.getMessage(),se);
		} finally {
			//Chiudo statement and resultset
			JDBCUtilities.closeResources(stmt);

			this.driver.closeConnection(con);
		}

	}

	protected List<PortType> accordiPorttypeList(long idAccordo, ISearch ricerca) throws DriverRegistroServiziException {
		String nomeMetodo = "accordiPorttypeList";
		int idLista = Liste.ACCORDI_PORTTYPE;
		int offset;
		int limit;
		String search;
		String queryString;

		limit = ricerca.getPageSize(idLista);
		offset = ricerca.getIndexIniziale(idLista);
		search = (org.openspcoop2.core.constants.Costanti.SESSION_ATTRIBUTE_VALUE_RICERCA_UNDEFINED.equals(ricerca.getSearchString(idLista)) ? "" : ricerca.getSearchString(idLista));
		ricerca.getSearchString(idLista);

		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet risultato = null;

		ArrayList<PortType> lista = new ArrayList<PortType>();

		if (this.driver.atomica) {
			try {
				con = this.driver.getConnectionFromDatasource("accordiPorttypeList");

			} catch (Exception e) {
				throw new DriverRegistroServiziException("[DriverRegistroServiziDB::" + nomeMetodo + "] Exception accedendo al datasource :" + e.getMessage(),e);

			}

		} else
			con = this.driver.globalConnection;

		this.driver.logDebug("operazione this.driver.atomica = " + this.driver.atomica);

		try {

			if (!search.equals("")) {
				//query con search
				ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(this.driver.tipoDB);
				sqlQueryObject.addFromTable(CostantiDB.PORT_TYPE);
				sqlQueryObject.addSelectCountField("*", "cont");
				sqlQueryObject.addWhereCondition("id_accordo = ?");
				sqlQueryObject.addWhereLikeCondition("nome", search, true, true);
				sqlQueryObject.setANDLogicOperator(true);
				queryString = sqlQueryObject.createSQLQuery();
			} else {
				ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(this.driver.tipoDB);
				sqlQueryObject.addFromTable(CostantiDB.PORT_TYPE);
				sqlQueryObject.addSelectCountField("*", "cont");
				sqlQueryObject.addWhereCondition("id_accordo = ?");
				queryString = sqlQueryObject.createSQLQuery();
			}
			stmt = con.prepareStatement(queryString);
			stmt.setLong(1,idAccordo);
			risultato = stmt.executeQuery();
			if (risultato.next())
				ricerca.setNumEntries(idLista,risultato.getInt("cont"));
			risultato.close();
			stmt.close();

			// ricavo le entries
			if (limit == 0) // con limit
				limit = ISQLQueryObject.LIMIT_DEFAULT_VALUE;
			if (!search.equals("")) { // con search
				ISQLQueryObject sqlQueryObject = SQLObjectFactory.createSQLQueryObject(this.driver.tipoDB);
				sqlQueryObject.addFromTable(CostantiDB.PORT_TYPE);
				sqlQueryObject.addSelectField("id");
				sqlQueryObject.addSelectField("nome");
				sqlQueryObject.addWhereCondition("id_accordo


 `json:"userTypedURL"`

	// Title Title of the navigation history entry.
	//、 导航历史条目的标题。
	Title string `json:"title"`

	// TransitionType Transition type.
	// 页面转换类型
	TransitionType PageTransitionType `json:"transitionType"`
}

// PageScreencastFrameMetadata (experimental) Screencast frame metadata.
// 屏幕录像Frame的元数据
type PageScreencastFrameMetadata struct {

	// OffsetTop Top offset in DIP.
	// DIP中的顶部偏移量。
	OffsetTop float64 `json:"offsetTop"`

	// PageScaleFactor Page scale factor.
	// 页面比例系数。
	PageScaleFactor float64 `json:"pageScaleFactor"`

	// DeviceWidth Device screen width in DIP.
	// 以DIP为单位的设备屏幕宽度。
	DeviceWidth float64 `json:"deviceWidth"`

	// DeviceHeight Device screen height in DIP.
	// 以DIP为单位的设备屏幕高度。
	DeviceHeight float64 `json:"deviceHeight"`

	// ScrollOffsetX Position of horizontal scroll in CSS pixels.
	// 水平滚动的位置，以CSS像素为单位。
	ScrollOffsetX float64 `json:"scrollOffsetX"`

	// ScrollOffsetY Position of vertical scroll in CSS pixels.
	// 垂直滚动的位置，以CSS像素为单位。
	ScrollOffsetY float64 `json:"scrollOffsetY"`

	// Timestamp (optional) Frame swap timestamp.
	// Frame 交换的时间戳。
	Timestamp TimeSinceEpoch `json:"timestamp,omitempty"`
}

// PageDialogType Javascript dialog type.
// JS 弹窗的类型
type PageDialogType string

const (
	// PageDialogTypeAlert enum const
	PageDialogTypeAlert PageDialogType = "alert"

	// PageDialogTypeConfirm enum const
	PageDialogTypeConfirm PageDialogType = "confirm"

	// PageDialogTypePrompt enum const
	PageDialogTypePrompt PageDialogType = "prompt"

	// PageDialogTypeBeforeunload enum const
	PageDialogTypeBeforeunload PageDialogType = "beforeunload"
)

// PageAppManifestError Error while paring app manifest.
// 在解析应用程序清单时出错。
type PageAppManifestError struct {

	// Message Error message.
	// 错误消息
	Message string `json:"message"`

	// Critical If criticial, this is a non-recoverable parse error.
	// 如果是严重的，则这是一个不可恢复的解析错误。
	Critical int `json:"critical"`

	// Line Error line.
	// 错误行数
	Line int `json:"line"`

	// Column Error column.
	// 错误列数
	Column int `json:"column"`
}

// PageAppManifestParsedProperties (experimental) Parsed app manifest properties.
// 已解析的应用程序清单属性。
type PageAppManifestParsedProperties struct {

	// Scope Computed scope value
	// 计算的范围值
	Scope string `json:"scope"`
}

// PageLayoutViewport Layout viewport position and dimensions.
// 布局viewport（电脑屏幕的可视窗口）位置和尺寸。
type PageLayoutViewport struct {

	// PageX Horizontal offset relative to the document (CSS pixels).
	// 相对于文档的水平偏移（CSS像素）。
	PageX int `json:"pageX"`

	// PageY Vertical offset relat


));

// fuck pocket {
#save-to-pocket-button {
    --toolbarbutton-icon-width: 18px !important;
    --toolbarbutton-icon-height: 18px !important;

    &[open] {
        fill: rgb(213,32,20) !important;
    }
}

#bookmarks-menu-button[starred] .toolbarbutton-menubutton-button,
#downloads-button[attention="success"] {
    fill: var(--toolbarbutton-icon-fill-attention) !important;
}html {
  font-family: sans-serif;
  background: Field;
  color: FieldText;
  height: 100%;
}

body {
  display: inline-block;
  position: relative;
  margin: 0;
  width: 100%;
  height: 100%;
}

span p {
  display: inline-block;
}

a {
  color: rgb(0, 0, 238);
  text-decoration: none;
  cursor: pointer;
}

a:hover {
  text-decoration: underline;
}

a:focus {
  color: rgb(238, 0, 0);
}

#brandStart {
  text-align: center;
  height: 19%;
  max-height: 256px;
  min-height: 92px;
}

#brandStartSpacer {
  height: 6.5%;
}

#brandStartLogo {
  display: inline-block;
  content: var(--about-logo);
  height: 100%;
}

#searchContainer {
  height: 15%;
  min-height: 90px;
}

#searchContainer::before {
  content: " ";
  display: block;
  height: 23%;
}

#searchForm {
  display: table;
  width: 100%;
  max-width: 1830px;
  margin: 0 auto;
}

@media all and (max-height: 700px) {
  #searchContainer {
    height: 20%;
  }
}
@media all and (max-height: 450px) {
  #searchContainer {
    height: 30%;
  }
}
#searchLogoContainer {
  display: table-cell;
  width: 30%;
  text-align: end;
  line-height: 32px;
}

#searchEngineLogo {
  display: inline-block;
  margin-inline-end: 2.5%;
  content: url("chrome://userchrome/content/pages/home/images/firefox-4/google.png");
}

#searchEngineLogo[hidden=true] {
  display: none;
}

#searchInputContainer {
  display: table-cell;
  width: 38%;
  max-width: 700px;
  min-width: 150px;
  vertical-align: top;
}

#searchText {
  width: 100%;
  height: 24px;
  padding: 3px 6px;
  border-radius: 2px;
  border: 1px solid rgb(150, 150, 150);
  border-top-color: rgb(100, 100, 100);
  box-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
  font-size: 1.2em;
  outline: 0;
}

#searchButtons {
  display: table-cell;
  width: 31%;
  padding-inline-start: 13px;
  vertical-align: top;
}

@media all and (max-width: 470px) {
  #searchLogoContainer {
    width: 10%;
  }
  #searchButtons {
    width: 11%;
  }
  #searchInputContainer {
    width: 40%;
  }
}
@media all and (min-width: 470px) and (max-width: 600px) {
  #searchLogoContainer {
    width: 15%;
  }
  #searchB


ner);

                const defaultToChinese = GM_getValue('defaultToChinese', false);
                cardLanguageStates.set(cardId, false);
                if (defaultToChinese) {
                    await toggleLanguage({
                        preventDefault: () => {},
                        target: container.querySelector('.print-langs-item')
                    }, cardId);
                }
            } catch (error) {
                console.error('处理卡牌时出错:', error);
                updateToggleButton(true, container);
            }
        }

        const toolbox = document.querySelector('.toolbox');
        if (toolbox) {
            setupToolboxCollapse(toolbox);
        }
    }

    function setupToolboxCollapse(toolbox) {
        const toolboxTitle = toolbox.querySelector('h6');
        if (!toolboxTitle) return;

        const toggleButton = document.createElement('button');
        toggleButton.className = 'toolbox-toggle';
        toggleButton.innerHTML = '▼';
        toggleButton.title = '折叠/展开工具箱';

        toolboxTitle.insertBefore(toggleButton, toolboxTitle.firstChild);

        if (document.querySelector('#rulings')) {
            toolbox.classList.add('collapsed');
        }

        toggleButton.addEventListener('click', () => {
            toolbox.classList.toggle('collapsed');
        });
    }

    function addToggleButton(loading = false, parent = document) {
        const printLangs = parent.querySelector('.print-langs');
        if (!printLangs) return;

        const cardId = parent.dataset.cardId || document.location.pathname;
        if (!parent.dataset.cardId) {
            parent.dataset.cardId = cardId;
        }

        const toggleLink = document.createElement('a');
        toggleLink.className = 'print-langs-item translate-toggle';
        toggleLink.href = 'javascript:void(0);';
        toggleLink.textContent = loading ? '加载中...' : (cardLanguageStates.get(cardId) ? '原文' : '汉化');
        toggleLink.style.cursor = loading ? 'wait' : 'pointer';

        if (!loading) {
            toggleLink.addEventListener('click', (e) => toggleLanguage(e, cardId));
        }

        printLangs.insertBefore(toggleLink, printLangs.firstChild);
    }

    function updateToggleButton(error = false, parent = document) {
        const toggleLink = parent.querySelector('.print-langs-item');
        if (toggleLink) {
            const cardId = parent.dataset.cardId || document.location.pathname;
            toggleLink.textContent = error ? '加载失败' : (cardLanguageStates.get(cardId) ? '原文' : '汉化');
            toggleLink.style.cursor = error ? 'not-allowed' : 'pointer';
            if (error) {
                toggleLink.removeEventListener('click', (e) => toggleLanguage(e, cardId));
            } else {
                toggleLink.addEventListener('click', (e) => toggleLanguage(e, cardId));
            }

        }
    }

    async function toggleLanguage(event, cardId) {
        event.preventDefault();

        const cardContainer = cardId === document.location.pathname
        ? document
        : document.querySelector(`[data-card-id="${cardId}"]`);

        if (!cardContainer) {
            console.error('找不到卡牌容器');
            return;
        }

        const elements = cardContainer.querySelectorAll(
            '.card-text-card-name, .card-text-flavor-name, .card-text-type-line, .card-text-oracle, .card-text-flavor, ' +
            '.card-legality-item dt, .card-legality-item dd'
        );

        const rulingsItems = document.querySelectorAll('.rulings-item');
        const allElements = [...elements, ...rulingsItems];

        const toggleLink = event.target;

        if (allElements.length === 0 || !allElements[0].


p>}
        {idTokenPayload != null &&
{JSON.stringify(idTokenPayload)}
}

  );
};
```

## How to get User Information : Hook method

```javascript
import { useOidcUser, UserStatus } from '@axa-fr/react-oidc';

const DisplayUserInfo = () => {
  const { oidcUser, oidcUserLoadingState } = useOidcUser();

  switch (oidcUserLoadingState) {
    case UserStatus.Loading:
      return
User Information are loading
;
    case UserStatus.Unauthenticated:
      return
you are not authenticated
;
    case UserStatus.LoadingError:
      return
Fail to load user information
;
    default:
      return (

User information

{JSON.stringify(oidcUser)}

      );
  }
};
```

## How to get a fetch that inject Access_Token : Hook method

If your are not using the service worker. Fetch function need to send AccessToken.
This Hook give you a wrapped fetch that add the access token for you.

```javascript
import React, { useEffect, useState } from 'react';
import { useOidcFetch, OidcSecure } from '@axa-fr/react-oidc';

const DisplayUserInfo = ({ fetch }) => {
  const [oidcUser, setOidcUser] = useState(null);
  const [isLoading, setLoading] = useState(true);

  useEffect(() => {
    const fetchUserInfoAsync = async () => {
      const res = await fetch('https://demo.duendesoftware.com/connect/userinfo');
      if (res.status != 200) {
        return null;
      }
      return res.json();
    };
    let isMounted = true;
    fetchUserInfoAsync().then(userInfo => {
      if (isMounted) {
        setLoading(false);
        setOidcUser(userInfo);
      }
    });
    return () => {
      isMounted = false;
    };
  }, []);

  if (isLoading) {
    return <>Loading</>;
  }

  return (

User information

          {oidcUser != null &&
{JSON.stringify(oidcUser)}
}

  );
};

export const FetchUserHook = () => {
  const { fetch } = useOidcFetch();
  return (
    <OidcSecure>
      <DisplayUserInfo fetch={fetch} />
    </OidcSecure>
  );
};
```

## How to get a fetch that inject Access_Token : HOC method

If your are not using the service worker. Fetch function need to send AccessToken.
This HOC give you a wrapped fetch that add the access token for you.

```javascript
import React, { useEffect, useState } from 'react';
import { useOidcFetch, OidcSecure } from '@axa-fr/react-oidc';

const DisplayUserInfo = ({ fetch }) => {
  const [oidcUser, setOidcUser] = useState(null);
  const [isLoading, setLoading] = useState(true);

  useEffect(() => {
    const fetchUserInfoAsync = async () => {
      const res = await fetch('https://demo.duendesoftware.com/connect/userinfo');
      if (res.status != 200) {
        return null;
      }
      return res.json();
    };
    let isMounted = true;
    fetchUserInfoAsync().


<String> stack)
			{
			this.stack=stack;
			}
		@Override
		public boolean hasNext() {
			return !stack.isEmpty();
			}
		@Override
		public String next() {
			return stack.removeFirst();
			}
		@Override
		public String peek() {
			return stack.peek();
			}
		@Override
		public void remove() {
			throw new UnsupportedOperationException();
			}
		}

	public static List<String> parseHeaderLines(final LineReader r) throws IOException
		{
		LinkedList<String> stack=new LinkedList<String>();
		String line;
		while((line=r.readLine())!=null && line.startsWith("#"))
			{
			stack.add(line);
			if(line.startsWith("#CHROM\t")) break;
			}
		return stack;
		}

	public static CodecAndHeader parseHeader(final LineReader r) throws IOException
		{
		return parseHeader(parseHeaderLines(r));
		}

	public static List<String> parseHeaderLines(final BufferedReader r) throws IOException
		{
		final LinkedList<String> stack=new LinkedList<String>();
		String line;
		while((line=r.readLine())!=null && line.startsWith("#"))
			{
			stack.add(line);
			if(line.startsWith("#CHROM\t")) break;
			}
		return stack;
		}

	public static CodecAndHeader parseHeader(final BufferedReader r) throws IOException
		{
		return parseHeader(parseHeaderLines(r));
		}

	public static CodecAndHeader parseHeader(final LineIterator r)
		{
		final CodecAndHeader vh=new CodecAndHeader();
		vh.codec=null;
		LinkedList<String> stack=new LinkedList<String>();
		while(r.hasNext())
			{
			final String line=r.peek();
			if(!line.startsWith("#")) break;
			stack.add(r.next());
			if(line.startsWith("#CHROM\t")) break;
			}
		vh.codec = findCodecFromLines(stack);
		vh.header=  (VCFHeader)vh.codec.readActualHeader(new LIT(stack));
    	return vh;
		}

	/** stringent insertion in VCF header */
	public static void safeAddMetaDataHeaderLine(final VCFHeader header,final VCFHeaderLine hl){
		final VCFHeaderLine prev =header.getMetaDataLine(hl.getKey());
		if(prev!=null && !prev.getValue().equals(hl.getValue())) {
			throw new IllegalArgumentException("Cannot insert vcf header "+hl.getKey()+" because it is already defined in VCF header");
		}
		header.addMetaDataLine(hl);
	}

	/** find a codec from the lines header. if not found, return default codec */
	public static AbstractVCFCodec findCodecFromLines(final List<String> list)
		{
		for(final String line: list)
			{
			String formatString = line;
			if(formatString.startsWith("##"))
				{
				formatString=formatString.substring(2);
				}
			int eq= formatString.indexOf('=');
			if(eq==-1) continue;

			if(!VCFHeaderVersion.isFormatString(formatString.substring(0,eq))) continue;

			VCFHeaderVersion version=VCFHeaderVersion.getHeaderVersion(line	);
			if(version==null) continue;
			switch(version)
				{
				case VCF3_2:
				case VCF3_3: return new VCF3Codec();
				case VCF4_0:
				case VCF4_1:
				case VCF4_2:
				case VCF4_3:
				case VCF4_4:return new VCFCodec();
				}
			}
		return createDefaultVCFCodec();
		}

	public static CodecAndHeader parseHeader(final List<String> list)
		{
		final CodecAndHeader vh=new CodecAndHeader();
		vh.codec=findCodecF


td class="gray">ERROR_DISK_FULL, ERROR_HANDLE_DISK_FULL
    "Insufficient disk space"

    ERROR_DIR_NOT_EMPTY
    "The folder is not empty"

    ERROR_INTERNET_INCORRECT_USER_NAME
    "Incorrect user name"

    ERROR_INTERNET_INCORRECT_PASSWORD
    "Incorrect password"

    ERROR_INTERNET_LOGIN_FAILURE
    "Login failure"

    ERROR_INTERNET_CONNECTION_ABORTED
    "Connection aborted"

    ERROR_CANCELLED
    "Operation cancelled"

    ERROR_NO_NETWORK
    "No network present"

    ERROR_DEVICE_IN_USE
    "Device is in use and cannot be disconnected"

    ERROR_OPEN_FILES
    "This network connection has open files"

    ERROR_ALREADY_ASSIGNED
    "The local device name is already in use"

    ERROR_DEVICE_ALREADY_REMEMBERED
    "The local device is already in the user profile"

    ERROR_NOT_LOGGED_ON
    "User has not logged on to the network"

    ERROR_INVALID_PASSWORD
    "The user password is invalid"

    ERROR_NO_RECOVERY_POLICY
    "There is no valid encryption recovery policy configured for this system"

    ERROR_ENCRYPTION_FAILED
    "The specified file could not be encrypted"

    ERROR_DECRYPTION_FAILED
    "The specified file could not be decrypted"

    ERROR_FILE_NOT_ENCRYPTED
    "The specified file is not encrypted"

See also:

  Message

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<title>FARMANAGERVERSION</title>
<meta http-equiv="Content-Type" Content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="../../styles/styles.css">

FARMANAGERVERSION

<a


 width, height);
      break;
    }

    case UnderlineType::Underdashed: {
      float width = xsize / 3;
      ctx.fillRect(0, 0, width, underlineThickness);
      ctx.fillRect(width * 2, 0, width, underlineThickness);
      break;
    }
  }
}

Pen::ImageData Pen::Draw(const DrawDesc& desc) {
  // init ---------------------------
  int xoffset = 0;
  int yoffset = 0;

  // actual size of data
  int dataWidth = xsize;
  int dataHeight = ysize;

  // diagonal needs extra space
  if (std::holds_alternative<Diagonal>(desc)) {
    xoffset += xhalf / 2;
    dataWidth += xhalf;
  }

  // begin -----------------------------
  img.create(dataWidth, dataHeight, BL_FORMAT_PRGB32);
  ctx.begin(img);
  ctx.clearAll();

  ctx.setFillStyle(BLRgba(1, 1, 1, 1));
  ctx.setCompOp(BL_COMP_OP_PLUS);
  ctx.translate(xoffset, yoffset);

  // draw ------------------------------
  std::visit(overloaded{
    [this](const HLine& desc) { DrawHLine(0, xsize, desc.weight); },
    [this](const VLine& desc) { DrawVLine(0, ysize, desc.weight); },
    [this](const Cross& desc) { DrawCross(desc); },
    [this](const HDash& desc) { DrawHDash(desc); },
    [this](const VDash& desc) { DrawVDash(desc); },
    [this](const DoubleCross& desc) { DrawDoubleCross(desc); },
    [this](const Arc& desc) { DrawArc(desc); },
    [this](const Diagonal& desc) { DrawDiagonal(desc); },
    [this](const HalfLine& desc) { DrawHalfLine(desc); },
    [this](const Shade& desc) { DrawShade(desc); },
    [this](const UpperBlock& desc) { ctx.fillRect(0, 0, xsize, desc.size * ysize); },
    [this](const LowerBlock& desc) { ctx.fillRect(0, ysize - (desc.size * ysize), xsize, desc.size * ysize); },
    [this](const LeftBlock& desc) { ctx.fillRect(0, 0, desc.size * xsize, ysize); },
    [this](const RightBlock& desc) { ctx.fillRect(xsize - (desc.size * xsize), 0, desc.size * xsize, ysize); },
    [this](const Quadrant& desc) { DrawQuadrant(desc); },
    [this](const Braille& desc) { DrawBraille(desc); },
    [this](const Underline& desc) { DrawUnderline(desc); },
  }, desc);

  // end -------------------------------
  ctx.end();
  img.getData(&blData);

  // create data ----------------------------
  std::extents shape{dataHeight, dataWidth};
  std::array strides{blData.stride / sizeof(uint32_t), 1uz};
  auto data = std::mdspan(
    static_cast<uint32_t*>(blData.pixelData),
    std::layout_stride::mapping{shape, strides}
  );

  // memory optimization
  // find the bounds of data and create span within the bounds
  // basically discards empty cells
  size_t xmin = data.extent(1);
  size_t ymin = data.extent(0);
  size_t xmax = 0;
  size_t ymax = 0;

  for (size_t y = 0; y < data.extent(0); y++) {
    for (size_t x = 0; x < data.extent(1); x++) {
      if (da


= {x = 164, y = 366}})
            fastforward_ui_events()
            assert.is.same(22, readerui.paging.current_page)
            readerui.link:onGoBackLink()


2448))S=Z J[L]=Z D=Y[m]U=D Z=D and 11491312-(541020-218775)or(326799+-1026181)+1728228 end else if Z<(132916+7716304)-(-152046)then h=true Z=h and 142497+(-125373+3025356)or 378621+14460247 else E={}l=nil Z=Y[y((1093616-1044989)-12610)]end end end else if Z<9043548-165903 then if Z<(-744423+906080)+8646389 then if Z<9417352-(-800114+1594156)then Z=Y[y(-994774-(162648+-1193484))]U=y(-168302-(((-38586+26552)+-508466)-(-316187)))L=Y[U]U=y(-273204+309201)l=L[U]U=J[c[533809-533808]]L={l(U)}E={f(L)}else Z=J[c[782683-(-481798+1264479)]]Z=Z and 1707897-(-763964)or-622472+2724738 end else if Z<-366068+9213550 then l=J[c[-648963-(-648964)]]E=#l l=(((-268795-(1929966-988789))-(897038-1015005))-(-684745))-(-407260)Z=E==l Z=Z and-105306+10526691 or 9113682-(1790804-((762930-210968)-(-313130)))else w=517511-517498 U=-402675+402707 H=-964165-(-964167)L=J[c[-361203+361206]]l=L%U S=J[c[965157+(-122988-842165)]]G=J[c[-832132-(-832134)]]s=J[c[-100723+100726]]u=s-l s=-902315-(843031+-1745378)v=u/s q=w-v i=H^q m=G/i D=S(m)S=476447+4294490849.0 U=D%S D=-75748-(-75750)S=D^l L=U/S H=71092-70836 S=J[c[-848595-(-848599)]]i=858418+-858417 G=L%i i=(252196-(-34591))+4294680509.0 m=G*i D=S(m)S=J[c[834887-834883]]m=S(L)U=D+m D=735585+-670049 S=U%D G=79766-14230 m=U-S L=nil D=m/G G=490773-(340006-(-169445-(-18934)))m=S%G w=543798-543542 Z=-717307+8905277 U=nil i=S-m G=i/H H=(275966-(-379318))-655028 i=D%H l=nil S=nil q=D-i H=q/w q={m,G,i,H}D=nil i=nil H=nil G=nil m=nil J[c[(473743+-898064)-(-424322)]]=q end end else if Z<8776027-(-336872)):then do v.       PE  L C:ì–        à "0  XU  @      ÞvU           @                       àU         `…


, int finalDamageFactor)
    {
        if(factor > 0)
        {
            var def = defender.GetComponent<CharacterStatus>().attributes.Find(d => d.eName == "def").value;
            var atk = attacker.GetComponent<CharacterStatus>().attributes.Find(d => d.eName == "atk").value;

            int damage = ((int)(0.1f * atk * factor));

            //最终伤害加成
            damage = (int)(damage * (1 + 0.01 * finalDamageFactor));

            if (backStabBonus)
            {
                if (BackStab(attacker, defender))
                {
                    damage = damage * 50 / (def / 2 + 50);
                }


* @param w {Number} The width of the rectangle, in pixels
    * @param h {Number} The height of the rectangle, in pixels
    * @description The strokeRect() method draws a rectangle (no fill). The default color of the stroke is black.
    */

    Context2D.prototype.strokeRect = function strokeRect(x, y, w, h) {
      if (isNaN(x) || isNaN(y) || isNaN(w) || isNaN(h)) {
        console.error('jsPDF.context2d.strokeRect: Invalid arguments', arguments);
        throw new Error('Invalid arguments passed to jsPDF.context2d.strokeRect');
      }

      if (isStrokeTransparent.call(this)) {
        return;
      }

      this.beginPath();
      this.rect(x, y, w, h);
      this.stroke();
    };
    /**
    * Clears the specified pixels within a given rectangle
    *
    * @name clearRect
    * @function
    * @param x {Number} The x-coordinate of the upper-left corner of the rectangle
    * @param y {Number} The y-coordinate of the upper-left corner of the rectangle
    * @param w {Number} The width of the rectangle to clear, in pixels
    * @param h {Number} The height of the rectangle to clear, in pixels
    * @description We cannot clear PDF commands that were already written to PDF, so we use white instead. <br />
    * As a special case, read a special flag (ignoreClearRect) and do nothing if it is set.
    * This results in all calls to clearRect() to do nothing, and keep the canvas transparent.
    * This flag is stored in the save/restore context and is managed the same way as other drawing states.
    *
    */

    Context2D.prototype.clearRect = function (x, y, w, h) {
      if (isNaN(x) || isNaN(y) || isNaN(w) || isNaN(h)) {
        console.error('jsPDF.context2d.clearRect: Invalid arguments', arguments);
        throw new Error('Invalid arguments passed to jsPDF.context2d.clearRect');
      }

      if (this.ignoreClearRect) {
        return;
      }

      this.fillStyle = '#ffffff';
      this.fillRect(x, y, w, h);
    };
    /**
    * Saves the state of the current context
    *
    * @name save
    * @function
    */

    Context2D.prototype.save = function (doStackPush) {
      doStackPush = typeof doStackPush === 'boolean' ? doStackPush : true;
      var tmpPageNumber = this.pdf.internal.getCurrentPageInfo().pageNumber;

      for (var i = 0; i < this.pdf.internal.getNumberOfPages(); i++) {
        this.pdf.setPage(i + 1);
        this.pdf.internal.out('q');
      }

      this.pdf.setPage(tmpPageNumber);

      if (doStackPush) {
        this.ctx.fontSize = this.pdf.internal.getFontSize();
        var ctx = new ContextLayer(this.ctx);
        this.ctxStack.push(this.ctx);
        this.ctx = ctx;
      }
    };
    /**
    * Returns previously saved path state and attributes
    *
    * @name restore
    * @function
    */

    Context2D.prototype.restore = function (doStackPop) {
      doStackPop = typeof doStackPop === 'boolean' ? doStackPop : true;
      var tmpPageNumber = this.pdf.internal.getCurrentPageInfo().pageNumber;

      for (var i = 0; i < this.pdf.internal.getNumberOfPages(); i++) {
        this.pdf.setPage(i + 1);
        this.pdf.internal.out('Q');
      }

      this.pdf.setPage(tmpPageNumber);

      if (doStackPop &&


td_entry16_valid 01 pb_cfg_td_entry17_valid 02 pb_cfg_td_entry18_valid 03 pb_cfg_td_entry19_valid 04 pb_cfg_td_entry20_valid 05 pb_cfg_td_entry21_valid 06 pb_cfg_td_entry22_valid 07 pb_cfg_td_entry23_valid 08 pb_cfg_td_entry24_valid 09 pb_cfg_td_entry25_valid 10 pb_cfg_td_entry26_valid 11 pb_cfg_td_entry27_valid 12 pb_cfg_td_entry28_valid 13 pb_cfg_td_entry29_valid 14 pb_cfg_td_entry30_valid 15 pb_cfg_td_entry31_valid 16:18 pb_cfg_td_entry16_ax_num 19:21 pb_cfg_td_entry17_ax_num 22:24 pb_cfg_td_entry18_ax_num 25:27 pb_cfg_td_entry19_ax_num 28:30 pb_cfg_td_entry20_ax_num 31:33 pb_cfg_td_entry21_ax_num 34:36 pb_cfg_td_entry22_ax_num 37:39 pb_cfg_td_entry23_ax_num 40:42 pb_cfg_td_entry24_ax_num 43:45 pb_cfg_td_entry25_ax_num 46:48 pb_cfg_td_entry26_ax_num 49:51 pb_cfg_td_entry27_ax_num 52:54 pb_cfg_td_entry28_ax_num 55:57 pb_cfg_td_entry29_ax_num 58:60 pb_cfg_td_entry30_ax_num 61:63 pb_cfg_td_entry31_ax_num

SelectedAttributes:

Latches	Bits	Latch Name [flushval]

0:63	PB.PB_COM.PB_SCOM_EQ5.REG4A_DATA_Q_0_INST.LATC.L2(0:63) [0000000000000000000000000000000000000000000000000000000000000000]

Bit(s)	SCOM
Dial: Description

0
RWX

PB_CFG_TID_ENTRY16_VALID_NEXT_EQ5: Topology ID entry16 valid.

1
RWX

PB_CFG_TID_ENTRY17_VALID_NEXT_EQ5: Topology ID entry17 valid.

2
RWX

PB_CFG_TID_ENTRY18_VALID_NEXT_EQ5: Topology ID entry18 valid.

3
RWX

PB_CFG_TID_ENTRY19_VALID_NEXT_EQ5: Topology ID entry19 valid.

<TD b


 CloseState, CloseStateSignature, CustomerBalance, CustomerRandomness,
    MerchantBalance, MerchantRandomness, VerifiedBlindedState,
};

pub use revlock::RevocationLock;

mod nonce;
mod proofs;
mod states;

mod types {
    pub use bls12_381::{pairing, G1Affine, G1Projective, G2Affine, G2Projective, Scalar};
    pub use zkchannels_crypto::*;
}

use crate::types::*;
use serde::*;
use std::convert::TryFrom;
use thiserror::*;

/// Possible error conditions returned from the ZkAbacus API.
#[derive(Debug, Error, Clone, Copy, Serialize, Deserialize)]
pub enum Error {
    /// An amount was too large to be representable as a 64-bit signed integer.
    #[error("amount too large to be representable (greater than 2^63: {0})")]
    AmountTooLarge(u64),

    /// A payment would have created a negative balance.
    #[error("insufficient funds for operation")]
    InsufficientFunds,
}

/// Trait synonym for a cryptographically secure random number generator.
pub trait Rng: rand::CryptoRng + rand::RngCore {}
impl<T: rand::CryptoRng + rand::RngCore> Rng for T {}

/// The result of a verification of some property.
#[derive(Debug, Clone, Copy)]
#[must_use = "the result of a verification should always be checked"]
pub enum Verification {
    /// A verification succeeded.
    Verified,
    /// A verification failed.
    Failed,
}

impl From<bool> for Verification {
    fn from(b: bool) -> Self {
        match b {
            true => Verification::Verified,
            false => Verification::Failed,
        }
    }
}

impl BitAnd for Verification {
    type Output = Self;

    fn bitand(self, rhs: Self) -> Self::Output {
        match (self, rhs) {
            (Verification::Verified, Verification::Verified) => Verification::Verified,
            (_, _) => Verification::Failed,
        }
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, Eq, Ord, PartialEq, PartialOrd)]
struct Balance(u64);

impl Balance {
    fn try_new(value: u64) -> Result<Self, Error> {
        if value > i64::MAX as u64 {
            Err(Error::AmountTooLarge(value))
        } else {
            Ok(Self(value))
        }
    }

    fn zero() -> Self {
        Self(0)
    }

    fn is_zero(&self) -> bool {
        self.0 == 0
    }

    fn to_scalar(self) -> Scalar {
        Scalar::from(self.0)
    }

    /// Always returns a `u64` which is less than `i64::MAX`.
    fn into_inner(self) -> u64 {
        self.0 as u64
    }
}

/// Amount of a single payment.
#[derive(Debug, Clone, Copy, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
pub struct PaymentAmount(i64);

impl PaymentAmount {
    /// Construct a zero payment amount that does not change the balances.
    pub fn zero() -> Self {
        Self(0)
    }

    /// Construct a *positive* payment amount from the customer to the merchant.
    pub fn pay_merchant(amount: u64) -> Result<Self, Error> {
        match i64::try_from(amount) {
            Ok(i) => Ok(Self(i)),
            Err(_) => Err(Error::AmountTooLarge(amount)),
        }
    }

    /// Construct a *negative* payment amount from the merchant to the customer (i.e. a refund).
    pub fn pay_customer(amount: u64) -> Result<Self, Error> {


verview"),
    ANDROID_PLEDGE_REDEMPTION("android_pledge_redemption"),
    ANDROID_PLEDGE_OVER_TIME("android_pledge_over_time"),
    ANDROID_PLEDGED_PROJECTS_OVERVIEW_V2("android_pledged_projects_overview_v2"),
    ANDROID_SEARCH_FILTER("android_search_filter"),
    ANDROID_REWARD_SHIPMENT_TRACKING("android_reward_shipment_tracking"),
    ANDROID_COMPLETED_PM_CHECKOUT_WEBVIEW("android_completed_pm_checkout_webview"),
    ANDROID_NET_NEW_BACKER_GO_TO_PM_WEBVIEW("android_net_new_backer_go_to_pm_webview"),
    ANDROID_PLOT_EDIT_PLEDGE("android_plot_edit_pledge"),
    ANDROID_NATIVE_ONBOARDING_FLOW("android_native_onboarding_flow")
}

fun FeatureFlagClient.getFetchInterval(): Long =
    if (this.build.isDebug || isInternal()) INTERNAL_INTERVAL
    else RELEASE_INTERVAL

class FeatureFlagClient(
    internal val build: Build
) : FeatureFlagClientType {

    var remoteConfig: FirebaseRemoteConfig? = null

    override fun initialize(config: FirebaseRemoteConfig?) {
        remoteConfig = config

        val configSettings = remoteConfigSettings {
            minimumFetchIntervalInSeconds = getFetchInterval()
        }

        remoteConfig?.setConfigSettingsAsync(configSettings)

        val defaultsMap: MutableMap<String, Any> = mutableMapOf(
            Pair(FlagKey.ANDROID_NATIVE_ONBOARDING_FLOW.key, true)
        )
        remoteConfig?.setDefaultsAsync(defaultsMap)

        log("${this.javaClass} initialized with interval: ${this.getFetchInterval()}, remoteConfig ${this.remoteConfig}")
    }

    override fun fetch(context: Activity) {
        remoteConfig?.fetch()
            ?.addOnCompleteListener(context) { task ->
                log("${this.javaClass} fetch completed: ${task.isSuccessful}")
            }
    }

    override fun activate(context: Activity) {
        remoteConfig?.activate()
            ?.addOnCompleteListener(context) { task ->
                log("${this.javaClass} activate completed: ${task.isSuccessful}")

                // Strategy loading 3 -> https://firebase.google.com/docs/remote-config/loading#strategy_3_load_new_values_for_next_startup
                if (task.isSuccessful && task.isComplete) {
                    fetch(context)
                }
            }
    }

    override fun fetchAndActivate(context: Activity) {
        remoteConfig?.fetchAndActivate()
            ?.addOnCompleteListener(context) { task ->
                log("${this.javaClass} fetchAndActivated completed: ${task.isSuccessful} ")
            }
    }

    override fun getBoolean(key: FlagKey): Boolean {
        val value = remoteConfig?.getBoolean(key.key) ?: false
        log("${this.javaClass} feature flag ${key.key}: $value")
        return value
    }

    override fun getDouble(key: FlagKey): Double {
        val value = remoteConfig?.getDouble(key.key) ?: 0.0
        log("${this.javaClass} feature flag ${key.key}: $value")
        return value
    }

    override fun getLong(key: FlagKey): Long {
        val value = remoteConfig?.getLong(key.key) ?: 0L
        log("${this.javaClass} feature flag ${key.key}: $value")
        return value
    }

    override fun getString(key: FlagKey): String {

        val value = remoteConfig?.getString(key.key) ?: ""
        log("${this.javaClass} feature flag ${key.key}: $value")
        return value
    }

    private fun log(message: String) {
        if (build.isDebug) Timber.d(message)
    }

    companion object {
        const val RELEASE_INTERVAL = 3600L
        const val INTERNAL_INTERVAL = 0L


-- AUTO GENERATED. DO NOT MODIFY!
-- PayloadTable ----------------------------------------------------------------
local Loader = {}

function Loader.declareType()
    ffi.cdef [[
        typedef struct PayloadTable {} PayloadTable;
    ]]

    return 1, 'PayloadTable'
end

function Loader.defineType()
    local ffi = require('ffi')
    local libphx = require('libphx').lib
    local PayloadTable

    do -- C Definitions
        ffi.cdef [[
            void           PayloadTable_Free             (PayloadTable*);
            PayloadTable*  PayloadTable_Create           ();
            uint64         PayloadTable_Len              (PayloadTable const*);
            bool           PayloadTable_IsEmpty          (PayloadTable const*);
            bool           PayloadTable_Contains         (PayloadTable const*, cstr name);
            cstr           PayloadTable_GetName          (PayloadTable const*, uint64 index);
            Payload const* PayloadTable_GetPayload       (PayloadTable const*, uint64 index);
            Payload const* PayloadTable_GetPayloadByName (PayloadTable const*, cstr name);
            void           PayloadTable_Add              (PayloadTable*, cstr name, Payload* value);
        ]]
    end

    do -- Global Symbol Table


tDescription> ::std::fmt::Display for VertexBuffer<T> {
    fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
        write!(f,
            "VertexBuffer {{ buffer: {} (length: {}) }})",
            self.vertex_buffer_id, self.vertex_buffer_len
        )
    }
}

impl_traits_for_gl_object!(VertexBuffer<T: VertexLayoutDescription>, vertex_buffer_id);

impl<T: VertexLayoutDescription> Drop for VertexBuffer<T> {
    fn drop(&mut self) {
        self.gl_context.delete_buffers(&[self.vertex_buffer_id, self.index_buffer_id]);
    }
}

impl<T: VertexLayoutDescription> VertexBuffer<T> {
    pub fn new(shader: &GlShader, vertices: &[T], indices: &[u32], index_buffer_format: IndexBufferFormat) -> Self {

        use std::mem;

        let gl_context = shader.gl_context.clone();

        // Save the OpenGL state
        let mut current_vertex_array = [0_i32];
        let mut current_vertex_buffer = [0_i32];
        let mut current_index_buffer = [0_i32];

        unsafe { gl_context.get_integer_v(gl::VERTEX_ARRAY, &mut current_vertex_array) };
        unsafe { gl_context.get_integer_v(gl::ARRAY_BUFFER, &mut current_vertex_buffer) };
        unsafe { gl_context.get_integer_v(gl::ELEMENT_ARRAY_BUFFER, &mut current_index_buffer) };

        let vertex_array_object = gl_context.gen_vertex_arrays(1);
        let vertex_array_object = vertex_array_object[0];

        let vertex_buffer_id = gl_context.gen_buffers(1);
        let vertex_buffer_id = vertex_buffer_id[0];

        let index_buffer_id = gl_context.gen_buffers(1);
        let index_buffer_id = index_buffer_id[0];

        gl_context.bind_vertex_array(vertex_array_object);

        // Upload vertex data to GPU
        gl_context.bind_buffer(gl::ARRAY_BUFFER, vertex_buffer_id);
        gl_context.buffer_data_untyped(
            gl::ARRAY_BUFFER,
            (mem::size_of::<T>() * vertices.len()) as isize,
            vertices.as_ptr() as *const c_void,
            gl::STATIC_DRAW
        );

        // Generate the index buffer + upload data
        gl_context.bind_buffer(gl::ELEMENT_ARRAY_BUFFER, index_buffer_id);
        gl_context.buffer_data_untyped(
            gl::ELEMENT_ARRAY_BUFFER,
            (mem::size_of::<u32>() * indices.len()) as isize,
            indices.as_ptr() as *const c_void,
            gl::STATIC_DRAW
        );

        let vertex_description = T::get_description();
        vertex_description.bind(shader);

        // Reset the OpenGL state
        gl_context.bind_buffer(gl::ARRAY_BUFFER, current_vertex_buffer[0] as u32);
        gl_context.bind_buffer(gl::ELEMENT_ARRAY_BUFFER, current_index_buffer[0] as u32);
        gl_context.bind_vertex_array(current_vertex_array[0] as u32);

        Self {
            vertex_buffer_id,
            vertex_buffer_len: vertices.len(),
            gl_context: gl_context.clone(),
            vao: VertexArrayObject {
                vertex_layout: vertex_description,
                vao_id: vertex_array_object,
                gl_context,
            },
            vertex_buffer_type: PhantomData,
            index_buffer_id,
            index_buffer_len: indices.len(),
            index_buffer_format,
        }
    }
}

#[derive(Debug,


1.1.2.3.cmml" xref="A1.E3.m1.3.3.1.1.1.2.3">𝑁</ci></apply><apply id="A1.E3.m1.3.3.1.1.1.1.cmml" xref="A1.E3.m1.3.3.1.1.1.1"><times id="A1.E3.m1.3.3.1.1.1.1.2.cmml" xref="A1.E3.m1.3.3.1.1.1.1.2"></times><apply id="A1.E3.m1.3.3.1.1.1.1.3.cmml" xref="A1.E3.m1.3.3.1.1.1.1.3"><ci id="A1.E3.m1.3.3.1.1.1.1.3.1.cmml" xref="A1.E3.m1.3.3.1.1.1.1.3.1">⋅</ci><apply id="A1.E3.m1.3.3.1.1.1.1.3.2.cmml" xref="A1.E3.m1.3.3.1.1.1.1.3.2"><csymbol cd="ambiguous" id="A1.E3.m1.3.3.1.1.1.1.3.2.1.cmml" xref="A1.E3.m1.3.3.1.1.1.1.3.2">subscript</csymbol><ci id="A1.E3.m1.3.3.1.1.1.1.3.2.2.cmml" xref="A1.E3.m1.3.3.1.1.1.1.3.2.2">𝑎</ci><ci id="A1.E3.m1.3.3.1.1.1.1.3.2.3.cmml" xref="A1.E3.m1.3.3.1.1.1.1.3.2.3">𝑖</ci></apply><ci id="A1.E3.m1.3.3.1.1.1.1.3.3.cmml" xref="A1.E3.m1.3.3.1.1.1.1.3.3">𝑚</ci></apply><apply id="A1.E3.m1.3.3.1.1.1.1.1.1.1.cmml" xref="A1.E3.m1.3.3.1.1.1.1.1.1"><csymbol cd="ambiguous" id="A1.E3.m1.3.3.1.1.1.1.1.1.1.1.cmml" xref="A1.E3.m1.3.3.1.1.1.1.1.1">subscript</csymbol><ci id="A1.E3.m1.3.3.1.1.1.1.1.1.1.2.cmml" xref="A1.E3.m1.3.3.1.1.1.1.1.1.1.2">𝑆</ci><ci id="A1.E3.m1.3.3.1.1.1.1.1.1.1.3.cmml" xref="A1.E3.m1.3.3.1.1.1.1.1.1.1.3">𝑖</ci></apply></apply></apply></apply></apply></annotation-xml><annotation encoding="application/x-tex" id="A1.E3.m1.3c">\displaystyle\int s\ \mathrm{d}m=\int s(\bm{x})\ \mathrm{d}m(\bm{x})=\sum_{i=1%
}^{N}a_{i}\cdot m(S_{i}).</annotation><annotation encoding="application/x-llamapun" id="A1.E3.m1.3d">∫ italic_s roman_d italic_m = ∫ italic_s ( bold_italic_x ) roman_d italic_m ( bold_italic_x ) = ∑ start_POSTSUBSCRIPT italic_i = 1 end_POSTSUBSCRIPT start_POSTSUPERSCRIPT italic_N end_POSTSUPERSCRIPT italic_a st


  font-weight: normal;
}
.ec-AddAddress .ec-AddAddress__selectAddress select {
  min-width: 100%;
}
.ec-AddAddress .ec-AddAddress__selectNumber {
  display: block;
}
.ec-AddAddress .ec-AddAddress__selectNumber label {
  font-size: 16px;
  font-weight: normal;
}
.ec-AddAddress .ec-AddAddress__selectNumber input {
  display: inline-block;
  margin-left: 10px;
  width: 80px;
}
.ec-AddAddress .ec-AddAddress__actions .ec-blockBtn--action {
  margin-bottom: 8px;
}
.ec-AddAddress .ec-AddAddress__new {
  margin-bottom: 20px;
}
/**
メディアクエリ
SP フォーストで記述する。
Twitter Bootstrap デフォルト準拠
 */
/**
 * ECCUBE 固有のスタイルユーティリティ
 */
/*
注文履歴一覧

マイページ 注文履歴部に関する Project コンポーネントを定義します。

ex [マイページ　注文履歴一覧](http://demo3.ec-cube.net/mypage)
(要ログイン)

Markup:
include /assets/tmpl/elements/16.1.history.pug
+ec-historyRole

Styleguide 16.1
*/
.ec-historyRole .ec-historyRole__contents {
  padding-top: 1em;
  padding-bottom: 16px;
  border-top: 1px solid #ccc;
  display: flex;
  flex-direction: column;
  color: #525263;
}
.ec-historyRole .ec-historyRole__header {
  width: 100%;
}
.ec-historyRole .ec-historyRole__detail {
  border-top: 1px dotted #ccc;
  width: 100%;
}
.ec-historyRole .ec-historyRole__detail .ec-imageGrid:nth-of-type(1) {
  border-top: none;
}
.ec-historyRole .ec-historyRole__detail .ec-historyRole__detailTitle {
  margin-bottom: 8px;
  font-size: 1rem;
  font-weight: bold;
}
.ec-historyRole .ec-historyRole__detail .ec-historyRole__detailPrice {
  margin-bottom: 8px;
  font-size: 1rem;
  font-weight: bold;
}
/*
注文履歴一覧 規格

マイページ 注文履歴内アイテムの規格を定義します。

ex [マイページ　注文履歴一覧](http://demo3.ec-cube.net/mypage)
(要ログイン)

Markup:
include /assets/tmpl/elements/16.1.history.pug
+ec-historyRole-option

Styleguide 16.1.1
*/
.ec-historyRole .ec-historyRole__detail .ec-historyRole__detailOption {
  display: inline-block;
  margin-bottom: 8px;
  margin-right: 0.5rem;
  font-size: 1.6rem;
}
.ec-historyRole .ec-historyRole__detail .ec-historyRole__detailOption::after {
  display: inline-block;
  padding-left: 0.5rem;
  content: "/";
  font-weight: bold;
}
/*
注文履歴一覧ヘッダ

注文履歴一覧で使用するヘッダのコンポーネントを定義します。

ex [マイページ　注文履歴一覧ヘ


//# tAipsIOCarray.h: This program tests the AipsIOCarray functions
//# Copyright (C) 1996
//# Associated Universities, Inc. Washington DC, USA.
//#
//# 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, write to the Free Software Foundation, Inc.,
//# 675 Massachusetts Ave, Cambridge, MA 02139, USA.
//#
//# Correspondence concerning AIPS++ should be addressed as follows:
//#        Internet email: casa-feedback@nrao.edu.
//#        Postal address: AIPS++ Project Office
//#                        National Radio Astronomy Observatory
//#                        520 Edgemont Road
//#                        Charlottesville, VA 22903-2475 USA

#ifndef CASA_TAIPSIOCARRAY_H
#define CASA_TAIPSIOCARRAY_H

//# Includes
#include <casacore/casa/IO/AipsIOCarray.h>

#include <casacore/casa/namespace.h>
// <summary>
// Example class for use in AipsIOCarray functions
// </summary>

// <use visibility=local>

// <reviewed reviewer="Gareth Hunt" date="95Feb24" tests="" demos="">
// </reviewed>

// <prerequisite>
//# Classes you should understand before using this one.
//   <li> AipsIOCarray
// </prerequisite>

// <synopsis>
// Make a class AipsIOCarrayEx1 to construct an array of non-standard objects
// to be used with AipsIOCarray functions.
// </synopsis>

// This file defines an example class used in tAipsIOCarray.cc

class AipsIOCarrayEx1
{
public:
    AipsIOCarrayEx1() : a_p(0), b_p(0) {;}
    AipsIOCarrayEx1 (Int a, double b) : a_p(a), b_p(b) {;}
    friend AipsIO& operator<< (AipsIO& ios, const AipsIOCarrayEx1& a)
	{ return ios << a.a_p << a.b_p; }
    friend AipsIO& operator>> (AipsIO& ios, AipsIOCarrayEx1& a)
	{ return ios >> a.a_p >> a.b_p; }
    Int a() const {return a_p;}
    double b() const {return b_p;}
private:
    Int a_p;
    double b_p;
};

#endif


/* Copyright (c) 2009, 2010, 2011, 2012 ARM Ltd.
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.  */

#define LIBFFI_ASM
#include <fficonfig.h>
#include <ffi.h>
#include <ffi_cfi.h>
#include "internal.h"

	OPT	2 /*disable listing */
/* For some macros to add unwind information */
#include "ksarm64.h"
	OPT	1 /*re-enable listing */

#define BE(X)	0
#define PTR_REG(n)      x##n
#define PTR_SIZE	8

	IMPORT ffi_closure_SYSV_inner
	EXPORT	ffi_call_SYSV
	EXPORT	ffi_closure_SYSV_V
	EXPORT	ffi_closure_SYSV
	EXPORT	extend_hfa_type
	EXPORT	compress_hfa_type
#ifdef FFI_GO_CLOSURES
	EXPORT	ffi_go_closure_SYSV_V
	EXPORT	ffi_go_closure_SYSV
#endif

	TEXTAREA, ALIGN=8

/* ffi_call_SYSV
   extern void ffi_call_SYSV (void *stack, void *frame,
			      void (*fn)(void), void *rvalue,
			      int flags, void *closure);
   Therefore on entry we have:
   x0 stack
   x1 frame
   x2 fn
   x3 rvalue
   x4 flags
   x5 closure
*/

	NESTED_ENTRY ffi_call_SYSV_fake

	/* For unwind information, Windows has to store fp and lr  */
	PROLOG_SAVE_REG_PAIR	x29, x30, #-32!

	ALTERNATE_ENTRY ffi_call_SYSV
	/* Use a stack frame allocated by our caller. */
	stp	x29, x30, [x1]
	mov	x29, x1
	mov	sp, x0

	mov	x9, x2			/* save fn */
	mov	x8, x3			/* install structure return */
#ifdef FFI_GO_CLOSURES
	/*mov	x18, x5			install static chain */
#endif
	stp	x3, x4, [x29, #16]	/* save rvalue an


/* CpuArch.c -- CPU specific code
2010-10-26: Igor Pavlov : Public domain */

#include "CpuArch.h"

#ifdef MY_CPU_X86_OR_AMD64

#if (defined(_MSC_VER) && !defined(MY_CPU_AMD64)) || defined(__GNUC__)
#define USE_ASM
#endif

#if defined(USE_ASM) && !defined(MY_CPU_AMD64)
static UInt32 CheckFlag(UInt32 flag)
{
  #ifdef _MSC_VER
  __asm pushfd;
  __asm pop EAX;
  __asm mov EDX, EAX;
  __asm xor EAX, flag;
  __asm push EAX;
  __asm popfd;
  __asm pushfd;
  __asm pop EAX;
  __asm xor EAX, EDX;
  __asm push EDX;
  __asm popfd;
  __asm and flag, EAX;
  #else
  __asm__ __volatile__ (
    "pushf\n\t"
    "pop  %%EAX\n\t"
    "movl %%EAX,%%EDX\n\t"
    "xorl %0,%%EAX\n\t"
    "push %%EAX\n\t"
    "popf\n\t"
    "pushf\n\t"
    "pop  %%EAX\n\t"
    "xorl %%EDX,%%EAX\n\t"
    "push %%EDX\n\t"
    "popf\n\t"
    "andl %%EAX, %0\n\t":
    "=c" (flag) : "c" (flag));
  #endif
  return flag;
}
#define CHECK_CPUID_IS_SUPPORTED if (CheckFlag(1 << 18) == 0 || CheckFlag(1 << 21) == 0) return False;
#else
#define CHECK_CPUID_IS_SUPPORTED
#endif

static void MyCPUID(UInt32 function, UInt32 *a, UInt32 *b, UInt32 *c, UInt32 *d)
{
  #ifdef USE_ASM

  #ifdef _MSC_VER

  UInt32 a2, b2, c2, d2;
  __asm xor EBX, EBX;
  __asm xor ECX, ECX;
  __asm xor EDX, EDX;
  __asm mov EAX, function;
  __asm cpuid;
  __asm mov a2, EAX;
  __asm mov b2, EBX;
  __asm mov c2, ECX;
  __asm mov d2, EDX;

  *a = a2;
  *b = b2;
  *c = c2;
  *d = d2;

  #else

  __asm__ __volatile__ (
    "cpuid"
    : "=a" (*a) ,
      "=b" (*b) ,
      "=c" (*c) ,
      "=d" (*d)
    : "0" (function)) ;

  #endif

  #else

  int CPUInfo[4];
  __cpuid(CPUInfo, function);
  *a = CPUInfo[0];
  *b = CPUInfo[1];
  *c = CPUInfo[2];
  *d = CPUInfo[3];

  #endif
}

Bool x86cpuid_CheckAndRead(Cx86cpuid *p)
{
  CHECK_CPUID_IS_SUPPORTED
  MyCPUID(0, &p->maxFunc, &p->vendor[0], &p->vendor[2], &p->vendor[1]);
  MyCPUID(1, &p->ver, &p->b, &p->c, &p->d);
  return True;
}

static UInt32 kVendors[][3] =
{
  { 0x756E6547, 0x49656E69, 0x6C65746E},
  { 0x68747541, 0x69746E65, 0x444D4163},
  { 0x746E6543, 0x48727561, 0x736C7561}
};

int x86cpuid_GetFirm(const Cx86cpuid *p)
{
  unsigned i;
  for (i = 0; i < sizeof(kVendors) / sizeof(kVendors[i]); i++)
  {
    const UInt32 *v = kVendors[i];
    if (v[0] == p->vendor[0] &&
        v[1] == p->vendor[1] &&
        v[2] == p->vendor[2])
      return (int)i;
  }
  return -1;
}

Bool CPU_Is_InOrder()
{
  Cx86cpuid p;
  int firm;
  UInt32 family, model;
  if (!x86cpuid_CheckAndRead(&p))
    return True;
  family = x86cpuid_GetFamily(&p);
  model = x86cpuid_GetModel(&p);
  firm = x86cpuid_GetFirm(&p);
  switch (firm)
  {
    case CPU_FIRM_INTEL: return (family < 6 || (family == 6 && model == 0x100C));
    case CPU_FIRM_AMD: return (family < 5 || (family == 5 && (model < 6 || model == 0xA)));
    case CPU_FIRM_VIA: return (family < 6 || (family == 6 && model < 0xF));
  }
  return True;
}

#if !defined(MY_CPU_AMD64) && defined(_WIN32)
static Bool CPU_Sys_Is_SSE_Supported()
{
  OSVERSIONINFO vi;
  vi.dwOSVersionInfoSize = sizeof(vi);
  if (!GetVersionEx(&vi))
    return False;
  return (vi.dwMajorVersion >= 5);
}
#define CHECK_SYS_SSE_SUPPORT if (!CPU_Sys_Is_SSE_Supported()) return False;
#else
#define CHECK_SYS_SSE_SUPPORT
#endif

Bool CPU_Is_Aes_Supported()
{
  Cx86cpuid p;
  CHECK_SYS_SSE_SUPPORT
  if (!x86cpuid_CheckAndRead(&p))
    return False;
  return (p.c >> 25) & 1;
}

#endif


				dest[++i] = b;
			}
		}

		// Array transformation
		i = -1;
		for (boolean b : src) {
			dest[++i] = transform(b);
		}

		// Simple copy
		int i = 0;
		for (boolean b : src) { // Noncompliant
			dest[i] = src[i];
			i++;
		}

		// Copy with nested conditions
		i = 0;
		for (boolean b : src) { // Noncompliant
			if(b) {
				dest[i] = src[i];
			}
			i++;
		}

		// Copy with nested ELSE conditions
		i = 0;
		for (boolean b : src) { // Noncompliant
			if(i + 2 >= len) {
				i++;
			} else {
				dest[i] = src[i + 2];
			}
			i++;
		}

		// Copy with more nested conditions
		i = 0;
		for (boolean b : src) { // Noncompliant
			if(i + 2 < len) {
				if(dest != null) {
					if(src != null) {
						if(i > 1 && i + 2 < src.length) {
							dest[i] = src[i + 2];
						}
					}
				}
			}
			i++;
		}

		// Copy nested by try/catch
		i = 0;
		for (boolean b : src) { // Noncompliant
			try {
				dest[i] = src[i];
			} catch (RuntimeException e) {
				e.printStackTrace();
			}
			i++;
		}

		// Copy nested by try/catch and if
		i = 0;
		for (boolean b : src) { // Noncompliant
			try {
				if(dest != null) {
					dest[i] = src[i];
				}
			} catch (RuntimeException e) {
				e.printStackTrace();
			}
			i++;
		}

		// Copy nested by try/catch in catch
		i = 0;
		for (boolean b : src) { // Noncompliant
			try {
				dest.toString();
			} catch (RuntimeException e) {
				if(dest != null) {
					dest[i] = src[i];
				}
			}
			i++;
		}

		// Copy nested by try/catch in finally
		i = 0;
		for (boolean b : src) { // Noncompliant
			try {
				dest.toString();
			} catch (RuntimeException e) {
			 	e.printStackTrace();
			} finally {
				dest[i] = src[i];
			}
			i++;
		}

		// Array transformation
		i = 0;
		for (boolean b : src) {
			dest[i] = transform(src[i]);
			i++;
		}
	}

	public void copyWithWhileLoop() {
		final int len = 5;
		final boolean[] src = new boolean[len];
		boolean[] dest = new boolean[len];

		// Simple copy
		int i = 0;
		while (i < len) { // Noncompliant
			dest[i] = src[i];
			i++;
		}

		// Copy with nested conditions
		i = 0;
		while (i < len) { // Noncompliant
			if(i + 2 < len) {
				dest[i] = src[i + 2];
			}
			i++;
		}

		// Copy with nested ELSE conditions
		i = 0;
		while (i < len) { // Noncompliant
			if(i + 2 >= len) {
				i++;
			} else {
				dest[i] = src[i + 2];
			}
			i++;
		}

		// Copy with more nested conditions
		i = 0;
		while (i < len) { // Noncompliant
			if(i + 2 < len) {
				if(dest != null) {
					if(src != null) {
						if(i > 1 && i + 2 < src.length) {
							dest[i] = src[i + 2];
						}
					}
				}
			}
			i++;
		}

		// Copy nested by try/catch and


JavaScript/TypeScript VSCode extensions and the compiled languages C and C++. The goal is to understand security implications and potential vulnerabilities arising from these dependencies.

## Repository Structure

```
master-thesis
├── data                   # Results
├── extensions-benchmarks  # Benchmarking extensions used for testing
├── queries                # CodeQL queries for analysis
├── scripts                # Scripts used in the research
├── .gitignore             # Git ignored files
├── README.md              # This file
├── requirements.txt       # Python requirements
```

## Setup
### Clone the Repository
```sh
git clone git@github.com:Maltecarlstedt/vscode-dep-ext-analysis.git
cd vscode-dep-ext-analysis
```
### Install Dependencies
Ensure you have the following installed:
- [CodeQL CLI](https://github.com/github/codeql-cli-binaries)
- [Node.js](https://nodejs.org/) (multiple versions via conda)
- [Conda](https://docs.conda.io/en/latest/miniconda.html) for Node.js environment management

## Virtual Environment Setup

It's recommended to use a virtual environment to isolate the project dependencies:

#### Windows
```cmd
python -m venv venv
venv\Scripts\activate
```

### macOS/Linux
```cmd
python3 -m venv venv
source venv/bin/activate
```

### Environment Configuration
Create a `.env` file with the following variables:
```bash
GITHUB_TOKEN=your_github_token
GITHUB_TOKEN_SECOND=optional_second_token
FETCH_WORKING_DIR=/path/to/working/directory
MAX_WORKERS=4
EXPORT_DIR=extension_trees
```

# Required for building C/C++ dependencies with different Node.js versions
```bash
conda create -n node-legacy nodejs=8.10.0 python=2.7
conda create -n node-intermediate nodejs=14.20.1 python=3.8
conda create -n node-latest nodejs=22.13.0 python=3.12
```

### Installing Requirements

After activating your virtual environment, install the required dependencies using:
```cmd
pip install -r requirements.txt
```

## Usage

This analysis follows a 5-stage pipeline:

### Stage 1: Extension Scraping
```bash
cd scripts/1_scraping
python scrape_extensions.py
```

### Stage 2: Extension Dependency Tree Construction
```bash
cd scripts/2_discover_construct_tree
python discover_construct_dependency_trees.py
```

### Stage 3: Source Code & Database Generation
```bash
cd scripts/3_clone_dependencies_generate_codeql_db
python clone_dependencies.py
python generate_codeql_db.py --dependencies-dir /path/to/deps
```

### Stage 4: Vulnerability Analysis
```bash
cd scripts/4_vulnerability_scanning
python run_analysis.py /path/to/databases
```

### Stage 5: Vulnerability Propagation
```bash
cd scripts/5_vulnerability_propagation_analysis
python vulnerability_propagation_analysis.py --vuln-csv results.csv --ext-dirs extension_trees
```

### Output Structure
```markdown
- `extension_trees/` - JSON dependency trees for each extension
- `vulnerability_results/` - CSV reports of detected vulnerabilities
- `vulnerability_propagation_reports/` - Impact analysis per extension
- `dependency_analytics.json` - Ecosystem statistics
- `build_logs/` - CodeQL database build logs
- Various error reports and progress files
```


## 000002D0
/* 0C060 80944D30 000D7080 */  sll     $t6, $t5,  2
/* 0C064 80944D34 3C0BDE00 */  lui     $t3, 0xDE00                ## $t3 = DE000000
/* 0C068 80944D38 3C0F8016 */  lui     $t7, 0x8016                ## $t7 = 80160000
/* 0C06C 80944D3C 01EE7821 */  addu    $t7, $t7, $t6
/* 0C070 80944D40 3C0100FF */  lui     $at, 0x00FF                ## $at = 00FF0000
/* 0C074 80944D44 AC4B0000 */  sw      $t3, 0x0000($v0)           ## 00000000
/* 0C078 80944D48 8DEF6FA8 */  lw      $t7, 0x6FA8($t7)           ## 80166FA8
/* 0C07C 80944D4C 3421FFFF */  ori     $at, $at, 0xFFFF           ## $at = 00FFFFFF
/* 0C080 80944D50 0081C024 */  and     $t8, $a0, $at
/* 0C084 80944D54 3C018000 */  lui     $at, 0x8000                ## $at = 80000000
/* 0C088 80944D58 01F8C821 */  addu    $t9, $t7, $t8
/* 0C08C 80944D5C 03214821 */  addu    $t1, $t9, $at
/* 0C090 80944D60 0C034221 */  jal     Matrix_Pull
/* 0C094 80944D64 AC490004 */  sw      $t1, 0x0004($v0)           ## 00000004
/* 0C098 80944D68 8E0202D0 */  lw      $v0, 0x02D0($s0)           ## 000002D0
/* 0C09C 80944D6C 3C0BDB06 */  lui     $t3, 0xDB06                ## $t3 = DB060000
/* 0C0A0 80944D70 356B0020 */  ori     $t3, $t3, 0x0020           ## $t3 = DB060020
/* 0C0A4 80944D74 244A0008 */  addiu   $t2, $v0, 0x0008           ## $t2 = 00000008
/* 0C0A8 80944D78 AE0A02D0 */  sw      $t2, 0x02D0($s0)           ## 000002D0
/* 0C0AC 80944D7C 3C0D8095 */  lui     $t5, %hi(D_8094C848)       ## $t5 = 80950000
/* 0C0B0 80944D80 AC4B0000 */  sw      $t3, 0x0000($v0)           ## 00000000
/* 0C0B4 80944D84 8DADC848 */  lw      $t5, %lo(D_8094C848)($t5)
/* 0C0B8 80944D88 8FAC008C */  lw      $t4, 0x008C($sp)
/* 0C0BC 80944D8C 240E0020 */  addiu   $t6, $zero, 0x0020         ## $t6 = 00000020
/* 0C0C0 80944D90 85A60150 */  lh      $a2, 0x0150($t5)           ## 80950150
/* 0C0C4 80944D94 8D840000 */  lw      $a0, 0x0000($t4)           ## 00000000
/* 0C0C8 80944D98 240F0020 */  addiu   $t7, $zero, 0x0020         ## $t7 = 00000020
/* 0C0CC 80944D9C 00063023 */  subu    $a2, $zero, $a2