/*
 * Copyright 2013 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#ifndef SkLumaColorFilter_DEFINED
#define SkLumaColorFilter_DEFINED

#include "SkColorFilter.h"

/**
 *  Luminance-to-alpha color filter, as defined in
 *  http://www.w3.org/TR/SVG/masking.html#Masking
 *  http://www.w3.org/TR/css-masking/#MaskValues
 *
 *  The resulting color is black with transparency equal to the
 *  luminance value modulated by alpha:
 *
 *    C' = [ Lum * a, 0, 0, 0 ]
 *
 */
class SK_API SkLumaColorFilter : public SkColorFilter {
public:
    static SkColorFilter* Create();

    virtual void filterSpan(const SkPMColor src[], int count, SkPMColor[]) const SK_OVERRIDE;

#if SK_SUPPORT_GPU
    virtual GrEffectRef* asNewEffect(GrContext*) const SK_OVERRIDE;
#endif

    SkDEVCODE(virtual void toString(SkString* str) const SK_OVERRIDE;)
    SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(SkLumaColorFilter)

protected:
    SkLumaColorFilter(SkReadBuffer& buffer);
    virtual void flatten(SkWriteBuffer&) const SK_OVERRIDE;

private:
    SkLumaColorFilter();

    typedef SkColorFilter INHERITED;
};

#endif


Perform memory action */
        bis	$31, $19, $16 	# [3]
        bis	$31, 3, $17 	# [1]
	br	$31, PERFORMMEMORYACTION
.align 3
G15808:
        ldq	$18, PROCESSORSTATE_STACKCACHEDATA($14)	#  [1-]
        s8addq	$8, $18, $8 	# reconstruct SCA [3]
        ldl	$2, 0($8)	#  [2]
        ldl	$3, 4($8)	# Read from stack cache [1]
        br	$31, G15807	# [1]
.align 3
G15810:
        blbc	$19, G15809	# [1]
        extll	$2, 0, $5 	# Do the indirect thing [0di]
        br	$31, G15806	# [1-]
.align 3
G15809:
        ldq	$20, PROCESSORSTATE_BINDREAD($14)	# Load the memory action table for cycle [1]
/* TagType. */
        and	$3, 63, $19 	# Discard the CDR code [0di]
        stq	$5, PROCESSORSTATE_VMA($14)	# stash the VMA for the (likely) trap [1-]
        s4addq	$19, $20, $19 	# Adjust for a longword load [2di]
        ldl	$20, 0($19)	# Get the memory action [2]
G15812:
/* Perform memory action */
        bis	$31, $20, $16 	# [3]
        bis	$31, 2, $17 	# [1]
	br	$31, PERFORMMEMORYACTION
.align 3
G15798:
        ldq	$18, PROCESSORSTATE_STACKCACHEDATA($14)	#  [1-]
        s8addq	$8, $18, $8 	# reconstruct SCA [3]
        ldl	$6, 0($8)	#  [2]
        ldl	$7, 4($8)	# Read from stack cache [1]
        br	$31, G15797	# [1]
.align 3
G15800:
        blbc	$19, G15799	# [1]
        extll	$6, 0, $1 	# Do the indirect thing [0di]
        br	$31, G15796	# [1-]
.align 3
G15799:
        ldq	$20, PROCESSORSTATE_BINDREAD($14)	# Load the memory action table for cycle [1]
/* TagType. */
        and	$7, 63, $19 	# Discard the CDR code [0di]
        stq	$1, PROCESSORSTATE_VMA($14)	# stash the VMA for the (likely) trap [1-]
        s4addq	$19, $20, $19 	# Adjust for a longword load [2di]
        ldl	$20, 0($19)	# Get the memory action [2]
G15802:
/* Perform memory action */
        bis	$31, $20, $16 	# [3]
        bis	$31, 2, $17 	# [1]
	br	$31, PERFORMMEMORYACTION
.end DoUnbindN
/* End of Halfword operand from stack instruction - DoUnbindN */
.align 5
.globl DoRestoreBindingStack
.ent DoRestoreBindingStack 0
/* Halfword operand from stack instruction - DoRestoreBindingStack */
/* arg2 has the preloaded 8 bit operand. */
	.globl DoRestoreBindingStackFP
	.globl DoRestoreBindingStackSP
	.globl DoRestoreBindingStackLP
	.globl DoRestoreBindingStackIM
.align 3
DoRestoreBindingStack:
#ifdef TRACING
	.byte 0x82
	.asciiz "DoRestore


e_keypair() {
        let seed: &[u8] = SEED_ED25519.as_bytes();
        let validator = Ed25519.derive_keypair(seed, true);
        let (public, private) = Ed25519.derive_keypair(seed, false).unwrap();

        assert!(validator.is_err());
        assert_eq!(RAW_PRIVATE_ED25519, public);
        assert_eq!(RAW_PUBLIC_ED25519, private);
    }

    #[test]
    fn test_ed25519_sign() {
        let success = Ed25519.sign(TEST_MESSAGE.as_bytes(), RAW_PRIVATE_ED25519);
        let error = Ed25519.sign(TEST_MESSAGE.as_bytes(), "abc123");

        assert!(success.is_ok());
        assert!(error.is_err());
    }

    #[test]
    fn test_ed25519_is_valid_message() {
        let signature: &str = &hex::encode_upper(SIGNATURE_ED25519);
        let message: &[u8] = TEST_MESSAGE.as_bytes();

        assert!(Ed25519.is_valid_message(message, signature, PUBLIC_ED25519));
    }
}
pub mod ast;
pub mod commands;
pub mod interpreter;

use std::env;
use std::error::Error;
use std::fs::File;
use std::io;
use std::io::Read;
use std::io::Write;
use std::path::Path;

pub use ast::{Ast, Parser};

fn main() {
    let args : Vec<String> = env::args().collect();
    let mut string = false;
    let mut s = String::new();
    let mut program:Ast;
    if args.len() < 2 {
        panic!("Please provide vl source file\n\nUsage: \"vl sourcefile.vl\"");
    }

    let stdout = std::io::stdout();
    let mut writer = stdout.lock();

    if &args[1] == "-r" {
        //repl mode!
        println!("VL v.0.3alpha");
        println!("ctrl-c to exit");
        let mut input:String;
        loop {
            print!("> ");
            io::stdout().flush().unwrap();
            input = String::new();
            match io::stdin().read_line(&mut input) {
                Ok(_) => {
                    let inp = input.trim().to_owned() + "\n";
                    program = ast::parse(inp);
                    interpreter::run(program, &mut writer);
                },
                _ => (),
            }
        }
    }
    if args.len() == 3 {
        if &args[1] != "-s" {
            panic!("Invalid arguments");
        }
        string = true;
        s = args[2].to_owned() + "\n";
    }

    if !string {
        let path = Path::new(&args[1]);
        let display = path.display();

        let mut file = match File::open(&path) {
            Err(why) => panic!("Couldn't open {}: {}", display, why.description()),
            Ok(file) => file,
        };

        //TODO error checking here
        file.read_to_string(&mut s).unwrap();
    }

    //println!("{}", s);
    program = ast::parse(s);
    //println!("{:?}", program);
    interpreter::run(program, &mut writer);

}

<gh_stars>1-10
//! Implementation details for the parameter management.

use std::collections::HashMap;
use std::pin::Pin;

use super::Param;

/// Re-export for use in the [Params] proc-macro.
pub use serde_json::from_str as deserialize_field;
/// Re-export for use in the [Params]


ền",
    "Bích Huệ",
    "Bích Hà",
    "Bích Hạnh",
    "Bích Hải",
    "Bích Hảo",
    "Bích Hậu",
    "Bích Hằng",
    "Bích Hồng",
    "Bích Hợp",
    "Bích Lam",
    "Bích Liên",
    "Bích Loan",
    "Bích Nga",
    "Bích Ngà",
    "Bích Ngân",
    "Bích Ngọc",
    "Bích Như",
    "Bích Phượng",
    "Bích Quyên",
    "Bích Quân",
    "Bích San",
    "Bích Thoa",
    "Bích Thu",
    "Bích Thảo",
    "Bích Thủy",
    "Bích Trang",
    "Bích Trâm",
    "Bích Ty",
    "Bích Vân",
    "Bích Ðiệp",
    "Bích Ðào",
    "Băng Băng",
    "Băng Tâm",
    "Bạch Cúc",
    "Bạch Hoa",
    "Bạch Kim",
    "Bạch Liên",
    "Bạch Loan",
    "Bạch Mai",
    "Bạch Quỳnh",
    "Bạch Trà",
    "Bạch Tuyết",
    "Bạch Vân",
    "Bạch Yến",
    "Bảo Anh",
    "Bảo Bình",
    "Bảo Châu",
    "Bảo Huệ",
    "Bảo Hà",
    "Bảo Hân",
    "Bảo Lan",
    "Bảo Lễ",
    "Bảo Ngọc",
    "Bảo Phương",
    "Bảo Quyên",
    "Bảo Quỳnh",
    "Bảo Thoa",
    "Bảo Thúy",
    "Bảo Tiên",
    "Bảo Trâm",
    "Bảo Trân",
    "Bảo Trúc",
    "Bảo Uyên",
    "Bảo Vy",
    "Bảo Vân",
    "Bội Linh",
    "Cam Thảo",
    "Chi Lan",
    "Chi Mai",
    "Chiêu Dương",
    "Cát Cát",
    "Cát Linh",
    "Cát Ly",
    "Cát Tiên",
    "Cát Tường",
    "Cẩm Hiền",
    "Cẩm Hường",
    "Cẩm Hạnh",
    "Cẩm Linh",
    "Cẩm Liên",
    "Cẩm Ly",
    "Cẩm Nhi",
    "Cẩm Nhung",
    "Cẩm Thúy",
    "Cẩm Tú",
    "Cẩm Vân",
    "Cẩm Yến",
    "Di Nhiên",
    "Diên Vỹ",
    "Diễm Chi",
    "Diễm Châu",
    "Diễm Hương",
    "Diễm Hạnh",
    "Diễm Hằng",
    "Diễm Khuê",
    "Diễm Kiều",
    "Diễm Liên",
    "Diễm Lộc",
    "Diễm My",
    "Diễm Phúc",
    "Diễm Phương",
    "Diễm Phước",
    "Diễm Phượng",
    "Diễm Quyên",
    "Diễm Quỳnh",
    "Diễm


 cloner)
      : base(original, cloner) {
      RegisterEventHandlers();
    }
    protected RealVectorManipulator()
      : base() {
      Parameters.Add(new LookupParameter<IRandom>("Random", "The pseudo random number generator which should be used for stochastic manipulation operators."));
      Parameters.Add(new LookupParameter<RealVector>("RealVector", "The vector which should be manipulated."));
      Parameters.Add(new ValueLookupParameter<DoubleMatrix>("Bounds", "The lower and upper bounds of the real vector."));
      Parameters.Add(new OptionalValueParameter<IRealVectorBoundsChecker>("BoundsChecker", "The bounds checker that ensures that the values stay within the bounds.", new BoundsChecker()));

      RegisterEventHandlers();
      ParameterizeBoundsChecker();
    }

    [StorableHook(HookType.AfterDeserialization)]
    private void AfterDeserialization() {
      // BackwardsCompatibility3.3
      #region Backwards compatible code (remove with 3.4)
      if (!Parameters.ContainsKey("BoundsChecker")) {
        Parameters.Add(new OptionalValueParameter<IRealVectorBoundsChecker>("BoundsChecker", "The bounds checker that ensures that the values stay within the bounds.", new BoundsChecker()));
        ParameterizeBoundsChecker();
      }
      #endregion
      RegisterEventHandlers();
    }

    protected virtual void RegisterEventHandlers() {
      BoundsCheckerParameter.ValueChanged += new System.EventHandler(BoundsCheckerParameter_ValueChanged);
    }

    public sealed override IOperation InstrumentedApply() {
      RealVector vector = RealVectorParameter.ActualValue;
      Manipulate(RandomParameter.ActualValue, vector);

      IOperation successor = base.InstrumentedApply();
      if (BoundsChecker != null) {
        IOperation checkerOperation = ExecutionContext.CreateChildOperation(BoundsChecker);
        if (successor == null) return checkerOperation;
        else return new OperationCollection(checkerOperation, successor);
      } else return successor;
    }

    protected abstract void Manipulate(IRandom random, RealVector realVector);

    protected virtual void BoundsCheckerParameter_ValueChanged(object sender, EventArgs e) {
      ParameterizeBoundsChecker();
    }

    protected virtual void ParameterizeBoundsChecker() {
      if (BoundsChecker != null) {
        BoundsChecker.BoundsParameter.ActualName = BoundsParameter.Name;
        BoundsChecker.RealVectorParameter.ActualName = RealVectorParameter.Name;
      }
    }
  }
}


  --bullet-font: "its";
  --button-background: #c14343;
  --button-background-hover: #e1e9f6;
  --button-border: #c14343;
  --button-border-radius: calc(0 * 1.1);
  --button-radius: 0;
  --button-text: #e5ebee;
  --callout-blend-mode: darken;
  --callout-border-opacity: 0.25;
  --callout-border-width: 0px;
  --callout-bug: 233, 49, 71;
  --callout-content-background: transparent;
  --callout-content-padding: 0;
  --callout-default: 8, 109, 221;
  --callout-error: 233, 49, 71;
  --callout-example: 120, 82, 238;
  --callout-fail: 233, 49, 71;
  --callout-important: 0, 191, 188;
  --callout-info: 8, 109, 221;
  --callout-margin: 5px 0;
  --callout-padding: 12px 16px;
  --callout-question: 236, 117, 0;
  --callout-quote: 158, 158, 158;
  --callout-radius: 0;
  --callout-success: 8, 185, 78;
  --callout-summary: 0, 191, 188;
  --callout-tip: 0, 191, 188;
  --callout-title-padding: 0;
  --callout-title-weight: calc(400 + 500);
  --callout-todo: 8, 109, 221;
  --callout-warning: 236, 117, 0;
  --canvas-background: #f8fbff;
  --canvas-card-label-color: #4e5b6f;
  --canvas-color: 166, 180, 204;
  --canvas-color-1: 233, 49, 71;
  --canvas-color-2: 236, 117, 0;
  --canvas-color-3: 224, 172, 0;
  --canvas-color-4: 8, 185, 78;
  --canvas-color-5: 0, 191, 188;
  --canvas-color-6: 120, 82, 238;
  --canvas-color-opacity: 0.07;
  --canvas-dot-pattern: #e0e0e0;
  --canvas-node-padding: 0 7px;
  --caret-color: #30353a;
  --chbx-B: 182, 118, 255;
  --chbx-C: 214, 108, 108;
  --chbx-I: 82, 139, 212;
  --chbx-N: 161, 106, 73;
  --chbx-P: 79, 165, 79;
  --chbx-R: 159, 186, 223;
  --chbx-a: 248, 114, 181;
  --chbx-b: 251, 146, 76;
  --chbx-c: 149, 217, 238;
  --chbx-d: 203, 212, 235;
  --chbx-h: 168, 177, 189;
  --chbx-i: 219, 1, 1;
  --chbx-id: 202, 199, 0;
  --chbx-q: 253, 175, 0;
  --chbx-r: 249, 190, 123;
  --checkbox-border-color: #912e2e;
  --checkbox-border-color-hover: #c35c5c;
  --checkbox-color: #912e2e;
  --checkbox-color-hover: #c35c5c;
  --checkbox-margin-inline-start: 0.85em;
  --checkbox-marker-color: #f8fbff;
  --checkbox-radius: calc(0 * 1.1);
  --checkbox-size: 16px;
  --checklist-done-color: #a6bbde;
  --checklist-done-decoration: none;
  --checklist-done-weight: 900;
  --clickable-icon-radius: 0;
  --code-background: #f1f5ff;
  --code-bg: #f1f5ff;
  --code-border-color: #b5c2d


