local DFGraphics = require('DFCommon.Graphics')
local DFFile = require('DFCommon.File')
local DFMoaiDebugger = require("DFMoai.Debugger")
local DFMath = require("DFCommon.Math")
local DFUtil = require('DFCommon.Util')
local Renderer = require('Renderer')
local Gui = require('UI.Gui')
local MiscUtil = require("MiscUtil")
local SoundManager = require('SoundManager')
local m = {}

function m.create()
    local Ob = MOAITransform.new()

    Ob.sDefaultRenderLayerName = 'UI'

--	local tHotkeyButtons = {}

    function Ob:init(sRenderLayerName,sLayoutFileName)
        self.uiWidth,self.uiHeight = 0,0
        if sLayoutFileName then
            self:processUIInfo(sLayoutFileName)
        end

        self.isUIElement = true
        if self.spriteList then
            self:loadUISpriteSheets(self.spriteList, self.xAlign or "left", self.yAlign or "top")
        end
        if self.spriteSheet then
            if not self.tUISpriteSheets then self.tUISpriteSheets = {} end
            if not self.tTextureToSpriteSheet then self.tTextureToSpriteSheet = {} end
            self:_addSpriteSheet(self.spriteSheet)
        end

        self.tAnimatingObjects = {}
        self.tTickElements = {}
		self.tHotkeyButtons = {}

        DFMoaiDebugger.dFileChanged:register(self.onFileChange,self)
    end

	function Ob:addHotkey(sKey, rButton)
--		if not self.tHotkeyButtons then
--			self.tHotkeyButtons = {}
--		end
        sKey = string.lower(sKey)

        local keyCode = -1

        if sKey == "esc" then
            keyCode = 27
        elseif sKey == "ret" or sKey == "ent" then
            keyCode = 13
        elseif sKey == "spc" then
            keyCode = 32
        else
            keyCode = string.byte(sKey)

            -- also store the uppercase version because hey why not
            local uppercaseKeyCode = string.byte(string.upper(sKey))
            self.tHotkeyButtons[uppercaseKeyCode] = rButton
        end

        self.tHotkeyButtons[keyCode] = rButton
    end

	function Ob:remHotkey(sKey)
		sKey = string.lower(sKey)

        local keyCode = -1

        if sKey == "esc" then
            keyCode = 27
        elseif sKey == "ret" or sKey == "ent" then
            keyCode = 13
        elseif sKey == "spc" then
            keyCode = 32
        else
            keyCode = string.byte(sKey)

            -- also store the uppercase version because hey why not
            local uppercaseKeyCode = string.byte(string.upper(sKey))
            self.tHotkeyButtons[uppercaseKeyCode] = nil
        end
		self.tHotkeyButtons[keyCode] = nil
	end

    -- returns true if key was handled
    function Ob:onKeyboard(key, bDown)
		if self.rSubmenu and self.rSubmenu.onKeyboard then
            return self.rSubmenu:onKeyboard(key, bDown)
        else
            if bDown and self.tHotkeyButtons[key] then
                self.tHotkeyButtons[key]:keyboardPressed()
                return true
            end
			if bDown and not self.tHotkeyButtons[key] then print('UIElement:onKeyboard('..key..') not found') end
        end
        return false
    end

    function Ob:setRenderLayer(sName)
        self.sRenderLayerName = sName
    end

    function Ob:getRenderL


eviceType::createAudioIODeviceType_CoreAudio()       { return nullptr; }
#endif

#if ! JUCE_IOS
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_iOSAudio()        { return nullptr; }
#endif

#if ! (JUCE_WINDOWS && JUCE_WASAPI)
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_WASAPI()          { return nullptr; }
#endif

#if ! (JUCE_WINDOWS && JUCE_DIRECTSOUND)
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_DirectSound()     { return nullptr; }
#endif

#if ! (JUCE_WINDOWS && JUCE_ASIO)
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_ASIO()            { return nullptr; }
#endif

#if ! (JUCE_LINUX && JUCE_ALSA)
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_ALSA()            { return nullptr; }
#endif

#if ! (JUCE_LINUX && JUCE_JACK)
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_JACK()            { return nullptr; }
#endif

#if ! JUCE_ANDROID
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_Android()         { return nullptr; }
#endif

#if ! (JUCE_ANDROID && JUCE_USE_ANDROID_OPENSLES)
AudioIODeviceType* AudioIODeviceType::createAudioIODeviceType_OpenSLES()        { return nullptr; }
#endif
/*
  ==============================================================================

   This file is part of the JUCE library.
   Copyright (c) 2013 - Raw Material Software Ltd.

   Permission is granted to use this software under the terms of either:
   a) the GPL v2 (or any later version)
   b) the Affero GPL v3

   Details of these licenses can be found at: www.gnu.org/licenses

   JUCE 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.

   ------------------------------------------------------------------------------

   To release a closed-source product which uses JUCE, commercial licenses are
   available: visit www.juce.com for more information.

  ==============================================================================
*/

#if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
 #define JUCE_DEBUG_XERRORS 1
#endif

Display* display = nullptr;
Window juce_messageWindowHandle = None;
XContext windowHandleXContext;   // This is referenced from Windowing.cpp

typedef bool (*WindowMessageReceiveCallback) (XEvent&);
WindowMessageReceiveCallback dispatchWindowMessage = nullptr;

typedef void (*SelectionRequestCallback) (XSelectionRequestEvent&);
SelectionRequestCallback handleSelectionRequest = nullptr;

//==============================================================================
ScopedXLock::ScopedXLock()       { XLockDisplay (display); }
ScopedXLock::~ScopedXLock()      { XUnlockDisplay (display); }

//==============================================================================
class InternalMessageQueue
{
public:
    InternalMessageQueue()
        : bytesInSocket (0),
          totalEventCount (0)
    {
        int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
        (void) ret; jassert (ret == 0);
    }

    ~InternalMessageQueue()
    {
        close (fd[0]);
        close (fd[1]);

        clearSingletonInstance();
    }

