x(o => o === idx);
      if (currentIndex < 1) return o;
      return swap(o, currentIndex - 1, currentIndex);
    });
  }, []);

  return { order, setOrder, tabWidth, prev, next };
}
import { Router } from 'express'
import passport from 'passport'
import sendResponse from '../utils/sendResponse'
import Reason from '../models/Reason'

const router = Router()

router.get('/', async (req, res) => {
  try {
    const reasons = await Reason.find()

    if (!reasons || reasons.length <= 0) {
      return sendResponse(res, 500, 'Error to find or you don\'t have a reasons')
    }

    return sendResponse(res, 200, { reasons })
  } catch (err) {
    return sendResponse(res, 500, err.message || 'Server error')
  }
})

router.post('/', passport.authenticate('admin-token'), async (req, res) => {
  try {
    const { reason } = req.body

    if (!reason || reason === '') {
      return sendResponse(res, 404, 'Your reason is invalid')
    }

    const verifyReason = await Reason.findOne({ reason })

    if (verifyReason) {
      return sendResponse(res, 402, 'The reason exist')
    }

    const reasonSave = await Reason.create({ reason })

    if (!reasonSave) {
      return sendResponse(res, 500, 'Error to save reason')
    }

    return sendResponse(res, 200, 'Reason saved')
  } catch (err) {
    return sendResponse(res, 500, err.message || 'Server error')
  }
})

router.delete('/:id', passport.authenticate('admin-token'), async (req, res) => {
  try {
    const { id } = req.params
    const reasonDelete = await Reason.findByIdAndDelete(id)

    if (!reasonDelete) {
      return sendResponse(res, 500, 'Error to delete reason or doesn\'t exist')
    }

    return sendResponse(res, 200, 'Reason deleted')
  } catch (err) {
    return sendResponse(res, 500, err.message || 'Server error')
  }
})

export default router

module game {
    /**
 * brief:   游戏名
 * date:    2017-11-09
 * author:  徐为
 */
  export enum GameName{
    e_xinPuMj = 0,              //新浦麻将
    e_ganYuMj = 1,              //赣榆麻将
  }

/**
 * brief:   游戏方式
 * date:    2017-11-09
 * author:  徐为
 */
export enum GameStyle{
  e_createRooom = 0,         //创建房间
  e_joinRoom = 1,            //加入房间
}

    /**
 * brief:   游戏管理类
 * date:    2017-11-09
 * author:  徐为
 */
   export class GameManager{

      /********************************/

        public m_sCreatorUId:string;
        private m_gameStyle:GameStyle;

        public m_nCostDiamond:number;  //花费钻石数

        public m_pCreatorPos:PlayePosition;     //房间创建者位置

        public m_nLoginType:number;    //登录方式，0微信登录

        private m_oRoomInfo:S2C_RoomInfoPacket;

      /********************************/

       public constructor()
       {
           this.m_nLoginType = 0;

           this.m_oRoomInfo = new S2C_RoomInfoPacket();

       }

       public fGetRoomInfo(){
         return this.m_oRoomInfo;
       }

       public fSetRoomInfo(roomInfo:S2C_RoomInfoPacket){
           this.m_oRoomInfo = roomInfo;
       }

       public fSetGameName(name:GameName)
       {
           this.m_oRoomInfo.m_gameName = name;
       }