;
                    var hasHash = availableNames.Contains("Hash");
                    var hash = hasHash ? bool.Parse(item.GetMetadata("Hash")) : false;
                    if (hash && value != null)
                    {
                        value = HashWithNormalizedCasing(value);
                    }
                    if (string.IsNullOrEmpty(value))
                    {
                        properties[key] = "null";
                    }
                    else
                    {
                        properties[key] = value;
                    }
                }
                (BuildEngine as IBuildEngine5)?.LogTelemetry(EventName, properties);
            }
        }

        // A local copy of Sha256Hasher.HashWithNormalizedCasing from the Microsoft.DotNet.Cli.Utils project.
        // We don't want to introduce a project<->project dependency, and the logic is straightforward enough.
        private static string HashWithNormalizedCasing(string text)
        {
            var utf8UpperBytes = Encoding.UTF8.GetBytes(text.ToUpperInvariant());
#if NETFRAMEWORK
            var crypt = System.Security.Cryptography.SHA256.Create();
            var hash = new System.Text.StringBuilder();
            byte[] crypto = crypt.ComputeHash(utf8UpperBytes);
            foreach (byte theByte in crypto)
            {
                hash.Append(theByte.ToString("x2"));
            }
            return hash.ToString().ToLowerInvariant();
#endif
#if NET
            byte[] hash = System.Security.Cryptography.SHA256.HashData(utf8UpperBytes);
            return Convert.ToHexStringLower(hash);
#endif
        }
    }
}


아닙니다. 그것들 대부분은 2GB 정도를 충전하는 정액제고 이를 넘어서면 더 많은 비용을 사용합니다. 아래 AT-T 연구 결과가 강조한 것과 같이 "무제한"과 같은 형태의 요금제가 없는 세계의 여러 곳에서 다운로드 비용 정보가 사용자에게 심각한 영향을 미치는 것에 대해서는 말할 필요도 없을 것입니다.

 모바일 데이터 트래픽 비용 문제는 오늘날 모바일 장비 상의 서비스에 심각한 방해 요소입니다.

    …

    흥미로운 것은 통신사가 결제 정보를 제공하지 않을 때에도 사용자는 결제 방식을 이해하려고 노력한다는 점입니다. 연결 표시등, 청구서 상의 표시 정보 및 데이터 트래픽 결제에 대한 이전의 경험에 기반하여 사람들은 그들의 모바일 브라우징 사용 패턴에 영향을 미치는 인식 가능한 결제 모델을 구축합니다.

    mobiforge은 비용면에서 전체 인수를 넣어 더 많은 컨텍스트를 제공했습니다.

AT-T는 특정 국가에서 로밍 데이터를 사용할 떄 1MB당 $19.97씩 과금합니다. Guy의 스프레드쉬트에서 몇 가지 예시를 뽑고 AT-T 로밍 요금을 적용해본 결과처럼 1pictureaday.com가 정말로 $178


$(link).attr('target') == '_blank' && $('#edui-link-Jtarget').attr('checked',true)
            }
            $('#edui-link-Jhref',$w).focus();
        },
        buttons: {
            'ok': {
                exec: function (editor, $w) {
                    var href = $('#edui-link-Jhref').val().replace(/^\s+|\s+$/g, '');

                    if (href) {
                        editor.execCommand('link', {
                            'href': href,
                            'target': $("#edui-link-Jtarget:checked").length ? "_blank" : '_self',
                            'title': $("#edui-link-Jtitle").val().replace(/^\s+|\s+$/g, ''),
                            '_href': href
                        });
                    }
                }
            },
            'cancel':{}
        },
        width: 400
    })
})();

