UF.PostUpdateAddPower
	self.AdditionalPower.displayPairs = {
		["DRUID"] = {
			[1] = true,
			[3] = true,
			[8] = true,
		},
		["SHAMAN"] = {
			[11] = true,
		},
		["PRIEST"] = {
			[13] = true,
		}
	}
end

function UF:ToggleAddPower()
	local frame = _G.oUF_Player
	if not frame then return end

	if C.db["UFs"]["AddPower"] then
		if not frame:IsElementEnabled("AdditionalPower") then
			frame:EnableElement("AdditionalPower")
			frame.AdditionalPower:ForceUpdate()
		end
	elseif frame:IsElementEnabled("AdditionalPower") then
		frame:DisableElement("AdditionalPower")
	end
end

function UF:ToggleSwingBars()
	local frame = _G.oUF_Player
	if not frame then return end

	if C.db["UFs"]["SwingBar"] then
		if not frame:IsElementEnabled("Swing") then
			frame:EnableElement("Swing")
		end
	elseif frame:IsElementEnabled("Swing") then
		frame:DisableElement("Swing")
	end
end

function UF:CreateSwing(self)
	local width, height = C.db["UFs"]["SwingWidth"], C.db["UFs"]["SwingHeight"]

	local bar = CreateFrame("Frame", nil, self)
	bar:SetSize(width, height)
	bar.mover = B.Mover(bar, L["UFs SwingBar"], "Swing", {"BOTTOM", UIParent, "BOTTOM", 0, 170})
	bar:ClearAllPoints()
	bar:SetPoint("CENTER", bar.mover)

	local two = CreateFrame("StatusBar", nil, bar)
	two:Hide()
	two:SetAllPoints()
	B.CreateSB(two, true, .8, .8, .8)

	local main = CreateFrame("StatusBar", nil, bar)
	main:Hide()
	main:SetAllPoints()
	B.CreateSB(main, true, .8, .8, .8)

	local off = CreateFrame("StatusBar", nil, bar)
	off:Hide()
	if C.db["UFs"]["OffOnTop"] then
		off:SetPoint("BOTTOMLEFT", bar, "TOPLEFT", 0, 3)
		off:SetPoint("BOTTOMRIGHT", bar, "TOPRIGHT", 0, 3)
	else
		off:SetPoint("TOPLEFT", bar, "BOTTOMLEFT", 0, -3)
		off:SetPoint("TOPRIGHT", bar, "BOTTOMRIGHT", 0, -3)
	end
	off:SetHeight(height)
	B.CreateSB(off, true, .8, .8, .8)

	bar.Text = B.CreateFS(bar, 12, "")
	bar.Text:SetShown(C.db["UFs"]["SwingTimer"])
	bar.TextMH = B.CreateFS(main, 12, "")
	bar.TextMH:SetShown(C.db["UFs"]["SwingTimer"])
	bar.TextOH = B.CreateFS(off, 12, "")
	bar.TextOH:SetShown(C.db["UFs"]["SwingTimer"])

	self.Swing = bar
	self.Swing.Twohand = two
	self.Swing.Mainhand = main
	self.Swing.Offhand = off
	self.Swing.hideOoc = true
end

local scrolls = {}
function UF:UpdateScrollingFont()
	local fontSize = C.db["UFs"]["FCTFontSize"]
	for _, scroll in pairs(scrolls) do
		B.SetFontSize(scroll, fontSize)
		scroll:SetSize(10*fontSize, 10*fontSize)
	end
end

function UF:CreateFCT(self)
	if not C.db["UFs"]["CombatText"] then return end

	local parentFrame = CreateFrame("Frame", nil, UIParent)
	local parentName = self:GetName()
	local


		{
			yyVAL.expr = &Expr{Position: yyDollar[1].pos.Position, Kind: ExprUnop, Op: "!", Left: yyDollar[2].expr}
		}
	case 104:
		yyDollar = yyS[yypt-2 : yypt+1]
//line reflow.y:553
		{
			yyVAL.expr = &Expr{Position: yyDollar[1].pos.Position, Kind: ExprUnop, Op: "-", Left: yyDollar[2].expr}
		}
	case 105:
		yyDollar = yyS[yypt-2 : yypt+1]
//line reflow.y:557
		{
			yyVAL.expr = &Expr{Position: yyDollar[1].pos.Position, Kind: ExprBlock, Left: yyDollar[2].expr}
		}
	case 106:
		yyDollar = yyS[yypt-5 : yypt+1]
//line reflow.y:559
		{
			yyVAL.expr = &Expr{Position: yyDollar[1].pos.Position, Kind: ExprCond, Cond: yyDollar[3].expr, Left: yyDollar[4].expr, Right: yyDollar[5].expr}
		}
	case 109:
		yyDollar = yyS[yypt-1 : yypt+1]
//line reflow.y:566
		{
			yyVAL.expr = &Expr{Position: yyDollar[1].pos.Position, Kind: ExprIdent, Ident: "file"}
		}
	case 110:
		yyDollar = yyS[yypt-1 : yypt+1]
//line reflow.y:568
		{
			yyVAL.expr = &Expr{Position: yyDollar[1].pos.Position, Comment: yyDollar[1].pos.comment, Kind: ExprIdent, Ident: "dir"}
		}
	case 111:
		yyDollar = yyS[yypt-6 : yypt+1]
//line reflow.y:570
		{
			yyVAL.expr = &Expr{Position: yyDollar[1].pos.Position, Comment: yyDollar[1].pos.comment, Kind: ExprFunc, Args: yyDollar[3].typfields, Left: yyDollar[6].expr}
		}
	case 112:
		yyDollar = yyS[yypt-7 : yypt+1]
//line reflow.y:572
		{
			yyVAL.expr = &Expr{Position: yyDollar[1].pos.Position, Comment: yyDollar[1].pos.comment, Kind: ExprAscribe, Type: yyDollar[5].typ, Left: &Expr{
				Position: yyDollar[7].expr.Position, Kind: ExprFunc, Args: yyDollar[3].typfields, Left: yyDollar[7].expr}}
		}
	case 113:
		yyDollar = yyS[yypt-6 : yypt+1]
//line reflow.y:575
		{
			yyVAL.expr = &Expr{Position: yyDollar[1].pos.Position, Comment: yyDollar[1].pos.comment, Kind: ExprExec, Decls: yyDollar[3].decllist, Type: yyDollar[5].typ, Template: yyDollar[6].template}
		}
	case 114:
		yyDollar = yyS[yypt-4 : yypt+1]
//line reflow.y:577
		{
			yyVAL.expr = &Expr{Position: yyDollar[1].pos.Position, Comment: yyDollar[1].pos.comment, Kind: ExprMake, Left: yyDollar[3].expr}
		}
	case 115:
		yyDollar = yyS[yypt-7 : yypt+1]