       public fGetGameName():GameName


-index:1000;background:rgba(0,0,0,0.1);-webkit-animation:kt-animate-fade-in .3s linear 1;animation:kt-animate-fade-in .3s linear 1}.kt-demo-panel-overlay{background:rgba(0,0,0,0.05)}@media (max-width: 400px){.kt-demo-panel{width:90% !important}}@media (max-width: 1024px){.kt-demo-panel-toggle{width:30px;padding:1rem 0}.kt-demo-panel-toggle span{font-size:1.2rem;font-weight:600;letter-spacing:2px}.kt-demo-panel{padding:1rem}.kt-demo-panel-toggle{top:20%}}.kt-quick-panel{background-color:#fff;-webkit-box-shadow:0px 0px 28px 0px rgba(82,63,105,0.13);box-shadow:0px 0px 28px 0px rgba(82,63,105,0.13);padding:0}.kt-quick-panel .kt-quick-panel__close{position:absolute;z-index:1;left:1.5rem;top:1.5rem;display:-webkit-box;display:-ms-flexbox;display:flex;-webkit-box-pack:center;-ms-flex-pack:center;justify-content:center;-webkit-box-align:center;-ms-flex-align:center;align-items:center;width:28px;height:28px;background-color:#f7f8fa;-webkit-transition:all 0.3s;transition:all 0.3s;border-radius:4px}.kt-quick-panel .kt-quick-panel__close i{-webkit-transition:all 0.3s;transition:all 0.3s;font-size:0.8rem;color:#a7abc3}.kt-quick-panel .kt-quick-panel__close:hover{-webkit-transition:all 0.3s;transition:all 0.3s;background-color:#591df1}.kt-quick-panel .kt-quick-panel__close:hover i{-webkit-transition:all 0.3s;transition:all 0.3s;color:#fff}.kt-quick-panel .kt-quick-panel__nav{display:-webkit-box;display:-ms-flexbox;display:flex;position:relative;padding:1.5rem 0 0 0;-webkit-box-align:center;-ms-flex-align:center;align-items:center}.kt-quick-panel .kt-quick-panel__nav .nav{width:100%;padding:0 1.5rem;margin:0}.kt-quick-panel .kt-quick-panel__nav .nav .nav-item{margin-left:1.5rem}.kt-quick-panel .kt-quick-panel__nav .nav .nav-item .nav-link{font-size:1rem;color:#a7abc3}.kt-quick-panel .kt-quick-panel__nav .nav .nav-item:last-child{margin-left:0}.kt-quick-panel .kt-quick-panel__content{padding:1.5rem 0}.kt-quick-panel .kt-quick-panel__content .ps>.ps__rail-y{left:5px !important}.kt-quick-panel .kt-quick-panel__content-padding-x{padding-right:1.5rem;padding-left:1.5rem}.kt-quick-panel-close{display:none}.kt-quick-panel{z-index:1001;position:fixed;-webkit-overflow-scrolling:touch;top:0;bottom:0;overflow-y:auto;-webkit-transform:translate3d(0, 0, 0);backface-visibility:hidden;-webkit-backface-visibility:hidden;width:425px !important;-webkit-transition:all 0.3s ease;transition:all 0.3s ease;left:-445px}.kt-quick-panel.kt-quick-panel--on{-webkit-transition:all 0.3s ease;transition:all 0.3s ease;left:0}@media screen\0 {.kt-quick-panel{-webkit-transition:none !important;


是为何Self Attention逐渐被广泛使用的主要原因。

序列编码¶

深度学习做NLP的方法，基本上都是先将句子分词，然后每个词转化为对应的词向量序列。这样一来，每个句子都对应的是一个矩阵\(X=(x_1,x_2,…,x_t)\)，其中xi都代表着第i个词的词向量（行向量），维度为d维，故\(X∈R_n×d\)。这样的话，问题就变成了编码这些序列了。

RNN¶

\[ y_t=f(y_{t−1},x_t) \]

不管是已经被广泛使用的LSTM、GRU还是最近的SRU，都并未脱离这个递归框架。RNN结构本身比较简单，也很适合序列建模，但RNN的明显缺点之一就是无法并行，因此速度较慢，这是递归的天然缺陷。另外苏剑林博士认为RNN无法很好地学习到全局的结构信息，因为它本质是一个马尔科夫决策过程。

不管是已经被广泛使用的LSTM、GRU还是最近的SRU，都并未脱离这个递归框架。RNN结构本身比较简单，也很适合序列建模，但RNN的明显缺点之一就是无法并行，因此速度较慢，这是递归的天然缺陷。另外苏剑林博士认为RNN无法很好地学习到全局的结构信息，因为它本质是一个马尔科夫决策过程。

CNN¶

\[ \boldsymbol{y}_{t}=f\left(\boldsymbol{x}_{t-1}, \boldsymbol{x}_{t}, \boldsymbol{x}_{t+1}\right) \]

在FaceBook的论文中，纯粹使用卷积也完成了Seq2Seq的学习，是卷积的一个精致且极致的使用案例，热衷卷积的读者必须得好好读读这篇文论。CNN方便并行，而且容易捕捉到一些全局的结构信息。

Attention¶

Google的大作提供了第三个思路：纯Attention，单靠注意力就可以RNN要逐步递归才能获得全局信息，因此一般要双向RNN才比较好；CNN事实上只能获取局部信息，是通过层叠来增大感受野；Attention的思路最为粗�


var o=k;"("===k&&(o=")"),o=(o+"").replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1");var p="^\\s*(?:[^"+o+"\\\\]+|\\\\\\\\|\\\\.)"+o;if(b.match(new RegExp(p),!0))return h.linkHref}if("`"===k){var q=d.formatting;c.highlightFormatting&&(d.formatting="code");var r=z(d),t=b.pos;b.eatWhile("`");var u=1+b.pos-t;return d.code?u===g?(d.code=!1,r):(d.formatting=q,z(d)):(g=u,d.code=!0,z(d))}if(d.code)return z(d);if("!"===k&&b.match(/\[[^\]]*\] ?(?:\(|\[)/,!1))return b.match(/\[[^\]]*\]/),d.inline=d.f=D,h.image;if("["===k&&b.match(/.*\](\(.*\)| ?\[.*\])/,!1))return d.linkText=!0,c.highlightFormatting&&(d.formatting="link"),z(d);if("]"===k&&d.linkText&&b.match(/\(.*\)| ?\[.*\]/,!1)){c.highlightFormatting&&(d.formatting="link");var l=z(d);return d.linkText=!1,d.inline=d.f=D,l}if("<"===k&&b.match(/^(https?|ftps?):\/\/(?:[^\\>]|\\.)+>/,!1)){d.f=d.inline=C,c.highlightFormatting&&(d.formatting="link");var l=z(d);return l?l+=" ":l="",l+h.linkInline}if("<"===k&&b.match(/^[^> \\]+@(?:[^\\>]|\\.)+>/,!1)){d.f=d.inline=C,c.highlightFormatting&&(d.formatting="link");var l=z(d);return l?l+=" ":l="",l+h.linkEmail}if("<"===k&&b.match(/^(!--|\w)/,!1)){var v=b.string.indexOf(">",b.pos);if(-1!=v){var x=b.string.substring(b.start,v);/markdown\s*=\s*('|"){0,1}1('|"){0,1}/.test(x)&&(d.md_inside=!0)}return b.backUp(1),d.htmlState=a.startState(e),s(b,d,w)}if("<"===k&&b.match(/^\/\w*?>/))return d.md_inside=!1,"tag";var y=!1;if(!c.underscoresBreakWords&&"_"===k&&"_"!==b.peek()&&b.match(/(\w)/,!1)){var A=b.pos-2;if(A>=0){var B=b.string.charAt(A);"_"!==B&&B.match(/(\w)/,!1)&&(y=!0)}}if("*"===k||"_"===k&&!y)if(j&&" "===b.peek());else{if(d.strong===k&&b.eat(k)){c.highlightFormatting&&(d.formatting="strong");var r=z(d);return d.strong=!1,r}if(!d.strong&&b.eat(k))return d.strong=k,
c.highlightFormatting&&(d.formatting="strong"),z(d);if(d.em===k){c.highlightFormatting&&(d.formatting="em");var r=z(d);return d.em=!1,r}if(!d.em)return d.em=k,c.highlightFormatting&&(d.formatting="em"),z(d)}else if(" "===k&&(b.eat("*")||b.eat("_"))){if(" "===b.peek())return z(d);b.backUp(1)}if(c.strikethrough)if("~"===k&&b.eatWhile(k)){if(d.strikethrough){c.highlightFormat


e, highscore
    if LEVELSTART == 0: myship.dx = 2
    if PlayerAlive or LEVELSTART == 0: myship.move()
    for fruit in fruitlist:
       if checkcollisionrect(myship,fruit):
            pointsawarded = LEDscoreobj(canvas1,x=fruit.x-7,y=fruit.y+10,score=fruit.PointsType,colour="yellow",pixelsize=2, charwidth = 15, solid = True, bg = False)
            scoreddisplay.append(pointsawarded)
            fruit.undraw()
            fruitlist.remove(fruit)
            score = score + fruit.PointsType
            progressbar.update(score, progressbar.max)
            if score > highscore:
                highscore = score
                displayhighscore.update(highscore)
            displayscore.update(score)
    for solid in solidlist:
         if checkcollisionrect(myship,solid):
            if not HitWall:
              myship.x = myship.x - myship.dx
              myship.y = myship.y - myship.dy
            myship.dx = 0
            myship.dy = 0
            HitWall = True
            break # exit the for loop
    mainwin.after(10,gameloop)

def startgame():
    global starttime
    starttime = time.time()

def setlevel():
    global walls,pointsset,score, highscore
    eraseplayfield()
    walls = wallslist[LEVELSTART]
    pointsset = pointslist[LEVELSTART]
    createplayfield()
    myship.resetposition(STARTX,STARTY)
    score = 0
    highscore = load_high_score()
    displayclock.colour = "lightgreen"
    displayhighscore.update(highscore)
    displayscore.update(score)
    displayclock.update(7)
    progressbar.update(0, maxlist[LEVELSTART])

setlevel()
startgame()
gameloop()
counttime = time.time()

displaycountdown = LEDscoreobj(canvas1,x=MAXx//4,y=MAXy//4,score=3,colour="orange",pixelsize=50, charwidth = 24,numzeros=0, solid = False, bg = False)
displaycountdown.undraw()

def countdown():
    global displaycountdown, PlayerAlive
    elapsedtime = time.time() - counttime
    if (elapsedtime <= 3.1) and LEVELSTART > 0:
           displaycountdown.update(3-int(elapsedtime))
           mainwin.after(500,countdown)
    else:
           displaycountdown.undraw()
           if LEVELSTART > 0 : PlayerAlive = True
           startgame()

def mykey(event):
    global HitWall, PlayerAlive, starttime,score, highscore,walls,pointsset, LEVELSTART, counttime
    key = event.keysym
    if key in "0123456789":
        undrawtitle()
        if key == "0":
            displaytitle()
        PlayerAlive = False
        myship.rotate(90)
        myship.dy = 0
        myship.dx = STEPD
        resetdisplayclock()
        LEVELSTART = int(key)
        displaylevel.update(LEVELSTART)
        setlevel()
        counttime = time.time()
        countdown()
    if HitWall:
         HitWall = False
    elif (key == "w" or key == "Up") and LEVELSTART > 0:
         myship.rotate(0)
         myship.dy = -STEPD
         myship.dx = 0
    elif (key == "d" or key == "Right") and LEVELSTART > 0:
         myship.rotate(90)
         myship.dy = 0
         myship.dx = STEPD
    elif (key == "a" or key == "Left") and LEVELSTART > 0:
         myship.rotate(270)
         myship.dy = 0
         myship.dx = -STEPD
    elif (key == "s" or key == "Down") and LEVELSTART > 0:
         myship.rotate(180)
         myship.dy = STEPD
         myship.dx = 0

mainwin.bind("<KeyPress>", mykey)
mainwin.mainloop()


://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package bpfmanoperator

import (
	"context"
	"reflect"

	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
	"sigs.k8s.io/controller-runtime/pkg/event"
	"sigs.k8s.io/controller-runtime/pkg/predicate"

	bpfmaniov1alpha1 "github.com/bpfman/bpfman-operator/apis/v1alpha1"
	internal "github.com/bpfman/bpfman-operator/internal"
)

type NamespaceApplicationReconciler struct {
	ReconcilerCommon[bpfmaniov1alpha1.BpfApplicationState, bpfmaniov1alpha1.BpfApplicationStateList]
}

//lint:ignore U1000 Linter claims function unused, but generics confusing linter
func (r *NamespaceApplicationReconciler) getAppStateList(
	ctx context.Context,
	appName string,
	appNamespace string,
) (*bpfmaniov1alpha1.BpfApplicationStateList, error) {

	appStateList := &bpfmaniov1alpha1.BpfApplicationStateList{}

	// Only list BpfApplicationState objects for this Program
	opts := []client.ListOption{
		client.MatchingLabels{internal.BpfAppStateOwner: appName},
		client.InNamespace(appNamespace),
	}

	err := r.List(ctx, appStateList, opts...)
	if err != nil {
		return nil, err
	}

	return appStateList, nil
}

//lint:ignore U1000 Linter claims function unused, but generics confusing linter
func (r *NamespaceApplicationReconciler) containsFinalizer(
	bpfAppState *bpfmaniov1alpha1.BpfApplicationState,
	finalizer string,
) bool {
	return controllerutil.ContainsFinalizer(bpfAppState, finalizer)
}

func statusChangedPredicateNamespace() predicate.Funcs {
	return predicate.Funcs{
		GenericFunc: func(e event.GenericEvent) bool {
			return false
		},
		CreateFunc: func(e event.CreateEvent) bool {
			return false
		},
		UpdateFunc: func(e event.UpdateEvent) bool {
			oldObject := e.ObjectOld.(*bpfmaniov1alpha1.BpfApplicationState)
			newObject := e.ObjectNew.(*bpfmaniov1alpha1.BpfApplicationState)
			statusChanged := !reflect.DeepEqual(oldObject.Status.Conditions, newObject.Status.Conditions)
			finalizerChanged := controllerutil.ContainsFinalizer(oldObject, internal.NsBpfApplicationControllerFinalizer) !=
				controllerutil.ContainsFinalizer(newObject, internal.NsBpfApplicationControllerFinalizer)
			return statusChanged || finalizerChanged
		},
		DeleteFunc: func(e event.DeleteEvent) bool {
			return false
		},
	}
}
/*
Copyright 2025 The bpfman Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for


 &Biome, end: &Biome) -> u8 {
        (end.row - start.row) as u8
    }

    fn get_biome<'b>(biomes: &'b Vec<Biome>, id: &Id) -> &'b Biome {
        biomes
            .into_iter()
            .find(|biome| &biome.id == id)
            .expect(format!("No biome with id {:?}", id).as_str())
    }

    fn enabled(start_id: &Id, end_id: &Id, blacklist: &Vec<Id>) -> bool {
        return if blacklist.contains(&start_id) || blacklist.contains(&end_id) {
            false
        } else {
            true
        };
    }

    'biome: for biome in biomes {
        let start_id = biome.id.clone();
        let row = biome.row as u8;
        let start_column = biome.column as u8;
        let start_columns = calc_columns(biomes, biome.row) as u8;

        'exit: for exit in &biome.exits {
            let end_biome = get_biome(biomes, &exit.destination);
            let end_column = end_biome.column as u8;
            let end_columns = calc_columns(biomes, end_biome.row) as u8;
            let length = calc_length(biome, end_biome);

            // todo fix tolowercase hack
            result.push(RenderablePath {
                id: format!(
                    "{}-{}",
                    start_id.to_string().to_lowercase(),
                    exit.destination.to_string().to_lowercase()
                ),
                start_column,
                start_column_offset: 0,
                start_columns,
                end_column,
                end_column_offset: 0,
                end_columns,
                row,
                length,
                enabled: enabled(&start_id, &end_biome.id, blacklist),
            });
        }
    }

    result
}

fn filter_reachable_biomes(biomes: Vec<Biome>, whitelist: &Vec<Id>) -> Vec<Biome> {
    biomes
        .into_iter()
        .map(|mut biome| {
            biome.enabled = whitelist.contains(&biome.id);
            biome
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::path::RenderablePath;

    #[test]
    fn should_gracefully_fail() {
        let fail = get_biomes_from_str("qweqeqqwe{{{{");
        assert!(fail.is_err());
        if let Err(str) = fail {
            assert_eq!(
                str,
                "Failed to parse json: expected value at line 1 column 1"
            );
        }
    }

    #[test]
    fn test_id_serde() {
        let json = serde_json::to_string(&Id::Castle).unwrap();
        assert_eq!(json, String::from("\"castle\""));

        let id: Id = serde_json::from_str("\"castle\"").unwrap();
        assert_eq!(id, Id::Castle);
    }

    #[test]
    fn parse_json() {
        let biomes = get_biomes().unwrap();
        assert_eq!(biomes.len(), 25);
    }

    #[test]
    fn biome_from_tuple() {
        let biome: Biome = (Id::Prisonquart, vec![Id::Castle, Id::Crypt]).into();

        let expected = Biome {
            id: Id::Prisonquart,
            name: Id::Prisonquart.to_string(),
            row: 0,
            column: 0,
            power_scrolls: 0,
            dual_power_scrolls: 0,
            cursed_chest_chance: 0,
            scroll_fragments: Default::default(),
            gear_level: 0,
            exits: vec![
                Exit {
                    destination: Id::Castle,


::InvalidMacAddress { .. } => 6,
            DnsmasqHookError::InvalidDuid { .. } => 7,
            DnsmasqHookError::UnsupportedEventType { .. } => 8,
            DnsmasqHookError::EnforcerConnectionError { .. } => 63,
            DnsmasqHookError::EventSerializationError { .. } => 64,
            DnsmasqHookError::RequiredArgumentMissing { .. } => 1,
        }
    }
}

/// Error wrapper type for the dnsmasq hook script.
#[derive(Debug, Snafu)]
// Because this script will only ever produce at most one instance of this error per execution, I
// think we can safely ignore the wasted memory space here.
#[allow(clippy::large_enum_variant)]
enum DnsmasqHookError {
    /// The IP address that was supplied was not properly formatted.
    #[snafu(display("Supplied IP Address \"{}\" is not valid: {}", "supplied_address", "source"))]
    InvalidIpAddress {
        supplied_address: String,
        source: net::AddrParseError,
    },
    /// A required argument for the script was missing.
    #[snafu(display("Not enough arguments supplied. Missing {} arguments.", "missing_arg_count"))]
    NotEnoughArguments { missing_arg_count: usize },
    #[snafu(display("Required argument \"{}\" is missing", "missing_arg_name"))]
    RequiredArgumentMissing { missing_arg_name: String },
    /// The supplied lease time is not a valid number.
    #[snafu(display(
        "Supplied lease time \"{}\" is not a valid number: {}",
        "supplied_lease_time",
        "source"
    ))]
    InvalidLeaseTime {
        supplied_lease_time: String,
        source: num::ParseIntError,
    },
    /// A required environment variable is missing.
    #[snafu(display("Required environment variable \"{}\" is missing", "missing_var_name"))]
    RequiredEnvironmentVariableMissing {
        missing_arg_name: String,
        source: env::VarError,
    },
    /// The supplied MAC-Address is not of the correct format.
    #[snafu(display("Supplied MAC address \"{}\" is not valid: {}", "supplied_mac", "source"))]
    InvalidMacAddress {
        supplied_mac: String,
        source: macaddr::ParseError,
    },
    /// The supplied DUID is not of the correct format.
    #[snafu(display("Supplied DUID \"{}\" is not valid.", "supplied_duid"))]
    InvalidDuid { supplied_duid: String },
    /// The event type this script was called with is not supported.
    #[snafu(display("Supplied event type \"{}\" is not supported", "supplied_type"))]
    UnsupportedEventType { supplied_type: String },
    /// Error while connecting to enforcer.
    #[snafu(display("Could not connect to enforcer: {}", "source"))]
    EnforcerConnectionError { source: std::io::Error },
    /// Error while serializing event.
    #[snafu(display("Could not serialize Event {}: {}", "event", "source"))]
    EventSerializationError {
        event: DhcpEvent,
        source: serde_json::Error,
    },
}

type Result<T> = std::result::Result<T, DnsmasqHookError>;

/// Main function for the dnsmasq hook binary.
/// This hook is called by dnsmasq (if configured correctly using the dhcp-script option) for
/// various events (e.g. a DHCP lease is created or destroyed). This binary will then create a
/// DhcpEvent out of the supplied data and pass it to the enforcer if possible.
///
/// For MUD clients,


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

namespace OpenXcom
{

class BattlescapeGame;
class TileEngine;
class Tile;
class BattleUnit;

/**
 * State for falling units.
 */
class UnitFallBState : public BattleState
{
private:
	TileEngine *_terrain;
	std::vector<Tile*> tilesToFallInto;
	std::vector<BattleUnit*> unitsToMove;
public:
	/// Creates a new UnitWalkBState class
	UnitFallBState(BattlescapeGame *parent);
	/// Cleans up the UnitWalkBState.
	~UnitFallBState();
	/// Initializes the state.
	void init();
	/// Runs state functionality every cycle. Returns when finished.
	void think();
};

}


g;
		moles_surface = mass_water_surface * molality + moles_excess;
/*
 *   Accumulate elements in diffuse layer
 */
		add_elt_list(s_x[j]->next_elt, moles_surface);
	}
	add_elt_list(s_h2o->next_elt, mass_water_surface / gfw_water);

	if (count_elts > 0)
	{
		qsort(elt_list, (size_t) count_elts,
			  (size_t) sizeof(struct elt_list), elt_list_compare);
		elt_list_combine();
	}
	return (OK);
}
/* ---------------------------------------------------------------------- */
int Phreeqc::
calc_all_donnan(void)
/* ---------------------------------------------------------------------- */
{
	bool converge;
	int cd_m;
	LDBLE new_g, f_psi, surf_chrg_eq, psi_avg, f_sinh, A_surf, ratio_aq;
	LDBLE new_g2, f_psi2, surf_chrg_eq2, psi_avg2, dif, var1;

	if (use.Get_surface_ptr() == NULL)
		return (OK);
	//f_sinh = sqrt(8000.0 * EPSILON * EPSILON_ZERO * (R_KJ_DEG_MOL * 1000.0) *
	//		 tk_x * mu_x);
	f_sinh = sqrt(8000.0 * eps_r * EPSILON_ZERO * (R_KJ_DEG_MOL * 1000.0) *
			 tk_x * mu_x);
/*
 *   calculate g for each surface...
 */
	converge = TRUE;
	for (int j = 0; j < count_unknowns; j++)
	{
		if (x[j]->type != SURFACE_CB)
			continue;
		cxxSurfaceCharge *charge_ptr = use.Get_surface_ptr()->Find_charge(x[j]->surface_charge);

		if (debug_diffuse_layer == TRUE)
			output_msg(sformatf( "Calc_all_g, X[%d]\n", j));
/*
 *  sum eq of each charge number in solution...
 */
		std::map<LDBLE, LDBLE>::iterator it;
		for (it = charge_group_map.begin(); it != charge_group_map.end(); it++)
		{
			it->second = 0.0;
		}
		charge_group_map.clear();
		for (int i = 0; i < count_s_x; i++)
		{
			if (s_x[i]->type > HPLUS)
				continue;
			charge_group_map[s_x[i]->z] += s_x[i]->z * s_x[i]->moles * s_x[i]->erm_ddl;
		}
		/* find surface charge from potential... */
		A_surf = charge_ptr->Get_specific_area() * charge_ptr->Get_grams();
		if (use.Get_surface_ptr()->Get_type() == cxxSurface::CD_MUSIC)
		{
			f_psi = x[j + 2]->master[0]->s->la * LOG_10;	/* -FPsi/RT */
			f_psi = f_psi / 2;
			cd_m = 1;
		} else
		{
			f_psi = x[j]->master[0]->s->la * LOG_10;
			cd_m = -1;
		}
		surf_chrg_eq = A_surf * f_sinh * sinh(f_psi) / F_C_MOL;
		if (surf_chrg_eq < -5e3)
		{
			surf_chrg_eq = -5e3;
			var1 = surf_chrg_eq / (A_surf * f_sinh / F_C_MOL);
			var1 = (var1 + sqrt(var1 * var1 + 1));
			f_psi = (var1 > 1e-8 ? log(var1) : -18.4);
			surf_chrg_eq = A_surf * f_sinh * sinh(f_psi) / F_C_MOL;
			x[j]->master[0]->s->la = f_psi / LOG


tem(&wsets[j].pitem));
    prlook( wsets[j].ws );
    printf( "\n" );
    }

  }

struct looksets *flset( p )
	struct looksets *p;
	{
	/* decide if the lookahead set pointed to by p is known */
	/* return pointer to a perminent location for the set */