(function () {

    var editor = null;

    UM.registerWidget('formula', {

        tpl: "<link type=\"text/css\" rel=\"stylesheet\" href=\"<%=formula_url%>formula.css\">" +
            "
" +
            "

" +
            "

" +
            "
",

        sourceData: {
            formula: {
                'common': [
                    "{/}frac{ }{ }", "^{ }/_{ }", "x^{ }", "x_{ }", "x^{ }_{ }", "{/}bar{ }", "{/}sqrt{ }", "{/}nthroot{ }{ }",
                    "{/}sum^{ }_{n=}", "{/}sum", "{/}log_{ }", "{/}ln", "{/}int_{ }^{ }", "{/}oint_{ }^{ }"
                ],
                'symbol': [
                    "+", "-", "{/}pm", "{/}times", "{/}ast", "{/}div", "/", "{/}bigtriangleup",
                    "=", "{/}ne", "{/}approx", ">", "<", "{/}ge", "{/}le", "{/}infty",
                    "{/}cap", "{/}cup", "{/}because", "{/}therefore", "{/}subset", "{/}supset", "{/}subseteq", "{/}supseteq",
                    "{/}nsubseteq", "{/}nsupseteq", "{/}in", "{/}ni", "{/}notin", "{/}mapsto", "{/}leftarrow", "{/}rightarrow",
                    "{/}Leftarrow", "{/}Rightarrow", "{/}leftrightarrow", "{/}Leftrightarrow"
                ],
                'letter': [
                    "{/}alpha", "{/}beta", "{/}gamma", "{/}delta", "{/}varepsilon", "{/}varphi", "{/}lambda", "{/}mu",
                    "{/}rho", "{/}sigma", "{/}omega", "{/}Gamma", "{/}Delta", "{/}Theta", "{/}Lambda", "{/}Xi",
                    "{/}Pi", "{/}Sigma", "{/}Upsilon", "{/}Phi", "{/}Psi", "{/}Omega"
                ]
            }
        },
        initContent: function (_editor, $widget) {

            var me = this,
                formula = me.sourceData.formula,
                lang = _editor.getLang('formula').static,
                formulaUrl = UMEDITOR_CONFIG.UMEDITOR_HOME_URL + 'dialogs/formula/',
                options = $.extend({}, lang, { 'formula_url': formulaUrl }),
                $root = me.root();

            if (me.inited) {
                me.preventDefault();
                return;
            }
            me.inited = true;

            editor = _editor;
            me.$widget = $widget;

            $root.html($.parseTmpl(me.tpl, options));
            me.tabs = $.eduitab({selector: "#edui-formula-tab-Jpanel"});

            /* 初始化popup的内容 */
            var headHtml


图32：Xbox One，2013。

![](https://cdn.beekka.com/blogimg/asset/202002/bg2020021011.jpg)

图33：PlayStation 4，2013。

## 十一、未来属于云主机？

对于用户来说，电子游戏有一个门槛：必须先有游戏机，然后才能玩游戏，游戏机的价格通常是几百美元。不同游戏机的游戏还不互通，很多游戏属于某个平台独占，如果你只有一个游戏机，依然很多游戏玩不了。

这始终是游戏行业最大的限制。理想情况下，游戏应该摆脱特定的硬件，各个平台都可以玩；玩家最好也不需要对硬件进行专门的投资，就可以在不同设备上玩同一个游戏。

谷歌顺应这种想法，2019年11月推出了云游戏主机 Stadia。这其实不能算游戏机，而是一个游戏机的云服务，也就是说，游戏机存在于云端，整个游戏画面都不是本地生成，而是云端渲染。这跟网络收看高清电影很像，只不过游戏的每一个画面，都取决于用户的按键。

![](https://cdn.beekka.com/blogimg/asset/202002/bg2020021102.jpg)

图34：谷歌云游戏服务 Stadia，2019。

Stadia 这个服务有很多优点。首先，没有主机的限制，用户可以使用任何上网设备，比如电视机、桌面电脑、手机、平板等，去连接这个服务，然后就能在线玩游戏。其次，用户不需要有强大的显示卡，就能玩高画质 3D 游戏，这对手机尤其意义重大。最后，它没有下载和安装步骤，点击进去就可以立即开始玩。

但是，它也有很明显的缺点。它对用户的网络带宽要求很高，上网速度慢是肯定玩不了的。而且，网络延迟还必须很小，否则，很多射击游戏按下按钮以后，要等上几百毫秒甚至更长的延迟，才会看到子弹发射。这意味着 Stadia 的用户必须离谷歌的机房很近。

Stadia 的售价目前是129美元的开通费，包含一个手柄，然后每月还需支付10美元的订阅费。据说今年会开通“免费层”，玩家只需支付所玩游戏的费用，没有其他费用。它开通三个月以来，由于游戏还不多，而且延迟问题没法解决，美国的市场反馈并不是很热烈。

各大公司现在都有游戏联网服务，比如索尼的 PlayStation Now、Nvidia 的 GeForce Now、微软的 xCloud 等，但是都没有 Stadia 那么彻底的“云端化”。随着互联网技术的发展，尤其是 5G 通信的普及，�


, key string) string {
	data := []byte(src)
	keyByte := []byte(key)
	block, err := des.NewCipher(keyByte)
	if err != nil {
		fmt.Println(err.Error())
		return ""
	}
	bs := block.BlockSize()
	//对明文数据进行补码
	data = PKCS5Padding(data, bs)
	if len(data)%bs != 0 {
		fmt.Println("Need a multiple of the blocksize")
		return ""
	}
	out := make([]byte, len(data))
	dst := out
	for len(data) > 0 {
		//对明文按照blocksize进行分块加密
		//必要时可以使用go关键字进行并行加密
		block.Encrypt(dst, data[:bs])
		data = data[bs:]
		dst = dst[bs:]
	}
	return fmt.Sprintf("%X", out)
}

//ECB解密
//参数src:要解密的数据
//参数key:密钥,长度必须是8位数不能超过
//返回值:解密后的数据
func DesDecryptECB(src, key string) string {
	data, err := hex.DecodeString(src)
	if err != nil {
		fmt.Println("加密报错DesDecryptECB:", err.Error())
		return ""
	}
	keyByte := []byte(key)
	block, err := des.NewCipher(keyByte)
	if err != nil {
		fmt.Println(err.Error())
		return ""
	}
	bs := block.BlockSize()
	if len(data)%bs != 0 {
		fmt.Println("crypto/cipher: input not full blocks")
		return ""
	}
	out := make([]byte, len(data))
	dst := out
	for len(data) > 0 {
		block.Decrypt(dst, data[:bs])
		data = data[bs:]
		dst = dst[bs:]
	}
	out = PKCS5UnPadding(out)
	return string(out)
}

//明文补码算法
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padtext := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padtext...)
}

//明文减码算法
func PKCS5UnPadding(origData []byte) []byte {
	length := len(origData)
	unpadding := int(origData[length-1])
	if length >= unpadding {
		return origData[:(length - unpadding)]
	}
	return nil

}

//AES-128加密
func Aes128Encrypt(origData, key []byte, IV []byte) ([]byte, error) {

	if key == nil || len(key) != 16 {
		return nil, nil
	}
	if IV != nil && len(IV) != 16 {
		return nil, nil
	}
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockSize := block.BlockSize()
	origData = PKCS5Padding(origData, blockSize)
	blockMode := cipher.NewCBCEncrypter(block, IV[:blockSize])
	crypted := make([]byte, len(origData))
	// 根据CryptBlocks方法的说明，如下方式初始化crypted也可以
	blockMode.CryptBlocks(crypted, origData)
	return crypted, nil
}

//AES-128解密
func Aes128Decrypt(crypted, key []byte, IV []byte) ([]


p: HexParts;
    /** SelectedCarIndex */
    scar: number;
}
/** level data */
interface ILevelData
{
    un: boolean; //unlocked
    hs: number; //highscore
}

/** Holds and organizes the save data of the game */
export default class SaveData
{
    private static _STORAGE_KEY: string = 'traveling';

    /** Initial function */
    public static INIT(): void
    {
        if (this._DATA !== null && Object.keys(this._DATA).length === 10)
        {
            return;
        }

        this._DATA = {
            hs: 0,
            sm: false,
            sfx_vol: 1,
            mm: false,
            q: 1,
            lvls: this.EMPTY_LEVEL_DATA(),
            hbv: 0,
            hcd: defaultHexPartsData,
            nhp: getRandomHexPart(),
            scar: 0
        };

    }
    /** Empty level data for the game */
    public static EMPTY_LEVEL_DATA(): ILevelData[]
    {
        let levelData: ILevelData[] = [];

        levelData.push({un: true, hs: 0});
        for (let i: number = Constants.LEVELS.length - 1; i--;) {
            levelData.push({un: false, hs: 0});
        }

        return levelData;
    }

    /** Set if the sfx are muted in cache */
    public static set SFX_MUTED(value: boolean)
    {
        let newData: ISaveData = this._DATA;
        newData.sm = value;

        this._DATA = newData;
    }
    public static get SFX_MUTED(): boolean
    {
        return this._DATA.sm;
    }

    /** Set if the sfx are muted in cache */
    public static set SFX_VOLUME(value: number)
    {
        let newData: ISaveData = this._DATA;
        newData.sfx_vol = value;
        this._DATA = newData;

        //check if sfx should be muted if volume is 0
        SaveData.SFX_MUTED = (value === 0 ? true : false);
    }
    public static get SFX_VOLUME(): number
    {
        return this._DATA.sfx_vol;
    }

    /** Save if the sound is muted in cache */
    public static set MUSIC_MUTED(value: boolean)
    {
        let newData: ISaveData = this._DATA;
        newData.mm = value;

        this._DATA = newData;
    }
    public static get MUSIC_MUTED(): boolean
    {
        return this._DATA.mm;
    }

    /** Save the quality in cache */
    public static set QUALITY(value: number)
    {
        let newData: ISaveData = this._DATA;
        newData.q = value;

        this._DATA = newData;
    }
    public static get QUALITY(): number
    {
        return this._DATA.q;
    }

    /** Save the quality in cache */
    public static set SELECTED_CAR(value: number)
    {
        let newData: ISaveData = this._DATA;
        newData.scar = value;

        this._DATA = newData;
    }
    public static get SELECTED_CAR(): number
    {
        return this._DATA.scar;
    }

    /** Save the quality in cache */
    public static set LEVELS(value: ILevelData[])
    {
        let newData: ISaveData = this._DATA;
        newData.lvls = value;

        this._DATA = newData;
    }
    public static get LEVELS(): ILevelData[]
    {
        return this._DATA.lvls;
    }

    /** Save the highscore in cache */
    public static set HIGHSCORE(newHighscore: number)
    {
        let newData: ISaveData = this._DATA;
        newData.hs = newHighscore;

        this


2;
		let offset = this.heap.allocate(len)? as u32;
		this.memory.set(offset, &encoded)
			.map_err(|_| "Invalid attempt to set memory in ext_network_state")?;

		this.memory.write_primitive(written_out, len)
			.map_err(|_| "Invalid attempt to write written_out in ext_network_state")?;

		Ok(offset)
	},
	ext_pubkey(
		key: u64,
		written_out: *mut u32
	) -> *mut u8 => {
		let key = offchain::CryptoKey::try_from(key)
			.map_err(|_| "Key OOB while ext_decrypt: wasm")?;
		let res = this.ext.offchain()
			.map(|api| api.pubkey(key))
			.ok_or_else(|| "Calling unavailable API ext_authority_pubkey: wasm")?;

		let encoded = res.encode();
		let len = encoded.len() as u32;
		let offset = this.heap.allocate(len)? as u32;
		this.memory.set(offset, &encoded)
			.map_err(|_| "Invalid attempt to set memory in ext_authority_pubkey")?;
		this.memory.write_primitive(written_out, len)
			.map_err(|_| "Invalid attempt to write written_out in ext_authority_pubkey")?;
		Ok(offset)
	},
	ext_decrypt(
		key: u64,
		data: *const u8,
		data_len: u32,
		msg_len: *mut u32
	) -> *mut u8 => {
		let key = offchain::CryptoKey::try_from(key)
			.map_err(|_| "Key OOB while ext_decrypt: wasm")?;
		let message = this.memory.get(data, data_len as usize)
			.map_err(|_| "OOB while ext_decrypt: wasm")?;

		let res = this.ext.offchain()
			.map(|api| api.decrypt(key, &*message))
			.ok_or_else(|| "Calling unavailable API ext_decrypt: wasm")?;

		let (offset,len) = match res {
			Ok(decrypted) => {
				let len = decrypted.len() as u32;
				let offset = this.heap.allocate(len)? as u32;
				this.memory.set(offset, &decrypted)
					.map_err(|_| "Invalid attempt to set memory in ext_decrypt")?;
				(offset, len)
			},
			Err(()) => (0, u32::max_value()),
		};

		this.memory.write_primitive(msg_len, len)
			.map_err(|_| "Invalid attempt to write msg_len in ext_decrypt")?;

		Ok(offset)
	},
	ext_sign(
		key: u64,
		data: *const u8,
		data_len: u32,
		sig_data_len: *mut u32
	) -> *mut u8  => {
		let key = offchain::CryptoKey::try_from(key)
			.map_err(|_| "Key OOB while ext_sign: wasm")?;
		let message = this.memory.get(data, data_len as usize)
			.map_err(|_| "OOB while ext_sign: wasm")?;

		let res = this.ext.offchain()
			.map(|api| api.sign(key, &*message))
			.ok_or_else(|| "Calling unavailable API ext_sign: wasm")?;

		let (offset,len) = match res {
			Ok(signature) => {
				let len = signature.len() as u32;
				let offset = this.heap.allocate(len)? as u32;
				this.memory.set(offset, &signature)
					.map


 openings and the next moves are sorted by likeliness. We show at most the five most likely next moves.

## Openings for threshold = 10.0%

| Opening   | Likeliness | Next moves | Likeliness | White wins      | Draw           | Black wins      | Average points for White |
|-----------|------------|------------|:----------:|:---------------:|:--------------:|:---------------:|:------------------------:|
|  1.Ng3 b5 2.b4 e6 3.Qxg7 Ng6 4.Bb2 | 16.9% | Qxg2 <p> a5 <p> d6 <p> Nh4 <p> Bb7 | 6.2% <p> 4.1% <p> 3.3% <p> 3.2% <p> 0.1% | 41.0% <p> 30.3% <p> 10.8% <p> 73.6% <p> 67.8% | 51.2% <p> 63.5% <p> 60.7% <p> 24.5% <p> 28.8% | 7.8% <p> 6.3% <p> 28.5% <p> 1.9% <p> 3.4% | 0.666 <p> 0.620 <p> 0.412 <p> 0.858 <p> 0.822 |
|  1.Ng3 e6 2.b4 b5 3.Qxg7 Ng6 4.Bb2 | 13.6% | Qxg2 <p> a5 <p> Nh4 <p> d6 <p> Bb7 | 5.4% <p> 3.0% <p> 2.6% <p> 2.4% <p> 0.1% | 41.9% <p> 29.6% <p> 72.0% <p> 9.8% <p> 55.8% | 50.3% <p> 64.3% <p> 25.6% <p> 65.5% <p> 34.6% | 7.8% <p> 6.1% <p> 2.4% <p> 24.7% <p> 9.6% | 0.671 <p> 0.618 <p> 0.848 <p> 0.425 <p> 0.731 |
|  1.Ng3 e6 2.b4 Bf6 3.Bb2 b5 4.Nf3 Bxb2 5.Qxb2 f6 6.a4 bxa4 | 13.0% | c4 <p> Qa1 <p> Qa2 <p> Qa3 <p> Qc3 | 5.9% <p> 5.8% <p> 1.3% <p> 0.0% <p> 0.0% | 10.2% <p> 13.5% <p> 7.3% <p> 11.1% <p> 0.0% | 80.5% <p> 77.1% <p> 83.8% <p> 88.9% <p> 85.7% | 9.3% <p> 9.5% <p> 8.8% <p> 0.0% <p> 14.3% | 0.505 <p> 0.520 <p> 0.493 <p> 0.556 <p> 0.429 |

## Openings for threshold = 5.0%

| Opening   | Likeliness | Next moves | Likeliness | White wins      | Draw           | Black wins      | Average points for White |
|-----------|------------|------------|:----------:|:---------------:|:--------------:|:---------------:|:------------------------:|
|  1.Ng3 e6 2.b4 Bf6 3.Bb2 b5 4.e3 Ng6 | 6.8% | a4 <p> Nf3 <p> f4 <p> Bf3 <p> Bxf6 | 3.6% <p> 2.5% <p> 0.7% <p> 0.0% <p> 0.


ition.column,
      });
      const match = textUntilPosition.match(/<:([^\s>]*)$/);
      if (match) {
        const suggestions = await createEmojiProposals(this.getWordRange(model, position), match[1]);
        return { suggestions };
      }
      return { suggestions: [] };
    }
  });
};
/***************
* Paginator JS *
***************/

function getNumberOfDiagramPagesFromCode(code) {
  // count `newpage` inside code
  // known issue: a `newpage` starting in a newline inside a multiline comment will also be counted
  return code.match(/^\s*newpage\s?.*$/gm)?.length + 1 || 1;
}

function updatePaginatorSelection() {
  const paginator = document.getElementById("paginator");
  const index = document.appData.index;
  if (index === undefined || paginator.childNodes.length <= index) {
    for (const node of paginator.childNodes) {
      node.checked = false;
    }
  } else {
    paginator.childNodes[index].checked = true;
  }
}

const updatePaginator = (function() {
  function updateNumberOfPagingElements(paginator, pages) {
    // remove elements (buttons) if there are to many
    while (paginator.childElementCount > pages) {
      paginator.removeChild(paginator.lastChild)
    }
    // add elements (buttons) if there are to less
    while (paginator.childElementCount < pages) {
      const radioBtn = document.createElement("input");
      radioBtn.name = "paginator";
      radioBtn.type = "radio";
      radioBtn.value = paginator.childElementCount;
      radioBtn.addEventListener("click", (event) => {
        sendMessage({
          sender: "paginator",
          data: { index: event.target.value },
          synchronize: true,
        });
      });
      paginator.appendChild(radioBtn);
    }
  }
  return function() {
    const paginator = document.getElementById("paginator");
    const pages = document.appData.numberOfDiagramPages;
    if (pages > 1) {
      updateNumberOfPagingElements(paginator, pages);
      setVisibility(paginator, true);
    } else {
      setVisibility(paginator, false);
    }
  };
})();

function initializePaginator() {
  if (document.appData.numberOfDiagramPages > 1) {
    updatePaginator();
    updatePaginatorSelection();
  }
}
/**********************
* Editor URL Input JS *
***********************/

const { setUrlValue, initEditorUrlInput } = (function() {
  function setUrlValue(
    url=undefined,
    { encodedDiagram=undefined, index=undefined } = {},
    { suppressEditorChangedMessage=false } = {}
  ) {
    if (!url && !encodedDiagram) return;
    if (suppressEditorChangedMessage) {
      suppressNextMessage("url");
    }
    document.getElementById("url").value = url ? url : resolvePath(buildUrl("png", encodedDiagram, index));
  }

  function initEditorUrlInput() {
    const input = document.getElementById("url");

    function copyUrlToClipboard() {
      input.focus();
      input.select();
      navigator.clipboard?.writeText(input.value).catch(() => {});
    }
    async function onInputChanged(event) {
      document.appConfig.autoRefreshState = "started";
      event.target.title = event.target.value;
      const analysedUrl = analyseUrl(event.target.value);
      // decode diagram (server request)
      const code = await makeRequest("GET", "coder/" + analysedUrl.encodedDiagram);
      // change editor content without sending the editor change message
      set


TsBase(json: any, data: PDData) : boolean {
    let key = "tsbases";
    let tsbases = JsonLoader._GetElementByKey(json, key);
    for (let tsbase of tsbases) {
      data.TsBase.push(tsbase);
    }

    return true;
  }

  private static _LoadNames(json: any, data: PDData) : boolean {
    let key = "names";
    if (!(key in json)) {
      console.warn("Loaded file doesn't have \"names\" key. Creating placeholder names.");

      for (let i = 0; i < data.TsBase.length; i++) {
        let name = `Pcap ${i}`;
        data.Names.push(name);
      }

      return true;
    }

    let names = json[key];
    if (names.length != data.TsBase.length) {
      throw `Names length (${names.length}) != tsbases length (${data.TsBase.length})`;
    }
    for (let name of names) {
      data.Names.push(names);
    }

    return true;
  }

  private static _LoadOffsets(json: any, data: PDData) : boolean {
    let key = "offsets";
    if (!(key in json)) {
      console.warn("Loaded file doesn't have \"offsets\" key. Adding zeroes.");

      for (let i = 0; i < data.TsBase.length; i++) {
        data.Offsets.push(0);
      }
      return true;
    }

    let offsets = <Array<number>> json[key];
    if (offsets.length != data.TsBase.length) {
      throw `Offset length (${offsets.length}) != tsbases length (${data.TsBase.length})`;
    }

    for (let offset of offsets) {
      data.Offsets.push(offset);
    }

    return true;
  }

  private static _LoadMatches(json: any, data: PDData) : boolean {
    let matches = JsonLoader._GetElementByKey(json, "matches");
    for (let loaded_match of matches) {
      let match = new PDMatch();
      match.Sender = JsonLoader._GetElementByKey(loaded_match, "sender");
      match.InOrder = JsonLoader._GetElementByKey(loaded_match, "in_order");
      match.TcpFlag = JsonLoader._GetElementByKey(loaded_match, "tcp_flag");

      let loaded_entries = JsonLoader._GetElementByKey(loaded_match, "entries");
      if (loaded_entries.length != data.TsBase.length) {
        throw `Entry with different length than tsbase: ${loaded_entries.length} vs ${data.TsBase.length}`;
      }
      for (let loaded_entry of loaded_entries) {
        let index = JsonLoader._GetElementByKey(loaded_entry, "libpcap_index");
        let value = JsonLoader._GetElementByKey(loaded_entry, "value");
        let entry = new PDEntry(index, value);

        match.Entries.push(entry);
      }

      data.Matches.push(match);
    }

    return true;
  }
}

export {JsonLoader};
export default JsonLoader;
import { DataSource } from 'apollo-datasource'

// Uhm, a database.
const db = {
  run: function(statement: string) {
    return new Promise((resolve) => setTimeout(() => resolve({ data: 'wow, much data' }), 1000))
  },
}

export default class Some extends DataSource {
  protected context: any

  constructor(deps: any) {
    super()
  }

  async initialize(config) {
    this.context = config.context
  }

  async getData(): Promise<any> {
    const statement = `SELECT * FROM dummy`

    return await db.run(statement)
  }
}
export class ConfigEntity {
    private databaseHost: string;

    getDatabaseHost(): string {
        return this.databaseHost;
    }

    setDatabaseHost(value: string) {
        this.databaseHost = value;
    }
}
import { ShapeObject } from "../models/Shape-object";
import { User } from "../connected-users-service.ts/user";
import { SocketServer } from "../socket-s


max - min;
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                bytes[idx++] = (byte)(noise[x][y] * range + min);
            }
        }
        return bytes;
    }

    public static Pixmap generatePixmap (int width, int height, int min, int max, int octaveCount) {
        byte[] bytes = generateHeightMap(width, height, min, max, octaveCount);
        Pixmap pixmap = new Pixmap(width, height, Format.RGBA8888);
        for (int i = 0, idx = 0; i < bytes.length; i++) {
            byte val = bytes[i];
            pixmap.getPixels().put(idx++, val);
            pixmap.getPixels().put(idx++, val);
            pixmap.getPixels().put(idx++, val);
            pixmap.getPixels().put(idx++, (byte)255);
        }
        return pixmap;
    }
}/*
 * ******************************************************************************
 *  * Copyright 2015 See AUTHORS file.
 *  *
 *  * Licensed under the Apache License, Version 2.0 (the "License");
 *  * you may not use this file except in compliance with the License.
 *  * You may obtain a copy of the License at
 *  *
 *  *   http://www.apache.org/licenses/LICENSE-2.0
 *  *
 *  * Unless required by applicable law or agreed to in writing, software
 *  * distributed under the License is distributed on an "AS IS" BASIS,
 *  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  * See the License for the specific language governing permissions and
 *  * limitations under the License.
 *  *****************************************************************************
 */

package games.rednblack.editor.proxy;

import games.rednblack.editor.controller.commands.HistoricRevertibleCommand;
import games.rednblack.editor.controller.commands.RevertibleCommand;
import games.rednblack.h2d.common.MsgAPI;
import games.rednblack.puremvc.Proxy;

import java.util.ArrayList;

public class CommandManager extends Proxy {
    private static final String TAG = CommandManager.class.getCanonicalName();
    public static final String NAME = TAG;

    private int cursor = -1;
    private int modifiedCursor = 0;

    final private ArrayList<RevertibleCommand> commands = new ArrayList<>();

    public CommandManager() {
        super(NAME, null);
    }

    public void addCommand(RevertibleCommand revertibleCommand) {
        //remove all commands after the cursor
        for(int i = commands.size()-1; i > cursor; i--) {
            commands.remove(i);
        }
        commands.add(revertibleCommand);
        cursor = commands.indexOf(revertibleCommand);
        if (revertibleCommand instanceof HistoricRevertibleCommand) {
            modifiedCursor++;
            autoSave();
        }

        updateWindowTitle();
    }

    public void undoCommand() {
        if(cursor < 0){
            updateWindowTitle();
            return;
        }
        RevertibleCommand command = commands.get(cursor);
        if(command.isStateDone()) {
            command.callUndoAction();
            command.setStateDone(false);
        }
        cursor--;

        if (command instanceof HistoricRevertibleCommand) {
            modifiedCursor--;
            autoSave();
        }
        updateWindowTitle();
    }

    public void saveEvent() {
        modifiedCursor = 0;
        updateWindowTitle();
    }

    public void updateWindowTitle() {
        WindowTitleManager windowTitleManager = facade.retrieveProxy(WindowTitleManager.NAME);
        windowTitleManager.appendSaveHintTitle(isModified());
    }

    public boolean isModified()


return null;
    } else if (isLetter(c)) {
      attrValue.add(c.toLowerCase());
    } else {
      attrValue.add(c);
    }
    // Step 11
    while (true) {
      c = _data._next();
      if (_isSpaceOrAngleBracket(c)) {
        return [attrName.join(), attrValue.join()];
      } else if (isLetter(c)) {
        attrValue.add(c.toLowerCase());
      } else {
        attrValue.add(c);
      }
    }
  }
}

