/////////////////////////////////////////////////////////////////////////
///@system 新一代交易所系统
///@company 上海期货信息技术有限公司
///@file ThostFtdcTraderApi.h
///@brief 定义了客户端接口
///@history
///20060106	赵鸿昊		创建该文件
/////////////////////////////////////////////////////////////////////////

#if !defined(THOST_FTDCTRADERAPI_H)
#define THOST_FTDCTRADERAPI_H

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#include "ThostFtdcUserApiStruct.h"

#if defined(ISLIB) && defined(WIN32)
#ifdef LIB_TRADER_API_EXPORT
#define TRADER_API_EXPORT __declspec(dllexport)
#else
#define TRADER_API_EXPORT __declspec(dllimport)
#endif
#else
#define TRADER_API_EXPORT
#endif

class CThostFtdcTraderSpi
{
public:
	///当客户端与交易后台建立起通信连接时（还未登录前），该方法被调用。
	virtual void OnFrontConnected(){};

	///当客户端与交易后台通信连接断开时，该方法被调用。当发生这个情况后，API会自动重新连接，客户端可不做处理。
	///@param nReason 错误原因
	///        0x1001 网络读失败
	///        0x1002 网络写失败
	///        0x2001 接收心跳超时
	///        0x2002 发送心跳失败
	///        0x2003 收到错误报文
	virtual void OnFrontDisconnected(int nReason){};

	///心跳超时警告。当长时间未收到报文时，该方法被调用。
	///@param nTimeLapse 距离上次接收报文的时间
	virtual void OnHeartBeatWarning(int nTimeLapse){};

	///客户端认证响应
	virtual void OnRspAuthenticate(CThostFtdcRspAuthenticateField *pRspAuthenticateField, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};

	///登录请求响应
	virtual void OnRspUserLogin(CThostFtdcRspUserLoginField *pRspUserLogin, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};

	///登出请求响应
	virtual void OnRspUserLogout(CThostFtdcUserLogoutField *pUserLogout, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};

	///用户口令更新请求响应
	virtual void OnRspUserPasswordUpdate(CThostFtdcUserPasswordUpdateField *pUserPasswordUpdate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};

	///资金账户口令更新请求响应
	virtual void OnRspTradingAccountPasswordUpdate(CThostFtdcTradingAccountPasswordUpdateField *pTradingAccountPasswordUpdate, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};

	///报单录入请求响应
	virtual void OnRspOrderInsert(CThostFtdcInputOrderField *pInputOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};

	///预埋单录入请求响应
	virtual void OnRspParkedOrderInsert(CThostFtdcParkedOrderField *pParkedOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};

	///预埋撤单录入请求响应
	virtual void OnRspParkedOrderAction(CThostFtdcParkedOrderActionField *pParkedOrderAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};

	///报单操作请求响应
	virtual void OnRspOrderAction(CThostFtdcInputOrderActionField *pInputOrderAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};

	///查询最大报单数量响应
	virtual void OnRspQueryMaxOrderVolume(CThostFtdcQueryMaxOrderVolumeField *pQueryMaxOrderVolume, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};

	///投资者结算结果确认响应
	virtual void OnRspSettlementInfoConfirm(CThostFtdcSettlementInfoConfirmField *pSettlementInfoConfirm, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};

	///删除预埋单响应
	virtual void OnRspRemoveParkedOrder(CThostFtdcRemoveParkedOrderField *pRemoveParkedOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};

	///删除预埋撤单响应
	virtual void OnRspRemoveParkedOrderAction(CThostFtdcRemoveParkedOrderActionField *pRemoveParkedOrderAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};

	///执行宣告录入请求响应
	virtual void OnRspExecOrderInsert(CThostFtdcInputExecOrderField *pInputExecOrder, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};

	///执行宣告操作请求响应
	virtual void OnRspExecOrderAction(CThostFtdcInputExecOrderActionField *pInputExecOrderAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};

	///询价录入请求响应
	virtual void OnRspForQuoteInsert(CThostFtdcInputForQuoteField *pInputForQuote, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};

	///报价录入请求响应
	virtual void OnRspQuoteInsert(CThostFtdcInputQuoteField *pInputQuote, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};

	///报价操作请求响应
	virtual void OnRspQuoteAction(CThostFtdcInputQuoteActionField *pInputQuoteAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};

	///批量报单操作请求响应
	virtual void OnRspBatchOrderAction(CThostFtdcInputBatchOrderActionField *pInputBatchOrderAction, CThostFtdcRspInfoField *pRspInfo, int nRequestID, bool bIsLast) {};

	///申请组合录入请求响应
	virtual void OnRspCombActionInsert(CThostFtdcInputCombActionField *pInputComb


ostadas-13142.json)
 * [Seared Shrimp With Warm New Potato Salad 1039](../../index/s/seared-shrimp-with-warm-new-potato-salad-1039.json)
 * [Shishito Pepper Potato Hash With Fried Eggs 51252300](../../index/s/shishito-pepper-potato-hash-with-fried-eggs-51252300.json)
 * [Shredded Sweet Potato And Carrot Fritters Ukoy](../../index/s/shredded-sweet-potato-and-carrot-fritters-ukoy.json)
 * [Shrimp And Sweet Potato Cakes With Chayote Slaw And Chipotle Sauce 102840](../../index/s/shrimp-and-sweet-potato-cakes-with-chayote-slaw-and-chipotle-sauce-102840.json)
 * [Sicilian Style Potato Gratin 241633](../../index/s/sicilian-style-potato-gratin-241633.json)
 * [Simple Two Potato Gratin 236539](../../index/s/simple-two-potato-gratin-236539.json)
 * [Skirt Steak And Horseradish Potato Salad 354291](../../index/s/skirt-steak-and-horseradish-potato-salad-354291.json)
 * [Smoked Oyster And Potato Salad With Arugula 102928](../../index/s/smoked-oyster-and-potato-salad-with-arugula-102928.json)
 * [Smoked Peppered Mackerel And Sour Cream On Homemade Potato Chips 101192](../../index/s/smoked-peppered-mackerel-and-sour-cream-on-homemade-potato-chips-101192.json)
 * [Smoked Salmon Tartare On New Potato Slices 10119](../../index/s/smoked-salmon-tartare-on-new-potato-slices-10119.json)
 * [Smoked Sausage Kale And Potato Soup 3114](../../index/s/smoked-sausage-kale-and-potato-soup-3114.json)
 * [Southwestern Sweet Potato Saute 233217](../../index/s/southwestern-sweet-potato-saute-233217.json)
 * [Spanish Potato Omelet Tortilla De Papa Espanola With Romesco Sauce 51121800](../../index/s/spanish-potato-omelet-tortilla-de-papa-espanola-with-romesco-sauce-51121800.json)
 * [Spiced Sweet Potato And Parsnip Tian](../../index/s/spiced-sweet-potato-and-parsnip-tian.json)
 * [Spiced Sweet Potato Bundt Cake 51256680](../../index/s/spiced-sweet-potato-bundt-cake-51256680.json)
 * [Spiced Sweet Potato Gratin 236482](../../index/s/spiced-sweet-potato-gratin-236482.json)
 * [Spicy Beef And Sweet Potato Stir Fry 14503](../../index/s/spicy-beef-and-sweet-potato-stir-fry-14503.json)
 * [Spicy Curry Noodle Soup With Chicken And Sweet Potato 241112](../../index/s/spicy-curry-noodle-soup-with-chicken-and-sweet-potato-241112.json)
 * [Spicy Jalapeno Sweet Potato Fries 51206450](../../index/s/spicy-jalapeno-sweet-potato-fries-51206450.json)
 * [Spicy Potato Tagine With Preserved Lemon And Olives 231569](../../index/s/spicy-potato-tagine-with-preserved-lemon-and-olives-231569.json)
 * [Spicy Sweet Potato Spread 358369](../../index/s/spicy-sweet-potato-spread-358369.json)
 * [Split Pea Soup With Sausage And Potato 23


>
        /// Отправить метаданные всем игрокам которые видят эту сущность без этой
        /// </summary>
        private void SendMetadataToAllAssociatedPlayers()
        {
            DataWatcher dataWatcher = TrackedEntity.MetaData;
            if (dataWatcher.IsChanged)
            {
                SendPacketPlayersCurrent(new PacketS1CEntityMetadata(TrackedEntity.Id, dataWatcher, false));
            }
        }

        /// <summary>
        /// Удалите отслеживаемого игрока из нашего списка и
        /// прикажите отслеживаемому игроку уничтожить нас из своего мира.
        /// </summary>
        public void RemoveTrackedPlayerSymmetric(EntityPlayerServer entity)
        {
            if (TrackingPlayers.ContainsValue(entity))
            {
                TrackingPlayers.Remove(entity);
                entity.SendRemoveEntity(TrackedEntity);
            }
        }

        /// <summary>
        /// Обновить видимость сущностей с списком игроков
        /// </summary>
        /// <param name="playerEntities">список игроков</param>
        public void UpdatePlayerList(MapListEntity playerEntities)
        {
            PlayerEntitiesUpdated = false;

            // Загружаем сущности игроку, в первом такте игрока
            bool beginFlagPlayer = (TrackedEntity is EntityPlayerServer entityPlayerServer && entityPlayerServer.TrackerBeginFlag == 1);

            if (beginFlagPlayer || TrackedEntity.IsDead || glm.distance(TrackedEntity.Position, LastTrackedEntityPos) > 2f)
            {
                LastTrackedEntityPos = TrackedEntity.Position;
                PlayerEntitiesUpdated = true;
                UpdatePlayerEntities(playerEntities);
            }

            if (TrackedEntity is EntityLiving entityLiving)
            {
                if (entityLiving.ActionChanged != EnumActionChanged.None)
                {
                    SendPacketPlayers(new PacketS14EntityMotion(entityLiving));
                    entityLiving.ActionNone();
                }
            } else if (TrackedEntity is EntityItem entityItem)
            {
                if (entityItem.IsMoving)
                {
                    SendPacketPlayers(new PacketS14EntityMotion(entityItem));
                }
            }
            else if (TrackedEntity is EntityThrowable entityThrowable)
            {
                SendPacketPlayers(new PacketS14EntityMotion(entityThrowable));
            }

            if (TrackedEntity.MetaData.IsChanged) //UpdateCounter % UpdateFrequency == 0)
            {
                SendMetadataToAllAssociatedPlayers();
                //if ("передвижение самостоятельное, не на ком-то или чём-то")
                {
                 //   EncodedPos = new vec3i(TrackedEntity.Position * 32f);
                }
        //        int var23;
        //        int var24;

        //        if (this.trackedEntity.ridingEntity == null)
        //        {
        //            ++this.ticksSinceLastForcedTeleport;
        //            var23 = MathHelper.floor_double(this.trackedEntity.posX * 32.0D);
        //            var24 = MathHelper.floor_double(this.trackedEntity.posY * 32.0D);
        //            int var25 = MathHelper.floor_double(this.trackedEntity.posZ * 32.0D);
        //            int var27 = MathHelper.floor_float(this.trackedEntity.rotationYaw * 256.0F / 360.0F);
        //            int var28 = MathHelper.floor_float(this.trackedEntity.rotationPitch * 256.0F / 360.0F);
        //            int var29 = var23 - this.encodedPosX;
        //            int var30 = var24 - this.encodedPosY;
        //            int var9 = var25 - this.encodedPosZ;
        //


m6 = rotation.z * num3;
            float num7 = rotation.x * num2;
            float num8 = rotation.x * num3;
            float num9 = rotation.y * num3;
            float num10 = rotation.w * num;
            float num11 = rotation.w * num2;
            float num12 = rotation.w * num3;
            Vector3 result;
            result.x = (1f - (num5 + num6)) * point.x + (num7 - num12) * point.y + (num8 + num11) * point.z;
            result.y = (num7 + num12) * point.x + (1f - (num4 + num6)) * point.y + (num9 - num10) * point.z;
            result.z = (num8 - num11) * point.x + (num9 + num10) * point.y + (1f - (num4 + num5)) * point.z;
            return result;
        }

        // Token: 0x06004932 RID: 18738 RVA: 0x0007E968 File Offset: 0x0007CB68
        private static bool IsEqualUsingDot(float dot)
        {
            return dot > 0.999999f;
        }

        // Token: 0x06004933 RID: 18739 RVA: 0x0007E988 File Offset: 0x0007CB88
        public static bool operator ==(Quaternion lhs, Quaternion rhs)
        {
            return lhs.x == rhs.x & lhs.y == rhs.y & lhs.z == rhs.z & lhs.w == rhs.w;
        }

        // Token: 0x06004934 RID: 18740 RVA: 0x0007E9AC File Offset: 0x0007CBAC
        public static bool operator !=(Quaternion lhs, Quaternion rhs)
        {
            return !(lhs == rhs);
        }

        // Token: 0x06004935 RID: 18741 RVA: 0x0007E9CC File Offset: 0x0007CBCC
        public static float Dot(Quaternion a, Quaternion b)
        {
            return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
        }

        // Token: 0x06004938 RID: 18744 RVA: 0x0007EA4C File Offset: 0x0007CC4C
        public static float Angle(Quaternion a, Quaternion b)
        {
            float num = Dot(a, b);
            return (!IsEqualUsingDot(num)) ? (Mathf.Acos(Mathf.Min(Mathf.Abs(num), 1f)) * 2f * 57.29578f) : 0f;
        }

        // Token: 0x06004939 RID: 18745 RVA: 0x0007EAA0 File Offset: 0x0007CCA0
        private static Vector3 Internal_MakePositive(Vector3 euler)
        {
            float num = -0.005729578f;
            float num2 = 360f + num;
            if (euler.x < num)
            {
                euler.x += 360f;
            }
            else if (euler.x > num2)
            {
                euler.x -= 360f;
            }
            if (euler.y < num)
            {
                euler.y += 360f;
            }
            else if (euler.y > num2)
            {
                euler.y -= 360f;
            }
            if (euler.z < num)
            {
                euler.z += 360f;
            }
            else if (euler.z > num2)
            {
                euler.z -= 360f;
            }
            return euler;
        }

        // Token: 0x06004941 RID: 18753 RVA: 0x0007EC9C File Offset: 0x0007CE9C
        public static Quaternion Normalize(Quaternion q)
        {
            float num = Mathf.Sqrt(Quaternion.Dot(q, q));
            Quaternion result;
            if (num < Mathf.Epsilon)
            {
                result = Quaternion.identity;
            }
            else
            {
                result = new Quaternion(q.x / num, q.y / num, q.z / num, q.w / num);
            }
            return result;
        }

        // Token: 0x06


r el in data {
        ctx.update(el.as_ref());
        ctx.update(&[0])
    }
    base64::encode_config(ctx.finish(), base64::URL_SAFE_NO_PAD)
}
// Copyright 2019 vtext developers
//
// Licensed under the Apache License, Version 2.0,
// <http://apache.org/licenses/LICENSE-2.0>. This file may not be copied,
// modified, or distributed except according to those terms.

use pyo3::prelude::*;
use pyo3::wrap_pyfunction;

mod stem;
mod tokenize;
mod tokenize_sentence;
mod utils;
mod vectorize;

use vtext::metrics;

///  dice_similarity(x, y)
///
///  Sørensen–Dice similarity coefficient
///
///  This similarity tokenizes the input string x, y as 2-char n-grams,
///  into two sets of tokens X, Y then computes,
///
///  similarity(x, y) = 2 * |X ∩ Y| / (|X| + |Y|)
///
///  where |X| is the cardinality of set X.
///
///  Parameters
///  ----------
///  x : str
///     string to compare
///  y : str
///     string to compare
///
///  Result
///  ------
///  similarity : float
///     computed similarity
///
///  Example
///  -------
///  >>> dice_similarity('yesterday', 'today')
///  0.333..
#[pyfunction]
pub fn dice_similarity(x: &str, y: &str) -> PyResult<f64> {
    Ok(metrics::string::dice_similarity(x, y))
}

///  jaro_similarity(x, y)
///
///  Jaro similarity
///
///  The `Jaro
///  similarity <https://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance#Jaro_Similarity>`_
///  accounts for the minimal number of character transpositions needed
///  to change one word in another.
///
///  References
///  ----------
///
///  <NAME> (1989). Advances in record linkage methodology
///  as applied to the 1985 census of Tampa Florida. Journal of the
///  American Statistical Association. 84 (406): 414-20.
///
///  Parameters
///  ----------
///  x : str
///     string to compare
///  y : str
///     string to compare
///
///  Result
///  ------
///  similarity : float
///     computed similarity
///
///  Example
///  -------
///  >>> jaro_similarity('yesterday', 'today')
///  0.581..
#[pyfunction]
pub fn jaro_similarity(x: &str, y: &str) -> PyResult<f64> {
    Ok(metrics::string::jaro_similarity(x, y))
}

///  jaro_winkler_similarity(x, y, p, max_l)
///
///  Jaro Winkler similarity
///
///  The `Jaro-Winkler
///  similarity <https://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance>`_
///  accounts for the minimal number of character transpositions needed
///  to change one word in another, and the length of the longest common prefix
///
///  The default values for parameters are ``p=0.1``, ``max_l=4``
///
///  References
///  ----------
///
///  <NAME>. 1990. String Comparator Metrics and Enhanced
///  Decision Rules in the Fellegi-Sunter Model of Record Linkage.
///  Proceedings of the Section on Survey Research Methods.
///  American Statistical Association: 354-359.
///
///  Parameters
///  ----------
///  x : str
///     string to compare
///  y : str
///     string to compare
///  p : float, default=0.1
///     the constant scaling factor to overweigh common prefixes
///  max_l : int, default=4
///     the length of common prefix at the start


score).toStrictEqual({
        amount: 0.65,
        answers: 0.35,
        hints: 0.15,
        time: 0.15
      });
    });
  });
});