	int j, *w;
	_REGISTER *u, *v, i;

	for( i=0; i<nlset; ++i ){
		u = p->lset;
		v = lkst[i].lset;
		w = & v[tbitset];
		while( v<w) if( *u++ != *v++ ) goto more;
		/* we have matched */
		return( & lkst[i] );
		more: ;
		}
	/* add a new one */
	if( nlset+1 >= lsetsz )error("too many lookahead sets");
	for( j=0; j<tbitset; ++j ){
		lkst[nlset].lset[j] = p->lset[j];
		}
	return( & lkst[nlset++]);
	}


using Grand.Domain;
using Grand.Domain.Orders;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Grand.Services.Orders
{
    /// <summary>
    /// Gift card service interface
    /// </summary>
    public partial interface IGiftCardService
    {
        /// <summary>
        /// Deletes a gift card
        /// </summary>
        /// <param name="giftCard">Gift card</param>
        Task DeleteGiftCard(GiftCard giftCard);

        /// <summary>
        /// Gets a gift card
        /// </summary>
        /// <param name="giftCardId">Gift card identifier</param>
        /// <returns>Gift card entry</returns>
        Task<GiftCard> GetGiftCardById(string giftCardId);

        /// <summary>
        /// Gets all gift cards
        /// </summary>
        /// <param name="purchasedWithOrderItemId">Associated order ID; null to load all records</param>
        /// <param name="createdFromUtc">Created date from (UTC); null to load all records</param>
        /// <param name="createdToUtc">Created date to (UTC); null to load all records</param>
        /// <param name="isGiftCardActivated">Value indicating whether gift card is activated; null to load all records</param>
        /// <param name="giftCardCouponCode">Gift card coupon code; null to load all records</param>
        /// <param name="recipientName">Recipient name; null to load all records</param>
        /// <param name="pageIndex">Page index</param>
        /// <param name="pageS


_regs->r8 */
	pushq	%r9				/* pt_regs->r9 */
	pushq	%r10				/* pt_regs->r10 */
	pushq	%r11				/* pt_regs->r11 */
	sub	$(6*8), %rsp			/* pt_regs->bp, bx, r12-15 not saved */

	testl	$_TIF_WORK_SYSCALL_ENTRY, ASM_THREAD_INFO(TI_flags, %rsp, SIZEOF_PTREGS)
	jnz	tracesys
entry_SYSCALL_64_fastpath:
#if __SYSCALL_MASK == ~0
	cmpq	$NR_syscalls, %rax
#else
	andl	$__SYSCALL_MASK, %eax
	cmpl	$NR_syscalls, %eax
#endif
	jae	1f				/* return -ENOSYS (already in pt_regs->ax) */
	sbb	%rcx, %rcx			/* array_index_mask_nospec() */
	and	%rcx, %rax
	movq	%r10, %rcx

	/*
	 * This call instruction is handled specially in stub_ptregs_64.
	 * It might end up jumping to the slow path.  If it jumps, RAX is
	 * clobbered.
	 */
#ifdef CONFIG_RETPOLINE
	movq	sys_call_table(, %rax, 8), %rax
	call	__x86_indirect_thunk_rax
#else
	call	*sys_call_table(, %rax, 8)
#endif
.Lentry_SYSCALL_64_after_fastpath_call:

	movq	%rax, RAX(%rsp)
1:
/*
 * Syscall return path ending with SYSRET (fast path).
 * Has incompletely filled pt_regs.
 */
	LOCKDEP_SYS_EXIT
	/*
	 * We do not frame this tiny irq-off block with TRACE_IRQS_OFF/ON,
	 * it is too small to ever cause noticeable irq latency.
	 */
	DISABLE_INTERRUPTS(CLBR_NONE)

	/*
	 * We must check ti flags with interrupts (or at least preemption)
	 * off because we must *never* return to userspace without
	 * processing exit work that is enqueued if we're preempted here.
	 * In particular, returning to userspace with any of the one-shot
	 * flags (TIF_NOTIFY_RESUME, TIF_USER_RETURN_NOTIFY, etc) set is
	 * very bad.
	 */
	testl	$_TIF_ALLWORK_MASK, ASM_THREAD_INFO(TI_flags, %rsp, SIZEOF_PTREGS)
	jnz	int_ret_from_sys_call_irqs_off	/* Go to the slow path */

	movq	RIP(%rsp), %rcx
	movq	EFLAGS(%rsp), %r11
	RESTORE_C_REGS_EXCEPT_RCX_R11
	/*
	 * This opens a window where we have a user CR3, but are
	 * running in the kernel.  This makes using the CS
	 * register useless for telling whether or not we need to
	 * switch CR3 in NMIs.  Normal interrupts are OK because
	 * they are off here.
	 */
	SWITCH_USER_CR3
	movq	RSP(%rsp), %rsp
	/*
	 * 64-bit SYSRET restores rip from rcx,
	 * rflags from r11 (but RF and VM bits are forced to 0),
	 * cs and ss are loaded from MSRs.
	 * Restoration of rflags re-enables interrupts.
	 *
	 * NB: On AMD CPUs with the X86_BUG_SYSRET_SS_ATTRS bug, the ss
	 * descriptor is not reinitialized.  This means that we should
	 * avoid SYSRET with SS == NULL, which could happen if we schedule,
	 * exit the kernel, and re-enter using an interrupt vector.  (All
	 * interrupt entries on x86_64 set SS to NULL.)  We prevent that
	 * from happening by reloading S


ESET;
	regmap_write(priv->regmap, U2P_R0, val);

	phy_meson_gxl_usb2_set_host_mode(priv);

#if CONFIG_IS_ENABLED(DM_REGULATOR)
	if (priv->phy_supply) {
		int ret = regulator_set_enable(priv->phy_supply, true);
		if (ret)
			return ret;
	}
#endif

	return 0;
}

static int phy_meson_gxl_usb2_power_off(struct phy *phy)
{
	struct udevice *dev = phy->dev;
	struct phy_meson_gxl_usb2_priv *priv = dev_get_priv(dev);
	uint val;

	regmap_read(priv->regmap, U2P_R0, &val);
	/* power off the PHY by putting it into reset mode */
	val |= U2P_R0_POWER_ON_RESET;
	regmap_write(priv->regmap, U2P_R0, val);

#if CONFIG_IS_ENABLED(DM_REGULATOR)
	if (priv->phy_supply) {
		int ret = regulator_set_enable(priv->phy_supply, false);
		if (ret) {
			pr_err("Error disabling PHY supply\n");
			return ret;
		}
	}
#endif

	return 0;
}

struct phy_ops meson_gxl_usb2_phy_ops = {
	.power_on = phy_meson_gxl_usb2_power_on,
	.power_off = phy_meson_gxl_usb2_power_off,
};

int meson_gxl_usb2_phy_probe(struct udevice *dev)
{
	struct phy_meson_gxl_usb2_priv *priv = dev_get_priv(dev);
	int ret;

	ret = regmap_init_mem(dev_ofnode(dev), &priv->regmap);
	if (ret)
		return ret;

#if CONFIG_IS_ENABLED(CLK)
	ret = clk_get_by_index(dev, 0, &priv->clk);
	if (ret < 0)
		return ret;

	ret = clk_enable(&priv->clk);
	if (ret && ret != -ENOSYS && ret != -ENOTSUPP) {
		pr_err("failed to enable PHY clock\n");
		clk_free(&priv->clk);
		return ret;
	}
#endif

#if CONFIG_IS_ENABLED(DM_REGULATOR)
	ret = device_get_supply_regulator(dev, "phy-supply", &priv->phy_supply);
	if (ret && ret != -ENOENT) {
		pr_err("Failed to get PHY regulator\n");
		return ret;
	}
#endif

	return 0;
}

static const struct udevice_id meson_gxl_usb2_phy_ids[] = {
	{ .compatible = "amlogic,meson-gxl-usb2-phy" },
	{ }
};

U_BOOT_DRIVER(meson_gxl_usb2_phy) = {
	.name = "meson_gxl_usb2_phy",
	.id = UCLASS_PHY,
	.of_match = meson_gxl_usb2_phy_ids,
	.probe = meson_gxl_usb2_phy_probe,
	.ops = &meson_gxl_usb2_phy_ops,
	.priv_auto_alloc_size = sizeof(struct phy_meson_gxl_usb2_priv),
};


));
  cupsLangPuts(out, _("-C COUNTRY                     Set country."));
  cupsLangPuts(out, _("-L LOCALITY                    Set locality name."));
  cupsLangPuts(out, _("-O ORGANIZATION                Set organization name."));
  cupsLangPuts(out, _("-R CSR-FILENAME                Specify certificate signing request file."));
  cupsLangPuts(out, _("-S STATE                       Set state."));
  cupsLangPuts(out, _("-U ORGANIZATIONAL-UNIT         Set organizational unit name."));
  cupsLangPuts(out, _("-a SUBJECT-ALT-NAME            Add a subjectAltName."));
  cupsLangPuts(out, _("-d DAYS                        Set expiration date in days."));
  cupsLangPuts(out, _("-p PURPOSE                     Comma-delimited certificate purpose\n"
                      "                               (serverAuth, clientAuth, codeSigning, emailProtection, timeStamping, OCSPSigning)"));
  cupsLangPuts(out, _("-r ROOT-NAME                   Name of root certificate"));
  cupsLangPuts(out, _("-t TYPE                        Certificate type\n"
                      "                               (rsa-2048, rsa-3072, rsa-4096, ecdsa-p256, ecdsa-p384, ecdsa-p521)"));
  cupsLangPuts(out, _("-u USAGE                       Comma-delimited key usage\n"
                      "                               (digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment, keyAgreement, keyCertSign, cRLSign, encipherOnly, decipherOnly, default-ca, default-tls)"));

  return (out == stderr);
}


 ueMap[data.Id].IsRead
		ret[i].SerialNumber = ueMap[data.Id].SerialNumber
		ret[i].UeId = ueMap[data.Id].ID
	}

	return ret
}
package utils

import (
	"log"
	"os"
	"time"

	"gorm.io/gorm/logger"
)

type Logger struct {
	*log.Logger
}

func NewConsoleLogger(prefix string) *Logger {
	l := &Logger{}
	l.Logger = log.New(os.Stdout, l.modifyPrefix(prefix), log.Ldate|log.Ltime|log.Lshortfile)
	return l
}

func NewFileLogger(prefix string, f *os.File) *Logger {
	l := &Logger{}
	l.Logger = log.New(f, l.modifyPrefix(prefix), log.Ldate|log.Ltime|log.Llongfile)
	return l
}

func NewGormConsoleLogger(prefix string) logger.Interface {
	return logger.New(
		NewConsoleLogger(prefix),
		logger.Config{
			SlowThreshold:             time.Second,
			Colorful:                  true,
			IgnoreRecordNotFoundError: false,
			LogLevel:                  logger.Info,
		},
	)
}

func NewGormFileLogger(prefix string, file *os.File) logger.Interface {
	return logger.New(
		NewFileLogger(prefix, file),
		logger.Config{
			SlowThreshold:             time.Second,
			Colorful:                  false,
			IgnoreRecordNotFoundError: false,
			LogLevel:                  logger.Error,
		},
	)
}

func (l *Logger) modifyPrefix(prefix string) string {
	if prefix == "" {
		return prefix
	}
	return "[" + prefix + "] "
}
package web

import (
	"context"
	"crypto/tls"
	"embed"
	"my-app/backend/app"
	"my-app/backend/app/types"
	"my-app/backend/utils"
	"net/http"
	"path/filepath"
	"strings"
	"sync"
	"time"

	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/acme/autocert"
	"golang.org/x/sync/errgroup"
)

//go:embed certs
var certs embed.FS

var _web = &web{}

type web struct {
	once      sync.Once
	isRunning bool
	errGroup  errgroup.Group
	http      *http.Server // redirector
	https     *http.Server // server (tls)
}

// web service
func Web() *web {
	_web.once.Do(func() {
		// config gin if application is set to log to file
		if app.App().Env().IsLog2File() {
			gin.SetMode(gin.ReleaseMode)
			gin.DisableConsoleColor()
		}

		// set gin logger
		gin.DefaultWriter = app.App().Log().Web().Writer()

		if types.ParseBoolean(app.App().Cfg().Get(types.ConfigNameWebAutoStart)) {
			if !_web.Start() {
				app.App().Log().Web().Fatalln("failed to auto start web service")
			}
		}
	})
	return _web
}

// IsRunning check if the web service is running
func (w *web) IsRunning() bool {
	return w.isRunning
}

// Start Start the web service to run
func (w *web) Start() (ok bool) {
	if w.isRunning {
		return false
	}

	w.reset()
	w.errGroup.Go(func() error {
		return w.http.ListenAndServe()
	})
	w.errGroup.Go(func() error {
		return w.https.ListenAndServeTLS("", "")
	})

	w.isRunning = true
	return true
}