    //==============================================================================
    void postMessage (MessageManager::MessageBase* const msg)
    {
        const int maxBytesInSocketQueue = 128;

        ScopedLock sl (lock);
        queue.add (msg);

        if (bytesInSocket < maxBytesInSocketQueue)
        {
            ++bytesInSocket;

            ScopedUnlock ul (lock);
            const unsigned c


",
        "properties": {
            "question": {
                "type": "string",
                "description": "The original question about the files",
            },
            "list_of_files_or_folders": {
                "type": "string",
                "description": """Return a list of file or folder paths. Return an empty string '' if there is no file or folder specified.""",
            },
        },
        "required": ["question", "list_of_files_or_folders"],
    },
}

TOOL_FUNCTION = search_graph_store_azure


1)),L[2]||(L[2]=P);var O=n.range.apply(this,L);if(O=O.map(function(t,e){return parseFloat(t.toPrecision(12))}),s=n.scale.linear().domain(L.slice(0,2)).range("clockwise"===f.direction?[0,360]:[360,0]),u.layout.angularAxis.domain=s.domain(),u.layout.angularAxis.endPadding=M?E:0,"undefined"==typeof(t=n.select(this).select("svg.chart-root"))||t.empty()){var z=(new DOMParser).parseFromString("<svg xmlns='http://www.w3.org/2000/svg' class='chart-root'>' + '<g class='outer-group'>' + '<g class='chart-group'>' + '<circle class='background-circle'></circle>' + '<g class='geometry-group'></g>' + '<g class='radial axis-group'>' + '<circle class='outside-circle'></circle>' + '</g>' + '<g class='angular axis-group'></g>' + '<g class='guides-group'><line></line><circle r='0'></circle></g>' + '</g>' + '<g class='legend-group'></g>' + '<g class='tooltips-group'></g>' + '<g class='title-group'><text></text></g>' + '</g>' + '</svg>","application/xml"),I=this.appendChild(this.ownerDocument.importNode(z.documentElement,!0));t=n.select(I)}t.select(".guides-group").style({"pointer-events":"none"}),t.select(".angular.axis-group").style({"pointer-events":"none"}),t.select(".radial.axis-group").style({"pointer-events":"none"});var D,R=t.select(".chart-group"),F={fill:"none",stroke:f.tickColor},B={"font-size":f.font.size,"font-family":f.font.family,fill:f.font.color,"text-shadow":["-1px 0px","1px -1px","-1px 1px","1px 1px"].map(function(t,e){return" "+t+" 0 "+f.font.outlineColor}).join(",")};if(f.showLegend){D=t.select(".legend-group").attr({transform:"translate("+[x,f.margin.top]+")"}).style({display:"block"});var N=p.map(function(t,e){var r=o.util.cloneJson(t);return r.symbol="DotPlot"===t.geometry?t.dotType||"circle":"LinePlot"!=t.geometry?"square":"line",r.visibleInLegend="undefined"==typeof t.visibleInLegend||t.visibleInLegend,r.color="LinePlot"===t.geometry?t.strokeColor:t.color,r});o.Legend().config({data:p.map(function(t,e){return t.name||"Element"+e}),legendConfig:a({},o.Legend.defaultConfig().legendConfig,{container:D,elements:N,reverseOrder:f.legend.reverseOrder})})();var j=D.node().getBBox();x=Math.min(f.width-j.width-f.margin.left-f.margin.right,f.height-f.margin.top-f.margin.bottom)/2,x=Math.max(10,x),_=[f.margin.left+x,f.margin.top+x],r.range([0,x]),u.layout.radialAxis.domain=r.domain(),D.attr("transform","translate("+[_[0]+x,_[1]-x]+")")}else D=t.select(".legend-group").style({display:"none"});t.attr({width:f.width,height:f.height}).style({opacity:f.opacity}),R.attr("transform","translate("+_+")").style({cursor:"crosshair"});var V=[(f.width-(f.margin.left+f.mar


; overflow: hidden;
}
.twitter {
	background: url("/Areas/Centers/Themes/StandardDevCenter/Content/HeaderFooterSprite.png?v=635605659907833944") no-repeat -108px -3px; width: 14px; height: 14px; overflow: hidden;
}
.logo {
	background: url("/Areas/Centers/Themes/StandardDevCenter/Content/HeaderFooterSprite.png?v=635605659907833944") no-repeat -129px -3px; width: 68px; height: 14px; overflow: hidden;
}
.header-search-button {
	background: url("/Areas/Centers/Themes/StandardDevCenter/Content/HeaderFooterSprite.png?v=635605659907833944") no-repeat -204px -3px; width: 14px; height: 14px; overflow: hidden;
}
.rtl .header-search-button {
	background: url("/Areas/Centers/Themes/StandardDevCenter/Content/HeaderFooterSprite.png?v=635605659907833944") no-repeat -225px -3px; width: 14px; height: 14px; overflow: hidden;
}
.selectLocale a::after {
	background: url("/Areas/Centers/Themes/StandardDevCenter/Content/HeaderFooterSprite.png?v=635605659907833944") no-repeat -246px -3px; width: 24px; height: 24px; overflow: hidden;
}
.office::after {
	background: url("/Areas/Centers/Themes/StandardDevCenter/Content/HeaderFooterSprite.png?v=635605659907833944") no-repeat -277px -3px; width: 17px; height: 20px; overflow: hidden;
}
.windowsBlue::after {
	background: url("/Areas/Centers/Themes/StandardDevCenter/Content/HeaderFooterSprite.png?v=635605659907833944") no-repeat -301px -3px; width: 19px; height: 19px; overflow: hidden;
}
.visualStudio::after {
	background: url("/Areas/Centers/Themes/StandardDevCenter/Content/HeaderFooterSprite.png?v=635605659907833944") no-repeat -327px -3px; width: 19px; height: 19px; overflow: hidden;
}
.nokia::after {
	background: url("/Areas/Centers/Themes/StandardDevCenter/Content/HeaderFooterSprite.png?v=635605659907833944") no-repeat -353px -3px; width: 19px; height: 19px; overflow: hidden;
}
.row #grip {
	background: url("/Areas/Centers/Themes/StandardDevCenter/Content/HeaderFooterSprite.png?v=635605659907833944") no-repeat -379px -3px; width: 24px; height: 13px; overflow: hidden;
}
.vkOne {
	background: url("/Areas/Centers/Themes/StandardDevCenter/Content/HeaderFooterSprite.png?v=635605659907833944") no-repeat -410px -3px; width: 14px; height: 14px; overflow: hidden;
}
.rtl .navL2 > li.toggle > a::after {
	background: url("/Areas/Centers/Themes/StandardDevCenter/Content/HeaderFooterSprite.png?v=635605659907833944") no-repeat -431px -3px; width: 9px; height: 12px; overflow: hidden;
}
.navL2 > li.toggle > a::after {
	background: url("/Areas/Centers/Themes/StandardDevCenter/Content/HeaderFooterSprite.png?v=635605659907833944") no-repeat -447px -3px; width: 9px; height: 12px; overflow: hidden;
}
.navL1 > li.active.toggle > a::after {
	background: url("/Area


.clearnlp.lexicon.propbank.PBLib;
import edu.emory.clir.clearnlp.pos.POSLibEn;
import edu.emory.clir.clearnlp.pos.POSTagEn;
import edu.emory.clir.clearnlp.util.DSUtils;
import edu.emory.clir.clearnlp.util.Joiner;
import edu.emory.clir.clearnlp.util.PatternUtils;
import edu.emory.clir.clearnlp.util.Splitter;
import edu.emory.clir.clearnlp.util.StringUtils;
import edu.emory.clir.clearnlp.util.arc.AbstractArc;
import edu.emory.clir.clearnlp.util.arc.PBArc;
import edu.emory.clir.clearnlp.util.arc.SRLArc;
import edu.emory.clir.clearnlp.util.lang.ENUtils;

/**
 * Constituent to dependency converter for English.
 * @since 3.0.0
 * @author Jinho D. Choi ({@code jinho.choi@emory.edu})
 */
public class EnglishC2DConverter extends AbstractC2DConverter
{

	private final Set<String> S_NPADVMOD	= DSUtils.toHashSet(CTTagEn.C_NML, CTTagEn.C_NP, CTTagEn.C_QP);
	private final Set<String> S_ADVCL		= DSUtils.toHashSet(CTTagEn.C_S, CTTagEn.C_SBAR, CTTagEn.C_SINV);
	private final Set<String> S_NFMOD		= DSUtils.toHashSet(CTTagEn.C_NML, CTTagEn.C_NP, CTTagEn.C_WHNP);
	private final Set<String> S_CCOMP		= DSUtils.toHashSet(CTTagEn.C_S, CTTagEn.C_SQ, CTTagEn.C_SINV, CTTagEn.C_SBARQ);
	private final Set<String> S_META		= DSUtils.toHashSet(CTTagEn.C_EDITED, CTTagEn.C_EMBED, CTTagEn.C_LST, CTTagEn.C_META, CTLibEn.POS_CODE, CTTagEn.C_CAPTION, CTTagEn.C_CIT, CTTagEn.C_HEADING, CTTagEn.C_TITLE);
	private final Set<String> S_MARK		= DSUtils.toHashSet(CTLibEn.POS_IN, CTLibEn.POS_TO, CTLibEn.POS_DT);
	private final Set<String> S_POSS		= DSUtils.toHashSet(CTLibEn.POS_PRPS, CTLibEn.POS_WPS);
	private final Set<String> S_INTJ		= DSUtils.toHashSet(CTTagEn.C_INTJ, CTLibEn.POS_UH);
	private final Set<String> S_PRT 		= DSUtils.toHashSet(CTTagEn.C_PRT, CTLibEn.POS_RP);
	private final Set<String> S_NUM			= DSUtils.toHashSet(CTLibEn.POS_CD, CTTagEn.C_QP);
	private final Set<String> S_DET			= DSUtils.toHashSet(CTLibEn.POS_DT, CTLibEn.POS_WDT, CTLibEn.POS_WP);
	private final Set<String> S_AUX			= DSUtils.toHashSet(CTLibEn.POS_MD, CTLibEn.POS_TO);
//	private final Set<String> S_NN			= DSUtils.toHashSet(CTTagEn.C_NML, CTTagEn.C_NP);

	private final Set<String> S_ADJT_PHRASE	= DSUtils.toHashSet(CTTagEn.C_ADJP, CTTagEn.C_WHADJP);
	private final Set<String> S_NOUN_PHRASE	= D


e.Value);

            Pkcs9SigningTime signingTimeAttr = (Pkcs9SigningTime)signedAttrs[1].Values[0];
            Assert.Equal(
                new DateTimeOffset(2017, 10, 26, 1, 6, 25, TimeSpan.Zero),
                new DateTimeOffset(signingTimeAttr.SigningTime));

            Pkcs9MessageDigest messageDigestAttr = (Pkcs9MessageDigest)signedAttrs[2].Values[0];
            Assert.Equal(
                "07849DC26FCBB2F3BD5F57BDF214BAE374575F1BD4E6816482324799417CB379",
                messageDigestAttr.MessageDigest.ByteArrayToHex());

            Assert.IsType<Pkcs9AttributeObject>(signedAttrs[3].Values[0]);
#if !NET
            Assert.NotSame(signedAttrs[3].Oid, signedAttrs[3].Values[0].Oid);
#endif
            Assert.Equal(
                "306A300B060960864801650304012A300B0609608648016503040116300B0609" +
                    "608648016503040102300A06082A864886F70D0307300E06082A864886F70D03" +
                    "0202020080300D06082A864886F70D0302020140300706052B0E030207300D06" +
                    "082A864886F70D0302020128",
                signedAttrs[3].Values[0].RawData.ByteArrayToHex());

#if NET
            Assert.Equal(
                "B93E81D141B3C9F159AB0021910635DC72E8E860BE43C28E5D53243D6DC247B7" +
                    "D4F18C20195E80DEDCC75B29C43CE5047AD775B65BFC93589BD748B950C68BAD" +
                    "DF1A4673130302BBDA8667D5DDE5EA91ECCB13A9B4C04F1C4842FEB1697B7669" +
                    "C7692DD3BDAE13B5AA8EE3EB5679F3729D1DC4F2EB9DC89B7E8773F2F8C6108C" +
                    "05",
                signer.GetSignature().ByteArrayToHex());
#endif

            CryptographicAttributeObjectCollection unsignedAttrs = signer.UnsignedAttributes;
            Assert.Empty(unsignedAttrs);

            SignerInfoCollection counterSigners = signer.CounterSignerInfos;
            Assert.Empty(counterSigners);

            X509Certificate2 signerCertificate = signer.Certificate;
            Assert.Equal(
                "CN=localhost, OU=.NET Framework, O=Microsoft Corp., L=Redmond, S=Washington, C=US",
                signerCertificate.SubjectName.Name);

            // CheckHash always throws for certificate-based signers.
            Assert.Throws<CryptographicException>(() => signer.CheckHash());

            // At this time we cannot support the PSS parameters for this document.
            Assert.Throws<CryptographicException>(() => signer.CheckSignature(true));

            // Since there are no NoSignature signers the document CheckHash will succeed.
            // Assert.NotThrows
            cms.CheckHash();

            // Since at least one signer fails, the document signature will fail
            Assert.Throws<CryptographicException>(() => cms.CheckSignature(true));
        }

        [ConditionalFact(typeof(SignatureSupport), nameof(SignatureSupport.SupportsRsaSha1Signatures))]
        public static void ReadRsaPkcs1SimpleDocument()
        {
            SignedCms cms = new SignedCms();

            cms.Decode(SignedDocuments.RsaPkcs1OneSignerIssuerAndSerialNumber);

            Assert.Equal(1, cms.Version);

            ContentInfo contentInfo = cms.ContentInfo;

            Assert.Equal("1.2.840.113549.1.7.1", contentInfo.ContentType.Value);
            Assert.Equal("4D6963726F736F6


p */
	case *lyx.AExprIConst, *lyx.AExprSConst, *lyx.AExprBConst, *lyx.AExprNConst, *lyx.ParamRef:
		/* should not happen */
	case *lyx.AExprEmpty:
		/*skip*/
	case *lyx.Select:
		/* in engine v2 we skip subplans */
	case *lyx.FuncApplication:
		// there are several types of queries like DELETE FROM rel WHERE colref = func_application
		// and func_application is actually routable statement.
		// ANY(ARRAY(subselect)) if one type.

		if strings.ToLower(texpr.Name) == "any" {
			if len(texpr.Args) > 0 {
				// maybe we should consider not only first arg.
				// however, consider only it

				switch argexpr := texpr.Args[0].(type) {
				case *lyx.SubLink:

					// ignore all errors.
					return qr.planQueryV1(ctx, argexpr.SubSelect, meta)
				}
			}
		}
	case *lyx.AExprNot:
		// swallow
	default:
		return nil, fmt.Errorf("route by clause, unknown expr %T: %w", expr, rerrors.ErrComplexQuery)
	}
	return p, nil
}

// TODO : unit tests
func (qr *ProxyQrouter) analyzeSelectStmt(ctx context.Context, selectStmt lyx.Node, meta *rmeta.RoutingMetadataContext) error {

	switch s := selectStmt.(type) {
	case *lyx.Select:
		if clause := s.FromClause; clause != nil {
			// route `insert into rel select from` stmt
			if err := qr.analyzeFromClauseList(ctx, clause, meta); err != nil {
				return err
			}
		}

		if clause := s.Where; clause != nil {
			if err := qr.analyzeWhereClause(ctx, clause, meta); err != nil {
				return err
			}
		}

		if s.LArg != nil {
			if err := qr.analyzeSelectStmt(ctx, s.LArg, meta); err != nil {
				return err
			}
		}
		if s.RArg != nil {
			if err := qr.analyzeSelectStmt(ctx, s.RArg, meta); err != nil {
				return err
			}
		}

		return nil
	/* functional table expressions */
	case *lyx.FuncApplication:
		return nil
	/* SELECT * FROM VALUES() ... */
	case *lyx.ValueClause:
		/* random route */
		return nil
	}

	return rerrors.ErrComplexQuery
}

// TODO : unit tests
// analyzes from clause
func (qr *ProxyQrouter) analyzeFromNode(ctx context.Context, node lyx.FromClauseNode, meta *rmeta.RoutingMetadataContext) error {
	spqrlog.Zero.Debug().
		Type("node-type", node).
		Msg("analyzing from node")
	switch q := node.(type) {
	case *lyx.RangeVar:
		if err := qr.processRangeNode(ctx, meta, q); err != nil {
			return err
		}

	case *lyx.JoinExpr:
		if err := qr.analyzeFromNode(ctx, q.Rarg, meta); err != nil {
			return err
		}
		if err := qr.analyzeFromNode(ctx, q.Larg, meta); err != nil {
			return err
		}
	case *lyx.SubSelect:
		return qr.analyzeSelectStmt(ctx, q.Arg, meta)
	default:
		// other cases to consider
		// lateral join, natural, etc
	}

	return nil
}

func (qr *ProxyQrouter) processRangeNode(ctx context.Context, meta *rmeta.RoutingMetadataContext, q *lyx.RangeVar) error {
	qualName := rfqn.RelationFQNFromRangeRangeVar(q)

	// CTE, skip
	if meta.RFQNIsCTE(qualName


anguageResources.InviteCode_RoomRequired);
            }

            ChatRoom targetRoom = context.Repository.VerifyRoom(targetRoomName, mustBeOpen: false);

            // ensure the user could join the room if they wanted to
            callingUser.EnsureAllowed(targetRoom);

            if (String.IsNullOrEmpty(targetRoom.InviteCode))
            {
                context.Service.SetInviteCode(callingUser, targetRoom, RandomUtils.NextInviteCode());
            }

            ChatRoom callingRoom = context.Repository.GetRoomByName(callerContext.RoomName);
            context.NotificationService.PostNotification(callingRoom, callingUser, String.Format(LanguageResources.InviteCode_Success, targetRoomName, targetRoom.InviteCode));
        }
    }
}


er:GetMouse()
	m.Icon = ''
end)
end)

FESpamBricks.MouseButton1Click:connect(function()
	for i=1,20 do
wait(1)
        for _,v in pairs(game.Players.LocalPlayer.Backpack:GetChildren()) do
if v:IsA'Accoutrement' then
v.Parent=game.Players.LocalPlayer.Character
v.Parent = workspace.Terrain
end
end
for i,v in pairs(game.Players.LocalPlayer.Character:GetChildren()) do
if v:IsA'Accoutrement' then
for ape,hax in pairs(v.Handle:GetChildren()) do
hax:Destroy()
end
wait'.1'
v.Parent=game.Players.LocalPlayer.StarterGear
end
end
for _,v in pairs(game.Players.LocalPlayer.Character:GetChildren()) do
v:Destroy()
end
local prt=Instance.new("Model", workspace);
        Instance.new("Part", prt).Name="Torso";
        Instance.new("Part", prt).Name="Head";
        Instance.new("Humanoid", prt).Name="Humanoid";
        game.Players.LocalPlayer.Character=prt

repeat wait(1) until game.Players.LocalPlayer.Character:FindFirstChild'Head'
for lol,dad in pairs(game.Players.LocalPlayer.Backpack:GetChildren()) do
if dad:IsA'Accoutrement' then
dad.Parent = game.Players.LocalPlayer.StarterGear
end
end
for _,v in pairs(game.Players.LocalPlayer.Character:GetChildren()) do
v:Destroy()
end
local prt2=Instance.new("Model", workspace);
        Instance.new("Part", prt).Name="Torso";
        Instance.new("Part", prt).Name="Head";
        Instance.new("Humanoid", prt).Name="Humanoid";
        game.Players.LocalPlayer.Character=prt
end
end)

FEDab.MouseButton1Click:connect(function()
	Player = "LocalPlayer"
AnimationId = "248263260"
local Anim = Instance.new("Animation")
Anim.AnimationId = "rbxassetid://"..AnimationId
local k = game.Players[Player].Character.Humanoid:LoadAnimation(Anim)
k:Play() --Play the animation
k:AdjustSpeed(1) --Set '1' to any value you want to adjust the animation speed.
end)

FESpasm.MouseButton1Click:connect(function()
	Player = "LocalPlayer"
AnimationId = "33796059"
local Anim = Instance.new("Animation")
Anim.AnimationId = "rbxassetid://"..AnimationId
local k = game.Players[Player].Character.Humanoid:LoadAnimation(Anim)
k:Play() --Play the animation
k:AdjustSpeed(99) --Set '1' to any value you want to adjust the animation speed.
end)

--================--
--================--
--End Of Script :P--
--================--
--================--

--=======================--
--=======================--
--Snxwwy Made this GUI :V--
--=======================--
--=======================--