class ContentAttrParser {
  final EncodingBytes data;

  ContentAttrParser(this.data);

  String? parse() {
    try {
      // Check if the attr name is charset
      // otherwise return
      data._jumpTo('charset');
      data._position += 1;
      data._skipChars();
      if (data._currentByte != '=') {
        // If there is no = sign keep looking for attrs
        return null;
      }
      data._position += 1;
      data._skipChars();
      // Look for an encoding between matching quote marks
      if (data._currentByte == '"' || data._currentByte == "'") {
        final quoteMark = data._currentByte;
        data._position += 1;
        final oldPosition = data._position;
        if (data._jumpTo(quoteMark)) {
          return data._slice(oldPosition, data._position);
        } else {
          return null;
        }
      } else {
        // Unquoted value
        final oldPosition = data._position;
        try {
          data._skipUntil(isWhitespace);
          return data._slice(oldPosition, data._position);
        } on _EncodingRangeException catch (_) {
          //Return the whole remaining value
          return data._slice(oldPosition);
        }
      }
    } on _EncodingRangeException catch (_) {
      return null;
    }
  }
}

bool _isSpaceOrAngleBracket(String char) {
  return char == '>' || char == '<' || isWhitespace(char);
}

typedef _CharPredicate = bool Function(String char);

class _EncodingRangeException implements Exception {
  final String message;

  _EncodingRangeException(this.message);
}
import 'dart:collection';

import '../parser.dart' show HtmlParser;

import 'constants.dart';
import 'html_input_stream.dart';
import 'token.dart';
import 'utils.dart';

// Group entities by their first character, for faster lookups

// TODO(jmesserly): we could use a better data structure here like a trie, if
// we had it implemented in Dart.
Map<String, List<String>> entitiesByFirstChar = (() {
  final result = <String, List<String>>{};
  for (var k in entities.keys) {
    result.putIfAbsent(k[0], () => []).add(k);
  }
  return result;
})();

// TODO(jmesserly): lots of ways to make this faster:
// - use char codes everywhere instead of 1-char strings
// - use switch instead of contains, indexOf
// - use switch instead of the sequential if tests
// - avoid string concat

/// This class takes care of tokenizing HTML.
class HtmlTokenizer implements Iterator<Token> {
  // TODO(jmesserly): a lot of these could be made private

  final HtmlInputStream stream;

  final bool lowercaseElementName;

  final bool lowercaseAttrName;

  /// True to generate spans in for [Token.span].
  final bool generateSpans;

  /// True to generate spans for attributes.
  final bool attributeSpans;

  /// This reference to the parser is used for correct CDATA handling.
  /// The [HtmlParser] will set this at construction time.
  HtmlParser? parser;

  final Queue<Token?> tokenQueue;

  /// Holds the token that is currently being processed.
  Token? currentToken;

  /// Holds a reference to the method to be invoked for the next parser state.
  late bool Function()


const AsmJitException& ex) {
//!     printf("EXCEPTION THROWN: %s\n", ex.what());
//!     return 1;
//!   }
//!
//!   return 0;
//! }
//! ```
//!
//! If C++ exceptions are not what you like or your project turns off them completely there is still a way of reducing
//! the error handling to a minimum by using a standard setjmp/longjmp approach. AsmJit is exception-safe and cleans
//! up everything before calling the ErrorHandler, so any approach is safe. You can simply jump from the error handler
//! without causing any side-effects or memory leaks. The following example demonstrates how it could be done:
//!
//! ```
//! // Error Handling #3 - Using setjmp/longjmp if exceptions are not allowed.
//! #include <asmjit/x86.h>
//! #include <setjmp.h>
//! #include <stdio.h>
//!
//! class LongJmpErrorHandler : public asmjit::ErrorHandler {
//! public:
//!   inline LongJmpErrorHandler() : err(asmjit::kErrorOk) {}
//!
//!   void handleError(asmjit::Error err, const char* message, asmjit::BaseEmitter* origin) override {
//!     this->err = err;
//!     longjmp(state, 1);
//!   }
//!
//!   jmp_buf state;
//!   asmjit::Error err;
//! };
//!
//! int main(int argc, char* argv[]) {
//!   using namespace asmjit;
//!
//!   JitRuntime rt;
//!   LongJmpErrorHandler eh;
//!
//!   CodeHolder code;
//!   code.init(rt.environment(), rt.cpuFeatures());
//!   code.setErrorHandler(&eh);
//!
//!   x86::Assembler a(&code);
//!
//!   if (!setjmp(eh.state)) {
//!     // Try to emit instruction that doesn't exist.
//!     a.emit(x86::Inst::kIdMov, x86::xmm0, x86::xmm1);
//!   }
//!   else {
//!     Error err = eh.err;
//!     printf("ASMJIT ERROR: 0x%08X [%s]\n", err, DebugUtils::errorAsString(err));
//!   }
//!
//!   return 0;
//! }
//! ```
class ASMJIT_VIRTAPI ErrorHandler {
public:
  ASMJIT_BASE_CLASS(ErrorHandler)

  //! \name Construction & Destruction
  //! \{

  //! Creates a new `ErrorHandler` instance.
  ASMJIT_API ErrorHandler() noexcept;
  //! Destroys the `ErrorHandler` instance.
  ASMJIT_API virtual ~ErrorHandler() noexcept;

  //! \}

  //! \name Interface
  //! \{

  //! Error handler (must be reimplemented).
  //!
  //! Error handler is called after an error happened and before it's propagated to the caller. There are multiple
  //! ways how the error handler can be used:
  //!
  //! 1. User-based error handling without throwing exception or using C's`longjmp()`. This is for users that don't
  //!     use exceptions and want customized error handling.
  //!
  //! 2. Throwing an exception. AsmJit doesn't use exceptions and is completely exception-safe, but you can throw
  //!     exception from your error handler if this way is the preferred way of handling errors in your project.
  //!
  //! 3. Using plain old C's `setjmp()` and `longjmp()`. Asmjit always puts `BaseEmitter` to a consistent state before
  //!    calling `handleError()`  so `longjmp()` can be used without any issues to cancel the code generation if an
  //!    error occurred. There is no difference between exceptions and `longjmp()` from AsmJit's perspective, however,
  //!    never jump outside of `CodeHolder` and `BaseEmitter` scope as you would leak memory.
  ASMJIT_API virtual void handleError(Error err, const char* message, BaseEmitter* origin);

  //! \}
};

//! \}

ASMJIT_END_NAMESPACE

#endif // ASMJIT_CORE_ERRORHANDLER_H_INCLUDED


gin-bottom:      0.5em;
    border-bottom:      solid;
    border-width:       1pt;
}

cfrDoc chapter,
cfrDoc subchapter  {
    margin-top:         6em;
}

cfrDoc chapter>num,
cfrDoc chapter>heading  {
    font-family:        sans-serif;
    font-size:          1.6em;
    font-weight:        normal;
}

cfrDoc chapter>heading+*  {
    border-top:        solid;
    border-width:      1pt;
    margin-top:        2em;
    padding-top:       1em;
}

cfrDoc subchapter>num,
cfrDoc subchapter>heading  {
    font-family:        sans-serif;
    font-size:          1.2em;
    font-weight:        bold;
}

cfrDoc part  {
    margin-bottom:      1.5em;
}

cfrDoc part>num,
cfrDoc part>heading,
cfrDoc subpart>num,
cfrDoc subpart>heading  {
    font-family:        sans-serif;
    font-size:          1.1em;
    font-weight:        bold;
}

cfrDoc section>chapeau,
cfrDoc paragraph  {
    text-indent:        1em;
    margin-left:        0em;
}

cfrDoc section  {
    text-indent:        -2em;
    margin-left:        2em;
}

cfrDoc section>:not(heading):not(num)  {
    margin-left:        -2em; /* sets margin back to normal */
}

cfrDoc section heading::before  {
    content:            " ";
}

cfrDoc section>heading::before  {
    content:            " \00a0";
}

cfrDoc paragraph>heading  {
    font-variant:       none;
    font-style:         italic;
}

cfrDoc level  {
    margin-left:        0em;
    text-indent:        0em;
}

cfrDoc level>heading  {
    display:            block;
    text-align:         center;
    margin-top:         1em;
    font-variant:       small-caps;
}

cfrDoc level>section  {
    margin-top:         0.3em;
}

cfrDoc heading+notes  {
    margin-top:         1.5em;
    /* add space above when notes comes directly after heading */
}

cfrDoc note, cfrDoc editorialNote  {
    display:            block;
    font-size:          0.9em;
    text-indent:        1em;
    text-align:         left;
}

cfrDoc note[topic="citation"]  {
    margin-top:         1em;
    text-indent:        0em;
}