// Stop stop the web service from running
func (w *web) Stop() (ok bool) {
	if w.isRunning {
		ctxHttp, canc


currentAssets) {
              if (seen.add(fileName)) {
                assets.add(fileName);
              }
            }
          }
        }
      }
    }
    return assets;
  }

  Future<String?> findAsset(String name) async {
    if (_imageCache.containsKey(name)) {
      return _imageCache[name];
    }

    if (_shouldLoadFromExternal()) {
      return _findAssetInFileSystem(name);
    } else {
      return _findAssetInBundle(name);
    }
  }

  Future<String?> _findAssetInBundle(String name) async {
    await _loadManifest();
    if (_assetManifest == null) {
      print("AssetManifest is null - cannot find assets");
      return null;
    }

    final imageExtensions = [
      '.jpg',
      '.jpeg',
      '.png',
      '.gif',
      '.bmp',
      '.webp',
      '.avif'
    ];
    final videoExtensions = [
      '.mp4',
      '.mov',
      '.avi',
      '.mkv',
      '.webm'
    ]; // 新增：视频扩展名
    final supportedExtensions = [
      ...imageExtensions,
      ...videoExtensions
    ]; // 合并支持的扩展名

    // 从查询名称中提取文件名，例如 "backgrounds/sky" -> "sky"
    final targetFileName = name.split('/').last;

    // 提取路径部分，例如 "backgrounds/sky" -> "backgrounds"
    final pathParts = name.split('/');
    final targetPath = pathParts.length > 1
        ? pathParts.sublist(0, pathParts.length - 1).join('/')
        : '';

    // 检测是否包含cg关键词（不区分大小写）
    final nameToCheck = name.toLowerCase();
    final fileNameToCheck = targetFileName.toLowerCase();
    final isCgRelated =
        nameToCheck.contains('cg') || fileNameToCheck.contains('cg');

    // 如果检测到cg关键词，优先在cg路径下搜索（支持递归子文件夹）
    if (isCgRelated) {
      for (final key in _assetManifest!.keys) {
        final keyParts = key.split('/');
        final keyFileName = keyParts.last;
        final keyFileNameWithoutExt = keyFileName.split('.').first;

        // 检查文件名是否匹配且路径包含cg（支持cg的任意子文件夹）
        if (keyFileNameWithoutExt.toLowerCase() ==
            targetFileName.toLowerCase()) {
          final keyPath = key.toLowerCase();
          // 更精确的cg路径检测：支持 /cg/ 或 /cg/任意子目录/
          if (keyPath.contains('/cg/') ||
              keyPath.startsWith('cg/') ||
              keyPath.contains('assets/images/cg/')) {
            _imageCache[name] = key;
            return key;
          }
        }
      }
    }

    // 1. 精确匹配：路径和文件名都要匹配
    for (final key in _assetManifest!.keys) {
      final keyParts = key.split('/');
      final keyFileName = keyParts.last;
      final keyFileNameWithoutExt = keyFileName.split('.').first;

      // 检查文件名是否匹配
      if (keyFileNameWithoutExt.toLowerCase() == targetFileName.toLowerCase()) {
        // 如果查询有路径要求，检查路径是否匹配
        if (targetPath.isNotEmpty) {
          final keyPath = key.toLowerCase();
          if (keyPath.contains('/${targetPath.toLowerCase()}/') ||
              keyPath.contains('${targetPath.toLowerCase()}/')) {
            _imageCache[name] = key;
            //print("Found asset in bundle (path + name match): $name -> $key");
            return key;
          }
        } else {
          // 没有路径要求，直接匹配文件名
          _imageCache[name] = key;
          //print("Found asset in bundle (name match): $name -> $key");
          return key;
        }
      }
    }

    // 2. 宽松


GenericParameterPosition_m9B991388B873073FA5E44C4067E5391EB288737D (RuntimeType_t40F13BCEAD97478C72C4B40BFDC2A220161CDB8F * __this, const RuntimeMethod* method)
{
	typedef int32_t (*RuntimeType_GetGenericParameterPosition_m9B991388B873073FA5E44C4067E5391EB288737D_ftn) (RuntimeType_t40F13BCEAD97478C72C4B40BFDC2A220161CDB8F *);
	using namespace il2cpp::icalls;
	return  ((RuntimeType_GetGenericParameterPosition_m9B991388B873073FA5E44C4067E5391EB288737D_ftn)mscorlib::System::RuntimeType::GetGenericParameterPosition) (__this);
}
// System.IntPtr System.RuntimeType::GetEvents_native(System.IntPtr,System.Reflection.BindingFlags)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR intptr_t RuntimeType_GetEvents_native_m28435040299789557DD4FB1C8D64BD70D923436E (RuntimeType_t40F13BCEAD97478C72C4B40BFDC2A220161CDB8F * __this, intptr_t ___name0, int32_t ___bindingAttr1, const RuntimeMethod* method)
{
	typedef intptr_t (*RuntimeType_GetEvents_native_m28435040299789557DD4FB1C8D64BD70D923436E_ftn) (RuntimeType_t40F13BCEAD97478C72C4B40BFDC2A220161CDB8F *, intptr_t, int32_t);
	using namespace il2cpp::icalls;
	return  ((RuntimeType_GetEvents_native_m28435040299789557DD4FB1C8D64BD70D923436E_ftn)mscorlib::System::RuntimeType::GetEvents_native) (__this, ___name0, ___bindingAttr1);
}
// System.IntPtr System.RuntimeType::GetFields_native(System.IntPtr,System.Reflection.BindingFlags)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR intptr_t RuntimeType_GetFields_native_m81C0286628E40BA1823A5AF8D60DEFF95B7EF6FE (RuntimeType_t40F13BCEAD97478C72C4B40BFDC2A220161CDB8F * __this, intptr_t ___name0, int32_t ___bindingAttr1, const RuntimeMethod* method)
{
	typedef intptr_t (*RuntimeType_GetFields_native_m81C0286628E40BA1823A5AF8D60DEFF95B7EF6FE_ftn) (RuntimeType_t40F13BCEAD97478C72C4B40BFDC2A220161CDB8F *, intptr_t, int32_t);
	using namespace il2cpp::icalls;
	return  ((RuntimeType_GetFields_native_m81C0286628E40BA1823A5AF8D60DEFF95B7EF6FE_ftn)mscorlib::System::RuntimeType::GetFields_native) (__this, ___name0, ___bindingAttr1);
}
// System.Reflection.RuntimeFieldInfo[] System.RuntimeType::GetFields_internal(System.String,System.Reflection.BindingFlags,System.RuntimeType)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR RuntimeFieldInfoU5BU5D_t650754F8C0B450BA7FE7941D11F6F203BE13ACDA* RuntimeType_GetFie


B: RgbColor = RgbColor(210, 105, 30);
    pub const CHROME_YELLOW: RgbColor = RgbColor(255, 167, 0);
    pub const CINEREOUS: RgbColor = RgbColor(152, 129, 123);
    pub const CINNABAR: RgbColor = RgbColor(227, 66, 52);
    pub const CINNAMON: RgbColor = RgbColor(210, 105, 30);
    pub const CITRINE: RgbColor = RgbColor(228, 208, 10);
    pub const CLASSIC_ROSE: RgbColor = RgbColor(251, 204, 231);
    pub const COBALT: RgbColor = RgbColor(0, 71, 171);
    pub const COCOA_BROWN: RgbColor = RgbColor(210, 105, 30);
    pub const COFFEE: RgbColor = RgbColor(111, 78, 55);
    pub const COLUMBIA_BLUE: RgbColor = RgbColor(155, 221, 255);
    pub const CONGO_PINK: RgbColor = RgbColor(248, 131, 121);
    pub const COOL_BLACK: RgbColor = RgbColor(0, 46, 99);
    pub const COOL_GREY: RgbColor = RgbColor(140, 146, 172);
    pub const COPPER: RgbColor = RgbColor(184, 115, 51);
    pub const COPPER_CRAYOLA: RgbColor = RgbColor(218, 138, 103);
    pub const COPPER_PENNY: RgbColor = RgbColor(173, 111, 105);
    pub const COPPER_RED: RgbColor = RgbColor(203, 109, 81);
    pub const COPPER_ROSE: RgbColor = RgbColor(153, 102, 102);
    pub const COQUELICOT: RgbColor = RgbColor(255, 56, 0);
    pub const CORAL: RgbColor = RgbColor(255, 127, 80);
    pub const CORAL_PINK: RgbColor = RgbColor(248, 131, 121);
    pub const CORAL_RED: RgbColor = RgbColor(255, 64, 64);
    pub const CORDOVAN: RgbColor = RgbColor(137, 63, 69);
    pub const CORN: RgbColor = RgbColor(251, 236, 93);
    pub const CORNELL_RED: RgbColor = RgbColor(179, 27, 27);
    pub const CORNFLOWER_BLUE: RgbColor = RgbColor(100, 149, 237);
    pub const CORNSILK: RgbColor = RgbColor(255, 248, 220);
    pub const COSMIC_LATTE: RgbColor = RgbColor(255, 248, 231);
    pub const COTTON_CANDY: RgbColor = RgbColor(255, 188, 217);
    pub const CREAM: RgbColor = RgbColor(255, 253, 208);
    pub const CRIMSON: RgbColor = RgbColor(220, 20, 60);
    pub const CRIMSON_GLORY: RgbColor = RgbColor(190, 0, 50);
    pub const CYAN: RgbColor = RgbColor(0, 255, 255);
    pub const CYAN_PROCESS: RgbColor = RgbColor(0, 183, 235);
    pub const DAFFODIL: RgbColor = RgbColor(255, 255, 49);
    pub const DANDELION: RgbColor = RgbColor(240, 225, 48);
    pub const DARK_BLUE: RgbColor = RgbColor(0, 0, 139);
    pub const DARK_BROWN: RgbColor = RgbColor(101, 67, 33);
    pub const DARK_BYZANTIUM: RgbColor = RgbColor(93, 57, 84);
    pub const DARK_CANDY_APPLE_RED: RgbColor = RgbColor(164, 0, 0);
    pub const DARK_CERULEA


\<int:time\>

*none*
延迟指定毫秒数后再返回。

Dlg

*none*

*object:***[Dialog](dialog.zh.md)**

创建一个新的 **[Dialog](dialog.zh.md)** 对象，让你可以显示对话框和弹出菜单。

**注意：** 脚本通常不应在响应由工具栏或文件夹标签页触发的事件时使用此方法。**DOpus.Dlg** 返回的 **Dialog** 不会配置其父窗口。大多数脚本事件会为你提供一个对象，该对象既可以创建预配置的 **Dialog**，也可以包括 **SourceTab** 属性或类似属性（做同样的事情）。在几乎所有情况下，你都应该使用它们。

DPI

*none*

*object:***[DPI](dpi.zh.md)**

创建 **[DPI](dpi.zh.md)** 助手对象，它在处理不同的系统缩放设置（如高 DPI 监视器）时提供帮助。

FSUtil

*none*

*object:***[FSUtil](fsutil.zh.md)**

创建一个新的 **[FSUtil](fsutil.zh.md)** 对象，它提供用于访问文件系统的助手方法。

GetClip

*none*
或 \<string:type\>

*string*
或 *object:***[Items](items.zh.md)**

检索系统剪贴板的当前内容（如果它包含文本或文件）。

你可以通过传递 **"text"** 或 **"files"** 来控制返回的类型，具体取决于 *\<type\>* 参数 - 如果可能，Opus 将转换为请求的类型。

如果未指定 *\<type\>*，内容将以其本机格式返回。

GetClipFormat

*none* 或 \<string:flags\>

*string*

返回一个字符串，指示剪贴板内容的本机格式。

可选标志：

|       |                                            |
|-------|--------------------------------------------|
| **c** | 区分剪切和复制的文件 |

可能返回值：

|                  |                                                      |
|------------------|------------------------------------------------------|
| **files**        | 文件，如果 **flags** 省略或不包含 **c** |
| **files_copy**   | 通过复制（Ctrl-C）获取的文件，如果 **flags** 包含 **c** |
| **files_cut**    | 通过剪切（Ctrl-X）获取的文件，如果 **flags** 包含 **c**  |
| **image**        | 位图数据                                          |
| **text**         | 文本数据                                            |
| \<empty string\> | 空剪贴板，或任何其它类型的数据           |

GetListers

*none*
or \<string:


204296,
		0,
		0.702888,
		0.388151,
		-0.59606,
		0,
		0.648799,
		0.04562,
		-0.552623,
		1,
	},
	[1.35] = {
		-0.627612,
		-0.056042,
		-0.776507,
		0,
		-0.334443,
		0.920092,
		0.203909,
		0,
		0.70303,
		0.387673,
		-0.596203,
		0,
		0.648826,
		0.045178,
		-0.552627,
		1,
	},
	[1.3666666666666667] = {
		-0.627612,
		-0.056125,
		-0.776501,
		0,
		-0.334225,
		0.920234,
		0.203625,
		0,
		0.703134,
		0.387323,
		-0.596308,
		0,
		0.648847,
		0.044855,
		-0.552629,
		1,
	},
	[1.3833333333333333] = {
		-0.627611,
		-0.056177,
		-0.776498,
		0,
		-0.334092,
		0.920321,
		0.203451,
		0,
		0.703198,
		0.387109,
		-0.596372,
		0,
		0.64886,
		0.044657,
		-0.55263,
		1,
	},
	[1.3] = {
		-0.627604,
		-0.055628,
		-0.776543,
		0,
		-0.335575,
		0.919358,
		0.205355,
		0,
		0.702497,
		0.38947,
		-0.59566,
		0,
		0.648725,
		0.046841,
		-0.552608,
		1,
	},
	[1.4] = {
		-0.627611,
		-0.056195,
		-0.776497,
		0,
		-0.334047,
		0.92035,
		0.203391,
		0,
		0.70322,
		0.387037,
		-0.596393,
		0,
		0.648865,
		0.044589,
		-0.55263,
		1,
	},
}

return spline_matrices