.43}},[3523]={{31.26,62.74},{32.1,68.19}},[3520]={{33.33,30.46},{39.55,54.71}},[3557]={{42.66,26.46}},[3525]={{55.65,67.88}},[3524]={{44.37,52.6}},[3522]={{50.01,58.6},{41.52,66.01}},[28]={{43.37,82.32}},[215]={{51.8,59.96}},[14]={{52.12,47.43}}},3519},
[188048] = {"Twilight Crystal Base",nil,nil,{[1377]={{67.04,18.67},{66.58,20.58},{67.47,20.16},{67.04,18.67},{66.58,20.58},{67.47,20.16}},[331]={{9.26,11.48},{9.63,12.18},{9.66,11.14},{9.26,11.48},{9.63,12.18},{9.66,11.14}},[405]={{40.34,30.23},{39.17,30.48},{39.64,29.7},{39.61,30.62}},[33]={{21.18,22.76},{20.9,24.15},{21.31,23.54}},[51]={{14.74,34.42},{16.07,36.9},{13.54,37.12},{15.34,36.06},{14.42,33.85},{13.5,35.01}}},1377},
[188049] = {"Ice Stone",nil,nil,{[331]={{9.64,12.18}}},331},
[188050] = {"Twilight Crystal Base",nil,nil,{[1377]={{66.57,20.58},{67.04,18.66},{67.48,20.18},{66.57,20.58},{67.04,18.66},{67.48,20.18}},[331]={{9.26,11.47},{9.64,12.18},{9.66,11.14},{9.26,11.47},{9.64,12.18},{9.66,11.14}},[405]={{40.34,30.23},{39.17,30.49},{39.64,29.69},{39.62,30.64}},[33]={{21.18,22.77},{20.89,24.16},{21.31,23.52}},[51]={{14.73,34.38},{16.1,36.92},{13.54,37.11},{15.35,36.1},{14.42,33.83},{13.48,35.01}}},1377},
[188067] = {"Ice Block",nil,nil,{[3717]={{-1,-1}}},3717},
[188072] = {"Ice Stone Mount",nil,nil,{[3717]={{-1,-1}}},3717},
[188073] = {"Ahune Bonfire",nil,nil,{[3717]={{-1,-1}}},3717},
[188081] = {"Sanctum Planetarium",nil,nil,{[4131]={{-1,-1}},[4075]={{-1,-1}},[4080]={{47.65,35.53},{48.5,44.42}}},4080},
[188114] = {"Orb of the Blue Flight",nil,nil,{[4075]={{-1,-1}}},4075},
[188115] = {"Orb of the Blue Flight",nil,nil,{[4075]={{-1,-1}}},4075},
[188116] = {"Orb of the Blue Flight",nil,nil,{[4075]={{-1,-1}}},4075},
[188123] = {"Mailbox",nil,nil,{[1657]={{67.18,16.47}}},1657,80},
[188124] = {"Ice Chest",nil,nil,nil,0},
[188126] = {"Guild Vault",nil,nil,{[3703]={{51.62,27.07},{46.04,31.22}}},3703},
[188127] = {"Guild Vault",nil,nil,{[3703]={{56.53,63.37},{62.38,58.96}}},3703},
[188128] = {"Flame of the Exodar",nil,


和添加了日志

![](https://mmbiz.qpic.cn/mmbiz_png/Kdg8y12zuNGGB7jjkRibJ6U6IERS1SMnvGrs1q3DK3TKgMetPn06iafTlWwbRQAdibZ8LZmLBphf2gJDLn2tBZiaqw/640?wx_fmt=png)

标记三就是稍微在原来微信 appservice.js 的基础上进行了一点修改，然后保存，期待这微信开发者工具上面会有一些不一样的烟火🎆，但奈何关了又开，开了又关半天屁的变化都没有，于是就产生了自我怀疑，难道不应该这样吗，但是还是感觉方向是对的，于是打算在试试终极解决方法《重启电脑》, 果然当我在打开开发者工具的时候看到了不一样的烟火🎆， 在 console 里面出现了耀眼的光芒，这里应该算一个突破性进展吧！！！

![](https://mmbiz.qpic.cn/mmbiz_png/Kdg8y12zuNGGB7jjkRibJ6U6IERS1SMnvhFa6Kbke7hD90nNMNI8HxqMhDhiafzKzFImib9vfGqMdPLjD6pwFIPug/640?wx_fmt=png)

看到 api 和返回的结果，发现这些其实就是微信提供对外的同步 api, 可以看到 getSystemInfo 走的其实是同步的方式，那微信还提供了 getSystemInfoSync 说明也是同步的，他们的底层实现都是同步的不知道这个 api 还提供这两个接口有什么意义 没理解，  然后又试了下其他微信提供的同步方法发现都会出现在这里，其他很多异步 api 的不会走这里都是通过 webstocket 走的，这里可以得出结论这些同步 api 请求都是通过 / apihelper/assdk 传输的，大家可以自己测试下拦截这个请求会发现更多内容。

**至于这个文件和基础库的关联和最核心的 webstocket 的实现和在文章开头说的案例分析和云开发小游戏架构分析相关，我打算放在下几篇《核心篇》里面来一一分享，本来打算放在一起的，但写起来才发现虽然文字不多但考虑东西太多时间要很久，如果放在一起只是大概概括的话会很快少很多省时省力，但是感觉没太大意义可能对一些想了解的同学没有太大帮助，所以我就想通过我中途的过程和遇到的问题来分析可能会好理解一些**

![](https://mmbiz.qpic.cn/mmbiz_png/zBWtzxgVo6mKL6RQTJy5ezicB1CoQD8L2wiawNTDRQrn2gmMBvibnPwzbafuQsG1R4lwelDNgOGM9sQs2QeY46ibdg/640?wx_fmt=png)

[

![](https://mmbiz.qpic.cn/mmbiz_jpg/zBWtzxgVo6kiaFHdvpSeux5dClYfLNNnu8qCicLxIcDca4fnyGibUqkp7jiam1ssbtCocyI5RicO9DFJq1M21hjNH7g/640?wx_fmt=jpeg)

实现小程序编译和运行环境系列 (一)

](http://mp.weixin.qq.com/s?__biz=MzI3OTA0NDQ3NQ=


ct
            .key("ClusterEndpointEncryptionType")
            .string(var_21.as_str());
    }
    Ok(())
}

pub fn serialize_structure_crate_input_create_parameter_group_input(
    object: &mut aws_smithy_json::serialize::JsonObjectWriter,
    input: &crate::input::CreateParameterGroupInput,
) -> Result<(), aws_smithy_http::operation::SerializationError> {
    if let Some(var_22) = &input.parameter_group_name {
        object.key("ParameterGroupName").string(var_22.as_str());
    }
    if let Some(var_23) = &input.description {
        object.key("Description").string(var_23.as_str());
    }
    Ok(())
}

pub fn serialize_structure_crate_input_create_subnet_group_input(
    object: &mut aws_smithy_json::serialize::JsonObjectWriter,
    input: &crate::input::CreateSubnetGroupInput,
) -> Result<(), aws_smithy_http::operation::SerializationError> {
    if let Some(var_24) = &input.subnet_group_name {
        object.key("SubnetGroupName").string(var_24.as_str());
    }
    if let Some(var_25) = &input.description {
        object.key("Description").string(var_25.as_str());
    }
    if let Some(var_26) = &input.subnet_ids {
        let mut array_27 = object.key("SubnetIds").start_array();
        for item_28 in var_26 {
            {
                array_27.value().string(item_28.as_str());
            }
        }
        array_27.finish();
    }
    Ok(())
}

pub fn serialize_structure_crate_input_decrease_replication_factor_input(
    object: &mut aws_smithy_json::serialize::JsonObjectWriter,
    input: &crate::input::DecreaseReplicationFactorInput,
) -> Result<(), aws_smithy_http::operation::SerializationError> {
    if let Some(var_29) = &input.cluster_name {
        object.key("ClusterName").string(var_29.as_str());
    }
    {
        object.key("NewReplicationFactor").number(
            #[allow(clippy::useless_conversion)]
            aws_smithy_types::Number::NegInt((input.new_replication_factor).into()),
        );
    }
    if let Some(var_30) = &input.availability_zones {
        let mut array_31 = object.key("AvailabilityZones").start_array();
        for item_32 in var_30 {
            {
                array_31.value().string(item_32.as_str());
            }
        }
        array_31.finish();
    }
    if let Some(var_33) = &input.node_ids_to_remove {
        let mut array_34 = object.key("NodeIdsToRemove").start_array();
        for item_35 in var_33 {
            {
                array_34.value().string(item_35.as_str());
            }
        }
        array_34.finish();
    }
    Ok(())
}

pub fn serialize_structure_crate_input_delete_cluster_input(
    object: &mut aws_smithy_json::serialize::JsonObjectWriter,
    input: &crate::input::DeleteClusterInput,
) -> Result<(), aws_smithy_http::operation::SerializationError> {
    if let Some(var_36) = &input.cluster_name {
        object.key("ClusterName").string(var_36.as_str());
    }
    Ok(())
}

pub fn serialize_structure_crate_input_delete_parameter_group_input(
    object: &mut aws_smithy_json::serialize::JsonObjectWriter,
    input: &crate::input::DeleteParameterGroupInput,


margin-right:20px}.editor-styles-wrapper [data-align=right] .wp-block-jetpack-google-docs-embed{margin-left:20px}html[amp] .wp-block-jetpack-google-docs-embed.alignleft,html[amp] .wp-block-jetpack-google-docs-embed.alignright{float:none}html[amp] .wp-block-jetpack-google-docs-embed__wrapper:before{content:none}html[amp] .wp-block-jetpack-google-docs-embed__error-msg:before{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16' fill='none'%3E%3Cpath d='M1.5 3.5v11h11V10H14v5a1 1 0 0 1-1 1H1a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1h5v1.5H1.5Z' fill='%231E2935'/%3E%3Cpath d='m15.922 1.178-8.907 8.907-1.06-1.06L14.86.118l1.06 1.06Z' fill='%231E2935'/%3E%3Cpath d='M7.5 0H16v1.5H7.5V0Z' fill='%231E2935'/%3E%3Cpath d='M16 0v8.5h-1.5V0H16Z' fill='%231E2935'/%3E%3C/svg%3E");background-size:12px;height:12px;top:1px;width:12px}html[amp] .wp-block-jetpack-google-docs-embed .loader{display:none}.wp-block-jetpack-slideshow{margin-bottom:1.5em;position:relative}.wp-block-jetpack-slideshow [tabindex="-1"]:focus{outline:0}.wp-block-jetpack-slideshow.wp-amp-block>.wp-block-jetpack-slideshow_container{opacity:1}.wp-block-jetpack-slideshow.wp-amp-block.wp-block-jetpack-slideshow__autoplay .wp-block-jetpack-slideshow_button-play,.wp-block-jetpack-slideshow.wp-amp-block.wp-block-jetpack-slideshow__autoplay.wp-block-jetpack-slideshow__autoplay-playing .wp-block-jetpack-slideshow_button-pause{display:block}.wp-block-jetpack-slideshow.wp-amp-block.wp-block-jetpack-slideshow__autoplay.wp-block-jetpack-slideshow__autoplay-playing .wp-block-jetpack-slideshow_button-play{display:none}.wp-block-jetpack-slideshow .wp-block-jetpack-slideshow_container{opacity:0;overflow:hidden;width:100%}.wp-block-jetpack-slideshow .wp-block-jetpack-slideshow_container.wp-swiper-initialized{opacity:1}.wp-block-jetpack-slideshow .wp-block-jetpack-slideshow_container.swiper-container{display:block}.wp-block-jetpack-slideshow .wp-block-jetpack-slideshow_container .wp-block-jetpack-slideshow_slide,.wp-block-jetpack-slideshow .wp-block-jetpack-slideshow_container .wp-block-jetpack-slideshow_swiper-wrapper{line-height:normal;margin:0;padding:0}.wp-block-jetpack-slideshow .wp-block-jetpack-slideshow_container ul.wp-block-jetpack-slideshow_swiper-wrapper{display:flex}.wp-block-jetpack-slideshow .wp-block-jetpack-slideshow_slide{display:flex;height:100%;width:100%}.wp-block-jetpack-slideshow .wp-block-jetpack-slideshow_slide figure{align-items:center;display:flex;height:100%;justify-content:center;margin:0;position:relative;width:


# Copyright (C) 2013 Claudio Guarnieri.
# Copyright (C) 2014-2017 Cuckoo Foundation.
# This file is part of Cuckoo Sandbox - http://www.cuckoosandbox.org
# See the file 'docs/LICENSE' for copying permission.

import web.errors

# Maximum upload size (10GB, so there's basically no limit).
MAX_UPLOAD_SIZE = 10 * 1024 * 1024 * 1024

# Override default secret key stored in $CWD/web/.secret_key
# Make this unique, and don't share it with anybody.
# SECRET_KEY = "YOUR_RANDOM_KEY"

# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = "en-us"

ADMINS = (
    # ("Your Name", "your_email@example.com"),
)

MANAGERS = ADMINS

# Allow verbose debug error message in case of application fault.
# It's strongly suggested to set it to False if you are serving the
# web application from a web server front-end (i.e. Apache).
DEBUG = False
DEBUG404 = False

# A list of strings representing the host/domain names that this Django site
# can serve.
# Values in this list can be fully qualified names (e.g. 'www.example.com').
# When DEBUG is True or when running tests, host validation is disabled; any
# host will be accepted. Thus it's usually only necessary to set it in production.
ALLOWED_HOSTS = ["*"]

handler404 = web.errors.handler404
handler500 = web.errors.handler500

#A list of strings representing the subnets or ipaddresses that can download
#samples and dropped files
#Values in this list can be ipv4 or ipv6 separated by ","
#(e.g. '127.0.0.0/8,10.0.0.0/8,fd00::/8').
ALLOWED_FILEDOWNLOAD_SUBNETS = '127.0.0.0/8,10.0.0.0/8,fd00::/8'


import argparse

TXN_TYPES = 3
CONTENTION_LEVEL = 2
OP_TYPE = 2
TXN_ACCESS = [11, 7, 8]

BUFFERS_SIZE = 2
COMMIT_BACKOFF = 4
ABORT_BACKOFF = 4

ACCESS_ACTION = 0
WAIT_ACTION = 1
PIECE_ACTION = 2
WAIT_INFO = 3

COMMIT_WAIT = TXN_TYPES * CONTENTION_LEVEL + 1

def construct_line(access_action, wait_action, piece_action, wait_info):
    line = ""
    line += str(access_action) + " "
    line += str(wait_action) + " "
    line += str(piece_action) + " "
    for i in range(TXN_TYPES):
        line += str(wait_info[i]) + " "
    line += "\n"
    return line

def transfer_policy(policy_file, new_policy_file):
    policy = open(policy_file, 'r')
    new_policy = open(new_policy_file, 'w')

    # copy buffer size
    for i in range(2):
        line = policy.readline()
        new_policy.write(line)

    # copy commit/abort backoff
    for i in range(COMMIT_BACKOFF + ABORT_BACKOFF):
        line = policy.readline()
        new_policy.write(line)

    # ignore commit wait
    for i in range(COMMIT_WAIT):
        policy.readline()

    # copy normal access
    line = policy.readline()
    new_policy.write(line)
    access_actions = []
    piece_actions = []
    for i in range(TXN_TYPES):
        for j in range(TXN_ACCESS[i]):
            access_action = (policy.readline().split('\n')[0]).split( )
            access_action = list(map(int, access_action))
            access_actions.append(access_action)
            for m in range(CONTENTION_LEVEL - 1):
                policy.readline()
            piece_action = (policy.readline().split('\n')[0]).split( )
            piece_action = list(map(int, piece_action))
            piece_actions.append(piece_action)
            for m in range(CONTENTION_LEVEL - 1):
                policy.readline()

    base = 0
    for i in range(TXN_TYPES):
        for j in range(TXN_ACCESS[i]):
            access_action = access_actions[base + j][ACCESS_ACTION]
            wait_action = access_actions[base + j][WAIT_ACTION]
            piece_action = piece_actions[base + j][PIECE_ACTION]

            wait_info = []
            if j != 0:
                prev_validation_wait_action = piece_actions[base + j - 1][WAIT_ACTION]
                current_wait = access_actions[base + j][WAIT_INFO:]
                prev_wait = piece_actions[base + j - 1][WAIT_INFO:]
                for m in range(TXN_TYPES):
                    wait = 0
                    if wait_action and prev_validation_wait_action:
                        wait = max(current_wait[m], prev_wait[m])
                    else:
                        if wait_action:
                            wait = current_wait[m]
                        else:
                            wait = prev_wait[m]
                    wait_info.append(wait)
                wait_action = wait_action | prev_validation_wait_action
            else:
                for m in range(TXN_TYPES):
                    wait_info.append(access_actions[base + j][WAIT_INFO + m])
            line = construct_line(access_action, wait_action, piece_action, wait_info)
            new_policy.write(line)
        base += TXN_ACCESS[i]

def main(args):

    transfer_policy(args.policy, args.new)
    return

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument('--policy', type=str,
                        help='policy file')
    parser.add_argument('--new', type=str, default='./new_policy',
                        help='new policy file')

    main(parser.parse_args())


PROTO_0:
  GETUPVAL R3 0
  GETTABLE R2 R3 R1
  JUMPIFNOT R2 [+3]
  GETUPVAL R3 0
  GETTABLE R2 R3 R1
  RETURN R2 1
  LOADK R4 K0 ["apis"]
  LOADK R6 K1 ["/orgs/v1/organizations?groupId=%*"]
  MOVE R8 R1
  NAMECALL R6 R6 K2 ["format"]
  CALL R6 2 1
  MOVE R5 R6
  NAMECALL R2 R0 K3 ["get"]
  CALL R2 3 1
  NAMECALL R2 R2 K4 ["await"]
  CALL R2 1 1
  GETUPVAL R3 0
  GETTABLEKS R5 R2 K5 ["responseBody"]
  GETTABLEKS R4 R5 K6 ["id"]
  SETTABLE R4 R3 R1
  GETUPVAL R4 0
  GETTABLE R3 R4 R1
  RETURN R3 1

PROTO_1:
  GETUPVAL R0 0
  LOADK R2 K0 ["apis"]
  LOADK R4 K1 ["/orgs/v2/universes/%*/permissions/organizations/%*/roles/%*"]
  GETUPVAL R6 1
  GETUPVAL R7 2
  GETUPVAL R9 3
  GETTABLEKS R8 R9 K2 ["id"]
  NAMECALL R4 R4 K3 ["format"]
  CALL R4 4 1
  MOVE R3 R4
  NAMECALL R0 R0 K4 ["get"]
  CALL R0 3 1
  NAMECALL R0 R0 K5 ["await"]
  CALL R0 1 1
  GETUPVAL R2 4
  GETTABLEKS R1 R2 K6 ["fromResponseBody"]
  GETTABLEKS R2 R0 K7 ["responseBody"]
  GETUPVAL R3 3
  GETUPVAL R4 5
  GETUPVAL R5 6
  CALL R1 4 -1
  RETURN R1 -1

PROTO_2:
  GETIMPORT R6 K1 [pcall]
  NEWCLOSURE R7 P0
  CAPTURE VAL R0
  CAPTURE VAL R1
  CAPTURE VAL R2
  CAPTURE VAL R3
  CAPTURE UPVAL U0
  CAPTURE VAL R4
  CAPTURE VAL R5
  CALL R6 1 -1
  RETURN R6 -1

PROTO_3:
  GETUPVAL R0 0
  LOADK R2 K0 ["apis"]
  LOADK R4 K1 ["/orgs/v2/universes/%*/permissions/organizations/%*/roles/%*"]
  GETUPVAL R6 1
  GETUPVAL R7 2
  GETUPVAL R8 3
  NAMECALL R4 R4 K2 ["format"]
  CALL R4 4 1
  MOVE R3 R4
  DUPTABLE R4 K5 [{"Body", "expectEmptyResponse"}]
  GETUPVAL R6 4
  GETTABLEKS R5 R6 K6 ["toRequestBody"]
  GETUPVAL R6 5
  CALL R5 1 1
  SETTABLEKS R5 R4 K3 ["Body"]
  LOADB R5 1
  SETTABLEKS R5 R4 K4 ["expectEmptyResponse"]
  NAMECALL R0 R0 K7 ["post"]
  CALL R0 4 1
  NAMECALL R0 R0 K8 ["await"]
  CALL R0 1 0
  RETURN R0 0

PROTO_4:
  GETIMPORT R5 K1 [pcall]
  NEWCLOSURE R6 P0
  CAPTURE VAL R0
  CAPTURE VAL R1
  CAPTURE VAL R2
  CAPTURE VAL R3
  CAPTURE UPVAL U0
  CAPTURE VAL R4
  CALL R5 1 -1
  RETURN R5 -1

PROTO_5:
  GETUPVAL R2 0
  NAMECALL R2 R2 K0 ["GetUserId"]
  CALL R


` // 非班中离返岗。为true时，不产生班中离返岗
}

type LeaveNeedPunchCfgBuilder struct {
	lateMinutesAsLate     int // 晚到超过多久记为迟到
	lateMinutesAsLateFlag bool

	lateMinutesAsLack     int // 晚到超过多久记为缺卡
	lateMinutesAsLackFlag bool

	earlyMinutesAsEarly     int // 早走超过多久记为早退
	earlyMinutesAsEarlyFlag bool

	earlyMinutesAsLack     int // 早走超过多久记为缺卡
	earlyMinutesAsLackFlag bool

	notDuringShift     bool // 非班中离返岗。为true时，不产生班中离返岗
	notDuringShiftFlag bool
}

func NewLeaveNeedPunchCfgBuilder() *LeaveNeedPunchCfgBuilder {
	builder := &LeaveNeedPunchCfgBuilder{}
	return builder
}

// 晚到超过多久记为迟到
//
// 示例值：0
func (builder *LeaveNeedPunchCfgBuilder) LateMinutesAsLate(lateMinutesAsLate int) *LeaveNeedPunchCfgBuilder {
	builder.lateMinutesAsLate = lateMinutesAsLate
	builder.lateMinutesAsLateFlag = true
	return builder
}

// 晚到超过多久记为缺卡
//
// 示例值：0
func (builder *LeaveNeedPunchCfgBuilder) LateMinutesAsLack(lateMinutesAsLack int) *LeaveNeedPunchCfgBuilder {
	builder.lateMinutesAsLack = lateMinutesAsLack
	builder.lateMinutesAsLackFlag = true
	return builder
}

// 早走超过多久记为早退
//
// 示例值：0
func (builder *LeaveNeedPunchCfgBuilder) EarlyMinutesAsEarly(earlyMinutesAsEarly int) *LeaveNeedPunchCfgBuilder {
	builder.earlyMinutesAsEarly = earlyMinutesAsEarly
	builder.earlyMinutesAsEarlyFlag = true
	return builder
}

// 早走超过多久记为缺卡
//
// 示例值：0
func (builder *LeaveNeedPunchCfgBuilder) EarlyMinutesAsLack(earlyMinutesAsLack int) *LeaveNeedPunchCfgBuilder {
	builder.earlyMinutesAsLack = earlyMinutesAsLack
	builder.earlyMinutesAsLackFlag = true
	return builder
}

// 非班中离返岗。为true时，不产生班中离返岗
//
// 示例值：false
func (builder *LeaveNeedPunchCfgBuilder) NotDuringShift(notDuringShift bool) *LeaveNeedPunchCfgBuilder {
	builder.notDuringShift = notDuringShift
	builder.notDuringShiftFlag = true
	return builder
}

func (builder *LeaveNeedPunchCfgBuilder) Build() *LeaveNeedPunchCfg {
	req := &LeaveNeedPunchCfg{}
	if builder.lateMinutesAsLateFlag {
		req.LateMinutesAsLate = &builder.lateMinutesAsLate

	}
	if builder.lateMinutesAsLackFlag {
		req.LateMinutesAsLack = &builder.lateMinutesAsLack

	}
	if builder.earlyMinutesAsEarlyFlag {
		req.EarlyMinutesAsEarly = &builder.earlyMinutesAsEarly

	}
	if builder.earlyMinutesAsLackFlag {
		req.EarlyMinutesAsLack = &builder.earlyMinutesAsLack

	}
	if builder.notDuringShiftFlag {
		req.NotDuringShift = &builder.notDuringShift

	}
	return req
}

type Location struct {
	LocationId *string `json:"location_id,omitempty"` // 地址 ID

	LocationName *string `json:"location_name,omitempty"` // 地址名称

	LocationType *int `json:"location_type,omitempty"` // 地址类型，1：GPS，2：Wi-Fi，8：IP

	Latitude *float64 `json:"latitude,


tcore.NewServer(nil)

	// 设置处理器
	// bs.Server.SetMessageHandler(bs.handleMessage) // 暂时注释掉
	// bs.Server.SetConnectHandler(bs.handleConnect) // 暂时注释掉
	// bs.Server.SetDisconnectHandler(bs.handleDisconnect) // 暂时注释掉

	log.Printf("后端服务器 %s 启动在 %s", bs.ID, bs.Address)
	return bs.Server.Start(bs.Address)
}

// handleConnect 处理连接
func (bs *BackendServer) handleConnect(conn core.Connection) {
	atomic.AddInt64(&bs.Connections, 1)
	log.Printf("后端服务器 %s: 新连接 %s (总连接: %d)", bs.ID, conn.RemoteAddr(), bs.Connections)
}

// handleDisconnect 处理断开连接
func (bs *BackendServer) handleDisconnect(conn core.Connection) {
	atomic.AddInt64(&bs.Connections, -1)
	log.Printf("后端服务器 %s: 连接断开 %s (总连接: %d)", bs.ID, conn.RemoteAddr(), bs.Connections)
}

// handleMessage 处理消息
func (bs *BackendServer) handleMessage(conn core.Connection, data []byte) {
	start := time.Now()

	var req RequestMessage
	if err := json.Unmarshal(data, &req); err != nil {
		log.Printf("后端服务器 %s: 解析请求失败: %v", bs.ID, err)
		return
	}

	// 更新统计
	atomic.AddInt64(&bs.TotalRequests, 1)

	// 模拟处理请求
	processingTime := time.Duration(rand.Intn(100)+50) * time.Millisecond
	time.Sleep(processingTime)

	// 创建响应
	resp := ResponseMessage{
		ID:        fmt.Sprintf("resp_%d", time.Now().UnixNano()),
		RequestID: req.ID,
		Type:      "response",
		Data: map[string]interface{}{
			"message":         fmt.Sprintf("Hello from server %s", bs.ID),
			"request_data":    req.Data,
			"processing_time": processingTime.String(),
		},
		ServerID:   bs.ID,
		StatusCode: 200,
		Timestamp:  time.Now().Unix(),
	}

	// 发送响应
	respData, err := json.Marshal(resp)
	if err != nil {
		log.Printf("后端服务器 %s: 序列化响应失败: %v", bs.ID, err)
		atomic.AddInt64(&bs.FailedRequests, 1)
		return
	}

	coreMsg := core.NewMessage(core.MessageTypeJSON, respData)
	conn.SendMessage(*coreMsg)

	// 更新响应时间
	responseTime := time.Since(start).Microseconds()
	atomic.StoreInt64(&bs.ResponseTime, responseTime)

	log.Printf("后端服务器 %s: 处理请求 %s (耗时: %v)", bs.ID, req.ID, time.Since(start))
}

// Stop 停止后端服务器
func (bs *BackendServer) Stop() error {
	if bs.Server != nil {
		return bs.Server.Stop()
	}
	return nil
}

// GetStats 获取服务器统计
func (bs *BackendServer) GetStats() map[string]interface{} {
	bs.mu.RLock()
	defer bs.mu.RUnlock()

	return map[string]interface{}{
		"id":              bs.ID,
		"address":         bs.Address,
		"weight":          bs.Weight,
		"connections":     atomic.LoadInt64(&bs.Connections),
		"healthy":         bs.Healthy,
		"last_check":      bs.LastCheck,
		"response_time":   atomic.LoadInt64(&bs.ResponseTime),
		"total_requests":  atomic.LoadInt64(&bs.TotalRequests),
		"failed_requests": atomic.LoadInt64(&bs.FailedRequests),
	}
}

// NewLoadBalancer 创建负载均衡器
func NewLoad


       this.errorResponse = errorResponse;
    }
    getResponse():ErrorResponse<ValidationError>|null {
        return this.errorResponse;
    }
    hasError(): boolean {
        if(!this.errorResponse)
            return false;
        return this.errorResponse.hasError();
    }

}// Import every module to make a handler from dashboard model
import express, { Request, Response } from 'express';
import DashboardQueries from '../services/dashboard';
import tokenReader from '../utilities/tokenReader';

// Building endpoints
const dashboardRoutes = (app: express.Application): void => {
	app.get('/top', top);
	app.get('/category/:category', category);
	app.get('/current/:id', tokenReader, current);
	app.get('/completed/:id', tokenReader, completed);
};

// Creating a reference to the DashboardQueries class
const queries = new DashboardQueries();

// Creating relation between routes and database
const top = async (_req: Request, res: Response) => {
	const best = await queries.topProducts();
	res.json(best);
};
const category = async (_req: Request, res: Response) => {
	const segregate = await queries.productByCategory(_req.params.category);
	res.json(segregate);
};
const current = async (_req: Request, res: Response) => {
	const curr = await queries.currentOrder(_req.params.id);
	res.json(curr);
};
const completed = async (_req: Request, res: Response) => {
	const comp = await queries.completedOrder(_req.params.id);
	res.json(comp);
};

// Allowing routes to be called
export default dashboardRoutes;
import {Block} from './block';
import * as SHA256 from 'crypto-js/sha256';
import * as bitcoinMessage from 'bitcoinjs-message';

// const SHA256  = require('crypto-js/sha256');

export class Blockchain {
  private chain: Block[];
  private height: number;

  constructor(block: Block) {
    this.chain = [];
    this.height = -1;

    this.addBlock(this.createGenesisBlock());
    this.initChain();
  }

  private async initChain(): Promise<void> {
    if (this.height === -1) {
      const block = this.createGenesisBlock();
      await this.addBlock(block);
    }
  }

  private createGenesisBlock(): Block {
    return new Block('Genesis Block');
  }

  private getPrevBlockHash(): string {
    return this.chain[this.chain.length - 1].hash;
  }

  private getChainHeight(): number {
    return this.chain.length;
  }

  private hashBlock(block: Block): string {
    return SHA256(JSON.stringify(block)).toString();
  }

  private setTimeStamp(): string {
    return new Date().getTime().toString().slice(0, -3);
  }

  private addBlock(newBlock: Block): Promise<unknown> {

    return new Promise((res, rej) => {
      newBlock.height = this.getChainHeight();
      newBlock.timeStamp = this.setTimeStamp(); /// UTC t.s

      if (this.chain.length > 0) {
        newBlock.prevBlockHash = this.getPrevBlockHash();
      }

      newBlock.hash = this.hashBlock(newBlock);

      this.chain.push(newBlock);
    });
  }

  private requestMessageOwnershipVerification(address:


# File: app/ui/tab_interface_data.py

import re
from natsort import natsorted
from PyQt5 import QtWidgets, QtCore, QtWebEngineWidgets
from PyQt5.QtWidgets import QVBoxLayout, QHBoxLayout, QSplitter, QComboBox, QLabel, QSizePolicy
from ..plotting.plotter import load_fig_to_webview

class InterfaceDataTab(QtWidgets.QWidget):
    plot_parameters_changed = QtCore.pyqtSignal()

    def __init__(self, parent=None):
        super().__init__(parent)
        self.df = None  # Holding a reference to the main frame
        self._setup_ui()

    def set_dataframe(self, df):
        """MainWindow provides the dataframe to this tab."""
        self.df = df

    def _setup_ui(self):
        # Widgets
        self.interface_selector = QComboBox()
        self.interface_selector.setEditable(True)
        self.side_selector = QComboBox()
        self.side_selector.setEditable(True)
        self.t_series_plot = QtWebEngineWidgets.QWebEngineView()
        self.r_series_plot = QtWebEngineWidgets.QWebEngineView()

        splitter = QSplitter(QtCore.Qt.Vertical)
        splitter.addWidget(self.t_series_plot)
        splitter.addWidget(self.r_series_plot)

        # Layouts
        side_layout = QHBoxLayout()
        side_selection_label = QLabel("Part Side Filter")
        side_selection_label.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Preferred)
        side_layout.addWidget(side_selection_label)
        side_layout.addWidget(self.side_selector)

        main_layout = QVBoxLayout(self)
        interface_selection_label = QLabel("Interface")
        main_layout.addWidget(interface_selection_label)
        main_layout.addWidget(self.interface_selector)
        main_layout.addLayout(side_layout)
        main_layout.addWidget(splitter)

        # Connections
        self.interface_selector.currentIndexChanged.connect(self._on_interface_changed)
        self.side_selector.currentIndexChanged.connect(self.plot_parameters_changed)

    # Private slots for internal logic
    def _on_interface_changed(self):
        self._populate_side_selector()
        self.plot_parameters_changed.emit()

    # Helper methods to call
    def _populate_side_selector(self):
        if self.df is None:
            return

        current_interface = self.interface_selector.currentText()
        if not current_interface:
            self.side_selector.clear()
            return

        pattern = re.compile(r'I\d+[a-zA-Z]?\s*-\s*(.*?)(?=\s*\()')
        relevant_cols = [col for col in self.df.columns if re.match(rf"^{re.escape(current_interface)}(?=\D)", col)]
        sides = sorted(set(pattern.search(col).group(1).strip() for col in relevant_cols if pattern.search(col)))

        self.side_selector.blockSignals(True)
        self.side_selector.clear()
        self.side_selector.addItems(sides)
        self.side_selector.blockSignals(False)

    def display_t_series_plot(self, fig):
        load_fig_to_webview(fig, self.t_series_plot)

    def display_r_series_plot(self, fig):

        load_fig_to_webview(fig, self.r_series_plot)


/* __ARC700__ || __ARCEM__ || __ARCHS__ */
#endif /* ENDIAN */
	.balign	4
.Lbytewise:
	breq	r2,0,.Lnil
	ldb	r4,[r0,0]
	ldb	r5,[r1,0]
	lsr.f	lp_count,r3
#ifdef __ARCEM__
	mov	r12,r3
	lpne	.Lbyte_end
	brne	r3,r12,.Lbyte_odd
#else
	lpne	.Lbyte_end
#endif
	ldb_s	r3,[r0,1]
	ldb_l	r12,[r1,1]
	brne	r4,r5,.Lbyte_even
	ldb.a	r4,[r0,2]
	ldb.a	r5,[r1,2]
#ifdef __ARCEM__
.Lbyte_end:
	brne	r3,r12,.Lbyte_odd
#else
	br


ckDetectorCuda(cv.argcheck(t, argRules)),
        Classes.Algorithm_dtor)
    return retval
end

do
    local TemplateMatching = torch.class('cuda.TemplateMatching', 'cv.Algorithm', cv.cuda)

    function TemplateMatching:match(t)
        local argRules = {
            {"image", required = true, operator = cv.wrap_tensor},
            {"templ", required = true, operator = cv.wrap_tensor},
            {"result", default = nil, operator = cv.wrap_tensor}
        }
        return cv.unwrap_tensors(C.TemplateMatching_matchCuda(cv.cuda._info(),
            self.ptr, cv.argcheck(t, argRules)))
    end
end

function cv.cuda.createTemplateMatching(t)
    local argRules = {
        {"srcType", required = true},
        {"method", required = true},
        {"user_block_size", default = {0, 0}, operator = cv.Size}
    }
    local retval = torch.factory('cuda.TemplateMatching')()
    retval.ptr = ffi.gc(
        C.createTemplateMatchingCuda(cv.argcheck(t, argRules)),
        Classes.Algorithm_dtor)
    return retval
end

function cv.cuda.bilateralFilter(t)
    local argRules = {
        {"src", required = true, operator = cv.wrap_tensor},
        {"dst", default = nil, operator = cv.wrap_tensor},
        {"kernel_size", required = true},
        {"sigma_color", required = true},
        {"sigma_spatial", required = true},
        {"borderMode", default = cv.BORDER_DEFAULT}
    }
    return cv.unwrap_tensors(C.bilateralFilterCuda(cv.cuda._info(), cv.argcheck(t, argRules)))
end

function cv.cuda.blendLinear(t)
    local argRules = {
        {"img1", required = true, operator = cv.wrap_tensor},
        {"img2", required = true, operator = cv.wrap_tensor},
        {"weights1", required = true, operator = cv.wrap_tensor},
        {"weights2", required = true, operator = cv.wrap_tensor},
        {"result", default = nil, operator = cv.wrap_tensor}
    }
    return cv.unwrap_tensors(C.blendLinearCuda(cv.cuda._info(), cv.argcheck(t, argRules)))
end

return cv.cuda


de != nil {
			t.cb.DisableMode(mode)
		}
	}
}