cfrDoc authority, cfrDoc source,
frDoc section authority  {
    display:            block;
    text-indent:        1em;
    text-align:         left;
    font-size:          0.85em;
    margin-top:         0.3em;
}

cfrDoc section>source  {
    margin-top:         0.7em;
    border-width:       1pt;
    text-indent:        0em;
}

cfrDoc appendix>num, cfrDoc appendix>heading  {
    display:            inline;
    font-variant:       small-caps;
    font-size:          1.1em;
}

cfrDoc appendix>p  {
    text-align:         left;
}

cfrDoc appendix>heading+p  {
    /* Adds space above a paragraph right after a heading */
    margin-top:         1em;
}

/* Statute Compilations */
statuteCompilation  {
    display:            block;
    margin-left:        24pt;
    margin-right:       24pt;
    font-size:          10pt;
	font-family: 		"Century


           var originalValue = mainPoint.value;
                var label = new GUIContent();
                label.text = GetLabel();
                var newColor = EditorGUILayout.ColorField(label, originalValue, showEyedropper: false, showAlpha: true, hdr: false);
                selectedPoints[0].value = newColor;
            }
            base.SelectEdit(curve, selectedPoints, mainPoint);
        }
#endif

        public override Color Lerp(Color val1, Color val2, float lerp)
        {
            //this looks better when unity is set to linear rather than gamma color space
            //see https://docs.unity3d.com/Manual/LinearRendering-LinearOrGammaWorkflow.html
            //and https://www.youtube.com/watch?v=LKnqECcg6Gw
            //if working in gamma, you can uncomment the following line to improve the appearance
            //return Color.Lerp(val1.linear,val2.linear,lerp).gamma
            return Color.Lerp(val1, val2,lerp);
        }
    }
}


val designer = designerDao.loadDesigner(it.id)
                if (designer == null) {
                    designerDao.insert(it.mapDesignerForUpsert())
                } else {
                    designerDao.update(it.mapDesignerForUpsert(designer.internalId))
                }
                refreshImages(it)
            }
        }
    }

    suspend fun refreshMissingImages(daysOld: Int = 14, limit: Int = 10) = withContext(Dispatchers.Default) {
        withContext(Dispatchers.IO) { designerDao.loadDesigners() }
            .filter { it.designerThumbnailUrl.isNullOrBlank() &&
                    (it.imagesUpdatedTimestamp == null || it.imagesUpdatedTimestamp.time.isOlderThan(daysOld.days)) }
            .sortedByDescending { it.whitmoreScore }
            .take(limit.coerceIn(0, 25))
            .map { it.mapToModel() }
            .forEach {
                Timber.i("Refreshing missing images for designer $it")
                refreshImages(it)
                delay(2_000)
            }
    }

    private suspend fun refreshImages(designer: Person) = withContext(Dispatchers.IO) {
        val timestamp = Date()
        val response = safeApiCall(context) { api.person(designer.id) }
        if (response.isSuccess) {
            response.getOrNull()?.items?.firstOrNull()?.mapToModel(designer, timestamp)?.let { person ->
                designerDao.updateImageUrls(person.id, person.imageUrl, person.thumbnailUrl, person.imagesUpdatedTimestamp ?: timestamp)
                val thumbnailId = person.thumbnailUrl.getImageId()
                if (thumbnailId != person.heroImageUrl.getImageId()) {
                    Timber.d("Designer $designer's hero URL doesn't match thumbnail ID $thumbnailId")
                    if (thumbnailId == INVALID_IMAGE_ID) {
                        Timber.d("Updating designer $designer with blank hero URL")
                        designerDao.updateHeroImageUrl(designer.id, "")
                    } else {
                        val urlMap = imageRepository.getImageUrls(thumbnailId)
                        urlMap[ImageRepository.ImageType.HERO]?.firstOrNull()?.let { heroUrl ->
                            Timber.d("Updating designer $designer with hero URL $heroUrl")
                            designerDao.updateHeroImageUrl(designer.id, heroUrl)
                        }
                    }
                }
            }
        }
    }

    suspend fun refreshMissingImagesForGame(gameId: Int, daysOld: Int = 14, limit: Int = 10) = withContext(Dispatchers.Default) {
        Timber.i("Refreshing up to $limit designer images from game $gameId missing for more than $daysOld days")
        withContext(Dispatchers.IO) { designerDao.loadDesignersForGame(gameId) }
            .asSequence()
            .filter { it.designerThumbnailUrl.isNullOrBlank() &&
                    (it.imagesUpdatedTimestamp == null || it.imagesUpdatedTimestamp.time.isOlderThan(daysOld.days)) }
            .sortedByDescending { it.whitmoreScore }
            .take(limit.coerceIn(0, 25))
            .map { it.mapToModel() }.toList()
            .forEach {
                Timber.i("Refreshing missing images for designer $it")
                refreshImages(it)
                delay(2_000)
            }
    }

    suspend fun calculateStats(progress: MutableLiveData<Pair<Int, Int>>) = withContext(Dispatchers.Default) {
        val designers = withContext(Dispatchers.IO) { designerDao.loadDesigners() }
            .map { it.mapToModel() }
            .sortedWith(


---------------------
-- Tribute Rewards --
---------------------

ZO_TRIBUTE_REWARDS_ROW_HEIGHT_GAMEPAD = 100

ZO_TributeRewards_Gamepad = ZO_Gamepad_ParametricList_Screen:Subclass()

function ZO_TributeRewards_Gamepad:Initialize(control)
    self.isShowScryableQueued = false
    self.queuedBrowseToAntiquityOrSetData = nil

    self:InitializeControl(control)
    self:InitializeLists()
    self:InitializeEvents()
end

function ZO_TributeRewards_Gamepad:InitializeControl(control)
    GAMEPAD_TRIBUTE_REWARDS_SCENE = ZO_Scene:New("tribute_rewards_gamepad", SCENE_MANAGER)

    local ACTIVATE_ON_SHOW = true
    ZO_Gamepad_ParametricList_Screen.Initialize(self, control, ZO_DO_NOT_CREATE_TAB_BAR, ACTIVATE_ON_SHOW, GAMEPAD_TRIBUTE_REWARDS_SCENE)

    self.fragment = ZO_SimpleSceneFragment:New(control)
    ZO_TRIBUTE_REWARDS_GAMEPAD_FRAGMENT = self.fragment
    self.fragment:SetHideOnSceneHidden(true)
    self.scene:AddFragment(ZO_TRIBUTE_REWARDS_GAMEPAD_FRAGMENT)

    self.currentRewardsType = ZO_TRIBUTE_REWARD_TYPES.SEASON_REWARDS
end

function ZO_TributeRewards_Gamepad:InitializeLists()
    local list = self:GetMainList()
    list:AddDataTemplate("ZO_GamepadItemEntryTemplate", ZO_SharedGamepadEntry_OnSetup, ZO_GamepadMenuEntryTemplateParametricListFunction)
    local USE_DEFAULT_COMPARISON = nil
    list:AddDataTemplateWithHeader("ZO_GamepadItemEntryTemplate", ZO_SharedGamepadEntry_OnSetup, ZO_GamepadMenuEntryTemplateParametricListFunction, USE_DEFAULT_COMPARISON, "ZO_GamepadMenuEntryHeaderTemplate")
    list:SetNoItemText(GetString(SI_TRIBUTE_FINDER_REWARDS_EMPTY))

     -- Initialize each lists' keybinds.
    self.keybindStripDescriptor =
    {
        alignment = KEYBIND_STRIP_ALIGN_LEFT,
        {
            keybind = "UI_SHORTCUT_PRIMARY",
            name = GetString(SI_GAMEPAD_SELECT_OPTION),
            callback = function()
                self:DeactivateList()
                TRIBUTE_REWARDS_LIST_GAMEPAD:Activate()
            end,
            sound = SOUNDS.GAMEPAD_MENU_FORWARD,
        },
    }
    ZO_Gamepad_AddBackNavigationKeybindDescriptorsWithSound(self.keybindStripDescriptor, GAME_NAVIGATION_TYPE_BUTTON)

    self:SetListsUseTriggerKeybinds(true)
    self:RefreshCategories()
    self:RefreshRewardsList()
end

function ZO_TributeRewards_Gamepad:InitializeEvents()
    -- TODO Tribute: Add events here
end

------------------------------------------------
-- Overrides ZO_Gamepad_ParametricList_Screen --
------------------------------------------------

function ZO_TributeRewards_Gamepad:PerformUpdate()
    self:RefreshRewardsList()
end

function ZO_TributeRewards_Gamepad:RefreshKeybinds()
    if self.keybindStripDescriptor and self:IsShowing() then
        if not KEYBIND_STRIP:HasKeybindButtonGroup(self.keybindStripDescriptor) then
            KEYBIND_STRIP:AddKeybindButtonGroup(self.keybindStripDescriptor)
        else
            KEYBIND_STRIP:UpdateKeybindButtonGroup(self.keybindStripDescriptor)
        end
    end
end

---------------------------------------------------
-- End Override ZO_Gamepad_ParametricList_Screen --
--------------------------------------------------


def send_initialize_request(self, project_root):
    request = innpv_pb2.InitializeRequest()
    request.protocol_version = 5
    request.project_root = project_root
    request.entry_point = 'entry_point.py'
    self.send_message(request)


-8px;
}
.m-btn-active,
.s-btn-active {
  background: #e6e6e6;
  color: #00438a;
  border: 1px solid #ddd;
  filter: none;
}
.m-btn-plain-active,
.s-btn-plain-active {
  background: transparent;
  padding: 0;
  border-width: 1px;
  border-style: solid;
  -moz-border-radius: 5px 5px 5px 5px;
  -webkit-border-radius: 5px 5px 5px 5px;
  border-radius: 5px 5px 5px 5px;
}
.m-btn .l-btn-left .l-btn-text {
  margin-right: 20px;
}
.m-btn .l-btn-icon-right .l-btn-text {
  margin-right: 40px;
}
.m-btn .l-btn-icon-right .l-btn-icon {
  right: 20px;
}
.m-btn .l-btn-icon-top .l-btn-text {
  margin-right: 4px;
  margin-bottom: 14px;
}
.m-btn .l-btn-icon-bottom .l-btn-text {
  margin-right: 4px;
  margin-bottom: 34px;
}
.m-btn .l-btn-icon-bottom .l-btn-icon {
  top: auto;
  bottom: 20px;
}
.m-btn .l-btn-icon-top .m-btn-downarrow,
.m-btn .l-btn-icon-bottom .m-btn-downarrow {
  top: auto;
  bottom: 0px;
  left: 50%;
  margin-left: -8px;
}
.m-btn-line {
  display: inline-block;
  position: absolute;
  font-size: 1px;
  display: none;
}
.m-btn .l-btn-left .m-btn-line {
  right: 0;
  width: 16px;
  height: 500px;
  border-style: solid;
  border-color: #bbb;
  border-width: 0 0 0 1px;
}
.m-btn .l-btn-icon-top .m-btn-line,
.m-btn .l-btn-icon-bottom .m-btn-line {
  left: 0;
  bottom: 0;
  width: 500px;
  height: 16px;
  border-width: 1px 0 0 0;
}
.m-btn-large .l-btn-icon-right .l-btn-text {
  margin-right: 56px;
}
.m-btn-large .l-btn-icon-bottom .l-btn-text {
  margin-bottom: 50px;
}
.m-btn-downarrow,
.s-btn-downarrow {
  background: url('images/menu_arrows.png') no-repeat 0 center;
}
.m-btn-plain-active,
.s-btn-plain-active {
  border-color: #ddd;
  background-color: #e6e6e6;
  color: #00438a;
}
.slider-disabled {
  opacity: 0.5;
  filter: alpha(opacity=50);
}
.slider-h {
  height: 22px;
}
.slider-v {
  width: 22px;
}
.slider-inner {
  position: relative;
  height: 6px;
  top: 7px;
  border-width: 1px;
  border-style: solid;
  border-radius: 5px;
}
.slider-handle {
  position: absolute;
  display: block;
  outline: none;
  width: 20px;
  height: 20px;
  top: 50%;
  margin-top: -10px;
  margin-left: -10px;
}
.slider-tip {
  position: absolute;
  display: inline-block;
  line-height: 12px;
  font-size: 12px;
  white-space: nowrap;
  top: -22px;
}
.slider-rule {
  position: relative;
  top: 15px;
}
.slider-rule span {
  position: absolute;
  display: inline-block;
  font-size: 0


Complete\n")

    # ---------------------------------------------------------------------------------------------
    RVMODEL_IO_WRITE_STR(x30, "Test part B4 - test BLTU\n")

    # Address for test results
    RVTEST_SIGBASE(x1, test_B4_res_exc)

inst_4:

    # Register initialization
    li      x5, 5
    li      x6, 6

    # Test
    bltu    x6, x5, 1f + 2
    li      x2, 0xCCCCCCCC
1:
    nop
    nop
    bltu    x5, x6, 1f + 2
    li      x2, 0
1:

    RVMODEL_IO_WRITE_STR(x30, "Test part C  - Complete\n")

    # ---------------------------------------------------------------------------------------------
    RVMODEL_IO_WRITE_STR(x30, "Test part B5 - test BGE\n")

    # Address for test results
    RVTEST_SIGBASE(x1, test_B5_res_exc)

inst_5:

    # Register initialization
    li      x5, 5
    li      x6, 6

    # Test
    bge     x5, x6, 1f + 2
    li      x2, 0xDDDDDDDD
1:
    nop
    nop
    bge     x6, x5, 1f + 2
    li      x2, 0
1:

    RVMODEL_IO_WRITE_STR(x30, "Test part D  - Complete\n")

    # ---------------------------------------------------------------------------------------------
    RVMODEL_IO_WRITE_STR(x30, "Test part B6 - test BGEU\n")

    # Address for test results
    RVTEST_SIGBASE(x1, test_B6_res_exc)

inst_6:

    # Register initialization
    li      x5, 5
    li      x6, 6

    # Test
    bgeu    x5, x6, 1f + 2
    li      x2, 0xEEEEEEEE
1:
    nop
    nop
    bgeu    x6, x5, 1f + 2
    li      x2, 0
1:

    RVMODEL_IO_WRITE_STR(x30, "Test part E  - Complete\n")

    # ---------------------------------------------------------------------------------------------


411;okd集群中添加集群外的glustefs">二、向OKD集群中添加集群外的GlusteFS

配置ansible主机清单/etc/ansible/hosts

[OSEv3:children]
...
glusterfs

[OSEv3:vars]
...
openshift_storage_glusterfs_namespace=app-storage
openshift_storage_glusterfs_storageclass=true
openshift_storage_glusterfs_storageclass_default=false
openshift_storage_glusterfs_block_deploy=true
openshift_storage_glusterfs_block_host_vol_size=100
openshift_storage_glusterfs_block_storageclass=true
openshift_storage_glusterfs_block_storageclass_default=false
openshift_storage_glusterfs_is_native=false
openshift_storage_glusterfs_heketi_is_native=true
openshift_storage_glusterfs_heketi_executor=ssh
openshift_storage_glusterfs_heketi_ssh_port=22
openshift_storage_glusterfs_heketi_ssh_user=root
openshift_storage_glusterfs_heketi_ssh_sudo=false
openshift_storage_glusterfs_heketi_ssh_keyfile="/root/.ssh/id_rsa"

[glusterfs]
gluster1.example.com glusterfs_ip=192.168.10.11 glusterfs_devices='[ "/dev/xvdc", "/dev/xvdd" ]'
gluster2.example.com glusterfs_ip=192.168.10.12 glusterfs_devices='[ "/dev/xvdc", "/dev/xvdd" ]'
gluster3.example.com glusterfs_ip=192.168.10.13 glusterfs_devices='[ "/dev/xvdc", "/dev/xvdd" ]'

执行openshift ansible playbook

ansible-playbook /root/openshift-ansible/playbooks/openshift-glusterfs/config.yml

三、卸载

ansible-playbook -e "openshift_storage_glusterfs_wipe=true" /root/openshift-ansible/playbooks/openshift-glusterfs/uninstall.yml

四、OKD中通过storage动态使用glusterfs作为PVC的后端存储

<h


me(Bold)));
        t.insert(Error,
            Item(RGB::new(0xff, 0x40, 0x40), Some(Bold)));

        return Styler(Arc::new(Theme {
            items: t,
        }));
    }
    pub fn apply(&self, style: Style, data: &str, buf: &mut String) {
        if let Some(Item(col, style)) = self.0.items.get(&style) {
            let mut c = data.color(*col);
            if let Some(s) = style {
                c = c.style(*s);
            }
            write!(buf, "{}", c).unwrap();
        } else {
            buf.push_str(data);
        }
    }
}
<gh_stars>0
#![allow(unused_variables)]