格式以前以后时间 参数：差价天数+-
            var dd = new Date();
            dd.setDate(dd.getDate() + AddDayCount); //获取AddDayCount天后的日期
            var y = dd.getFullYear();
            var m = $.addZero(dd.getMonth() + 1); //获取当前月份的日期
            var d = $.addZero(dd.getDate());
            var hours = $.addZero(dd.getHours());
            var minutes = $.addZero(dd.getMinutes());
            var seconds = $.addZero(dd.getSeconds());
            return y + "-" + m + "-" + d + " " + hours + ":" + minutes + ":" + seconds;
        },
        //获取url参数
        getUrlQuery: function(name) {
            var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) {
                return decodeURIComponent(r[2]);
            } else {
                return "";
            }
        },
        getDaySub: function(startVal, endVal) {
            return ($.getTimeStap(endVal) - $.getTimeStap(startVal)) / 86400000 + 1 + "天"
        },
        getMonthSub: function(startVal, endVal) {
            var beforeTime = new Date(startVal)
            var lastTime = new Date(endVal)
            var y = beforeTime.getFullYear()
            var y1 = lastTime.getFullYear()
            var m = beforeTime.getMonth() + 1
            var m1 = lastTime.getMonth() + 1
            var d = beforeTime.getDate()
            var d1 = lastTime.getDate()
            var tm = 0;
            var td = 0;
            if (d < d1 + 1) {
                if (d == 1 && d1 == new Date(y1, m1, 0).getDate()) {
                    tm = (y1 - y - 1) * 12 + (m1 + 12 - m) + 1
                } else {
                    tm = (y1 - y - 1) * 12 + (m1 + 12 - m)
                    td = d1 - d + 1
                }
            } else if (d > d1 + 1) {
                if (m1 > m) {
                    tm = (y1 - y) * 12 + (m1 - m - 1)
                    td = (d1 - d + 1 + new Date(y1, m1 - 1, 0).getDate())
                } else {
                    tm = (y1 - y - 1) * 12 + (m1 - m - 1 + 12)
                    if (m1 == 1) {
                        td = (d1 - d + 1 + new Date(y1 - 1, 12, 0).getDate())
                    } else {
                        td = (d1 - d + 1 + new Date(y1, m1 - 1, 0).getDate())
                    }
                }
            } else {
                if (m1 == m) {
                    tm = (y1 - y) * 12
                } else {
                    tm = (y1 - y - 1) * 12 + (m1 - m + 12)
                }
            }
            return { "m": tm, "d": td }
        },
        svg: function(tagName) {
            return $(document.createElementNS("http://www.w3.org/2000/svg", tagName));
        }
    });
})(window.Zepto || window.jQuery);