//line reflow.y:579
		{
			yyVAL.expr = &Expr{Position: yyDollar[1].pos.Position, Comment: yyDollar[1].


apply {
            toastEvent.observe { str ->
                str?.let {
                    CyxbsToast.makeText(
                        baseContext,
                        it,
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
            longToastEvent.observe { str ->
                str?.let {
                    CyxbsToast.makeText(
                        baseContext,
                        it,
                        Toast.LENGTH_LONG
                    ).show()
                }
            }
            progressDialogEvent.observe {
                it ?: return@observe
                //确保只有一个对话框会被弹出
                if (it != ProgressDialogEvent.DISMISS_DIALOG_EVENT && progressDialog?.isShowing != true) {
                    progressDialog = progressDialog ?: initProgressBar()
                    if (it == ProgressDialogEvent.SHOW_NONCANCELABLE_DIALOG_EVENT) progressDialog?.setCancelable(
                        false
                    )
                    progressDialog?.show()
                } else if (it == ProgressDialogEvent.DISMISS_DIALOG_EVENT && progressDialog?.isShowing != false) {
                    progressDialog?.dismiss()
                }
            }
        }
    }

    protected open fun getViewModelFactory(): ViewModelProvider.Factory? = null

    inline fun <T> LiveData<T>.observe(crossinline onChange: (T) -> Unit) =
        observe(this@BaseViewModelActivity) { onChange(it) }

    override fun onDestroy() {
        super.onDestroy()
        if (progressDialog?.isShowing == true) {
            progressDialog?.dismiss()
        }
    }

}package com.mredrock.cyxbs.common.network.exception

import com.mredrock.cyxbs.common.BuildConfig
import com.mredrock.cyxbs.common.utils.LogUtils
import com.mredrock.cyxbs.common.utils.extensions.toast
import retrofit2.HttpException
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException

/**
 * 只处理简单的网络异常及账号密码错误
 * Created By jay68 on 2018/8/12.
 */
@Deprecated("检测状态已过时，请不要再使用")
object DefaultErrorHandler : ErrorHandler {
    override fun handle(e: Throwable?): Boolean {
        when {
            e == null -> toast(
                if (BuildConfig.DEBUG) throw NullPointerException("throwable must be not null") else "未知错误"
            )
            e is SocketTimeoutException || e is ConnectException || e is UnknownHostException -> toast(
                if (BuildConfig.DEBUG) e.toString() else "网络中断，请检查您的网络状态"
            )
            e is HttpException -> toast(
                if (BuildConfig.DEBUG) e.response()?.raw().toString() else "此服务暂时不可用"
            )

            e is RedrockApiIllegalStateException -> toast("数据异常，请稍后再试")

            e.message.equals("authentication error") -> toast("登录失败：学号或者密码错


embedded culture of achievement and communication to continually exceed customer expectations. Our engineers are among the best in the IT industry with an unparalleled knowledge of hardware and software that is built on our partner certification programs and our in-house training ground of more than 25,000 pieces of IT equipment. This means our engineers don’t train on your job.

Patrick Hiller and Ken Snuggs co-founded Abacus in 2000 with the goal of providing IT products and services from an ethical company that truly represents their clients' best interests. We've cultivated partnerships with dozens of key hardware, software and solutions providers to ensure that our recommendations are always vendor neutral. We also believe in taking care of our own employees with the same level of care and integrity. We hire quality people who share our client focus, and we provide a work environment that makes them want to stay. Our low turnover means our clients develop long-term relationships with their Solution Teams. It’s all part of the Abacus Approach to doing business. Because we get IT.

The Abacus Approach

Success makes everyone look good. Our goal is to make hiring Abacus look like the best business decision you’ve ever made. If there is a block in the road, we’ll find a way around it. Are your people overtaxed? We'll take on more of their responsibilities. Looking to get your folks more hands-on? We'll train them and offer guidance.

The reason we can say failure is not an option is because we don't make vague promises. We tailor everything to your particular IT challenges and we bring in our service engineers early in the process to determine a solution and set realistic timeframes. By the way, our service engineers and warehouse staff are pretty much rock stars. Check out a few of them that really do rock the house here. They have an in-house advantage of our huge inventory of the latest and greatest equipment to take apart, analyze, and configure to each client's specific requirements.

Not everyone at Abacus is an engineer or a rock star, but the rest of us are good at what we do, too. We designed the Abacus culture to encourage frequent communication and company-wide ownership of our customers' satisfaction. We are direct, professional, and easy to work with because we love what we do. We know that we are the best at helping our clients improve their IT functions and their bottom-line.

You want the short version? We get IT. We’ve got your back, your bottom-line, and your best interests covered.

<div class="DnnModule-DNN_HTML


ashmap::DashMap;

    lazy_static! {
        static ref TRACKING: DashMap<String, Instant> = DashMap::new();
    }

    let now = Instant::now();
    let duration = match TRACKING.get(name) {
        Some(time) => now.duration_since(*time),
        None => Duration::from_millis(0),
    };

    TRACKING.insert(name.to_owned(), now);

    duration
}

pub fn init_logger() {
    let console = fern::Dispatch::new()
        .format(console_format)
        .level(LevelFilter::Info)
        .level_for("tomoka_rs", LevelFilter::Trace)
        .level_for("tracing", LevelFilter::Error)
        .level_for("serenity", LevelFilter::Error)
        .filter(|meta| meta.level() > LevelFilter::Warn)
        .chain(io::stdout());

    let err_console = fern::Dispatch::new()
        .format(console_format)
        .level(LevelFilter::Warn)
        .chain(io::stderr());

    let file = fern::Dispatch::new()
        .format(file_format)
        .level(LevelFilter::Warn)
        //.level_for("serenity", LevelFilter::Trace)
        .level_for("tomoka_rs", LevelFilter::Debug)
        .chain(fern::DateBased::new("logs/", "tomo-%F.log"));

    fern::Dispatch::new()
        .chain(file)
        .chain(console)
        .chain(err_console)
        .apply()
        .unwrap();
}

fn console_format(cb: fern::FormatCallback, message: &Arguments, record: &Record) {
    let mut name = record.target().to_owned();

    if let Some(line) = record.line() {
        name.push_str(&format!(":{}", line));
    }

    let duration = get_time_and_update(&name);

    cb.finish(format_args!(
        "{}{} {}{} {} ({}ms)",
        "[".dark_gray(),
        level_style(record.level()),
        name,
        "]".dark_gray(),
        message,
        duration.as_millis(),
    ))
}

fn file_format(cb: fern::FormatCallback, message: &Arguments, record: &Record) {
    let line = record.line().map(|v| format!(":{}", v));

    cb.finish(format_args!(
        "{} {:<5} {}{} {}",
        chrono::Local::now().format("%T%.3f"),
        record.level(),
        record.target(),
        line.unwrap_or_default(),
        message,
    ))
}

fn level_style(level: Level) -> CString {
    match level {
        Level::Trace => "TRACE".dark_gray(),
        Level::Debug => "DEBUG".white(),
        Level::Info => "INFO".green(),
        Level::Warn => "WARN".yellow(),
        Level::Error => "ERROR".red().bold(),
    }
}use rand::seq::SliceRandom;

pub struct Garapon<T> {
    balls: Vec<T>,
}

impl<T> Garapon<T> {
    pub fn new() -> Garapon<T> {
        Garapon { balls: vec![] }
    }

    pub fn push(&mut self, v: T) {
        self.balls.push(v);
    }
}

impl<T> Iterator for Garapon<T> {
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        // NOTE: ガラポンって毎回シャッフルされるじゃん？そのシャッフル
        let mut rng = rand::thread_rng();
        self.balls.shuffle(&mut rng);

        return self.balls.pop();
    }
}
//! Contains test cases which cover ZG-CONFORMANCE-018
//!
//! The node responds to `GetData` requests with the appropriate transaction or block as requested by


 p[i]
        if (coeff == 0.0) continue
        print (when {
            coeff ==  1.0  -> if (i < pd) " + " else ""
            coeff == -1.0  -> if (i < pd) " - " else "-"
            coeff <   0.0  -> if (i < pd) " - ${-coeff}" else "$coeff"
            else           -> if (i < pd) " + $coeff" else "$coeff"
        })
        if (i > 1) print("x^$i")
        else if (i == 1) print("x")
    }
    println()
}

fun main(args: Array<String>) {
    val n = doubleArrayOf(-42.0, 0.0, -12.0, 1.0)
    val d = doubleArrayOf( -3.0, 1.0,   0.0, 0.0)
    print("Numerator   : ")
    polyShow(n)
    print("Denominator : ")
    polyShow(d)
    println("-------------------------------------")
    val (q, r) = polyLongDiv(n, d)
    print("Quotient    : ")
    polyShow(q)
    print("Remainder   : ")
    polyShow(r)
}
typealias matrix = MutableList<MutableList<Int>>

fun printSquare(latin: matrix) {
    for (row in latin) {
        println(row)
    }
    println()
}

fun latinSquare(n: Int) {
    if (n <= 0) {
        println("[]")
        return
    }

    val latin = MutableList(n) { MutableList(n) { it } }
    // first row
    latin[0].shuffle()

    // middle row(s)
    for (i in 1 until n - 1) {
        var shuffled = false
        shuffling@
        while (!shuffled) {
            latin[i].shuffle()
            for (k in 0 until i) {
                for (j in 0 until n) {
                    if (latin[k][j] == latin[i][j]) {
                        continue@shuffling
                    }
                }
            }
            shuffled = true
        }
    }

    // last row
    for (j in 0 until n) {
        val used = MutableList(n) { false }
        for (i in 0 until n - 1) {
            used[latin[i][j]] = true
        }
        for (k in 0 until n) {
            if (!used[k]) {
                latin[n - 1][j] = k
                break
            }
        }
    }

    printSquare(latin)
}

fun main() {
    latinSquare(5)
    latinSquare(5)
    latinSquare(10) // for good measure
}
// version 1.1.3

object Perlin {

    private val permutation = intArrayOf(
        151, 160, 137,  91,  90,  15, 131,  13, 201,  95,  96,  53, 194, 233,   7, 225,
        140,  36, 103,  30,  69, 142,   8,  99,  37, 240,  21,  10,  23, 190,   6, 148,
        247, 120, 234,  75,   0,  26, 197,  62,  94, 252, 219, 203, 117,  35,  11,  32,
         57, 177,  33,  88, 237, 149,  56,  87, 174,  20, 125, 136, 171, 168,  68, 175,
         74, 165,  71, 134, 139,  48,  27, 166,  77, 146, 158, 231,  83, 111, 229, 122,
         60, 211, 133, 230, 220, 105,  92,  41,  55,  46, 245,  40, 244, 102, 143,  54,
         65,  25,  63, 161,   1, 216,  80,  73, 209,  76, 132, 187, 208,  89,  18, 169,
        200, 196, 135, 130, 116, 188


,
		subject_extra = "",
		extra_service = 3,
		money = 2999,
		tag = 1,
		gem = 0,
		limit_type = 2,
		picture = "fudai61",
		id_str = "com.yostaren.azurlane.diamond133",
		first_pay_double = 0,
		extra_gem = 0,
		id = 123,
		airijp_id = "com.yostaren.azurlane.diamond133",
		extra_service_item = {
			{
				2,
				69961,
				1
			},
			{
				1,
				4,
				2020
			},
			{
				2,
				15008,
				50
			},
			{
				2,
				20001,
				20
			},
			{
				2,
				15003,
				10
			},
			{
				1,
				6,
				100
			}
		},
		time = {
			{
				{
					2020,
					4,
					23
				},
				{
					0,
					0,
					0
				}
			},
			{
				{
					2020,
					5,
					6
				},
				{
					23,
					59,
					59
				}
			}
		},
		display = {
			{
				2,
				69961,
				1
			},
			{
				1,
				4,
				2020
			},
			{
				2,
				15008,
				50
			}
		},
		sub_display = {},
		ignorePlatform = {}
	},
	[124] = {
		limit_arg = 1,
		descrip_extra = "The pack includes lots of material rewards. The Startup Pack will be sent to you via in-game mail, please check your mailbox to claim the pack. ",
		type = 1,
		name = "Night Out Lucky Bag ",
		descrip = "Contains 1 x random Ship skin, 2020 x Gems, and other rewards. ",
		subject = "Night Out Lucky Bag ",
		subject_extra = "",
		extra_service = 3,
		money = 2999,
		tag = 1,
		gem = 0,
		limit_type = 2,
		picture = "lihe1_l",
		id_str = "com.yostaren.azurlane.diamond134",
		first_pay_double = 0,
		extra_gem = 0,
		id = 124,
		airijp_id = "com.yostaren.azurlane.diamond134",
		extra_service_item = {
			{
				2,
				69910,
				1
			},
			{
				1,
				4,
				2020
			},
			{
				2,
				42017,
				2
			},
			{
				2,
				15008,
				50
			},
			{
				2,
				20001,
				20
			},
			{
				2,
				15003,
				10
			},
			{
				1,
				6,
				100
			}
		},
		time = {
			{
				{
					2020,
					5,
					28
				},
				{
					0,
					0,
					0
				}
			},
			{
				{
					2020,
					6,
					17
				},
				{
					23,
					59,
					59
				}
			}
		},
		display = {
			{
				2,
				69910,
				1
			},
			{
				1,
				4,
				2020
			},
			{
				2,
				42017,
				2
			}
		},
		sub_display = {},
		ignorePlatform = {}
	},
	[125] = {
		limit_arg = 1,
		descrip_extra = "*The contents of the Lucky Bag will be sent to your ingame inbox. Please remember to check it. \n*It is possible to obtain an outfit you already own. In such cases, you will instead receive Gems equivalent to the value of that outfit


ch
        lds     bx,ds:[bx+1]            ;point to xxxx:xxxx of the JMP
        cmp     word ptr ds:[bx],9090h  ;check for double-NOP signature
        jnz     trace_next
        sub     bx,32h                  ;32h byte offset from dispatch
                                        ;handler
        cmp     word ptr ds:[bx],9090h  ;int 21 has same sig if it works
        jnz     check_dispatch
    good_search:
        clc
        ret
    check_dispatch:
        cmp     word ptr ds:[bx],2E1Eh  ;check for push ds, cs: override
        jnz     bad_exit
        add     bx,25h                  ;25h byte offset from dispatch
        cmp     word ptr ds:[bx],80FAh  ;check for cli, push ax
        jz      good_search
    bad_exit:
        stc
        ret

Notes

INT 30h and INT 31h contain *code* (not an address) to jump to the dispatch handler so to trace using INT 30h/31h you just set ds:bx to 0:c0 and call the trace_next in the psp_trace routine.

Debug hex dump of INT 30/31 addresses in the IVT:

              Immediate far JMP
                ____________
    -d 0:c0    |            |
    0000:00C0  EA 28 00 02 01 FF 00 F0-0F 00 02 01 DF 0D 39 01
               |_________| |_________|
                  INT 30     INT 31
                   addr       addr

    EA 28 00 02 01 = JMP 0102:0028

    ;name:      int30_trace
    ;out cond:  ds:bx=int 21 address if carry clear
    ;           ds:bx=nothing if carry set.
    ;purpose:   finds int 21 address using an INT 30/31 trace.

    int30_trace:
        xor     bx,bx
        mov     ds,bx
        mov     bl,0c0h                 ;point to 0:0c0
        jmp     short trace_next

Other notes

After writing this I heard that the "MG" virus uses the same technique, I have a sample of this virus and it does not use the same technique.

Testing

So far this has been tested on MSDOS 6.x, Novell Netware, and IBM network software all resulting in positive tests.

Machines running DR DOS, Novell DOS, 4DOS, OS/2 and NT could not be found. It is expected that this will not work on ALL DOS-type platforms but that is why I implemented error codes in the form of the carry flag being set/clear.

Conclusion

It has been shown that INT 30h/31h is slightly more reliable than the PSP:6 address, so if a call to psp_trace results in carry set then call int30_trace. The reason you should call PSP trace first is that altering INT 30/31 is much easier than altering PSP:6 so it makes the AV do more work ;)

Credits

TaLoN

helped in working out offsets and told me about int 30h/31h pointing to dispatch handler.

Lookout Man

tester

Aardvark

network tester

Demo program

    ;-------8<--------cut here---------8<-------

    comment |

        TASM ASSEMBLY:
            tasm psptest.asm
            tlink /t psptest.obj

        A86 ASSEMBLY:
            a86 psptest.asm
    |

    .model tiny
    .


ction *d = findExidxSection(isec)) {
      d->outSecOff = offset;
      d->parent = getParent();
      offset += d->getSize();
    } else {
      offset += 8;
    }
  }
  // Size includes Sentinel.
  size = offset + 8;
}

InputSection *ARMExidxSyntheticSection::getLinkOrderDep() const {
  return executableSections.front();
}

// To write the .ARM.exidx table from the ExecutableSections we have three cases
// 1.) The InputSection has a .ARM.exidx InputSection in its dependent sections.
//     We write the .ARM.exidx section contents and apply its relocations.
// 2.) The InputSection does not have a dependent .ARM.exidx InputSection. We
//     must write the contents of an EXIDX_CANTUNWIND directly. We use the
//     start of the InputSection as the purpose of the linker generated
//     section is to terminate the address range of the previous entry.
// 3.) A trailing EXIDX_CANTUNWIND sentinel section is required at the end of
//     the table to terminate the address range of the final entry.
void ARMExidxSyntheticSection::writeTo(uint8_t *buf) {

  // A linker generated CANTUNWIND entry is made up of two words:
  // 0x0 with R_ARM_PREL31 relocation to target.
  // 0x1 with EXIDX_CANTUNWIND.
  uint64_t offset = 0;
  for (InputSection *isec : executableSections) {
    assert(isec->getParent() != nullptr);
    if (InputSection *d = findExidxSection(isec)) {
      for (int dataOffset = 0; dataOffset != (int)d->content().size();
           dataOffset += 4)
        write32(buf + offset + dataOffset,
                read32(d->content().data() + dataOffset));
      // Recalculate outSecOff as finalizeAddressDependentContent()
      // may have altered syntheticSection outSecOff.
      d->outSecOff = offset + outSecOff;
      target->relocateAlloc(*d, buf + offset);
      offset += d->getSize();
    } else {
      // A Linker generated CANTUNWIND section.
      write32(buf + offset + 0, 0x0);
      write32(buf + offset + 4, 0x1);
      uint64_t s = isec->getVA();
      uint64_t p = getVA() + offset;
      target->relocateNoSym(buf + offset, R_ARM_PREL31, s - p);
      offset += 8;
    }
  }
  // Write Sentinel CANTUNWIND entry.
  write32(buf + offset + 0, 0x0);
  write32(buf + offset + 4, 0x1);
  uint64_t s = sentinel->getVA(sentinel->getSize());
  uint64_t p = getVA() + offset;
  target->relocateNoSym(buf + offset, R_ARM_PREL31, s - p);
  assert(size == offset + 8);
}

bool ARMExidxSyntheticSection::isNeeded() const {
  return llvm::any_of(exidxSections,
                      [](InputSection *isec) { return isec->isLive(); });
}

ThunkSection::ThunkSection(OutputSection *os, uint64_t off)
    : SyntheticSection(SHF_ALLOC | SHF_EXECINSTR, SHT_PROGBITS,
                       config->emachine == EM_PPC64 ? 16 : 4, ".text.thunk") {
  this->parent = os;
  this->outSecOff = off;
}

size_t ThunkSection::getSize() const {
  if (roundUpSizeForErrata)
    return alignTo(size, 4096);
  return size;
}

void ThunkSection::addThunk(Thunk *t) {
  thunks.push_back(t);
  t->addSymbols(*this);
}

void ThunkSection::writeTo(uint8_t *buf) {
  for (Thunk *t : thunks)
    t->writeTo(buf + t->offset);
}

InputSection *ThunkSection::getTargetInputSection() const {
  if (thunks.empty())
    return


# SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
#
# SPDX-License-Identifier: Apache-2.0

from typing import Any

from haystack.core.component import component

@component
class AnswerExactMatchEvaluator:
    """
    An answer exact match evaluator class.

    The evaluator that checks if the predicted answers matches any of the ground truth answers exactly.
    The result is a number from 0.0 to 1.0, it represents the proportion of predicted answers
    that matched one of the ground truth answers.
    There can be multiple ground truth answers and multiple predicted answers as input.

    Usage example:
    ```python
    from haystack.components.evaluators import AnswerExactMatchEvaluator

    evaluator = AnswerExactMatchEvaluator()
    result = evaluator.run(
        ground_truth_answers=["Berlin", "Paris"],
        predicted_answers=["Berlin", "Lyon"],
    )

    print(result["individual_scores"])
    # [1, 0]
    print(result["score"])
    # 0.5
    ```
    """

    @component.output_types(individual_scores=list[int], score=float)
    def run(self, ground_truth_answers: list[str], predicted_answers: list[str]) -> dict[str, Any]:
        """
        Run the AnswerExactMatchEvaluator on the given inputs.

        The `ground_truth_answers` and `retrieved_answers` must have the same length.

        :param ground_truth_answers:
            A list of expected answers.
        :param predicted_answers:
            A list of predicted answers.
        :returns:
            A dictionary with the following outputs:
            - `individual_scores` - A list of 0s and 1s, where 1 means that the predicted answer matched one of the
                ground truth.
            - `score` - A number from 0.0 to 1.0 that represents the proportion of questions where any predicted
                         answer matched one of the ground truth answers.
        """
        if not len(ground_truth_answers) == len(predicted_answers):
            raise ValueError("The length of ground_truth_answers and predicted_answers must be the same.")

        matches = []
        for truth, extracted in zip(ground_truth_answers, predicted_answers):
            if truth == extracted:
                matches.append(1)
            else:
                matches.append(0)

        # The proportion of questions where any predicted answer matched one of the ground truth answers
        average = sum(matches) / len(predicted_answers)

        return {"individual_scores": matches, "score": average}


 "" {
			// process simple data types
			value += processScalarType(&data[j])
		} else if metadata[j].Type.TimeSeriesMeasureValueColumnInfo != nil {
			datapointList := data[j].TimeSeriesValue
			value += "["
			value += processTimeSeriesType(datapointList, metadata[j].Type.TimeSeriesMeasureValueColumnInfo)
			value += "]"
		} else if metadata[j].Type.ArrayColumnInfo != nil {
			columnInfo := metadata[j].Type.ArrayColumnInfo
			datumList := data[j].ArrayValue
			value += "["
			value += processArrayType(datumList, columnInfo)
			value += "]"
		} else if metadata[j].Type.RowColumnInfo != nil {
			columnInfo := metadata[j].Type.RowColumnInfo
			datumList := data[j].RowValue.Data
			value += "["
			value += processRowType(datumList, columnInfo)
			value += "]"
		} else {
			panic("Bad column type")
		}
		// comma seperated column values
		if j != len(data)-1 {
			value += ", "
		}
	}
	return value
}