describe('partial_score=false', () => {
  const options1 = {
    ...options,
    partial_score: false
  };

  describe('verdict=true', () => {
    const options2 = {
      ...options1,
      verdict: true
    };

    it(`Should work for all correct answers`, () => {
      const score = calculateScore({
        ...options2,
        totalAnswers: 1,
        totalCorrectAnswers: 1
      });

      expect(score).toStrictEqual({
        amount: 1,
        answers: 0.7,
        hints: 0.15,
        time: 0.15
      });
    });
  });

  describe('verdict=false', () => {
    const options2 = {
      ...options1,
      verdict: false
    };

    it(`Should work for partial correct answers`, () => {
      const score = calculateScore({
        ...options2,
        totalAnswers: 2,
        totalCorrectAnswers: 1
      });

      expect(score).toStrictEqual({
        amount: 0,
        answers: 0.35,
        hints: 0.15,
        time: 0.15
      });
    });
  });
});
export class Pedidos{
    id : number;
    idUsuario : number;
    fecha : Date;
    numeroLibros : number;
    precioTotal : number;

    constructor(idUsuario: number, fecha : Date, numeroLibros:number, precioTotal:number){
        this.idUsuario = idUsuario;
        this.fecha = fecha;
        this.numeroLibros = numeroLibros;
        this.precioTotal = precioTotal;
    }
}namespace task5 {

    export interface sorte {
        ueberschrift: string;
        preis: number;
        name: string;
        type: string;
        value: string;
    }

    export interface sorteangabe {
        [key: string]: sorte[];
    }

    export let ausfuellen: sorteangabe
        = {
        "sorten": [
            { ueberschrift: "Sorten", preis: 0.90, name: "Schokolade", type:"checkbox", value:"Schokolade"},
            { ueberschrift: "Sorten", preis: 0.90, name: "Soya Schokolade", type:"checkbox", value:"Soya Schokolade"},
            { ueberschrift: "Sorten", preis: 0.90, name: "Vanille", type:"checkbox", value:"Vanille"},
            { ueberschrift: "Sorten", preis: 0.90, name: "Erdbeere", type:"checkbox", value:"Erdbeere"},
            { ueberschrift: "Sorten", preis: 0.90, name: "Banane", type:"checkbox", value:"Banane"},
        ]  ,
        "zusaetze": [
                { ueberschrift: "Zusätze", preis: 0.20, name: "Streusel", type:"checkbox", value:"Streusel"},
                { ueberschrift: "Zusätze", preis: 0.20, name: "Sahne", type:"checkbox", value:"Sahne"}
            ],
        }}interface Foo {
    foo: true; // nothing special. We are test object equality.
}

export module module {
    function createFoo() : Foo;
    function equalFoo(f: Foo): true;
}import { ISoldier } from "./ISoldier";
import { IRandomEventBehavior } from "./IRandomEventBehavior";

export interface IDisplayAdapter {
    gameInitialized(): void;
    playerCreated(name: string): void;

    soldierCreated(soldier: ISoldier): void;
    soldiersCreated(player: string, count: number): void;

    gameStarted(): void;

    attack(attacker: ISoldier, defender: ISoldier, attack: string, dmg: n


::Reg<chipid_cidr::CHIPID_CIDR_SPEC>,
    #[doc = "0x04 - Chip ID Extension Register"]
    pub chipid_exid: crate::Reg<chipid_exid::CHIPID_EXID_SPEC>,
}
#[doc = "CHIPID_CIDR register accessor: an alias for `Reg<CHIPID_CIDR_SPEC>`"]
pub type CHIPID_CIDR = crate::Reg<chipid_cidr::CHIPID_CIDR_SPEC>;
#[doc = "Chip ID Register"]
pub mod chipid_cidr;
#[doc = "CHIPID_EXID register accessor: an alias for `Reg<CHIPID_EXID_SPEC>`"]
pub type CHIPID_EXID = crate::Reg<chipid_exid::CHIPID_EXID_SPEC>;
#[doc = "Chip ID Extension Register"]
pub mod chipid_exid;
<filename>runtime/src/function_kind.rs
use alloc::boxed::Box;
use core::hash::{Hash, Hasher};
use core::{fmt, ptr};

use gc::{Gc, Trace};

use super::{Object, Scope, Value, Vector};

pub enum FunctionKind {
    Internal(Gc<dyn Value>),
    External(Box<dyn Fn(&Gc<Object<Scope>>, &Gc<Object<Vector>>) -> Gc<dyn Value>>),
}

impl Trace for FunctionKind {
    #[inline]
    fn trace(&mut self, marked: bool) {
        match self {
            FunctionKind::Internal(ref mut v) => {
                v.trace(marked);
            }
            _ => {}
        }
    }
}

impl Eq for FunctionKind {}

impl PartialEq for FunctionKind {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        match self {
            &FunctionKind::Internal(ref body) => match other {
                &FunctionKind::Internal(ref other_body) => body == other_body,
                _ => false,
            },
            &FunctionKind::External(ref func) => match other {
                &FunctionKind::External(ref other_func) => ::core::ptr::eq(func, other_func),
                _ => false,
            },
        }
    }
}

impl fmt::Debug for FunctionKind {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            &FunctionKind::Internal(ref body) => write!(f, "{:?}", body),
            &FunctionKind::External(_) => f.write_str(":external"),
        }
    }
}

impl Hash for FunctionKind {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        match self {
            &FunctionKind::Internal(ref body) => body.hash(state),
            &FunctionKind::External(ref func) => ptr::hash(func, state),
        }
    }
}

impl FunctionKind {
    #[inline]
    pub fn new_internal(body: Gc<dyn Value>) -> Self {
        FunctionKind::Internal(body)
    }
    #[inline]
    pub fn new_external<F>(body: F) -> Self
    where
        F: 'static + Fn(&Gc<Object<Scope>>, &Gc<Object<Vector>>) -> Gc<dyn Value>,
    {
        FunctionKind::External(Box::new(body))
    }

    #[inline]
    pub fn is_internal(&self) -> bool {
        match self {
            &FunctionKind::Internal(_) => true,
            &FunctionKind::External(_) => false,
        }
    }
    #[inline]
    pub fn is_external(&self) -> bool {
        !self.is_internal()
    }
}
<reponame>kneitinger/nightgraph
use super::*;
use kurbo::BezPath;
use kurbo::Shape as KurboShape;

pub struct PolyBuilder {
    points: Option<Vec<Point>>,
    stroke_width: f64,
    smooth: bool,
    precompute: bool,
}