use super::{Buffer2D};
use super::super::math_util::fixed_point::*;
use std::fmt;
use nalgebra::{Vector4};

const WT_W:usize = 128;
const WT_H:usize = 128;

lazy_static! {
    static ref WEIGHT_TABLE_FLOAT:[f32;4*WT_W*WT_H] = {
        let mut table = [0f32;4*WT_W*WT_H];
        for y in 0..WT_H as i32{
            for x in 0..WT_W as i32{

                let index = (WT_W as i32 *y  + x) as usize * 4;
                let u = (x as f32+0.5)/ WT_W as f32 ;
                let v = (y as f32+0.5)/ WT_H as f32;

                let one = 1.0;
                let wtl = (one-u)*(one-v);
                let wtr = (one-v)*u;
                let wbl = (one-u)*v;
                let wbr = u*v;

                table[index+0] = wtl;
                table[index+1] = wtr;
                table[index+2] = wbl;
                table[index+3] = wbr;
            }
        }
        table
    };
}

pub trait Sampler2D<CT,BT:Copy + fmt::Display + Default >{
    fn interpolate<T:Buffer2D<BT>>(&self, x:CT,y:CT,buffer:& T)->BT;
    fn uv_map<T:Buffer2D<BT>>(&self,uv:Vector4<f32>,buffer:& T)->BT;
}

pub struct NearestSampler2D;

pub struct LinearSampler2D;

impl Sampler2D<f32,u32> for NearestSampler2D{
    fn interpolate<T:Buffer2D<u32>>(&self, x: f32, y: f32, buffer: & T)->u32{
         buffer.get((y as u32,x as u32))
    }
    fn uv_map<T:Buffer2D<u32>>(&self,uv:Vector4<f32>,buffer:& T)->u32{
        let w = buffer.width() as f32;
        let h = buffer.height() as f32;
        let u = (w*uv.x).min(w-1.0).max(0.0);
        let v = (h*(1.0-uv.y)).min(h-1.0).max(0.0);
        self.interpolate(u, v, buffer)
    }
}

impl Sampler2D<f32,u32> for LinearSampler2D{
    fn interpolate<T:Buffer2D<u32>>(&self, x: f32, y: f32, src_buffer: & T)->u32{
        let u =  x - (x as i32) as f32;
        let v =  y - (y as i32) as f32;
        let x0 = x as u32;
        let y0 = y as u32;
        let w = src_buffer.width();
        let h = src_buffer.height();

        //clamping 'adjacent indices'
        let x


	}

}

#[repr(C)]
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct StandardCollector_PredictResult {
	pub label: i32,
	pub distance: f64,
}

opencv_type_simple! { crate::face::StandardCollector_PredictResult }

impl StandardCollector_PredictResult {
	/// ## C++ default parameters
	/// * label_: -1
	/// * distance_: DBL_MAX
	pub fn new(label_: i32, distance_: f64) -> Result<crate::face::StandardCollector_PredictResult> {
		unsafe { sys::cv_face_StandardCollector_PredictResult_PredictResult_int_double(label_, distance_) }.into_result()
	}

}
use types::*;
use utils::all::All;

use super::GameState;

use resources::Resources;

impl GameState {
    pub fn animation_update_system(&mut self, dt: f32, res: &mut Resources) -> bool {
        let mut busy = false;

        let mut finished = Vec::new();

        for (p, a, e) in self
            .positions
            .iter_mut()
            .zip(self.animations.iter_mut())
            .zip(self.entities.iter())
            .filter_map(|x| x.all())
        {
            if a.time_left > 0.0 {
                busy = true;
                let dt = if a.start_delay > 0.0 {
                    let step = dt.min(a.start_delay);
                    a.start_delay -= step;
                    dt - step
                } else {
                    dt
                };
                if a.sound_start != Sounds::None && a.start_delay <= 0.0 {
                    res.play_sound(a.sound_start);
                    a.sound_start = Sounds::None;
                }
                let time_step = dt.min(a.time_left);
                *p += (a.target_pos - *p) * time_step / a.time_left;
                a.time_left -= dt;
            } else {
                finished.push(*e);
                res.play_sound(a.sound_stop);
            }
        }

        for e in finished.into_iter() {
            let idx = self.ent_lookup[&e];
            if let Some(target) = self.animations[idx].take().unwrap().target_stack {
                let tidx = self.ent_lookup[&target];
                let card = self.stacks[idx].take().unwrap().pop_card().unwrap();
                self.stacks[tidx].as_mut().unwrap().push_card(card);
                self.dirty = true;
            }
            self.remove_entity(e);
        }

        busy
    }
}
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.

//! Utilities for scoring payment channels.
//!
//! [`Scorer`] may be given to [`find_route`] to score payment channels during path finding when a
//! custom [`Score`] implementation is not needed.
//!
//! # Example
//!
//! ```
//! # extern crate secp256k1;
//! #
//! # use lightning::routing::network_graph::NetworkGraph;
//! # use lightning::routing::router::{RouteParameters, find_route};
//! # use lightning::routing::scoring::{Scorer, ScoringParameters};
//! # use lightning::util::logger::


0.6V6h1v8.6H148.2z M144.8,11.5c0,0.8,0.2,1.4,0.5,1.8
			s0.7,0.6,1.2,0.6s0.9-0.2,1.2-0.6s0.5-1,0.5-1.7c0-0.9-0.2-1.5-0.5-1.9s-0.7-0.6-1.2-0.6s-0.9,0.2-1.2,0.6S144.8,10.7,144.8,11.5z
			"/>
		<path d="M155.1,12.6l1.1,0.1c-0.2,0.6-0.5,1.1-1,1.5s-1.1,0.5-1.8,0.5c-0.9,0-1.6-0.3-2.2-0.8s-0.8-1.3-0.8-2.4
			c0-1,0.3-1.9,0.8-2.4s1.2-0.9,2.1-0.9c0.8,0,1.5,0.3,2,0.8s0.8,1.4,0.8,2.4c0,0.1,0,0.2,0,0.3h-4.6c0,0.7,0.2,1.2,0.6,1.6
			s0.8,0.5,1.3,0.5c0.4,0,0.7-0.1,1-0.3S154.9,13.1,155.1,12.6z M151.6,10.9h3.5c0-0.5-0.2-0.9-0.4-1.2c-0.3-0.4-0.8-0.6-1.3-0.6
			s-0.9,0.2-1.2,0.5S151.7,10.4,151.6,10.9z"/>
		<path d="M161.5,14.6v-0.8c-0.4,0.6-1,0.9-1.7,0.9c-0.5,0-1-0.1-1.4-0.4s-0.7-0.7-1-1.1s-0.3-1.1-0.3-1.7c0-0.6,0.1-1.2,0.3-1.7
			s0.5-0.9,0.9-1.2s0.9-0.4,1.4-0.4c0.4,0,0.7,0.1,1,0.2s0.5,0.4,0.7,0.6V6h1v8.6H161.5z M158.2,11.5c0,0.8,0.2,1.4,0.5,1.8
			s0.7,0.6,1.2,0.6s0.9-0.2,1.2-0.6s0.5-1,0.5-1.7c0-0.9-0.2-1.5-0.5-1.9s-0.7-0.6-1.2-0.6s-0.9,0.2-1.2,0.6S158.2,10.7,158.2,11.5z
			"/>
	</g>
	<g>
		<path class="st3" d="M105.7,11.7l1-0.2c0.1,0.4,0.2,0.7,0.5,1s0.6,0.3,1.1,0.3s0.8-0.1,1.1-0.3s0.4-0.4,0


fg(unix)]
    pub fn new(executor: E, exec_tmout: Duration) -> Self {
        let milli_sec = exec_tmout.as_millis();
        let it_value_some = Timeval {
            tv_sec: (milli_sec / 1000) as i64,
            tv_usec: (milli_sec % 1000) as i64,
        };
        let it_value_zero = Timeval {
            tv_sec: 0,
            tv_usec: 0,
        };
        let it_interval_some = Timeval {
            tv_sec: 0,
            tv_usec: 0,
        };
        let it_interval_zero = Timeval {
            tv_sec: 0,
            tv_usec: 0,
        };
        let itimerval = Itimerval {
            it_value: it_value_some,
            it_interval: it_interval_some,
        };
        let itimerval_zero = Itimerval {
            it_value: it_value_zero,
            it_interval: it_interval_zero,
        };
        Self {
            executor,
            itimerval,
            itimerval_zero,
        }
    }

    #[cfg(windows)]
    pub fn new(executor: E, exec_tmout: Duration) -> Self {
        Self { executor }
    }

    /// Retrieve the inner `Executor` that is wrapped by this `TimeoutExecutor`.
    pub fn inner(&mut self) -> &mut E {
        &mut self.executor
    }
}

impl<E, EM, I, S, Z> Executor<EM, I, S, Z> for TimeoutExecutor<E>
where
    E: Executor<EM, I, S, Z>,
    I: Input,
{
    fn run_target(
        &mut self,
        fuzzer: &mut Z,
        state: &mut S,
        mgr: &mut EM,
        input: &I,
    ) -> Result<ExitKind, Error> {
        #[cfg(unix)]
        unsafe {
            setitimer(ITIMER_REAL, &mut self.itimerval, null_mut());
        }
        #[cfg(windows)]
        {
            // TODO
        }

        let ret = self.executor.run_target(fuzzer, state, mgr, input);

        #[cfg(unix)]
        unsafe {
            setitimer(ITIMER_REAL, &mut self.itimerval_zero, null_mut());
        }
        #[cfg(windows)]
        {
            // TODO
        }

        ret
    }
}

impl<E, OT> HasObservers<OT> for TimeoutExecutor<E>
where
    E: HasObservers<OT>,
    OT: ObserversTuple,
{
    #[inline]
    fn observers(&self) -> &OT {
        self.executor.observers()
    }

    #[inline]
    fn observers_mut(&mut self) -> &mut OT {
        self.executor.observers_mut()
    }
}

impl<E, EM, I, OT, S, Z> HasObserversHooks<EM, I, OT, S, Z> for TimeoutExecutor<E>
where
    E: HasObservers<OT>,
    I: Input,
    OT: ObserversTuple + HasExecHooksTuple<EM, I, S, Z>,
{
}
use std::collections::HashMap;
use std::ops::{Index, IndexMut};
mod input;

fn main() {
	println!("{}", solve(input::puzzle_input()));
	// 2346881602152
}

fn solve(input: &str) -> u64 {
	let mut machine = Machine::new();
	machine.run(input);
	machine.mem.words.values().sum()
}

#[derive(Debug)]
struct Machine {
	mask: Mask,
	mem: Mem
}