// isModeSet returns true if the mode is set.
func (t *Terminal) isModeSet(mode ansi.Mode) bool {
	m, ok := t.modes[mode]
	return ok && m.IsSet()
}
package vt

import (
	"image/color"

	uv "github.com/charmbracelet/ultraviolet"
	"github.com/charmbracelet/x/ansi"
)

// Callbacks represents a set of callbacks for a terminal.
type Callbacks struct {
	// Bell callback. When set, this function is called when a bell character is
	// received.
	Bell func()

	// Title callback. When set, this function is called when the terminal title
	// changes.
	Title func(string)

	// IconName callback. When set, this function is called when the terminal
	// icon name changes.
	IconName func(string)

	// AltScreen callback. When set, this function is called when the alternate
	// screen is activated or deactivated.
	AltScreen func(bool)

	// CursorPosition callback. When set, this function is called when the cursor
	// position changes.
	CursorPosition func(old, new uv.Position) //nolint:predeclared,revive

	// CursorVisibility callback. When set, this function is called when the
	// cursor visibility changes.
	CursorVisibility func(visible bool)

	// CursorStyle callback. When set, this function is called when the cursor
	// style changes.
	CursorStyle func(style CursorStyle, blink bool)

	// CursorColor callback. When set, this function is called when the cursor
	// color changes. Nil indicates the default terminal color.
	CursorColor func(color color.Color)

	// BackgroundColor callback. When set, this function is called when the
	// background color changes. Nil indicates the default terminal color.
	BackgroundColor func(color color.Color)

	// ForegroundColor callback. When set, this function is called when the
	// foreground color changes. Nil indicates the default terminal color.
	ForegroundColor func(color color.Color)

	// WorkingDirectory callback. When set, this function is called when the
	// current working directory changes.
	WorkingDirectory func(string)

	// EnableMode callback. When set, this function is called when a mode is
	// enabled.
	EnableMode func(mode ansi.Mode)

	// DisableMode callback. When set, this function is called when a mode is
	// disabled.
	DisableMode func(mode ansi.Mode)
}
package helpers