impl Default for PolyBuilder {
    fn default() -> Self {


bol-description"]={en:["CAC 40 Index"],ro:["CAC 40 Index"]},e.exports["#TVC:ES10-symbol-description"]={en:["Spain Government Bonds 10 YR"],ro:["Spain Government Bonds 10 YR"]},e.exports["#TVC:EUBUND-symbol-description"]={en:["Euro Bund"],ro:["Euro Bund"]},e.exports["#TVC:GB02-symbol-description"]={en:["UK Government Bonds 2 YR"],ro:["UK Government Bonds 2 YR"]},e.exports["#TVC:GB10-symbol-description"]={en:["UK Government Bonds 10 YR"],ro:["UK Government Bonds 10 YR"]},e.exports["#TVC:GOLD-symbol-description"]={en:["CFDs on Gold (US$ / OZ)"],ro:["CFDs on Gold (US$ / OZ)"]},e.exports["#TVC:ID03-symbol-description"]={en:["Indonesia Government Bonds 3 YR"],ro:["Indonesia Government Bonds 3 YR"]},e.exports["#TVC:ID10-symbol-description"]={en:["Indonesia Government Bonds 10 YR"],ro:["Indonesia Government Bonds 10 YR"]},e.exports["#TVC:PALLADIUM-symbol-description"]={en:["CFDs on Palladium (US$ / OZ)"],ro:["CFDs on Palladium (US$ / OZ)"]},e.exports["#TVC:PT10-symbol-description"]={en:["Portugal Government Bonds 10 YR"],ro:["Portugal Government Bonds 10 YR"]},e.exports["#TVC:SILVER-symbol-description"]={en:["CFDs on Silver (US$ / OZ)"],ro:["CFDs on Silver (US$ / OZ)"]},e.exports["#TSX:TSX-symbol-description"]={en:["S&P/TSX Composite Index"],ro:["S&P/TSX Composite Index"]},e.exports["#OANDA:CH20CHF-symbol-description"]={en:["Swiss 20 Index"],ro:["Swiss 20 Index"]},e.exports["#TVC:SHCOMP-symbol-description"]={en:["Shanghai Composite Index"],ro:["Shanghai Composite Index"]},e.exports["#NZX:ALLC-symbol-description"]={en:["S&P/NZX All Index (Capital Index)"],ro:["S&P/NZX All Index (Capital Index)"]},e.exports["#AMEX:SHYG-symbol-description"]={en:["Shares 0-5 YEAR High Yield Corporate Bond ETF"],ro:["Shares 0-5 YEAR High Yield Corporate Bond ETF"]},e.exports["#TVC:AU10-symbol-description"]={en:["Australia Government Bonds 10 YR"],ro:["Australia Government Bonds 10 YR"]},e.exports["#TVC:CN10-symbol-description"]={en:["China Government Bonds 10 YR"],ro:["China Government Bonds 10 YR"]},e.exports["#TVC:KR10-symbol-description"]={en:["Korea Government Bonds 10 YR"],ro:["Korea Government Bonds 10 YR"]},e.exports["#NYMEX:RB1!-symbol-description"]={en:["RBOB Gasoline Futures"],ro:["RBOB Gasoline Futures"]},e.exports["#NYMEX:HO1!-symbol-description"]={en:["NY Harbor ULSD Futures"],ro:["NY Harbor ULSD Futures"]},e.exports["#NYMEX:AEZ1!-symbol-description"]={en:["NY Ethanol Futures"],ro:["NY Ethanol Futures"]},e.exports["#OANDA:XCUUSD-symbol-description"]={en:["CFDs on Copper (US$ / lb)"],ro:["CFDs on Copper (US$ / lb)"]},e.exports["#COMEX:ZA1!-symbol-description"]={en:["Zinc Futures"],ro:["Zinc Futures"]},e.exports["#CBOT:ZW1!-symbol-description"]={en


// This is free and unencumbered software released into the public domain.
//
// Anyone is free to copy, modify, publish, use, compile, sell, or
// distribute this software, either in source code form or as a compiled
// binary, for any purpose, commercial or non-commercial, and by any
// means.

#define ENABLE_QREGS
//#define ENABLE_HELLO
//#define ENABLE_RVTST
#define ENABLE_SIEVE
#define ENABLE_MULTST
#define ENABLE_STATS

#ifndef ENABLE_QREGS
#  undef ENABLE_RVTST
#endif

// Only save registers in IRQ wrapper that are to be saved by the caller in
// the RISC-V ABI, with the excpetion of the stack pointer. The IRQ handler
// will save the rest if necessary. I.e. skip x3, x4, x8, x9, and x18-x27.
#undef ENABLE_FASTIRQ

#def ENABLE_FASTIRQ

#include "custom_ops.S"

	.section .text
	.global irq
	#.global hello
	.global sieve
	.global multest
	.global hard_mul
	.global hard_mulh
	.global hard_mulhsu
	.global hard_mulhu
	.global hard_div
	.global hard_divu
	.global hard_rem
	.global hard_remu
	.global stats
	.global enable_timer
	.global main

reset_vec:
	// no more than 16 bytes here !
	// picorv32_waitirq_insn(zero)
	picorv32_maskirq_insn(zero, zero)
	j start

/* Interrupt handler
 **********************************/

.balign 16
irq_vec:
	/* save registers */

	picorv32_setq_insn(q2, x1)
	picorv32_setq_insn(q3, x2)

	lui x1, %hi(irq_regs)
	addi x1, x1, %lo(irq_regs)

	picorv32_getq_insn(x2, q0)
	sw x2,   0*4(x1)

	picorv32_getq_insn(x2, q2)
	sw x2,   1*4(x1)

	picorv32_getq_insn(x2, q3)
	sw x2,   2*4(x1)

#ifdef ENABLE_FASTIRQ
	sw x3,   3*4(x1)
	sw x4,   4*4(x1)
	sw x8,   8*4(x1)
	sw x9,   9*4(x1)
	sw x18, 18*4(x1)
	sw x19, 19*4(x1)
	sw x20, 20*4(x1)
	sw x21, 21*4(x1)
	sw x22, 22*4(x1)
	sw x23, 23*4(x1)
	sw x24, 24*4(x1)
	sw x25, 25*4(x


{
			var image = this.imageBundles[i].getImage(key);

			if (image != null)
			{
				return image;
			}
		}
	}

	return null;
};

/**
 * Group: Order
 */

/**
 * Function: orderCells
 *
 * Moves the given cells to the front or back. The change is carried out
 * using <cellsOrdered>. This method fires <mxEvent.ORDER_CELLS> while the
 * transaction is in progress.
 *
 * Parameters:
 *
 * back - Boolean that specifies if the cells should be moved to back.
 * cells - Array of <mxCells> to move to the background. If null is
 * specified then the selection cells are used.
 */
mxGraph.prototype.orderCells = function(back, cells)
{
	if (cells == null)
	{
		cells = mxUtils.sortCells(this.getSelectionCells(), true);
	}

	this.model.beginUpdate();
	try
	{
		this.cellsOrdered(cells, back);
		this.fireEvent(new mxEventObject(mxEvent.ORDER_CELLS,
				'back', back, 'cells', cells));
	}
	finally
	{
		this.model.endUpdate();
	}

	return cells;
};

/**
 * Function: cellsOrdered
 *
 * Moves the given cells to the front or back. This method fires
 * <mxEvent.CELLS_ORDERED> while the transaction is in progress.
 *
 * Parameters:
 *
 * cells - Array of <mxCells> whose order should be changed.
 * back - Boolean that specifies if the cells should be moved to back.
 */
mxGraph.prototype.cellsOrdered = function(cells, back)
{
	if (cells != null)
	{
		this.model.beginUpdate();
		try
		{
			for (var i = 0; i < cells.length; i++)
			{
				var parent = this.model.getParent(cells[i]);

				if (back)
				{
					this.model.add(parent, cells[i], i);
				}
				else
				{
					this.model.add(parent, cells[i],
							this.model.getChildCount(parent) - 1);
				}
			}

			this.fireEvent(new mxEventObject(mxEvent.CELLS_ORDERED,
					'back', back, 'cells', cells));
		}
		finally
		{
			this.model.endUpdate();
		}
	}
};

/**
 * Group: Grouping
 */

/**
 * Function: groupCells
 *
 * Adds the cells into the given group. The change is carried out using
 * <cellsAdded>, <cellsMoved> and <cellsResized>. This method fires
 * <mxEvent.GROUP_CELLS> while the transaction is in progress. Returns the
 * new group. A group is only created if there is at least one entry in the
 * given array of cells.
 *
 * Parameters:
 *
 * group - <mxCell> that represents the target group. If null is specified
 * then a new group is created using <createGroupCell>.
 * border - Optional integer that specifies the border between the child
 * area and the group bounds. Default is 0.
 * cells - Optional array of <mxCells> to be grouped. If null is specified
 * then the selection cells are used.
 */
mxGraph.prototype.groupCells = function(group, border, cells)
{
	if (cells == null)
	{
		cells = mxUtils.sortCells(this.getSelectionCells(), true);
	}

	cells = this.getCellsForGroup(cells);

	if (group == null)
	{
		group = this.createGroupCell(cells);
	}

	var bounds = this.getBoundsForGroup(group, cells, border);

	if (cells.length > 1 && bounds != null)
	{
		// Uses parent of group or


`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建，默认使用前者，后者为使用STS鉴权时使用，详见“使用STS创建标签管理(TAG) Client”小节。
2. `SignOption`字段为生成签名字符串时的选项，详见下表说明：

名称          | 类型  | 含义
--------------|-------|-----------
HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头
Timestamp     | int64 | 生成的签名字符串中使用的时间戳，默认使用请求发送时的值
ExpireSeconds | int   | 签名字符串的有效期

     其中，HeadersToSign默认为`Host`，`Content-Type`，`Content-Length`，`Content-MD5`；TimeStamp一般为零值，表示使用调用生成认证字符串时的时间戳，用户一般不应该明确指定该字段的值；ExpireSeconds默认为1800秒即30分钟。
3. `Retry`字段指定重试策略，目前支持两种：`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者，该重试策略是指定最大重试次数、最长重试时间和重试基数，按照重试基数乘以2的指数级增长的方式进行重试，直到达到最大重试测试或者最长重试时间为止。

# 主要接口

标签管理(TAG)API对于每个HTTP请求，认证签名放在Authorization头域中，后端统一认证。且后端在Response头域中会添加x-bce-request-id，作为请求唯一标识，方便追踪定位问题。

目前支持的标签管理(TAG)API接口如下：

- 创建标签
- 删除标签
- 标签列表
- 查看标签下绑定的资源
- 标签列表
- 批量绑定资源
- 批量解绑资源
- 删除标签关联关系
- 全量更新资源的绑定关系

### 创建标签

使用以下代码可以创建标签
```go
args := &TagsRequest{
    Tags: []Tag{
    {
        TagKey:   "key",
        TagValue: "val",
    }, {
        TagKey:   "key",
        TagValue: "val1",
    },
    },
}

result, err := client.CreateTags(args)
if err != nil {
    fmt.Println("CreateTags failed:", err)
} else {
    fmt.Println("CreateTags success: ", result)
}
```

> **提示：**
> 1.  接口详细描述请参考标签管理(TAG)[API文档](https://cloud.baidu.com/doc/TAG/s/Okbrb3ral)。

### 删除标签

使用以下代码可以删除标签
```go
args := &TagsRequest{
    Tags: []Tag{
    {
        TagKey:   "key",
        TagValue: "val",
    }, {
        TagKey:   "key",
        TagValue: "val1",
    },
    },
}

result, err := client.DeleteTags(args)
if err != nil {
    fmt.Println("DeleteTags failed:", err)
} else {
    fmt.Println("DeleteTags success: ")
}


�생은 에너지 큐브의 대규모 응용의 시작을 알렸으며, 이는 곳 전 세계의 큰 변화를 불러올 것이다……]]
	},
	[2106] = {
		group_ID = 6,
		name = "미디어 기록：전통적인 업계를 보호하자. ε-cube를 경계하라!",
		subTitle = "",
		pic = "2106",
		id = 2106,
		is_classified = 0,
		content = [[
……ε-cube 응용에 반대하는 시위는 벌써 6주에 접어들었습니다. 시위에 참여하는 인원은 계속해서 증가하고 있습니다.
 대다수의 시위자는 ε-cube가 인체 건강에 영향을 주는 전자파를 발산하며, 심지어 인류의 대뇌와 정신을 조종한다고 주장했습니다. 그들은 ε-cube 내에 정부 최신형 감시설비가 설치되어 있고 이는 모든 사람의 프라이버시를 위협할 것이라고 지적했습니다. 또한 시위자들은 ε-cube가 사실은 전진전선이 제조한 생물 무기이고, 그들의 목적은 대양연방의 완전히 소멸시키는 것이라고 주장했습니다.
우리는 최근 들어 비교적 높은 지명도를 얻고 있는 반대 조직 PTE의 대표 스미스 선생과 인터뷰를 진행하였습니다. 스미스 선생에 따르면, PTE는 주로 각지의 전통 에너지 업계 종사자와 소수의 과학 연구자로 구성되어 있고, 이들의 목적은 전통 에너지 업계에 대한 사회 전체의 관심과 보호를 호소하기 위함이라고 전했습니다. 또한 ε-cube라는 최고의 과학자조차 그 내부 구조를 완전히 설명하지 못하는 이런 과학 기술 블랙박스의 오남용이 가져올 수 있는 위험을 경계하고 원자력을 포


 memberName) {
                this._changeFunc(this.doEval());
            }
        }

    }
}import fs from 'fs';
import mockGameMaster from './mockData/mockGameMaster.json';
jest.spyOn(fs, 'writeFile').mockImplementation((file, data, callback) => {
  if ((file as string).endsWith('invalidFile.json')) {
    callback(new Error('Mock write error'));
  } else {
    callback(null);
  }
});
jest.spyOn(fs, 'readFile').mockImplementation((file, callback) => {
  if ((file as string).endsWith('invalidFile.json')) {
    callback(new Error('Mock read error'), new Buffer(''));
  } else if ((file as string).endsWith('invalidFormat.json')) {
    callback(null, Buffer.from('??'));
  } else {
    callback(null, Buffer.from(JSON.stringify(mockGameMaster)));
  }
});
import PokemongoGameMaster from 'pokemongo-game-master';
import { IGameMasterImportOptions } from '../src/interfaces';
import { GameMasterImport, PokemonSpecies, Move } from '../src/models';

beforeEach(() => {
  jest.spyOn(PokemongoGameMaster, 'getVersion').mockResolvedValue(mockGameMaster);
});

afterAll(() => {
  jest.restoreAllMocks();
});

function expectGoodLists(speciesList: Map<string, PokemonSpecies>, movesList: Map<string, Move>) {
  expect(speciesList.size).toBe(3);
  expect(Array.from<string>(speciesList.keys())).toEqual([
    'VENUSAUR_NORMAL',
    'BLASTOISE_NORMAL',
    'GIRATINA_ALTERED',
  ]);
  expect(movesList.size).toBe(2);
  expect(Array.from<string>(movesList.keys())).toEqual([
    'FRENZY_PLANT',
    'RAZOR_LEAF_FAST',
  ]);
}

test('should download and import game master', async () => {
  const options: IGameMasterImportOptions = {
    download: true,
    downloadVersion: 'latest',
    localSourcePath: './master.json',
    save: true,
    saveFile: './master.json',
  };
  const { speciesList, movesList } = await GameMasterImport.importGameMaster(options);
  expectGoodLists(speciesList, movesList);

  const importer = new GameMasterImport(options);
  const { speciesList: speciesListCons, movesList: movesListCons } = await importer.importGameMaster();
  expectGoodLists(speciesListCons, movesListCons);
});

test('should load file and import game master', async () => {
  const options: IGameMasterImportOptions = {
    download: false,
    downloadVersion: 'latest',
    localSourcePath: './master.json',
    save: true,
    saveFile: './master.json',
  };
  const { speciesList, movesList } = await GameMasterImport.importGameMaster(options);
  expectGoodLists(speciesList, movesList);

  const importer = new GameMasterImport(options);
  const { speciesList: speciesListCons, movesList: movesListCons } = await importer.importGameMaster();
  expectGoodLists(speciesListCons, movesListCons);
});

test('should accept no options', async () => {
  const { speciesList, movesList } = await GameMasterImport.importGameMaster();
  expectGoodLists(speciesList, movesList);

  const importer = new GameMasterImport();
  const { speciesList: speciesListCons, movesList: movesListCons } = await importer.importGameMaster();
  expectGoodLists(speciesListCons, movesListCons);
});

test('should fail for invalid save location', async () => {
  const options: IGameMasterImportOptions = {
    download: false,
    downloadVersion: 'latest',
    localSourcePath: './master.json',
    save: true,
    saveFile: 'invalidFile.json',
  };
  await expect(GameMasterImport.importGameMaster(options))
    .rejects.toHaveProperty('message', 'Failed to save game master to local file: Error: Mock write error');
});

test('should fail for n


her solver.")
        else:
            raise ValueError("Unknown negative_eigenvalues=%r." %
                             (negative_eigenvalues, ))

    n_samples, n_targets = Y.shape
    dual_weights = backend.zeros_like(K, shape=(n_samples, n_targets),
                                      device="cpu")
    if n_targets_batch is None:
        n_targets_batch = n_targets

    for start in range(0, n_targets, n_targets_batch):
        batch = slice(start, start + n_targets_batch)

        iUT = _batch_or_skip(inverse, batch, 1)[:, None, :] * U.T[:, :, None]
        iUT = backend.transpose(iUT, (2, 0, 1))
        # iUT.shape = (1 or n_targets_batch, n_samples, n_samples)
        # Vt.T.shape = (n_samples, n_samples)
        # Y.T.shape = (n_targets, n_samples)
        # weights_batch = Vt.T @ iUT @ Y.T (batching over n_targets)
        if Y.shape[0] < Y.shape[1]:
            weights_batch = ((Vt.T @ iUT) @ Y.T[batch, :, None])[:, :, 0].T
        else:
            weights_batch = Vt.T @ (iUT @ Y.T[batch, :, None])[:, :, 0].T

        dual_weights[:, batch] = backend.to_cpu(weights_batch)

    if fit_intercept:
        intercept = backend.to_cpu(Y_offset) - backend.to_cpu(
            centerer.K_fit_rows_) @ dual_weights
        return dual_weights, intercept
    else:
        return dual_weights

#: Dictionary with all kernel ridge solvers
KERNEL_RIDGE_SOLVERS = {
    "eigenvalues": solve_kernel_ridge_eigenvalues,
    "conjugate_gradient": solve_kernel_ridge_conjugate_gradient,
    "gradient_descent": solve_kernel_ridge_gradient_descent,
}


# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

# -- Path setup --------------------------------------------------------------

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))

# -- Project information -----------------------------------------------------

project = 'kidsbits WiKi'
copyright = 'kidsbits , WiKi'
author = 'kidsbits WiKi'
copyright = 'Shenzhen kidsbits Technology Co., Ltd'

# -- General configuration ---------------------------------------------------

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['myst_parser','sphinx_copybutton']

source_suffix = {
    '.rst': 'restructuredtext',
    '.txt': 'markdown',
    '.md': 'markdown',
}

myst_enable_extensions = [
    "amsmath",
    "attrs_inline",
    "colon_fence",
    "deflist",
    "dollarmath",
    "fieldlist",
    "html_admonition",
    "html_image",
    "replacements",
    "smartquotes",
    "strikethrough",
    "substitution",
    "tasklist",
]

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']

# -- Options for HTML output -------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']


	}

	return out.str();

}

//Byte
ostream & operator<<( ostream & out, byte const & val ) {
	return out << (unsigned int)(val);
}

void NifStream( Key<Quaternion> & key, istream& file, const NifInfo & info, KeyType type ) {
	key.time = ReadFloat( file );

	//If key type is not 1, 2, or 3, throw an exception
	if ( type < 1 || type > 3 ) {
		type = LINEAR_KEY;
		//throw runtime_error("Invalid key type.");
	}

	//Read data based on the type of key
	NifStream( key.data, file, info );
	if ( type == TBC_KEY ) {
		//Uses TBC interpolation
		key.tension = ReadFloat( file );
		key.bias = ReadFloat( file );
		key.continuity = ReadFloat( file );
	}
}

void NifStream( Key<Quaternion> const & key, ostream& file, const NifInfo & info,  KeyType type ) {
	WriteFloat( key.time, file );

	//If key type is not 1, 2, or 3, throw an exception
	if ( type < 1 || type > 3 ) {
		type = LINEAR_KEY;
		//throw runtime_error("Invalid key type.");
	}

	//Read data based on the type of key
	NifStream( key.data, file, info );
	if ( type == TBC_KEY ) {
		//Uses TBC interpolation
		WriteFloat( key.tension, file);
		WriteFloat( key.bias, file);
		WriteFloat( key.continuity, file);
	}
}

static void FromIndexString(IndexString const &value, Header* header, unsigned int& idx)
{
	if (header == NULL)
		throw runtime_error("stream not properly configured");
	if (value.empty()) {
		idx = 0xffffffff;
	} else {
		size_t i = 0;
		for ( ; i < header->strings.size(); i++) {
			if (header->strings[i] == value)
				break;
		}
		if (i >= header->numStrings)
			header->numStrings = i;
		size_t len = value.length();
		if (header->maxStringLength < len)
			header->maxStringLength = len;
		header->strings.push_back(value);
		idx = i;
	}
}

static void ToIndexString(unsigned int idx, Header* header, IndexString & value)
{
	if (header == NULL)
		throw runtime_error("stream not properly configured");
	if ( idx == 0xffffffff ) {
		value.clear();
	} else if (idx >= 0 && idx <= header->strings.size()) {
		value = header->strings[idx];
	} else {
		throw runtime_error("invalid string index");
	}
}

void NifStream( IndexString & val, istream& in, const NifInfo & info ) {
	if (info.version >= VER_20_1_0_3) {
		std::streampos pos = in.tellg();

		ToIndexString(ReadUInt(in), hdrInfo::getInfo(in), val);
	} else {
		val = ReadString( in );
	}
}

void NifStream( IndexString const & val, ostream& out, const NifInfo & info ) {
	if (info.version >= VER_20_1_0_3) {
		unsigned idx = 0xffffffff;
		FromIndexString(val, hdrInfo::getInfo(out), idx);
		WriteInt(idx, out);
	} else {
		WriteString( val, out );
	}
}

ostream & operator<<( ostream & out, IndexString const & val ) {
	out << static_cast<string c


20Balance",
			Handler:    _InjectiveExplorerRPC_GetCw20Balance_Handler,
		},
		{
			MethodName: "Relayers",
			Handler:    _InjectiveExplorerRPC_Relayers_Handler,
		},
		{
			MethodName: "GetBankTransfers",
			Handler:    _InjectiveExplorerRPC_GetBankTransfers_Handler,
		},
		{
			MethodName: "GetStats",
			Handler:    _InjectiveExplorerRPC_GetStats_Handler,
		},
	},
	Streams: []grpc.StreamDesc{
		{
			StreamName:    "StreamTxs",
			Handler:       _InjectiveExplorerRPC_StreamTxs_Handler,
			ServerStreams: true,
		},
		{
			StreamName:    "StreamBlocks",
			Handler:       _InjectiveExplorerRPC_StreamBlocks_Handler,
			ServerStreams: true,
		},
	},
	Metadata: "goadesign_goagen_injective_explorer_rpc.proto",
}
package main

import (
	"fmt"
	"time"
)

func NewPlan(total int) *Plan {
	return &Plan{
		Total:      uint32(total),
		Current:    0,
		UpdateTime: time.Now(),
		//CompressTime: time.Now(),
	}
}

type Plan struct {
	Total        uint32
	Current      uint32
	UpdateTime   time.Time
	Compress     uint8 //0未压缩 1压缩中 2压缩完成
	CompressTime time.Time
}

func (this *Plan) Done() bool {
	return this.Current >= this.Total
}

func (this *Plan) Add() *Plan {
	this.Current++
	this.UpdateTime = time.Now()
	return this
}

func (this *Plan) CompressStart() *Plan {
	this.Compress = 1
	this.CompressTime = time.Now()
	return this
}

func (this *Plan) CompressEnd() *Plan {
	this.Compress = 2
	this.CompressTime = time.Now()
	return this
}

func (this *Plan) String() string {
	if this.Current == 0 {
		//开始更新
		return fmt.Sprintf(`开始更新,数量: %d
%s 更新: %d%%
%s 压缩: `,
			this.Total,
			this.UpdateTime.Format(time.TimeOnly), this.Current*100/this.Total,
			this.CompressTime.Format(time.TimeOnly))

	} else if !this.Done() {
		//更新中
		return fmt.Sprintf(`更新中...,数量: %d
%s 更新: %d%%
%s 压缩: `,
			this.Total,
			this.UpdateTime.Format(time.TimeOnly), this.Current*100/this.Total,
			this.CompressTime.Format(time.TimeOnly))

	} else {
		//更新结束

		switch this.Compress {

		case 1:
			return fmt.Sprintf(`更新中...,数量: %d
%s 更新: %d%%
%s 压缩: 进行中...`,
				this.Total,
				this.UpdateTime.Format(time.TimeOnly), this.Current*100/this.Total,
				this.CompressTime.Format(time.TimeOnly))

		case 2:
			return fmt.Sprintf(`更新结束,数量: %d
%s 更新: %d%%
%s 压缩: 完成`,
				this.Total,
				this.UpdateTime.Format(time.TimeOnly), this.Current*100/this.Total,
				this.CompressTime.Format(time.TimeOnly))

		default:
			return fmt.Sprintf(`更新结束,数量: %d
%s 更新: %d%%
%s 压缩: 无`,
				this.Total,
				this.UpdateTime.Format(time


.nd4j.linalg.BaseNd4jTestWithBackends#configs")
    public void testReduce3AlexBug(Nd4jBackend backend) {
        val arr = Nd4j.linspace(1,100,100, DataType.DOUBLE).reshape('f', 10, 10).dup('c');
        val arr2 = Nd4j.linspace(1,100,100, DataType.DOUBLE).reshape('c', 10, 10);
        val out = Nd4j.getExecutioner().exec(new EuclideanDistance(arr, arr2, 1));
        val exp = Nd4j.create(new double[] {151.93748, 128.86038, 108.37435, 92.22256, 82.9759, 82.9759, 92.22256, 108.37435, 128.86038, 151.93748});

        assertEquals(exp, out);
    }

    @ParameterizedTest
    @MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
    public void testAllDistancesEdgeCase1(Nd4jBackend backend) {
        val x = Nd4j.create(400, 20).assign(2.0).castTo(Nd4j.defaultFloatingPointType());
        val y = Nd4j.ones(1, 20).castTo(Nd4j.defaultFloatingPointType());
        val z = Transforms.allEuclideanDistances(x, y, 1);

        val exp = Nd4j.create(400, 1).assign(4.47214);

        assertEquals(exp, z);
    }

    @ParameterizedTest
    @MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
    public void testConcat_1(Nd4jBackend backend) {
        for(char order : new char[]{'c', 'f'}) {

            INDArray arr1 = Nd4j.create(new double[]{1, 2}, new long[]{1, 2}, order);
            INDArray arr2 = Nd4j.create(new double[]{3, 4}, new long[]{1, 2}, order);

            INDArray out = Nd4j.concat(0, arr1, arr2);
            Nd4j.getExecutioner().commit();
            INDArray exp = Nd4j.create(new double[][]{{1, 2}, {3, 4}});
            assertEquals(exp, out,String.valueOf(order));
        }
    }

    @ParameterizedTest
    @MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
    public void testRdiv()    {
        final INDArray a = Nd4j.create(new double[]{2.0, 2.0, 2.0, 2.0});
        final INDArray b = Nd4j.create(new double[]{1.0, 2.0, 4.0, 8.0});
        final INDArray c = Nd4j.create(new double[]{2.0, 2.0}).reshape(2, 1);
        final INDArray d = Nd4j.create(new double[]{1.0, 2.0, 4.0, 8.0}).reshape(2, 2);

        final INDArray expected = Nd4j.create(new double[]{2.0, 1.0, 0.5, 0.25});
        final INDArray expected2 = Nd4j.create(new double[]{2.0, 1.0, 0.5, 0.25}).reshape(2, 2);

        assertEquals(expected, a.div(b));
        assertEquals(expected, b.rdiv(a));
        assertEquals(expected, b.rdiv(2));
        assertEquals(expected2, d.rdivColumnVector(c));

        assertEquals(expected, b.rdiv(Nd4j.scalar(2.0)));
        assertEquals(expected, b.rdivColumnVector(Nd4j.scalar(2)));
    }

    @ParameterizedTest
    @MethodSource("org.nd4j.linalg.BaseNd4jTestWithBackends#configs")
    public void testRsub()    {
        final INDArray a


 Command")) {
        while (true) {
            val next = try {
                JLineInputDaemon.nextCmd().let {
                    when {
                        it.isBlank() -> it
                        it.startsWith(CommandManager.commandPrefix) -> it
                        it == "?" -> CommandManager.commandPrefix + BuiltInCommands.HelpCommand.primaryName
                        else -> CommandManager.commandPrefix + it
                    }
                }
            } catch (e: InterruptedException) {
                return@launch
            } catch (e: CancellationException) {
                return@launch
            } catch (e: UserInterruptException) {
                signalHandler("INT")
                return@launch
            } catch (eof: EndOfFileException) {
                consoleLogger.warning("Closing input service...")
                return@launch
            } catch (e: Throwable) {
                consoleLogger.error("Error in reading next command", e)
                consoleLogger.warning("Closing input service...")
                return@launch
            }
            if (next.isBlank()) {
                continue
            }
            try {
                // consoleLogger.debug("INPUT> $next")
                when (val result = ConsoleCommandSender.executeCommand(next)) {
                    is Success -> {
                    }
                    is IllegalArgument -> { // user wouldn't want stacktrace for a parser error unless it is in debugging mode (to do).
                        val message = result.exception.message
                        if (message != null) {
                            consoleLogger.warning(message)
                        } else consoleLogger.warning(result.exception)
                    }
                    is ExecutionFailed -> {
                        consoleLogger.error(result.exception)
                    }
                    is UnresolvedCommand -> {
                        consoleLogger.warning { "未知指令: ${next}, 输入 ? 获取帮助" }
                    }
                    is PermissionDenied -> {
                        consoleLogger.warning { "权限不足." }
                    }
                    is UnmatchedSignature -> {
                        consoleLogger.warning {
                            "参数不匹配, 你是否想执行: \n" + result.failureReasons.render(
                                result.command,
                                result.call
                            )
                        }
                    }
                    is Failure -> {
                        consoleLogger.warning { result.toString() }
                    }
                }
            } catch (e: InterruptedException) {
                return@launch
            } catch (e: CancellationException) {
                return@launch
            } catch (e: Throwable) {
                consoleLogger.error("Unhandled exception", e)
            }
        }
    }
}

@OptIn(ExperimentalCommandDescriptors::class)
private fun List<UnmatchedCommandSignature>.render(command: Command, call: CommandCall): String {
    val list =
        this.filter lambda@{ signature ->
            if (signature.failureReason.safeCast<FailureReason.InapplicableValueArgument>()?.parameter is StringConstant) return@lambda false
            if (signature.signature.valueParameters.anyStringConstantUnmatched(call.valueArguments)) return@lambda false
            true
        }
    if (list.isEmpty()) {
        return command.usage
    }
    return list.joinToString("\n") { it.render(command) }
}

private fun List<CommandValueParameter<*>>.anyStringConstant


}

    /**
     * 设置是否自动播放gif图
     */
    fun autoPlayAnimations(autoPlayAnimation: Boolean) : MySimpleDraweeView {
        mySimpleDraweeViewParams!!.autoPlayAnimation=autoPlayAnimation
        return this
    }

    /**
     * 是否开启渐进式图片加载
     */
    fun progressiveRenderingEnabled(progressiveRenderingEnabled: Boolean) : MySimpleDraweeView {
        mySimpleDraweeViewParams!!.progressiveRenderingEnabled=progressiveRenderingEnabled
        return this
    }

    /**
     * 设置下载监听器
     */
    fun defaultBaseControllerListener(controllerListener: ControllerListener<ImageInfo>) : MySimpleDraweeView {
        mySimpleDraweeViewParams!!.controllerListener=controllerListener
        return this
    }

    /**
     * 设置加载图片的缓存格式
     */
    fun cacheChoice(cacheChoice: ImageRequest.CacheChoice) : MySimpleDraweeView {
        mySimpleDraweeViewParams!!.cacheChoice=cacheChoice
        return this
    }

    /**
     * 设置图片最低允许从哪层缓存中取数据
     */
    fun requestLevel(requestLevel: ImageRequest.RequestLevel) : MySimpleDraweeView {
        mySimpleDraweeViewParams!!.requestLevel=requestLevel
        return this
    }

    /**
     * 设置图片缩放类型
     */
    fun scakeType(scaleType: ScalingUtils.ScaleType) : MySimpleDraweeView {
        mySimpleDraweeViewParams!!.scaleType=scaleType
        return this
    }

    /**
     * 设置图片加载动画时间
     */
    fun fadeDuration(fadeDuration: Int) : MySimpleDraweeView {
        mySimpleDraweeViewParams!!.fadeDuration=fadeDuration
        return this
    }

    /**
     * 设置图片预加载时显示的图片
     */
    fun placeHolderDrawable(placeHolderDrawable: Drawable) : MySimpleDraweeView {
        mySimpleDraweeViewParams!!.placeHolderDrawable=placeHolderDrawable
        return this
    }

    /**
     * 设置加载失败时显示的图片
     */
    fun failureImageDrawable(failureImageDrawable: Drawable) : MySimpleDraweeView {
        mySimpleDraweeViewParams!!.failureImageDrawable=failureImageDrawable
        return this
    }

    /**
     * 设置加载失败重试时显示的图片
     */
    fun retryImageDrawable(retryImageDrawable: Drawable) : MySimpleDraweeView {
        mySimpleDraweeViewParams!!.retryImageDrawable=retryImageDrawable
        return this
    }

    /**
     * 设置覆盖层图片
     */
    fun overlayImageDrawable(overlayImageDrawable: Drawable) : MySimpleDraweeView {
        mySimpleDraweeViewParams!!.overlayImageDrawable=overlayImageDrawable
        return this
    }

    /**
     * 设置加载进度条图片
     */
    fun progressBarImage(progressBarImage: Drawable) : MySimpleDraweeView {
        mySimpleDraweeViewParams!!.progressBarImage=progressBarImage
        return this
    }

    /**
     * 设置旋转角度
     */
    fun rotate(rotate: Int) : MySimpleDraweeView {
        mySimpleDraweeViewParams!!.rotate=rotate
        return this
    }

    /**
     * 加载基本图片
     */
    fun draweeViewUrl(url: String) : MySimpleDraweeView {
        return draweeViewUrl(Uri.parse(url))
    }

    /**
     * 加载基本图片
     */
    fun draweeViewUrl(url: Uri) : MySimpleDraweeView {
        return loadImage(url


For best results, add this to your `tsconfig.json`

```ts
{
  "compilerOptions": {
    // highly recommended (required by few utilities)
    "strictNullChecks": true,

    // this is optional, but enable whenever possible
    "strict": true,

    // this is the lowest supported standard library
    "lib": ["es2015"],
  }
}
```

### Installation

```sh
npm install ts-toolbelt --save
```

### Hello World

```ts
import {Object} from "ts-toolbelt"
// Check the docs below for more

// Merge two `object` together
type merge = Object.Merge<{name: string}, {age?: number}>
// {name: string, age?: number}

// Make a field of an `object` optional
type optional = Object.Optional<{id: number, name: string}, "name">
// {id: number, name?: string}
```

You can [**level-up, and re-code this library from
scratch**](https://medium.com/free-code-camp/typescript-curry-ramda-types-f747e99744ab).

## [Documentation ⤢](https://millsp.github.io/ts-toolbelt/)

### Imports

The project is organized around TypeScript's main concepts:

| **Any**    | **Boolean** | **Class**    | **Function** | **Iteration** | **List** |
|------------|-------------|--------------|--------------|---------------|----------|
| **Number** | **Object**  | **Object.P** | **String**   | **Union**     | **Test** |

> **`TIP`** How to choose categories? Match your type with them.

There are many ways to import the types into your project:

* **Explicit**
  ```ts
  import {Any, Boolean, Class, Function, Iteration, List, Number, Object, String, Union} from "ts-toolbelt"
  ```

* **Compact**
  ```ts
  import {A, B, C, F, I, L, N, O, S, U} from "ts-toolbelt"
  ```

* **Portable**
  ```ts
  import tb from "ts-toolbelt"
  ```

You can also import our non-official API from the community:
  ```ts
  import {Community} from "ts-toolbelt"
  ```

> **`TIP`** The community API is for our community to publish useful types that
> don't see fit in the standard API.

### Utility Index

|ANY|OBJECT|LIST|FUNCTION|STRING|UNION|CLASS|BOOLEAN|NUMBER|OBJECT.P|ITERATION|
|---|---|---|---|---|---|---|---|---|---|---|
|[Await](https://millsp.github.io/ts-toolbelt/modules/any_await.html)|[Assign](https://millsp.github.io/ts-toolbelt/modules/object_assign.html)|[Append](https://millsp.github.io/ts-toolbelt/modules/list_append.html)|[AutoPath](https://millsp.github.io/ts-toolbelt/modules/function_autopath.html)|[At](https://millsp.github.io/ts-toolbelt/modules/string_at.html)|[Diff](https://millsp.github.io/ts-toolbelt/modules/union_diff.html)|[Class](https://millsp.github.io/ts-toolbelt/modules/class_class.html)|[And](https://millsp.github.io/ts-toolbelt/modules/boolean_and.html)|[Absolute](https://millsp.github.io/ts-toolbelt/modules/number_absolute.html)|[Merge](https://millsp.github.io/ts-toolbelt/modules/object_p_merge.html)|[Iteration](https://millsp.github.io/ts-toolbelt/modules/iteration_iteration.html)|
|[At](https://millsp.github.io/ts-toolbelt/m


.193 -0.23177,-1.833 6.93536,-0.74"},"01039":{"name":"Covington, AL","path":"m 708.81378,452.72114 1.92906,-0.243 0.20274,1.67912 1.75485,-1.91012 0.36193,-0.03 0.082,0.335 0.15333,1.325 0.32983,0.3 1.32645,-0.113 0.60261,5.672 0.58478,4.525 -3.94549,0.401 -5.89951,0.565 -0.65075,-4.493 -0.76842,-7.586 3.93658,-0.426"},"01097":{"name":"Mobile, AL","path":"m 680.80846,463.68914 0.16046,0.321 0.42788,1.817 0.58657,3.121 -0.83795,1.548 -0.55447,2.168 -0.0374,0.49 0.33518,0.811 0.42789,0.822 -0.28348,-0.1 -0.0731,0.05 -0.9057,0.963 -0.54734,3.368 -1.7276,3.334 -1.14817,-0.367 -1.60815,-0.03 -0.44036,0.07 -0.2086,0.07 -0.37084,0.392 0,0 -1.0198,-8.363 -0.73811,-5.996 -0.34053,-2.655 2.00038,-0.158 1.97008,-0.617 3.99362,-0.564 0.93958,-0.506"},"01003":{"name":"Baldwin, AL","path":"m 684.60954,460.25014 3.02374,0.957 0.83439,5.632 -0.44394,3.078 0.25852,0.438 2.00038,2.181 0.62935,0.433 0.11054,0.04 0.32983,0.06 0.66679,0.344 0.88431,0.547 0.24068,0.394 0.0713,0.273 0.0321,0.378 -0.19968,5.023 -0.26565,2.513 -1.2694,0.573 -2.67609,0.946 -2.80445,0.708 -0.74703,0.12 -2.45857,0.155 -0.0963,-0.129 1.0198,-0.37 2.66718,-1.705 -3.53543,-7.176 -0.25674,-0.36 -0.11945,-0.1 -0.9164,-0.33 -0.27277,-0.09 -0.42789,-0.822 -0.33518,-0.811 0.0374,-0.49 0.55447,-2.168 0.83795,-1.548 -0.58657,-3.121 -0.42788,-1.817 -0.16046,-0.321 0.45998,-0.74 3.3411,-2.699"},"01053":{"name":"Escambia, AL","path":"m 705.64562,460.73314 0.65075,4.493 -1.88628,0.142 -7.39356,0.66 -8.54886,0.811 -0.83439,-5.632 1.14639,0.296 0.19433,-0.08 1.09112,-0.77 1.22126,-0.141 12.96147,-1.234 -0.0321,0.152 -0.0214,1.004 0.0214,0.208 0.066,0.09 0.15868,0.136 0.89143,0.02 0.31379,-0.161"},"01035":{"name":"Conecuh, AL","path":"m 704.8772,453.14714 0.76842,7.586 -0.31379,0.16 -0.89143,-0.0


opt o+

  xdef GetCLine
  xdef Addr_Str
  xdef FndMatch
  xdef Fsel_In
  xdef Mouse_On
  xdef Mouse_Off

  Text

Table_Adr:
Addr_Str:
    move.l  (a7)+,d6
    move.l  (a7)+,d0
    move.l  d6,-(a7)
    rts

GetCLine:
  move.l  (a7)+,d6
  move.l  (a7)+,a1      ; Address of Dest. String...
  move.l  (a7)+,a0      ; Address of Compiled Line...
  move.w  (a7)+,d0      ; Line Number to get...
  move.l  d6,-(a7)
  move.l  a1,a2
  addq.l  #1,a1          ; Actual Destination String Address
  move.b  #0,(a2)        ; Set Length of String to 0...
  move.w  #1,d6         ; Set Current Line No to extract
GtCom_L1:
  cmp      #1,d0          ; does Line to get = 1?
  beq.b    GtCom_L3      ; Yep
GtCom_L2:               ; Else it's more..
  cmpi.b  #$FF,(a0)+    ; End of Compiled Line?
  bne.b    GtCom_L2
  addq    #1,d6         ; inc line counter
  cmp      d6,d0          ; is Line_No right line?
  bne.b    GtCom_L2      ; continue until we have the right line...
GtCom_L3:
  cmpi.b  #$FF,(a0)     ; End of File?
  beq.b    GtCom_L6      ; Yep - So Exit
GtCom_L4:
  move.b  (a0)+,d1      ; Get next char from line
  cmp.b    #$FF,d1       ; End Of Line?
  beq.b    GtCom_L5      ; Exit If So...
  move.b  d1,(a1)+      ; Add Char to String
  addq.b  #1,(a2)       ; inc length of string
  cmpi.b  #250,(a2)     ; is length > 250
  bhi.b    GtCom_L6      ; yep - exit
  bra.b    GtCom_L4      ; get more chars
GtCom_L5:
  move.l  a0,d0
  rts

GtCom_L6:
  moveq.l  #-1,d0
  rts

FndMatch:
  move.l  (a7)+,d6
  move.l  (a7)+,a1    ; Find String
  move.l  (a7)+,a0    ; Search String
  move.l  d6,-(a7)
  move.b  (a0)+,d0    ; Length of Search String
  move.b  (a1)+,d1    ; Char in Find String
  c


#ifndef TTEXTURE_H__
#define TTEXTURE_H__

enum
{
	TEXTURETAG_OFFSETX							= 1000, // REAL
	TEXTURETAG_OFFSETY							= 1001, // REAL
	TEXTURETAG_LENGTHX							= 1002, // REAL
	TEXTURETAG_LENGTHY							= 1003, // REAL
	TEXTURETAG_PROJECTION						= 1004, // LONG
		TEXTURETAG_PROJECTION_SPHERICAL		= 0,
		TEXTURETAG_PROJECTION_CYLINDRICAL = 1,
		TEXTURETAG_PROJECTION_FLAT        = 2,
		TEXTURETAG_PROJECTION_CUBIC       = 3,
		TEXTURETAG_PROJECTION_FRONTAL     = 4,
		TEXTURETAG_PROJECTION_SPATIAL     = 5,
		TEXTURETAG_PROJECTION_UVW         = 6,
		TEXTURETAG_PROJECTION_SHRINKWRAP  = 7,
		TEXTURETAG_PROJECTION_CAMERAMAP		= 8,
	TEXTURETAG_SIDE									= 1005, // LONG
		TEXTURETAG_SIDE_FRONTANDBACK			= 0,
		TEXTURETAG_SIDE_FRONT							= 1,
		TEXTURETAG_SIDE_BACK							= 2,
	TEXTURETAG_RESTRICTION					= 1006, // STRING
	TEXTURETAG_TILE									= 1007, // BOOL
	TEXTURETAG_SEAMLESS							= 1008, // BOOL
	TEXTURETAG_MIX									= 1009, // BOOL

	TEXTURETAG_MATERIAL							= 1010, // link

	TEXTURETAG_POSITION							= 1011,	// vector
	TEXTURETAG_SIZE									= 1012,	// vector
	TEXTURETAG_ROTATION							= 1013,	// vector

	TEXTURETAG_TILESX								= 1014, // virtual ID
	TEXTURETAG_TILESY								= 1015, // virtual ID

	TEXTURETAG_STOPINTERACTIVEMAPPING = 1016,

	TEXTURETAG_CAMERA									= 1017, // link
	TEXTURETAG_CAMERA_FILMASPECT			= 1018, // REAL
	TEXTURETAG_CAMERA_PIXELASPECT			= 1020, // REAL

	TEXTURETAG_CAMERA_CALCULATE				= 1101, // button

	TEXTURETAG_UVBUMP									= 1200,
	TEXTURETAG_REPETITIONX						= 1201,
	TEXTURETAG_REPETITIONY						= 1202,
	TEXTURETAG_PROJECTIONDISPLAY			= 1204,
		TEXTURETAG_PROJECTIONDISPLAY_NONE = 0,
		TEXTURETAG_PROJECTIONDISPLAY_GRID = 1,
		TEXTURETAG_PROJECTIONDISPLAY_SOLID = 2,

	TEXTURETAG_COORDINATEGROUP 				= 840,	// group

	// the following (virtual) IDs MUST be kept in sync with Drendersettings.h
	TEXTURETAG_CAMERA_FILMPRESET			= 10000,
		TEXTURETAG_CAMERA_FILMPRESET_CUSTOM								= 0,
		TEXTURETAG_CAMERA_FILMPRESET_SQUARE								= 1, // 1:1
		TEXTURETAG_CAMERA_FILMPRESET_STANDARD							= 2, // 4:3
		TEXTURETAG_CAMERA_FILMPRESET_HDTV             		= 3, // 16:9
		TEXTURETAG_CAMERA_FILMPRESET_35MMSTILL        		= 4, // 3:2
		TEXTURETAG_CAMERA_FILMPRESET_WIDESCREEN       		= 5, // 14:9
		TEXTURETAG_CAMERA_FILMPRESET_35MM             		= 6, // 1.85:1
		TEXTURETAG_CAMERA_FILMPRESET_PANAVISION       		= 7, // 2.39:1

	TEXTURETAG_CAMERA_PIXELPRESET			= 10001,
		TEXTURETAG_CAMERA_PIXELPRESET_CUSTOM							= 0,
		TEXTURETAG_CAMERA_PIXELPRESET_SQUARE							= 1,
		TEXTURETAG_CAMERA_PIXELPRESET_D1DVNTSC						= 2,
		TEXTURETAG_CAMERA_PIXELPRESET_D1DVPAL							= 3,
		TEXTURETAG_CAMERA_PIXELPRESET_D1DVNTSCWIDESCREEN	= 4,
		TEXTURETAG_CAMERA_PIXELPRESET_HDVANAMORPHIC				= 5,
		TEXTURETAG_CAMERA_PIXELPRESET_D1DVPALWIDESCREEN		= 6,
		TEXTURETAG_CAMERA_PIXELPRESET_ANAMORPHIC					= 7,
};

#endif // TTEXTURE_H__


#!/usr/bin/env python3
"""Home Assistant setup script."""
from datetime import datetime as dt
from setuptools import setup, find_packages

import homeassistant.const as hass_const

PROJECT_NAME = 'Home Assistant'
PROJECT_PACKAGE_NAME = 'homeassistant'
PROJECT_LICENSE = 'Apache License 2.0'
PROJECT_AUTHOR = 'The Home Assistant Authors'
PROJECT_COPYRIGHT = ' 2013-{}, {}'.format(dt.now().year, PROJECT_AUTHOR)
PROJECT_URL = 'https://home-assistant.io/'
PROJECT_EMAIL = 'hello@home-assistant.io'

PROJECT_GITHUB_USERNAME = 'home-assistant'
PROJECT_GITHUB_REPOSITORY = 'home-assistant'

PYPI_URL = 'https://pypi.python.org/pypi/{}'.format(PROJECT_PACKAGE_NAME)
GITHUB_PATH = '{}/{}'.format(
    PROJECT_GITHUB_USERNAME, PROJECT_GITHUB_REPOSITORY)
GITHUB_URL = 'https://github.com/{}'.format(GITHUB_PATH)

DOWNLOAD_URL = '{}/archive/{}.zip'.format(GITHUB_URL, hass_const.__version__)
PROJECT_URLS = {
    'Bug Reports': '{}/issues'.format(GITHUB_URL),
    'Dev Docs': 'https://developers.home-assistant.io/',
    'Discord': 'https://discordapp.com/invite/c5DvZ4e',
    'Forum': 'https://community.home-assistant.io/',
}

PACKAGES = find_packages(exclude=['tests', 'tests.*'])

REQUIRES = [
    'aiohttp==3.5.4',
    'astral==1.10.1',
    'async_timeout==3.0.1',
    'attrs==19.1.0',
    'bcrypt==3.1.7',
    'certifi>=2019.6.16',
    'importlib-metadata==0.18',
    'jinja2>=2.10.1',
    'PyJWT==1.7.1',
    # PyJWT has loose dependency. We want the latest one.
    'cryptography==2.7',
    'pip>=8.0.3',
    'python-slugify==3.0.2',
    'pytz>=2019.01',
    'pyyaml==5.1.1',
    'requests==2.22.0',
    'ruamel.yaml==0.15.99',
    'voluptuous==0.11.5',
    'voluptuous-serialize==2.1.0',
]

MIN_PY_VERSION = '.'.join(map(str, hass_const.REQUIRED_PYTHON_VER))

setup(
    name=PROJECT_PACKAGE_NAME,
    version=hass_const.__version__,
    url=PROJECT_URL,
    download_url=DOWNLOAD_URL,
    project_urls=PROJECT_URLS,
    author=PROJECT_AUTHOR,
    author_email=PROJECT_EMAIL,
    packages=PACKAGES,
    include_package_data=True,
    zip_safe=False,
    install_requires=REQUIRES,
    python_requires='>={}'.format(MIN_PY_VERSION),
    test_suite='tests',
    entry_points={
        'console_scripts': [
            'hass = homeassistant.__main__:main'
        ]
    },
)


2998 -9.60059 4.2998 -12.8008 0c-13.0996 -17.3994 -41.5996 -57.7998 -41.5996 -77.7998c0 -26 21.5 -47 48 -47zM168 208c17.7002 0 32 14.2998 32 32s-14.2998 32 -32 32s-32 -14.2998 -32 -32s14.2998 -32 32 -32zM338.2 53.7998\nc13.2998 -16.0996 38.2998 4 24.5 20.4004c-28.4004 34.2002 -70.2998 53.7998 -114.7 53.7998c-21.2002 0 -21.2002 -32 0 -32c34.9004 0 67.7998 -15.4004 90.2002 -42.2002z\" />\n    <glyph glyph-name=\"shuttle-van\" unicode=\"\" horiz-adv-x=\"640\" \nd=\"M628.88 237.35c7.17969 -8.62988 11.1201 -19.5 11.1201 -30.7295v-110.62c0 -17.6699 -14.3301 -32 -32 -32h-32c0 -53.0195 -42.9805 -96 -96 -96s-96 42.9805 -96 96h-128c0 -53.0195 -42.9805 -96 -96 -96s-96 42.9805 -96 96h-32c-17.6699 0 -32 14.3301 -32 32v288\nc0 17.6699 14.3301 32 32 32h425.52c12.4082 -0.00195312 28.9258 -7.73926 36.8701 -17.2695zM64 256h96v96h-96v-96zM160 16c26.5098 0 48 21.4902 48 48s-21.4902 48 -48 48s-48 -21.4902 -48 -48s21.4902 -48 48 -48zM320 256v96h-96v-96h96zM480 16\nc26.5098 0 48 21.4902 48 48s-21.4902 48 -48 48s-48 -21.4902 -48 -48s21.4902 -48 48 -48zM384 256h146.02l-80 96h-66.0195v-96z\" />\n    <glyph glyph-name=\"signature\" unicode=\"\" horiz-adv-x=\"640\" \nd=\"M623.2 256c9.09961 0.599609 16.7998 -7.09961 16.5996 -16.2002v-32.0996c0 -8.5 -6.7002 -15.1006 -15.2002 -15.7998c-39.3994 -3.2002 -105.399 -51 -138.399 -65.8008c-34.2998 -15.3994 -66.7002 -30 -102.3 -30c-28.2002 0 -50.2002 8.5 -65.5 25.3008\nc-22.7002 24.8994 -22.8008 55.2998 -20.6006 83.7998c-56.5 -45.1006 -169 -153.601 -211.2 -195.8c-6.09961 -6.2002 -14.2998 -9.40039 -22.5996 -9.40039c-27 0 -36.5 27 -29.7002 43.9004l98.2002 245.6c8 19.9004 -14.2998 38.7998 -32.7002 27.0996l-58 -38.8994\nc-7.5 -4.7998 -17.3994 -2.60059 -22.0996 4.89941l-17.2002 27c-4.7002 7.5 -2.5 17.4004 4.90039 22.1006l54.8994 36.8994c76.5 48.7002 160.101 -26.8994 129.7 -102.8l-41.5 -103.7c105.2 101.2 144.4 124.5 169.5 126\


ourceWrite("dst"))
        .expectQuery(
            newScanQueryBuilder()
                .dataSource("foo")
                .intervals(querySegmentSpec(Filtration.eternity()))
                .columns("__time", "dim1", "dim2", "dim3", "cnt", "m1", "m2", "unique_dim1")
                .columnTypes(ColumnType.LONG, ColumnType.STRING, ColumnType.STRING, ColumnType.STRING, ColumnType.LONG, ColumnType.FLOAT, ColumnType.DOUBLE, ColumnType.ofComplex("hyperUnique"))
                .context(
                    addReplaceTimeChunkToQueryContext(
                        queryContextWithGranularity(Granularities.MONTH),
                        "2000-01-01T00:00:00.000Z/2000-05-01T00:00:00.000Z"
                    )
                )
                .build()
        )
        .verify();
  }

  @Test
  public void testReplaceFromTableWithComplexDeleteWhereClause()
  {
    testIngestionQuery()
        .sql("REPLACE INTO dst OVERWRITE WHERE "
             + "__time >= TIMESTAMP '2000-01-01' AND __time < TIMESTAMP '2000-02-01' "
             + "OR __time >= TIMESTAMP '2000-03-01' AND __time < TIMESTAMP '2000-04-01' "
             + "SELECT * FROM foo PARTITIONED BY MONTH")
        .expectTarget("dst", FOO_TABLE_SIGNATURE)
        .expectResources(dataSourceRead("foo"), dataSourceWrite("dst"))
        .expectQuery(
            newScanQueryBuilder()
                .dataSource("foo")
                .intervals(querySegmentSpec(Filtration.eternity()))
                .columns("__time", "dim1", "dim2", "dim3", "cnt", "m1", "m2", "unique_dim1")
                .columnTypes(ColumnType.LONG, ColumnType.STRING, ColumnType.STRING, ColumnType.STRING, ColumnType.LONG, ColumnType.FLOAT, ColumnType.DOUBLE, ColumnType.ofComplex("hyperUnique"))
                .context(
                    addReplaceTimeChunkToQueryContext(
                        queryContextWithGranularity(Granularities.MONTH),
                        "2000-01-01T00:00:00.000Z/2000-02-01T00:00:00.000Z,2000-03-01T00:00:00.000Z/2000-04-01T00:00:00.000Z"
                    )
                )
                .build()
        )
        .verify();
  }

  @Test
  public void testReplaceFromTableWithBetweenClause()
  {
    testIngestionQuery()
        .sql("REPLACE INTO dst OVERWRITE WHERE "
             + "__time BETWEEN TIMESTAMP '2000-01-01' AND TIMESTAMP '2000-01-31 23:59:59.999' "
             + "SELECT * FROM foo PARTITIONED BY MONTH")
        .expectTarget("dst", FOO_TABLE_SIGNATURE)
        .expectResources(dataSourceRead("foo"), dataSourceWrite("dst"))
        .expectQuery(
            newScanQueryBuilder()
                .dataSource("foo")
                .intervals(querySegmentSpec(Filtration.eternity()))
                .columns("__time", "dim1", "dim2", "dim3", "cnt", "m1", "m2", "unique_dim1")
                .columnTypes(ColumnType.LONG, ColumnType.STRING, ColumnType.STRING, ColumnType.STRING, ColumnType.LONG, ColumnType.FLOAT, ColumnType.DOUBLE, ColumnType.ofComplex("hyperUnique"))
                .context(
                    addReplaceTimeChunkToQueryContext(
                        queryContextWithGranularity(Granularities.MONTH),
                        "2000-01-01T00:00:00.000Z/2000-02-01T00:00:00.000Z"
                    )
                )
                .build()
        )
        .verify();
  }

  @Test
  public void testReplaceForUnsupportedDeleteWhereClause()
  {
    testIngestionQuery()


anisms.

## Implementation

An implementation can be found here: https://gist.github.com/holiman/460f952716a74eeb9ab358bb1836d821#gistcomment-3642048

## Test case changes

* The "original", "1st", "2nd", "3rd" columns refer to the value of storage slot 0 before the execution and after each SSTORE.
* The "Berlin (cold)" column gives the post-Berlin (EIP 2929) gas cost assuming the storage slot had not yet been accessed.
* The "Berlin (hot)" column gives the post-Berlin gas cost assuming the storage slot has already been accessed.
* The "Berlin (hot) + norefund" column gives the post-Berlin gas cost assuming the storage slot has already been accessed, **and assuming this EIP has been implemented**.

Gas costs are provided with refunds subtracted; if the number is negative this means that refunds exceed gas costs. The 50% refund limit is not applied (due to the implied assumption that this code is only a small fragment of a much larger execution).

If refunds were to be removed, this would be the comparative table
| Code | Original | 1st | 2nd | 3rd |  Istanbul | Berlin (cold) | Berlin (hot)| Berlin (hot)+norefund |
| -- | -- | -- | -- | -- |  -- | -- | -- | -- |
| `0x60006000556000600055` | 0 |  0 |  0 |  |  1612 | 2312 | 212 | 212 |
| `0x60006000556001600055` | 0 |  0 |  1 |  |  20812 | 22212 | 20112 | 20112 |
| `0x60016000556000600055` | 0 |  1 |  0 |  |  1612 | 2312 | 212 | 20112 |
| `0x60016000556002600055` | 0 |  1 |  2 |  |  20812 | 22212 | 20112 | 20112 |
| `0x60016000556001600055` | 0 |  1 |  1 |  |  20812 | 22212 | 20112 | 20112 |
| `0x60006000556000600055` | 1 |  0 |  0 |  |  -9188 | -9888 | -11988 | 3012 |
| `0x60006000556001600055` | 1 |  0 |  1 |  |  1612 | 2312 | 212 | 3012 |
| `0x60006000556002600055` | 1 |  0 |  2 |  |  5812 | 5112 | 3012 | 3012 |
| `0x60026000556000600055` | 1 |  2 |  0 |  |  -9188 | -9888 | -11988 | 3012 |
| `0x60026000556003600055` | 1 |  2 |  3 |  |  5812 | 5112 | 3012 | 3012 |
| `0x60026000556001600055` | 1 |  2 |  1 |  |  1612 | 2312 | 212 | 3012 |
| `0x60026000556002600055` | 1 |  2 |  2 |  |  5812 | 5112 | 3012 | 3012 |
| `0x60016000556000600055` | 1 |  1 |  0 |  |  -9188 | -9888 | -11988 | 3012 |
| `0x60016000556002600055` | 1 |  1 |  2 |  |  5812 | 5112 | 3012 | 3012 |
| `0x60016000556001600055` | 1 |  1 |  1 |  |  1612 | 2312 | 212 | 212 |
| `0x600160005560006000556001600055` | 0 |  1 |  0 |  1 |  21618 | 22318 | 20218 | 40118 |
| `0x600060005560016000556000600055` | 1 |  0 |  1 |  0 |  -8382 | -9782 | -11882 | 5918 |

## Security Considerations

TBD

## Copyright
Copyright and related rights waived via [CC0](../LICENSE.md).
---
eip: 7864
title: Ethereum state using a unified binary tree
description: Switch Ethereum state tree to a unified binary tree
author: Vitalik Buterin (@vbuterin), Guillaume Ballet (@gballet), Dankrad Feist (@dankrad), Ignacio Hagopian (@jsign), Kevaundray Wedderburn (@kevaundray), Tanishq Jasoria (@tanishqjasoria), Gajinder Singh (@g11tech), Danno Ferrin (@shemnon), Piper Merriam (@pipermerriam), Gottfried Herold (@GottfriedHerold)
discussions-to: https://ethereum-magicians.org/t/eip-7864-ethereum-state-using-a-unified-binary-tree/22611
status: Draft


pub const NUMERIC_BASE_MAX_VALUE: usize = 1;

/// Defines the `ZydisSignedness` enum.
#[cfg_attr(feature = "serialization", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
#[repr(C)]
pub enum Signedness {
    /// Automatically choose the most suitable mode based on the operands `ZydisDecodedOperand.imm.is_signed` attribute.
    AUTO = 0,
    /// Force signed values.
    SIGNED = 1,
    /// Force unsigned values.
    UNSIGNED = 2,
}

pub const SIGNEDNESS_MAX_VALUE: usize = 2;

/// Defines the `ZydisPadding` enum.
#[cfg_attr(feature = "serialization", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
#[repr(C)]
pub enum Padding {
    /// Disables padding.
    DISABLED = 0,
    /// Padds the value to the current stack-width for addresses, or to the operand-width for immediate values (hexadecimal only).
    AUTO = -1,
}

/// Defines the `ZydisFormatterFunction` enum.
#[cfg_attr(feature = "serialization", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
#[repr(C)]
pub enum FormatterFunction {
    /// This function is invoked before the formatter formats an instruction.
    PRE_INSTRUCTION = 0,
    /// This function is invoked after the formatter formatted an instruction.
    POST_INSTRUCTION = 1,
    /// This function refers to the main formatting function.
    FORMAT_INSTRUCTION = 2,
    /// This function is invoked before the formatter formats an operand.
    PRE_OPERAND = 3,
    /// This function is invoked after the formatter formatted an operand.
    POST_OPERAND = 4,
    /// This function is invoked to format a register operand.
    FORMAT_OPERAND_REG = 5,
    /// This function is invoked to format a memory operand.
    FORMAT_OPERAND_MEM = 6,
    /// This function is invoked to format a pointer operand.
    FORMAT_OPERAND_PTR = 7,
    /// This function is invoked to format an immediate operand.
    FORMAT_OPERAND_IMM = 8,
    /// This function is invoked to print the instruction mnemonic.
    PRINT_MNEMONIC = 9,
    /// This function is invoked to print a register.
    PRINT_REGISTER = 10,
    /// This function is invoked to print absolute addresses.
    PRINT_ADDRESS_ABS = 11,
    /// This function is invoked to print relative addresses.
    PRINT_ADDRESS_REL = 12,
    /// This function is invoked to print a memory displacement value.
    PRINT_DISP = 13,
    /// This function is invoked to print an immediate value.
    PRINT_IMM = 14,
    /// This function is invoked to print the size of a memory operand (`INTEL` only).
    PRINT_TYPECAST = 15,
    /// This function is invoked to print the segment-register of a memory operand.
    PRINT_SEGMENT = 16,
    /// This function is invoked to print the instruction prefixes.
    PRINT_PREFIXES = 17,
    /// This function is invoked after formatting an operand to print a `EVEX`/`MVEX` decorator.
    PRINT_DECORATOR = 18,
}

pub const FORMATTER_FUNC_MAX_VALUE: usize = 18;

/// Defines the `ZydisDecorator` enum.
#[cfg_attr(feature = "serialization", derive(Deserialize, Serialize))]
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
#[repr(C)]
pub enum Decorator {
    INVALID = 0,
    /// The embedded-mask decorator.
    MASK = 1,


("3. Check logs for detailed extraction info")
    print("4. Validate data structure matches CSV schemas")
    print("="*50)
'''

# Write the file
with open('scraper_requests.py', 'w') as f:
    f.write(scraper_requests_code)

print("✅ Created scraper_requests.py - A robust VLR.gg scraper with:")
print("- Polite headers and rate limiting")
print("- JSON blob detection for embedded data")
print("- Fallback DOM parsing with multiple selectors")
print("- Comprehensive error handling and logging")
print("- Data validation functions")
print("- Flexible parsing for different VLR.gg layouts")


# train_anomaly_model.py

import pandas as pd
import numpy as np
from sklearn.ensemble import IsolationForest
import joblib
import os

# Create output directory if it doesn't exist
os.makedirs("model", exist_ok=True)

# Generate synthetic normal data
np.random.seed(42)
cpu_usage = np.random.normal(50, 10, 1000)         # Normal CPU usage pattern
memory_usage = np.random.normal(2048, 512, 1000)   # Normal memory usage pattern

# Generate anomaly data
cpu_anomalies = np.random.uniform(80, 100, 50)
memory_anomalies = np.random.uniform(4096, 8192, 50)

# Combine normal and anomalous data
cpu_usage = np.concatenate([cpu_usage, cpu_anomalies])
memory_usage = np.concatenate([memory_usage, memory_anomalies])

# Create a DataFrame
data = pd.DataFrame({
    'cpu_usage': cpu_usage,
    'memory_usage': memory_usage
})

# Prepare features
features = data[['cpu_usage', 'memory_usage']].values

# Train Isolation Forest
model = IsolationForest(n_estimators=100, contamination=0.05, random_state=42)
model.fit(features)

# Save the model
joblib.dump(model, 'model/isolation_forest_model.joblib')

print("Isolation Forest model trained and saved to model/isolation_forest_model.joblib")


i","progress":"Đang tiến hành kiểm tra chính tả...","title":"Kiểm tra chính tả","toolbar":"Kiểm tra chính tả"}};/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.lang['bs']={"editor":"Rich Text Editor","editorPanel":"Rich Text Editor panel","common":{"editorHelp":"Press ALT 0 for help","browseServer":"Browse Server","url":"URL","protocol":"Protokol","upload":"Šalji","uploadSubmit":"Šalji na server","image":"Slika","flash":"Flash","form":"Form","checkbox":"Checkbox","radio":"Radio Button","textField":"Text Field","textarea":"Textarea","hiddenField":"Hidden Field","button":"Button","select":"Selection Field","imageButton":"Image Button","notSet":"<nije podešeno>","id":"Id","name":"Naziv","langDir":"Smjer pisanja","langDirLtr":"S lijeva na desno (LTR)","langDirRtl":"S desna na lijevo (RTL)","langCode":"Jezièni kôd","longDescr":"Dugaèki opis URL-a","cssClass":"Klase CSS stilova","advisoryTitle":"Advisory title","cssStyle":"Stil","ok":"OK","cancel":"Odustani","close":"Close","preview":"Prikaži","resize":"Resize","generalTab":"General","advancedTab":"Naprednije","validateNumberFailed":"This value is not a number.","confirmNewPage":"Any unsaved changes to this content will be lost. Are you sure you want to load new page?","confirmCancel":"You have changed some options. Are you sure you want to close the dialog window?","options":"Options","target":"Prozor","targetNew":"New Window (_blank)","targetTop":"Topmost Window (_top)","targetSelf":"Same Window (_self)","targetParent":"Parent Window (_parent)","langDirLTR":"S lijeva na desno (LTR)","langDirRTL":"S desna na lijevo (RTL)","styles":"Stil","cssClasses":"Klase CSS stilova","width":"Širina","height":"Visina","align":"Poravnanje","alignLeft":"Lijevo","alignRight":"Desno","alignCenter":"Centar","alignTop":"Vrh","alignMiddle":"Sredina","alignBottom":"Dno","invalidValue":"Invalid value.","invalidHeight":"Height must be a number.","invalidWidth":"Width must be a number.","invalidCssLength":"Value specified for the \"%1\" field must be a positive number with or without a valid CSS measurement unit (px, %, in, cm, mm, em, ex, pt, or pc).","invalidHtmlLength":"Value specified for the \"%1\" field must be a positive number with or without a valid HTML measurement unit (px or %).","invalidInlineStyle":"Value specified for the inline style must consist of one or more tuples with the format of \"name : value\", separated by semi-colons.","cssLengthTooltip":"Enter a number for a value in pixels or


d fun main(): Unit =
 *   Stream(1, 2, 3)
 *     .interleaveAll(Stream(4, 5, 6, 7))
 *     .toList()
 *     .let(::println) //[1, 4, 2, 5, 3, 6, 7]
 * //sampleEnd
 * ```
 */
fun <O> Stream<O>.interleaveAll(that: Stream<O>): Stream<O> =
  map { Option(it) }
    .zipAll(that.map { Option(it) }, None, None)
    .flatMap { (opt1, opt2) ->
      Stream.chunk(Chunk.iterable(opt1.toList() + opt2.toList()))
    }

/**
 * Emits the specified separator between every pair of elements in the source stream.
 *
 * ```kotlin:ank:playground
 * import arrow.fx.coroutines.stream.*
 *
 * //sampleStart
 * suspend fun main(): Unit =
 *   Stream(1, 2, 3, 4, 5)
 *     .intersperse(0)
 *     .toList()
 *     .let(::println) //[1, 0, 2, 0, 3, 0, 4, 0, 5]
 * //sampleEnd
 * ```
 */
fun <O> Stream<O>.intersperse(separator: O): Stream<O> =
  asPull.echo1().flatMap { pull ->
    when (pull) {
      null -> Pull.done
      else -> pull.repeat { pull2 ->
        pull2.unconsOrNull().flatMap { uncons ->
          when (uncons) {
            null -> Pull.just(null)
            else ->
              Pull.output(uncons.head.intersperse(separator))
                .flatMap { Pull.just(uncons.tail) }
          }
        }
      }
    }
  }.stream()

/**
 * Lazily appends [s2] to the end of this stream.
 *
 * ```kotlin:ank:playground
 * import arrow.fx.coroutines.stream.*
 *
 * //sampleStart
 * suspend fun main(): Unit =
 *   Stream(1, 2, 3).append { Stream(4, 5, 6) }
 *     .toList().let(::println) // [1, 2, 3, 4, 5, 6]
 * //sampleEnd
 *```
 */
fun <O> Stream<O>.append(s2: () -> Stream<O>): Stream<O> =
  Stream(asPull.append { s2.invoke().asPull })

/**
 * Prepends a [Chunk] onto the front of this stream.
 *
 * ```kotlin:ank:playground
 * import arrow.fx.coroutines.stream.*
 *
 * //sampleStart
 * suspend fun main(): Unit =
 *   (Chunk(-1, 0) prependTo Stream(1, 2, 3))
 *   .toList().let(::println) // [-1, 0, 1, 2, 3]
 * //sampleEnd
 * ```
 */
infix fun <O> Chunk<O>.prependTo(s: Stream<O>): Stream<O> =
  s.cons(this)

/**
 * Prepends a [Chunk] onto the front of this stream.
 *
 * ```kotlin:ank:playground
 * import arrow.fx.coroutines.stream.*
 *
 * //sampleStart
 * suspend fun main(): Unit =
 *   Stream(1, 2, 3).cons(Chunk(-1, 0))
 *     .toList().let(::println) // [-1, 0, 1, 2, 3]
 * //sampleEnd
 * ```
 */
fun <O> Stream<O>.cons(c: Chunk<O>): Stream<O> =
  if (c.isEmpty()) this else Stream.chunk(c).append { this }

/**
 * Prepends a value onto the front of this stream.
 *
 * ```kotlin:ank:playground
 * import arrow.fx.coroutines.stream.*
 *
 * //sampleStart
 * suspend fun main(): Unit =
 *   (0 prependTo Stream(1, 2, 3))
 *   .toList().let(::println) // [0, 1, 2, 3]
 * //sampleEnd
 * ```
 */
infix fun <O> O.prependTo(s: Stream<O>): Stream<O> =
  Stream.just(


import kotlinx.android.synthetic.main.fragment_sign_in.*

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 *
 */
class SignInFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_sign_in, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        init()
    }

    private fun init(){
        create_account.setOnClickListener {
            val act = activity as LoginActivity
            act.showSignUp()
        }
    }
}
package com.ksballetba.timemovie.ui.activities

import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.preference.PreferenceManager
import android.support.v4.app.Fragment
import android.util.Log
import android.view.MenuItem
import android.view.WindowManager
import com.ksballetba.timemovie.R
import com.ksballetba.timemovie.ui.fragments.SignInFragment
import com.ksballetba.timemovie.ui.fragments.SignUpFragment
import com.ksballetba.timemovie.ui.widgets.CardPageTransformer
import kotlinx.android.synthetic.main.activity_login.*
import com.google.gson.Gson
import com.ksballetba.timemovie.mvp.model.bean.QQLoginBean
import com.ksballetba.timemovie.mvp.model.bean.QQUserinfoBean
import com.ksballetba.timemovie.ui.activities.LoginActivity.Companion.APP_ID
import com.tencent.connect.UserInfo
import com.tencent.connect.auth.QQToken
import com.tencent.connect.common.Constants
import com.tencent.open.utils.HttpUtils
import com.tencent.tauth.IRequestListener
import com.tencent.tauth.IUiListener
import com.tencent.tauth.Tencent
import com.tencent.tauth.UiError
import org.apache.http.conn.ConnectTimeoutException
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
import java.lang.Exception
import java.net.MalformedURLException
import java.net.SocketTimeoutException

class LoginActivity : AppCompatActivity() {

    companion object {
        const val APP_ID = "101510659"
    }
    lateinit var signInFragment: SignInFragment
    lateinit var signUpFragment: SignUpFragment
    var fragmentList = ArrayList<Fragment>()
    lateinit var mTencent:Tencent
    lateinit var mTencentUiListener: BaseUiListener
    override fun onCreate(savedInstanceState: Bundle?) {
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        mTencent = Tencent.createInstance(APP_ID,applicationContext)
        mTencentUiListener = BaseUiListener()
        initFragments()
    }
    private fun initFragments() {
        setSupportActionBar(login_toolbar)
        supportActionBar?.title = ""
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        signInFragment = SignInFragment()
        signUpFragment = SignUpFragment()
        fragmentList.add(signInFragment)
        fragmentList.add(signUpFragment)
        login_viewpager.offscreenPageLimit = 2
        login_viewpager.adapter = KotlinPagerAdapter(fragmentList,supportFragmentManager)
        login_viewpager.setPageTransformer(true,CardPageTransformer())
        login_qq.setOnClickListener {
            tencentLo


s_algo = "MS_ZRTP_SAS_B256";
	res.sas_algo = {MS_ZRTP_SAS_B256};

	BC_ASSERT_EQUAL(zrtp_params_call(marieAlgo, paulineAlgo, res), 0, int, "%d");

	// Call where Marie uses MS_ZRTP_SAS_B256 and Pauline MS_ZRTP_SAS_B32
	// This result in using one or the other
	marieAlgo.sas_algo = "MS_ZRTP_SAS_B256";
	paulineAlgo.sas_algo = "MS_ZRTP_SAS_B32";
	res.sas_algo = {MS_ZRTP_SAS_B256, MS_ZRTP_SAS_B32};

	BC_ASSERT_EQUAL(zrtp_params_call(marieAlgo, paulineAlgo, res), 0, int, "%d");
}

static void zrtp_cipher_call(void) {
	ZrtpAlgoString marieAlgo;
	ZrtpAlgoString paulineAlgo;
	ZrtpAlgoRes res;

	// Default is AES128
	marieAlgo.cipher_algo = NULL;
	paulineAlgo.cipher_algo = NULL;
	res.cipher_algo = {MS_ZRTP_CIPHER_AES1};
	BC_ASSERT_EQUAL(zrtp_params_call(marieAlgo, paulineAlgo, res), 0, int, "%d");

	// Using AES128
	marieAlgo.cipher_algo = "MS_ZRTP_CIPHER_AES1";
	paulineAlgo.cipher_algo = "MS_ZRTP_CIPHER_AES1";
	res.cipher_algo = {MS_ZRTP_CIPHER_AES1};
	BC_ASSERT_EQUAL(zrtp_params_call(marieAlgo, paulineAlgo, res), 0, int, "%d");

	// Using AES256
	marieAlgo.cipher_algo = "MS_ZRTP_CIPHER_AES3";
	paulineAlgo.cipher_algo = "MS_ZRTP_CIPHER_AES3";
	res.cipher_algo = {MS_ZRTP_CIPHER_AES3};
	BC_ASSERT_EQUAL(zrtp_params_call(marieAlgo, paulineAlgo, res), 0, int, "%d");

	// One using AES128 and the other AES256, result can be any
	marieAlgo.cipher_algo = "MS_ZRTP_CIPHER_AES3";
	paulineAlgo.cipher_algo = "MS_ZRTP_CIPHER_AES1";
	res.cipher_algo = {MS_ZRTP_CIPHER_AES3, MS_ZRTP_CIPHER_AES1};
	BC_ASSERT_EQUAL(zrtp_params_call(marieAlgo, paulineAlgo, res), 0, int, "%d");
}

static void zrtp_key_agreement_call(void) {
	ZrtpAlgoString marieAlgo;
	ZrtpAlgoString paulineAlgo;
	ZrtpAlgoRes res;

	// Default is DH3k otherwise
	marieAlgo.key_agreement_algo = NULL;
	paulineAlgo.key_agreement_algo = NULL;
	res.key_agreement_algo = {MS_ZRTP_KEY_AGREEMENT_DH3K};
	BC_ASSERT_EQUAL(zrtp_params_call(marieAlgo, paulineAlgo, res), 0, int, "%d");

	// Use DH2k
	bctbx_list_t *ka_list = NULL;
	ka_list = bctbx_list_append(ka_list, (void *)(intptr_t)(LinphoneZrtpKeyAgreementDh2k));
	marieAlgo.key_agreement_algo = ka_list;
	paulineAlgo.key_agreement_algo = ka_list;
	res.key_agreement


(reporters, NewTempoDBReporter(config.TempoDB))
		log.Println("Reporters: TempoDB OK.")
	}

	if config.Librato.User == "" || config.Librato.Key == "" {
		log.Println("Reporters: No Librato credentials, skipping.")
	} else {
		reporters = append(reporters, NewLibratoReporter(config.Librato))
		log.Println("Reporters: Librato OK.")
	}

	if config.Graphite.LineRec == "" {
		log.Println("Reporters: No Graphite config, skipping.")
	} else {
		reporters = append(reporters, NewGraphiteReporter(config.Graphite))
		log.Println("Reporters: Graphite OK.")
	}

	if config.Stdout {
		log.Println("Reporters: Showing you output (you said -stdout=true).")
		reporters = append(reporters, NewStdoutReporter())
	}

	log.Println("Launching Health")

	report(config, &reporters)

	// set up a periodic report
	ticker := time.NewTicker(time.Second * time.Duration(config.Interval))
	go func() {
		for _ = range ticker.C {
			report(config, &reporters)
		}
	}()

	log.Println("Launching Control")

	//statics (UI)
	http.Handle("/", http.FileServer(http.Dir("./web/")))
	//control endpoint
	http.HandleFunc(control.Mount, control.Handler)
	http.HandleFunc(webreporter.Mount, webreporter.Handler)
	http.ListenAndServe(fmt.Sprintf("%s:%d", config.Host, config.Port), nil)
}

func report(config *GroundControlConfig, reporters *[]Reporter) {
	h, err := GetHealth(config.Temperature)
	if err != nil {
		log.Fatalln(err)
		os.Exit(-1)
	}

	for _, r := range *reporters {
		r.ReportHealth(h)
	}
}

func loadConfiguration(configPath string) (c *GroundControlConfig) {
	if configPath == "" {
		println("Error: You should specify a config file.")
		flag.Usage()
		os.Exit(-1)
	}

	text, err := ioutil.ReadFile(configPath)
	if err != nil {
		log.Fatalln("Cannot read config file: ", configPath)
	}

	config := &GroundControlConfig{}
	err = json.Unmarshal(text, &config)

	if err != nil {
		log.Fatalln("Cannot parse config file: ", configPath)
	}
	return config
}
// Copyright (c) 2012 VMware, Inc.

// +build darwin freebsd netbsd openbsd

// Go interface to BSD kqueue process events.
package psnotify

import (
	"syscall"
)

const (
	// Flags (from <sys/event.h>)
	PROC_EVENT_FORK = syscall.NOTE_FORK // fork() events
	PROC_EVENT_EXEC = syscall.NOTE_EXEC // exec() events
	PROC_EVENT_EXIT = syscall.NOTE_EXIT // exit() events

	// Watch for all process events
	PROC_EVENT_ALL = PROC_EVENT_FORK | PROC_EVENT_EXEC | PROC_EVENT_EXIT
)

type kqueueListener struct {
	kq  int                 // The syscall.Kqueue() file descriptor
	buf [1]syscall.Kevent_t // An event buffer for Add/Remove watch
}

// Initialize bsd implementation of the eventListener interface
func createListener() (eventListener, error) {
	listener := &kqueueListener{}
	kq, err := syscall.Kqueue()
	listener.kq = kq
	return listener, err
}

// Initialize Kevent_t fields and propagate changelist for the given pid
func (w *Watcher) kevent(pid int, fflags uint32, flags int) error {
	listener, _ := w.listener.(*kqueueListener)
	event := &listener.buf[0]

	syscall.SetKevent(event, pid, syscall.EVFILT_PROC, flags)
	event.Fflags = fflags

	_, err := syscall.Kevent(listener.kq, listener.buf[:], nil, nil)

	return err
}

// Delete filter for given pid from the queue
func (w *Watcher) unregister(


import torch
from .Criterion import Criterion
from .Sigmoid import Sigmoid
from .BCECriterion import BCECriterion

class MultiLabelSoftMarginCriterion(Criterion):
    """
    A MultiLabel multiclass criterion based on sigmoid:

    the loss is:
    l(x, y) = - sum_i y[i] * log(p[i]) + (1 - y[i]) * log (1 - p[i])
    where p[i] = exp(x[i]) / (1 + exp(x[i]))

    and with weights:
    l(x, y) = - sum_i weights[i] (y[i] * log(p[i]) + (1 - y[i]) * log (1 - p[i]))

    """

    def __init__(self, weights=None):
        super(MultiLabelSoftMarginCriterion, self).__init__()
        self.lsm = Sigmoid()
        self.nll = BCECriterion(weights)

    def updateOutput(self, input, target):
        input = input if input.nelement() == 1 else input.squeeze()
        target = target if target.nelement() == 1 else target.squeeze()
        self.lsm.updateOutput(input)
        self.nll.updateOutput(self.lsm.output, target)
        self.output = self.nll.output
        return self.output

    def updateGradInput(self, input, target):
        size = input.size()
        input = input if input.nelement() == 1 else input.squeeze()
        target = target if target.nelement() == 1 else target.squeeze()
        self.nll.updateGradInput(self.lsm.output, target)
        self.lsm.updateGradInput(input, self.nll.gradInput)
        self.gradInput = self.lsm.gradInput.view(size)
        return self.gradInput


  product: ProductCodeEnum.Ipa,
    text: '2x1 India Pale Ale Offer',
    discountApplied: 0,
  }],
  bulkDiscount: [{
    product: ProductCodeEnum.Hoppy,
    text: 'x3 Hoppy Pils',
    discountApplied: 0,
  }],
  promoCode: [{
    text: 'Promo Code',
    discountApplied: 0,
  }],
};

export const fakeDatabase = {
  products,
  pricingRules,
};

const delay = (ms: number): Promise<void> =>
  new Promise(resolve => setTimeout(resolve, ms));

export const fetchProducts = (): Promise<ProductInterface[] | undefined> =>
  delay(500).then(() => fakeDatabase.products);

export const fetchPricingRules =
  (): Promise<PricingRuleInterface | undefined> =>
    delay(500).then(() => fakeDatabase.pricingRules);

export const updateQuantity =
  (productCode: ProductCodeEnum, quantity: number = 0):
  Promise<ProductInterface | undefined> => delay(50).then(() => {
    const foundProduct = fakeDatabase.products
      .find((product: ProductInterface) => product.code === productCode);
    if (foundProduct){
      foundProduct.quantity += quantity;
    }
    return foundProduct;

  });
import {suite, test} from '@testdeck/mocha';
import {expect} from 'chai';
import {ExpressionInterpreter} from "../../src/libs/expressions/ExpressionInterpreter";

@suite('functional/expressions_interpreter')
class Expressions_interpreterSpec {

  @test
  async 'simple string equal condition'() {
    let conditions_string = '\'test\' = \'searchfor\'';
    let interpreter = new ExpressionInterpreter();
    let cond = interpreter.interprete(conditions_string);
    let json = cond.toJson();
    expect(json).to.deep.eq({
      'test': {'$eq': 'searchfor'}
    });
  }

  @test
  async 'simple numeric equal condition'() {
    let conditions_string = '\'testnr\' = 1';

    let interpreter = new ExpressionInterpreter();
    let cond = interpreter.interprete(conditions_string);
    let json = cond.toJson();
    expect(json).to.deep.eq({
      'testnr': {$eq: 1}
    });
  }

  @test
  async '"and" boolean grouping'() {
    let conditions_string = '\'testnr\' = 1 AND \'test\' = \'searchfor\'';
    let interpreter = new ExpressionInterpreter();
    let cond = interpreter.interprete(conditions_string);
    //console.log(interpreter.queue)
    let json = cond.toJson();
    expect(json).to.deep.eq({
      '$and': [
        {testnr: {$eq: 1}},
        {test: {$eq: 'searchfor'}},
      ]
    });
  }

  @test
  async '"or" boolean grouping'() {
    let conditions_string = '\'testnr\' = 1 OR \'test\' = \'searchfor\'';
    let interpreter = new ExpressionInterpreter();
    let cond = interpreter.interprete(conditions_string);
    //console.log(interpreter.queue)
    let json = cond.toJson();
    expect(json).to.deep.eq({
      '$or': [
        {testnr: {$eq: 1}},
        {test: {$eq: 'searchfor'}},
      ]
    });
  }

  @test
  async 'multiple "and" boolean grouping'() {
    let conditions_string = '\'testnr\' = 1 AND \'test\' = \'searchfor\' AND adc.def=1';
    let interpreter = new ExpressionInterpreter();
    let cond = interpreter.interprete(conditions_string);
    //console.log(interpreter.queue)
    let json