impl Machine {


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import traceback
import io
import json

import stixmarx

from stix2slider.options import initialize_options
from stix2slider.convert_stix import convert_indicator

def read2str(fname):
    in_str = None
    try:
        with io.open(fname, "r") as f:
            in_str = f.read()
    except:
        print traceback.format_exc().decode('utf-8')

    return in_str

def write2file(fname, out_str):
    with open(fname, "w") as f:
        f.write(out_str)

def stix2to1():
    try:
        data_dir = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../data'))

        in_str = read2str(data_dir + '/stixv2.json')

        initialize_options()

        container = stixmarx.new()
        stix_package = container.package

        json_content = json.loads(in_str)
        if type(json_content) == list:
            for json_data in json_content:
                if "type" in json_data and json_data["type"] == "indicator":
                    indicator = convert_indicator(json_data)
                    stix_package.add_indicator(indicator)
        else:
            if "type" in json_content and json_content["type"] == "bundle":
                if "objects" in json_content and json_content["objects"] and type(json_content["objects"]) == list:
                    for json_data in json_content["objects"]:
                        if "type" in json_data and json_data["type"] == "indicator":
                            indicator = convert_indicator(json_data)
                            stix_package.add_indicator(indicator)

            elif "type" in json_content and json_content["type"] == "indicator":
                indicator = convert_indicator(json_content)
                stix_package.add_indicator(indicator)

        container.flush()
        container = None

#        print stix_package.to_xml()
        out_fname = './stixv2.xml'
        write2file(out_fname, stix_package.to_xml())

    except:
        print traceback.format_exc().decode('utf-8')

if __name__ == "__main__":
     stix2to1()


, "\n")
	renderedLines = strings.Trim(renderedLines, "\n")
	return renderedLines, nil
}
package geos

// #include "go-geos.h"
import "C"

import (
	"runtime"
	"unsafe"
)

// A CoordSeq is a coordinate sequence.
type CoordSeq struct {
	context    *Context
	s          *C.struct_GEOSCoordSeq_t
	owner      *Geom
	dimensions int
	size       int
}

// NewCoordSeq returns a new CoordSeq.
func (c *Context) NewCoordSeq(size, dims int) *CoordSeq {
	c.mutex.Lock()
	defer c.mutex.Unlock()
	return c.newNonNilCoordSeq(C.GEOSCoordSeq_create_r(c.cHandle, C.uint(size), C.uint(dims)))
}

// NewCoordSeqFromCoords returns a new CoordSeq populated with coords.
func (c *Context) NewCoordSeqFromCoords(coords [][]float64) *CoordSeq {
	c.mutex.Lock()
	defer c.mutex.Unlock()
	return c.newNonNilCoordSeq(c.newGEOSCoordSeqFromCoords(coords))
}

// Clone returns a clone of s.
func (s *CoordSeq) Clone() *CoordSeq {
	s.context.mutex.Lock()
	defer s.context.mutex.Unlock()
	return s.context.newNonNilCoordSeq(C.GEOSCoordSeq_clone_r(s.context.cHandle, s.s))
}

// Dimensions returns the dimensions of s.
func (s *CoordSeq) Dimensions() int {
	return s.dimensions
}

// IsCCW returns if s is counter-clockwise.
func (s *CoordSeq) IsCCW() bool {
	s.context.mutex.Lock()
	defer s.context.mutex.Unlock()
	var cIsCCW C.char
	switch C.GEOSCoordSeq_isCCW_r(s.context.cHandle, s.s, &cIsCCW) {
	case 1:
		return cIsCCW != 0
	default:
		panic(s.context.err)
	}
}

// Ordinate returns the idx-th dim coordinate of s.
func (s *CoordSeq) Ordinate(idx, dim int) float64 {
	s.context.mutex.Lock()
	defer s.context.mutex.Unlock()
	if idx < 0 || s.size <= idx {
		panic(errIndexOutOfRange)
	}
	if dim < 0 || s.dimensions <= dim {
		panic(errDimensionOutOfRange)
	}
	var value float64
	if C.GEOSCoordSeq_getOrdinate_r(s.context.cHandle, s.s, C.uint(idx), C.uint(dim), (*C.double)(&value)) == 0 {
		panic(s.context.err)
	}
	return value
}

// SetOrdinate sets the idx-th dim coordinate of s to val.
func (s *CoordSeq) SetOrdinate(idx, dim int, val float64) {
	s.context.mutex.Lock()
	defer s.context.mutex.Unlock()
	if idx < 0 || s.size <= idx {
		panic(errIndexOutOfRange)
	}
	if dim < 0 || s.dimensions <= dim {
		panic(errDimensionOutOfRange)
	}
	if C.GEOSCoordSeq_setOrdinate_r(s.context.cHandle, s.s, C.uint(idx), C.uint(dim), C.double(val)) == 0 {
		panic(s.context.err)
	}
}

// SetX sets the idx-th X coordinate of s to val.
func (s *CoordSeq) SetX(idx int, val float64) {
	s.context.mutex.Lock()
	defer s


able() {
    return stub.stopScanRunCallable();
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * List CrawledUrls under a given ScanRun.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient.create()) {
   *   ListCrawledUrlsRequest request =
   *       ListCrawledUrlsRequest.newBuilder()
   *           .setParent("parent-995424086")
   *           .setPageToken("pageToken873572522")
   *           .setPageSize(883849137)
   *           .build();
   *   for (CrawledUrl element : webSecurityScannerClient.listCrawledUrls(request).iterateAll()) {
   *     // doThingsWith(element);
   *   }
   * }
   * }

   *
   * @param request The request object containing all of the parameters for the API call.
   * @throws com.google.api.gax.rpc.ApiException if the remote call fails
   */
  public final ListCrawledUrlsPagedResponse listCrawledUrls(ListCrawledUrlsRequest request) {
    return listCrawledUrlsPagedCallable().call(request);
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * List CrawledUrls under a given ScanRun.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (WebSecurityScannerClient webSecurityScannerClient = WebSecurityScannerClient.create()) {
   *   ListCrawledUrlsRequest request =
   *       ListCrawledUrlsRequest.newBuilder()
   *           .setParent("parent-995424086")
   *           .setPageToken("pageToken873572522")
   *           .setPageSize(883849137)
   *           .build();
   *   ApiFuture<CrawledUrl> future =
   *       webSecurityScannerClient.listCrawledUrlsPagedCallable().futureCall(request);
   *   // Do something.
   *   for (CrawledUrl element : future.get().iterateAll()) {
   *     // doThingsWith(element);
   *   }
   * }
   * }

   */
  public final UnaryCallable<ListCrawledUrlsRequest, ListCrawledUrlsPagedResponse>
      listCrawledUrlsPagedCallable() {
    return stub.listCrawledUrlsPagedCallable();
  }

  // AUTO-GENERATED DOCUMENTATION AND METHOD.
  /**
   * List CrawledUrls under a given ScanRun.
   *
   *
Sample code:
   *
   *
{@code
   * // This snippet has been automatically generated and should be regarded as a code template only.
   * // It will require modifications to work:
   * // - It may require correct/in-range values for request initialization.
   * // - It may require specifying regional endpoints when creating the service client as shown in
   * // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
   * try (WebSecurityScannerClient web


                        1),
                    getModuleTranslations());

    public static final DriveTrainSimulationConfig mapleSimConfig =
            DriveTrainSimulationConfig.Default()
                    .withRobotMass(ROBOT_MASS_KG)
                    .withCustomModuleTranslations(getModuleTranslations())
                    .withGyro(COTS.ofNav2X())
                    .withSwerveModule(
                            new SwerveModuleSimulationConfig(
                                    DCMotor.getKrakenX60(1),
                                    DCMotor.getFalcon500(1),
                                    TunerConstants.FrontLeft.DriveMotorGearRatio,
                                    TunerConstants.FrontLeft.SteerMotorGearRatio,
                                    Volts.of(TunerConstants.FrontLeft.DriveFrictionVoltage),
                                    Volts.of(TunerConstants.FrontLeft.SteerFrictionVoltage),
                                    Meters.of(TunerConstants.FrontLeft.WheelRadius),
                                    KilogramSquareMeters.of(TunerConstants.FrontLeft.SteerInertia),
                                    WHEEL_COF));

    static final Lock odometryLock = new ReentrantLock();
    private final GyroIO gyroIO;
    public Angle[] SwerveTurnAngle =
            new Angle[] {Radians.zero(), Radians.zero(), Radians.zero(), Radians.zero()};
    public Angle[] SwerveDriveAngle =
            new Angle[] {Radians.zero(), Radians.zero(), Radians.zero(), Radians.zero()};

    private Consumer<Pose2d> resetSimulationPoseCallBack = null;

    private final GyroIOInputsAutoLogged gyroInputs = new GyroIOInputsAutoLogged();
    private final Module[] modules = new Module[4]; // FL, FR, BL, BR
    private final SysIdRoutine sysId;
    private final SysIdRoutine turnSysId;
    private final Alert gyroDisconnectedAlert =
            new Alert("Disconnected gyro, using kinematics as fallback.", AlertType.kError);
    @AutoLogOutput private Rotation2d desiredHeading;

    private Rotation2d gyroOffset = Rotation2d.kZero;

    private Field2d field = new Field2d();

    public SwerveDriveKinematics kinematics = new SwerveDriveKinematics(getModuleTranslations());
    private Rotation2d rawGyroRotation = new Rotation2d();
    public SwerveModulePosition[] lastModulePositions = // For delta tracking
            new SwerveModulePosition[] {
                new SwerveModulePosition(),
                new SwerveModulePosition(),
                new SwerveModulePosition(),
                new SwerveModulePosition()
            };
    private final SwerveDrivePoseEstimator globalPoseEstimator =
            new SwerveDrivePoseEstimator(
                    kinematics, rawGyroRotation, lastModulePositions, new Pose2d());
    private final SwerveDrivePoseEstimator localPoseEstimator =
            new SwerveDrivePoseEstimator(
                    kinematics, rawGyroRotation, lastModulePositions, new Pose2d());

    private static final GalacticSlewRateLimiter slewRateLimiterX =
            new GalacticSlewRateLimiter(1.5);
    private static final GalacticSlewRateLimiter slewRateLimiterY =
            new GalacticSlewRateLimiter(1.5);

    private boolean useLocalInAuto = false;

    public boolean getUseLocalInAuto() {
        return useLocalInAuto;
    }

    public void setUseLocalInAuto(boolean useLocalInAuto) {
        this.useLocalInAuto = useLocalInAuto;
    }

    public Drive(
            GyroIO gyroIO, ModuleIO[] moduleIOS, Optional<SwerveDriveSimulation> driveSimulation) {
        this(gyroIO, moduleI


48px;
}

.my-tree-joint-over .my-tree-close {
	background: url(../images/gxt/tree/vnode_transparent.gif) no-repeat 0px
		-15px;
}

.my-tree-notchecked {
	background: url(../images/gxt/tree/notchecked.gif) no-repeat 0px 50%;
}

.my-tree-checked {
	background: url(../images/gxt/tree/checked.gif) no-repeat 0px 50%;
}

.my-tree-loading .tree-folder {
	background: url(../images/gxt/icons/wait.gif) no-repeat 0px -1px
		!important;
}

.my-tree-loading .my-tree-item-text span {
	font-style: italic;
}

.x-ftree-selected .x-ftree-text {
	background-color: #d9e8fb;
}

.x-ftree-node-over .x-ftree-text {
	background-color: #eee;
}

.x-ftree-item {
	line-height: 18px;
}

.x-ftree-joint,.x-ftree-icon {
	border: 0 none;
	height: 18px;
	margin: 0;
	padding: 0;
	vertical-align: top;
	width: 16px;
	background-position: center;
	background-repeat: no-repeat;
}

.x-ftree-text {
	color: black;
	font: normal 11px arial, tahoma, helvetica, sans-serif;
	white-space: nowrap;
	text-decoration: none;
	color: black;
	padding-left: 4px;
	vertical-align: middle;
	line-height: 18px;
	padding: 2px 4px 4px 4px;
}

/* some default icons for leaf/folder */
.x-ftree-expanded .x-ftree-icon {
	background-image: url(../images/default/tree/folder-open.gif);
}

.x-ftree-leaf .x-ftree-icon {
	background-image: url(../images/default/tree/leaf.gif);
}

.x-ftree-collapsed .x-ftree-icon {
	background-image: url(../images/gxt/icons/folder-closed.gif);
}

/* Arrows */
.x-ftree-arrows .x-ftree-joint {
	background: transparent;
}

.x-ftree-arrows .x-ftree-joint-plus {
	background: transparent url(../images/default/tree/arrows.gif) no-repeat
		0 0;
}

.x-ftree-arrows .x-ftree-joint-minus {
	background: transparent url(../images/default/tree/arrows.gif) no-repeat
		-16px 0;
}

.x-ftree-arrows .x-ftree-ec-over .x-ftree-joint-plus {
	background-position: -32px 0;
}

.x-ftree-arrows .x-ftree-ec-over .x-ftree-joint-minus {
	background-position: -48px 0;
}

.x-ftree2-selected {
	background-color: #d9e8fb !important;
}

.x-ftree2-node-over {
	background-color: #eee;
}

.x-ftree2-node-drop {
	background-color: #defadc;
}

.x-ftree2-joint,.x-ftree2-icon {
	border: 0 none;
	height: 18px;
	margin: 0;
	padding: 0;
	vertical-align: top;
	width: 16px;
	background-position: center;
	background-repeat: no-repeat;
}