import (
	"pentagi/pkg/csum"
)

// ContextEstimate represents the estimated context size range
type ContextEstimate struct {
	MinTokens int // Minimum estimated tokens (optimal summarization)
	MaxTokens int // Maximum estimated tokens (approaching limits)
	MinBytes  int // Minimum estimated bytes
	MaxBytes  int // Maximum estimated bytes
}

// Global parameter boundaries based on data nature and algorithm constraints
var (
	// Absolute minimums based on data nature
	MinBodyPairBytes      = 512      // Minimum possible body pair size
	MinSectionBytes       = 3 * 1024 // Minimum section: header + 1 body pair
	MinSystemMessageBytes = 1 * 1024 // Minimum system message
	MinHumanMessageBytes  = 512      // Minimum human message
	MinQASections         = 1        // At least one QA section
	MinKeepQASections     = 1


clude ms-fontWeight-semilight;
    }

    .subject {
      @include ms-fontWeight-semilight;
    }

    .date {
      @include ms-fontWeight-semilight;
    }

    .preview {
      @include ms-fontWeight-light;
    }
  }

  .noMessages {
    @include ms-font-m;
  }

  .error {
    @include ms-font-m;
    color: $ms-color-alert;
  }
}
@import '~office-ui-fabric-react/dist/sass/References.scss';

.personalTasks {
  .webPartTitle, .viewAll, .groupTitle {
    padding-left: 10px;
  }

  .groupTitle {
    @include ms-font-m-plus;
    @include ms-fontWeight-semibold;
    margin-top: 1em;
  }

  .task {
    display: block;
    padding: 0.5em 10px;
    color: $ms-color-black;
    @include ms-fontWeight-semilight;

    &:hover {
      color: inherit;
      background: $ms-color-neutralLight;
    }

    .title {
      @include ms-fontWeight-regular;
    }

    .dueDateWrapper {
      display: flex;
    }

    .dueDateTime {
      display: inline;
      @include ms-font-s-plus;
      color: $ms-color-neutralSecondary;
      display: flex;
      flex: 0 0 auto;
      flex-direction: row;
      flex-wrap: nowrap;
      line-height: 20px;

      i {
        display: block;
      }

      &.isLate {
        background: #d63867;
        color: #fff;
        padding: .1em .4em;
      }

      .label {
        padding-left: 0.5em;
      }
    }
  }

  .completed {
    .title {
      text-decoration: line-through;
    }
  }

  .viewAll {
    display: block;
    margin-top: 1em;
  }

  .noTasks {
    @include ms-font-m;
    padding-left: 10px;
  }

  .error {
    @include ms-font-m;
    color: $ms-color-alert;
    padding-left: 10px;
  }
}
@tailwind base;
@tailwind components;
@tailwind utilities;