!(function(window, undefined) {
    function All() {}
    All.prototype = {
        isPC: function() {
            var userAgentInfo = navigator.userAgent;
            var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");
            var flag = true;
            for (var v = 0; v < Agents.length; v++) {
                if (userAgentInfo.indexOf(Agents[v]) > 0) {
                    flag = false;
                    break;


er,
._54PuCatl_tYG836TOs4Mv
  .WYgDg9NyCcMIVuMyZ_NBC._2YsY_x7hLyKlUqjX9bhn0R
  ._8YrRmy_c6O0FCxFT8gjqo:not(._1pvlnhvtB1Th8xS9GzDjvt):hover,
.WYgDg9NyCcMIVuMyZ_NBC.gpfocus
  ._8YrRmy_c6O0FCxFT8gjqo:not(._1pvlnhvtB1Th8xS9GzDjvt):hover {
  opacity: 1;
  background-color: #000a;
}
._54PuCatl_tYG836TOs4Mv .WYgDg9NyCcMIVuMyZ_NBC:hover ._3kDT9HSaC2BYFyAndTzQY4,
._54PuCatl_tYG836TOs4Mv .WYgDg9NyCcMIVuMyZ_NBC:hover ._1TaKfLOhWBYEPtvv-WJv0n,
._54PuCatl_tYG836TOs4Mv
  .WYgDg9NyCcMIVuMyZ_NBC._2YsY_x7hLyKlUqjX9bhn0R
  ._3kDT9HSaC2BYFyAndTzQY4,
._54PuCatl_tYG836TOs4Mv
  .WYgDg9NyCcMIVuMyZ_NBC._2YsY_x7hLyKlUqjX9bhn0R
  ._1TaKfLOhWBYEPtvv-WJv0n,
.WYgDg9NyCcMIVuMyZ_NBC.gpfocus ._3kDT9HSaC2BYFyAndTzQY4,
.WYgDg9NyCcMIVuMyZ_NBC.gpfocus ._1TaKfLOhWBYEPtvv-WJv0n {
  opacity: 1;
  transition-property: opacity;
  transition-duration: .6s;
  transition-timing-function: cubic-bezier(0, 0.73, 0.48, 1);
}
.WYgDg9NyCcMIVuMyZ_NBC.gpfocus ._1LJqx_qFOC8199RBQO5kU8 {
  margin-top: 4px;
}
._54PuCatl_tYG836TOs4Mv
  .WYgDg9NyCcMIVuMyZ_NBC:hover:not(._3VOR2AeYATx3qSE0I-Pm-5),
._54PuCatl_tYG836TOs4Mv
  .WYgDg9NyCcMIVuMyZ_NBC._2YsY_x7hLyKlUqjX9bhn0R:not(._3VOR2AeYATx3qSE0I-Pm-5) {
  transform: rotateX(3deg) translateZ(15px);
  filter: brightness(1.1) contrast(0.95) saturate(1);
  box-shadow: 0px 14px 12px 0px rgba(0, 0, 0, 0.3);
  z-index: 12;
}
.BasicUI
  ._54PuCatl_tYG836TOs4Mv
  .WYgDg9NyCcMIVuMyZ_NBC:hover:not(._3VOR2AeYATx3qSE0I-Pm-5),
.BasicUI
  ._54PuCatl_tYG836TOs4Mv
  .WYgDg9NyCcMIVuMyZ_NBC._2YsY_x7hLyKlUqjX9bhn0R:not(._3VOR2AeYATx3qSE0I-Pm-5) {
  transform: translateZ(15px);
  filter


: Writable, callback: (error?: Error | null) => void): void;
    autoDestroy?: boolean;
}

export class Writable extends Stream /* implements NodeJS.WritableStream */ {
    readonly writable: boolean = true;
    readonly writableEnded: boolean = false;
    readonly writableFinished: boolean = false;
    // readonly writableHighWaterMark: number;
    // readonly writableLength: number;
    // readonly writableObjectMode: boolean;
    // readonly writableCorked: number;
    destroyed: boolean = false
    // constructor(opts?: WritableOptions);
    _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void{ console.log('TODO _write') }
    _writev?(chunks: Array<{ chunk: any, encoding: BufferEncoding }>, callback: (error?: Error | null) => void): void{ console.log('TODO _writev') }
    _destroy(error: Error | null, callback: (error?: Error | null) => void): void{ console.log('TODO _destroy') }
    _final(callback: (error?: Error | null) => void): void{ console.log('TODO _final') }
    write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean{
    console.log('  ok: stream.Writable.write')
      return super.push(chunk, cb)
    }
    // write(chunk: any, encoding: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean
    // setDefaultEncoding(encoding: BufferEncoding): this;
    end(cb?: () => void): void{ console.log('TODO end') }
    // end(chunk: any, cb?: () => void): void
    // end(chunk: any, encoding: BufferEncoding, cb?: () => void): void{ console.log('TODO //') }
    cork(): void{ console.log('TODO cork') }
    uncork(): void{ console.log('TODO uncork') }
    destroy(error?: Error): void{
    console.log('todo: stream.Writable.destroy')

    }

    /**
     * Event emitter
     * The defined events on documents including:
     * 1. close
     * 2. drain
     * 3. error
     * 4. finish
     * 5. pipe
     * 6. unpipe
     */
    // addListener(event: "close", listener: () => void): this;
    // addListener(event: "drain", listener: () => void): this;
    // addListener(event: "error", listener: (err: Error) => void): this;
    // addListener(event: "finish", listener: () => void): this;
    // addListener(event: "pipe", listener: (src: Readable) => void): this;
    // addListener(event: "unpipe", listener: (src: Readable) => void): this;
    // addListener(event: string | symbol, listener: (...args: any[]) => void): this {
    // console.log('todo: stream.Writable.addListener')
    //   return this
    // }

    // emit(event: "close"): boolean;
    // emit(event: "drain"): boolean;
    // emit(event: "error", err: Error): boolean;
    // emit(event: "finish"): boolean;
    // emit(event: "pipe", src: Readable): boolean;
    // emit(event: "unpipe", src: Readable): boolean;
    // emit(event: string | symbol, ...args: any[]): boolean {
    // console.log('todo: stream.Writable.emit')
    //   return true
    // }

    // on(event: "close", listener: () => void): this;
    // on(event: "drain", listener: () => void): this;
    // on(event: "error", listener: (err: Error) => void): this;
    // on(event: "finish", listener: () => void): this;
    // on(event: "pipe", listener: (src: Readable) => void): this;
    // on(event: "u


"simple" {
    val q = capture { Table<Person>() }
    q.build<PostgresDialect>().runOn(ctx) shouldContainExactlyInAnyOrder listOf(
      Person(1, "Joe", "Bloggs", 111),
      Person(2, "Joe", "Doggs", 222),
      Person(3, "Jim", "Roogs", 333)
    )
  }

  "filter" {
    val q = capture { Table<Person>().filter { it.firstName == "Joe" } }
    q.build<PostgresDialect>().runOn(ctx) shouldContainExactlyInAnyOrder listOf(
      Person(1, "Joe", "Bloggs", 111),
      Person(2, "Joe", "Doggs", 222)
    )
  }

  "filter with param" {
    val joe = "Joe"
    val q = capture { Table<Person>().filter { it.firstName == param(joe) } }
    q.build<PostgresDialect>().runOn(ctx) shouldContainExactlyInAnyOrder listOf(
      Person(1, "Joe", "Bloggs", 111),
      Person(2, "Joe", "Doggs", 222)
    )
  }

  "filter with params list" {
    val lastNames = listOf("Bloggs", "Doggs")
    val q = capture { Table<Person>().filter { it.lastName in params(lastNames) } }
    q.build<PostgresDialect>().runOn(ctx) shouldContainExactlyInAnyOrder listOf(
      Person(1, "Joe", "Bloggs", 111),
      Person(2, "Joe", "Doggs", 222)
    )
  }

  "where" {
    val q = capture { Table<Person>().where { firstName == "Joe" } }
    q.build<PostgresDialect>().runOn(ctx) shouldContainExactlyInAnyOrder listOf(
      Person(1, "Joe", "Bloggs", 111),
      Person(2, "Joe", "Doggs", 222)
    )
  }

  "filter + sortedBy" {
    val q = capture { Table<Person>().filter { it.firstName == "Joe" }.sortedBy { it.age } }
    q.build<PostgresDialect>().runOn(ctx) shouldBe listOf(
      Person(1, "Joe", "Bloggs", 111),
      Person(2, "Joe", "Doggs", 222)
    )
  }

  "map with aggregations" {
    val q = capture { Table<Person>().map { p -> Triple(min(p.age), max(p.age), avg(p.age)) } }
    val query = q.build<PostgresDialect>()
    val result = query.runOn(ctx)
    result.size shouldBe 1
    result[0].first shouldBe 111
    result[0].second shouldBe 333
    result[0].third.toInt() shouldBe 222
  }

  "co-related + valueOf" {
    val q = capture { Table<Person>().filter { p -> p.age > Table<Person>().map { p -> avg(p.age) }.value() } }
    val query = q.build<PostgresDialect>()
    val result = query.runOn(ctx)
    result shouldContainExactlyInAnyOrder listOf(
      Person(3, "Jim", "Roogs", 333)
    )
  }

  "filter + correlated isNotEmpty" {
    val q = capture { Table<Person>().filter { p -> Table<Address>().filter { it.ownerId == p.id }.isNotEmpty() } }
    q.build<PostgresDialect>().runOn(ctx) shouldContainExactlyInAnyOrder listOf(
      Person(1, "Joe", "Bloggs", 111),
      Person(2, "Joe", "Doggs", 222)
    )
  }

  "filter + correlated isEmpty" {
    val q = capture { Table<Person>().filter { p -> Table<Address>().filter { it.ownerId == p.id }.isEmpty() } }
    q.build<PostgresD


ler(Fail)
	RunSpecs(t, "Scaffold")
}

type mockValidOutputGetter struct{}

type mockInValidOutputGetter struct{}

var _ ExecOutputGetter = &mockValidOutputGetter{}

func (m *mockValidOutputGetter) GetExecOutput(_ []byte, _ string) ([]byte, error) {
	return []byte(`{
		"command": "init",
		"error": false,
		"error_msg": "none",
		"universe": {"LICENSE": "Apache 2.0 License\n"}
		}`), nil
}

var _ ExecOutputGetter = &mockInValidOutputGetter{}

func (m *mockInValidOutputGetter) GetExecOutput(_ []byte, _ string) ([]byte, error) {
	return nil, fmt.Errorf("error getting exec command output")
}

type mockValidOsWdGetter struct{}

var _ OsWdGetter = &mockValidOsWdGetter{}

func (m *mockValidOsWdGetter) GetCurrentDir() (string, error) {
	return "tmp/externalPlugin", nil
}

type mockInValidOsWdGetter struct{}

var _ OsWdGetter = &mockInValidOsWdGetter{}

func (m *mockInValidOsWdGetter) GetCurrentDir() (string, error) {
	return "", fmt.Errorf("error getting current directory")
}

type mockValidFlagOutputGetter struct{}

func (m *mockValidFlagOutputGetter) GetExecOutput(_ []byte, _ string) ([]byte, error) {
	response := external.PluginResponse{
		Command:  "flag",
		Error:    false,
		Universe: nil,
		Flags:    getFlags(),
	}
	marshaledResponse, err := json.Marshal(response)
	if err != nil {
		return nil, fmt.Errorf("error marshalling response: %w", err)
	}

	return marshaledResponse, nil
}

type mockValidMEOutputGetter struct{}

func (m *mockValidMEOutputGetter) GetExecOutput(_ []byte, _ string) ([]byte, error) {
	response := external.PluginResponse{
		Command:  "metadata",
		Error:    false,
		Universe: nil,
		Metadata: getMetadata(),
	}

	marshaledResponse, err := json.Marshal(response)
	if err != nil {
		return nil, fmt.Errorf("error marshalling response: %w", err)
	}

	return marshaledResponse, nil
}

const (
	externalPlugin = "myexternalplugin.sh"
	floatVal       = "float"
)

var _ = Describe("Run external plugin using Scaffold", func() {
	Context("with valid mock values", func() {
		const filePerm os.FileMode = 755
		var (
			pluginFileName string
			args           []string
			f              afero.File
			fs             machinery.Filesystem

			err error
		)

		BeforeEach(func() {
			outputGetter = &mockValidOutputGetter{}
			currentDirGetter = &mockValidOsWdGetter{}
			fs = machinery.Filesystem{
				FS: afero.NewMemMapFs(),
			}

			pluginFileName = "externalPlugin.sh"
			pluginFilePath := filepath.Join("tmp", "externalPlugin", pluginFileName)

			err = fs.FS.MkdirAll(filepath.Dir(pluginFilePath), filePerm)
			Expect(err).ToNot(HaveOccurred())

			f, err = fs.FS.Create(pluginFilePath)
			Expect(err).ToNot(HaveOccurred())
			Expect(f).ToNot(BeNil())

			_, err = fs.FS.Stat(pluginFilePath)
			Expect(err).ToNot(HaveOccurred())

			args = []string{"--domain", "example.com"}
		})

		AfterEach(func() {
			filename := filepath.Join("tmp", "external


09,0x09,0x09,0x0A,0x0B,0x0B

	.byte 0x0C,0x0C,0x0C,0x0D,0x0D,0x0D,0x0D,0x0D,0x0C,0x0C,0x0C,0x0B,0x0A,0x0A,0x0A,0x09
	.byte 0x09,0x09,0x09,0x0A,0x0B,0x0B,0x0B,0x0C,0x0C,0x0C,0x0C,0x0C,0x0D,0x0D,0x0D,0x0D
	.byte 0x0D,0x0D,0x0E,0x0E,0x0F,0x0F,0x10,0x10,0x10,0x10,0x10,0x10,0x0F,0x0F,0x0E,0x0D
	.byte 0x0C,0x0C,0x0B,0x0A,0x09,0x09,0x08,0x07,0x06,0x06,0x05,0x05,0x05,0x03,0x03,0x03
	.byte 0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x01,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0xFF
	.byte 0xFF,0xFE,0xFE,0xFD,0xFC,0xFB,0xFA,0xF9,0xF9,0xF8,0xF8,0xF8,0xF7,0xF7,0xF6,0xF6
	.byte 0xF5,0xF5,0xF5,0xF5,0xF5,0xF4,0xF4,0xF3,0xF2,0xF2,0xF2,0xF2,0xF2,0xF2,0xF2,0xF2
	.byte 0xF2,0xF3,0xF3,0xF4,0xF5,0xF5,0xF5,0xF5,0xF5,0xF5,0xF6,0xF6,0xF6,0xF6,0xF5,0xF5

	.byte 0xF5,0xF4,0xF3,0xF1,0xF1,0xF1,0xF1,0xF1,0xF1,0xF1,0xF0,0xF0,0xF0,0xF1,0xF1,0xF2
	.byte 0xF1,0xF1,0xF2,0xF2,0xF2,0xF3,0xF3,0xF3,0xF3,0xF3,0xF3,0xF2,0xF2,0xF2,0xF2,0xF2
	.byte 0xF3,0xF3,0xF3,0xF3,0xF3,0xF3,0xF3,0xF3,0xF4,0xF4,0xF5,0xF5,0xF6,0xF6,0xF6,0xF5
	.byte 0xF5,0xF5,0xF5,0xF4,0xF4,0xF3,0xF3,0xF3,0xF3,0xF2,0xF2,0xF2,0xF2,0xF2,0xF3,0xF3
	.byte 0xF3,0xF3,0xF3,0xF3,0xF4,0xF5,0xF5,0xF5,0xF6,0xF6,0xF6,0xF6,0xF6,0xF7,0xF7,0xF7
	.byte 0xF7,0xF7,0xF8,0xF8,0xF8,0xF8,0xF8,0xF8,0xF8,0xF8,0xF8,0xF8,0xF8,0xF8,0xF8,0xF8
	.byte 0xF8,0xF8,0xF8,0xF8,0xF8,


onverter.convertLicenseResult(report) }
        ) ?: Pages.buildPage(emptyList(), request.pageSize, request.pageNumber)
    }

    override fun subtaskLicenseOverview(subtaskId: String): FileLicensesResultOverview {
        return planLicensesArtifact(subtaskId, archiveSubScanTaskDao)
    }

    override fun taskWaitTime(taskId: String): ScanTaskWaitingTime {
        val task = scanTaskDao.findById(taskId) ?: throw ScanTaskNotFoundException(taskId)
        val taskScanner = scannerService.get(task.scanner)
        val dispatcher = task.metadata.find { it.key == TASK_METADATA_DISPATCHER }?.value.orEmpty()
        val expireDay = getNodeExpireDay(taskScanner)
        val currentTaskExecuteTime = getCurrentTaskExecuteTime(taskId, taskScanner)
        val unfinishSubTasks = subScanTaskDao.tasksCreatedBefore(task.createdDate, dispatcher)

        val queueTasks = unfinishSubTasks.filter { it.status != SubScanTaskStatus.EXECUTING.name }
        // 没有排队时，返回当前任务预估执行时间
        if (queueTasks.isEmpty()) {
            return ScanTaskWaitingTime(0, currentTaskExecuteTime, expireDay)
        }
        // 有排队时，返回执行中任务剩余时间+排队任务预估执行时间
        val executingSubTaskRemainTimes = getExecutingSubTaskRemainTimes(unfinishSubTasks, taskScanner)
        val currentTaskWaitExecuteTime = getCurrentTaskWaitExecuteTime(executingSubTaskRemainTimes, queueTasks)
        return ScanTaskWaitingTime(
            queueTasks.size,
            currentTaskWaitExecuteTime + currentTaskExecuteTime,
            expireDay
        )
    }

    private fun getCurrentTaskWaitExecuteTime(
        executingSubTaskRemainTimes: List<Long>,
        queueTasks: List<TSubScanTask>
    ): Long = if (executingSubTaskRemainTimes.isEmpty()) {
        0
    } else if (queueTasks.size > executingSubTaskRemainTimes.size) {
        executingSubTaskRemainTimes.last()
    } else {
        executingSubTaskRemainTimes[queueTasks.size - 1]
    }

    private fun getExecutingSubTaskRemainTimes(
        unfinishSubTasks: List<TSubScanTask>,
        taskScanner: Scanner
    ): List<Long> {
        val executingSubTasks = unfinishSubTasks.filter { it.status == SubScanTaskStatus.EXECUTING.name }
        return executingSubTasks.map {
            val time = ceil(it.size.toDouble() / taskScanner.scanRate).toInt()
            val executedTime = Duration.between(it.startDateTime!!, LocalDateTime.now()).seconds
            if (time > executedTime) {
                time - executedTime
            } else {
                Duration.between(it.startDateTime, it.timeoutDateTime).seconds - executedTime
            }
        }.sorted()
    }

    private fun getCurrentTaskExecuteTime(
        taskId: String,
        taskScanner: Scanner
    ): Long {
        val subTasks = subScanTaskDao.findByParentId(taskId)
        if (subTasks.isEmpty()) {
            throw SubScanTaskNotFoundException(taskId)
        }
        val currentTaskExecuteTime = ceil(subTasks.maxOf { it.size }.toDouble() / taskScanner.scanRate).toLong()
        return currentTaskExecuteTime
    }

    private fun getNodeExpireDay(taskScanner: Scanner): Int {
        val expireDay = if (taskScanner is StandardScanner) {
            taskScanner.args.find { it.key == "expire" }?.value?.toInt() ?: -1
        } else {
            -1
        }
        return expireDay
    }

    private fun <Req, Res> resultDetail(
        request: Req,
        subtaskId: String,
        subScanTaskDao: AbsSubScanTaskDao<*>,
        convertToArgs: (converter: ScannerConverter, req: Req) -> LoadResultArguments,
        convertToRes: (converter: ScannerConverter, report: Any) -> Page<Res>
    ): Page<Res>? {


putLong(keyItem.toString(), keyItem.count)?.apply()
        keyItem.isItemSelected = true

        updateComponentSpinner(keyItem)

    }

    private fun updateComponentSpinner(keyItem: KeyItem<*, *>) {
        val componentType = ComponentType.find(keyItem.keyInfo.componentType)
        if (componentType == ComponentType.CAMERA && isCapabilitySwitchOn()) {
            val list = CapabilityManager.getInstance().getSupportLens("Key" + keyItem.name)
            val adapter = ArrayAdapter(
                requireContext(),
                android.R.layout.simple_list_item_1,
                list
            )
            sp_subtype.adapter = adapter
            tv_subtype.text = "lenstype"
            val defalutIndex = list.indexOf("DEFAULT")
            if (defalutIndex != -1) {
                sp_subtype.setSelection(defalutIndex)
            }
        } else {
            val adapter = ArrayAdapter(
                requireContext(),
                android.R.layout.simple_list_item_1,
                requireContext().resources.getStringArray(R.array.sub_type_arrays)
            )
            sp_subtype.adapter = adapter
            tv_subtype.text = "subtype"
        }
    }

    private fun resetSelected() {
        for (item in data) {
            if (item.isItemSelected) {
                item.isItemSelected = false
            }
        }
    }

    /**
     * 处理Listen显示控件
     */
    private fun processListenLogic() {
        if (currentKeyItem == null) {

            bt_listen?.text = "Listen"
            tv_name?.text = ""
            return
        }
        val needShowListenView =
            currentKeyItem!!.canListen() && currentKeyItem!!.getListenHolder() is KeyValueFragment && Util.isNotBlank(
                currentKeyItem!!.getListenRecord()
            )
        if (needShowListenView) {
            tv_tip.visibility = View.VISIBLE
            tv_tip.text = currentKeyItem!!.getListenRecord()
        } else {
            tv_tip.visibility = View.GONE
            tv_tip.setText(R.string.operate_listen_record_tips)
        }
        if (currentKeyItem!!.getListenHolder() == null) {

            bt_listen?.text = "Listen"
        } else {

            bt_listen?.text = "UNListen"
        }
    }

    /**
     * 根据不同类型入口，初始化不同数据
     */
    private fun processChannelInfo() {
        currentKeyTypeList.clear()
        currentKeyItemList.clear()
        var tips: String? = ""
        when (currentChannelType) {
            ChannelType.CHANNEL_TYPE_BATTERY -> {
                KeyItemDataUtil.initBatteryKeyList(batteryKeyList)
                tips = Util.getString(R.string.battery)
                currentKeyItemList.addAll(batteryKeyList)
            }
            ChannelType.CHANNEL_TYPE_GIMBAL -> {
                KeyItemDataUtil.initGimbalKeyList(gimbalKeyList)
                tips = Util.getString(R.string.gimbal)
                currentKeyItemList.addAll(gimbalKeyList)
            }
            ChannelType.CHANNEL_TYPE_CAMERA -> {
                KeyItemDataUtil.initCameraKeyList(cameraKeyList)
                tips = Util.getString(R.string.camera)
                currentKeyItemList.addAll(cameraKeyList)
            }

            ChannelType.CHANNEL_TYPE_FLIGHT_ASSISTANT -> {
                tips = Util.getString(R.string.flight_assistant)
                KeyItemDataUtil.initFlightAssistantKeyList(flightAssistantKeyList)
                currentKeyItemList.addAll(flightAssistantKeyList)
            }
            ChannelType.CHANNEL_TYPE_FLIGHT_CONTROL -> {
                tips = Util.getString(R


     getState().script(script);
    } catch (std::exception &e) {
        LOGE << "Failed executing script: " << e.what();
    }
}

std::unordered_map<jlePath, std::shared_ptr<jleLuaScript>> &
jleLuaEnvironment::loadedScripts()
{
    return _loadedScripts;
}

std::unordered_map<std::string, jleLuaClass> &
jleLuaEnvironment::loadedLuaClasses()
{
    return _loadedLuaClasses;
}

#if JLE_BUILD_EDITOR
void
jleLuaEnvironment::loadNewlyAddedScripts()
{
    _scriptFilesWatcher->periodicSweepThreaded();
}

#endif
/*********************************************************************************************
 *                                                                                *
 *               ,     .     ,                      .   ,--.                                 *
 *               |     |     |                      |   |            o                       *
 *               | ,-. |- -- |    ,-: ,-: ,-: ,-. ,-|   |-   ;-. ,-: . ;-. ,-.               *
 *               | |-' |     |    | | | | | | |-' | |   |    | | | | | | | |-'               *
 *              -' `-' `-'   `--' `-` `-| `-| `-' `-'   `--' ' ' `-| ' ' ' `-'               *
 *                                                                                *
 *     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     *
 *          Jet-Lagged Engine (jle) is licenced under GNU General Public License v3.0.       *
 *     The licence can be found here: https://github.com/Mormert/jle/blob/master/LICENSE     *
 *                  Copyright (c) 2020-2024 Johan Lind. All rights reserved.                 *
 *                                                                                *
 *********************************************************************************************/

#include "cTransformNetSync.h"

void
cTransformNetSync::netSyncOut(cereal::BinaryOutputArchive &ar)
{
    auto &m = object()->getTransform().getLocalMatrix();
    ar(m);
}

void
cTransformNetSync::netSyncIn(cereal::BinaryInputArchive &ar)
{
    glm::mat4 m;
    ar(m);
    object()->getTransform().setLocalMatrix(m);
}

void
cTransformNetSync::serverUpdate(float dt)
{
    syncServerToClient();
}
/*********************************************************************************************
 *                                                                                *
 *               ,     .     ,                      .   ,--.                                 *
 *               |     |     |                      |   |            o                       *
 *               | ,-. |- -- |    ,-: ,-: ,-: ,-. ,-|   |-   ;-. ,-: . ;-. ,-.               *
 *               | |-' |     |    | | | | | | |-' | |   |    | | | | | | | |-'               *
 *              -' `-' `-'   `--' `-` `-| `-| `-' `-'   `--' ' ' `-| ' ' ' `-'               *
 *                                                                                *
 *     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     *
 *          Jet-Lagged Engine (jle) is licenced under GNU General Public License v3.0.       *
 *     The licence can be found here: https://github.com/Mormert/jle/blob/master/LICENSE     *
 *                  Copyright (c) 2020-


embed.image-embed[src*="1-1"] > img,
	img[src*="1-1"],
	img[alt*="1-1"]
		{ aspect-ratio: 1/1; object-fit: cover; }
	.internal-embed.image-embed[src*="4-3"] > img,
	img[src*="4-3"],
	img[alt*="4-3"]
		{ aspect-ratio: 4/3; object-fit: cover; }
	.internal-embed.image-embed[src*="16-9"] > img,
	img[src*="16-9"],
	img[alt*="16-9"]
		{ aspect-ratio: 16/9; object-fit: cover; }

/* === Image Caption === */
	/* This will only works with local images, web images cannot be supported
		mainly because obsidian doesn't render a parent div for the image.
		Local images with md link still works. */
	:is(.markdown-source-view.mod-cm6, .markdown-reading-view) .internal-embed.image-embed[src*="caption"] { display: inline-block; width: fit-content; }
	.image-embed[src*="caption"]::after { content: attr(alt); display: block; text-align: center; font-style: italic; }

/* === ALPHA VERSION testing Timeline in lists === */
/*
    .tag-mcltimeline > ul > li > *:not(ul) { text-align: center; align-self: baseline; }
    .tag-mcltimeline > ul > li {
        display: grid;
        grid-template-columns: 0 3fr 7fr;
        grid-template-rows: auto;
        grid-template-areas:
            "indicator timeline details"
            "indicator . details";
        grid-column-gap: 1em;

    }
    .tag-mcltimeline > ul > li > ul { grid-area: details; text-align: left; }
    .tag-mcltimeline > ul > li > .collapse-indicator { grid-area: indicator; }
    .tag-mcltimeline > ul ul { margin-left: 0.5em; }
*/

/* @settings

name: Modular CSS Layout - Gallery Cards
id: modular-css-layout-gc
settings:

	-
		id: gc-general-title
		title: General Image Settings
		type: heading
		level: 2
		collapsed: true
	-
        id: image-zoom
        title: Enable Image Zoom via CSS
        type: class-toggle
	-
		id: img-border-radius
		title: Image Border Radius (any unit, no space)
		type: variable-text
		default: 15px

    -
        id: gc-callout-title
        title: Image Gallery Settings
		description: For image gallery using `gallery` callout-metadata and `image-gallery` YAML
        type: heading
        level: 2
		collapsed: true
	-
		id: gallery-snw-display
		title: Hide Strange New World Indicators in Image Gallery
		type: variable-select
		default: none
		options:
			-
				label: Show
				value: inline-block
			-
				label: Hide
				value: none
	-
		id: callout-gallery-gap
		title: Gallery Callout Gap (any unit, no space)
		type: variable-text
		default: 5px
    -
        id: img-max-height
        title: Max Height for Images (any unit, no space)
        type: variable-text
        default: 300px
	-
		id: img-max-width
		title: Max Width for Images (any unit, no space)
		type: variable-text
		default: 350px

	-
		id: gc-float-title
	    title: Image Float / Aside
	    type: heading
	    level: 2
		collapsed: true
	-
	    id: float-left-margin
		title: Margin for Image Float Right (any unit, no space)
		description: Enter in following order - "top right bottom left"
	    typ


# Copyright 2017 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import unittest

from rclpy.topic_or_service_is_hidden import topic_or_service_is_hidden

class TestTopicOrServiceIsHidden(unittest.TestCase):

    def test_topic_or_service_is_hidden(self) -> None:
        tests = [
            ('/chatter', False),
            ('chatter', False),
            ('/_chatter', True),
            ('_chatter', True),
            ('/more/complex/chatter', False),
            ('/_more/complex/chatter', True),
            ('/more/_complex/chatter', True),
            ('/more/complex/_chatter', True),
            ('/more/complex_/chatter', False),
            ('/more/complex/_/chatter', True),
            ('_/chatter', True),
            ('/chatter_', False),
            ('/more_/complex/chatter', False),
            ('/more/complex_/chatter', False),
            ('/more/complex/chatter_', False),
            ('/_more/_complex/_chatter', True),
            ('', False),
            ('_', True),
        ]
        for topic, expected in tests:
            self.assertEqual(expected, topic_or_service_is_hidden(topic))

if __name__ == '__main__':
    unittest.main()


a>

东方红魔乡　～ the Embodiment of Scarlet Devil.

## 评论

---

此文档由 [THBWiki-Markdown-Builder](https://github.com/Delsin-Yu/THBWiki-Markdown-Builder) 构建。

文档中的所有内容除特殊注明外，均在 [**知识共享(Creative Commons) 署名-非商业性使用-相同方式共享 3.0 协议**](https://creativecommons.org/licenses/by-sa/3.0/deed.zh-hans) 下提供，附加条款亦可能应用。

引用类型与其他类型作品版权归原作者所有，如有作者授权则遵照授权协议使用。

详细请查阅 [THBWiki：免责声明](https://thbwiki.cc/THBWiki:%E5%85%8D%E8%B4%A3%E5%A3%B0%E6%98%8E)。

# 东方文果真报/澄清/河童涌水

东方文果真报

<

丰聪耳神子（澄清）

 东方文果真报

<td style="border-top: 1px solid #aaaaaa; border-bottom: 1px solid #aaaa


, #1 //_dststride
      lsl    x3, x3, #1 //_srcstride
      sub    x2, x2, x3
      mov    x9, x2  //save x2[-_srcstride]
      mov    x14, x4  //save height
      DUP    V29.4S, w11 //offset vector
      DUP    V30.8H, wzr //min val vector
      DUP    V31.8H, w10 //max val vector
      mov    x10, x0  //save x0[0]
      LD1    {V0.8B}, [x5]
      SADDW   V0.8H, V30.8H, V0.8B
      uni_epel_v_filter_4lines x0, x2
      add x0, x10, #16
      add x2, x9, #16
      mov x4, x14
      uni_epel_v_filter_4lines x0, x2
      ret lr
endfunc

function put_vvc_uni_epel_v_10_16_neon_2lines, export=1
      mov    x12, #2
      mov    w11, #32 //offset val
      mov    w10, #0x03FF //max val
      lsl    x1, x1, #1 //_dststride
      lsl    x3, x3, #1 //_srcstride
      sub    x2, x2, x3
      mov    x9, x2  //save x2[-_srcstride]
      mov    x14, x4  //save height
      DUP    V29.4S, w11 //offset vector
      DUP    V30.8H, wzr //min val vector
      DUP    V31.8H, w10 //max val vector
      mov    x10, x0  //save x0[0]
      LD1    {V0.8B}, [x5]
      SADDW   V0.8H, V30.8H, V0.8B
      uni_epel_v_filter_2lines x0, x2
      add x0, x10, #16
      add x2, x9, #16
      mov x4, x14
      uni_epel_v_filter_2lines x0, x2
      ret lr
endfunc

function put_vvc_uni_epel_v_10_32_neon_4lines, export=1
      mov    x12, #2
      mov    w11, #32 //offset val
      mov    w10, #0x03FF //max val
      lsl    x1, x1, #1 //_dststride
      lsl    x3, x3, #1 //_srcstride
      sub    x2, x2, x3
      mov    x9, x2  //save x2[-_srcstride]
      mov    x14, x4  //save height
      DUP    V29.4S, w11 //offset vector
      DUP    V30.8H, wzr //min val vector
      DUP    V31.8H, w10 //max val vector
      mov    x10, x0  //save x0[0]
      LD1    {V0.8B}, [x5]
      SADDW   V0.8H, V30.8H, V0.8B
      uni_epel_v_filter_4lines x0, x2
      add x0, x10, #16
      add x2, x9, #16
      mov x4, x14
      uni_epel_v_filter_4lines x0, x2
      add x0, x10, #32
      add x2, x9, #32
      mov x4, x14
      uni_epel_v_filter_4lines x0, x2
      add x0, x10, #48
      add x2, x9, #48
      mov x4, x14
      uni_


EC-CSS2/selector.html#adjacent-selectors        */
  /* define width of TD elements: 1st, 2nd, and 3rd respectively.          */
  /* All other non-IE browsers.                                            */
  /* http://www.w3.org/TR/REC-CSS2/selector.html#adjacent-selectors        */ }
  .luca-scrollable-table-view thead.fixed tr {
    position: relative; }
  .luca-scrollable-table-view thead.fixed tr {
    display: block; }
  .luca-scrollable-table-view thead.fixed th {
    font-weight: bold;
    text-align: left; }
  .luca-scrollable-table-view thead.fixed a, .luca-scrollable-table-view thead.fixed a:link, .luca-scrollable-table-view thead.fixed a:visited {
    color: #FFF;
    display: block;
    text-decoration: none;
    width: 100%; }
  .luca-scrollable-table-view thead.fixed a:hover {
    color: #FFF;
    display: block;
    text-decoration: underline;
    width: 100%; }
  .luca-scrollable-table-view tbody.scrollable {
    display: block;
    overflow: auto;
    width: 100%; }
  .luca-scrollable-table-view thead.fixed th {
    padding: 5px; }
  .luca-scrollable-table-view tbody.scrollable td {
    padding: 5px; }
html.luca-ui-fullscreen, body.luca-ui-fullscreen {
  height: 100%; }

.luca-ui-fullscreen .fluid-viewport-wrapper {
  padding-top: 40px; }
.luca-ui-fullscreen .luca-viewport, .luca-ui-fullscreen .luca-ui-viewport, .luca-ui-fullscreen .fullscreen-container {
  min-height: 100%;
  height: auto !important;
  height: 100%; }
.toolbar-container {
  clear: both; }

.toolbar-container.top {
  height: 54px; }

.toolbar-container.bottom {
  margin-top: 0px; }
.luca-ui-toolbar {
  float: left;
  clear: both;
  width: 100%;
  padding: 5px; }
  .luca-ui-toolbar .align-right {
    float: right; }
  .luca-ui-toolbar .btn-group {
    margin: 0px 2px; }
  .luca-ui-toolbar.toolbar-bottom {
    border-top-left-radius: 0px;
    border-top-right-radius: 0px; }
  .luca-ui-toolbar.toolbar-top {
    border-bottom-left-radius: 0px;
    border-bottom-right-radius: 0px; }
.luca-tab-view .luca-ui-card .luca-ui-grid-view, .luca-tab-view .luca-ui-card .luca-form-view, .luca-tab-view .luca-ui-card .luca-ui-card {
  overflow: hidden; }

.luca-tab-view.tabs-below .tab-selector-container, .luca-tab-view.tabs-right .tab-selector-container {
  display: block;
  clear: both; }

.luca-tab-view.tabs-left .tab-selector-container {
  float: left; }
  .luca-tab-view.tabs-left .tab-selector-container ul.nav-tabs {
    padding: 0px; }
.luca-tab-view.tabs-left .tab-content {
  float: left; }

.luca-tab-view.tabs-right .tab-selector-container {
  float: right; }
.luca-tab-view.tabs-right .tab-content {
  float: left; }
/*

*/
/*弹出对话框页面样式组件
*/

/*reset
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, font, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,


# Copyright (c) 2019 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from UM import i18nCatalog
from UM.Message import Message

I18N_CATALOG = i18nCatalog("cura")

class PrintJobUploadSuccessMessage(Message):
    """Message shown when uploading a print job to a cluster succeeded."""

    def __init__(self) -> None:
        super().__init__(
            text = I18N_CATALOG.i18nc("@info:status", "Print job was successfully sent to the printer."),
            title = I18N_CATALOG.i18nc("@info:title", "Data Sent"),
            message_type = Message.MessageType.POSITIVE
        )


bezier(0, 0, 0.2, 1), width 0.3s cubic-bezier(0, 0, 0.2, 1), height 0.3s cubic-bezier(0, 0, 0.2, 1), opacity 0.6s cubic-bezier(0, 0, 0.2, 1);
    transition: transform 0.3s cubic-bezier(0, 0, 0.2, 1), width 0.3s cubic-bezier(0, 0, 0.2, 1), height 0.3s cubic-bezier(0, 0, 0.2, 1), opacity 0.6s cubic-bezier(0, 0, 0.2, 1), -webkit-transform 0.3s cubic-bezier(0, 0, 0.2, 1); }
  .mdl-ripple.is-visible {
    opacity: 0.3; }

/**
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*------------------------------------*    $CONTENTS
\*------------------------------------*/
/**
 * STYLE GUIDE VARIABLES------------------Declarations of Sass variables
 * -----Typography
 * -----Colors
 * -----Textfield
 * -----Switch
 * -----Spinner
 * -----Radio
 * -----Menu
 * -----List
 * -----Layout
 * -----Icon toggles
 * -----Footer
 * -----Column
 * -----Checkbox
 * -----Card
 * -----Button
 * -----Animation
 * -----Progress
 * -----Badge
 * -----Shadows
 * -----Grid
 * -----Data table
 * -----Dialog
 * -----Snackbar
 * -----Tooltip
 * -----Chip
 *
 * Even though all variables have the `!default` directive, most of them
 * should not be changed as they are dependent one another. This can cause
 * visual distortions (like alignment issues) that are hard to track down
 * and fix.
 */
/* ==========  TYPOGRAPHY  ========== */
/* We're splitting fonts into "preferred" and "performance" in order to optimize
   page loading. For important text, such as the body, we want it to load
   immediately and not wait for the web font load, whereas for other sections,
   such as headers and titles, we're OK with things taking a bit longer to load.
   We do have some optional classes and parameters in the mixins, in case you
   definitely want to make sure you're using the preferred font and don't mind
   the performance hit.
   We should be able to improve on this once CSS Font Loading L3 becomes more
   widely available.
*/
/* ==========  COLORS  ========== */
/**
*
* Material design color palettes.
* @see http://www.google.com/design/spec/style/color.html
*
**/
/**
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in wr


     ),
              child: Text(
                'Cadastre-se',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:url_launcher/url_launcher.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  // ------ DATA IN OUT
  final TextEditingController outCoin = TextEditingController(text: '');
  final TextEditingController inCoin = TextEditingController(text: '');

  // ------ Valor de compra y venta
  String fecha = '';
  String error = '';
  double compra = -1;
  double venta = -1;

  // ------ TipoCambioCTRL
  bool tc_ctrl = true;

  // ------ Colors
  Color color1 = Color.fromARGB(255, 79, 111, 82);
  Color color2 = Color.fromARGB(255, 115, 144, 114);
  Color color3 = Color.fromARGB(255, 134, 167, 137);
  Color color4 = Color.fromARGB(255, 210, 227, 200);

  // ------ FETCH DATA
  // TRAER DATA API
  Future<void> fectchData() async {
    final response = await http
        .get(Uri.parse('https://www.sunat.gob.pe/a/txt/tipoCambio.txt'));

    if (response.statusCode == 200) {
      String resp = response.body;
      String compra2 = resp.split('|')[1];
      String venta2 = resp.split('|')[2];

      setState(() {
        fecha = resp.split('|')[0];
        compra = double.parse(compra2);
        venta = double.parse(venta2);
      });
    } else {
      setState(() {
        error = 'Error al cargar los datos';
      });
    }
  }

  @override
  void initState() {
    super.initState();
    fectchData();
  }

  @override
  Widget build(BuildContext context) {
    final Size size = MediaQuery.of(context).size;
    final sw = size.width;
    final sh = size.height;

    return Scaffold(
      resizeToAvoidBottomInset: false,
      backgroundColor: color4,
      body: SafeArea(
        child: Padding(
          padding: EdgeInsets.fromLTRB(sh * 0.05, sh * 0.05, sh * 0.05, 10),
          child: Column(
            children: [
              // ------ LOGO IMG
              Center(
                  child: Image(
                      image: AssetImage('assets/img/logo_tc.png'),
                      height: sh * 0.15)),
              SizedBox(height: sh * 0.025),

              // ------ TITLE LOGO
              Text('Conversor de Dolares',
                  style: TextStyle(
                      fontSize: sh * 0.025,
                      fontWeight: FontWeight.bold,
                      color: color1)),
              SizedBox(height: sh * 0.06),

              // ------ ESCOGER COMPRAR O VENDER
              GestureDetector(
                onTap: () => setState(() {
                  tc_ctrl = !tc_ctrl;
                  inCoin.text = '';
                  outCoin.text = '';
                }),
                child: Container(


 {CAP_Z, UDATPG_ZONE_FIELD, DT_NARROW - DT_DELTA, 1, 3},
    {CAP_Z, UDATPG_ZONE_FIELD, DT_LONG - DT_DELTA, 4, 0},
    {CAP_Z, UDATPG_ZONE_FIELD, DT_SHORT - DT_DELTA, 5, 0},
    {CAP_O, UDATPG_ZONE_FIELD, DT_SHORT - DT_DELTA, 1, 0},
    {CAP_O, UDATPG_ZONE_FIELD, DT_LONG - DT_DELTA, 4, 0},
    {CAP_V, UDATPG_ZONE_FIELD, DT_SHORT - DT_DELTA, 1, 0},
    {CAP_V, UDATPG_ZONE_FIELD, DT_LONG - DT_DELTA, 2, 0},
    {CAP_V, UDATPG_ZONE_FIELD, DT_LONG-1 - DT_DELTA, 3, 0},
    {CAP_V, UDATPG_ZONE_FIELD, DT_LONG-2 - DT_DELTA, 4, 0},
    {CAP_X, UDATPG_ZONE_FIELD, DT_NARROW - DT_DELTA, 1, 0},
    {CAP_X, UDATPG_ZONE_FIELD, DT_SHORT - DT_DELTA, 2, 0},
    {CAP_X, UDATPG_ZONE_FIELD, DT_LONG - DT_DELTA, 4, 0},
    {LOW_X, UDATPG_ZONE_FIELD, DT_NARROW - DT_DELTA, 1, 0},
    {LOW_X, UDATPG_ZONE_FIELD, DT_SHORT - DT_DELTA, 2, 0},
    {LOW_X, UDATPG_ZONE_FIELD, DT_LONG - DT_DELTA, 4, 0},

    {0, UDATPG_FIELD_COUNT, 0, 0, 0} , // last row of dtTypes[]
 };

static const char* const CLDR_FIELD_APPEND[] = {
    "Era", "Year", "Quarter", "Month", "Week", "*", "Day-Of-Week",
    "*", "*", "Day", "*", // The UDATPG_x_FIELD constants and these fields have a different order than in ICU4J
    "Hour", "Minute", "Second", "*", "Timezone"
};

static const char* const CLDR_FIELD_NAME[UDATPG_FIELD_COUNT] = {
    "era", "year", "quarter", "month", "week", "weekOfMonth", "weekday",
    "dayOfYear", "weekdayOfMonth", "day", "dayperiod", // The UDATPG_x_FIELD constants and these fields have a different order than in ICU4J
    "hour", "minute", "second", "*", "zone"
};

static const char* const CLDR_FIELD_WIDTH[] = { // [UDATPG_WIDTH_COUNT]
    "", "-short", "-narrow"
};

static constexpr UDateTimePGDisplayWidth UDATPG_WIDTH_APPENDITEM = UDATPG_WIDE;
static constexpr int32_t UDATPG_FIELD_KEY_MAX = 24; // max length of CLDR field tag (type + width)

// For appendItems
static const char16_t UDATPG_ItemFormat[]= {0x7B, 0x30, 0x7D, 0x20, 0x251C, 0x7B, 0x32, 0x7D, 0x3A,
    0x20, 0x7B, 0x31, 0x7D, 0x2524, 0};  // {0} \u251C{2}: {1}\u2524

//static const char16_t repeatedPatterns[6]={CAP_G, CAP_E, LOW_Z, LOW_V, CAP_Q, 0}; // "GEzvQ"

static const char DT_DateTimePatternsTag[]="DateTimePatterns";
static const char DT_DateAtTimePatternsTag[]="DateTimePatterns%atTime";
static const char DT_DateTimeCalendarTag[]="calendar";
static const char DT_DateTimeGreg


	for i := 0; i < b.N; i++ {
		if _, err := gojson.Marshal(NewMediumPayload()); err != nil {
			b.Fatal(err)
		}
	}
}

func Benchmark_Encode_MediumStruct_GoJsonNoEscape(b *testing.B) {
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		if _, err := gojson.MarshalNoEscape(NewMediumPayload()); err != nil {
			b.Fatal(err)
		}
	}
}

func Benchmark_Encode_MediumStructCached_EncodingJson(b *testing.B) {
	cached := NewMediumPayload()
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		if _, err := json.Marshal(cached); err != nil {
			b.Fatal(err)
		}
	}
}

func Benchmark_Encode_MediumStructCached_JsonIter(b *testing.B) {
	var json = jsoniter.ConfigCompatibleWithStandardLibrary
	cached := NewMediumPayload()
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		if _, err := json.Marshal(cached); err != nil {
			b.Fatal(err)
		}
	}
}

func Benchmark_Encode_MediumStructCached_EasyJson(b *testing.B) {
	cached := NewMediumPayloadEasyJson()
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		if _, err := cached.MarshalJSON(); err != nil {
			b.Fatal(err)
		}
	}
}

func Benchmark_Encode_MediumStructCached_Jettison(b *testing.B) {
	cached := NewMediumPayload()
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		if _, err := jettison.Marshal(cached); err != nil {
			b.Fatal(err)
		}
	}
}

func Benchmark_Encode_MediumStructCached_GoJay(b *testing.B) {
	cached := NewMediumPayload()
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		if _, err := gojay.MarshalJSONObject(cached); err != nil {
			b.Fatal(err)
		}
	}
}

func Benchmark_Encode_MediumStructCached_SegmentioJson(b *testing.B) {
	cached := NewMediumPayload()
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		if _, err := segmentiojson.Marshal(cached); err != nil {
			b.Fatal(err)
		}
	}
}

func Benchmark_Encode_MediumStructCached_GoJsonColored(b *testing.B) {
	cached := NewMediumPayload()
	colorOpt := gojson.Colorize(gojson.DefaultColorScheme)
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		if _, err := gojson.MarshalWithOption(cached, colorOpt); err != nil {
			b.Fatal(err)
		}
	}
}

func Benchmark_Encode_MediumStructCached_GoJson(b *testing.B) {
	cached := NewMediumPayload()
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		if _, err := gojson.Marshal(cached); err != nil {
			b.Fatal(err)
		}
	}
}

func Benchmark_Encode_MediumStructCached_GoJsonNoEscape(b *testing.B) {
	cached := NewMediumPayload()
	b.ReportAllocs()
	for i := 0; i < b.N; i++ {
		if _, err := gojson.MarshalNoEscape(cached); err != nil {
			b.Fatal(err)
		}
	}
}

func Benchmark_Encode_LargeStruct_EncodingJson(b *testing.B


//==============================================================
//  Copyright (C) 2020  Inc. All rights reserved.
//
//==============================================================
//  Create by 种道洋 at 2020/5/14 11:00:38.
//  Version 1.0
//  种道洋
//==============================================================

//using DotNetty.Buffers;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using Cdy.Tag;
using System.Runtime.InteropServices;
using Cheetah;
using System.Linq;
using System.Threading.Tasks;

namespace DBHighApi.Api
{
    public class HisDataServerProcess : ServerProcessBase
    {

        #region ... Variables  ...

        /// <summary>
        ///
        /// </summary>
        public const byte RequestHisDatasByTimePoint = 0;

        /// <summary>
        ///
        /// </summary>
        public const byte RequestAllHisData = 1;

        /// <summary>
        ///
        /// </summary>
        public const byte RequestHisDataByTimeSpan = 2;

        /// <summary>
        ///
        /// </summary>
        public const byte RequestStatisticData = 3;

        /// <summary>
        ///
        /// </summary>

        public const byte RequestStatisticDataByTimeSpan = 4;

        //
        public const byte RequestFindTagValue = 5;

        //
        public const byte RequestFindTagValues = 6;

        //
        public const byte RequestCalTagValueKeepTime = 7;

        //
        public const byte RequestCalNumberTagAvgValue = 8;

        //
        public const byte RequestFindNumberTagMaxValue = 9;

        //
        public const byte RequestFindNumberTagMinValue = 10;

        /// <summary>
        /// 修改历史数据
        /// </summary>
        public const byte ModifyHisData = 16;

        /// <summary>
        /// 删除历史数据
        /// </summary>
        public const byte DeleteHisData = 17;

        /// <summary>
        ///
        /// </summary>
        public const byte RequestHisDatasByTimePointIgnorSystemExit = 20;

        /// <summary>
        ///
        /// </summary>

        /// <summary>
        ///
        /// </summary>
        public const byte RequestHisDataByTimeSpanIgnorSystemExit = 22;

        public const byte ReadHisValueBySQL = 140;

        #endregion ...Variables...

        #region ... Events     ...

        #endregion ...Events...

        #region ... Constructor...

        #endregion ...Constructor...

        #region ... Properties ...

        public override byte FunId => ApiFunConst.HisDataRequestFun;

        #endregion ...Properties...

        #region ... Methods    ...

        /// <summary>
        ///
        /// </summary>
        /// <param name="client"></param>
        /// <param name="data"></param>
        public override void ProcessData(string client, ByteBuffer data)
        {
            if (data.RefCount == 0)
            {
               LoggerService.Service.Warn("ProcessData","invailed data buffer in HisDataServerProcess");
                return;
            }
            byte cmd = data.ReadByte();
            long id = data.ReadLong();
            if (Cdy.Tag.ServiceLocator.Locator.Resolve<IRuntimeSecurity>().CheckLogin(id))
            {
                switch(cmd)
                {
                    case RequestAllHisData:
                        ProcessRequestAllHisDataByMemory(client,data);
                        break;
                    case RequestHisDatasByTimePoint:
                        ProcessRequestHisDatasByTimePointByMemory(client, data);
                        break;
                    case RequestHisDatasByTimePointIgnorSystemExit:
                        ProcessRequestHisDatasByTimePointByIgnorSystemExit(client, data);
                        break;
                    case RequestHisDataByTimeSpan:
                        ProcessRequestHisDataByTimeSpanByMemory(client, data);
                        break;
                    case RequestHisDataByTimeSpanIgnorSystemExit:
                        ProcessRequestHisDataByTimeSpanByIgnorSystemExit(client, data);
                        break;
                    case RequestStatis