.x-ftree2-joint div {
	width: 16p


'tcx> {
    fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::Lifetime<RustInterner<'tcx>> {
        use rustc_middle::ty::RegionKind::*;

        match self {
            ReEarlyBound(_) => {
                panic!("Should have already been substituted.");
            }
            ReLateBound(db, br) => match br.kind {
                ty::BoundRegionKind::BrAnon(var) => {
                    chalk_ir::LifetimeData::BoundVar(chalk_ir::BoundVar::new(
                        chalk_ir::DebruijnIndex::new(db.as_u32()),
                        var as usize,
                    ))
                    .intern(interner)
                }
                ty::BoundRegionKind::BrNamed(_def_id, _name) => unimplemented!(),
                ty::BrEnv => unimplemented!(),
            },
            ReFree(_) => unimplemented!(),
            ReStatic => chalk_ir::LifetimeData::Static.intern(interner),
            ReVar(_) => unimplemented!(),
            RePlaceholder(placeholder_region) => {
                chalk_ir::LifetimeData::Placeholder(chalk_ir::PlaceholderIndex {
                    ui: chalk_ir::UniverseIndex { counter: placeholder_region.universe.index() },
                    idx: 0,
                })
                .intern(interner)
            }
            ReEmpty(_) => unimplemented!(),
            // FIXME(chalk): need to handle ReErased
            ReErased => unimplemented!(),
        }
    }
}

impl<'tcx> LowerInto<'tcx, Region<'tcx>> for &chalk_ir::Lifetime<RustInterner<'tcx>> {
    fn lower_into(self, interner: &RustInterner<'tcx>) -> Region<'tcx> {
        let kind = match self.data(interner) {
            chalk_ir::LifetimeData::BoundVar(var) => ty::RegionKind::ReLateBound(
                ty::DebruijnIndex::from_u32(var.debruijn.depth()),
                ty::BoundRegion { kind: ty::BrAnon(var.index as u32) },
            ),
            chalk_ir::LifetimeData::InferenceVar(_var) => unimplemented!(),
            chalk_ir::LifetimeData::Placeholder(p) => {
                ty::RegionKind::RePlaceholder(ty::Placeholder {
                    universe: ty::UniverseIndex::from_usize(p.ui.counter),
                    name: ty::BoundRegionKind::BrAnon(p.idx as u32),
                })
            }
            chalk_ir::LifetimeData::Static => ty::RegionKind::ReStatic,
            chalk_ir::LifetimeData::Phantom(_, _) => unimplemented!(),
        };
        interner.tcx.mk_region(kind)
    }
}

impl<'tcx> LowerInto<'tcx, chalk_ir::Const<RustInterner<'tcx>>> for ty::Const<'tcx> {
    fn lower_into(self, interner: &RustInterner<'tcx>) -> chalk_ir::Const<RustInterner<'tcx>> {
        let ty = self.ty.lower_into(interner);
        let value = match self.val {
            ty::ConstKind::Value(val) => {
                chalk_ir::ConstValue::Concrete(chalk_ir::ConcreteConst { interned: val })
            }
            ty::ConstKind::Bound(db, bound) => chalk_ir::ConstValue::BoundVar(
                chalk_ir::BoundVar::new(chalk_ir::DebruijnIndex::new(db.as_u32()), bound.index()),
            ),
            _ => unimplemented!("Const not implemented. {:?}", self),
        };


 STATUS_BAR_LOCALIZER.formatText("lockedBy", status.lockOwnerName ?: "")
      this.btnLock.text =
          if (GPCloudOptions.userId.value?.equals(status.lockOwnerId) == true) STATUS_BAR_LOCALIZER.formatText("locked")
          else lockOwner
      this.btnLock.tooltip = Tooltip(lockOwner)
    } else {
      this.btnLock.graphic = FontAwesomeIconView(FontAwesomeIcon.UNLOCK)
      this.btnLock.text = STATUS_BAR_LOCALIZER.formatText("notLocked")
      this.btnLock.tooltip = Tooltip(STATUS_BAR_LOCALIZER.formatText("notLocked.tooltip"))
    }

    this.status = status
  }

  private fun onOnlineModeChange(newValue: OnlineDocumentMode) {
    GlobalScope.launch(Dispatchers.JavaFx) {
      updateOnlineMode(newValue)
    }
  }

  private fun updateOnlineMode(mode: OnlineDocumentMode) {
    when (mode) {
      OnlineDocumentMode.ONLINE_ONLY -> {
        this.btnOffline.run {
          text = STATUS_BAR_LOCALIZER.formatText("mode.onlineOnly")
          graphic = FontAwesomeIconView(FontAwesomeIcon.CLOUD)
          tooltip = Tooltip(STATUS_BAR_LOCALIZER.formatText("mode.onlineOnly.tooltip"))
          Decorator.removeAllDecorations(this)
          isDisable = false
        }
        this.btnLock.isDisable = false
      }
      OnlineDocumentMode.MIRROR -> {
        this.btnOffline.run {
          text = STATUS_BAR_LOCALIZER.formatText("mode.mirror")
          graphic = FontAwesomeIconView(FontAwesomeIcon.CLOUD_DOWNLOAD)
          tooltip = Tooltip(STATUS_BAR_LOCALIZER.formatText("mode.mirror.tooltip"))
          Decorator.removeAllDecorations(this)
          isDisable = false
        }
        this.btnLock.isDisable = false
      }
      OnlineDocumentMode.OFFLINE_ONLY -> {
        this.btnOffline.run {
          text = STATUS_BAR_LOCALIZER.formatText("mode.offline")
          graphic = FontAwesomeIconView(FontAwesomeIcon.CLOUD_DOWNLOAD)
          tooltip = Tooltip(STATUS_BAR_LOCALIZER.formatText("mode.offline.tooltip"))
          Decorator.addDecoration(this, GraphicDecoration(createWarningDecoration(), Pos.BOTTOM_LEFT, 6.0, -4.0))
          isDisable = true
        }

        observableDocument.value.asOnlineDocument()?.let {
          if (it is GPCloudDocument) {
            reconnectStatus.startReconnectPing(it)
          }
        }
        this.uiFacade.showOptionDialog(
            JOptionPane.WARNING_MESSAGE,
            STATUS_BAR_LOCALIZER.formatText("mode.offline.warning"),
            arrayOf(OkAction.createVoidAction("ok"))
        )
        this.btnLock.isDisable = true
      }
    }
  }

  // This is called when cloud document changes and we receive an update notification.
  // We want to show a dialog asking to reload document or ignore the update.
  private fun handleLatestVersionChange(newDocument: Document, doc: OnlineDocument, newValue: LatestVersion) {
    OptionPaneBuilder<Boolean>().run {
      i18n = RootLocalizer.createWithRootKey("cloud.loadLatestVersion")
      graphic = FontAwesomeIconView(FontAwesomeIcon.REFRESH)
      elements = listOf(
          OptionElementData("reload", userData = true,  isSelected = true),
          OptionElementData("ignore", userData = false)
      )
      titleHelpString?.update(newValue.author, GanttLanguage.getInstance().formatDate(GanttCalendar.getInstance().apply {
        time = Date(newValue.timestamp)
      }))

      showDialog { choice ->
        if (choice) {
          GlobalScope.launch(Dispatchers.IO) {
            doc.fetch().also {
              it.update()


import warnings
warnings.simplefilter("ignore", DeprecationWarning)

import os
import sys
from pathlib import Path
from dotenv import load_dotenv
load_dotenv(verbose=True)
import pandas as pd

root = str(Path(__file__).resolve().parents[1])
sys.path.append(root)

from finworld.log import logger
from alpaca.data.historical import StockHistoricalDataClient, NewsClient
from alpaca.data.requests import StockBarsRequest, NewsRequest
from alpaca.data.timeframe import TimeFrame, TimeFrameUnit
from datetime import datetime

async def price():
    client = StockHistoricalDataClient(
        api_key=os.getenv("ALPACA_API_KEY"),
        secret_key=os.getenv("ALPACA_SECRET_KEY")
    )

    request_params = StockBarsRequest(
        symbol_or_symbols="AAPL",
        timeframe=TimeFrame.Minute,
        start=datetime.strptime("2025-05-01", '%Y-%m-%d'),
        end=datetime.strptime("2025-05-07", '%Y-%m-%d')
    )

    bars = client.get_stock_bars(request_params)

    df = bars.df
    df = df.reset_index()

    df['timestamp'] = df['timestamp'].dt.tz_convert('America/New_York')
    df['timestamp'] = df['timestamp'].dt.tz_localize(None)

    return df

def get_news():
    client = NewsClient(
        api_key=os.getenv("ALPACA_API_KEY"),
        secret_key=os.getenv("ALPACA_SECRET_KEY")
    )

    request_params = NewsRequest(
        symbols="AAPL",
        start=datetime.strptime("2025-05-01", '%Y-%m-%d'),
        end=datetime.strptime("2025-05-07", '%Y-%m-%d'),
        include_content=True,
    )
    news = client.get_news(request_params)
    df = news.df
    df['timestamp'] = pd.to_datetime(df['created_at'])

    print(df.columns)

    df = df.reset_index()
    df['timestamp'] = df['timestamp'].dt.tz_convert('America/New_York')
    df['timestamp'] = df['timestamp'].dt.tz_localize(None)

    return df

if __name__ == "__main__":

    # Initialize the logger
    log_path = os.path.join(root, "workdir", "tests")
    os.makedirs(log_path, exist_ok=True)

    log_path = os.path.join(log_path, "logger.log")
    logger.init_logger(log_path=log_path, accelerator=None)

    # price = asyncio.run(price())
    # logger.info(price)

    news = get_news()
    for i in range(10):
        logger.info(news.iloc[i].to_dict())


------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int CBoneFollower::ObjectCaps()
{
	CBaseEntity *pOwner = GetOwnerEntity();
	if ( pOwner )
	{
		if( pOwner->m_iGlobalname != NULL_STRING )
		{
			int caps = BaseClass::ObjectCaps() | pOwner->ObjectCaps();
			caps &= ~FCAP_ACROSS_TRANSITION;
			return caps;
		}
	}

	return BaseClass::ObjectCaps();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBoneFollower::Use( CBaseEntity *pActivator, CBaseEntity *pCaller, USE_TYPE useType, float value )
{
	CBaseEntity *pOwner = GetOwnerEntity();
	if ( pOwner )
	{
		pOwner->Use( pActivator, pCaller, useType, value );
		return;
	}

	BaseClass::Use( pActivator, pCaller, useType, value );
}

//-----------------------------------------------------------------------------
// Purpose: Pass on Touch calls to the entity we're following
//-----------------------------------------------------------------------------
void CBoneFollower::Touch( CBaseEntity *pOther )
{
	CBaseEntity *pOwner = GetOwnerEntity();
	if ( pOwner )
	{
		//TODO: fill in the touch trace with the hitbox number associated with this bone
		pOwner->Touch( pOther );
		return;
	}

	BaseClass::Touch( pOther );
}

//-----------------------------------------------------------------------------
// Purpose: Pass on trace attack calls to the entity we're following
//-----------------------------------------------------------------------------
void CBoneFollower::TraceAttack( const CTakeDamageInfo &info, const Vector &vecDir, trace_t *ptr )
{
	CBaseEntity *pOwner = GetOwnerEntity();
	if ( pOwner )
	{
		pOwner->DispatchTraceAttack( info, vecDir, ptr );
		return;
	}

	BaseClass::TraceAttack( info, vecDir, ptr );
}

LINK_ENTITY_TO_CLASS( phys_bone_follower, CBoneFollower );

// create a manager and a list of followers directly from a ragdoll
void CreateBoneFollowersFromRagdoll( CBaseAnimating *pEntity, CBoneFollowerManager *pManager, vcollide_t *pCollide )
{
	IVPhysicsKeyParser *pParse = physcollision->VPhysicsKeyParserCreate( pCollide );
	while ( !pParse->Finished() )
	{
		const char *pBlock = pParse->GetCurrentBlockName();
		if ( !strcmpi( pBlock, "solid" ) )
		{
			solid_t solid;

			pParse->ParseSolid( &solid, NULL );
			// collisions are off by default, turn them on
			solid.params.enableCollisions = true;
			solid.params.pName = STRING(pEntity->GetModelName());

			pManager->AddBoneFollower( pEntity, solid.name, &solid );
		}
		else
		{
			pParse->SkipBlock();
		}
	}
	physcollision->VPhysicsKeyParserDestroy( pParse );
}
// datatest.cpp - written and placed in the public domain by Wei Dai

#define CRYPTOPP_DEFAULT_NO_DLL
#define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1

#include "cryptlib.h"
#include "factory.h"
#include "integer.h"
#include "filters.h"
#include "hex.h"
#include "randpool.h"
#include "files.h"
#include "trunhash.h"
#include "queue.h"
#include "smartptr.h"
#include "validate.h"
#include "hkdf.h"


rn a mediacloud admin client for the logged in user.  Passing in a key lets you ovveride reading it out
    # of the request object (which you might not have access to)
    mc_key_to_use = user_mc_key
    if mc_key_to_use is None:
        mc_key_to_use = user_mediacloud_key()
    user_mc = mediacloud.api.AdminMediaCloud(mc_key_to_use)
    try:
        user_mc.V2_API_URL = config.get('MEDIA_CLOUD_API_URL')
    except ConfigException:
        pass  # just use the default API url because a custom one is not defined
    return user_mc

def user_mediacloud_client(user_mc_key=None):
    # Return a mediacloud client for the logged in user.  Passing in a key lets you ovveride reading it out
    # of the request object (which you might not have access to)
    mc_key_to_use = user_mc_key
    if mc_key_to_use is None:
        mc_key_to_use = user_mediacloud_key()
    user_mc = mediacloud.api.MediaCloud(mc_key_to_use)
    try:
        user_mc.V2_API_URL = config.get('MEDIA_CLOUD_API_URL')
    except ConfigException:
        pass  # just use the default API url because a custom one is not defined
    return user_mc