@layer base {
  .sample_details h1 {
    @apply text-3xl;
    @apply mb-2;
  }

  .sample_details h2 {
    @apply text-2xl;
    @apply mb-2;
  }

  .sample_details h3 {
    @apply text-xl;
    @apply mb-2;
  }

  .sample_details h4 {
    @apply text-lg;
    @apply mb-2;
  }

  .sample_details h5, .sample_details h6, .sample_details p {
    @apply mb-2;
  }

  .sample_details a {
    color: var(--vscode-textLink-foreground);
    @apply hover:underline;
  }

  .sample_details ul {
    display: block;
    list-style-type: disc;
  }

  .sample_details ol {
    display: block;
    list-style-type: decimal;
  }

  .sample_details li {
    display: list-item;
    @apply ml-4;
  }

  .sample_details ul ul li {
    @apply ml-8;
  }

  .sample_details table th, .sample_details table td {
    @apply border-collapse;
    @apply px-2;
    @apply py-2;
    border: 1px solid var(--vscode-editorWidget-border);
  }

  .sample_details img {
    @apply inline-block;
    @apply mb-2;


0x04, 0x04, 0xd1, 0xf5,  // zh-tw
            0x04, 0x05, 0x17, 0xe5,  // cs-cz
            0x04, 0x06, 0x18, 0xd5,  // da-dk
            0x04, 0x07, 0x1a, 0xc5,  // de-de
            0x04, 0x08, 0x1f, 0xe5,  // el-gr
            0x04, 0x09, 0x3e, 0x65,  // en-us
            0x04, 0x0a, 0x44, 0xcc,  // es-es_tradnl
            0x04, 0x0b, 0x4d, 0x15,  // fi-fi
            0x04, 0x0c, 0x53, 0x25,  // fr-fr
            0x04, 0x0d, 0x63, 0x75,  // he-il
            0x04, 0x0e, 0x65, 0x15,  // hu-hu
            0x04, 0x0f, 0x68, 0x25,  // is-is
            0x04, 0x10, 0x68, 0xc5,  // it-it
            0x04, 0x11, 0x6a, 0xa5,  // ja-jp
            0x04, 0x12, 0x72, 0xa5,  // ko-kr
            0x04, 0x13, 0x8a, 0x75,  // nl-nl
            0x04, 0x14, 0x86, 0xe5,  // nb-no
            0x04, 0x15, 0x91, 0xa5,  // pl-pl
            0x04, 0x16, 0x93, 0x65,  // pt-br
            0x04, 0x17, 0x9a, 0x95,  // rm-ch
            0x04, 0x18, 0x9b, 0x85,  // ro-ro
            0x04, 0x19, 0x9d, 0x75,  // ru-ru
            0x04, 0x1a, 0x64, 0x65,  // hr-hr
            0x04, 0x1b, 0xa5, 0x25,  // sk-sk
            0x04, 0x1c, 0xa9, 0xe5,  // sq-al
            0x04, 0x1d, 0xb3, 0x55,  // sv-se
            0x04, 0x1e, 0xb8, 0x95,  // th-th
            0x04, 0x1f, 0xbb, 0x75,  // tr-tr
            0x04, 0x20, 0xc0, 0x75,  // ur-pk
            0x04, 0x21, 0x67, 0x35,  // id-id
            0x04, 0x22, 0xbf, 0xd5,  // uk-ua
            0x04, 0x23, 0x0e, 0x75,  // be-by
            0x04, 0x24, 0xa5, 0x75,  // sl-si
            0x04, 0x25, 0x49, 0xe5,  // et-ee
            0x04, 0x26, 0x7d, 0x55,  // lv-lv
            0x04, 0x27, 0x7b, 0xf5,  // lt-lt
            0x04, 0x28, 0xb7, 0xfa,  // tg-cyrl-tj
            0x04, 0x29, 0x4a, 0xe5,  // fa-ir
            0x04, 0x2a, 0xc4, 0x55,  // vi-vn
            0x04, 0x2b, 0x65, 0xd5,  // hy-am
            0x04, 0x2c, 0x0d, 0x2a,  // az-latn-az
            0x04, 0x2d, 0x4a, 0x35,


ort on the elements, arranging them according to their
   * natural order.
   *
   * @param a the byte array to sort
   */
  public static void sort(byte[] a)
  {
    qsort(a, 0, a.length);
  }

  /**
   * Performs a stable sort on the elements, arranging them according to their
   * natural order.
   *
   * @param a the byte array to sort
   * @param fromIndex the first index to sort (inclusive)
   * @param toIndex the last index to sort (exclusive)
   * @throws IllegalArgumentException if fromIndex > toIndex
   * @throws ArrayIndexOutOfBoundsException if fromIndex < 0
   *         || toIndex > a.length
   */
  public static void sort(byte[] a, int fromIndex, int toIndex)
  {
    if (fromIndex > toIndex)
      throw new IllegalArgumentException();
    if (fromIndex < 0)
      throw new ArrayIndexOutOfBoundsException();
    qsort(a, fromIndex, toIndex - fromIndex);
  }

  /**
   * Finds the index of the median of three array elements.
   *
   * @param a the first index
   * @param b the second index
   * @param c the third index
   * @param d the array
   * @return the index (a, b, or c) which has the middle value of the three
   */
  private static int med3(int a, int b, int c, byte[] d)
  {
    return (d[a] < d[b]
            ? (d[b] < d[c] ? b : d[a] < d[c] ? c : a)
            : (d[b] > d[c] ? b : d[a] > d[c] ? c : a));
  }

  /**
   * Swaps the elements at two locations of an array
   *
   * @param i the first index
   * @param j the second index
   * @param a the array
   */
  private static void swap(int i, int j, byte[] a)
  {
    byte c = a[i];
    a[i] = a[j];
    a[j] = c;
  }

  /**
   * Swaps two ranges of an array.
   *
   * @param i the first range start
   * @param j the second range start
   * @param n the element count
   * @param a the array
   */
  private static void vecswap(int i, int j, int n, byte[] a)
  {
    for ( ; n > 0; i++, j++, n--)
      swap(i, j, a);
  }

  /**
   * Performs a recursive modified quicksort.
   *
   * @param array the array to sort
   * @param from the start index (inclusive)
   * @param count the number of elements to sort
   */
  private static void qsort(byte[] array, int from, int count)
  {
    // Use an insertion sort on small arrays.
    if (count <= 7)
      {
        for (int i = from + 1; i < from + count; i++)
          for (int j = i; j > from && array[j - 1] > array[j]; j--)
            swap(j, j - 1, array);
        return;
      }

    // Determine a good median element.
    int mid = from + count / 2;
    int lo = from;
    int hi = from + count - 1;

    if (count > 40)
      { // big arrays, pseudomedian of 9
        int s = count / 8;
        lo = med3(lo, lo + s, lo + 2 * s, array);
        mid = med3(mid - s, mid, mid + s, array);
        hi = med3(hi - 2 * s, hi - s, hi, array);
      }
    mid = med3(lo, mid, hi, array);

    int a, b, c, d;
    int comp;

    // Pull the median element out of the fray, and use it as a pivot.
    swap(from, mid, array);
    a = b = from;
    c = d = from + count - 1;

    // Repeatedly move b and c to each other, swapping elements so
    // that all elements


--------|-------------------------------------------------------------------------------------------|
| `for`         | Iterates over a sequence or range.                                                       |
| `while`       | Repeats as long as the condition is `True`.                                              |
| `break`       | Exits the loop early.                                                                    |
| `continue`    | Skips the rest of the current iteration and moves to the next.                           |
| `pass`        | Does nothing (placeholder).                                                              |
| `else`        | Executes after the loop finishes (unless `break` is used).                               |
| `nested`      | Loops inside loops for multi-dimensional data.                                           |
| `itertools`   | Provides advanced tools like permutations, combinations, and Cartesian products.         |

## String
### **Strings in Python**

Strings are one of the most commonly used data types in Python. They are sequences of characters enclosed in single quotes (`'`), double quotes (`"`), or triple quotes (`'''` or `"""`).

---

### **1. Basics of Strings**
1. **Defining Strings**:
   ```python
   single_quote = 'Hello'
   double_quote = "World"
   triple_quote = '''This is a
   multi-line string.'''
   ```

2. **Empty String**:
   ```python
   empty = ''
   ```

3. **Strings Are Immutable**:
   - Once created, you cannot modify a string directly. You can only create a new string.
   ```python
   text = "hello"
   # text[0] = 'H'  # Error
   text = "Hello"  # New string is created
   ```

---

### **2. String Operations**

#### **Concatenation and Repetition**
1. **Concatenation**:
   ```python
   greeting = "Hello" + " " + "World"
   print(greeting)  # Output: Hello World
   ```

2. **Repetition**:
   ```python
   repeated = "Hi! " * 3
   print(repeated)  # Output: Hi! Hi! Hi!
   ```

---

### **3. String Indexing and Slicing**

#### **Indexing**
- Strings are zero-indexed:
   ```python
   text = "Python"
   print(text[0])  # Output: P
   print(text[-1])  # Output: n (last character)
   ```

#### **Slicing**
- Extract substrings using slicing:
   ```python
   text = "Python"
   print(text[0:3])  # Output: Pyt
   print(text[:3])   # Output: Pyt (same as above)
   print(text[3:])   # Output: hon
   print(text[::2])  # Output: Pto (step of 2)
   print(text[::-1]) # Output: nohtyP (reversed)
   ```

---

### **4. String Methods**

#### **Case Manipulation**
1. **Uppercase and Lowercase**:
   ```python
   print("hello".upper())  # Output: HELLO
   print("HELLO".lower())  # Output: hello
   ```

2. **Capitalize and Title Case**:
   ```python
   print("hello world".capitalize())  # Output: Hello world
   print("hello world".title())       # Output: Hello World
   ```

3. **Swap Case**:
   ```python
   print("Hello World".swapcase())  # Output: hELLO wORLD
   ```

#### **Searching and Finding**
1. **Find and Index**:
   - `find()` returns the index of the first occurrence or `-1` if not found.
   ```python
   print("hello world".find("world"))  # Output: 6


[0.3]
× FFFC × 0308 × 0020 ÷ 0E01 ÷	#  × [0.3] OBJECT REPLACEMENT CHARACTER (CB) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) ÷ [18.0] THAI CHARACTER KO KAI (SA_AL) ÷ [0.3]
× FFFC ÷ 3041 ÷	#  × [0.3] OBJECT REPLACEMENT CHARACTER (CB) ÷ [20.02] HIRAGANA LETTER SMALL A (CJ_NS) ÷ [0.3]
× FFFC × 0020 ÷ 3041 ÷	#  × [0.3] OBJECT REPLACEMENT CHARACTER (CB) × [7.01] SPACE (SP) ÷ [18.0] HIRAGANA LETTER SMALL A (CJ_NS) ÷ [0.3]
× FFFC × 0308 ÷ 3041 ÷	#  × [0.3] OBJECT REPLACEMENT CHARACTER (CB) × [9.0] COMBINING DIAERESIS (CM1_CM) ÷ [20.02] HIRAGANA LETTER SMALL A (CJ_NS) ÷ [0.3]
× FFFC × 0308 × 0020 ÷ 3041 ÷	#  × [0.3] OBJECT REPLACEMENT CHARACTER (CB) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) ÷ [18.0] HIRAGANA LETTER SMALL A (CJ_NS) ÷ [0.3]
× 007D ÷ 0023 ÷	#  × [0.3] RIGHT CURLY BRACKET (CL) ÷ [999.0] NUMBER SIGN (AL) ÷ [0.3]
× 007D × 0020 ÷ 0023 ÷	#  × [0.3] RIGHT CURLY BRACKET (CL) × [7.01] SPACE (SP) ÷ [18.0] NUMBER SIGN (AL) ÷ [0.3]
× 007D × 0308 ÷ 0023 ÷	#  × [0.3] RIGHT CURLY BRACKET (CL) × [9.0] COMBINING DIAERESIS (CM1_CM) ÷ [999.0] NUMBER SIGN (AL) ÷ [0.3]
× 007D × 0308 × 0020 ÷ 0023 ÷	#  × [0.3] RIGHT CURLY BRACKET (CL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) ÷ [18.0] NUMBER SIGN (AL) ÷ [0.3]
× 007D ÷ 2014 ÷	#  × [0.3] RIGHT CURLY BRACKET (CL) ÷ [999.0] EM DASH (B2) ÷ [0.3]
× 007D × 0020 ÷ 2014 ÷	#  × [0.3] RIGHT CURLY BRACKET (CL) × [7.01] SPACE (SP) ÷ [18.0] EM DASH (B2) ÷ [0.3]
× 007D × 0308 ÷ 2014 ÷	#  × [0.3] RIGHT CURLY BRACKET (CL) × [9.0] COMBINING DIAERESIS (CM1_CM) ÷ [999.0] EM DASH (B2) ÷ [0.3]
× 007D × 0308 × 0020 ÷ 2014 ÷	#  × [0.3] RIGHT CURLY BRACKET (CL) × [9.0] COMBINING DIAERESIS (CM1_CM) × [7.01] SPACE (SP) ÷ [18.0] EM DASH (B2) ÷ [0.3]
× 007D × 0009 ÷	#  × [0.3] RIGHT CURLY BRACKET (CL) × [21.01] <CHARACTER TABULATION> (BA) ÷ [


   read = false
        new = false
    }

    /**
     * Clear the files.
     */
    fun clear() {
        files.clear()
    }

    fun fileIds(): IntArray {
        return files.keys.toIntArray()
    }

    fun files(): Array<File> {
        return files.values.toTypedArray()
    }

    @Deprecated("Use property syntax", ReplaceWith("xtea"))
    fun xtea(xtea: IntArray?) {
        this.xtea = xtea
    }

    @Deprecated("Use property syntax", ReplaceWith("xtea"))
    fun xtea(): IntArray? {
        return xtea
    }

    open fun toHash(name: String): Int {
        return name.hashCode()
    }

    override fun toString(): String {
        return "Archive[id=$id, hash_name=$hashName, revision=$revision, crc=$crc, has_whirlpool=${whirlpool != null}, read=$read, files_size=${files.size}]"
    }

}package org.distrinet.lanshield

import android.app.AppOpsManager
import android.app.Application
import android.content.Context
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.util.Log
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.longPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStoreFile
import androidx.lifecycle.MutableLiveData
import androidx.work.Configuration
import androidx.work.ListenableWorker
import androidx.work.WorkerFactory
import androidx.work.WorkerParameters
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.HiltAndroidApp
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import org.distrinet.lanshield.backendsync.AppUsageStats
import org.distrinet.lanshield.backendsync.OpenPortsWorker
import org.distrinet.lanshield.backendsync.SendToServerWorkerr
import org.distrinet.lanshield.database.AppDatabase
import org.distrinet.lanshield.database.dao.FlowDao
import org.distrinet.lanshield.database.dao.LANShieldSessionDao
import org.distrinet.lanshield.database.dao.LanAccessPolicyDao
import org.distrinet.lanshield.database.dao.OpenPortsDao
import org.distrinet.lanshield.vpnservice.LANShieldNotificationManager
import javax.inject.Inject
import javax.inject.Singleton

const val FEEDBACK_URL = "https://forms.gle/zh2J3KMzZjMnv2Qi9"
const val STUDY_MORE_INFO_URL = "https://lanshield.eu/user-study"
const val ABOUT_LANSHIELD_URL = "https://lanshield.eu"
const val PRIVACY_POLICY_URL = "https://lanshield.eu/privacy-policy"

val NO_SYSTEM_OVERRIDE_PACKAGE_NAMES = listOf("com.android.chrome")

const val PACKAGE_NAME_UNKNOWN = "Unknown"
const val PACKAGE_NAME_ROOT = "Root"
const val PACKAGE_NAME_SYSTEM = "System"
const val PACKAGE_NAME_PLAY_SERVICES = "Google Play Services"

const val BACKEND_URL = "https://api.lanshield.eu"
//const val BACKEND_URL = "http://192.168.157.147"
//const val BACKEND_URL = "http://192.168.55.147:5000"

const val ADD_FLOWS = "/add_flow"
const val ADD_ACL = "/add_acl"
const val ADD


G_MAXMP, 	CHAR_WORKMAXMP,			1 },
		{ CHAR_P_STRING_EXP, 	CHAR_EXP,				0 },
		{ CHAR_P_STRING_LV, 	CHAR_LV,				0 },
		{ CHAR_P_STRING_ATK, 	CHAR_WORKATTACKPOWER,	1 },
		{ CHAR_P_STRING_DEF, 	CHAR_WORKDEFENCEPOWER,	1 },
		{ CHAR_P_STRING_QUICK, 	CHAR_WORKQUICK,			1 },
		{ CHAR_P_STRING_CHARM, 	CHAR_WORKFIXCHARM,		1 },
		{ CHAR_P_STRING_LUCK, 	CHAR_WORKFIXLUCK,		1 },
		{ CHAR_P_STRING_GOLD, 	CHAR_GOLD,				0 },
		{ CHAR_P_STRING_TITLE, 	CHAR_INDEXOFEQTITLE,	0 },
		{ CHAR_P_STRING_NAME, 	CHAR_NAME,				2 },
		{ CHAR_P_STRING_OWNTITLE, CHAR_OWNTITLE,			2 },
		{ CHAR_P_STRING_VITAL, 	CHAR_VITAL,				10 },
		{ CHAR_P_STRING_STR, 	CHAR_STR,				10 },
		{ CHAR_P_STRING_TOUGH, 	CHAR_TOUGH,				10 },
		{ CHAR_P_STRING_DEX, 	CHAR_DEX,				10 },
		{ CHAR_P_STRING_EARTH, 	CHAR_WORKFIXEARTHAT,	11 },
		{ CHAR_P_STRING_WATER, 	CHAR_WORKFIXWATERAT,	11 },
		{ CHAR_P_STRING_FIRE, 	CHAR_WORKFIXFIREAT,		11 },
		{ CHAR_P_STRING_WIND, 	CHAR_WORKFIXWINDAT,		11 },
		{ CHAR_P_STRING_DUELPOINT, 	CHAR_DUELPOINT,		0 },
		{ CHAR_P_STRING_TRANSMIGRATION, CHAR_TRANSMIGRATION, 0},
		{ CHAR_P_STRING_RIDEPET, CHAR_RIDEPET, 0},
		{ CHAR_P_STRING_LEARNRIDE, CHAR_LEARNRIDE, 0},
		{ CHAR_P_STRING_BASEBASEIMAGENUMBER, CHAR_BASEBASEIMAGENUMBER, 0},
		{ CHAR_P_STRING_SKYWALKER, CHAR_WORKSKYWALKER, 1},
		{ CHAR_P_STRING_DEBUGMODE, CHAR_WORKDEBUGMODE, 1},
	};

	snprintf( CHAR_P_statusSendBuffer, sizeof( CHAR_P_statusSendBuffer),
				"P%s|", cnv10to62( indextable, buf,sizeof(buf)));
	strlength = strlen( CHAR_P_statusSendBuffer );

	for( i = 1; i < sizeof( int) * 8; i ++ ){
		if( indextable & (1 << i) ) {
			char	tmp[256];
			BOOL	found = FALSE;
			for( j = 0; j < arraysizeof( chk); j ++ ) {
				if( chk[j].kind ==  1 << i ) {
					if( chk[j].gettype == 0 ) {
						ret = CHAR_getInt( charaindex,chk[j].intdataindex);
						snprintf( tmp, sizeof( tmp), "%d|", ret);
					}else if( chk[j].gettype == 1 ) {
						ret = CHAR_getWorkInt( charaindex,chk[j].intdataindex);
						snprintf( tmp, sizeof( tmp), "%d|", ret);
					}else if( chk[j].gettype == 10 ) {
						ret = CHAR_getInt( charaindex, chk[j].intdataindex)/100;
						snprintf( tmp, sizeof( tmp), "%d|", ret);
					}else if( chk[j].gettype == 11 ) {
						ret = CHAR_getWorkInt( charaindex, chk[j].intdataindex);
						if( ret < 0) ret = 0;
						snprintf( tmp, sizeof( tmp), "%d|", ret);
					}else if( chk[j].gettype == 2 ) {
						char    escapebuffer[128];
						char *a = CHAR_getChar( charaindex, chk[j].intdataindex);

						snprintf( tmp,sizeof( tmp ),
								  "%s|",
								  makeEscapeString( a, escapebuffer,
								  					sizeof(escapebuffer)
								));
					}

					found = TRUE;
					break;
				}
			}
			if( !found) {
				if( indextable & CHAR_P_STRING_NEXTEXP ) {
					ret = CHAR_GetLevelExp( charaindex, CHAR_getInt( charaindex, CHAR_LV ) + 1);
					snprintf( tmp, sizeof( tmp), "%d|", ret);
					found = TRUE;
				}
			}
			if( !found) {
				print( "ҲָĲ[%d]\n",indextable);
			}else {
				strcpysafe( &CHAR_P_statusSendBuffer[ strlength],
							sizeof( CHAR_P_statusSendBuffer) - strlength,
							tmp);

				strlength += strlen( tmp );
				if( strlength >= sizeof( CHAR_P_statusSendBuffer ) ) {
					return CHAR_P_statusSendBuffer;
				}
			}
		}
	}
	return CHAR_P_statusSendBuffer;
}

BOOL CHAR_send_P_StatusString( int charaindex, unsigned int indextable )
{
	char*   string;
	//if( indextable >= ( CHAR_P_STRING_BASEBASEIMAGENUMBER << 1)) {
	if( indextable >= ( CHAR_P_STRING_SKYWALKER << 1)) {
	//if( indextable >= ( CHAR_P_STRING_DEBUGMODE << 1)) {
		print( "send_P invalid index[%d]\n", indextable);
		return FALSE;
	}

	if( CHAR_getInt(charaindex,CHAR_WHICHTYPE) != CHAR_TYPEPLAYER ){
		return FALSE;
	}

	string = CHAR_make_P_StatusString( charaindex, indextable );

	if( string != NULL ){
		int     fd;
		fd = getfdFromCharaIndex( charaindex );
		if( fd != -1 ){
			lssproto_S_send( fd, string );
			return TRUE;
		}
	}
	return FALSE;
}
static char CHAR_N_statusSendBuffer[STRINGBUFSIZ];
/*------------------------------------------------------------
 * ͷʧ˪      ٯ  ë£
 * ¦
 *  charaindex      int     ƽҷ̼
 *  indextable		int 	P ë˪ɷ¶
 *------------------------------------------------------------*/
static char *CHAR_make_N_StatusString( int charaindex, int num, unsigned int indextable )
{
	int		i,j;
	int 	nindex = -1;
	int		ret = 0;
	int		strlength;
	char	buf[64];
	struct {
		unsigned int		kind;
		int		intdataindex;
		int		gettype;
	}chk[] = {
		{ CHAR_N_STRING_OBJINDEX, 	CHAR_WORKOBJINDEX,	1 },
		{ CHAR_N_STRING_LV,		CHAR_


   "it is unreachable from the internet (possibly because of a firewall, or lack of port forwarding)" : "無法透過互聯網聯繫到（可能是防火牆或缺少端口轉發的關繫）",
    "For use cases like this, we offer instructions for a" : "對於這類的使用案例，我們提供了有關",
    "Quick tryout with Nextcloud docker." : "使用 Nextcloud docker 快速試用。",
    "Loading available demo servers …" : "正在載入可用的展示用伺服器……",
    "No available demo servers found." : "找不到可用的展示用伺服器。",
    "Documents opened with the demo server configured will be sent to a 3rd party server. Only use this for evaluating Collabora Online." : "在設定了展示用伺服器的情況下開啟文件會將其傳送給第三方的伺服器。僅將其用於評估 Collabora Online。",
    "Please make sure you understand that the following will happen if you set up the Collabora Online demo." : "請確保您了解如果您設定了 Collabora Online 展示用伺服器的情況下會發生什麼事。",
    "The service will send users documents to Collabora and/or third party demo servers." : "服務會將用戶文件傳送給 Collabora 及／或第三方展示用伺服器。",
    "This service is not intended for production use, hence the documents will show tile watermarks." : "此服務不適用於生產用途，因此文件將會顯示圖磚水印。",
    "The demo service may be under heavy load, and its performance is not representative in any way of the performance of an on-premise installation." : "展示服務可能會處於高度負載的情況，且其效能並不代表內部部署安裝的效能。",
    "These servers are used for testing and development, and may run test versions of the software. As such they may crash, burn, and re-start without warning." : "這些伺服器用於測試與開發，且可能會執行測試版的軟體。因此它們可能會當機、燃燒或在未經警告的情況下重新啟動。",
    "The users documents will not be retained by a third party after their session completes except in exceptional circumstances. By using the service, the user gives permission for Collabora engineers to exceptionally use such document data, solely for the purpose of providing, optimizing and improving Collabora Online. Such document data will remain confidential to Collabora and/or any third party providing a demo server." : "除非在特殊情況下，否則用戶的文件將會在工作階段結束後由第三方保留。使用此服務，即表示用戶同意給予 Collabora 工程師特別使用此類文件資料來提供、最佳化與改善 Collabora Online。Collabora 及／或提供展示用伺服器的第三方會將這類文件資料視為祕密保護。",
    "At the first use and after an update, each user will get the warning, explaining all the above." : "在首次使用與更新後，每個用戶都會收到解釋以上所有資訊的警告。",
    "I agree, and use the demo server" : "我同意，並使用展示用伺服器",
    "I will setup my own server" : "我將會設定我自己的伺服器


 {{ foo }}", { replace: "hello", foo: "world" }),
      "hello world",
    );
  });
});
import { arraySort, camelCase, inArray } from "../utils";
import {
  FieldName,
  IDocumentNode,
  IFieldNode,
  IPackageNode,
  NodeKind,
  IDependency
} from "./ast";

type ParseFn<ParsedValue> = (value: string) => ParsedValue;

export const dependencyParser: ParseFn<IDependency[]> = value => {
  return value
    .split(", ")
    .reduce((dependencies: IDependency[], current: string): IDependency[] => {
      const [name, ...alternates] = current
        .split(" | ")
        .map(v => v.split(" ")[0]);

      return !inArray(dependencies, d => d.name === name)
        ? [...dependencies, { name, alternates }]
        : dependencies;
    }, []);
};

const fieldValueParsers: { [fieldName: string]: ParseFn<any> } = {
  Depends: dependencyParser
};

export default class Parser {
  public parse = (source: string): IDocumentNode => {
    return {
      kind: NodeKind.Document,
      packages: arraySort(
        source.split("\n\n").map(this._parsePackage),
        (a, b) => a.package.value.localeCompare(b.package.value)
      )
    };
  };

  private _parsePackage = (source: string): IPackageNode => {
    const pattern = /^[\w\-]+: (?:.|\n\s)+$/gm;
    const fields = (source.match(pattern) || []).map(this._parseField);

    return {
      kind: NodeKind.Package,
      ...Object.values(FieldName).reduce(
        (
          data: { [fieldName: string]: IFieldNode<any> },
          fieldName: FieldName
        ) => {
          const field = fields.filter(f => f.name === FieldName[fieldName])[0];

          return field ? { [camelCase(fieldName)]: field, ...data } : data;
        },
        {}
      )
    };
  };

  private _parseField = (source: string): IFieldNode<any> => {
    const [fieldName, fieldValue] = source.split(": ");
    const parseFn = fieldValueParsers[fieldName];

    return {
      kind: NodeKind.Field,
      name: fieldName,
      value: parseFn ? parseFn(fieldValue) : fieldValue
    };
  };
}
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { Devices } from '../common/devices';

@Injectable({
  providedIn: 'root'
})

// get deivce list - single device by Id
export class DeviceService {

  // base url for Device entity and search url to get Devices by gateway Id
  baseURL : string = "http://localhost:8080/api/devices/";
  searchURl : string = "search/findAllDevicesByGatewaysId?id=";

  constructor(private httpClient : HttpClient) { }

  // observables of device list - get list of devices and map it
  getDevicesList(id : number) : Observable<Devices[]> {
    const url = `${this.baseURL}${this.searchURl}${id}`;

    return this.httpClient.get<mapDeviceJson>(url).pipe(
      map(indexedDB => indexedDB._embedded.devices)
    )
  }

  // get single device
  getDevice(id : number) : Observable<Devices> {
    const URL : string = `${this.baseURL}${id}`;
    return this.httpClient.get<Devices>(URL);
  }
}

// map the Backend Json Objects to Device list
export interface mapDeviceJson {
  _embedded : {
    devices : Devices[]
  }
}
import { Controller, Param, Body, Get, Post, Put, Delete, NotFoundError } from "routing-contr


#region Copyright (c) 2023-2025 SnowBank SAS, (c) 2005-2023 Doxense SAS
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// 	* Redistributions of source code must retain the above copyright
// 	  notice, this list of conditions and the following disclaimer.
// 	* Redistributions in binary form must reproduce the above copyright
// 	  notice, this list of conditions and the following disclaimer in the
// 	  documentation and/or other materials provided with the distribution.
// 	* Neither the name of SnowBank nor the
// 	  names of its contributors may be used to endorse or promote products
// 	  derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL SNOWBANK SAS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion

// ReSharper disable UnusedTypeParameter
// ReSharper disable MemberHidesStaticFromOuterClass
namespace SnowBank.Runtime.Tests
{
	[TestFixture]
	[Category("Core-SDK")]
	[Parallelizable(ParallelScope.All)]
	public class TypeHelperFacts
	{

		[Test]
		public void Test_GetFr


_platform/features/user/view/widget/empty_chats.dart';
import 'package:telware_cross_platform/core/theme/palette.dart';
import 'package:telware_cross_platform/features/user/view/widget/user_chats.dart';
import 'package:hive/hive.dart';
import 'package:telware_cross_platform/core/models/contact_model.dart';
import 'package:flexible_scrollbar/flexible_scrollbar.dart';
import 'package:telware_cross_platform/features/auth/view/widget/confirmation_dialog.dart';
import 'package:telware_cross_platform/features/user/view_model/user_view_model.dart';

class BlockUserScreen extends ConsumerStatefulWidget {
  static const String route = '/block-user';

  const BlockUserScreen({super.key});

  @override
  ConsumerState<BlockUserScreen> createState() => _BlockUserScreen();
}

class _BlockUserScreen extends ConsumerState<BlockUserScreen>
    with TickerProviderStateMixin {
  final ContactService _contactService = ContactService();
  late List<Map<String, dynamic>> userChats;
  late List<Map<String, dynamic>> userContacts;
  late TabController _tabController;
  final ScrollController scrollController = ScrollController();

  void blockConfirmationDialog(
    String user, {
    String? userId,
    required GlobalKey<State> onConfirmKey,
    required GlobalKey<State> onCancelKey,
  }) {
    showConfirmationDialog(
      context: context,
      title: 'Block user',
      titleFontWeight: FontWeight.bold,
      titleColor: Palette.primaryText,
      titleFontSize: 18.0,
      subtitle: 'Are you sure you want to block $user?',
      subtitleFontWeight: FontWeight.normal,
      subtitleFontSize: 16.0,
      contentGap: 20.0,
      confirmText: 'Block user',
      confirmColor: const Color.fromRGBO(238, 104, 111, 1),
      confirmPadding: const EdgeInsets.only(left: 40.0),
      cancelText: 'Cancel',
      cancelColor: const Color.fromRGBO(100, 181, 239, 1),
      onCancelButtonKey: onCancelKey,
      onConfirmButtonKey: onConfirmKey,
      onConfirm: () {
        // Block the user
        if (userId != null) {
          ref.read(userViewModelProvider.notifier).blockUser(userId: userId);
        }
        context.pop();
        // Close the dialog
        context.pop();
        // Return to Blocked Users screen which is the previous screen.
      },
      onCancel: () => {context.pop()},
      actionsAlignment: MainAxisAlignment.end,
    );
  }

  Future<void> _initializeContacts() async {
    try {
      await _contactService.fetchAndStoreContacts();
      var box = Hive.box<ContactModelBlock>('contacts-block');
      for (var contact in box.values) {
        userContacts[0]["options"].add({
          "text": contact.name,
          "imageMemory": contact.photo,
          "subtext": contact.phone,
        });
      }
      for (var option in userContacts[0]["options"]) {
        option["color"] = Palette.primaryText;
        option["fontSize"] = 15.0;
        option["fontWeight"] = FontWeight.w500;
        option["avatar"] = true;
        option["subtextFontSize"] = 14.0;
        option["imageWidth"] = 47.0;
        option["imageHeight"] = 47.0;
        option["onTap"] = () => blockConfirmationDialog(
              option["text"],
              onConfirmKey:
                  GlobalKeyCategoryManager.addKey('blockContactConfirm'),
              onCancelKey:
                  GlobalKeyCategoryManager.addKey('blockContactCancel'),
            );
      }
      setState(() {});
    } ca


 4), NF, FL.mul(DYE_FLUIDS_FLOWER[DYE_INDEX_Red          ], 1), IL.Remains_Plant.get(1));
		RM.Juicer       .addRecipe1(T, 16,   16,  3000, ST.make(Blocks.red_flower       , 1, 5), NF, FL.mul(DYE_FLUIDS_FLOWER[DYE_INDEX_Orange       ], 1), IL.Remains_Plant.get(1));
		RM.Juicer       .addRecipe1(T, 16,   16,  3000, ST.make(Blocks.red_flower       , 1, 6), NF, FL.mul(DYE_FLUIDS_FLOWER[DYE_INDEX_LightGray    ], 1), IL.Remains_Plant.get(1));
		RM.Juicer       .addRecipe1(T, 16,   16,  3000, ST.make(Blocks.red_flower       , 1, 7), NF, FL.mul(DYE_FLUIDS_FLOWER[DYE_INDEX_Pink         ], 1), IL.Remains_Plant.get(1));
		RM.Juicer       .addRecipe1(T, 16,   16,  3000, ST.make(Blocks.red_flower       , 1, 8), NF, FL.mul(DYE_FLUIDS_FLOWER[DYE_INDEX_LightGray    ], 1), IL.Remains_Plant.get(1));
		RM.Juicer       .addRecipe1(T, 16,   16,  3000, ST.make(Blocks.yellow_flower    , 1, 0), NF, FL.mul(DYE_FLUIDS_FLOWER[DYE_INDEX_Yellow       ], 1), IL.Remains_Plant.get(1));
		RM.Juicer       .addRecipe1(T, 16,   16,  6000, ST.make(Blocks.double_plant     , 1, 1), NF, FL.mul(DYE_FLUIDS_FLOWER[DYE_INDEX_Magenta      ], 2), IL.Remains_Plant.get(1));
		RM.Juicer       .addRecipe1(T, 16,   16,  6000, ST.make(Blocks.double_plant     , 1, 4), NF, FL.mul(DYE_FLUIDS_FLOWER[DYE_INDEX_Red          ], 2), IL.Remains_Plant.get(1));
		RM.Juicer       .addRecipe1(T, 16,   16,  6000, ST.make(Blocks.double_plant     , 1, 5), NF, FL.mul(DYE_FLUIDS_FLOWER[DYE_INDEX_Pink         ], 2), IL.Remains_Plant.get(1));
		RM.Juicer       .addRecipe1(T, 16,   16, 10000, ST.make(Blocks.double_plant     , 1, 0), NF, FL.Oil_Sunflower.make(75), ST.make(Items.dye, 2, 11));
		RM.Juicer       .addRecipe1(T, 16,   16,  9000, ST.make(Blocks.cactus           , 1, W), NF, FL.Juice_Cactus.make(75), IL.Dye_Cactus.get(2));
		RM.Juicer       .addRecipe1(T, 16,   16,  5000, ST.make(Items.reeds             , 1, W), NF, FL.Juice_Reed.make(75), IL.Remains_Plant.get(1));
		RM.Juicer       .addRecipe1(T, 16,   64, 10000, OM.dust(MT.Ice, U9)                    , NF, FL.Ice.make( 111), NI);
		RM.Juicer       .addRecipe1(T, 16,   64, 10000, OM.dust(MT.Ice, U4)                    , NF, FL.Ice.make( 250), NI);
		RM.Juicer       .addRecipe1(T, 16,   64, 10000, OM.dust(MT.Ice)                        , NF, FL.Ice.make(1000), NI);
		RM.Juicer       .addRecipe1(T, 16,   64, 10000, gemChi


auto RestoreHealth = this->m_kill_hp->value;

			auto HeadshotCheck = 1.0f;

			if (Victim->m_bHeadshotKilled)
			{
				this->m_Headshots[Killer->entindex()]++;

				HeadshotCheck = 2.0f;

				if (this->m_kill_hp_hs->value > 0.0f)
				{
					RestoreHealth = this->m_kill_hp_hs->value;
				}
			}

			if (RestoreHealth > 0.0f)
			{
				Killer->edict()->v.health = clamp(Killer->edict()->v.health + RestoreHealth, 1.0f, 100.0f);
			}

			if (this->m_kill_repair_armor->value == HeadshotCheck)
			{
				Killer->edict()->v.armorvalue = 100.0f;
			}

			if (this->m_kill_fade->value == HeadshotCheck)
			{
				gCSDM_Util.ScreenFade(Killer->edict(), BIT(10), BIT(10), 0x0000, 0, 0, 200, 75);
			}

			if (this->m_kill_sound->value == HeadshotCheck)
			{
				g_engfuncs.pfnClientCommand(Killer->edict(), "%s", "speak \"sound/fvox/blip.wav\"\n");
			}

			if (this->m_reload_on_kill->value == HeadshotCheck)
			{
				if (Killer->m_pActiveItem)
				{
					if (Killer->m_pActiveItem->iItemSlot() == PRIMARY_WEAPON_SLOT || Killer->m_pActiveItem->iItemSlot() == PISTOL_SLOT)
					{
						Killer->CSPlayer()->ReloadWeapons(Killer->m_pActiveItem, true, true);
					}
				}
			}

			if (this->m_kill_msg->value)
			{
				auto Value = (int)(Killer->edict()->v.health - (float)(Killer->m_iLastClientHealth));

				if (Value > 0)
				{
					gCSDM_Util.ShowHudMessage(Killer->edict(), gCSDM_Util.SetHudParam(0, 255, 0, -1.0f, 0.8f, 0, 1.0f, 1.0f, 0.0f, 0.0f, 1), "+%d HP", Value);
				}
			}
		}
	}
}

void CCSDM_Misc::UpdateClientData(CBasePlayer* Player, bool Reset)
{
	if (Player->IsPlayer())
	{
		if (Reset || (Player->edict()->v.frags == 0.0f))
		{
			this->m_Headshots[Player->entindex()] = 0;
		}

		if (!Player->IsBot())
		{
			if (Player->m_iTeam == TERRORIST || Player->m_iTeam == CT)
			{
				if (this->m_kd_ratio_hud->value)
				{
					static float NextTime;

					if (gpGlobals->time > NextTime)
					{
						auto KD_Ratio = 0.0f;

						auto HS_Ratio = 0.0f;

						if (Player->edict()->v.frags > 0.0f)
						{
							KD_Ratio = (Player->m_iDeaths > 0) ? (1.0f * (Player->edict()->v.frags / static_cast<float>(Player->m_iDeaths))) : (1.0f * Player->edict()->v.frags);

							HS_Ratio = 100.0f * (static_cast<float>(this->m_Headshots[Player->entindex()]) / Player->edict()->v.frags);
						}

						gCSDM_Util.ShowHudMessage(Player->edict(), gCSDM_Util.SetHudParam(0, 255, 0, -1.0f, 0.01f, 0, 2.1f, 2.1f, 0.0f, 0.0f, 2), "K/D: %.2f - HS: %.2f%%",


   let unvote_2_request = ExecuteRequestBuilder::standard(
        ACCOUNT_2_ADDR,
        CONTRACT_POS_VOTE,
        (String::from(UNVOTE_METHOD), DAPP_1_ADDR, None::<U512>),
    )
    .build();

    let mut builder = InMemoryWasmTestBuilder::from_result(result);
    let _ = builder
        .exec(unvote_1_request)
        .expect_success()
        .commit()
        .exec(unvote_2_request)
        .expect_success()
        .commit()
        .finish();

    // #8 assert voted amount of DAPP_1
    assert_voted_amount(&pop_uref, &DAPP_1_ADDR, U512::zero(), &builder);
    assert_voting_amount(&pop_uref, &ACCOUNT_1_ADDR, U512::zero(), &builder);
    assert_voting_amount(&pop_uref, &ACCOUNT_2_ADDR, U512::zero(), &builder);
}

#[ignore]
#[test]
fn should_fail_to_vote_more_than_bonded() {
    let bond_amount = U512::from(1000);
    let vote_amount = U512::from(1001);
    let dapp_addr = Key::Hash([11u8; 32]);

    let bond_request = ExecuteRequestBuilder::standard(
        DEFAULT_ACCOUNT_ADDR,
        CONTRACT_POS_VOTE,
        (String::from(BOND_METHOD), bond_amount),
    )
    .build();
    let vote_request = ExecuteRequestBuilder::standard(
        DEFAULT_ACCOUNT_ADDR,
        CONTRACT_POS_VOTE,
        (String::from(VOTE_METHOD), dapp_addr, vote_amount),
    )
    .build();

    let mut builder = InMemoryWasmTestBuilder::default();
    let result = builder
        .run_genesis(&DEFAULT_GENESIS_CONFIG)
        .exec(bond_request)
        .expect_success()
        .commit()
        .exec(vote_request)
        .commit()
        .finish();

    let response = result
        .builder()
        .get_exec_response(1)
        .expect("should have a response")
        .to_owned();

    let error_message = utils::get_error_message(response);

    // pos::Error::VoteTooLarge => 38
    assert!(error_message.contains(&format!(
        "Revert({})",
        u32::from(ApiError::ProofOfStake(38))
    )));
}
<gh_stars>0
#[derive(Clone, Default, Debug)]
pub struct PageMargins {
    left: f32,
    right: f32,
    top: f32,
    bottom: f32,
    header: f32,
    footer: f32,
}
impl PageMargins {
    pub fn get_left(&self)-> &f32 {
        &self.left
    }
    pub(crate) fn set_left(&mut self, value:f32) {
        self.left = value;
    }
    pub fn get_right(&self)-> &f32 {
        &self.right
    }
    pub(crate) fn set_right(&mut self, value:f32) {
        self.right = value;
    }
    pub fn get_top(&self)-> &f32 {
        &self.top
    }
    pub(crate) fn set_top(&mut self, value:f32) {
        self.top = value;
    }
    pub fn get_bottom(&self)-> &f32 {
        &self.bottom
    }
    pub(crate) fn set_bottom(&mut self, value:f32) {
        self.bottom = value;
    }
    pub fn get_header(&self)-> &f32 {
        &self.header
    }
    pub(crate) fn set_header(&mut self, value:f32) {
        self.header = value;
    }
    pub fn get_footer(&self)-> &f32


/* UNCHECKED */ MCStringAppend(t_buffer, p_locale -> weekday_names[t_dayofweek - 1]); break; // Full day of week
			case 'b': /* UNCHECKED */ MCStringAppend(t_buffer, p_locale -> abbrev_month_names[t_month - 1]); break; // Abbreviated month
			case 'B': /* UNCHECKED */ MCStringAppend(t_buffer, p_locale -> month_names[t_month - 1]); break; // Full month
			case 'w': /* UNCHECKED */ MCStringAppendFormat(t_buffer, "%d", t_dayofweek); break; // Day of week
			case 'd': /* UNCHECKED */ MCStringAppendFormat(t_buffer, t_pad ? "%02d" : "%d", t_day); break; // Day of month
			case 'm': /* UNCHECKED */ MCStringAppendFormat(t_buffer, t_pad ? "%02d" : "%d", t_month); break; // Month of year
			case 'y': /* UNCHECKED */ MCStringAppendFormat(t_buffer, t_pad ? "%02d" : "%d", t_year % 100); break; // 2-digit year
			case 'Y': /* UNCHECKED */ MCStringAppendFormat(t_buffer, t_pad ? "%04d" : "%d", t_year); break; // 4-digit year
			case 'I': /* UNCHECKED */ MCStringAppendFormat(t_buffer, t_pad ? "%02d" : "%d", (t_hour % 12) == 0 ? 12 : t_hour % 12); break; // 12-hour hour
			case 'J': /* UNCHECKED */ MCStringAppendFormat(t_buffer, t_pad ? "%02d" : "%d", t_hour % 12); break; // 12-hour 0-based hour
			case 'H': /* UNCHECKED */ MCStringAppendFormat(t_buffer, t_pad ? "%02d" : "%d", t_hour); break; // 24-hour hour
			case 'M': /* UNCHECKED */ MCStringAppendFormat(t_buffer, t_pad ? "%02d" : "%d", t_minute); break; // minutes
			case 'S': /* UNCHECKED */ MCStringAppendFormat(t_buffer, t_pad ? "%02d" : "%d", t_second); break; // seconds
			case 'p': /* UNCHECKED */ MCStringAppend(t_buffer, t_hour < 12 ? p_locale -> time_morning_suffix : p_locale -> time_evening_suffix); break; // 12-hour identifier
			case 'z': /* UNCHECKED */ MCStringAppendFormat(t_buffer, "%+05d", (t_bias / 60) * 100 + t_bias % 60); break; // timezone
			case '%': /* UNCHECKED */ MCStringAppendChar(t_buffer, '%'); break;
			}
		}
		else
			/* UNCHECKED */ MCStringAppendChar(t_buffer, t_char);

		t_char = MCStringGetCharAtIndex(p_format, t_offset++);
	}

	/* UNCHECKED */ MCStringCopyAndRelease(t_buffer, r_buffer);
}

static inline void datetime_normalize_value(int4 p_minimum, int4 p_maximum, int4& x_value, int4& x_overflow)
{
	while(x_value < p_minimum)
	{
		x_value += (p_maximum - p_minimum);
		x_overflow -= 1;
	}

	while(x_value >= p_maximum)
	{
		x_value -= (p_maximum - p_minimum);
		x_overflow += 1;
	}
}

static inline bool datetime_get_gregorian_leap_year(int4 p_year)
{
	return ((p_year & 0x3) == 0) && ((p_year % 100) != 0 || (p_year % 400) == 0);
}

static void datetime_normalize(MCDateTime& x_datetime