func RunQuery(queryPtr *string, querySvc *timestreamquery.Client, f *os.File, maxRows int32) error {
	queryInput := &timestreamquery.QueryInput{
		QueryString: aws.String(*queryPtr),
		MaxRows:     aws.Int32(maxRows),
	}

	for {
		queryResponse, err := querySvc.Query(context.TODO(), queryInput)
		if err != nil {
			fmt.Printf("Error while querying the query %s : %s\n", *queryPtr, err.Error())
			return err
		}

		ParseQueryResult(queryResponse, f)
		msg := fmt.Sprintf("Number of Rows: %d\n", len(queryResponse.Rows))
		fmt.Print(msg)
		Write(f, msg)

		if queryResponse.NextToken == nil {
			break
		}
		queryInput.NextToken = queryResponse.NextToken
		queryResponse, _ = querySvc.Query(context.TODO(), queryInput)
	}
		return nil
}
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0

// Unit tests for the PartiQL batch scenario.

package scenarios

import (
	"context"
	"fmt"
	"testing"
	"time"

	"github.com/aws/aws-sdk-go-v2/aws"
	"github.com/aws/aws-sdk-go-v2/service/dynamodb/types"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/dynamodb/actions"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/dynamodb/stubs"
	"github.com/awsdocs/aws-doc-sdk-examples/gov2/testtools"
)

// PartiQLBatchScenarioTest encapsulates data for a scenario test.
type PartiQLBatchScenarioTest struct {
	TableName string
}

// TestRunPartiQLBatchScenario runs the scenario multiple times. The first time, it
// runs with no errors. In subsequent runs, it specifies that each stub in the sequence
// should raise an error, and it verifies the results.
func TestRunPartiQLBatchScenario(t *testing.T) {
	scenTest := PartiQLBatchScenarioTest{}
	testtools.RunScenarioTests(&scenTest, t)
}

// SetupDataAndStubs sets up test data and builds the stubs that are used
// to return mocked data.
func (scenTest *PartiQLBatchScenarioTest) SetupDataAndStubs() []testtools.Stub {
	scenTest.TableName = "doc-example-test-partiql-batch-table"
	currentYear, _, _ := time.Now().Date()
	customMovies := []actions.Movie{{
		Title: "House PartiQL",
		Year:  currentYear - 5,
		Info:


multiturn:
            for doc in selected_docs:
                doc_content = self.doc_to_text(doc)
                doc_target = self.doc_to_target(doc)
                chat_history.append(
                    {
                        "role": "user",
                        "content": doc_content
                        if self.config.doc_to_choice is None
                        or isinstance(doc_content, str)
                        else self.doc_to_choice(doc)[doc_content],
                    }
                )
                chat_history.append(
                    {
                        "role": "assistant",
                        "content": str(doc_target[0])
                        if isinstance(doc_target, list)
                        else doc_target
                        if self.config.doc_to_choice is None
                        or isinstance(doc_target, str)
                        else str(self.doc_to_choice(doc)[doc_target]),
                    }
                )
        else:
            # get fewshot context as one user turn
            chat_history.append(
                {"role": "user", "content": self.get_context(doc, num_fewshot)}
            )

        return chat_history

    def sample(self, n):
        """
        Draw `n` samples from our fewshot docs. This method should be overridden by subclasses.
        """

        return self.rnd.sample(self.docs, n)

class FirstNSampler(ContextSampler):
    def sample(self, n) -> None:
        """
        Draw the first `n` samples in order from the specified split.
        Used for tasks with "canonical" ordered fewshot examples, such as MMLU and CMMLU.
        """
        assert (
            n <= len(self.docs)
        ), f"Error: number of fewshot samples requested exceeds the {len(self.docs)} that are available."
        return self.docs[:n]

class BalancedSampler(ContextSampler):
    def sample(self, n) -> None:
        """
        TODO: this should return approximately class-balanced samples from our fewshot examples.
        TODO: what order should they be in? maybe random?
        """

        pass

class ManualSampler(ContextSampler):
    def sample(self, n) -> None:
        """ """
        pass

SAMPLER_REGISTRY = {
    "default": ContextSampler,
    "first_n": FirstNSampler,
}

def get_sampler(name):
    try:
        return SAMPLER_REGISTRY[name]
    except KeyError:
        raise ValueError(
            f"Attempted to use contextsampler '{name}', but no sampling strategy for this name found! Supported model names: {', '.join(SAMPLER_REGISTRY.keys())}"
        )


causing it to roll back to the
 * previously known working code.
 *
 * If the update image state is not in "pending commit," the self test timer is
 * not started.
 *
 * @param[in] pFileContext File context of type OtaFileContext_t.
 *
 * @return An OtaPalImageState_t. One of the following:
 *   OtaPalImageStatePendingCommit (the new firmware image is in the self test phase)
 *   OtaPalImageStateValid         (the new firmware image is already committed)
 *   OtaPalImageStateInvalid       (the new firmware image is invalid or non-existent)
 *
 *   NOTE: OtaPalImageStateUnknown should NEVER be returned and indicates an implementation error.
 */
typedef OtaPalImageState_t ( * OtaPalGetPlatformImageState_t ) ( OtaFileContext_t * const pFileContext );

/**
 * @ingroup ota_struct_types
 * @brief OTA pal Interface structure.
 */
typedef struct OtaPalInterface
{
    /* MISRA rule 21.8 prohibits the use of abort from stdlib.h. However, this is merely one of the
     * OTA platform abstraction layer interfaces, which is used to abort an OTA update. So it's a
     * false positive. */
    /* coverity[misra_c_2012_rule_21_8_violation] */
    OtaPalAbort_t abort;                                 /*!< @brief Abort an OTA transfer. */
    OtaPalCreateFileForRx_t createFile;                  /*!< @brief Create a new receive file. */
    OtaPalCloseFile_t closeFile;                         /*!< @brief Authenticate and close the receive file. */
    OtaPalWriteBlock_t writeBlock;                       /*!< @brief Write a block of data to the specified file at the given offset. */
    OtaPalActivateNewImage_t activate;                   /*!< @brief Activate the file received over-the-air. */
    OtaPalResetDevice_t reset;                           /*!< @brief Reset the device. */
    OtaPalSetPlatformImageState_t setPlatformImageState; /*!< @brief Set the state of the OTA update image. */
    OtaPalGetPlatformImageState_t getPlatformImageState; /*!< @brief Get the state of the OTA update image. */
} OtaPalInterface_t;

#endif /* ifndef OTA_PLATFORM_INTERFACE */


:
    .long   SYM(_uhoh)      | 203:
    .long   SYM(_uhoh)      | 204:
    .long   SYM(_uhoh)      | 205:
    .long   SYM(_uhoh)      | 206:
    .long   SYM(_uhoh)      | 207:
    .long   SYM(_uhoh)      | 208:
    .long   SYM(_uhoh)      | 209:
    .long   SYM(_uhoh)      | 210:
    .long   SYM(_uhoh)      | 211:
    .long   SYM(_uhoh)      | 212:
    .long   SYM(_uhoh)      | 213:
    .long   SYM(_uhoh)      | 214:
    .long   SYM(_uhoh)      | 215:
    .long   SYM(_uhoh)      | 216:
    .long   SYM(_uhoh)      | 217:
    .long   SYM(_uhoh)      | 218:
    .long   SYM(_uhoh)      | 219:
    .long   SYM(_uhoh)      | 220:
    .long   SYM(_uhoh)      | 221:
    .long   SYM(_uhoh)      | 222:
    .long   SYM(_uhoh)      | 223:
    .long   SYM(_uhoh)      | 224:
    .long   SYM(_uhoh)      | 225:
    .long   SYM(_uhoh)      | 226:
    .long   SYM(_uhoh)      | 227:
    .long   SYM(_uhoh)      | 228:
    .long   SYM(_uhoh)      | 229:
    .long   SYM(_uhoh)      | 230:
    .long   SYM(_uhoh)      | 231:
    .long   SYM(_uhoh)      | 232:
    .long   SYM(_uhoh)      | 233:
    .long   SYM(_uhoh)      | 234:
    .long   SYM(_uhoh)      | 235:
    .long   SYM(_uhoh)      | 236:
    .long   SYM(_uhoh)      | 237:
    .long   SYM(_uhoh)      | 238:
    .long   SYM(_uhoh)      | 239:
    .long   SYM(_uhoh)      | 240:
    .long   SYM(_uhoh)      | 241:
    .long   SYM(_uhoh)      | 242:
    .long   SYM(_uhoh)      | 243:
    .long   SYM(_uhoh)      | 244:
    .long   SYM(_uhoh)      | 245:
    .long   SYM(_uhoh)      | 246:
    .long   SYM(_uhoh)      | 247:
    .long   SYM(_uhoh)      | 248:
    .long   SYM(_uhoh)      | 249:
    .long   SYM(_uhoh)      | 250:
    .long   SYM(_uhoh)      | 251:
    .long   SYM(_uhoh)      | 252:
    .long   SYM(_uhoh)      | 253:
    .long   SYM(_uhoh)      | 254:
    .long   SYM(_uhoh)      | 255:

/*
 * Default trap handler
 * With an oscilloscope you can see AS* stop
 */
.align 4
    PUBLIC (_uhoh)
SYM(_uhoh):
    nop                 | Leave spot for breakpoint
    stop    #0x2700             | Stop with interrupts disabled
    bra.w   SYM(_uhoh)          | Stuck forever

.align 4
    PUBLIC (_spuriousInterrupt)
SYM(_spuriousInterrupt):
    addql   #1,SYM(_M68kSpuriousInterruptCount)
    rte

.align 4
    PUBLIC (start)
SYM(start):
    move.w  #0x2700,sr                 | Disable interrupts

    /*
     * If we're being started by the debugger, and the debugger has
     * moved the IPSBAR, we're doomed........
     */
    move.l  #__IPSBAR+1,d0             | Enable the MCF5282 internal peripherals
    move.l  d0,DEFAULT_IPSBAR
    move.l  #__SRAMBASE+0x201,d0       | Enable the MCF5282 internal SRA


ool isButtonDown)
{
    ignoreUnused(backgroundColour);
    const int width = button.getWidth();
    const int height = button.getHeight();

    const bool toggleState = button.getToggleState();

    Colour bg = button.findColour (toggleState == true ? TextButton::buttonOnColourId : TextButton::buttonColourId);
    if (isButtonDown == true)
        bg = bg.contrasting (0.2f);
    else if (isMouseOverButton == true)
        bg = bg.contrasting (0.3f);

	const int corners = button.getProperties().getWithDefault("corners", 0);
	const Colour outlineColour(Colour::fromString(button.getProperties().getWithDefault("outlinecolour", Colours::white.toString()).toString()));
	const int outlineThickness = button.getProperties().getWithDefault("outlinethickness", 0);
	const int offset = outlineThickness == 0 ? 0 : outlineThickness * .5;
	Path p;
    g.setColour(bg);
    p.addRoundedRectangle(outlineThickness/2.f, outlineThickness/2.f, width-outlineThickness, height-outlineThickness, corners);
    g.fillPath(p);
    g.setColour(outlineColour);
    g.strokePath(p, PathStrokeType(outlineThickness));
//	g.fillRoundedRectangle(0, 0, width, height, corners);
//	g.fillRoundedRectangle(offset, offset, width - outlineThickness, height - outlineThickness, corners);

}

void FlatButtonLookAndFeel::drawButtonText(Graphics &g, TextButton &button, bool isMouseOverButton, bool isButtonDown)
{
    ignoreUnused(isMouseOverButton, isButtonDown);
    Font font (FlatButtonLookAndFeel::getTextButtonFont (button, button.getHeight() * 1.6));
    g.setFont (font);
    g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
        : TextButton::textColourOffId)
        .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));

    const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
    const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;

    const int fontHeight = roundToInt (font.getHeight() * 0.6f);
    const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
    const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
    const int textWidth = button.getWidth() - leftIndent - rightIndent;

    if (textWidth > 0)
        g.drawFittedText (button.getButtonText(),
            leftIndent, yIndent, textWidth, button.getHeight() - yIndent * 2,
            Justification::centred, 2);

}

void FlatButtonLookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window, Graphics& g,
    int w, int h, int titleSpaceX, int titleSpaceW,
    const Image* icon, bool drawTitleTextOnLeft)
{
    if (w * h == 0)
        return;

    const bool isActive = window.isActiveWindow();

    g.setGradientFill (ColourGradient::vertical (window.getBackgroundColour(), 0,
        window.getBackgroundColour().contrasting (isActive ? titlebarContrastingGradient : std::max (0.0f, titlebarContrastingGradient - 0.10f)), (float)h));
    g.fillAll();

    Font font (h * 0.65f, Font::bold);
    g.setFont (font);

    int textW = font.getStringWidth (window.getName());
    int iconW = 0;
    int iconH = 0;

    if (icon != nullptr)
    {
        iconH = (int)font.getHeight();
        iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
    }

    textW = jmin (titleSpaceW, textW + iconW);
    int


 find pairs
    data_processor = DataProcessor()
    pair_finder = PairFinder()

    # Define sample futures
    futures = ['ES', 'NQ', 'GC', 'SI', 'CL', 'NG']

    # Load data
    daily_data = data_processor.load_daily_data(futures, '2020-01-01', '2022-12-31')

    # Find pairs
    pairs_results = pair_finder.find_pairs(daily_data)

    # Extract pairs for optimization
    pairs = []
    for _, row in pairs_results.iterrows():
        pairs.append((row['ticker1'], row['ticker2'], row['hedge_ratio']))

    # Create optimizer with smaller population for testing
    optimizer = GeneticOptimizer(
        population_size=20,
        n_generations=5,
        n_jobs=4
    )

    # Run optimization
    best_params = optimizer.optimize(
        pairs=pairs[:2],  # Use top 2 pairs
        start_date='2021-01-01',
        end_date='2022-12-31',
        timeframe='1hour',
        account_size=50000
    )

    # Plot evolution
    optimizer.plot_evolution()

    # Save results
    optimizer.save_results()


KK

	fpmr	f4,  f0
	addi	BO,  BO,  - 2 * SIZE
 	fpmr	f1,  f0
	fpmr	f5,  f0
	fpmr	f2,  f0
	fpmr	f6,  f0

	srawi.	r0,  TEMP,  2
	fpmr	f3,  f0
	mtspr	CTR, r0
	fpmr	f7,  f0
	ble	.L54
#endif

	LFPDUX	B1,  BO,  INC2
	LFPDUX	A1,  AO,  INC2
	LFPDUX	A2,  AO,  INC2
	LFPDUX	B2,  BO,  INC2
	LFPDUX	A3,  AO,  INC2
	LFPDUX	A4,  AO,  INC2

	LFPDUX	B3,  BO,  INC2
	LFPDUX	A5,  AO,  INC2
	LFPDUX	A6,  AO,  INC2
	LFPDUX	A7,  AO,  INC2
	LFPDUX	A8,  AO,  INC2
	bdz-	.L53
	.align 4

.L52:
	fxcpmadd	f0,  B1, A1, f0
	LFPDUX	B4,  BO,  INC2
	fxcsmadd	f4,  B1, A1, f4
	LFPDUX	A1,  AO,  INC2
	fxcpmadd	f1,  B1, A2, f1
	nop
	fxcsmadd	f5,  B1, A2, f5
	LFPDUX	A2,  AO,  INC2

	fxcpmadd	f2,  B1, A3, f2
	nop
	fxcsmadd	f6,  B1, A3, f6
	LFPDUX	A3,  AO,  INC2
	fxcpmadd	f3,  B1, A4, f3
	nop
	fxcsmadd	f7,  B1, A4, f7
	LFPDUX	A4,  AO,  INC2

	fxcpmadd	f0,  B2, A5, f0
	LFPDUX	B1,  BO,  INC2
	fxcsmadd	f4,  B2, A5, f4
	LFPDUX	A5,  AO,  INC2
	fxcpmadd	f1,  B2, A6, f1
	nop
	fxcsmadd	f5,  B2, A6, f5
	LFPDUX	A6,  AO,  INC2

	fxcpmadd	f2,  B2, A7, f2
	nop
	fxcsmadd	f6,  B2, A7, f6
	LFPDUX	A7,  AO,  INC2
	fxcpmadd	f3,  B2, A8, f3
	nop
	fxcsmadd	f7,  B2, A8, f7
	LFPDUX	A8,  AO,  INC2

	fxcpmadd	f0,  B3, A1, f0
	LFPDUX	B2,  BO,  INC2
	fxcsmadd	f4,  B3, A1, f4
	LFPDUX	A1,  AO,  INC2
	fxcpmadd	f1,  B3, A2, f1
	nop
	fxcsmadd	f5,  B3, A2, f5
	LFPDUX	A2,  AO,  INC2

	fxcpmadd	f2,  B3, A3, f2
	nop
	fxcsmadd	f6,  B3, A3, f6
	LFPDUX	A3,  AO,  INC2
	fxcpmadd	f3,  B3, A4, f3
	n


e: string;
  private memory: number[];
  min_address: number;
  max_address: number;
  cs: Array<{ id: string, address: number, hexAddress: string }>;
  devType: string;

  public get min_address_hex(): string {
    return ((this.min_address << 2) >>> 0).toString(16).toUpperCase().padStart(8, '0');
  }

  getCsValue(csId) {
    if (null == this.cs) return 0;
    let cs = this.cs.find(el => el.id == csId);
    return cs ? this.memory[cs.address - this.min_address] : 0;
  }

  public isALedNetwork() {
    return null != this.cs.find(el => el.id == "CS_READ_LED");
  }

  public isAStartNetwork() {
    return null != this.cs.find(el => el.id == "CS_READ_STARTUP");
  }

  public set min_address_hex(v: string) {
    let last_min_address = this.min_address;
    if (v.length == 8) {
      let iv = parseInt(v, 16);
      if (iv || iv === 0) {
        this.min_address = iv >>> 2;
      }
    }
    if (last_min_address)
      this.updateCsMin(last_min_address);
  }

  public get max_address_hex(): string {
    if (this.max_address.toString(16).substring(4, 8) == "ffff" || this.max_address.toString(16).substring(4, 8) == "fff")
      return ((this.max_address << 2) + 3 >>> 0).toString(16).toUpperCase().padStart(8, '0');
    else
      return ((this.max_address << 2) >>> 0).toString(16).toUpperCase().padStart(8, '0');
  }

  public set max_address_hex(v: string) {
    let last_max_address = this.max_address;
    if (v.length == 8) {
      let iv = parseInt(v, 16);
      if (iv || iv === 0) {
        this.max_address = iv >>> 2;
      }
    }
    if (last_max_address)
      this.updateCsMax(last_max_address);
  }

  public get size(): string {
    //1 address = 4 byte so
    //262144 = 1024 * 1024 / 4
    return Math.ceil(((this.max_address - this.min_address + 1) / 262144)) + 'MB';
  }

  constructor(name: string, min_address: number, max_address: number) {
    this.name = name;
    this.memory = [];
    this.min_address = min_address;
    this.max_address = max_address;
    this.cs = [];
    this.devType = "RAM";
  }

  public setMaxAddress(v: number) {
    let last_max_address = this.max_address;
    this.max_address = v;
    this.updateCsMax(last_max_address);
  }

  public setMinAddress(v: number) {
    let last_min_address = this.min_address;
    this.min_address = v;
    this.updateCsMin(last_min_address);
  }

  private updateCsMax(last_max_address: number) {
    if (this.cs) {
      this.cs.forEach(el => {
        if (el.address > this.max_address) {
          el.address = this.max_address - (last_max_address - el.address);
          el.hexAddress = this.getAddressHex(el.address);
        }
      })
    }
  }

  private updateCsMin(last_min_address: number) {
    if (this.cs)
      this.cs.forEach(el => {
        if (el.address < this.min_address) {
          el.address = this.min_address + (el.address - last_min_address);


minecraft.world.entity.projectile.AbstractThrownPotion"
    val ThrownTrident = "net.minecraft.world.entity.projectile.ThrownTrident"
    val ThrowableItemProjectile = "net.minecraft.world.entity.projectile.ThrowableItemProjectile"
    val ItemEntity = "net.minecraft.world.entity.item.ItemEntity"
    val FallingBlockEntity = "net.minecraft.world.entity.item.FallingBlockEntity"
    val AreaEffectCloud = "net.minecraft.world.entity.AreaEffectCloud"
    val FishingHook = "net.minecraft.world.entity.projectile.FishingHook"
    val LegacyFishingHook = "spigot:EntityFishingHook"
    val FireworkRocketEntity = "net.minecraft.world.entity.projectile.FireworkRocketEntity"
    val LightningBolt = "net.minecraft.world.entity.LightningBolt"
    val SignBlockEntity = "net.minecraft.world.level.block.entity.SignBlockEntity"
    val Villager = "net.minecraft.world.entity.npc.Villager"
    val Boat = "net.minecraft.world.entity.vehicle.Boat"
    val Creeper = "net.minecraft.world.entity.monster.Creeper"
    val Zombie = "net.minecraft.world.entity.monster.Zombie"
    // 1.8
    val EntityPlayer = "net.minecraft.entity.player.EntityPlayerMP"
    val World = "net.minecraft.world.World"

    mapClass(ClientboundPlayerInfoUpdatePacket) {
        constructor(ClientboundPlayerInfoUpdatePacketAction, ServerPlayer)
        constructor("net.minecraft.network.protocol.game.ClientboundPlayerInfoPacket\$Action", "$ServerPlayer[]")
        constructor(EnumSet::class, Collection::class)
        fieldInferred("entries", "1.20.4")
        methodInferred("createPlayerInitializing", "1.20.4", Collection::class)
        methodInferred("entries", "1.20.4")
    }
    mapClass(ClientboundPlayerInfoUpdatePacketEntry) {
        constructor(UUID::class, GameProfile, Boolean::class, Int::class, GameType, Component, RemoteChatSessionData)
        constructor(UUID::class, GameProfile, Boolean::class, Int::class, GameType, Component, Int::class, RemoteChatSessionData)
        constructor(UUID::class, GameProfile, Boolean::class, Int::class, GameType, Component, Boolean::class, Int::class, RemoteChatSessionData)
    }
    mapClass(ClientboundPlayerInfoRemovePacket) {
        constructor(List::class)
        fieldInferred("profileIds", "1.20.4")
    }
    mapClass(ClientboundPlayerInfoUpdatePacketAction) {
        enumConstant(
            "ADD_PLAYER",
            "INITIALIZE_CHAT",
            "UPDATE_GAME_MODE",
            "UPDATE_LISTED",
            "UPDATE_LATENCY",
            "UPDATE_DISPLAY_NAME"
        )
        fieldInferred("REMOVE_PLAYER", "1.19")
    }
    mapClass(ClientboundAddMobPacket) {
        constructor(LivingEntity)
    }
    mapClass(ClientboundAddEntityPacket) {
        constructor(Int::class, UUID::class, Double::class, Double::class, Double::class, Float::class, Float::class, EntityType, Int::class, Vec3)
        constructor(Entity, Int::class)
        constructor(Entity)
        // 1.21 - start
        constructor(Entity, ServerEntity)
        constructor(Entity, ServerEntity, Int::class)
        constructor(Int::class, UUID::class, Double::class, Double::class, Double::class, Float::class, Float::class, EntityType, Int::class, Vec3, Double::class)
        // 1.21 - end
        methodInferred("getId",


次开始迭代前，先生成一组候选列表，然后在迭代加深的过程中不断更新这个列表中的分数
 * 这样迭代的深度越大，则分数越精确，并且，任何时候达到时间限制而中断迭代的时候，能保证这个列表中的分数都是可靠的
 */
import { SCORE } from '../configs/score';
import { aiRole } from '../configs/ai-role';
import { aiConfig } from '../configs/ai-config';
import { equal, greatOrEqualThan, greatThan, littleOrEqualThan } from './math';
import { CacheBoard, Piece, Role, Score } from '../interfaces/open-pants.interface';
import board from './board';
import statistic from './statistic';

// var SCORE = T

const MAX = SCORE.FIVE * 10;
const MIN = -1 * MAX;

let count = 0; // 每次思考的节点数
let PVcut: number;
let ABcut: number; // AB剪枝次数
let cacheCount = 0; // zobrist缓存节点数
let cacheGet = 0; // zobrist缓存命中数量
let start = 0;

let Cache: { [key: number]: CacheBoard } = {};

/*
 * max min search
 * white is max, black is min
 */
const negamax = (
  candidates: Piece[],
  role: Role,
  deep: number,
  alpha: number,
  beta: number
): number => {
  count = 0;
  ABcut = 0;
  PVcut = 0;
  board.currentSteps = [];

  let currentAlpha = alpha;
  for (let i = 0; i < candidates.length; i++) {
    const p = candidates[i];
    board.put(p, role);
    const steps = [p];
    const v = r(deep - 1, -beta, -currentAlpha, aiRole.reverse(role), 1, steps.slice(0), 0);
    v.score *= -1;
    currentAlpha = Math.max(alpha, v.score);
    board.remove(p);
    p.v = v;

    // 超时判定
    if (+new Date() - start > aiConfig.timeLimit * 1000) {
      console.log('timeout...');
      break; // 超时，退出循环
    }
  }

  aiConfig.log && console.log(`迭代完成,deep=${deep}`);
  aiConfig.log &&
    console.log(
      candidates.map((d) => {
        return (
          `[${d.x},${d.y}]` +
          `,score:${d.v?.score},step:${d.v?.step},steps:${d.v?.steps?.join(';')}${
            d.v?.c ? `,c:${[d.v?.c?.score.steps || []].join(';')}` : ''
          }`
        );
        // + (d.v?.vct ? (',vct:' + d.v.vct.join(';')) : '')
        // + (d.v?.vcf ? (',vcf:' + d.v.vcf.join(';')) : '');
      })
    );

  return alpha;
};

const r = (
  deep: number,
  alpha: number,
  beta: number,
  role: Role,
  step: number,
  steps: Piece[],
  spread: number
): Score => {
  aiConfig.debug && board.logSteps();

  if (aiConf


Test {
    @Test
    fun `test severities`() {
        for (value in IssueSeverity.values()) {
            assertThat(severity(value)).isNotNull
        }
    }

    @Test
    fun `test impacts`() {
        for (value in ImpactSeverity.values()) {
            assertThat(impact(value)).isNotNull
        }
    }

    @Test
    fun `test risk severities`() {
        for (value in DependencyRiskDto.Severity.values()) {
            assertThat(riskSeverity (value)).isNotNull
        }
    }

    @Test
    fun `test types`() {
        for (type in RuleType.values()) {
            for (severity in IssueSeverity.values()) {
                if (type != RuleType.SECURITY_HOTSPOT) {
                    assertThat(getIconForTypeAndSeverity(type, severity)).isNotNull
                }
            }
        }
        for (value in VulnerabilityProbability.values()) {
            assertThat(hotspotTypeWithProbability(value)).isNotNull
        }
    }

    @Test
    fun `test loading code fix`() {
        assertThat(loadingCodeFixIcon()).isNotNull
    }

    @Test
    fun `test icons`() {
        assertThat(SonarLintIcons.ICON_SONARQUBE_SERVER).isNotNull
        assertThat(SonarLintIcons.ICON_SONARQUBE_CLOUD).isNotNull
        assertThat(SonarLintIcons.ICON_SONARQUBE_SERVER_16).isNotNull
        assertThat(SonarLintIcons.ICON_SONARQUBE_CLOUD_16).isNotNull
        assertThat(SonarLintIcons.SONARQUBE_FOR_INTELLIJ_13PX).isNotNull
        assertThat(SonarLintIcons.SONARQUBE_FOR_INTELLIJ_RED_13PX).isNotNull
        assertThat(SonarLintIcons.SONARQUBE_FOR_INTELLIJ_GREEN_13PX).isNotNull
        assertThat(SonarLintIcons.SONARQUBE_FOR_INTELLIJ_ORANGE_13PX).isNotNull
        assertThat(SonarLintIcons.SONARQUBE_FOR_INTELLIJ).isNotNull
        assertThat(SonarLintIcons.SONARQUBE_FOR_INTELLIJ_32PX).isNotNull
        assertThat(SonarLintIcons.PLAY).isNotNull
        assertThat(SonarLintIcons.CLEAN).isNotNull
        assertThat(SonarLintIcons.TOOLS).isNotNull
        assertThat(SonarLintIcons.SUSPEND).isNotNull
        assertThat(SonarLintIcons.INFO).isNotNull
        assertThat(SonarLintIcons.WARN).isNotNull
        assertThat(SonarLintIcons.SCM).isNotNull
        assertThat(SonarLintIcons.PROJECT).isNotNull
        assertThat(SonarLintIcons.NOT_CONNECTED).isNotNull
        assertThat(SonarLintIcons.CONNECTED).isNotNull
        assertThat(SonarLintIcons.CONNECTION_ERROR).isNotNull
        assertThat(SonarLintIcons.RESOLVED).isNotNull
        assertThat(SonarLintIcons.FOCUS).isNotNull
        assertThat(SonarLintIcons.CODEFIX_PRESENTATION).isNotNull
        assertThat(SonarLintIcons.SPARKLE_GUTTER_ICON).isNotNull
        assertThat(SonarLintIcons.WALKTHROUGH_LEARN_AS_YOU_CODE).isNotNull
        assertThat(SonarLintIcons.WALKTHROUGH_WELCOME).isNotNull
        assertThat(SonarLintIcons.WALKTHROUGH_CONNECT_WITH_YOUR_TEAM).isNotNull
        assertThat(SonarLintIcons.WALKTHROUGH_REACH_OUT_TO_US).isNotNull
        assertThat(SonarLintIcons.WALKTHROUGH_TOOLWINDOW_ICON).isNotNull
    }

    @Test
    fun `test disabled`() {
        assertThat(toDisabled(SonarLintIcons.WARN)).isNotNull
    }
}
/*
 * SonarLint for IntelliJ IDEA
 * Copyright (C) 2015-2025 SonarSource
 * sonarlint@sonarsource.com
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Pu


?deferred.resolve():jvm.$.get(this.params.mapUrlByCode(code,this)).then(function(){that.mapsLoaded[code]=!0,deferred.resolve()},function(){deferred.reject()}),deferred},drillDown:function(name,code){var currentMap=this.history[this.history.length-1],that=this,focusPromise=currentMap.setFocus({region:code,animate:!0}),downloadPromise=this.downloadMap(code);focusPromise.then(function(){"pending"===downloadPromise.state()&&that.spinner.show()}),downloadPromise.always(function(){that.spinner.hide()}),this.drillDownPromise=jvm.$.when(downloadPromise,focusPromise),this.drillDownPromise.then(function(){currentMap.params.container.hide(),that.maps[name]?that.maps[name].params.container.show():that.addMap(name,{map:name,multiMapLevel:currentMap.params.multiMapLevel+1}),that.history.push(that.maps[name]),that.backButton.show()})},goBack:function(){var currentMap=this.history.pop(),prevMap=this.history[this.history.length-1],that=this;currentMap.setFocus({scale:1,x:.5,y:.5,animate:!0}).then(function(){currentMap.params.container.hide(),prevMap.params.container.show(),prevMap.updateSize(),1===that.history.length&&that.backButton.hide(),prevMap.setFocus({scale:1,x:.5,y:.5,animate:!0})})}},jvm.MultiMap.defaultParams={mapNameByCode:function(code,multiMap){return code.toLowerCase()+"_"+multiMap.defaultProjection+"_en"},mapUrlByCode:function(code,multiMap){return"jquery-jvectormap-data-"+code.toLowerCase()+"-"+multiMap.defaultProjection+"-en.js"}};jQuery.fn.vectorMap('addMap', 'us_lcc',{"insets": [{"width": 220, "top": 440, "height": 192.76093370153905, "bbox": [{"y": -9264259.168284032, "x": -4695169.263875983}, {"y": -6764278.677986234, "x": -1841916.2872271966}], "left": 0}, {"width": 80, "top": 460, "height": 171.28243723090768, "bbox": [{"y": -4783904.929675324, "x": -5950370.881002157}, {"y": -4215886.671550633, "x": -56


iting time on lane 1i_0 = ",getWaitingTime("1i_0"))

        print("Inside episode counter", counter)

        counter += 1
        total_t += 1
        # batch_experience = experience[:batch_history]

        newLeftState, newRightState, qlength = makeMoves(1, 1, transition_time)

        vehicleList = traci.vehicle.getIDList()
        num_vehicles = len(vehicleList)
        if num_vehicles:
            avg = 0
            max = 0
            mini = 100
            for id in vehicleList:
                time = traci.vehicle.getAccumulatedWaitingTime(id)
                if time > max:
                    max = time

                if time < mini:
                    mini = time

                avg += time
            avg /= num_vehicles
            delay_data_avg.append(avg)
            delay_data_max.append(max)
            delay_data_min.append(mini)
            length_data_avg.append(qlength)
            delay_data_time.append(traci.simulation.getCurrentTime() / 1000)

        leftState = newLeftState
        rightState = newRightState

    plt.plot(delay_data_time, delay_data_avg, 'b-', label='avg')
    # plt.plot(delay_data_time, delay_data_min, 'g-', label='min')
    # plt.plot(delay_data_time, delay_data_max,'r-', label='max')
    plt.legend(loc='upper left')
    plt.ylabel('Waiting time per minute')
    plt.xlabel('Time in simulation (in s)')

    plt.figure()
    plt.plot(delay_data_time, length_data_avg, 'b-', label='avg')
    plt.legend(loc='upper left')
    plt.ylabel('Average Queue Length')
    plt.xlabel('Time in simulation (in s)')
    plt.show()
    AVG_Q_len_perepisode.append(sum_q_lens / 702)
    sum_q_lens = 0

print(AVG_Q_len_perepisode)

# import matplotlib.pyplot as plt
#
# plt.plot([x for x in range(num_episode)],[AVG_Q_len_perepisode], 'ro')
# plt.axis([0, num_episode, 0, 10])
# plt.show()


。\n\n-“翻译”模式: 创建包含已翻译的文本的画板，这样您就可以在各种语言之间比较画板。\n\n有关更多信息，请参阅插件中包含的自述文件。","KEYWORDS":["翻译","翻译","本地化","本地化","多语言","全球化","版面","工作效率","协作"],"ABOUT_SUMMARY":"
适用于 Adobe XD 的 World Ready 插件
在设计文件时，请记住该文件以后将被本地化为多种语言。使用 World Ready 插件，以确保您的画板中的文本适合您计划将对文件进行本地化的语言的元素。或者使用 World Ready 快速比较原始语言中的元素在被翻译成另一种语言后的样子。
安装 World Ready

 1. 启动 Adobe XD。
 2. 打开“插件”菜单。选择“发现插件”。搜索“World Ready”
 3. 要安装该插件，只需单击“安装”按钮 安装已完成。现在让我们检查一下文件是否已本地化就绪。
检查本地化字符串是否适合我们的所有语言中的元素
当我们创建设计时，我们通常会调整元素大小以适应我们正在使用的语言。但是，我们通常不会留意作为该文件的本地化目标语言的其他语言。让我们使用 World Ready 来快速检查我们的文件，以找到不适合我们设计的元素的本地化字符串。
 1. 在 Adobe XD 中打开设计后，选择您要测试的画板。注意: 在您的文件中选择一个画板。
 2. 从“插件”菜单中选择 World Ready。
 3. 在“World Ready”对话框中选择一种翻译服务。注意: 该插件默认提供 Microsoft 翻译服务。要使用其他服务，请输入该服务的有效许可证密钥。要获取许可证密钥，只需单击 API 密钥框右侧的 (?)。许可证密钥将存储在您的系统上的以下位置，对于 WIN 为“C:\\Users\\<user>\\AppData\\Local\\Packages\\Adobe.CC.XD_adky2gkssdxte\\LocalState\\plugin_settings\\com.g11n.worldready”，对于 MAC 为“\\Users\\<user>\\Library\\Application Support\\Adobe\\Adobe XD CC\\plugin_settings\\com.g11n.worldready”。
 4. 选择“突出显示”。
 5. 然后选择一种或多种您要用于测试画板的语言。注意: World Ready 当前支持列出的语言集。
 6. 单击“突


PassyEntriesEncryptedCSVFile<T>.fromFile(
        file,
        encrypter: encrypter,
      );
}
import 'package:passy/passy_data/password.dart';

class PassySearch {
  static List<PasswordMeta> searchPasswords({
    required Iterable<PasswordMeta> passwords,
    required String terms,
    List<String> tags = const [],
  }) {
    final List<PasswordMeta> _found = [];
    final List<String> _terms = terms.trim().toLowerCase().split(' ');
    for (PasswordMeta _password in passwords) {
      if (_password.tags.length < tags.length) continue;
      {
        bool testPassword(PasswordMeta value) => _password.key == value.key;

        if (_found.any(testPassword)) continue;
      }
      {
        int _positiveCount = 0;
        bool _tagMismatch = false;
        for (String tag in tags) {
          if (!_password.tags.contains(tag)) {
            _tagMismatch = true;
            break;
          }
        }
        if (_tagMismatch) continue;
        for (String _term in _terms) {
          if (_password.username.toLowerCase().contains(_term)) {
            _positiveCount++;
            continue;
          }
          if (_password.nickname.toLowerCase().contains(_term)) {
            _positiveCount++;
            continue;
          }
          for (String website in _password.websites) {
            if (website.toLowerCase().contains(_term)) {
              _positiveCount++;
              continue;
            }
          }
        }
        if (_positiveCount == _terms.length) {
          _found.add(_password);
        }
      }
    }
    return _found;
  }
}
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:convert/convert.dart';
import 'package:otp/otp.dart' as otp;
import 'package:passy/passy_data/custom_field.dart';
import 'package:passy/passy_data/password.dart';
import 'package:passy/passy_data/tfa.dart';
import 'package:pointycastle/key_derivators/scrypt.dart';
import 'package:pointycastle/key_derivators/api.dart';
import 'package:pointycastle/api.dart';
import 'package:pointycastle/block/modes/gcm.dart';
import 'package:pointycastle/block/aes.dart';

TFAType? _aegisTypeToTFAType(String type) {
  switch (type) {
    case 'totp':
      return TFAType.TOTP;
    case 'hotp':
      return TFAType.HOTP;
    case 'steam':
      return TFAType.Steam;
  }
  return null;
}

otp.Algorithm? _aegisAlgoToTFAType(String algo) {
  switch (algo) {
    case 'SHA1':
      return otp.Algorithm.SHA1;
    case 'SHA256':
      return otp.Algorithm.SHA256;
    case 'SHA512':
      return otp.Algorithm.SHA512;
  }
  return null;
}

List<Password> _convertAegis(Map<String, dynamic> db) {
  String keyPrefix = '${DateTime.now().toUtc().toIso8601String()}-import';
  List<Password> result = [];
  var entries = db['entries'];
  int i = 0;
  for (var entry in entries) {
    var name = entry['name'];
    var type = entry['type'];
    TFAType? tfaType = _aegisTypeToTFAType(type);
    if (tfaType == null) continue;
    var info = entry['info'];
    if (info is! Map<String, dynamic>) continue;
    var algo = info['algo'];
    otp.Algorithm? tfaAl


/*
 * vala-panel-appmenu
 * Copyright (C) 2018 Konstantin Pugin <ria.freelander@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 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 Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef REGISTRARMAIN_H
#define REGISTRARMAIN_H

#include <gio/gio.h>

G_BEGIN_DECLS

G_DECLARE_FINAL_TYPE(RegistrarApplication, registrar_application, REGISTRAR, APPLICATION,
                     GApplication)

RegistrarApplication *registrar_application_new();

G_END_DECLS

#endif // REGISTRARMAIN_H


blog .top-pic1,
.w3l-homeblog .top-pic2,
.w3l-homeblog .top-pic3,
.w3l-homeblog .top-pic4,
.w3l-homeblog .top-pic5,
.w3l-homeblog .top-pic6,
.w3l-homeblog .top-pic7,
.w3l-homeblog .top-pic8 {
    transition: .3s ease;
    -webkit-transition: .3s ease;
    -moz-transition: .3s ease;
    -ms-transition: .3s ease;
    -o-transition: .3s ease;
}

.w3l-homeblog .top-pic1:hover,
.w3l-homeblog .top-pic2:hover,
.w3l-homeblog .top-pic3:hover,
.w3l-homeblog .top-pic4:hover,
.w3l-homeblog .top-pic5:hover,
.w3l-homeblog .top-pic6:hover,
.w3l-homeblog .top-pic7:hover,
.w3l-homeblog .top-pic8:hover {
    transform: translateY(-0.25rem);
    /* box-shadow: rgba(46, 41, 51, 0.08) 0px 2px 4px, rgba(71, 63, 79, 0.16) 0px 5px 10px; */
    transition: .3s ease;
    -webkit-transition: .3s ease;
    -moz-transition: .3s ease;
    -ms-transition: .3s ease;
    -o-transition: .3s ease;
}

.w3l-homeblog .top-pic1:before,
.w3l-homeblog .top-pic2:before,
.w3l-homeblog .top-pic3:before,
.w3l-homeblog .top-pic4:before,
.w3l-homeblog .top-pic5:before,
.w3l-homeblog .top-pic6:before,
.w3l-homeblog .top-pic7:before,
.w3l-homeblog .top-pic8:before {
    position: absolute;
    content: '';
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: #000;
    opacity: .7;
    border-radius: var(--border-radius-full);
    z-index: -1;
}

.w3l-homeblog .author {
    display: grid;
    grid-template-columns: 40px auto;
    grid-gap: 20px;
}

.w3l-homeblog ul.blog-meta li a {
    font-size: 18px;
    color: #eee;
    font-weight: 600;
    line-height: 28px;
}

.w3l-homeblog a.blog-desc,
.w3l-homeblog a.blog-desc:hover {
    font-size: 1.5rem;
    line-height: 1.33;
    font-weight: 600;
    display: inline-block;
    color: #fff;
    margin: 0.6rem 0 1rem 0;
}

.w3l-homeblog .ser-grid a.blog-desc,
.ser-grid a.blog-desc:hover {
    font-size: 1.6rem;
}

.w3l-homeblog span.meta-value {
    color: #fff;
    font-weight: 700;
}

.w3l-homeblog .author img {
    border: 2px solid #999;
}

.w3l-homeblog p.course-sub {
    color: #fff;
    opacity: 0.9;
    text-transform: capitalize;
    font-size: 15px;
    line-height: 14px;
}

.w3l-homeblog .sup-ser-para {
    color: var(--font-color);
    max-width: 700px;
}

.w3l-homeblog .ser-grid span.fa {
    background: rgb(255 255 25


for more information.

part of pointycastle.api;

/// This kind of exception is thrown when a user tries to create an algorithm
/// or domain parameters that were not correctly registered. This can be
/// because the corresponding class was not imported, or because the algorithm
/// does not exist.
class RegistryFactoryException implements Exception {
  final String message;

  RegistryFactoryException(this.message);

  RegistryFactoryException.unknown(String algorithm, [Type type])
      : this("No algorithm registered" +
            (type != null ? " of type $type" : "") +
            " with name: $algorithm");

  RegistryFactoryException.invalid(String algorithm, [Type type])
      : this("Algorithm name $algorithm is invalid" +
            (type != null ? " of type $type" : ""));

  @override
  String toString() => "RegistryFactoryException: $message";
}
/// HMAC
///
/// Calculates a HMACs from a key and data provided on the command line.
///
/// For example:
///
///     dart hmac-sha1.dart "mykey" "Hello world!"
///
/// Note: this example use Pointy Castle WITHOUT the registry.

import 'dart:convert';
import 'dart:typed_data';

import "package:pointycastle/export.dart";

Uint8List hmacSha1(Uint8List hmacKey, Uint8List data) {
  final hmac = HMac(SHA256Digest(), 64) // HMAC SHA-256 must use block length of 64
    ..init(KeyParameter(hmacKey));

  return hmac.process(data);
}

void hmacWithOtherDigestAlgorithms(Uint8List hmacKey, Uint8List data)
{
  final hmacSha256 = HMac(SHA256Digest(), 64);
  final hmacSha512 = HMac(SHA512Digest(), 128);
  final hmacMd2 = HMac(MD2Digest(), 16);
  final hmacMd5 = HMac(MD5Digest(), 64);

  for (final hmac in [hmacSha256, hmacSha512, hmacMd2, hmacMd5]) {
    hmac.init(KeyParameter(hmacKey));
    final value = hmac.process(data);

    print('${hmac.algorithmName}: ${bin2hex(value)}');
  }
}

void main(List<String> args) {
  if (args.length != 2) {
    print('Usage: hmac-direct key data');
    return;
  }

  final key = utf8.encode(args[0]); // first argument is the key
  final data = utf8.encode(args[1]); // second argument is the data

  print('Data: "${args[1]}"');
  final hmacValue = hmacSha1(key, data);
  //print('HMAC SHA-1: $hmacValue');
  print('HMAC SHA-1: ${bin2hex(hmacValue)}');

  hmacWithOtherDigestAlgorithms(key, data);
}

//----------------------------------------------------------------
/// Represent bytes in hexadecimal
///
/// If a [separator] is provided, it is placed the hexadecimal characters
/// representing each byte. Otherwise, all the hexadecimal characters are
/// simply concatenated together.

String bin2hex(Uint8List bytes, {String separator, int wrap}) {
  var len = 0;
  final buf = StringBuffer();
  for (final b in bytes) {
    final s = b.toRadixString(16);
    if (buf.isNotEmpty && separator != null) {
      buf.write(separator);
      len += separator.length;
    }

    if (wrap != null && wrap < len + 2) {
      buf.write('\n');
      len = 0;
    }

    buf.write('${(s.length == 1) ? '0' : ''}$s');
    len += 2;
  }
  return buf.toString();
}
/// En


Hgs8FnsrPRfpncrREXAFg3__112onfvp_fgevatVpAF2_11pune_genvgfVpRRAF2_9nyybpngbeVpRRRR:
nop
.data
.globl b__MA6tbbtyr8cebgbohs8vagreany32vzcyvpvg_jrnx_zrffntr_bapr_vavg_R
.type b__MA6tbbtyr8cebgbohs8vagreany32vzcyvpvg_jrnx_zrffntr_bapr_vavg_R,%object
b__MA6tbbtyr8cebgbohs8vagreany32vzcyvpvg_jrnx_zrffntr_bapr_vavg_R:
.space __SIZEOF_POINTER__
.text
.weak b__MA6tbbtyr8cebgbohs13ErcrngrqSvryqVzR9PbclNeenlRCzCXzv
.type b__MA6tbbtyr8cebgbohs13ErcrngrqSvryqVzR9PbclNeenlRCzCXzv,%function
b__MA6tbbtyr8cebgbohs13ErcrngrqSvryqVzR9PbclNeenlRCzCXzv:
nop
.data
.weak b__MA6tbbtyr8cebgbohs13ErcrngrqSvryqVsR14xErcUrnqreFvmrR
.type b__MA6tbbtyr8cebgbohs13ErcrngrqSvryqVsR14xErcUrnqreFvmrR,%object
b__MA6tbbtyr8cebgbohs13ErcrngrqSvryqVsR14xErcUrnqreFvmrR:
.space __SIZEOF_POINTER__
.text
.weak b__MAX6tbbtyr8cebgbohs13ErcrngrqSvryqVzR5rzcglRi
.type b__MAX6tbbtyr8cebgbohs13ErcrngrqSvryqVzR5rzcglRi,%function
b__MAX6tbbtyr8cebgbohs13ErcrngrqSvryqVzR5rzcglRi:
nop
.data
.weak b__MTIMA6tbbtyr8cebgbohs8vagreany12FuhgqbjaQngn3trgRiR4qngn
.type b__MTIMA6tbbtyr8cebgbohs8vagreany12FuhgqbjaQngn3trgRiR4qngn,%object
b__MTIMA6tbbtyr8cebgbohs8vagreany12FuhgqbjaQngn3trgRiR4qngn:
.space __SIZEOF_POINTER__
.text
.weak b__MA6tbbtyr8cebgbohs13ErcrngrqSvryqVyR7ErfreirRv
.type b__MA6tbbtyr8cebgbohs13ErcrngrqSvryqVyR7ErfreirRv,%function
b__MA6tbbtyr8cebgbohs13ErcrngrqSvryqVyR7ErfreirRv:
nop
.text
.globl b__MA6tbbtyr8cebgbohs8vagreany19VzcyvpvgJrnxZrffntr16qrsnhyg_vafgnaprRi
.type b__MA6tbbtyr8cebgbohs8vagreany19VzcyvpvgJrnxZrffntr16qrsnhyg_vafgnaprRi,%function
b__MA6tbbtyr8cebgbohs8vagreany19VzcyvpvgJrnxZrffntr16qrsnhyg_vafgnaprRi:
nop


al query = """
            SELECT array_to_string(
                array(select substr('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', trunc(random() * 62)::integer + 1, 1)
            FROM   generate_series(1, 100000)), '');
        """.trimIndent()
        val stmt = this.proxy.connection.createStatement()
        val result = stmt.executeQuery(query)
        while (result.next()) {
            val randomString = result.getString("array_to_string")
            println(randomString.length)
            println(randomString.length == 100000)
            assertTrue(randomString.length == 100000)
        }

        this.proxy.eventService.assertQueryIsAudited(query)
    }

    @Test
    fun `Must support CRUD operations`() {
        // The logic is - the tests executes query against the proxy, and the result is observed via the direct connection.
        // For the select query, the direct connection is no used.
        val createTableQuery = "CREATE TABLE IF NOT EXISTS proxy_test_crud (id INTEGER,random VARCHAR(32));"
        val insertQuery = "INSERT INTO proxy_test_crud(id, random) VALUES (1, 'test');"
        val selectQuery = "SELECT * FROM proxy_test_crud;"
        val updateQuery = "UPDATE proxy_test_crud SET random='TSET' WHERE id = 1;"
        val deleteQuery = "DELETE FROM proxy_test_crud WHERE id = 1;"
        val stmt = this.proxy.connection.createStatement()
        stmt.executeUpdate(createTableQuery)
        // Create/Insert
        val insertStmt = this.proxy.connection.createStatement()
        insertStmt.executeUpdate(insertQuery)
        val selectStmt = this.directConnection.createStatement()
        val resultPostInsert = selectStmt.executeQuery(selectQuery)
        while (resultPostInsert.next()) {
            val id = resultPostInsert.getInt("id")
            val random = resultPostInsert.getString("random")
            assertTrue(id == 1)
            assertTrue(random == "test")
        }
        // Read/Select
        val proxySelectStmt = this.proxy.connection.createStatement()
        val resultFromSelect = proxySelectStmt.executeQuery(selectQuery)
        while (resultFromSelect.next()) {
            val id = resultFromSelect.getInt("id")
            val random = resultFromSelect.getString("random")
            assertTrue(id == 1)
            assertTrue(random == "test")
        }
        // Update
        val updateStmt = this.proxy.connection.createStatement()
        updateStmt.executeUpdate(updateQuery)
        val resultPostUpdate = selectStmt.executeQuery(selectQuery)
        while (resultPostUpdate.next()) {
            val id = resultPostUpdate.getInt("id")
            val random = resultPostUpdate.getString("random")
            assertTrue(id == 1)
            assertTrue(random == "TSET")
        }

        // Delete
        val deleteStmt = this.proxy.connection.createStatement()
        deleteStmt.executeUpdate(deleteQuery)
        val resultPostDelete = selectStmt.executeQuery(selectQuery)
        var size = 0
        while (resultPostDelete.next()) {
            size++
        }
        assertTrue(size == 0)

        this.proxy.eventService.assertQueryIsAudited(selectQuery)
        this.proxy.eventService.assertQueryIsAudited(insertQuery)
        this.proxy.eventService.assertQueryIsAudited(updateQuery)
        this.proxy.eventService.assertQueryIsAudited(deleteQuery)
    }

    @Test
    fun `Postgres proxy must support creating and executing stored procedures`() {
        val createTableQuery = "CREATE TABLE IF NOT EXISTS proxy_test_procedures (id INTEGER,random VARCHAR(32));"
        val storedProcedure = """
        CREATE OR REPLACE PROCEDURE addTestRow(IN random VARCHAR(32))
        LANGUAGE plpgsql
        AS $$
        BEGIN


 getSpaceConsumed(foo).getTypeSpaces().get(StorageType.SSD);
    assertEquals(file1Len, ssdConsumed);

    // move file from foo to bar
    try {
      dfs.rename(createdFile1foo, createdFile1bar);
      fail("Should have failed with QuotaByStorageTypeExceededException ");
    } catch (Throwable t) {
      LOG.info("Got expected exception ", t);
    }

    ContentSummary cs = dfs.getContentSummary(foo);
    assertEquals(cs.getSpaceConsumed(), file1Len * REPLICATION);
    assertEquals(cs.getTypeConsumed(StorageType.SSD), file1Len);
    assertEquals(cs.getTypeConsumed(StorageType.DISK), file1Len * 2);
  }

  /**
   * Test if the quota can be correctly updated for create file even
   * QuotaByStorageTypeExceededException is thrown
   */
  @Test(timeout = 60000)
  public void testQuotaByStorageTypeExceptionWithFileCreate() throws Exception {
    final Path foo = new Path(dir, "foo");
    Path createdFile1 = new Path(foo, "created_file1.data");
    dfs.mkdirs(foo);

    dfs.setStoragePolicy(foo, HdfsConstants.ONESSD_STORAGE_POLICY_NAME);
    dfs.setQuotaByStorageType(foo, StorageType.SSD, BLOCKSIZE * 4);

    INode fnode = getINode4Write(foo);

    // Create the 1st file of size 2 * BLOCKSIZE under directory "foo" and expect no exception
    long file1Len = BLOCKSIZE * 2;
    int bufLen = BLOCKSIZE / 16;
    DFSTestUtil.createFile(dfs, createdFile1, bufLen, file1Len, BLOCKSIZE, REPLICATION, seed);

    //let time for the quota monitor to apply quota
    Thread.sleep(1000);
    long currentSSDConsumed = getSpaceConsumed(foo).getTypeSpaces().get(StorageType.SSD);
    assertEquals(file1Len, currentSSDConsumed);

    // Create the 2nd file of size 1.5 * BLOCKSIZE under directory "foo" and expect no exception
    Path createdFile2 = new Path(foo, "created_file2.data");
    long file2Len = BLOCKSIZE + BLOCKSIZE / 2;
    DFSTestUtil.createFile(dfs, createdFile2, bufLen, file2Len, BLOCKSIZE, REPLICATION, seed);

    //let time for the quota monitor to apply quota
    Thread.sleep(1000);
    currentSSDConsumed = getSpaceConsumed(foo).getTypeSpaces().get(StorageType.SSD);

    assertEquals(file1Len + file2Len, currentSSDConsumed);

    // Create the 3rd file of size BLOCKSIZE under directory "foo" and expect quota exceeded exception
    Path createdFile3 = new Path(foo, "created_file3.data");
    long file3Len = BLOCKSIZE;

    try {
      DFSTestUtil.createFile(dfs, createdFile3, bufLen, file3Len, BLOCKSIZE, REPLICATION, seed);
      fail("Should have failed with QuotaByStorageTypeExceededException ");
    } catch (Throwable t) {
      LOG.info("Got expected exception ", t);

      //let time for the quota monitor to apply quota
      Thread.sleep(1000);
      currentSSDConsumed = getSpaceConsumed(foo).getTypeSpaces().get(StorageType.SSD);
      assertEquals(file1Len + file2Len, currentSSDConsumed);
    }
  }

  @Test(timeout = 60000)
  public void testQuotaByStorageTypeParentOffChildOff() throws Exception {
    final Path parent = new Path(dir, "parent");
    final Path child = new Path(parent, "child");
    dfs.mkdirs(parent);
    dfs.mkdirs(child);

    dfs.setStoragePolicy(parent, HdfsConstants.ONESSD_STORAGE_POLICY_NAME);

    // Create file of size 2.5 * BLOCKSIZE under child directory.
    // Since both parent and child directory do not have SSD quota set,


json[r'imagePullSecrets'] = this.imagePullSecrets;
    json[r'initContainers'] = this.initContainers;
    if (this.nodeName != null) {
      json[r'nodeName'] = this.nodeName;
    } else {
      json[r'nodeName'] = null;
    }
    json[r'nodeSelector'] = this.nodeSelector;
    if (this.os != null) {
      json[r'os'] = this.os;
    } else {
      json[r'os'] = null;
    }
    json[r'overhead'] = this.overhead;
    if (this.preemptionPolicy != null) {
      json[r'preemptionPolicy'] = this.preemptionPolicy;
    } else {
      json[r'preemptionPolicy'] = null;
    }
    if (this.priority != null) {
      json[r'priority'] = this.priority;
    } else {
      json[r'priority'] = null;
    }
    if (this.priorityClassName != null) {
      json[r'priorityClassName'] = this.priorityClassName;
    } else {
      json[r'priorityClassName'] = null;
    }
    json[r'readinessGates'] = this.readinessGates;
    if (this.restartPolicy != null) {
      json[r'restartPolicy'] = this.restartPolicy;
    } else {
      json[r'restartPolicy'] = null;
    }
    if (this.runtimeClassName != null) {
      json[r'runtimeClassName'] = this.runtimeClassName;
    } else {
      json[r'runtimeClassName'] = null;
    }
    if (this.schedulerName != null) {
      json[r'schedulerName'] = this.schedulerName;
    } else {
      json[r'schedulerName'] = null;
    }
    if (this.securityContext != null) {
      json[r'securityContext'] = this.securityContext;
    } else {
      json[r'securityContext'] = null;
    }
    if (this.serviceAccount != null) {
      json[r'serviceAccount'] = this.serviceAccount;
    } else {
      json[r'serviceAccount'] = null;
    }
    if (this.serviceAccountName != null) {
      json[r'serviceAccountName'] = this.serviceAccountName;
    } else {
      json[r'serviceAccountName'] = null;
    }
    if (this.setHostnameAsFQDN != null) {
      json[r'setHostnameAsFQDN'] = this.setHostnameAsFQDN;
    } else {
      json[r'setHostnameAsFQDN'] = null;
    }
    if (this.shareProcessNamespace != null) {
      json[r'shareProcessNamespace'] = this.shareProcessNamespace;
    } else {
      json[r'shareProcessNamespace'] = null;
    }
    if (this.subdomain != null) {
      json[r'subdomain'] = this.subdomain;
    } else {
      json[r'subdomain'] = null;
    }
    if (this.terminationGracePeriodSeconds != null) {
      json[r'terminationGracePeriodSeconds'] =
          this.terminationGracePeriodSeconds;
    } else {
      json[r'terminationGracePeriodSeconds'] = null;
    }
    json[r'tolerations'] = this.tolerations;
    json[r'topologySpreadConstraints'] = this.topologySpreadConstraints;
    json[r'volumes'] = this.volumes;
    return json;
  }

  /// Returns a new [IoK8sApiCoreV1PodSpec] instance and imports its values from
  /// [value] if it's a [Map], null otherwise.
  // ignore: prefer_constructors_over_static_methods
  static IoK8sApiCoreV1PodSpec? fromJson(dynamic value) {
    if (value is Map) {
      final json = value.cast<String, dynamic>();

      // Ensure that the map contains the required keys.
      // Note 1: the values aren't checked for validity beyond being non-null.
      // Note 2: this code is stripped in release mode!
      assert(() {
        req


uctionOpportunity>> result;

  std::set<uint32_t> merge_block_ids;
  for (auto* function : GetTargetFunctions(context, target_function)) {
    for (auto& block : *function) {
      auto merge_block_id = block.MergeBlockIdIfAny();
      if (merge_block_id) {
        merge_block_ids.insert(merge_block_id);
      }
    }
  }

  // Consider each loop construct header in the module.
  for (auto* function : GetTargetFunctions(context, target_function)) {
    for (auto& block : *function) {
      auto loop_merge_inst = block.GetLoopMergeInst();
      if (!loop_merge_inst) {
        // This is not a loop construct header.
        continue;
      }

      uint32_t continue_block_id =
          loop_merge_inst->GetSingleWordOperand(kContinueNodeIndex);

      // Check whether the loop construct's continue target is the merge block
      // of some structured control flow construct.  If it is, we cautiously do
      // not consider applying a transformation.
      if (merge_block_ids.find(continue_block_id) != merge_block_ids.end()) {
        continue;
      }

      // Check whether the loop header block is also the continue target. If it
      // is, we cautiously do not consider applying a transformation.
      if (block.id() == continue_block_id) {
        continue;
      }

      // Check whether the loop construct header dominates its merge block.
      // If not, the merge block must be unreachable in the control flow graph
      // so we cautiously do not consider applying a transformation.
      auto merge_block_id =
          loop_merge_inst->GetSingleWordInOperand(kMergeNodeIndex);
      if (!context->GetDominatorAnalysis(function)->Dominates(block.id(),
                                                              merge_block_id)) {
        continue;
      }

      // Check whether the loop construct merge block postdominates the loop
      // construct header.  If not (e.g. because the loop contains OpReturn,
      // OpKill or OpUnreachable), we cautiously do not consider applying
      // a transformation.
      if (!context->GetPostDominatorAnalysis(function)->Dominates(
              merge_block_id, block.id())) {
        continue;
      }

      // We can turn this structured loop into a selection, so add the
      // opportunity to do so.
      result.push_back(
          MakeUnique<StructuredLoopToSelectionReductionOpportunity>(context,
                                                                    &block));
    }
  }
  return result;
}

std::string StructuredLoopToSelectionReductionOpportunityFinder::GetName()
    const {
  return "StructuredLoopToSelectionReductionOpportunityFinder";
}

}  // namespace reduce
}  // namespace spvtools
// Copyright (c) 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by 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.

#include "source/reduce/remove_struct_member_reduction_opportunity.h"

#include "source/opt/ir_context.h"

namespace spvtools {
namespace reduce {

bool RemoveStructMemberReductionOpportunity::PreconditionHolds() {


les =  previousNumOfBoxes + mUpdateData_CreatedHandleSize;
	//const PxU32 numHandles =  mPreviousNumOfBoxes + mUpdateData_CreatedHandleSize;

	if(numHandles == 0)
		return;

	PxU32 nbProjections = numHandles*2;

	//we need to pad the number of projection to the multiply of 4
	nbProjections = (nbProjections + 3) & (~3);

	runRadixSort(nbProjections, mRadixSortWORDescBuf.getDevicePtr());
	GPU_DEBUG_STREAM(mStream, "GPU radix sort fail!!\n")
}

// PT:
// In:
//   bpDesc->boxHandles
// Out:
//   bpDesc->boxNewSapBox1D or bpDesc->boxSapBox1D
void PxgCudaBroadPhaseSap::initializeSapBoxKernel(const PxU32 numHandles, bool isNew)
{
	PX_PROFILE_ZONE("PxgCudaBroadPhaseSap.initializeSapBoxKernel", mContextID);

	const PxU32 nbBlocks = ((numHandles*2) + PxgBPKernelBlockDim::BP_INITIALIZE_SAPBOX-1)/ PxgBPKernelBlockDim::BP_INITIALIZE_SAPBOX;
	if(nbBlocks)
	{
		CUdeviceptr bpDescd = mBPDescBuf.getDevicePtr();
		KERNEL_PARAM_TYPE kernelParams[] = { CUDA_KERNEL_PARAM(bpDescd), CUDA_KERNEL_PARAM(numHandles), CUDA_KERNEL_PARAM(isNew) };

		_launch<GPU_BP_DEBUG>(PROLOG, PxgKernelIds::BP_INITIALIZE_SAPBOX, nbBlocks, 1, 1, PxgBPKernelBlockDim::BP_INITIALIZE_SAPBOX, 1, 1, 0, EPILOG);
	}
}

// PT:
// In:
//    bpDesc->updateData_fpBounds
//    bpDesc->updateData_contactDistances
//    bpDesc->updateData_BoxesCapacity
// Out:
//    bpDesc->newIntegerBounds
void PxgCudaBroadPhaseSap::translateAABBsKernel()
{
	PX_PROFILE_ZONE("PxgCudaBroadPhaseSap.translateAABBsKernel", mContextID);

	if(mUpdateData_BoxesCapacity == 0)
		return;

	CUdeviceptr bpDescd = mBPDescBuf.getDevicePtr();
	KERNEL_PARAM_TYPE kernelParams[] = { CUDA_KERNEL_PARAM(bpDescd) };

	const PxU32 aabbsPerBlock = PxgBPKernelBlockDim::BP_TRANSLATE_AABBS/8;
	const PxU32 nbBlocks = (mUpdateData_BoxesCapacity + aabbsPerBlock-1)/aabbsPerBlock;	// PT: do we really need mBoxesCapacity here?

	_launch<GPU_BP_DEBUG>(PROLOG, PxgKernelIds::BP_TRANSLATE_AABBS, nbBlocks, 1, 1, PxgBPKernelBlockDim::BP_TRANSLATE_AABBS, 1, 1, 0, EPILOG);
}

void PxgCudaBroadPhaseSap::markRemovedPairsKernel()
{
	PX_PROFILE_ZONE("PxgCudaBroadPhaseSap.markRemovedPairsKernel", mContextID);

	if(mUpdateData_RemovedHandleSize)
	{
		CUdeviceptr bpDescd = mBPDescBuf.getDevicePtr();
		KERNEL_PARAM_TYPE kernelParams[] = { CUDA_KERNEL_PARAM(bpDescd) };

		_launch<GPU_BP_DEBUG>(PROLOG, PxgKernelIds::BP_MARK_DELETEDPAIRS, PxgBPKernelGridDim::BP_UPDATE_DELETEDPAIRS, 1, 1, PxgBPKernelBlockDim::BP_UPDATE_DELETEDPAIRS, 1, 1, 0, EPILOG);
	}
}

void PxgCudaBroadPhaseS


(move.x, move.y) >= helper.texSize);
    // check if we are completely invalid anyway (teleported) and then better not change depth
    if (z_moved)
    {
      if (scroller && !forceInvalidate && !fullUpdate)
      {
        if (inTransition)
        {
          backFrame.zn = current.zn;
          backFrame.zf = current.zf;
        }

        changeDepth(tex, scroller, z_scale, z_ofs);
        return BeforeRenderReturned{helper.texSize * helper.texSize, true, true};
      }
      else // if we are completely invalid anyway, better invalidate it
      {
        invalidate(true);
      }
    }
  }

  IPoint2 newTexelsOrigin = getTexelOrigin(pos);

  const IPoint2 halfTexSize(helper.texSize >> 1, helper.texSize >> 1);

  int texelsMoveThreshold = ((move_part * helper.texSize) + TEXEL_ALIGN - 1);
  texelsMoveThreshold = max((int)0, min(texelsMoveThreshold, (int)helper.texSize));
  texelsMoveThreshold = texelsMoveThreshold - texelsMoveThreshold % TEXEL_ALIGN;
  const int maxTexelsToUpdate = clamp(max_update_part, 0.001f, 1.f) * helper.texSize * helper.texSize;

  IPoint2 move = abs(helper.curOrigin - newTexelsOrigin);
  if (move.x < texelsMoveThreshold && move.y < texelsMoveThreshold && !invalidRegions.size())
  {
    // Cascade is fully updated, the scrolled depth range is now valid again.
    bool scrolledPreviously = scrolledDepthMin > 0 || scrolledDepthMax < 1;
    scrolledDepthMin = 0;
    scrolledDepthMax = 1;
    return BeforeRenderReturned{0, scrolledPreviously};
  }
  const int dynamicThreshold = invalidRegions.size() ? min(texelsMoveThreshold * 2, (int)helper.texSize / 2) : texelsMoveThreshold;
  // preferrably update already invalidRegions, unless we moved even more
  // so we have less invalid regions
  bool ret = move.x >= dynamicThreshold || move.y >= dynamicThreshold;
  if (!ret && invalidRegions.empty())
  {
    return BeforeRenderReturned{0, endFrameTransition(tex)};
  }

  Tab<IBBox2> regionsToDiscard(framemem_ptr());
  if (ret)
  {
    const float fullUpdateThreshold = optimizeBigQuadsRender ? 0.75 : 0.45; // -V547
    const int fullUpdateThresholdTexels = fullUpdateThreshold * helper.texSize;
    if (max(move.x, move.y) < fullUpdateThresholdTexels) // if distance travelled is too big, there is no need to update movement in
                                                         // two steps
    {
      if (move.x < move.y)
        newTexelsOrigin.x = helper.curOrigin.x;
      else
        newTexelsOrigin.y = helper.curOrigin.y;
    }

    ToroidalGatherCallback::RegionTab regions0;
    ToroidalGatherCallback shadowcb(regions0);
    uint32_t texelsUpdated = (uint32_t)max((int)0, toroidal_update(newTexelsOrigin, helper, fullUpdateThresholdTexels, shadowcb));
    current.torOfs = point2((helper.mainOrigin - helper.curOrigin) % helper.texSize) / helper.texSize;
    current.alignedOrigin = point2(helper.curOrigin) * texelSize;

    G_ASSERT(texelsUpdated > 0);
    clip_list_to(notRenderedRegions, get_texture_box(helper));
    toroidal_clip_regions(helper, invalidRegions);
    if (texelsUpdated <= maxTexelsToUpdate * 2 || !optimize


kDemandedConstant(
    SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
    TargetLoweringOpt &TLO) const {
  // Delay optimization, so we don't have to deal with illegal types, or block
  // optimizations.
  if (!TLO.LegalOps)
    return false;

  // Only optimize AND for now.
  if (Op.getOpcode() != ISD::AND)
    return false;

  EVT VT = Op.getValueType();

  // Ignore vectors.
  if (VT.isVector())
    return false;

  assert(VT == MVT::i32 && "Unexpected integer type");

  // Make sure the RHS really is a constant.
  ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
  if (!C)
    return false;

  unsigned Mask = C->getZExtValue();

  unsigned Demanded = DemandedBits.getZExtValue();
  unsigned ShrunkMask = Mask & Demanded;
  unsigned ExpandedMask = Mask | ~Demanded;

  // If the mask is all zeros, let the target-independent code replace the
  // result with zero.
  if (ShrunkMask == 0)
    return false;

  // If the mask is all ones, erase the AND. (Currently, the target-independent
  // code won't do this, so we have to do it explicitly to avoid an infinite
  // loop in obscure cases.)
  if (ExpandedMask == ~0U)
    return TLO.CombineTo(Op, Op.getOperand(0));

  auto IsLegalMask = [ShrunkMask, ExpandedMask](unsigned Mask) -> bool {
    return (ShrunkMask & Mask) == ShrunkMask && (~ExpandedMask & Mask) == 0;
  };
  auto UseMask = [Mask, Op, VT, &TLO](unsigned NewMask) -> bool {
    if (NewMask == Mask)
      return true;
    SDLoc DL(Op);
    SDValue NewC = TLO.DAG.getConstant(NewMask, DL, VT);
    SDValue NewOp = TLO.DAG.getNode(ISD::AND, DL, VT, Op.getOperand(0), NewC);
    return TLO.CombineTo(Op, NewOp);
  };

  // Prefer uxtb mask.
  if (IsLegalMask(0xFF))
    return UseMask(0xFF);

  // Prefer uxth mask.
  if (IsLegalMask(0xFFFF))
    return UseMask(0xFFFF);

  // [1, 255] is Thumb1 movs+ands, legal immediate for ARM/Thumb2.
  // FIXME: Prefer a contiguous sequence of bits for other optimizations.
  if (ShrunkMask < 256)
    return UseMask(ShrunkMask);

  // [-256, -2] is Thumb1 movs+bics, legal immediate for ARM/Thumb2.
  // FIXME: Prefer a contiguous sequence of bits for other optimizations.
  if ((int)ExpandedMask <= -2 && (int)ExpandedMask >= -256)
    return UseMask(ExpandedMask);

  // Potential improvements:
  //
  // We could try to recognize lsls+lsrs or lsrs+lsls pairs here.
  // We could try to prefer Thumb1 immediates which can be lowered to a
  // two-instruction sequence.
  // We could try to recognize more legal ARM/Thumb2 immediates here.

  return false;
}

bool ARMTargetLowering::SimplifyDemandedBitsForTargetNode(
    SDValue Op, const APInt &OriginalDemandedBits,
    const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
    unsigned Depth) const {
  unsigned Opc = Op.getOpcode();

  switch (Opc) {
  case ARMISD::ASRL:
  case ARMISD::LSRL: {
    // If this is result


白，容易理解：

1. 谁可以切确的知道哪些属性被 adapter 使用过？

   当然是被调用过的 adapter 自己了，每个 adapter 在执行完成后，都可以给出自己使用属性集合，mixer 只要做一个简单收集就可以拿到这个信息。

2. mixer 知道了，怎么告之 envoy？

   不是有个现成的 response 嘛，将前面收集到的属性集合通过 response 传递回 envoy 就是了。

搞定！现在再重新看回前面给出的这个图片，就很容易理解了。

![img](https://skyao.io/post/201804-istio-mixer-cache-concepts/images/referenced-attributes.jpg)

## 下一步

在介绍完基本概念之后，我们将在下一篇文章中开始讲解 mixer cache 的工作原理，然后在更后面的章节中深入实现细节。
---
title: "社区投稿风格指南"
linkTitle: "风格指南"
date: 2020-06-09T06:00:00+08:00
summary: "本指南为社区投稿提供了一套风格指南规范。"
type: "book"
weight: 1
---

本指南为云原生社区博客风格指南。主要目的为：

- 提高中文文案可读性
- 统一文档风格，保证社区投稿对外输出风格一致
- 避免不同的文档作者对同一问题反复作出决策，降低与文档相关的沟通成本

## 文件头

文件头部配置为 Hugo 静态网站编译所必须的，所有投稿文章都需要在投稿文件的头部添加文件头（文件头前后使用三个短横线“-”），例如：

```yaml
---
title: "文章标题"
date: 2020-06-09T06:00:00+08:00
summary: "对本文的摘要或者描述。"
authors: ["张三","李四"]
translators: ["张三","李四"]
categories: ["Kubernetes"]
tags: ["Kubernetes", "源码分析"]
links:
  - icon: language
    icon_pack: fa
    name: 阅读英文版原文
    url: https://www.example.com
---
```

其中：

- `title`: 表示投稿的标题，例如：`社区投稿风格指南`。
- `date`: 表示投稿的时间，使用 RFC3999 格式，例如：`2020-06-09T06:00:00+08


171
// CHECK:  encoding: [0x62,0xe3,0xfd,0x48,0x09,0xf7,0xab]
          vrndscalepd zmm22, zmm7, 171

// CHECK: vrndscalepd zmm22 {k1}, zmm7, 171
// CHECK:  encoding: [0x62,0xe3,0xfd,0x49,0x09,0xf7,0xab]
          vrndscalepd zmm22 {k1}, zmm7, 171

// CHECK: vrndscalepd zmm22 {k1} {z}, zmm7, 171
// CHECK:  encoding: [0x62,0xe3,0xfd,0xc9,0x09,0xf7,0xab]
          vrndscalepd zmm22 {k1} {z}, zmm7, 171

// CHECK: vrndscalepd zmm22, zmm7, {sae}, 171
// CHECK:  encoding: [0x62,0xe3,0xfd,0x18,0x09,0xf7,0xab]
          vrndscalepd zmm22, zmm7, {sae}, 171

// CHECK: vrndscalepd zmm22, zmm7, 123
// CHECK:  encoding: [0x62,0xe3,0xfd,0x48,0x09,0xf7,0x7b]
          vrndscalepd zmm22, zmm7, 123

// CHECK: vrndscalepd zmm22, zmm7, {sae}, 123
// CHECK:  encoding: [0x62,0xe3,0xfd,0x18,0x09,0xf7,0x7b]
          vrndscalepd zmm22, zmm7, {sae}, 123

// CHECK: vrndscalepd zmm22, zmmword ptr [rcx], 123
// CHECK:  encoding: [0x62,0xe3,0xfd,0x48,0x09,0x31,0x7b]
          vrndscalepd zmm22, zmmword ptr [rcx], 123

// CHECK: vrndscalepd zmm22, zmmword ptr [rax + 8*r14 + 291], 123
// CHECK:  encoding: [0x62,0xa3,0xfd,0x48,0x09,0xb4,0xf0,0x23,0x01,0x00,0x00,0x7b]
          vrndscalepd zmm22, zmmword ptr [rax + 8*r14 + 291], 123

// CHECK: vrndscalepd zmm22, qword ptr [rcx]{1to8}, 123
// CHECK:  encoding: [0x62,0xe3,0xfd,0x58,0x09,0x31,0x7b]
          vrndscalepd zmm22, qword ptr [rcx]{1to8}, 123

// CHECK: vrndscalepd zmm22, zmmword ptr [rdx + 8128], 123
// CHECK:  encoding: [0x62,0xe3,0xfd,0x48,0x09,0x72,0x7f,0x7b]
          vrndscalepd zmm22, zmmword ptr [rdx + 8128], 123

// CHECK: vrndscalepd zmm22, zmmword ptr [rdx + 8192], 123
// CHECK:  encoding: [0x62,0xe3,0xfd,0x48,0x09,0xb2,0x00,0x20,0x00,0x00,0x7b]
          vrndscalepd zmm22, zmmword ptr [rdx + 8192], 123

// CHECK: vrndscalepd zmm22, zmmword ptr [rdx - 8192], 123
// CHECK:  encoding: [0x62,0xe3,0xfd,0x48,0x09,0x72,0x80,0x7b]
          vrndscalepd zmm22,


onnect(addr, auth.host())?
        .await
        .map_err(Into::into)
}

async fn connect_0rtt(
    uri: &http::Uri,
    endpoint: &Endpoint,
) -> Result<NewConnection, Box<dyn std::error::Error>> {
    let auth = uri
        .authority()
        .ok_or("destination must have a host")?
        .clone();

    let port = auth.port_u16().unwrap_or(443);

    // dns me!
    let addr = tokio::net::lookup_host((auth.host(), port))
        .await?
        .next()
        .ok_or("dns found no addresses")?;

    debug!("DNS Lookup for {:?}: {:?}", uri, addr);

    endpoint
        .connect(addr, auth.host())?
        .into_0rtt()
        .map(|x| x.0)
        .map_err(|_| "0RTT failed".to_string().into())
}

struct YesVerifier;

impl rustls::client::ServerCertVerifier for YesVerifier {
    fn verify_server_cert(
        &self,
        _end_entity: &Certificate,
        _intermediates: &[Certificate],
        _server_name: &ServerName,
        _scts: &mut dyn Iterator<Item = &[u8]>,
        _ocsp_response: &[u8],
        _now: SystemTime,
    ) -> Result<ServerCertVerified, rustls::Error> {
        Ok(ServerCertVerified::assertion())
    }
}
<reponame>nya3jp/icfpc2021<gh_stars>0
// Copyright 2021 <NAME>
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use geom::schema::{Hole, Pose, Problem, UsedBonus};

use geom::*;

pub fn distance(p1: &Point, p2: &Point) -> usize {
    let d = *p1 - *p2;
    Point::dot(d, d) as usize
}

pub fn dislike(hole: &Hole, pose: &Pose) -> usize {
    let mut dislike = 0;
    for p1 in &hole.polygon.vertices {
        dislike += pose
            .vertices
            .iter()
            .map(|p2| distance(p1, p2))
            .min()
            .unwrap()
    }
    dislike as usize
}

pub fn bonus(problem: &Problem, pose: &Pose) -> Vec<UsedBonus> {
    let mut bonuses = vec![];
    for b in &problem.bonuses {
        for v in &pose.vertices {
            if v == &b.position {
                bonuses.push(UsedBonus {
                    bonus: b.bonus,
                    problem: b.problem,
                    edge: None
                });
            }
            eprintln!("b, v: {:?}, {:?}", v, &b.position);
        }
    }
    bonuses
}

fn is_inside_hole_internal(
    problem: &Problem,
    pose: &Pose,
    changed: Option<&[usize]>,
    verbose: bool,
) -> bool {
    // The vertices in pose should match with figure.
    if problem.figure.vertices.len() != pose.vertices.len() {
        if verbose {
            eprintln!(
                "Edge mismatch: {:?}, {:?}",
                problem.figure.vert