content
stringlengths
5
1.05M
local DEPOSIT_TRIGGER = script:GetCustomProperty("DepositTrigger"):WaitForObject() local players = Game.GetPlayers() -- function OnBeginOverlap(trigger, player) -- if (not player or not player:IsA("Player")) then -- return -- end -- if trigger.name == "LobbyZone" then -- --player:SetResource("OutsideLobby", 0) -- --player:AddResource("PermStorage", player:GetResource("Coins")) -- --permanentStorage = permanentStorage + player:GetResource("TempStorage") -- --player:SetResource("Coins", player:GetResource("PermStorage")) -- elseif trigger.name == "GameZone" then -- --outsideLobby = true -- --player:SetResource("TempStorage", 0) -- player:SetResource("Coins", 0) -- --player:SetResource("OutsideLobby", 1) -- end -- end -- function OnPlayerJoined(player) -- --player:SetResource("PermStorage", player:GetResource("Coins")) -- if ZONE_1:IsOverlapping(player) then -- OnBeginOverlap(ZONE_1, player) -- end -- end function OnInteracted(trigger, player) local permStorage = player:GetResource("Bank") player:AddResource("Bank", player:GetResource("Bag")) player:SetResource("Bag", 0) --print(player:GetResource("PermStorage")) end --ZONE_1.beginOverlapEvent:Connect(OnBeginOverlap) DEPOSIT_TRIGGER.interactedEvent:Connect(OnInteracted) --ZONE_2.beginOverlapEvent:Connect(OnBeginOverlap) --Game.playerJoinedEvent:Connect(OnPlayerJoined)
local utils = require('d2grailcheck.utils') local Data = require('d2grailcheck.data') local Checker = require('d2grailcheck.checker') local argparse = require('d2grailcheck.argparse') local formats = { ["simple"] = require('d2grailcheck.formats.simple'), ["d2-holy-grail"] = require('d2grailcheck.formats.d2-holy-grail'), } local DEFAULT_GAME_DIR = { "C:/Program Files (x86)/Diablo II/", "C:/Program Files/Diablo II/" } local parser = argparse() parser:option('-g --game-dir', "Path to Diablo II game directory", DEFAULT_GAME_DIR) :argname('<path>') :convert(function(path) if not utils.pathexists(path) then return nil, "Game directory not found: "..path end return path end) parser:option('-s --save-dir', "Path to Diablo II save directory") :argname('<path>') :convert(function(path) if not utils.pathexists(path) then return nil, "Save directory not found: "..path end return path end) parser:require_command(false):command_target('format') local simpleCmd = parser:command('simple') local dhgCmd = parser:command('d2-holy-grail dhg') dhgCmd:argument("username") dhgCmd:argument("password") local args = parser:parse() -- Get/validate format if not args.format then args.format = "simple" end -- Get/validate game and save directories if type(args.game_dir) == "table" then for _, dir in ipairs(args.game_dir) do if utils.pathexists(dir) then args.game_dir = dir break end end end if type(args.game_dir) ~= "string" then parser:error("Game directory not found, tried:\n "..table.concat(args.game_dir, "\n ")) end print("Game Directory: "..args.game_dir) if not args.save_dir then local dir = utils.guessSaveDir(args.game_dir) assert(dir, "Failed to guess save directory from game directory") assert(utils.pathexists(dir), "Guessed save directory does not exist: "..dir) args.save_dir = dir end print("Save Directory: "..args.save_dir) -- Main logic local luv = require('luv') coroutine.wrap(function() print("\nLoading items...") local items = assert(utils.getItemsInDirectory(args.save_dir)) print("Loading data...") local data = Data.new(args.game_dir) print("Checking grail...") local checker = Checker.new(data, items, args) print("Formatting...") local formatter = formats[args.format] local output = formatter(checker) print("") if args.format == "d2-holy-grail" then print("Preparing to sync with d2-holy-grail...") local json = require('d2grailcheck.dkjson') package.path = "./deps/?.lua;./deps/?/init.lua;" .. package.path local http = require('coro-http-luv') local endpoint = "https://d2-holy-grail.herokuapp.com/api/grail/"..args.username -- this is a bit silly, but this will fail and provide us with a -- valid token with the minimal amount of data being sent to/from the server print("Getting token...") local res, body = http.request('PUT', endpoint.."/settings", { {"Content-Type", "application/json"}, {"Referer", "https://d2-holy-grail.herokuapp.com/"..args.username}, }, json.encode({ password=args.password, settings={}, token="", })) local jsonBody = json.decode(body) assert(not jsonBody or jsonBody.type ~= "password", "Incorrect password:\n"..args.password.."\n(note: you might need to escape special characters)") assert(jsonBody and jsonBody.type == "token", "Unexpected response from server (code="..res.code.."):\n\n"..body.."\n") local token = jsonBody.correctToken local putData = output:gsub("$TOKEN", token) print("Syncing data with server...") res, body = http.request('PUT', endpoint, { {"Content-Type", "application/json"}, {"Referer", "https://d2-holy-grail.herokuapp.com/"..args.username}, }, putData) assert(res and res.code == 200, "Unexpected response from server (code="..res.code.."):\n\n"..body.."\n") print("Updated: https://d2-holy-grail.herokuapp.com/"..args.username) else print(output) end end)() luv.run()
CloneClass( PlayerInventoryGui ) --[[ Temporary until PlayerInventoryGui decides to decrypt fully instead of stopping half way through the initialization function ]] Hooks:RegisterHook("PlayerInventoryGUIOnPreviewPrimary") function PlayerInventoryGui.preview_primary(self, ...) local args = ... local r = Hooks:ReturnCall("PlayerInventoryGUIOnPreviewPrimary", self, args) if r ~= nil then return r end self.orig.preview_primary(self, ...) end Hooks:RegisterHook("PlayerInventoryGUIOnPreviewSecondary") function PlayerInventoryGui.preview_secondary(self, ...) local args = ... local r = Hooks:ReturnCall("PlayerInventoryGUIOnPreviewSecondary", self, args) if r ~= nil then return r end self.orig.preview_secondary(self, ...) end Hooks:RegisterHook("PlayerInventoryGUIOnPreviewMelee") function PlayerInventoryGui.preview_melee(self, ...) local args = ... local r = Hooks:ReturnCall("PlayerInventoryGUIOnPreviewMelee", self, args) if r ~= nil then return r end self.orig.preview_melee(self, ...) end Hooks:RegisterHook("PlayerInventoryGUIOnOpenWeaponModMenu") function PlayerInventoryGui.open_weapon_mod_menu(self, box) BlackMarketGui._choose_weapon_mods_callback(self, box.params.mod_data) end
ClassicLFG = LibStub("AceAddon-3.0"):NewAddon("ClassicLFG", "AceConsole-3.0") ClassicLFG.AceGUI = LibStub("AceGUI-3.0") ClassicLFG.Locale = LibStub("AceLocale-3.0"):GetLocale("ClassicLFG") ClassicLFG.MinimapIcon = LibStub("LibDBIcon-1.0") GetTalentTabInfo = GetTalentTabInfo or function(index) return "Assasination", nil, math.random(1,10), "RogueAssasination" end ClassicLFG.DefaultProfile ={ profile = { minimap = { hide = false, }, InviteText = "invite please", BroadcastDungeonGroupInterval = 90, BroadcastDungeonGroupChannel = "General", ShowAllDungeons = false, AutoAcceptInvite = false, InviteKeyword = "inv", AutoInvite = false, ShowMinimapIcon = true, BroadcastDungeonGroup = true, Toast = { Enabled = true, X = GetScreenWidth() / 2 - 260 / 2, Y = (GetScreenHeight() / 4) * -1, } }, } function ClassicLFG:OnEnable() ClassicLFG.ChannelManager:UpdateChannels() end local f = CreateFrame('Frame') f.joined = false f:SetScript('OnUpdate', function(self, elapsed) self.delayed = (self.delayed or 0) + elapsed if self.delayed > 2 then local numActiveChannels = C_ChatInfo.GetNumActiveChannels() if numActiveChannels and (numActiveChannels >= 1) and self.joined == false then if numActiveChannels < MAX_WOW_CHAT_CHANNELS then JoinChannelByName(ClassicLFG.Config.Network.Channel.Name, nil, nil, true) self.joined = true local channels = { GetChannelList() } local i = 2 while i < #channels do if (channels[i] == ClassicLFG.Config.Network.Channel.Name) then ClassicLFG.Config.Network.Channel.Id = channels[i - 1] end i = i + 3 end ClassicLFG.Network:SendObject(ClassicLFG.Config.Events.RequestData, "RequestGroupData", "CHANNEL", ClassicLFG.Config.Network.Channel.Id) ClassicLFG.Network:SendObject(ClassicLFG.Config.Events.VersionCheck, ClassicLFG.Config.Version, "CHANNEL", ClassicLFG.Config.Network.Channel.Id) self:SetScript('OnUpdate', nil) end end elseif self.delayed > 45 then self:SetScript('OnUpdate', nil) end end) function ClassicLFG:OnInitialize() self.DB = LibStub("AceDB-3.0"):New("ClassicLFG_DB", self.DefaultProfile) local iconPath = ([[Interface\Addons\%s\%s\%s]]):format("ClassicLFG", "textures", "inv_misc_groupneedmore") self.LDB = LibStub("LibDataBroker-1.1"):NewDataObject("ClassicLFG_LDB", { type = "launcher", text = "ClassicLFG_LDB", icon = iconPath, OnClick = self.MinimapIconClick, OnTooltipShow = self.MinimapTooltip, }) self.MinimapIcon:Register("ClassicLFG_LDB", self.LDB, self.DB.profile.minimap) self:RegisterChatCommand("lfg", "MinimapIconClick") self:RegisterChatCommand("classiclfg", "MinimapIconClick") self:RegisterChatCommand("clfg", "MinimapIconClick") local initialState = self:GetInitialState() initialState.Db = self.DB self.Store:SetState(self:DeepCopy(initialState)) self.Store:GetState().Db = self.DB self.Initialized = true self.ToastManager = ClassicLFGToastManager() end function ClassicLFG:GetInitialState() return { MainWindowOpen = false, NetworkObjectsSend = 0, NetworkPackagesSend = 0, DungeonGroupQueued = false, DungeonGroup = nil, Db = nil, Player = { Level = UnitLevel("player") }, ShareTalents = true } end function ClassicLFG:InitMInimapIcon() if self.DB.profile.minimap.hide then self.MinimapIcon:Hide("ClassicLFG_LDB") else self.MinimapIcon:Show("ClassicLFG_LDB") end end function ClassicLFG:MinimapIconClick() ClassicLFG.Store:PublishAction(ClassicLFG.Actions.ToggleMainWindow) end function ClassicLFG:Reset() self.Store:SetState(self.InitialState) end function ClassicLFG.MinimapTooltip(tooltip) if not tooltip or not tooltip.AddLine then return end tooltip:AddLine("ClassicLFG") tooltip:AddLine(ClassicLFG.Locale["Leftclick: Open LFG Browser"]) end
---------------------------------------------------------------------------------------------------- -- -- Copyright (c) Contributors to the Open 3D Engine Project. -- For complete copyright and license terms please see the LICENSE at the root of this distribution. -- -- SPDX-License-Identifier: Apache-2.0 OR MIT -- -- -- ---------------------------------------------------------------------------------------------------- g_screenshotOutputFolder = ResolvePath('@user@/Scripts/Screenshots/Readback') Print('Saving screenshots to ' .. NormalizePath(g_screenshotOutputFolder)) OpenSample('RPI/Readback') SelectImageComparisonToleranceLevel("Level H") SetShowImGui(false) -- First capture at 512x512 ResizeViewport(512, 512) SetImguiValue('Width', 512) SetImguiValue('Height', 512) IdleFrames(1) SetImguiValue('Readback', true) IdleFrames(5) CaptureScreenshot(g_screenshotOutputFolder .. '/screenshot_1.png') IdleFrames(1) -- Then at 1024x1024 ResizeViewport(1024, 1024) SetImguiValue('Width', 1024) SetImguiValue('Height', 1024) IdleFrames(1) SetImguiValue('Readback', true) IdleFrames(5) CaptureScreenshot(g_screenshotOutputFolder .. '/screenshot_2.png') IdleFrames(1) SetShowImGui(true) OpenSample(nil)
module 'mock' CLASS: ScriptedFSMController ( FSMController ) :MODEL{ Field 'script' :asset( 'com_script' ) :getset( 'Script' ); } registerComponent( 'ScriptedFSMController', ScriptedFSMController ) function ScriptedFSMController:__init() self.scriptPath = false self.delegate = false self.dataInstance = false end function ScriptedFSMController:getScript() return self.scriptPath end function ScriptedFSMController:setScript( path ) self.scriptPath = path self:updateComponentScript() end function ScriptedFSMController:updateComponentScript() local path = self.scriptPath local scriptObj = loadAsset( path ) local delegate, dataInstance for k, v in pairs( self ) do --clear collected method if k:startwith( '_FSM_' ) then self[ k ] = false end end if scriptObj then local fsmCollector = FSMController.__createStateMethodCollector( self ) delegate, dataInstance = scriptObj:buildInstance( self, { fsm = fsmCollector } ) end local prevInstance = self.dataInstance self.delegate = delegate or false self.dataInstance = dataInstance or false if prevInstance and dataInstance then _cloneObject( prevInstance, dataInstance ) end end function ScriptedFSMController:onStart( ent ) --Update delegate local delegate = self.delegate if delegate then --insert global variables delegate.entity = ent -- delegate.scene = ent:getScene() local onStart = delegate.onStart if onStart then onStart() end self.onThread = delegate.onThread local onMsg = delegate.onMsg if onMsg then self.msgListener = onMsg ent:addMsgListener( self.msgListener ) end if delegate.onUpdate then ent.scene:addUpdateListener( self ) end end return FSMController.onStart( self, ent ) end function ScriptedFSMController:onUpdate( dt ) return self.delegate.onUpdate( dt ) end function ScriptedFSMController:onDetach( ent ) if self.delegate then local onDetach = self.delegate.onDetach if onDetach then onDetach( ent ) end if self.msgListener then ent:removeMsgListener( self.msgListener ) end ent.scene:removeUpdateListener( self ) end end function ScriptedFSMController:installInputListener( option ) return installInputListener( self.delegate, option ) end function ScriptedFSMController:uninstallInputListener() return uninstallInputListener( self.delegate ) end function ScriptedFSMController:__serialize( objMap ) local dataInstance = self.dataInstance if not dataInstance then return end return _serializeObject( dataInstance, objMap ) end function ScriptedFSMController:__deserialize( data, objMap ) if not data then return end local dataInstance = self.dataInstance if not dataInstance then return end return _deserializeObject( dataInstance, data, objMap ) end function ScriptedFSMController:__clone( src, objMap ) local dataInstance = self.dataInstance if not dataInstance then return end return _cloneObject( src, dataInstance, objMap ) end
----------------------------------------------------------------------------------------------- -- Client Lua Script for Builder -- Copyright (c) NCsoft. All rights reserved ----------------------------------------------------------------------------------------------- require "Window" require "Apollo" require "GameLib" require "MacrosLib" ----------------------------------------------------------------------------------------------- -- Builder Module Definition ----------------------------------------------------------------------------------------------- local Builder = {} ----------------------------------------------------------------------------------------------- -- Localisation ----------------------------------------------------------------------------------------------- local L = Apollo.GetPackage("Gemini:Locale-1.0").tPackage:GetLocale("Builder", true) ----------------------------------------------------------------------------------------------- -- Constants ----------------------------------------------------------------------------------------------- local cAddons = { abilities = {[1] = "Abilities", } } HSColor = {Blue = 0, Black = 1, Green = 2 } ----------------------------------------------------------------------------------------------- -- Initialization ----------------------------------------------------------------------------------------------- function Builder:new(o) o = o or {} setmetatable(o, self) self.__index = self self.majorVersion = 0 self.minorVersion = 4 self.patchVersion = 6 self.suffixVersion = 0 -- 0 = Rien 1 = a self.versionLetter = "" self.version = "v" .. string.format("%d.%d.%d", self.majorVersion, self.minorVersion, self.patchVersion) .. self.versionLetter self.author = "YellowKiwi" self.addonName = "Builder" self.builds = {} self:DefaultConfig() return o end function Builder:Init() local bHasConfigureFunction = false local strConfigureButtonText = "" local tDependencies = { -- "UnitOrPackageName", } Apollo.RegisterAddon(self, bHasConfigureFunction, strConfigureButtonText, tDependencies) end ----------------------------------------------------------------------------------------------- -- Builder OnLoad ----------------------------------------------------------------------------------------------- function Builder:OnLoad() -- load our form file self.xmlDoc = XmlDoc.CreateFromFile("Builder.xml") self.xmlConfigDoc = XmlDoc.CreateFromFile("BuilderConfig.xml") Apollo.LoadSprites("BuilderSprites.xml") self.xmlDoc:RegisterCallback("OnDocumentReady", self) end function Builder:OnDocumentReady() if self.xmlDoc == nil or not self.xmlDoc:IsLoaded() then return end Apollo.RegisterEventHandler("WindowManagementReady", "OnWindowManagementReady", self) Apollo.RegisterEventHandler("InterfaceMenuListHasLoaded", "OnInterfaceMenuListHasLoaded", self) Apollo.RegisterEventHandler("Builder_Show", "OnBuilderOn", self) --Gear Hook Event Apollo.RegisterEventHandler("Generic_GEAR_UPDATE", "OnGearUpdate", self) --This is need because AMP Abilites unlock Apollo.RegisterEventHandler("SpecChanged", "OnAMPPageChanged", self) self.hasGear = self:IsGearLoaded() Apollo.RegisterEventHandler("GenericBuilderUpdate", "OnBuilderUpdate", self) --TODO Message Gear not decteced if not self.hasGear then self.currentGearId = 0 end end function Builder:OnWindowManagementReady() Apollo.RegisterSlashCommand("builder", "OnBuilderSlash", self) self:InitUI() end function Builder:OnBuilderOn() if self.wndMain:IsShown() then self.wndMain:Close() else self:RestoreAllBuilds() self.wndMain:Invoke() Event_FireGenericEvent("Generic_GEAR_UPDATE", "G_GETGEAR", nil, nil, nil) end end function Builder:OnBuilderSlash(strCommand, strBuildName) if strBuildName ~= nil and strBuildName ~= '' then -- Find if the build exist local predicate = function(b) return b.name == strBuildName end local buildId = self:TableFind(self.builds, predicate, true) if buildId ~= nil then --self:UpdateBuildWithId(buildId, true) -- call from builder to equip self.changeGear = true self:UpdateBuildWithId(buildId) self.currentBuild = buildId self:UpdateHotSwap() else Print(L["MACROERROR"] .. strBuildName) end else -- /builder without buildName self:OnBuilderOn() end end function Builder:InitUI() self.wndMain = Apollo.LoadForm(self.xmlDoc, "BuilderForm", nil, self) self.wndOverwrite = Apollo.LoadForm(self.xmlDoc, "OverwritePopUp", nil, self) if self.wndMain == nil then Apollo.AddAddonErrorText(self, L["MAINERROR"]) return end self.wndMain:Show(false, true) self.wndOverwrite:Show(false,true) if self.config ~= nil then if self.config.mainWindowOffset and self.config.mainWindowOffset ~= nil then self.wndMain:SetAnchorOffsets(unpack(self.config.mainWindowOffset)) end end -- Localisation self.wndMain:FindChild("BuilderPanel:TopPanel:btnCreate"):SetText(L["CREATENEW"]) self.btnOverwriteBuild = self.wndMain:FindChild("BuilderPanel:TopPanel:btnOverwrite") self.btnOverwriteBuild:SetTooltip(L["OVERWRITE"]) self:ToggleOverwriteButton() self:HotSwapInit() --Capture Build Change Apollo.RegisterEventHandler("SpecChanged", "OnAbilityChangedEvent", self) Apollo.RegisterEventHandler("StanceChanged", "OnStanceChange", self) Apollo.RegisterEventHandler("AbilityWindowHasBeenToggled", "OnAbilityWindowToggled", self) --Apollo.RegisterEventHandler("GenericEvent_OpenEldanAugmentation", "OnAbilityChangedEvent", self) --Apollo.RegisterEventHandler("InterfaceMenuList_AlertAddOn", "OnAbilityChangedEvent", self) Apollo.RegisterEventHandler("ToggleBlockBarsVisibility","OnToggleBars",self) Apollo.RegisterEventHandler("UnitEnteredCombat", "OnEnteredCombat", self) Apollo.RegisterEventHandler("PlayerResurrected", "OnResurrected", self) Event_FireGenericEvent("Generic_GEAR_UPDATE", "G_GETGEAR", nil, nil, nil) self.abilitiesAddon = Apollo.GetAddon("Abilities") end -- ############################################################################################################################## -- REGION : Main Panel -- ############################################################################################################################## ------------------------------ -- User Interface ------------------------------ function Builder:DrawBuildItem(nBuildId) local newBuildItem = nil if self.config.useTag then newBuildItem = Apollo.LoadForm(self.xmlDoc,"BuildTagTemplateFrame", self.lstBuilds, self) local tagDropDown = newBuildItem:FindChild("btnDropDownTag") if self.builds[nBuildId].tagId == nil or self.builds[nBuildId].tagId == 0 then tagDropDown:SetText(L["NONE"]) else tagDropDown:SetText(self.config.tags[self.builds[nBuildId].tagId]) end else newBuildItem = Apollo.LoadForm(self.xmlDoc, "BuildTemplateFrame", self.lstBuilds, self) end local sBuildName = self.builds[nBuildId].name if sBuildName == nil then sBuildName = self:SetBuildName(nil, nBuildId) end newBuildItem:FindChild("btnUse"):SetTooltip(L["USEBUILD"] .. sBuildName .. L["CREATEMACRO"]) newBuildItem:SetData(nBuildId) newBuildItem:SetName("build_" .. nBuildId) local txtBuildName = newBuildItem:FindChild("txtBuildName") txtBuildName:SetMaxTextLength(40) txtBuildName:SetTextRaw(sBuildName); if nBuildId == self.currentBuild then txtBuildName:SetTextColor("AddonOk") -- TODO Maybe do something with the use button else txtBuildName:SetTextColor("white") end self.lstBuilds:ArrangeChildrenVert() end function Builder:DrawDetailPanel(buildId, fraTemplate) local detailFrame = fraTemplate:FindChild("DetailFrame") local detailContainer = Apollo.LoadForm(self.xmlDoc, "DetailContainer", detailFrame, self) detailContainer:SetData(buildId) self:DrawBuildDetail(self.builds[buildId],detailContainer,false) end function Builder:RedrawCurrentBuildPanel() if self.currentLAS ~= nil then self.currentLAS:DestroyChildren() end self.currentLAS = self.wndMain:FindChild("BuilderPanel:TopPanel:CurrentLAS") local currentLASFrame = Apollo.LoadForm(self.xmlDoc, "DetailContainer", self.currentLAS, self) local currentLASBuild = self:GetCurrentLAS() self:DrawBuildDetail(currentLASBuild, currentLASFrame, true) if self:IsAbilitiesOpen() then self.wndMain:FindChild("BuilderPanel:TopPanel:EditingBackground"):Show(true,true) else self.wndMain:FindChild("BuilderPanel:TopPanel:EditingBackground"):Show(false,true) end if self:DetectBuildChange() then self.wndMain:FindChild("BuilderPanel:TopPanel:btnOverwrite"):Show(true,true) else self.wndMain:FindChild("BuilderPanel:TopPanel:btnOverwrite"):Show(false,true) end end function Builder:DrawBuildDetail(build, detailContainer, isCurrentLAS) if build ~= nil then -- Innnate Ability local innateIcon = detailContainer:FindChild("InnateIcon") local nSpell = GameLib.GetClassInnateAbilitySpells().nSpellCount if nSpell >= 2 then nSpell = 2 end innateIcon:SetSprite(GameLib.GetClassInnateAbilitySpells().tSpells[build.innateIndex * nSpell]:GetIcon()) -- Abilites local actionBarContainer = detailContainer:FindChild("ActionBarContainer") for idx = 1, 8 do local currentSlot = Apollo.LoadForm(self.xmlDoc, "BuildItem", actionBarContainer, self) currentSlot:SetData(idx) local abilityCase = currentSlot:FindChild("AbilityCase") local abilityId = build.abilities[idx] abilityCase:SetAbilityId(abilityId) local txtTier = currentSlot:FindChild("TierText") local tier = build.abilitiesTiers[abilityId] local tierText = L["BASE"] if tier > 1 then tier = tier - 1 tierText = L["TIER"] .. tier end txtTier:SetText(tierText) end actionBarContainer:ArrangeChildrenHorz(0) --AMP Page detailContainer:FindChild("AmpPage"):SetText(L["ACTIONSET"] .. build.actionSetIndex) --Gear local gearSet = detailContainer:FindChild("GearSet") local btnGearSet = detailContainer:FindChild("btnDropDownGear") gearSet:Show(false,false) btnGearSet:Show(false,false) if self.hasGear then if isCurrentLAS then gearSet:Show(true,true) local gearText = "" if self.gearSets == nil then gearText = L["NOEQUIPMENT"] elseif self.currentGearId == 0 or self.currentGearId == nil then gearText = L["NOTSET"] else gearText = self.gearSets[self.currentGearId].name end gearSet:SetText(gearText) else local gearText = "" btnGearSet:Show(true,true) if build.gearId == 0 or build.gearId == nil then gearText = L["NONE"] else if self.gearSets ~= nil then gearText = self.gearSets[build.gearId].name else gearText = L["NONE"] end end btnGearSet:SetText(gearText) end end end end function Builder:EraseDetailPanel(fraTemplate) local detailFrame = fraTemplate:FindChild("DetailFrame") detailFrame:DestroyChildren() end function Builder:UpdateBuildList() self.lstBuilds = self.wndMain:FindChild("BuilderPanel:BuildsList") self.lstBuilds:DestroyChildren() for i, peCurrent in pairs(self.builds) do self:DrawBuildItem(i) end end function Builder:RestoreAllBuilds() self:RedrawCurrentBuildPanel() self:UpdateBuildList() end ------------------------------ -- UI EVENTS ------------------------------ function Builder:OnCheckDetails( wndHandler, wndControl, eMouseButton ) local nBuildId = wndControl:GetParent():GetData() local fraTemplate = wndControl:GetParent() local width = fraTemplate:GetWidth() local l,t,r,b = fraTemplate:GetAnchorOffsets() local height = 45 if wndControl:IsChecked() then height = 137 self:DrawDetailPanel(nBuildId, fraTemplate) else self:EraseDetailPanel(fraTemplate) end fraTemplate:Move(l, t, width, height) self.lstBuilds:ArrangeChildrenVert() end function Builder:OnBuildNameConfirm(wndHandler, wndControl, strText) local nBuildId = wndControl:GetParent():GetData() local newName = strText:match("^%s*(.-)%s*$") local oldName = self.builds[nBuildId].name if newName == oldName then return end local buildName = self:SetBuildName(strText, nBuildId) wndControl:SetTextRaw(buildName) --Rename Macro if(self.builds[nBuildId].macro ~= nil) then local macro = MacrosLib.GetMacro(self.builds[nBuildId].macro) if macro then local tParam = { sName = "Builder - " .. newName, sSprite = macro.strSprite, sCmds = "/builder " .. newName, bGlobal = macro.bIsGlobal, nId = macro.nId, } self:SaveMacro(tParam) end end -- Send Generic Event Event_FireGenericEvent("GenericBuilderUpdate","B_RENAME", nBuildId, self.builds) self:UpdateHotSwap() self:UpdateBuildList() end function Builder:OnCreateNewBuild(wndHandler, wndControl, eMouseButton) local buildToSave = self:GetCurrentLAS() local nBuildId = self:SaveBuild(buildToSave,nil) self.currentBuild = nBuildId self:UpdateBuildList() self:UpdateHotSwap() Event_FireGenericEvent("GenericBuilderUpdate", "B_CREATE", nBuildId, self.builds) end function Builder:OnDeleteBuild(wndHandler, wndControl, eMouseButton) if eMouseButton == 0 then local nBuildId = wndControl:GetParent():GetData() --Delete Macro if(self.builds[nBuildId].macro ~= nil) then local macro = MacrosLib.GetMacro(self.builds[nBuildId].macro) if macro then self:DeleteMacro(self.builds[nBuildId].macro) end end self:DeleteBuild(nBuildId); Event_FireGenericEvent("GenericBuilderUpdate", "B_DELETE", nBuildId, self.builds) end end function Builder:OnUseBuild(wndHandler, wndControl, eMouseButton) if eMouseButton == GameLib.CodeEnumInputMouse.Left then local nBuildId = wndControl:GetParent():GetData() --self:UpdateBuildWithId(nBuildId, true) -- call from builder to equip self.changeGear = true self:UpdateBuildWithId(nBuildId) Event_FireGenericEvent("GenericBuilderUpdate", "B_USE", self.currentBuild, self.builds) end end function Builder:OnMoveBuildUp( wndHandler, wndControl, eMouseButton ) if eMouseButton == 0 then local nBuildId = wndControl:GetParent():GetData() if nBuildId > 1 then local buildToMoveUp = self.builds[nBuildId] local buildToMoveDown = self.builds[nBuildId - 1] self.builds[nBuildId] = buildToMoveDown self.builds[nBuildId - 1] = buildToMoveUp if self.currentBuild == nBuildId then self.currentBuild = self.currentBuild - 1 -- UP build just under current elseif self.currentBuild == nBuildId - 1 then self.currentBuild = self.currentBuild + 1 end self:UpdateBuildList(); end end end function Builder:OnMoveBuildDown( wndHandler, wndControl, eMouseButton ) if eMouseButton == 0 then local nBuildId = wndControl:GetParent():GetData() local nbBuild = table.getn(self.builds) if nBuildId < nbBuild then local buildToMoveUp = self.builds[nBuildId+1] local buildToMoveDown = self.builds[nBuildId] self.builds[nBuildId + 1] = buildToMoveDown self.builds[nBuildId] = buildToMoveUp if self.currentBuild == nBuildId then self.currentBuild = self.currentBuild + 1 -- Down build just above current elseif self.currentBuild == nBuildId + 1 then self.currentBuild = self.currentBuild -1 end self:UpdateBuildList(); end end end function Builder:OnGenerateTooltip( wndHandler, wndControl, tType, splTarget) if wndControl == wndHandler then if wndControl:GetAbilityTierId() and splTarget:GetId() ~= wndControl:GetAbilityTierId() then splTarget = GameLib.GetSpell(wndControl:GetAbilityTierId()) end Tooltip.GetSpellTooltipForm(self, wndHandler, splTarget, {bTiers = true}) end end function Builder:OnBuilderCloseBtn(wndHandler, wndControl, eMouseButton) self.wndMain:Close() end ---------------------------------- -- Overwrite build functions ---------------------------------- function Builder:OnOverwriteBuildClick(wndHandler, wndControl, eMouseButton) self:OpenOverwritePopUp(L["OVERWRITEMSG"]) end function Builder:OpenOverwritePopUp(message) self.wndOverwrite:FindChild("lblOverwriteMessage"):SetText(message .. self.builds[self.currentBuild].name) self.wndOverwrite:FindChild("btnYes"):SetText(L["ACCEPT"]) self.wndOverwrite:FindChild("btnNo"):SetText(L["DECLINE"]) self.wndOverwrite:Show(true, true) end function Builder:OnAcceptOverwriteClick(wndHandler, wndControl, eMouseButton) if eMouseButton == GameLib.CodeEnumInputMouse.Left then self:SaveBuild(self:GetCurrentLAS(),self.currentBuild) self:RedrawCurrentBuildPanel() self:UpdateBuildList() self:UpdateHotSwap() self.wndOverwrite:Show(false,true) self.btnOverwriteBuild:Show(false,true) end end function Builder:OnDeclineOverwriteClick( wndHandler, wndControl, eMouseButton) if eMouseButton == GameLib.CodeEnumInputMouse.Left then self.currentBuild = nil self:UpdateBuildList() self:RedrawCurrentBuildPanel() self:UpdateHotSwap() self.wndOverwrite:Show(false,true) end end function Builder:ToggleOverwriteButton() -- Hide Overwrite Buid button if self.currentBuild == nil or self.currentBuild == 0 then self.btnOverwriteBuild:Show(false,true) else self.btnOverwriteBuild:Show(true,true) end end ------------------------------ -- Tag Events ------------------------------ function Builder:OnTagDropDown( wndHandler, wndControl, eMouseButton ) local buildId = wndControl:GetParent():GetData() local mousePosition = Apollo.GetMouse() local x = mousePosition.x local y = mousePosition.y if self.dropDownTag ~= nil then self.dropDownTag:Destroy() end self.dropDownTag = Apollo.LoadForm(self.xmlDoc, "CustomDropDown", nil, self) wndControl:AttachWindow(self.dropDownTag) -- None button self:CreateTagDropDownButton(buildId, 0, L["NONE"], wndControl) if self.config.tags ~= nil then for i, tag in pairs(self.config.tags) do self:CreateTagDropDownButton(buildId, i, tag, wndControl) end end self.dropDownTag:FindChild("CustomList"):ArrangeChildrenVert(0) self.dropDownTag:FindChild("CustomList") self.dropDownTag:Move(x, y+10, 125, 150) self.dropDownTag:Show(true,true) end function Builder:CreateTagDropDownButton(pBuildId, pTagId, pText, pButton) self.btnTagDropDown = Apollo.LoadForm(self.xmlDoc, "btnTagDropDown", self.dropDownTag:FindChild("CustomList"), self) self.btnTagDropDown:SetText(pText) self.btnTagDropDown:SetData({buildId = pBuildId, tagId = pTagId, button = pButton}) end function Builder:OnTagSelectClick( wndHandler, wndControl, eMouseButton ) local data = wndControl:GetData() self.builds[data.buildId].tagId = data.tagId if data.tagId ~= 0 then data.button:SetText(self.config.tags[data.tagId]) else data.button:SetText(L["NONE"]) end wndControl:GetParent():GetParent():Show(false,false) end -- ############################################################################################################################## -- REGION : HotSwap -- ############################################################################################################################## function Builder:HotSwapInit() self.wndHotSwap = Apollo.LoadForm(self.xmlDoc, "HotSwapFrame", nil, self) local hsDropDown = self.wndHotSwap:FindChild("HSDropDown") if self.config == nil then self.config = {} self.config.useHotSwap = true self.config.hotSwapColor = HSColor.Blue end self.wndHotSwap:Show(self.config.useHotSwap,true) if self.config.hotSwapColor == HSColor.Blue then hsDropDown:SetSprite("BK3:btnHolo_Blue_SmallNormal") elseif self.config.hotSwapColor == HSColor.Black then hsDropDown:SetSprite("BK3:btnHolo_Blue_SmallDisabled") elseif self.config.hotSwapColor == HSColor.Green then hsDropDown:SetSprite("BK3:btnHolo_Green_SmallNormal") end if self.config ~= nil then if self.config.hotSwapOffset and self.config.hotSwapOffset ~= nil then self.wndHotSwap:SetAnchorOffsets(unpack(self.config.hotSwapOffset)) end end self:UpdateHotSwap() end function Builder:UpdateHotSwap() local HSDropDown = self.wndHotSwap:FindChild("HSDropDown") -- Builder has no build saved if self.builds ~= nil and self.currentBuild ~= nil and self:TableLength(self.builds) > 0 then HSDropDown:SetText(self.builds[self.currentBuild].name) else HSDropDown:SetText(L["NOBUILD"]) end end function Builder:HotSwapTagList() local noneTagsCount = 0 for i, peCurrent in pairs(self.builds) do if peCurrent.tagId == 0 or peCurrent.tagId == nil then noneTagsCount = 1 break end end if noneTagsCount == 1 then local btnTag = Apollo.LoadForm(self.xmlDoc, "HSTagButton", self.lstHSBuilds, self) btnTag:SetData(0) btnTag:SetText(L["NONE"]) end for i, peTag in pairs(self.config.tags) do btnTag = Apollo.LoadForm(self.xmlDoc, "HSTagButton", self.lstHSBuilds, self) btnTag:SetData(i) btnTag:SetText(peTag) end end function Builder:OnHotSwapClick(wndHandler, wndControl, eMouseButton, nLastRelativeMouseX, nLastRelativeMouseY, bDoubleClick, bStopPropagation) if wndControl ~= self.wndHotSwap then return end local hsDropDown = self.wndHotSwap:FindChild("HSDropDown") --hsDropDown:SetSprite("BK3:btnHolo_Blue_SmallPressed") -- Change Sprite if eMouseButton == GameLib.CodeEnumInputMouse.Left then local buildsContainer = self.wndHotSwap:FindChild("HSContainer") buildsContainer:Show(true,true) self.lstHSBuilds = buildsContainer:FindChild("HSBuildList") self.lstHSBuilds:DestroyChildren() if self.config.useTag then self:HotSwapTagList(self.lstHSBuilds) else -- Builds list construction for i, peCurrent in pairs(self.builds) do local btnBuild = Apollo.LoadForm(self.xmlDoc, "HSBuildButton", self.lstHSBuilds, self) btnBuild:SetData(i) btnBuild:SetText(self.builds[i].name) end end self.lstHSBuilds:ArrangeChildrenVert() local oLeft, oTop, oRight, oBottom = self.wndHotSwap:GetAnchorOffsets() local topOffset = 145 if self.config.hotSwapHeight ~= nil then topOffset = self.config.hotSwapHeight end local bottomOffset = 40 oLeft = 0 oRight = 0 if oTop > 0 then oTop = -topOffset oBottom = -bottomOffset else oTop = bottomOffset + 2 oBottom = topOffset + 2 end buildsContainer:SetAnchorOffsets(oLeft, oTop, oRight, oBottom) elseif eMouseButton == GameLib.CodeEnumInputMouse.Right then self:OnBuilderOn() end end function Builder:OnHotSwapTagClick( wndHandler, wndControl, eMouseButton ) local tagId = wndControl:GetData() self.lstHSBuilds:DestroyChildren() if tagId ~= 0 then for i, peCurrent in pairs(self.builds) do if self.builds[i].tagId == tagId then local btnBuild = Apollo.LoadForm(self.xmlDoc, "HSBuildButton", self.lstHSBuilds, self) btnBuild:SetData(i) btnBuild:SetText(self.builds[i].name) end end else for i, peCurrent in pairs(self.builds) do if self.builds[i].tagId == tagId or self.builds[i].tagId == nil then local btnBuild = Apollo.LoadForm(self.xmlDoc, "HSBuildButton", self.lstHSBuilds, self) btnBuild:SetData(i) btnBuild:SetText(self.builds[i].name) end end end self.lstHSBuilds:ArrangeChildrenVert() end function Builder:OnHotSwapMouseEnter( wndHandler, wndControl, x, y ) if wndControl ~= self.wndHotSwap then return end local hsDropDown = self.wndHotSwap:FindChild("HSDropDown") --TODO: MaybeChnage for theme --hsDropDown:SetSprite("BK3:btnHolo_Blue_SmallFlyby") end function Builder:OnHotSwapMouseExit( wndHandler, wndControl, x, y ) if wndControl ~= self.wndHotSwap then return end local hsDropDown = self.wndHotSwap:FindChild("HSDropDown") --TODO: MaybeChnage for theme --hsDropDown:SetSprite("BK3:btnHolo_Blue_SmallNormal") end function Builder:OnHotSwapUse( wndHandler, wndControl, eMouseButton ) if eMouseButton == GameLib.CodeEnumInputMouse.Left then local nBuildId = wndControl:GetData() --self:UpdateBuildWithId(nBuildId, true) -- call from builder to equip self.changeGear = true self:UpdateBuildWithId(nBuildId) Event_FireGenericEvent("GenericBuilderUpdate","B_USE", self.currentBuild, self.builds) self:UpdateHotSwap() if self.wndMain:IsShown() then self:RestoreAllBuilds() end --Close Container local buildsContainer = self.wndHotSwap:FindChild("HSContainer") buildsContainer:Show(false,true) end end -- ############################################################################################################################## -- REGION : Config Panel -- ############################################################################################################################## function Builder:OnConfigToggle(wndHandler, wndControl, eMouseButton) self.builderPanel = self.wndMain:FindChild("BuilderPanel") self.builderConfigPanel = self.wndMain:FindChild("BuilderConfigPanel") local builderTitle = self.wndMain:FindChild("BuilderTitle") if not self.builderConfigPanel:IsVisible() then self:OpenConfigPanel() builderTitle:SetText(L["CONFIG"]) else self.builderPanel:Show(true,true) self.builderConfigPanel:Show(false,false) builderTitle:SetText(L["BUILDER"]) end end function Builder:OpenConfigPanel() self.builderPanel:Show(false,false) self.builderConfigPanel:Show(true,true) --Default value if self.config.hotSwapHeight == nil then self.config.hotSwapHeight = 145 end if self.config.useHotSwap == nil then self.config.useHotSwap = true end if not self.config.useTag == nil then self.config.useTag = false end if not self.config.useHotSwap == nil then self.config.useHotSwap = true end if not self.config.hideHotSwapCombat == nil then self.config.hideHotSwapCombat = false end --Restore config values self.builderConfigPanel:FindChild("TagFrame:btnTag"):SetCheck(self.config.useTag) self.builderConfigPanel:FindChild("TagFrame:btnCreateNewTag"):Enable(self.config.useTag) self.builderConfigPanel:FindChild("GeneralFrame:btnHotSwap"):SetCheck(self.config.useHotSwap) self.builderConfigPanel:FindChild("GeneralFrame:btnHideHotSwapCombat"):SetCheck(self.config.hideHotSwapCombat) local pgbHeight = self.builderConfigPanel:FindChild("GeneralFrame:SliderHotSwapHeight") pgbHeight:SetMax(400) pgbHeight:SetProgress(self.config.hotSwapHeight - 100) pgbHeight:FindChild("Slider"):SetValue(self.config.hotSwapHeight - 100) pgbHeight:FindChild("Value"):SetText(self.config.hotSwapHeight) --HS Color if self.config.hotSwapColor == HSColor.Blue then self.builderConfigPanel:FindChild("GeneralFrame:Colors:optBlue"):SetCheck(true) elseif self.config.hotSwapColor == HSColor.Black then self.builderConfigPanel:FindChild("GeneralFrame:Colors:optBlack"):SetCheck(true) elseif self.config.hotSwapColor == HSColor.Green then self.builderConfigPanel:FindChild("GeneralFrame:Colors:optGreen"):SetCheck(true) else self.builderConfigPanel:FindChild("GeneralFrame:Colors:optBlue"):SetCheck(true) self.config.hotSwapColor = HSColor.Blue end -- Version Number value self.builderConfigPanel:FindChild("VersionLabel"):SetText(self.version) self:RefreshTagList() end function Builder:OnUseTagToggle( wndHandler, wndControl, eMouseButton ) local isChecked = self.builderConfigPanel:FindChild("TagFrame:btnTag"):IsChecked() local btnAddNewTag = self.builderConfigPanel:FindChild("TagFrame:btnCreateNewTag") self.config.useTag = isChecked btnAddNewTag:Enable(self.config.useTag) self:UpdateBuildList() end function Builder:OnHotSwapToggle(wndHandler, wndControl, eMouseButton) local isChecked = self.builderConfigPanel:FindChild("GeneralFrame:btnHotSwap"):IsChecked() self.config.useHotSwap = isChecked self.wndHotSwap:Show(self.config.useHotSwap,true) end function Builder:OnHotSwapHideCombat(wndHandler, wndControl, eMouseButton) local isChecked = self.builderConfigPanel:FindChild("GeneralFrame:btnHideHotSwapCombat"):IsChecked() self.config.hideHotSwapCombat = isChecked end function Builder:OnTagNameConfirm( wndHandler, wndControl, strText) local nTagId = wndControl:GetParent():GetData() local newName = strText:match("^%s*(.-)%s*$") local oldName = self.config.tags[nTagId] if newName == oldName then return end local tagName = self:SetTagName(strText, nTagId) wndControl:SetTextRaw(tagName) self:RefreshTagList() end function Builder:OnCreateNewTag( wndHandler, wndControl, eMouseButton ) local nTagId = 0 local nbTag = self:TableLength(self.config.tags) for i=1, nbTag do if self.config.tags[1] == nil then nTagId = 1 else if self.config.tags[i + 1] == nil then nTagId = i + 1 end end end if nTagId == 0 then nTagId = 1 end self.config.tags[nTagId] = L["NEWTAG"] self:RefreshTagList() end function Builder:RefreshTagList() self.lstConfigTags = self.wndMain:FindChild("BuilderConfigPanel:TagFrame:TagList") self.lstConfigTags:DestroyChildren() for id, peCurrent in pairs(self.config.tags) do local newTagListItem = Apollo.LoadForm(self.xmlDoc,"TagListItem", self.lstConfigTags, self) newTagListItem:SetData(id) newTagListItem:SetName("tag_" .. id) local sTagName = self.config.tags[id] if sTagName == nil then sTagName = self:SetTagName(nil, id) end local txtTagName = newTagListItem:FindChild("txtTagName") txtTagName:SetMaxTextLength(10) txtTagName:SetTextRaw(sTagName) end self.lstConfigTags:ArrangeChildrenVert() end function Builder:OnDeleteTagClick( wndHandler, wndControl, eMouseButton ) if eMouseButton == 0 then local tagId = wndControl:GetParent():GetData() local nbTags = self:TableLength(self.config.tags) self.config.tags[tagId] = nil -- Arrange builds tag ids for i, peCurrent in pairs(self.builds) do if self.builds[i].tagId ~= nil then if self.builds[i].tagId == tagId then self.builds[i].tagId = 0 elseif self.builds[i].tagId > tagId then self.builds[i].tagId = self.builds[i].tagId - 1 end else self.builds[i].tagId = 0 end end -- Reorder the tag array for i = tagId, nbTags - 1 do self.config.tags[i] = self.config.tags[i+1] end self.config.tags[nbTags] = nil self:RefreshTagList() self:UpdateBuildList() end end function Builder:OnMoveTagUp(wndHandler, wndControl, eMouseButton) if eMouseButton == 0 then local nTagId = wndControl:GetParent():GetData() if nTagId > 1 then local tagToMoveUp = self.config.tags[nTagId] local tagToMoveDown = self.config.tags[nTagId - 1] self.config.tags[nTagId] = tagToMoveDown self.config.tags[nTagId - 1] = tagToMoveUp -- Arrange builds tag ids for i, peCurrent in pairs(self.builds) do if peCurrent.tagId == nTagId then peCurrent.tagId = nTagId - 1 elseif peCurrent.tagId == nTagId - 1 then peCurrent.tagId = nTagId end end self:RefreshTagList(); self:UpdateBuildList() end end end function Builder:OnMoveTagDown(wndHandler, wndControl, eMouseButton) if eMouseButton == 0 then local nTagId = wndControl:GetParent():GetData() local nbTags = table.getn(self.config.tags) if nTagId < nbTags then local tagToMoveUp = self.config.tags[nTagId + 1] local tagToMoveDown = self.config.tags[nTagId] self.config.tags[nTagId + 1] = tagToMoveDown self.config.tags[nTagId] = tagToMoveUp -- Arrange builds tag ids for i, peCurrent in pairs(self.builds) do if peCurrent.tagId == nTagId then peCurrent.tagId = nTagId + 1 elseif peCurrent.tagId == nTagId + 1 then peCurrent.tagId = nTagId end end self:RefreshTagList(); self:UpdateBuildList(); end end end function Builder:OnHSSliderHeightChanged( wndHandler, wndControl, fNewValue, fOldValue) self.config.hotSwapHeight = fNewValue + 100 local pgbHeight = wndControl:GetParent() pgbHeight:SetProgress(fNewValue) pgbHeight:FindChild("Value"):SetText(self.config.hotSwapHeight) end -- ############################################################################################################################## -- REGION : Utilies Functions -- ############################################################################################################################## function Builder:SaveBuild(tBuild, nBuildId) local buildTag local buildName if nBuildId == nil then local nBuild = self:TableLength(self.builds) for _=1, nBuild do if self.builds[1] == nil then nBuildId = 1 else if self.builds[_ + 1] == nil then nBuildId = _ + 1 end end end if nBuild == 0 then nBuildId = 1 end else self.currentGearId = self.builds[nBuildId].gearId buildName = self.builds[nBuildId].name buildTag = self.builds[nBuildId].tagId end self.builds[nBuildId] = {} tBuild.gearId = self.currentGearId self.builds[nBuildId] = tBuild if nBuildId ~= nil then self.builds[nBuildId].name = buildName self.builds[nBuildId].tagId = buildTag end return nBuildId end function Builder:GetCurrentLAS() local actionSetIndex = AbilityBook.GetCurrentSpec() local actionSet = ActionSetLib.GetCurrentActionSet() local abilities = nil local abilitiesTiers = nil local innateSpell = nil if actionSet ~= nil then abilities = {unpack(actionSet, 1, 8)} abilitiesTiers = self:ToMap(abilities,1) innateSpell = GameLib.GetCurrentClassInnateAbilitySpell() for key, ability in ipairs(AbilityBook.GetAbilitiesList()) do if abilitiesTiers [ability.nId] then abilitiesTiers[ability.nId] = ability.nCurrentTier end end end return { actionSetIndex = actionSetIndex , abilities = abilities, abilitiesTiers = abilitiesTiers , innateIndex = GameLib.GetCurrentClassInnateAbilityIndex(), } end --------------------------------------------------- -- Delete a Build --------------------------------------------------- function Builder:DeleteBuild(nBuildId) --local nbBuilds = self:TableLength(self.builds) if self.builds[nBuildId] ~= nil then self.builds[nBuildId] = nil end -- Reorder the builder array -- for i = nBuildId, nbBuilds - 1 do -- self.builds[i] = self.builds[i+1] -- end -- self.builds[nbBuilds] = nil if self.currentBuild ~= nil then if nBuildId == self.currentBuild then self.currentBuild = nil self:UpdateHotSwap() -- elseif nBuildId < self.currentBuild then -- self.currentBuild = self.currentBuild - 1 end end self:UpdateBuildList() end --------------------------------------------------- -- Update Build With Build ID --------------------------------------------------- --function Builder:UpdateBuildWithId(nBuildId, changeGear) function Builder:UpdateBuildWithId(nBuildId) self.currentBuild = nBuildId --self:UpdateBuild(self.builds[nBuildId], changeGear) self:UpdateBuild(self.builds[nBuildId]) self:UpdateHotSwap() self:OnBuilderCloseBtn() end --------------------------------------------------- -- Update Player --------------------------------------------------- --function Builder:UpdateBuild(build, changeGear) function Builder:UpdateBuild(build) self.isLoadingBuild = true self.isLoadingActionSet = true self:ShowWaitingIcon(self.isLoadingBuild) local player = GameLib.GetPlayerUnit() if player:IsDead() or player:IsInCombat() then self:ShowWaitingIcon(true) else self:ShowWaitingIcon(true) --Gear Set --if build.gearId ~= 0 and build.gearId ~= nil and self.currentGearId ~= build.gearId and changeGear then if build.gearId ~= 0 and build.gearId ~= nil and self.currentGearId ~= build.gearId and self.changeGear then self.isLoadingGear = true Event_FireGenericEvent("Generic_GEAR_UPDATE", "G_EQUIP", build.gearId, nil, 3) else self.isLoadingGear = false end if build.actionSetIndex ~= AbilityBook.GetCurrentSpec() then AbilityBook.SetCurrentSpec(build.actionSetIndex) -- Need to wait on callback to continue return else self.isLoadingActionSet = false end self.ResetSpellTiers() local currentActionSet = ActionSetLib.GetCurrentActionSet() for key, abilityId in ipairs(build.abilities) do currentActionSet[key] = abilityId end for abilityId, tier in pairs(build.abilitiesTiers) do AbilityBook.UpdateSpellTier(abilityId, tier) end local result = ActionSetLib.RequestActionSetChanges(currentActionSet) if build.innateIndex and currentActionSet.innateIndex ~= GameLib.GetCurrentClassInnateAbilityIndex() then GameLib.SetCurrentClassInnateAbilityIndex(build.innateIndex) end self.isLoadingActionSet = false self.isLoadingBuild = false self:ShowWaitingIcon(self.isLoadingBuild or self.isLoadingGear) end end function Builder:DetectBuildChange() if self.currentBuild == 0 or self.currentBuild == nil then return false -- TODO MAYBE : Ask to create a new one end local oldBuild = self.builds[self.currentBuild] local currentBuild = self:GetCurrentLAS() -- Action Set if oldBuild.actionSetIndex ~= currentBuild.actionSetIndex then return true end -- Validate Innate if oldBuild.innateIndex ~= currentBuild.innateIndex then return true end -- Validate Abilities & Tiers for idx = 1, 8 do if oldBuild.abilities[idx] ~= currentBuild.abilities[idx] then return true else local abilityId = oldBuild.abilities[idx] if oldBuild.abilitiesTiers[abilityId] ~= currentBuild.abilitiesTiers[abilityId] then return true end end end return false end function Builder:OnAMPPageChanged() if not self.isLoadingActionSet then return end self:RedrawCurrentBuildPanel() -- We need to callback to change the rest after a AMP Page change self.waitingAMP = ApolloTimer.Create(.3, false, "waitingAMP", {waitingAMP = function() --self:UpdateBuildWithId(self.currentBuild, true) self:UpdateBuildWithId(self.currentBuild) end}) end -- ############################################################################################################################## -- REGION : Persistance -- ############################################################################################################################## --------------------------------------------------------------------------------------------------- -- OnSave Data to AddonSavedData --------------------------------------------------------------------------------------------------- function Builder:OnSave(eLevel) if eLevel ~= GameLib.CodeEnumAddonSaveLevel.Character then return end local tData = {} self.config = { currentBuild = self.currentBuild, mainWindowOffset = {self.wndMain:GetAnchorOffsets()}, hotSwapOffset = {self.wndHotSwap:GetAnchorOffsets()}, hotSwapHeight = self.config.hotSwapHeight, useHotSwap = self.config.useHotSwap, hideHotSwapCombat = self.config.hideHotSwapCombat, useTag = self.config.useTag, tags = self.config.tags, version = self.version, hotSwapColor = self.config.hotSwapColor, } tData.config = self.config tData.builds = self.builds return tData end --------------------------------------------------------------------------------------------------- -- OnRestore Data from AddonSavedData --------------------------------------------------------------------------------------------------- function Builder:OnRestore(eLevel,tData) if eLevel ~= GameLib.CodeEnumAddonSaveLevel.Character then return end if tData.builds == nil then self.builds = tData return end if tData.builds then self.builds = tData.builds else self.builds = nil end if tData.config.currentBuild and tData.config.currentBuild >=1 then self.currentBuild = tData.config.currentBuild else self.currentBuild = nil end if tData.config then self.config = self:DeepCopy(tData.config) -- Check Version MissMatch if self.config.version ~= self.version then if self.version == "0.2" then self.config.hotSwapOffset = {-30, -19, 255, 37} elseif self.version == "0.3" then self.config.useHotSwap = true self.config.useTag = false elseif self.version == "v0.3.5a" then self.config.hotSwapHeight = 145 elseif self.version == "v0.4" then self.config.hideHotSwapCombat = false self.config.hotSwapColor = HSColor.Blue end end if self.config.tags == nil then self.config.tags = {} end else self:DefaultConfig() end end ----------------------------------------------------------------------------------------------- -- Reset Default Config ----------------------------------------------------------------------------------------------- function Builder:DefaultConfig() self.config = {} self.config.useTag = false self.config.useHotSwap = true self.config.hotSwapHeight = 145 self.config.hideHotSwapCombat = false self.config.tags = {} self.config.hotSwapOffset = {-30, -19, 255, 37} self.config.hotSwapColor = HSColor.Blue end --------------------------------------------------------------------------------------------------- -- BuilderForm Functions --------------------------------------------------------------------------------------------------- function Builder:OnHotSwapBlueCheck( wndHandler, wndControl, eMouseButton ) self.config.hotSwapColor = HSColor.Blue local hsDropDown = self.wndHotSwap:FindChild("HSDropDown") hsDropDown:SetSprite("BK3:btnHolo_Blue_SmallNormal") end function Builder:OnHotSwapBlackCheck( wndHandler, wndControl, eMouseButton ) self.config.hotSwapColor = HSColor.Black local hsDropDown = self.wndHotSwap:FindChild("HSDropDown") hsDropDown:SetSprite("BK3:btnHolo_Blue_SmallDisabled") end function Builder:OnHotSwapGreenCheck( wndHandler, wndControl, eMouseButton ) self.config.hotSwapColor = HSColor.Green local hsDropDown = self.wndHotSwap:FindChild("HSDropDown") hsDropDown:SetSprite("BK3:btnHolo_Green_SmallNormal") end ----------------------------------------------------------------------------------------------- -- Builder Instance ----------------------------------------------------------------------------------------------- local BuilderInst = Builder:new() BuilderInst:Init()
sound.Add( { name = "Weapon_Melee_Blunt.Impact_Light", channel = CHAN_AUTO, level = SNDLVL_NORM, volume = 1.0, sound = { ")nmrihimpact/blunt_light1.wav", ")nmrihimpact/blunt_light2.wav", ")nmrihimpact/blunt_light3.wav", ")nmrihimpact/blunt_light4.wav", ")nmrihimpact/blunt_light5.wav", ")nmrihimpact/blunt_light6.wav", ")nmrihimpact/blunt_light7.wav", ")nmrihimpact/blunt_light8.wav" }, } ) sound.Add( { name = "Weapon_Melee_Blunt.Impact_Heavy", channel = CHAN_AUTO, level = SNDLVL_NORM, volume = 1.0, sound = { ")nmrihimpact/blunt_heavy1.wav", ")nmrihimpact/blunt_heavy2.wav", ")nmrihimpact/blunt_heavy3.wav", ")nmrihimpact/blunt_heavy4.wav", ")nmrihimpact/blunt_heavy5.wav", ")nmrihimpact/blunt_heavy6.wav" }, } ) sound.Add( { name = "Weapon_Melee_Sharp.Impact_Light", channel = CHAN_AUTO, level = SNDLVL_NORM, volume = 1.0, sound = { ")nmrihimpact/sharp_light1.wav", ")nmrihimpact/sharp_light2.wav", ")nmrihimpact/sharp_light3.wav" }, } ) sound.Add( { name = "Weapon_Melee_Sharp.Impact_Heavy", channel = CHAN_AUTO, level = SNDLVL_NORM, volume = 1.0, sound = { ")nmrihimpact/sharp_heavy1.wav", ")nmrihimpact/sharp_heavy2.wav", ")nmrihimpact/sharp_heavy3.wav", ")nmrihimpact/sharp_heavy4.wav", ")nmrihimpact/sharp_heavy5.wav", ")nmrihimpact/sharp_heavy6.wav" }, } ) sound.Add( { name = "Weapon_Melee.Impact_Brick", channel = CHAN_AUTO, level = SNDLVL_NORM, volume = 1.0, sound = { ")nmrihimpact/brick/brick_impact_bullet1.wav", ")nmrihimpact/brick/brick_impact_bullet2.wav", ")nmrihimpact/brick/brick_impact_bullet3.wav", ")nmrihimpact/brick/brick_impact_bullet4.wav", ")nmrihimpact/brick/brick_impact_bullet5.wav" }, } ) sound.Add( { name = "Weapon_Melee.Impact_Cardboard", channel = CHAN_AUTO, level = SNDLVL_NORM, volume = 1.0, sound = { ")nmrihimpact/cardboard/ammo_box_impact_01.wav", ")nmrihimpact/cardboard/ammo_box_impact_02.wav", ")nmrihimpact/cardboard/ammo_box_impact_03.wav", ")nmrihimpact/cardboard/ammo_box_impact_04.wav", ")nmrihimpact/cardboard/ammo_box_impact_05.wav" }, } ) sound.Add( { name = "Weapon_Melee.Impact_Concrete", channel = CHAN_AUTO, level = SNDLVL_NORM, volume = 1.0, sound = { ")nmrihimpact/concrete/concrete_impact_bullet1.wav", ")nmrihimpact/concrete/concrete_impact_bullet2.wav", ")nmrihimpact/concrete/concrete_impact_bullet3.wav", ")nmrihimpact/concrete/concrete_impact_bullet4.wav", ")nmrihimpact/concrete/concrete_impact_bullet5.wav" }, } ) sound.Add( { name = "Weapon_Melee.Impact_Metal", channel = CHAN_AUTO, level = SNDLVL_NORM, volume = 1.0, sound = { ")nmrihimpact/metal/metal_solid_impact_bullet1.wav", ")nmrihimpact/metal/metal_solid_impact_bullet2.wav", ")nmrihimpact/metal/metal_solid_impact_bullet3.wav", ")nmrihimpact/metal/metal_solid_impact_bullet4.wav", ")nmrihimpact/metal/metal_solid_impact_bullet5.wav" }, } ) sound.Add( { name = "Weapon_Melee.Impact_Generic", channel = CHAN_AUTO, level = SNDLVL_NORM, volume = 1.0, sound = { ")nmrihimpact/surfaces/sand_impact_bullet1.wav", ")nmrihimpact/surfaces/sand_impact_bullet2.wav", ")nmrihimpact/surfaces/sand_impact_bullet3.wav", ")nmrihimpact/surfaces/sand_impact_bullet4.wav", ")nmrihimpact/surfaces/sand_impact_bullet5.wav" }, } ) sound.Add( { name = "Weapon_Melee.Impact_Wood", channel = CHAN_AUTO, level = SNDLVL_NORM, volume = 1.0, sound = { ")nmrihimpact/wood/wood_solid_impact_bullet1.wav", ")nmrihimpact/wood/wood_solid_impact_bullet2.wav", ")nmrihimpact/wood/wood_solid_impact_bullet3.wav", ")nmrihimpact/wood/wood_solid_impact_bullet4.wav", ")nmrihimpact/wood/wood_solid_impact_bullet5.wav" }, } )
-- Lua module file for Python compiled with Intel stack (incl. MKL) help([[ Python 2.7.10, Intel compiler + MKL ]]) load("intel/16.0.0", "mkl/11.3.0", "intelmpi/5.1.1") local base = '/homeappl/home/louhivuo/appl_taito/python-2.7.10' setenv('PYTHONHOME', base) prepend_path('PYTHONPATH', pathJoin(base, 'lib')) prepend_path('PATH', pathJoin(base, 'bin'))
-- set wifi softap mode wifi.setmode(wifi.SOFTAP); wifi.start();
-- Simple Game Loader -- Created by ls522 and skiaboos. DO NOT DELETE THIS OR ANYTHING AFTER! -- Instances: local Loading = Instance.new("ScreenGui") local Background = Instance.new("Frame") local LoadingMain = Instance.new("Frame") local F1 = Instance.new("Frame") local F1T = Instance.new("TextLabel") local F2 = Instance.new("Frame") local F2T = Instance.new("TextLabel") local F3 = Instance.new("Frame") local F3T = Instance.new("TextLabel") local PlayB = Instance.new("TextButton") local LoadingT = Instance.new("TextLabel") --Properties: Loading.Name = "Loading" Loading.Parent = game.Players.LocalPlayer:WaitForChild("PlayerGui") Loading.ZIndexBehavior = Enum.ZIndexBehavior.Sibling Background.Name = "Background" Background.Parent = Loading Background.BackgroundColor3 = Color3.fromRGB(0, 0, 0) Background.BackgroundTransparency = 0.010 Background.Size = UDim2.new(0, 1920, 0, 1080) LoadingMain.Name = "LoadingMain" LoadingMain.Parent = Background LoadingMain.BackgroundColor3 = Color3.fromRGB(38, 38, 38) LoadingMain.BackgroundTransparency = 0.190 LoadingMain.Position = UDim2.new(0.27783528, 0, 0.604221523, 0) LoadingMain.Size = UDim2.new(0, 851, 0, 100) F1.Name = "F1" F1.Parent = LoadingMain F1.BackgroundColor3 = Color3.fromRGB(255, 255, 255) F1.Size = UDim2.new(0, 100, 0, 100) F1.Visible = false F1T.Name = "F1T" F1T.Parent = F1 F1T.BackgroundColor3 = Color3.fromRGB(255, 255, 255) F1T.Size = UDim2.new(0, 100, 0, 100) F1T.Visible = false F1T.Font = Enum.Font.SourceSans F1T.Text = "Started" F1T.TextColor3 = Color3.fromRGB(0, 0, 0) F1T.TextScaled = true F1T.TextSize = 14.000 F1T.TextWrapped = true F2.Name = "F2" F2.Parent = LoadingMain F2.BackgroundColor3 = Color3.fromRGB(255, 255, 255) F2.Position = UDim2.new(0.441833138, 0, 0, 0) F2.Size = UDim2.new(0, 100, 0, 100) F2.Visible = false F2T.Name = "F2T" F2T.Parent = F2 F2T.BackgroundColor3 = Color3.fromRGB(255, 255, 255) F2T.Size = UDim2.new(0, 100, 0, 100) F2T.Visible = false F2T.Font = Enum.Font.SourceSans F2T.Text = "50%" F2T.TextColor3 = Color3.fromRGB(0, 0, 0) F2T.TextScaled = true F2T.TextSize = 14.000 F2T.TextWrapped = true F3.Name = "F3" F3.Parent = LoadingMain F3.BackgroundColor3 = Color3.fromRGB(255, 255, 255) F3.Position = UDim2.new(0.88249135, 0, 0, 0) F3.Size = UDim2.new(0, 99, 0, 100) F3.Visible = false F3T.Name = "F3T" F3T.Parent = F3 F3T.BackgroundColor3 = Color3.fromRGB(255, 255, 255) F3T.Size = UDim2.new(0, 99, 0, 100) F3T.Visible = false F3T.Font = Enum.Font.SourceSans F3T.Text = "Done!" F3T.TextColor3 = Color3.fromRGB(0, 0, 0) F3T.TextScaled = true F3T.TextSize = 14.000 F3T.TextWrapped = true PlayB.Name = "PlayB" PlayB.Parent = LoadingMain PlayB.BackgroundColor3 = Color3.fromRGB(255, 255, 255) PlayB.BackgroundTransparency = 1.000 PlayB.Size = UDim2.new(0, 851, 0, 100) PlayB.Visible = false PlayB.Font = Enum.Font.SourceSans PlayB.Text = "Play now!" PlayB.TextColor3 = Color3.fromRGB(255, 255, 255) PlayB.TextScaled = true PlayB.TextSize = 14.000 PlayB.TextWrapped = true LoadingT.Name = "LoadingT" LoadingT.Parent = Background LoadingT.BackgroundColor3 = Color3.fromRGB(255, 255, 255) LoadingT.BackgroundTransparency = 1.000 LoadingT.Position = UDim2.new(0.402817309, 0, 0.2024692, 0) LoadingT.Size = UDim2.new(0, 371, 0, 92) LoadingT.Font = Enum.Font.SourceSans LoadingT.Text = "Loading..." LoadingT.TextColor3 = Color3.fromRGB(255, 255, 255) LoadingT.TextScaled = true LoadingT.TextSize = 14.000 LoadingT.TextWrapped = true -- Scripts. Messing around there means code death wait(1) F1.Visible = true F1T.Visible = true wait(5) F2.Visible = true F2T.Visible = true wait(5) F3.Visible = true F3T.Visible = true wait(1) F1.Visible = false F2.Visible = false F3.Visible = false PlayB.Visible = true PlayB.MouseButton1Down:connect(function() Background.Visible = false end)
--暂时别加这个吧 -- require 'war3library.libraries.interact.buff.template' require 'war3library.libraries.interact.buff.减攻速' require 'war3library.libraries.interact.buff.减速' require 'war3library.libraries.interact.buff.缩放' require 'war3library.libraries.interact.buff.高度' require 'war3library.libraries.interact.buff.晕眩'
-- Player stuff local ply = FindMetaTable("Player") function ply:GetSecondaryUserGroup() return xSGroups.Users[self:SteamID64()] or nil end function ply:GetSecondaryGroupPower() return xSGroups.Groups[self:GetUserGroup()].power or 0 end function ply:GetSecondaryGroupTable() return xSGroups.Groups[self:GetUserGroup()] or nil end -- Other function xSGroups.Core.RegisterGroup(name, power) xSGroups.Groups[name] = {name = name, power = power} end function xSGroups.Core.GetGroupPower(name) return xSGroups.Groups[name].power or 0 end function xSGroups.Core.GetGroupsWithPower(power) local groups = {} for k, v in pairs(xSGroups.Groups) do if v.power >= power then table.insert(groups, v) end end return groups end
local Game = {} local json = require("json") Game.__index = Game Game.expTickRate = 1 Game.expBonusRate = { [ 0] = 0.900, -- Non-follower [ 1] = 1.000, -- New! follower [ 2] = 1.250, -- 0 months [ 3] = 1.375, -- 1 month [ 4] = 1.500, -- 3 months [ 5] = 1.700, -- 6 months [ 6] = 1.900, -- 9 months [ 7] = 2.000, -- 1 year [ 8] = 2.100, -- 2 years [ 9] = 2.150, -- 3 years [10] = 2.275, -- 4 years [11] = 2.400, -- 5 years [12] = 2.500, -- 6 years } function Game.start(channel) local playerData = {} if (love.filesystem.exists(channel ..".json")) then playerData = json.decode(love.filesystem.read(channel ..".json")) end local ret = { channel = channel, players = {}, playerData = playerData, -- All players + data nextUpdate = Game.updateTime, internalPlayers = {}, playerCount = 0, } return setmetatable(ret, Game) end function Game:update(dt) self:runUpdates(dt) end function Game:updateFollowing(followers, playerName) if not playerName then for k, v in pairs(self.playerData) do if followers[k] then print(string.format("Updating %s as having starlevel %d and badge %s!", k, followers[k].level, followers[k].badge)) self.playerData[k].starLevel = followers[k].level self.playerData[k].starBadge = followers[k].badge end end else if followers[playerName] and self.playerData[playerName] then self.playerData[playerName].starLevel = followers[playerName].level self.playerData[playerName].starBadge = followers[playerName].badge end end end function Game:runUpdates(dt) -- Award EXP per tick to each player who is active for player, pdata in pairs(self.players) do if pdata.isInChannel then self:awardExp(player, self:getExpPerTick(self.playerData[player], dt)) end end end local function activitySorter(self) return function (p1, p2) local player1 = { activity = self.players[p1], data = self.playerData[p1] } local player2 = { activity = self.players[p2], data = self.playerData[p2] } -- People still in the channel sort first if player1.activity.isInChannel and not player2.activity.isInChannel then -- P1 in channel, P2 is not return true elseif not player1.activity.isInChannel and player2.activity.isInChannel then -- P2 in channel, P1 is not return false else -- Otherwise, sort by EXP return player1.data.exp > player2.data.exp end end end function Game:updateInternalList() local plist = {} local count = 0 for k, v in pairs(self.players) do count = count + 1 plist[count] = k end local sorter = activitySorter(self) table.sort(plist, sorter) self.internalPlayers = plist self.playerCount = count end -- On join, add player to active-players list function Game:addPlayer(player, channel) if (channel ~= self.channel) then return end if (not self.playerData[player]) then self.playerData[player] = { level = 1, exp = 0, dexp = 0, thisLevelExp = 0, starLevel = 0, starBadge = "", nextLevelExp = Game.getLevelExp(1), } elseif (self.players[player] and not self.players[player].isInChannel) then print("Readded disappeared player", player) self.players[player].isInChannel = true end if not self.players[player] then self.players[player] = { isInChannel = true, } end sounds.join:play() print("Added player", player) addMessage(player .." joined!") self:updateInternalList() end -- On part, remove player from active-players list function Game:removePlayer(player, channel) if (channel and channel ~= self.channel) then return end if self.players[player] then sounds.leave:play() addMessage(player .." left.") --self.players[player] = nil self.players[player].isInChannel = false end self:updateInternalList() end function Game:playerChat(player, channel, message) print("Chat", channel, player, message) if (not self.players[player] or not self.players[player].isInChannel) then print("Adding not-joined player ".. player .."!") self:addPlayer(player, channel) return true end return false end function Game:awardExp(player, exp) local p = self.playerData[player] local cl = p.level local ce = p.exp local cr = p.nextLevelExp p.exp = p.exp + exp p.dexp = math.floor(p.exp) if math.floor(p.exp) >= cr then print("Level up!", player, cl + 1) sounds.levelup:play() p.level = p.level + 1 p.thisLevelExp = cr p.nextLevelExp = Game.getLevelExp(cl + 1) addMessage(string.format("%s is now level %d!", player, p.level)) end end function Game.getLevelExp(level) return math.floor(100 * level + (5 * (level - 1) ^ 3) / 3) end function Game:getExpPerTick(pdata, dt) local bonus = 0.0 if pdata.starLevel then bonus = self.expBonusRate[pdata.starLevel] end local exp = (dt * self.expTickRate) * bonus return math.max(0, exp) end return Game
--[[ Netherstorm -- Abjurist Belmara.lua This script was written and is protected by the GPL v2. This script was released by BlackHer0 of the BLUA Scripting Project. Please give proper accredidations when re-releasing or sharing this script with others in the emulation community. ~~End of License Agreement -- BlackHer0, July, 21th, 2008. ]] function Abjurist_OnEnterCombat(Unit, Event) Unit:RegisterEvent("Abjurist_Armor", 10000, 0) Unit:RegisterEvent("Abjurist_Missiles", 1000,0) end function Abjurist_Armor(Unit, Event) Unit:CastSpell(12544) end function Abjurist_Missiles(Unit, Event) Unit:FullCastSpellOnTarget(34447,Unit:GetClosestPlayer()) end function Abjurist_OnLeaveCombat(Unit,Event) Unit:RemoveEvents() end function Abjurist_OnDied(Unit,Event) Unit:RemoveEvents() end RegisterUnitEvent (19546, 1, "Abjurist_OnEnterCombat") RegisterUnitEvent (19546, 2, "Abjurist_OnLeaveCombat") RegisterUnitEvent (19546, 4, "Abjurist_OnDied")
--Taiidan supplyShow("Utility", "Never"); h
--主入口函数。从这里开始lua逻辑 local rawset = rawset -- 全局函数 -- 用于声明全局变量 function define(name,value) rawset(_G,name,value) end local function initialize() LuaLogHelper.initialize() end -- 在此处定义注册一些全局变量 local function gloablDefine() -- 必须首先注册全局Class,顺序敏感 define("Class",require("Core.middleclass")) define("LuaLogHelper",require("Utilitys.LuaLogHelper")) define("EventMgr",require("Mgrs.EventMgr")) define("CommonUtility",require("Utilitys.CommonUtility")) define("ConfigMgr",require("Mgrs.ConfigMgr")) define("ModuleManager",require("Mgrs.ModuleManager")) define("UIUtils",require("Utilitys.UIUtils")) end -- 初始化一些参数 local function initParam() -- 初始化随机种子 math.randomseed(tostring(os.time()):reverse():sub(1, 6)) end local function EventTest(param) print("------------>接受到参数",param) end function Main() gloablDefine() initParam() initialize() EventMgr:Instance():RegisterEvent(1,2,EventTest) EventMgr:Instance():DispatchEvent(1,2,{key = "123",value= 456,"abc",123}) end --场景切换通知 function OnLevelWasLoaded(level) collectgarbage("collect") Time.timeSinceLevelLoad = 0 end function OnApplicationQuit() end
mokk_guard = Creature:new { customName = "Mokk Guard", socialGroup = "mokk_tribe", faction = "mokk_tribe", level = 300, chanceHit = 75.0, damageMin = 1800, damageMax = 3500, baseXp = 2500, baseHAM = 80000, baseHAMmax = 100000, armor = 2, resists = {80,80,80,80,80,80,80,40,60}, meatType = "", meatAmount = 0, hideType = "", hideAmount = 0, boneType = "", boneAmount = 0, milk = 0, tamingChance = 0.0, ferocity = 0, pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY, creatureBitmask = PACK + HERD, optionsBitmask = AIENABLED, diet = HERBIVORE, scale = 1.1, templates = { "object/mobile/dantari_male.iff", "object/mobile/dantari_female.iff"}, lootGroups = { { groups = { {group = "trash_common", chance = 10000000}, }, lootChance = 10000000 }, { groups = { {group = "mokk_elites", chance = 10000000}, }, lootChance = 8000000 }, { groups = { {group = "trash_rare", chance = 10000000}, }, lootChance = 3000000 }, { groups = { {group = "tierone", chance = 1500000}, {group = "tiertwo", chance = 3500000}, {group = "tierthree", chance = 2500000}, {group = "tierdiamond", chance = 2500000}, }, lootChance = 4000000 } }, weapons = {"blood_razer_weapons"}, conversationTemplate = "", attacks = merge(pikemanmaster,fencermaster,tkamaster) } CreatureTemplates:addCreatureTemplate(mokk_guard, "mokk_guard")
function get_name() return "A SIMPLE COUNTER" end function get_description() return {} end function get_streams() outx = { 1, 2, 3, 4, 5, 6, 7 } return { { STREAM_OUTPUT, "OUT", 0, outx }, } end function get_layout() return { TILE_COMPUTE } end function get_layout_width() return 1 end
data:extend( { { type = "recipe", name = "empty-recipe", icon = "__More_Ammo__/graphics/icons/items/empty-magazine.png", icon_size = 63, enabled = true, category = "crafting", group = "intermediate-products", subgroup = "intermediate-product", order = "a", ingredients = { {"iron-plate", 2}, }, energy_required = 5, result = "empty-magazine" } } )
--------------------------------------------- -- PerimeterX(www.perimeterx.com) Nginx plugin ---------------------------------------------- local M = {} function M.load(px_config) local _M = {} local px_api = require("px.utils.pxapi").load(px_config) local px_logger = require("px.utils.pxlogger").load(px_config) local px_headers = require("px.utils.pxheaders").load(px_config) local px_constants = require "px.utils.pxconstants" local px_common_utils = require "px.utils.pxcommonutils" local auth_token = px_config.auth_token local captcha_api_path = px_constants.CAPTCHA_PATH local pcall = pcall local function split_s(str, delimiter) local result = {} local from = 1 local delim_from, delim_to = string.find(str, delimiter, from) while delim_from do table.insert(result, string.sub(str, from, delim_from - 1)) from = delim_to + 1 delim_from, delim_to = string.find(str, delimiter, from) end table.insert(result, string.sub(str, from)) return result end -- new_request_object -- -- takes no arguments -- returns table local function new_captcha_request_object(captcha) local captcha_reset = {} captcha_reset.cid = '' captcha_reset.request = {} captcha_reset.request.firstParty = px_config.first_party_enaled or false captcha_reset.request.ip = px_headers.get_ip() captcha_reset.request.uri = ngx.var.uri captcha_reset.request.captchaType = px_config.captcha_provider captcha_reset.request.headers = px_common_utils.filter_headers(px_config.sensitive_headers, true) captcha_reset.pxCaptcha = captcha; captcha_reset.hostname = ngx.var.host; px_logger.debug('Captcha evaulation completed') return captcha_reset end function _M.process(captcha) if not captcha then px_logger.debug('No Captcha cookie present on the request'); return -1; end px_logger.debug('Captcha cookie found, evaluating'); local request_data = new_captcha_request_object(captcha) px_logger.debug('Sending Captcha API call to eval cookie'); local start_risk_rtt = px_common_utils.get_time_in_milliseconds() local success, response = pcall(px_api.call_s2s, request_data, captcha_api_path, auth_token) ngx.ctx.risk_rtt = px_common_utils.get_time_in_milliseconds() - start_risk_rtt if success then px_logger.debug('Captcha API response validation status: passed'); ngx.ctx.pass_reason = 'captcha' return response.status elseif string.match(response,'timeout') then px_logger.debug('Captcha API response validation status: timeout'); ngx.ctx.pass_reason = 'captcha_timeout' return 0 end px_logger.error('Unexpected exception while evaluating Captcha cookie' .. cjson.encode(response)); return 0; end return _M end return M
local t = {} for i = 1, 200 do t[math.random(1000)] = math.random(100) end return t, 30000, 5
local _context = getContext() local _input = _context:getInput() local _painter = _context:getPainter() local _style = _painter:getStyle() exports('slider', function(min, value, max, w) local w = w or _context:getWidgetWidth() local h = _style.widget.height _context:beginDraw(w, h) local sliderStyle = _style.slider local newValue = value local isHovered = _input:isRectHovered(_painter:getX() - sliderStyle.tickMark.width / 2, _painter:getY(), w + sliderStyle.tickMark.width, h) if isHovered and (_input:isMouseDown() or _input:isMousePressed()) then newValue = math.min(max, math.max(min, min + ((_input:getMousePosX() - _painter:getX()) / w * (max + min)))) end local sh = (h - sliderStyle.height) / 2 _painter:setColor(_style.color.widget) _painter:move(0, sh) _painter:drawRect(w, sliderStyle.height) local sx = w * (returnValue or value) / (max + min) local tx = sx - sliderStyle.tickMark.width / 2 local ty = -sliderStyle.tickMark.height / 4 _painter:setColor(isHovered and _style.color.hover or _style.color.primary) _painter:move(tx, ty) _painter:drawRect(sliderStyle.tickMark.width, sliderStyle.tickMark.height) _context:endDraw() return newValue ~= value, newValue end)
---------------------------------------------------------- -- Load RayUI Environment ---------------------------------------------------------- RayUI:LoadEnv("Misc") local M = R:NewModule("Misc", "AceEvent-3.0", "AceTimer-3.0") M.modName = L["小玩意儿"] _Misc = M _Modules = {} function M:RegisterMiscModule(name) table.insert(_Modules, name) end function M:Initialize() local errList, errText = {}, "" for _, name in pairs(_Modules) do local module = self:GetModule(name, true) if module then -- M.Logger:Debug(name .. " Initializing...") local _, catch = pcall(module.Initialize, module) R:ThrowError(catch) else table.insert(errList, name) end end end function M:Info() return L["|cff7aa6d6Ray|r|cffff0000U|r|cff7aa6d6I|r的各种实用便利小功能."] end R:RegisterModule(M:GetName())
-- -- gh-6018: in an auto-election cluster nodes with voter state could be selected -- as bootstrap leaders. They should not, because a voter can't be ever writable -- and it can neither boot itself nor register other nodes. -- -- Similar situation was with the manual election. All instances might have -- manual election mode. Such a cluster wouldn't be able to boot if their -- bootstrap master wouldn't become an elected leader automatically at least -- once. -- test_run = require('test_run').new() function boot_with_master_election_mode(mode) \ test_run:cmd('create server master with '.. \ 'script="replication/gh-6018-master.lua"') \ test_run:cmd('start server master with wait=False, args="'..mode..'"') \ test_run:cmd('create server replica with '.. \ 'script="replication/gh-6018-replica.lua"') \ test_run:cmd('start server replica') \ end function stop_cluster() \ test_run:cmd('stop server replica') \ test_run:cmd('stop server master') \ test_run:cmd('delete server replica') \ test_run:cmd('delete server master') \ end -- -- Candidate leader. -- boot_with_master_election_mode('candidate') test_run:switch('master') test_run:wait_cond(function() return not box.info.ro end) assert(box.info.election.state == 'leader') test_run:switch('replica') assert(box.info.ro) assert(box.info.election.state == 'follower') test_run:switch('default') stop_cluster() -- -- Manual leader. -- boot_with_master_election_mode('manual') test_run:switch('master') test_run:wait_cond(function() return not box.info.ro end) assert(box.info.election.state == 'leader') test_run:switch('replica') assert(box.info.ro) assert(box.info.election.state == 'follower') test_run:switch('default') stop_cluster()
package("cpp-taskflow") set_homepage("https://cpp-taskflow.github.io/") set_description("A fast C++ header-only library to help you quickly write parallel programs with complex task dependencies") add_urls("https://github.com/cpp-taskflow/cpp-taskflow.git") add_urls("https://github.com/cpp-taskflow/cpp-taskflow/archive/v$(version).zip") add_versions("2.2.0", "6b3c3b083e6e93a988cebc8bbf794a78f61904efab21f1e3a667b3cf60d58ca2") on_install(function (package) os.cp("taskflow", package:installdir("include")) end) on_test(function (package) assert(package:check_cxxsnippets({test = [[ #include <assert.h> static void test() { tf::Executor executor; tf::Taskflow taskflow; std::vector<int> range(10); std::vector<int> out(10); std::iota(range.begin(), range.end(), 0); std::iota(out.begin(), out.end(), 0); taskflow.parallel_for(range.begin(), range.end(), [&] (const int i) { out[i] = i; }); executor.run(taskflow).get(); for (int i = 0; i < 10; i++) { assert(out[i] == i); } } ]]}, {configs = {languages = "c++1z"}, includes = "taskflow/taskflow.hpp"})) end)
-- https://github.com/kyazdani42/nvim-tree.lua require("nvim-tree").setup( { -- 自动关闭 auto_close = true, -- 视图 view = { -- 宽度 width = 30, -- 高度 height = 30, -- 隐藏顶部的根目录显示 hide_root_folder = false, -- 自动调整大小 auto_resize = true }, diagnostics = { -- 是否启用文件诊断信息 enable = true, icons = { hint = "", info = "", warning = "", error = "" } }, git = { -- 是否启用 git 信息 enable = true, ignore = true, timeout = 500 } } ) -- 默认图标,可自行修改 vim.g.nvim_tree_icons = { default = " ", symlink = " ", git = { unstaged = "", staged = "✓", unmerged = "", renamed = "➜", untracked = "", deleted = "", ignored = "" }, folder = { -- arrow_open = "╰─▸", -- arrow_closed = "├─▸", arrow_open = "", arrow_closed = "", default = "", open = "", empty = "", empty_open = "", symlink = "", symlink_open = "" } } -- 目录后加上反斜杠 / vim.g.nvim_tree_add_trailing = 1 -- 按 leader 1 打开文件树 vim.keybinds.gmap("n", "<leader>1", "<cmd>NvimTreeToggle<CR>", vim.keybinds.opts) -- 按 leader fc 在文件树中找到当前以打开文件的位置 vim.keybinds.gmap("n", "<leader>fc", "<cmd>NvimTreeFindFile<CR>", vim.keybinds.opts) -- 默认按键 -- o :打开目录或文件 -- a :新增目录或文件 -- r :重命名目录或文件 -- x :剪切目录或文件 -- c :复制目录或文件 -- d :删除目录或文件 -- y :复制目录或文件名称 -- Y :复制目录或文件相对路径 -- gy :复制目录或文件绝对路径 -- p :粘贴目录或文件 -- s :使用系统默认程序打开目录或文件 -- <Tab> :将文件添加到缓冲区,但不移动光标 -- <C-v> :垂直分屏打开文件 -- <C-x> :水平分屏打开文件 -- <C-]> :进入光标下的目录 -- <C-r> :重命名目录或文件,删除已有目录名称 -- - :返回上层目录 -- I :切换隐藏文件/目录的可见性 -- H :切换点文件的可见性 -- R :刷新资源管理器 -- 另外,文件资源管理器操作和操作文档方式一致,可按 / ? 进行搜索
SETTINGS_REFRESH = 2000 -- Interval in which team channels are refreshed, in MS. bShowChatIcons = true voicePlayers = {} globalMuted = {} --- addEventHandler ( "onClientPlayerVoiceStart", root, function() if isPlayerVoiceMuted ( source ) then cancelEvent() return end voicePlayers[source] = true end ) addEventHandler ( "onClientPlayerVoiceStop", root, function() voicePlayers[source] = nil end ) addEventHandler ( "onClientPlayerQuit", root, function() voicePlayers[source] = nil end ) --- function checkValidPlayer ( player ) if not isElement(player) or getElementType(player) ~= "player" then outputDebugString ( "is/setPlayerVoiceMuted: Bad 'player' argument", 2 ) return false end return true end --- setTimer ( function() bShowChatIcons = getElementData ( resourceRoot, "show_chat_icon", show_chat_icon ) end, SETTINGS_REFRESH, 0 )
---------------------------------------------------------- -- Load RayUI Environment ---------------------------------------------------------- RayUI:LoadEnv("Skins") local S = _Skins local function LoadSkin() local r, g, b = _r, _g, _b local PVPQueueFrame = PVPQueueFrame local HonorFrame = HonorFrame local ConquestFrame = ConquestFrame local WarGamesFrame = WarGamesFrame -- Category buttons for i = 1, 4 do local bu = PVPQueueFrame["CategoryButton"..i] local icon = bu.Icon local cu = bu.CurrencyDisplay bu.Ring:Hide() S:Reskin(bu, true) bu.Background:SetAllPoints() bu.Background:SetColorTexture(r, g, b, .2) bu.Background:Hide() icon:SetTexCoord(.08, .92, .08, .92) icon:SetPoint("LEFT", bu, "LEFT") icon:SetDrawLayer("OVERLAY") icon.bg = S:CreateBG(icon) icon.bg:SetDrawLayer("ARTWORK") if cu then local ic = cu.Icon ic:SetSize(16, 16) ic:SetPoint("TOPLEFT", bu.Name, "BOTTOMLEFT", 0, -8) cu.Amount:SetPoint("LEFT", ic, "RIGHT", 4, 0) ic:SetTexCoord(.08, .92, .08, .92) ic.bg = S:CreateBG(ic) ic.bg:SetDrawLayer("BACKGROUND", 1) end end PVPQueueFrame.CategoryButton1.Icon:SetTexture("Interface\\Icons\\achievement_bg_winwsg") PVPQueueFrame.CategoryButton2.Icon:SetTexture("Interface\\Icons\\achievement_bg_killxenemies_generalsroom") PVPQueueFrame.CategoryButton3.Icon:SetTexture("Interface\\Icons\\ability_warrior_offensivestance") local englishFaction = UnitFactionGroup("player") hooksecurefunc("PVPQueueFrame_SelectButton", function(index) local self = PVPQueueFrame for i = 1, 4 do local bu = self["CategoryButton"..i] if i == index then bu.Background:Show() else bu.Background:Hide() end end end) PVPQueueFrame.CategoryButton1.Background:Show() -- Honor frame local Inset = HonorFrame.Inset local BonusFrame = HonorFrame.BonusFrame for i = 1, 9 do select(i, Inset:GetRegions()):Hide() end BonusFrame.WorldBattlesTexture:Hide() BonusFrame.ShadowOverlay:Hide() S:Reskin(BonusFrame.DiceButton) for _, bonusButton in pairs({"RandomBGButton", "Arena1Button", "AshranButton", "BrawlButton"}) do local bu = BonusFrame[bonusButton] local reward = bu.Reward S:Reskin(bu, true) bu.SelectedTexture:SetDrawLayer("BACKGROUND") bu.SelectedTexture:SetColorTexture(r, g, b, .2) bu.SelectedTexture:SetAllPoints() if reward then reward.Border:Hide() S:ReskinIcon(reward.Icon) end end hooksecurefunc("HonorFrameBonusFrame_Update", function() local _, _, _, _, _, winHonorAmount, winConquestAmount = GetRandomBGInfo() local rewardIndex = 0 if winConquestAmount and winConquestAmount > 0 then rewardIndex = rewardIndex + 1 local frame = HonorFrame.BonusFrame["BattlegroundReward"..rewardIndex] frame.Icon:SetTexture("Interface\\Icons\\PVPCurrency-Conquest-"..englishFaction) end if winHonorAmount and winHonorAmount > 0 then rewardIndex = rewardIndex + 1 local frame = HonorFrame.BonusFrame["BattlegroundReward"..rewardIndex] frame.Icon:SetTexture("Interface\\Icons\\PVPCurrency-Honor-"..englishFaction) end end) IncludedBattlegroundsDropDown:SetPoint("TOPRIGHT", BonusFrame.DiceButton, 40, 26) -- Honor frame specific for _, bu in pairs(HonorFrame.SpecificFrame.buttons) do bu.Bg:Hide() bu.Border:Hide() bu:SetNormalTexture("") bu:SetHighlightTexture("") local bg = CreateFrame("Frame", nil, bu) bg:SetPoint("TOPLEFT", 2, 0) bg:SetPoint("BOTTOMRIGHT", -1, 2) S:CreateBD(bg, 0) bg:SetFrameLevel(bu:GetFrameLevel()-1) bu.tex = S:CreateGradient(bu) bu.tex:SetDrawLayer("BACKGROUND") bu.tex:SetPoint("TOPLEFT", bg, 1, -1) bu.tex:SetPoint("BOTTOMRIGHT", bg, -1, 1) bu.SelectedTexture:SetDrawLayer("BACKGROUND") bu.SelectedTexture:SetColorTexture(r, g, b, .2) bu.SelectedTexture:SetAllPoints(bu.tex) bu.Icon:SetTexCoord(.08, .92, .08, .92) bu.Icon.bg = S:CreateBG(bu.Icon) bu.Icon.bg:SetDrawLayer("BACKGROUND", 1) bu.Icon:SetPoint("TOPLEFT", 5, -3) end -- Conquest Frame Inset = ConquestFrame.Inset for i = 1, 9 do select(i, Inset:GetRegions()):Hide() end ConquestFrame.ArenaTexture:Hide() ConquestFrame.RatedBGTexture:Hide() ConquestFrame.ArenaHeader:Hide() ConquestFrame.RatedBGHeader:Hide() ConquestFrame.ShadowOverlay:Hide() S:CreateBD(ConquestTooltip) local ConquestFrameButton_OnEnter = function(self) ConquestTooltip:SetPoint("TOPLEFT", self, "TOPRIGHT", 1, 0) end ConquestFrame.Arena2v2:HookScript("OnEnter", ConquestFrameButton_OnEnter) ConquestFrame.Arena3v3:HookScript("OnEnter", ConquestFrameButton_OnEnter) ConquestFrame.RatedBG:HookScript("OnEnter", ConquestFrameButton_OnEnter) for _, bu in pairs({ConquestFrame.Arena2v2, ConquestFrame.Arena3v3, ConquestFrame.RatedBG}) do S:Reskin(bu, true) local reward = bu.Reward bu.SelectedTexture:SetDrawLayer("BACKGROUND") bu.SelectedTexture:SetColorTexture(r, g, b, .2) bu.SelectedTexture:SetAllPoints() if reward then reward.Border:Hide() S:ReskinIcon(reward.Icon) end end ConquestFrame.Arena3v3:SetPoint("TOP", ConquestFrame.Arena2v2, "BOTTOM", 0, -1) -- War games Inset = WarGamesFrame.RightInset for i = 1, 9 do select(i, Inset:GetRegions()):Hide() end WarGamesFrame.InfoBG:Hide() WarGamesFrame.HorizontalBar:Hide() WarGamesFrameInfoScrollFrame.scrollBarBackground:Hide() WarGamesFrameInfoScrollFrame.scrollBarArtTop:Hide() WarGamesFrameInfoScrollFrame.scrollBarArtBottom:Hide() WarGamesFrameDescription:SetTextColor(.9, .9, .9) local function onSetNormalTexture(self, texture) if texture:find("Plus") then self.plus:Show() else self.plus:Hide() end end for _, button in pairs(WarGamesFrame.scrollFrame.buttons) do local bu = button.Entry local SelectedTexture = bu.SelectedTexture bu.Bg:Hide() bu.Border:Hide() bu:SetNormalTexture("") bu:SetHighlightTexture("") local bg = CreateFrame("Frame", nil, bu) bg:SetPoint("TOPLEFT", 2, 0) bg:SetPoint("BOTTOMRIGHT", -1, 2) S:CreateBD(bg, 0) bg:SetFrameLevel(bu:GetFrameLevel()-1) local tex = S:CreateGradient(bu) tex:SetDrawLayer("BACKGROUND") tex:SetPoint("TOPLEFT", 3, -1) tex:SetPoint("BOTTOMRIGHT", -2, 3) SelectedTexture:SetDrawLayer("BACKGROUND") SelectedTexture:SetColorTexture(r, g, b, .2) SelectedTexture:SetPoint("TOPLEFT", 2, 0) SelectedTexture:SetPoint("BOTTOMRIGHT", -1, 2) bu.Icon:SetTexCoord(.08, .92, .08, .92) bu.Icon.bg = S:CreateBG(bu.Icon) bu.Icon.bg:SetDrawLayer("BACKGROUND", 1) bu.Icon:SetPoint("TOPLEFT", 5, -3) local header = button.Header header:GetNormalTexture():SetAlpha(0) header:SetHighlightTexture("") header:SetPushedTexture("") local headerBg = CreateFrame("Frame", nil, header) headerBg:SetSize(13, 13) headerBg:SetPoint("LEFT", 4, 0) headerBg:SetFrameLevel(header:GetFrameLevel()-1) S:CreateBD(headerBg, 0) local headerTex = S:CreateGradient(header) headerTex:SetAllPoints(headerBg) local minus = header:CreateTexture(nil, "OVERLAY") minus:SetSize(7, 1) minus:SetPoint("CENTER", headerBg) minus:SetTexture(R["media"].blank) minus:SetVertexColor(1, 1, 1) local plus = header:CreateTexture(nil, "OVERLAY") plus:SetSize(1, 7) plus:SetPoint("CENTER", headerBg) plus:SetTexture(R["media"].blank) plus:SetVertexColor(1, 1, 1) header.plus = plus hooksecurefunc(header, "SetNormalTexture", onSetNormalTexture) end S:ReskinCheck(WarGameTournamentModeCheckButton) -- Main style S:Reskin(HonorFrame.QueueButton) S:Reskin(ConquestFrame.JoinButton) S:Reskin(WarGameStartButton) S:ReskinDropDown(HonorFrameTypeDropDown) S:ReskinScroll(HonorFrameSpecificFrameScrollBar) S:ReskinScroll(WarGamesFrameScrollFrameScrollBar) S:ReskinScroll(WarGamesFrameInfoScrollFrameScrollBar) -- Role and XPbar for _, Hfame in pairs({HonorFrame, ConquestFrame}) do Hfame.RoleInset:StripTextures() S:ReskinCheck(Hfame.RoleInset.TankIcon:GetChildren()) S:ReskinCheck(Hfame.RoleInset.HealerIcon:GetChildren()) S:ReskinCheck(Hfame.RoleInset.DPSIcon:GetChildren()) Hfame.XPBar.Frame:Hide() Hfame.XPBar.Bar.OverlayFrame.Text:Point("CENTER" , Hfame.XPBar.Bar.OverlayFrame, "CENTER") local bg = CreateFrame("Frame", nil, Hfame.XPBar.Bar) bg:SetPoint("TOPLEFT", 0, 1) bg:SetPoint("BOTTOMRIGHT", 0, -1) bg:SetFrameLevel(Hfame.XPBar.Bar:GetFrameLevel()-1) S:CreateBD(bg, .3) Hfame.XPBar.Bar.Background:Hide() Hfame.XPBar.NextAvailable.Frame:Hide() Hfame.XPBar.NextAvailable:ClearAllPoints() Hfame.XPBar.NextAvailable:SetPoint("LEFT", Hfame.XPBar.Bar, "RIGHT") Hfame.XPBar.NextAvailable:SetSize(25, 25) Hfame.XPBar.NextAvailable.Icon:SetAllPoints() Hfame.XPBar.NextAvailable.Icon:SetTexCoord(.08, .92, .08, .92) Hfame.XPBar.NextAvailable.Icon.SetTexCoord = R.dummy S:ReskinIcon(Hfame.XPBar.NextAvailable.Icon) Hfame.XPBar.NextAvailable.Frame.Show = R.dummy Hfame.XPBar.Levelbg = CreateFrame("Frame", nil, Hfame.XPBar) Hfame.XPBar.Levelbg:SetPoint("RIGHT", Hfame.XPBar.Bar, "LEFT") Hfame.XPBar.Levelbg:SetSize(25, 25) Hfame.XPBar.Levelbg:SetFrameLevel(1) Hfame.XPBar.Level:SetPoint("CENTER", Hfame.XPBar.Levelbg, "CENTER") Hfame.XPBar.Level:SetJustifyH("CENTER") S:CreateBD(Hfame.XPBar.Levelbg, .5) end for _, tooltip in pairs({ConquestTooltip, PVPRewardTooltip}) do tooltip:SetBackdrop(nil) S:CreateStripesThin(tooltip) tooltip:CreateShadow("Background") tooltip.stripesthin:SetInside(tooltip) tooltip.border:SetInside(tooltip.BackdropFrame) if tooltip.ItemTooltip then tooltip.ItemTooltip.IconBorder:Kill() tooltip.ItemTooltip.Icon:SetTexCoord(0.08, .92, .08, .92) tooltip.ItemTooltip.b = CreateFrame("Frame", nil, tooltip.ItemTooltip) tooltip.ItemTooltip.b:SetAllPoints(tooltip.ItemTooltip.Icon) tooltip.ItemTooltip.b:CreateShadow("Background") tooltip.ItemTooltip.Count:ClearAllPoints() tooltip.ItemTooltip.Count:SetPoint("BOTTOMRIGHT", tooltip.ItemTooltip.Icon, "BOTTOMRIGHT", 0, 2) end end end S:AddCallbackForAddon("Blizzard_PVPUI", "PVP", LoadSkin)
---mc通用接口 ---@class mc mc = {} ---创建表单对象 ---@return CustomForm 新创建的空白表单对象 function mc.newCustomForm() end ---创建表单对象 ---@return SimpleForm 新创建的空白表单对象 function mc.newSimpleForm() end
local http_util=require"http_util" local config=require"config" local mode_map={ [wifi.SOFTAP]="ap", [wifi.STATION]="sta", [wifi.STATIONAP]="sta+ap" } return function(state,send,data) -- XXX: Working around https://github.com/elua/elua/issues/69 local ap_ssid,ap_password=wifi.ap.getconfig() local sta_ssid,sta_password=wifi.sta.getconfig() return http_util.reply_json(send,{name=config.get_value("name"),version=config.get_value("version"),wifi_mode=mode_map[wifi.getmode()],wifi_ap={ap_ssid,ap_password},wifi_sta={sta_ssid,sta_password}}) end
function tableLength(t) local len=0 for k, v in pairs(t) do len=len+1 end return len; end function printTable ( t ) local print_r_cache={} local function sub_print_r(t,indent) if (print_r_cache[tostring(t)]) then print(indent.."*"..tostring(t)) else print_r_cache[tostring(t)]=true if (type(t)=="table") then for pos,val in pairs(t) do if (type(val)=="table") then print(indent.."["..pos.."] => "..tostring(t).." {") sub_print_r(val,indent..string.rep(" ",string.len(pos)+8)) print(indent..string.rep(" ",string.len(pos)+6).."}") elseif (type(val)=="string") then print(indent.."["..pos..'] => "'..val..'"') else print(indent.."["..pos.."] => "..tostring(val)) end end else print(indent..tostring(t)) end end end if (type(t)=="table") then print(tostring(t).." {") sub_print_r(t," ") print("}") else sub_print_r(t," ") end print() end function stringSplit(str, separator) local nFindStartIndex = 1 local nSplitIndex = 1 local nSplitArray = {} while true do local nFindLastIndex = string.find(str, separator, nFindStartIndex) if not nFindLastIndex then nSplitArray[nSplitIndex] = string.sub(str, nFindStartIndex, string.len(str)) break end nSplitArray[nSplitIndex] = string.sub(str, nFindStartIndex, nFindLastIndex - 1) nFindStartIndex = nFindLastIndex + string.len(separator) nSplitIndex = nSplitIndex + 1 end return nSplitArray end
cc = cc or {} ---EaseElastic object ---@class EaseElastic : ActionEase local EaseElastic = {} cc.EaseElastic = EaseElastic -------------------------------- ---brief Set period of the wave in radians.<br> ---param fPeriod The value will be set. ---@param fPeriod float ---@return EaseElastic function EaseElastic:setPeriod(fPeriod) end -------------------------------- ---brief Initializes the action with the inner action and the period in radians.<br> ---param action The pointer of the inner action.<br> ---param period Period of the wave in radians. Default is 0.3.<br> ---return Return true when the initialization success, otherwise return false. ---@param action ActionInterval ---@param period float ---@return bool function EaseElastic:initWithAction(action, period) end -------------------------------- ---brief Get period of the wave in radians. Default value is 0.3.<br> ---return Return the period of the wave in radians. ---@return float function EaseElastic:getPeriod() end return EaseElastic
local T = {} local SHOW_ERRORS = false -- Reset Buffer content. Depends on implementation. local function resetBuf(self, l, i, ones) self.len = l self.i = i table.clear(self.buf) if ones then -- Fill with ones. local n = math.ceil(l/32) for i = 1, n-1 do self.buf[i] = 0xFFFFFFFF end self.buf[n] = 2^((l-1)%32+1)-1 end end local function join(a, b) local c = table.create(#a + #b) table.move(a, 1, #a, 1, c) table.move(b, 1, #b, #a+1, c) return c end local function pass(t, v, msg) msg = msg or "expected pass" if type(v) == "function" then local ok, err = pcall(v) if not ok then t:Errorf("%s: %s", msg, err) return end if not err then t:Error(msg) end elseif not v then t:Errorf(msg) end end local function fail(t, v, msg) msg = msg or "expected fail" if type(v) == "function" then local ok, err = pcall(v) if ok then if err then t:Error(msg) end t:Errorf(msg) return elseif SHOW_ERRORS then t:Logf("ERROR: %s\n", err) end elseif v then t:Errorf(msg) end end local ones do local pow2 = {1, 3, 7, 15, 31, 63, 127} function ones(size) local r = size % 8 if r == 0 then return string.rep("\255", math.floor(size/8)) end return string.rep("\255", math.floor(size/8)) .. string.char(pow2[r]) end end local explodeByte = { [0x00]="00000000",[0x01]="10000000",[0x02]="01000000",[0x03]="11000000", [0x04]="00100000",[0x05]="10100000",[0x06]="01100000",[0x07]="11100000", [0x08]="00010000",[0x09]="10010000",[0x0A]="01010000",[0x0B]="11010000", [0x0C]="00110000",[0x0D]="10110000",[0x0E]="01110000",[0x0F]="11110000", [0x10]="00001000",[0x11]="10001000",[0x12]="01001000",[0x13]="11001000", [0x14]="00101000",[0x15]="10101000",[0x16]="01101000",[0x17]="11101000", [0x18]="00011000",[0x19]="10011000",[0x1A]="01011000",[0x1B]="11011000", [0x1C]="00111000",[0x1D]="10111000",[0x1E]="01111000",[0x1F]="11111000", [0x20]="00000100",[0x21]="10000100",[0x22]="01000100",[0x23]="11000100", [0x24]="00100100",[0x25]="10100100",[0x26]="01100100",[0x27]="11100100", [0x28]="00010100",[0x29]="10010100",[0x2A]="01010100",[0x2B]="11010100", [0x2C]="00110100",[0x2D]="10110100",[0x2E]="01110100",[0x2F]="11110100", [0x30]="00001100",[0x31]="10001100",[0x32]="01001100",[0x33]="11001100", [0x34]="00101100",[0x35]="10101100",[0x36]="01101100",[0x37]="11101100", [0x38]="00011100",[0x39]="10011100",[0x3A]="01011100",[0x3B]="11011100", [0x3C]="00111100",[0x3D]="10111100",[0x3E]="01111100",[0x3F]="11111100", [0x40]="00000010",[0x41]="10000010",[0x42]="01000010",[0x43]="11000010", [0x44]="00100010",[0x45]="10100010",[0x46]="01100010",[0x47]="11100010", [0x48]="00010010",[0x49]="10010010",[0x4A]="01010010",[0x4B]="11010010", [0x4C]="00110010",[0x4D]="10110010",[0x4E]="01110010",[0x4F]="11110010", [0x50]="00001010",[0x51]="10001010",[0x52]="01001010",[0x53]="11001010", [0x54]="00101010",[0x55]="10101010",[0x56]="01101010",[0x57]="11101010", [0x58]="00011010",[0x59]="10011010",[0x5A]="01011010",[0x5B]="11011010", [0x5C]="00111010",[0x5D]="10111010",[0x5E]="01111010",[0x5F]="11111010", [0x60]="00000110",[0x61]="10000110",[0x62]="01000110",[0x63]="11000110", [0x64]="00100110",[0x65]="10100110",[0x66]="01100110",[0x67]="11100110", [0x68]="00010110",[0x69]="10010110",[0x6A]="01010110",[0x6B]="11010110", [0x6C]="00110110",[0x6D]="10110110",[0x6E]="01110110",[0x6F]="11110110", [0x70]="00001110",[0x71]="10001110",[0x72]="01001110",[0x73]="11001110", [0x74]="00101110",[0x75]="10101110",[0x76]="01101110",[0x77]="11101110", [0x78]="00011110",[0x79]="10011110",[0x7A]="01011110",[0x7B]="11011110", [0x7C]="00111110",[0x7D]="10111110",[0x7E]="01111110",[0x7F]="11111110", [0x80]="00000001",[0x81]="10000001",[0x82]="01000001",[0x83]="11000001", [0x84]="00100001",[0x85]="10100001",[0x86]="01100001",[0x87]="11100001", [0x88]="00010001",[0x89]="10010001",[0x8A]="01010001",[0x8B]="11010001", [0x8C]="00110001",[0x8D]="10110001",[0x8E]="01110001",[0x8F]="11110001", [0x90]="00001001",[0x91]="10001001",[0x92]="01001001",[0x93]="11001001", [0x94]="00101001",[0x95]="10101001",[0x96]="01101001",[0x97]="11101001", [0x98]="00011001",[0x99]="10011001",[0x9A]="01011001",[0x9B]="11011001", [0x9C]="00111001",[0x9D]="10111001",[0x9E]="01111001",[0x9F]="11111001", [0xA0]="00000101",[0xA1]="10000101",[0xA2]="01000101",[0xA3]="11000101", [0xA4]="00100101",[0xA5]="10100101",[0xA6]="01100101",[0xA7]="11100101", [0xA8]="00010101",[0xA9]="10010101",[0xAA]="01010101",[0xAB]="11010101", [0xAC]="00110101",[0xAD]="10110101",[0xAE]="01110101",[0xAF]="11110101", [0xB0]="00001101",[0xB1]="10001101",[0xB2]="01001101",[0xB3]="11001101", [0xB4]="00101101",[0xB5]="10101101",[0xB6]="01101101",[0xB7]="11101101", [0xB8]="00011101",[0xB9]="10011101",[0xBA]="01011101",[0xBB]="11011101", [0xBC]="00111101",[0xBD]="10111101",[0xBE]="01111101",[0xBF]="11111101", [0xC0]="00000011",[0xC1]="10000011",[0xC2]="01000011",[0xC3]="11000011", [0xC4]="00100011",[0xC5]="10100011",[0xC6]="01100011",[0xC7]="11100011", [0xC8]="00010011",[0xC9]="10010011",[0xCA]="01010011",[0xCB]="11010011", [0xCC]="00110011",[0xCD]="10110011",[0xCE]="01110011",[0xCF]="11110011", [0xD0]="00001011",[0xD1]="10001011",[0xD2]="01001011",[0xD3]="11001011", [0xD4]="00101011",[0xD5]="10101011",[0xD6]="01101011",[0xD7]="11101011", [0xD8]="00011011",[0xD9]="10011011",[0xDA]="01011011",[0xDB]="11011011", [0xDC]="00111011",[0xDD]="10111011",[0xDE]="01111011",[0xDF]="11111011", [0xE0]="00000111",[0xE1]="10000111",[0xE2]="01000111",[0xE3]="11000111", [0xE4]="00100111",[0xE5]="10100111",[0xE6]="01100111",[0xE7]="11100111", [0xE8]="00010111",[0xE9]="10010111",[0xEA]="01010111",[0xEB]="11010111", [0xEC]="00110111",[0xED]="10110111",[0xEE]="01110111",[0xEF]="11110111", [0xF0]="00001111",[0xF1]="10001111",[0xF2]="01001111",[0xF3]="11001111", [0xF4]="00101111",[0xF5]="10101111",[0xF6]="01101111",[0xF7]="11101111", [0xF8]="00011111",[0xF9]="10011111",[0xFA]="01011111",[0xFB]="11011111", [0xFC]="00111111",[0xFD]="10111111",[0xFE]="01111111",[0xFF]="11111111", } local explode do local a = table.create(512*8) function explode(v, size) size = size or #v*8 if size == 0 then return "" end local n = math.ceil(size/8) for i = 1, n do a[i] = explodeByte[string.byte(v, i)] end a[n] = string.sub(a[n], 1, (size-1)%8+1) return table.concat(a, "", 1, n) end end local function explodeBuf(buf) return explode(buf:String(), buf:Len()) end local unprint = "[^\32-\126]" local function compError(want, got, fn) if string.match(want, unprint) or string.match(got, unprint) then want = "*" .. string.gsub(want, ".", function(c) return string.format("\\x%02X", string.byte(c)) end) got = "*" .. string.gsub(got, ".", function(c) return string.format("\\x%02X", string.byte(c)) end) end if fn then return fn("unexpected buffer content:\n\twant: %s\n\t got: %s", want, got) end return "unexpected buffer content:\n\twant: %s\n\t got: %s", want, got end local function compare(want, got) if got == want then return nil end return compError(want, got) end local function bits(t, buf, bits) if buf:Len() ~= #bits then t:Errorf("expected length %d, got %d", #bits, buf:Len()) return true end local got = explodeBuf(buf) if got ~= bits then t:Errorf(compError(bits, got)) return true end return false end local unitSuite = { lengths = { 00, 01, 02, 15, 16, 17, 31, 32, 33, 47, 48, 49, 63, 64, 65, }, sizes = { 00, 01, 02, 03, 07, 08, 09, 15, 16, 17, 23, 24, 25, 30, 31, 32, }, values = { { value = -8589934594 --[[-2^33-2]] , bytes = "\xFE\xFF\xFF\xFF" , bits = "0111111111111111111111111111111110111111111111111111111111111111" }, { value = -8589934593 --[[-2^33-1]] , bytes = "\xFF\xFF\xFF\xFF" , bits = "1111111111111111111111111111111110111111111111111111111111111111" }, { value = -8589934592 --[[-2^33+0]] , bytes = "\x00\x00\x00\x00" , bits = "0000000000000000000000000000000001111111111111111111111111111111" }, { value = -8589934591 --[[-2^33+1]] , bytes = "\x01\x00\x00\x00" , bits = "1000000000000000000000000000000001111111111111111111111111111111" }, { value = -4294967298 --[[-2^32-2]] , bytes = "\xFE\xFF\xFF\xFF" , bits = "0111111111111111111111111111111101111111111111111111111111111111" }, { value = -4294967297 --[[-2^32-1]] , bytes = "\xFF\xFF\xFF\xFF" , bits = "1111111111111111111111111111111101111111111111111111111111111111" }, { value = -4294967296 --[[-2^32+0]] , bytes = "\x00\x00\x00\x00" , bits = "0000000000000000000000000000000011111111111111111111111111111111" }, { value = -4294967295 --[[-2^32+1]] , bytes = "\x01\x00\x00\x00" , bits = "1000000000000000000000000000000011111111111111111111111111111111" }, { value = -2147483650 --[[-2^31-2]] , bytes = "\xFE\xFF\xFF\x7F" , bits = "0111111111111111111111111111111011111111111111111111111111111111" }, { value = -2147483649 --[[-2^31-1]] , bytes = "\xFF\xFF\xFF\x7F" , bits = "1111111111111111111111111111111011111111111111111111111111111111" }, { value = -2147483648 --[[-2^31+0]] , bytes = "\x00\x00\x00\x80" , bits = "0000000000000000000000000000000111111111111111111111111111111111" }, { value = -2147483647 --[[-2^31+1]] , bytes = "\x01\x00\x00\x80" , bits = "1000000000000000000000000000000111111111111111111111111111111111" }, { value = -33554434 --[[-2^25-2]] , bytes = "\xFE\xFF\xFF\xFD" , bits = "0111111111111111111111111011111111111111111111111111111111111111" }, { value = -33554433 --[[-2^25-1]] , bytes = "\xFF\xFF\xFF\xFD" , bits = "1111111111111111111111111011111111111111111111111111111111111111" }, { value = -33554432 --[[-2^25+0]] , bytes = "\x00\x00\x00\xFE" , bits = "0000000000000000000000000111111111111111111111111111111111111111" }, { value = -33554431 --[[-2^25+1]] , bytes = "\x01\x00\x00\xFE" , bits = "1000000000000000000000000111111111111111111111111111111111111111" }, { value = -16777218 --[[-2^24-2]] , bytes = "\xFE\xFF\xFF\xFE" , bits = "0111111111111111111111110111111111111111111111111111111111111111" }, { value = -16777217 --[[-2^24-1]] , bytes = "\xFF\xFF\xFF\xFE" , bits = "1111111111111111111111110111111111111111111111111111111111111111" }, { value = -16777216 --[[-2^24+0]] , bytes = "\x00\x00\x00\xFF" , bits = "0000000000000000000000001111111111111111111111111111111111111111" }, { value = -16777215 --[[-2^24+1]] , bytes = "\x01\x00\x00\xFF" , bits = "1000000000000000000000001111111111111111111111111111111111111111" }, { value = -8388610 --[[-2^23-2]] , bytes = "\xFE\xFF\x7F\xFF" , bits = "0111111111111111111111101111111111111111111111111111111111111111" }, { value = -8388609 --[[-2^23-1]] , bytes = "\xFF\xFF\x7F\xFF" , bits = "1111111111111111111111101111111111111111111111111111111111111111" }, { value = -8388608 --[[-2^23+0]] , bytes = "\x00\x00\x80\xFF" , bits = "0000000000000000000000011111111111111111111111111111111111111111" }, { value = -8388607 --[[-2^23+1]] , bytes = "\x01\x00\x80\xFF" , bits = "1000000000000000000000011111111111111111111111111111111111111111" }, { value = -131074 --[[-2^17-2]] , bytes = "\xFE\xFF\xFD\xFF" , bits = "0111111111111111101111111111111111111111111111111111111111111111" }, { value = -131073 --[[-2^17-1]] , bytes = "\xFF\xFF\xFD\xFF" , bits = "1111111111111111101111111111111111111111111111111111111111111111" }, { value = -131072 --[[-2^17+0]] , bytes = "\x00\x00\xFE\xFF" , bits = "0000000000000000011111111111111111111111111111111111111111111111" }, { value = -131071 --[[-2^17+1]] , bytes = "\x01\x00\xFE\xFF" , bits = "1000000000000000011111111111111111111111111111111111111111111111" }, { value = -65538 --[[-2^16-2]] , bytes = "\xFE\xFF\xFE\xFF" , bits = "0111111111111111011111111111111111111111111111111111111111111111" }, { value = -65537 --[[-2^16-1]] , bytes = "\xFF\xFF\xFE\xFF" , bits = "1111111111111111011111111111111111111111111111111111111111111111" }, { value = -65536 --[[-2^16+0]] , bytes = "\x00\x00\xFF\xFF" , bits = "0000000000000000111111111111111111111111111111111111111111111111" }, { value = -65535 --[[-2^16+1]] , bytes = "\x01\x00\xFF\xFF" , bits = "1000000000000000111111111111111111111111111111111111111111111111" }, { value = -32770 --[[-2^15-2]] , bytes = "\xFE\x7F\xFF\xFF" , bits = "0111111111111110111111111111111111111111111111111111111111111111" }, { value = -32769 --[[-2^15-1]] , bytes = "\xFF\x7F\xFF\xFF" , bits = "1111111111111110111111111111111111111111111111111111111111111111" }, { value = -32768 --[[-2^15+0]] , bytes = "\x00\x80\xFF\xFF" , bits = "0000000000000001111111111111111111111111111111111111111111111111" }, { value = -32767 --[[-2^15+1]] , bytes = "\x01\x80\xFF\xFF" , bits = "1000000000000001111111111111111111111111111111111111111111111111" }, { value = -514 --[[-2^ 9-2]] , bytes = "\xFE\xFD\xFF\xFF" , bits = "0111111110111111111111111111111111111111111111111111111111111111" }, { value = -513 --[[-2^ 9-1]] , bytes = "\xFF\xFD\xFF\xFF" , bits = "1111111110111111111111111111111111111111111111111111111111111111" }, { value = -512 --[[-2^ 9+0]] , bytes = "\x00\xFE\xFF\xFF" , bits = "0000000001111111111111111111111111111111111111111111111111111111" }, { value = -511 --[[-2^ 9+1]] , bytes = "\x01\xFE\xFF\xFF" , bits = "1000000001111111111111111111111111111111111111111111111111111111" }, { value = -258 --[[-2^ 8-2]] , bytes = "\xFE\xFE\xFF\xFF" , bits = "0111111101111111111111111111111111111111111111111111111111111111" }, { value = -257 --[[-2^ 8-1]] , bytes = "\xFF\xFE\xFF\xFF" , bits = "1111111101111111111111111111111111111111111111111111111111111111" }, { value = -256 --[[-2^ 8+0]] , bytes = "\x00\xFF\xFF\xFF" , bits = "0000000011111111111111111111111111111111111111111111111111111111" }, { value = -255 --[[-2^ 8+1]] , bytes = "\x01\xFF\xFF\xFF" , bits = "1000000011111111111111111111111111111111111111111111111111111111" }, { value = -130 --[[-2^ 7-2]] , bytes = "\x7E\xFF\xFF\xFF" , bits = "0111111011111111111111111111111111111111111111111111111111111111" }, { value = -129 --[[-2^ 7-1]] , bytes = "\x7F\xFF\xFF\xFF" , bits = "1111111011111111111111111111111111111111111111111111111111111111" }, { value = -128 --[[-2^ 7+0]] , bytes = "\x80\xFF\xFF\xFF" , bits = "0000000111111111111111111111111111111111111111111111111111111111" }, { value = -127 --[[-2^ 7+1]] , bytes = "\x81\xFF\xFF\xFF" , bits = "1000000111111111111111111111111111111111111111111111111111111111" }, { value = -4 --[[-2^ 1-2]] , bytes = "\xFC\xFF\xFF\xFF" , bits = "0011111111111111111111111111111111111111111111111111111111111111" }, { value = -3 --[[-2^ 1-1]] , bytes = "\xFD\xFF\xFF\xFF" , bits = "1011111111111111111111111111111111111111111111111111111111111111" }, { value = -2 --[[-2^ 1+0]] , bytes = "\xFE\xFF\xFF\xFF" , bits = "0111111111111111111111111111111111111111111111111111111111111111" }, { value = -1 --[[-2^ 1+1]] , bytes = "\xFF\xFF\xFF\xFF" , bits = "1111111111111111111111111111111111111111111111111111111111111111" }, { value = 0 --[[ 2^ 1-2]] , bytes = "\x00\x00\x00\x00" , bits = "0000000000000000000000000000000000000000000000000000000000000000" }, { value = 1 --[[ 2^ 1-1]] , bytes = "\x01\x00\x00\x00" , bits = "1000000000000000000000000000000000000000000000000000000000000000" }, { value = 2 --[[ 2^ 1+0]] , bytes = "\x02\x00\x00\x00" , bits = "0100000000000000000000000000000000000000000000000000000000000000" }, { value = 3 --[[ 2^ 1+1]] , bytes = "\x03\x00\x00\x00" , bits = "1100000000000000000000000000000000000000000000000000000000000000" }, { value = 126 --[[ 2^ 7-2]] , bytes = "\x7E\x00\x00\x00" , bits = "0111111000000000000000000000000000000000000000000000000000000000" }, { value = 127 --[[ 2^ 7-1]] , bytes = "\x7F\x00\x00\x00" , bits = "1111111000000000000000000000000000000000000000000000000000000000" }, { value = 128 --[[ 2^ 7+0]] , bytes = "\x80\x00\x00\x00" , bits = "0000000100000000000000000000000000000000000000000000000000000000" }, { value = 129 --[[ 2^ 7+1]] , bytes = "\x81\x00\x00\x00" , bits = "1000000100000000000000000000000000000000000000000000000000000000" }, { value = 254 --[[ 2^ 8-2]] , bytes = "\xFE\x00\x00\x00" , bits = "0111111100000000000000000000000000000000000000000000000000000000" }, { value = 255 --[[ 2^ 8-1]] , bytes = "\xFF\x00\x00\x00" , bits = "1111111100000000000000000000000000000000000000000000000000000000" }, { value = 256 --[[ 2^ 8+0]] , bytes = "\x00\x01\x00\x00" , bits = "0000000010000000000000000000000000000000000000000000000000000000" }, { value = 257 --[[ 2^ 8+1]] , bytes = "\x01\x01\x00\x00" , bits = "1000000010000000000000000000000000000000000000000000000000000000" }, { value = 510 --[[ 2^ 9-2]] , bytes = "\xFE\x01\x00\x00" , bits = "0111111110000000000000000000000000000000000000000000000000000000" }, { value = 511 --[[ 2^ 9-1]] , bytes = "\xFF\x01\x00\x00" , bits = "1111111110000000000000000000000000000000000000000000000000000000" }, { value = 512 --[[ 2^ 9+0]] , bytes = "\x00\x02\x00\x00" , bits = "0000000001000000000000000000000000000000000000000000000000000000" }, { value = 513 --[[ 2^ 9+1]] , bytes = "\x01\x02\x00\x00" , bits = "1000000001000000000000000000000000000000000000000000000000000000" }, { value = 32766 --[[ 2^15-2]] , bytes = "\xFE\x7F\x00\x00" , bits = "0111111111111110000000000000000000000000000000000000000000000000" }, { value = 32767 --[[ 2^15-1]] , bytes = "\xFF\x7F\x00\x00" , bits = "1111111111111110000000000000000000000000000000000000000000000000" }, { value = 32768 --[[ 2^15+0]] , bytes = "\x00\x80\x00\x00" , bits = "0000000000000001000000000000000000000000000000000000000000000000" }, { value = 32769 --[[ 2^15+1]] , bytes = "\x01\x80\x00\x00" , bits = "1000000000000001000000000000000000000000000000000000000000000000" }, { value = 65534 --[[ 2^16-2]] , bytes = "\xFE\xFF\x00\x00" , bits = "0111111111111111000000000000000000000000000000000000000000000000" }, { value = 65535 --[[ 2^16-1]] , bytes = "\xFF\xFF\x00\x00" , bits = "1111111111111111000000000000000000000000000000000000000000000000" }, { value = 65536 --[[ 2^16+0]] , bytes = "\x00\x00\x01\x00" , bits = "0000000000000000100000000000000000000000000000000000000000000000" }, { value = 65537 --[[ 2^16+1]] , bytes = "\x01\x00\x01\x00" , bits = "1000000000000000100000000000000000000000000000000000000000000000" }, { value = 131070 --[[ 2^17-2]] , bytes = "\xFE\xFF\x01\x00" , bits = "0111111111111111100000000000000000000000000000000000000000000000" }, { value = 131071 --[[ 2^17-1]] , bytes = "\xFF\xFF\x01\x00" , bits = "1111111111111111100000000000000000000000000000000000000000000000" }, { value = 131072 --[[ 2^17+0]] , bytes = "\x00\x00\x02\x00" , bits = "0000000000000000010000000000000000000000000000000000000000000000" }, { value = 131073 --[[ 2^17+1]] , bytes = "\x01\x00\x02\x00" , bits = "1000000000000000010000000000000000000000000000000000000000000000" }, { value = 8388606 --[[ 2^23-2]] , bytes = "\xFE\xFF\x7F\x00" , bits = "0111111111111111111111100000000000000000000000000000000000000000" }, { value = 8388607 --[[ 2^23-1]] , bytes = "\xFF\xFF\x7F\x00" , bits = "1111111111111111111111100000000000000000000000000000000000000000" }, { value = 8388608 --[[ 2^23+0]] , bytes = "\x00\x00\x80\x00" , bits = "0000000000000000000000010000000000000000000000000000000000000000" }, { value = 8388609 --[[ 2^23+1]] , bytes = "\x01\x00\x80\x00" , bits = "1000000000000000000000010000000000000000000000000000000000000000" }, { value = 16777214 --[[ 2^24-2]] , bytes = "\xFE\xFF\xFF\x00" , bits = "0111111111111111111111110000000000000000000000000000000000000000" }, { value = 16777215 --[[ 2^24-1]] , bytes = "\xFF\xFF\xFF\x00" , bits = "1111111111111111111111110000000000000000000000000000000000000000" }, { value = 16777216 --[[ 2^24+0]] , bytes = "\x00\x00\x00\x01" , bits = "0000000000000000000000001000000000000000000000000000000000000000" }, { value = 16777217 --[[ 2^24+1]] , bytes = "\x01\x00\x00\x01" , bits = "1000000000000000000000001000000000000000000000000000000000000000" }, { value = 33554430 --[[ 2^25-2]] , bytes = "\xFE\xFF\xFF\x01" , bits = "0111111111111111111111111000000000000000000000000000000000000000" }, { value = 33554431 --[[ 2^25-1]] , bytes = "\xFF\xFF\xFF\x01" , bits = "1111111111111111111111111000000000000000000000000000000000000000" }, { value = 33554432 --[[ 2^25+0]] , bytes = "\x00\x00\x00\x02" , bits = "0000000000000000000000000100000000000000000000000000000000000000" }, { value = 33554433 --[[ 2^25+1]] , bytes = "\x01\x00\x00\x02" , bits = "1000000000000000000000000100000000000000000000000000000000000000" }, { value = 2147483646 --[[ 2^31-2]] , bytes = "\xFE\xFF\xFF\x7F" , bits = "0111111111111111111111111111111000000000000000000000000000000000" }, { value = 2147483647 --[[ 2^31-1]] , bytes = "\xFF\xFF\xFF\x7F" , bits = "1111111111111111111111111111111000000000000000000000000000000000" }, { value = 2147483648 --[[ 2^31+0]] , bytes = "\x00\x00\x00\x80" , bits = "0000000000000000000000000000000100000000000000000000000000000000" }, { value = 2147483649 --[[ 2^31+1]] , bytes = "\x01\x00\x00\x80" , bits = "1000000000000000000000000000000100000000000000000000000000000000" }, { value = 4294967294 --[[ 2^32-2]] , bytes = "\xFE\xFF\xFF\xFF" , bits = "0111111111111111111111111111111100000000000000000000000000000000" }, { value = 4294967295 --[[ 2^32-1]] , bytes = "\xFF\xFF\xFF\xFF" , bits = "1111111111111111111111111111111100000000000000000000000000000000" }, { value = 4294967296 --[[ 2^32+0]] , bytes = "\x00\x00\x00\x00" , bits = "0000000000000000000000000000000010000000000000000000000000000000" }, { value = 4294967297 --[[ 2^32+1]] , bytes = "\x01\x00\x00\x00" , bits = "1000000000000000000000000000000010000000000000000000000000000000" }, { value = 8589934590 --[[ 2^33-2]] , bytes = "\xFE\xFF\xFF\xFF" , bits = "0111111111111111111111111111111110000000000000000000000000000000" }, { value = 8589934591 --[[ 2^33-1]] , bytes = "\xFF\xFF\xFF\xFF" , bits = "1111111111111111111111111111111110000000000000000000000000000000" }, { value = 8589934592 --[[ 2^33+0]] , bytes = "\x00\x00\x00\x00" , bits = "0000000000000000000000000000000001000000000000000000000000000000" }, { value = 8589934593 --[[ 2^33+1]] , bytes = "\x01\x00\x00\x00" , bits = "1000000000000000000000000000000001000000000000000000000000000000" }, { value = -3713140662 , bytes = "\x4A\xF8\xAD\x22" , bits = "0101001000011111101101010100010011111111111111111111111111111111" }, { value = -3373259426 , bytes = "\x5E\x25\xF0\x36" , bits = "0111101010100100000011110110110011111111111111111111111111111111" }, { value = -3131314028 , bytes = "\x94\xF0\x5B\x45" , bits = "0010100100001111110110101010001011111111111111111111111111111111" }, { value = -2608337582 , bytes = "\x52\xED\x87\x64" , bits = "0100101010110111111000010010011011111111111111111111111111111111" }, { value = -2451551556 , bytes = "\xBC\x4A\xE0\x6D" , bits = "0011110101010010000001111011011011111111111111111111111111111111" }, { value = -2327306534 , bytes = "\xDA\x1E\x48\x75" , bits = "0101101101111000000100101010111011111111111111111111111111111111" }, { value = -1967660761 , bytes = "\x27\xE1\xB7\x8A" , bits = "1110010010000111111011010101000111111111111111111111111111111111" }, { value = -1843415739 , bytes = "\x45\xB5\x1F\x92" , bits = "1010001010101101111110000100100111111111111111111111111111111111" }, { value = -1686629713 , bytes = "\xAF\x12\x78\x9B" , bits = "1111010101001000000111101101100111111111111111111111111111111111" }, { value = -1163653267 , bytes = "\x6D\x0F\xA4\xBA" , bits = "1011011011110000001001010101110111111111111111111111111111111111" }, { value = -921707869 , bytes = "\xA3\xDA\x0F\xC9" , bits = "1100010101011011111100001001001111111111111111111111111111111111" }, { value = -581826633 , bytes = "\xB7\x07\x52\xDD" , bits = "1110110111100000010010101011101111111111111111111111111111111111" }, { value = 581826633 , bytes = "\x49\xF8\xAD\x22" , bits = "1001001000011111101101010100010000000000000000000000000000000000" }, { value = 921707869 , bytes = "\x5D\x25\xF0\x36" , bits = "1011101010100100000011110110110000000000000000000000000000000000" }, { value = 1163653267 , bytes = "\x93\xF0\x5B\x45" , bits = "1100100100001111110110101010001000000000000000000000000000000000" }, { value = 1686629713 , bytes = "\x51\xED\x87\x64" , bits = "1000101010110111111000010010011000000000000000000000000000000000" }, { value = 1843415739 , bytes = "\xBB\x4A\xE0\x6D" , bits = "1101110101010010000001111011011000000000000000000000000000000000" }, { value = 1967660761 , bytes = "\xD9\x1E\x48\x75" , bits = "1001101101111000000100101010111000000000000000000000000000000000" }, { value = 2327306534 , bytes = "\x26\xE1\xB7\x8A" , bits = "0110010010000111111011010101000100000000000000000000000000000000" }, { value = 2451551556 , bytes = "\x44\xB5\x1F\x92" , bits = "0010001010101101111110000100100100000000000000000000000000000000" }, { value = 2608337582 , bytes = "\xAE\x12\x78\x9B" , bits = "0111010101001000000111101101100100000000000000000000000000000000" }, { value = 3131314028 , bytes = "\x6C\x0F\xA4\xBA" , bits = "0011011011110000001001010101110100000000000000000000000000000000" }, { value = 3373259426 , bytes = "\xA2\xDA\x0F\xC9" , bits = "0100010101011011111100001001001100000000000000000000000000000000" }, { value = 3713140662 , bytes = "\xB6\x07\x52\xDD" , bits = "0110110111100000010010101011101100000000000000000000000000000000" }, }, } local intSuite = { lengths = {}, sizes = { 39, 40, 41, 47, 48, 49, 51, 52, 53, }, values = { -- { value = -9007199254740994 --[[-2^53-2]] , bytes = "\xFE\xFF\xFF\xFF\xFF\xFF\xDF\xFF" , bits = "0111111111111111111111111111111111111111111111111111101111111111" }, -- { value = -9007199254740993 --[[-2^53-1]] , bytes = "\xFF\xFF\xFF\xFF\xFF\xFF\xDF\xFF" , bits = "1111111111111111111111111111111111111111111111111111101111111111" }, { value = -9007199254740992 --[[-2^53+0]] , bytes = "\x00\x00\x00\x00\x00\x00\xE0\xFF" , bits = "0000000000000000000000000000000000000000000000000000011111111111" }, { value = -9007199254740991 --[[-2^53+1]] , bytes = "\x01\x00\x00\x00\x00\x00\xE0\xFF" , bits = "1000000000000000000000000000000000000000000000000000011111111111" }, { value = -4503599627370498 --[[-2^52-2]] , bytes = "\xFE\xFF\xFF\xFF\xFF\xFF\xEF\xFF" , bits = "0111111111111111111111111111111111111111111111111111011111111111" }, { value = -4503599627370497 --[[-2^52-1]] , bytes = "\xFF\xFF\xFF\xFF\xFF\xFF\xEF\xFF" , bits = "1111111111111111111111111111111111111111111111111111011111111111" }, { value = -4503599627370496 --[[-2^52+0]] , bytes = "\x00\x00\x00\x00\x00\x00\xF0\xFF" , bits = "0000000000000000000000000000000000000000000000000000111111111111" }, { value = -4503599627370495 --[[-2^52+1]] , bytes = "\x01\x00\x00\x00\x00\x00\xF0\xFF" , bits = "1000000000000000000000000000000000000000000000000000111111111111" }, { value = -2251799813685250 --[[-2^51-2]] , bytes = "\xFE\xFF\xFF\xFF\xFF\xFF\xF7\xFF" , bits = "0111111111111111111111111111111111111111111111111110111111111111" }, { value = -2251799813685249 --[[-2^51-1]] , bytes = "\xFF\xFF\xFF\xFF\xFF\xFF\xF7\xFF" , bits = "1111111111111111111111111111111111111111111111111110111111111111" }, { value = -2251799813685248 --[[-2^51+0]] , bytes = "\x00\x00\x00\x00\x00\x00\xF8\xFF" , bits = "0000000000000000000000000000000000000000000000000001111111111111" }, { value = -2251799813685247 --[[-2^51+1]] , bytes = "\x01\x00\x00\x00\x00\x00\xF8\xFF" , bits = "1000000000000000000000000000000000000000000000000001111111111111" }, { value = -562949953421314 --[[-2^49-2]] , bytes = "\xFE\xFF\xFF\xFF\xFF\xFF\xFD\xFF" , bits = "0111111111111111111111111111111111111111111111111011111111111111" }, { value = -562949953421313 --[[-2^49-1]] , bytes = "\xFF\xFF\xFF\xFF\xFF\xFF\xFD\xFF" , bits = "1111111111111111111111111111111111111111111111111011111111111111" }, { value = -562949953421312 --[[-2^49+0]] , bytes = "\x00\x00\x00\x00\x00\x00\xFE\xFF" , bits = "0000000000000000000000000000000000000000000000000111111111111111" }, { value = -562949953421311 --[[-2^49+1]] , bytes = "\x01\x00\x00\x00\x00\x00\xFE\xFF" , bits = "1000000000000000000000000000000000000000000000000111111111111111" }, { value = -281474976710658 --[[-2^48-2]] , bytes = "\xFE\xFF\xFF\xFF\xFF\xFF\xFE\xFF" , bits = "0111111111111111111111111111111111111111111111110111111111111111" }, { value = -281474976710657 --[[-2^48-1]] , bytes = "\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF" , bits = "1111111111111111111111111111111111111111111111110111111111111111" }, { value = -281474976710656 --[[-2^48+0]] , bytes = "\x00\x00\x00\x00\x00\x00\xFF\xFF" , bits = "0000000000000000000000000000000000000000000000001111111111111111" }, { value = -281474976710655 --[[-2^48+1]] , bytes = "\x01\x00\x00\x00\x00\x00\xFF\xFF" , bits = "1000000000000000000000000000000000000000000000001111111111111111" }, { value = -140737488355330 --[[-2^47-2]] , bytes = "\xFE\xFF\xFF\xFF\xFF\x7F\xFF\xFF" , bits = "0111111111111111111111111111111111111111111111101111111111111111" }, { value = -140737488355329 --[[-2^47-1]] , bytes = "\xFF\xFF\xFF\xFF\xFF\x7F\xFF\xFF" , bits = "1111111111111111111111111111111111111111111111101111111111111111" }, { value = -140737488355328 --[[-2^47+0]] , bytes = "\x00\x00\x00\x00\x00\x80\xFF\xFF" , bits = "0000000000000000000000000000000000000000000000011111111111111111" }, { value = -140737488355327 --[[-2^47+1]] , bytes = "\x01\x00\x00\x00\x00\x80\xFF\xFF" , bits = "1000000000000000000000000000000000000000000000011111111111111111" }, { value = -2199023255554 --[[-2^41-2]] , bytes = "\xFE\xFF\xFF\xFF\xFF\xFD\xFF\xFF" , bits = "0111111111111111111111111111111111111111101111111111111111111111" }, { value = -2199023255553 --[[-2^41-1]] , bytes = "\xFF\xFF\xFF\xFF\xFF\xFD\xFF\xFF" , bits = "1111111111111111111111111111111111111111101111111111111111111111" }, { value = -2199023255552 --[[-2^41+0]] , bytes = "\x00\x00\x00\x00\x00\xFE\xFF\xFF" , bits = "0000000000000000000000000000000000000000011111111111111111111111" }, { value = -2199023255551 --[[-2^41+1]] , bytes = "\x01\x00\x00\x00\x00\xFE\xFF\xFF" , bits = "1000000000000000000000000000000000000000011111111111111111111111" }, { value = -1099511627778 --[[-2^40-2]] , bytes = "\xFE\xFF\xFF\xFF\xFF\xFE\xFF\xFF" , bits = "0111111111111111111111111111111111111111011111111111111111111111" }, { value = -1099511627777 --[[-2^40-1]] , bytes = "\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF" , bits = "1111111111111111111111111111111111111111011111111111111111111111" }, { value = -1099511627776 --[[-2^40+0]] , bytes = "\x00\x00\x00\x00\x00\xFF\xFF\xFF" , bits = "0000000000000000000000000000000000000000111111111111111111111111" }, { value = -1099511627775 --[[-2^40+1]] , bytes = "\x01\x00\x00\x00\x00\xFF\xFF\xFF" , bits = "1000000000000000000000000000000000000000111111111111111111111111" }, { value = -549755813890 --[[-2^39-2]] , bytes = "\xFE\xFF\xFF\xFF\x7F\xFF\xFF\xFF" , bits = "0111111111111111111111111111111111111110111111111111111111111111" }, { value = -549755813889 --[[-2^39-1]] , bytes = "\xFF\xFF\xFF\xFF\x7F\xFF\xFF\xFF" , bits = "1111111111111111111111111111111111111110111111111111111111111111" }, { value = -549755813888 --[[-2^39+0]] , bytes = "\x00\x00\x00\x00\x80\xFF\xFF\xFF" , bits = "0000000000000000000000000000000000000001111111111111111111111111" }, { value = -549755813887 --[[-2^39+1]] , bytes = "\x01\x00\x00\x00\x80\xFF\xFF\xFF" , bits = "1000000000000000000000000000000000000001111111111111111111111111" }, { value = 549755813886 --[[ 2^39-2]] , bytes = "\xFE\xFF\xFF\xFF\x7F\x00\x00\x00" , bits = "0111111111111111111111111111111111111110000000000000000000000000" }, { value = 549755813887 --[[ 2^39-1]] , bytes = "\xFF\xFF\xFF\xFF\x7F\x00\x00\x00" , bits = "1111111111111111111111111111111111111110000000000000000000000000" }, { value = 549755813888 --[[ 2^39+0]] , bytes = "\x00\x00\x00\x00\x80\x00\x00\x00" , bits = "0000000000000000000000000000000000000001000000000000000000000000" }, { value = 549755813889 --[[ 2^39+1]] , bytes = "\x01\x00\x00\x00\x80\x00\x00\x00" , bits = "1000000000000000000000000000000000000001000000000000000000000000" }, { value = 1099511627774 --[[ 2^40-2]] , bytes = "\xFE\xFF\xFF\xFF\xFF\x00\x00\x00" , bits = "0111111111111111111111111111111111111111000000000000000000000000" }, { value = 1099511627775 --[[ 2^40-1]] , bytes = "\xFF\xFF\xFF\xFF\xFF\x00\x00\x00" , bits = "1111111111111111111111111111111111111111000000000000000000000000" }, { value = 1099511627776 --[[ 2^40+0]] , bytes = "\x00\x00\x00\x00\x00\x01\x00\x00" , bits = "0000000000000000000000000000000000000000100000000000000000000000" }, { value = 1099511627777 --[[ 2^40+1]] , bytes = "\x01\x00\x00\x00\x00\x01\x00\x00" , bits = "1000000000000000000000000000000000000000100000000000000000000000" }, { value = 2199023255550 --[[ 2^41-2]] , bytes = "\xFE\xFF\xFF\xFF\xFF\x01\x00\x00" , bits = "0111111111111111111111111111111111111111100000000000000000000000" }, { value = 2199023255551 --[[ 2^41-1]] , bytes = "\xFF\xFF\xFF\xFF\xFF\x01\x00\x00" , bits = "1111111111111111111111111111111111111111100000000000000000000000" }, { value = 2199023255552 --[[ 2^41+0]] , bytes = "\x00\x00\x00\x00\x00\x02\x00\x00" , bits = "0000000000000000000000000000000000000000010000000000000000000000" }, { value = 2199023255553 --[[ 2^41+1]] , bytes = "\x01\x00\x00\x00\x00\x02\x00\x00" , bits = "1000000000000000000000000000000000000000010000000000000000000000" }, { value = 140737488355326 --[[ 2^47-2]] , bytes = "\xFE\xFF\xFF\xFF\xFF\x7F\x00\x00" , bits = "0111111111111111111111111111111111111111111111100000000000000000" }, { value = 140737488355327 --[[ 2^47-1]] , bytes = "\xFF\xFF\xFF\xFF\xFF\x7F\x00\x00" , bits = "1111111111111111111111111111111111111111111111100000000000000000" }, { value = 140737488355328 --[[ 2^47+0]] , bytes = "\x00\x00\x00\x00\x00\x80\x00\x00" , bits = "0000000000000000000000000000000000000000000000010000000000000000" }, { value = 140737488355329 --[[ 2^47+1]] , bytes = "\x01\x00\x00\x00\x00\x80\x00\x00" , bits = "1000000000000000000000000000000000000000000000010000000000000000" }, { value = 281474976710654 --[[ 2^48-2]] , bytes = "\xFE\xFF\xFF\xFF\xFF\xFF\x00\x00" , bits = "0111111111111111111111111111111111111111111111110000000000000000" }, { value = 281474976710655 --[[ 2^48-1]] , bytes = "\xFF\xFF\xFF\xFF\xFF\xFF\x00\x00" , bits = "1111111111111111111111111111111111111111111111110000000000000000" }, { value = 281474976710656 --[[ 2^48+0]] , bytes = "\x00\x00\x00\x00\x00\x00\x01\x00" , bits = "0000000000000000000000000000000000000000000000001000000000000000" }, { value = 281474976710657 --[[ 2^48+1]] , bytes = "\x01\x00\x00\x00\x00\x00\x01\x00" , bits = "1000000000000000000000000000000000000000000000001000000000000000" }, { value = 562949953421310 --[[ 2^49-2]] , bytes = "\xFE\xFF\xFF\xFF\xFF\xFF\x01\x00" , bits = "0111111111111111111111111111111111111111111111111000000000000000" }, { value = 562949953421311 --[[ 2^49-1]] , bytes = "\xFF\xFF\xFF\xFF\xFF\xFF\x01\x00" , bits = "1111111111111111111111111111111111111111111111111000000000000000" }, { value = 562949953421312 --[[ 2^49+0]] , bytes = "\x00\x00\x00\x00\x00\x00\x02\x00" , bits = "0000000000000000000000000000000000000000000000000100000000000000" }, { value = 562949953421313 --[[ 2^49+1]] , bytes = "\x01\x00\x00\x00\x00\x00\x02\x00" , bits = "1000000000000000000000000000000000000000000000000100000000000000" }, { value = 2251799813685246 --[[ 2^51-2]] , bytes = "\xFE\xFF\xFF\xFF\xFF\xFF\x07\x00" , bits = "0111111111111111111111111111111111111111111111111110000000000000" }, { value = 2251799813685247 --[[ 2^51-1]] , bytes = "\xFF\xFF\xFF\xFF\xFF\xFF\x07\x00" , bits = "1111111111111111111111111111111111111111111111111110000000000000" }, { value = 2251799813685248 --[[ 2^51+0]] , bytes = "\x00\x00\x00\x00\x00\x00\x08\x00" , bits = "0000000000000000000000000000000000000000000000000001000000000000" }, { value = 2251799813685249 --[[ 2^51+1]] , bytes = "\x01\x00\x00\x00\x00\x00\x08\x00" , bits = "1000000000000000000000000000000000000000000000000001000000000000" }, { value = 4503599627370494 --[[ 2^52-2]] , bytes = "\xFE\xFF\xFF\xFF\xFF\xFF\x0F\x00" , bits = "0111111111111111111111111111111111111111111111111111000000000000" }, { value = 4503599627370495 --[[ 2^52-1]] , bytes = "\xFF\xFF\xFF\xFF\xFF\xFF\x0F\x00" , bits = "1111111111111111111111111111111111111111111111111111000000000000" }, { value = 4503599627370496 --[[ 2^52+0]] , bytes = "\x00\x00\x00\x00\x00\x00\x10\x00" , bits = "0000000000000000000000000000000000000000000000000000100000000000" }, { value = 4503599627370497 --[[ 2^52+1]] , bytes = "\x01\x00\x00\x00\x00\x00\x10\x00" , bits = "1000000000000000000000000000000000000000000000000000100000000000" }, { value = 9007199254740990 --[[ 2^53-2]] , bytes = "\xFE\xFF\xFF\xFF\xFF\xFF\x1F\x00" , bits = "0111111111111111111111111111111111111111111111111111100000000000" }, { value = 9007199254740991 --[[ 2^53-1]] , bytes = "\xFF\xFF\xFF\xFF\xFF\xFF\x1F\x00" , bits = "1111111111111111111111111111111111111111111111111111100000000000" }, { value = 9007199254740992 --[[ 2^53+0]] , bytes = "\x00\x00\x00\x00\x00\x00\x20\x00" , bits = "0000000000000000000000000000000000000000000000000000010000000000" }, -- { value = 9007199254740993 --[[ 2^53+1]] , bytes = "\x01\x00\x00\x00\x00\x00\x20\x00" , bits = "1000000000000000000000000000000000000000000000000000010000000000" }, }, } intSuite = { lengths = join(unitSuite.lengths, intSuite.lengths), sizes = join(unitSuite.sizes, intSuite.sizes), values = join(unitSuite.values, intSuite.values), } local unitTestInterval = 1 local function testSuite(t, Bitbuf, suite, cb) local n = 0 local time = os.clock() local lengths = suite.lengths if not lengths then lengths = {0} elseif type(lengths) == "number" then local a = table.create(lengths+1, 0) for i in ipairs(a) do a[i] = i-1 end lengths = a end local sizes = suite.sizes if not sizes then sizes = {0} elseif type(sizes) == "number" then local a = table.create(sizes+1, 0) for i in ipairs(a) do a[i] = i-1 end sizes = a end local values = suite.values if not values then values = {{value=0, bytes="\0", bits="0"}} elseif type(values) == "number" then local a = table.create(values+1, 0) for i in ipairs(a) do a[i] = {value = i-1, bits = explodeByte[i-1]} end values = a end local buf if Bitbuf then buf = Bitbuf.new(sizes[#sizes]) end for l, length in ipairs(lengths) do for i = 1, l do local index = lengths[i] for _, size in ipairs(sizes) do for _, value in ipairs(values) do if buf then resetBuf(buf, length, index, suite.ones) end local r = {cb(buf, length, index, size, value)} if r[1] then t:Errorf("[%d:%d:%d:%d]: " .. r[1], length, index, size, value.value, unpack(r, 2)) n = n + 1 end if n >= 10 then t:Fatal("too many errors") end if os.clock()-time >= unitTestInterval then t:Yield() time = os.clock() end end end end end end local pi64Bits = string.pack("<d", math.pi) local pi32Bits = string.pack("<f", math.pi) function T.TestNew(t, require) local Bitbuf = require() pass(t, Bitbuf.new():Len() == 0, "no argument expects zero-length buffer") pass(t, Bitbuf.new(42):Len() == 42, "argument sets buffer length") pass(t, Bitbuf.new(42):Index() == 0, "index of new buffer is 0") bits(t, Bitbuf.new(42), "000000000000000000000000000000000000000000") end function T.TestFromString(t, require) local Bitbuf = require() bits(t, Bitbuf.fromString(string.sub(pi64Bits, 1, 8)), "0001100010110100001000100010101011011111100001001001000000000010") bits(t, Bitbuf.fromString(string.sub(pi64Bits, 1, 7)), "00011000101101000010001000101010110111111000010010010000") bits(t, Bitbuf.fromString(string.sub(pi64Bits, 1, 6)), "000110001011010000100010001010101101111110000100") bits(t, Bitbuf.fromString(string.sub(pi64Bits, 1, 5)), "0001100010110100001000100010101011011111") bits(t, Bitbuf.fromString(string.sub(pi64Bits, 1, 4)), "00011000101101000010001000101010") bits(t, Bitbuf.fromString(string.sub(pi64Bits, 1, 3)), "000110001011010000100010") bits(t, Bitbuf.fromString(string.sub(pi64Bits, 1, 2)), "0001100010110100") bits(t, Bitbuf.fromString(string.sub(pi64Bits, 1, 1)), "00011000") bits(t, Bitbuf.fromString(""), "") end function T.TestBuffer_String(t, require) local Bitbuf = require() local bytes = "\x18\x2D\x44\x54\xFB\x21\x09\x40" for i = 0, #bytes do local want = string.sub(bytes, 1, i) local buf = Bitbuf.fromString(want) local got = buf:String() if got ~= want then t:Errorf(compError(want, buf:String())) end end local buf = Bitbuf.new() for l = 0, 64 do resetBuf(buf, l, 0, true) local want = string.rep("1", l) .. string.rep("0", math.ceil(l/8)*8-l) local got = explode(buf:String()) if got ~= want then t:Errorf(compError(want, got)) end end end function T.TestBuffer_writeUnit(t, require) local Bitbuf = require() testSuite(t, Bitbuf, unitSuite, function(buf, l, i, s, v) buf:writeUnit(s, v.value) local expi = i + s local explen = math.max(expi, l) if buf:Len() ~= explen then return "expected length %d, got %d", explen, buf:Len() end if buf:Index() ~= expi then return "expected index %d, got %d", expi, buf:Index() end local want = string.rep("0", i) .. string.sub(v.bits, 1, s) .. string.rep("0", l-i-s) local got = explodeBuf(buf) return compare(want, got) end) end function T.TestBuffer_readUnit(t, require) local Bitbuf = require() testSuite(t, Bitbuf, unitSuite, function(buf, l, i, s, v) buf:writeUnit(s, v.value) buf:SetIndex(i) local value = buf:readUnit(s) local expi = i + s local explen = math.max(expi, l) if buf:Len() ~= explen then return "expected length %d, got %d", explen, buf:Len() end if buf:Index() ~= expi then return "expected index %d, got %d", expi, buf:Index() end local want = bit32.band(v.value, 2^s-1) if value ~= want then return "expected value %d, got %d", want, value end end) end function T.TestBuffer_Len(t, require) local Bitbuf = require() for i = 0, 256 do local n = Bitbuf.new(i):Len() if n ~= i then t:Errorf("length %d expected, got %d", i, n) end end end function T.TestBuffer_SetLen(t, require) local Bitbuf = require() testSuite(t, nil, {lengths = unitSuite.lengths}, function(_, l, i, _, _) local buf = Bitbuf.new() buf:SetIndex(i) buf:SetLen(l) if buf:Len() ~= l then return "expected length %d, got %d", l, buf:Len() end local expi = math.min(i, l) if buf:Index() ~= expi then return "expected index %d, got %d", expi, buf:Index() end local want = string.rep("0", l) local got = explodeBuf(buf) return compare(want, got) end) end function T.TestBuffer_Index(t, require) local Bitbuf = require() pass(t, Bitbuf.new(42):Index() == 0, "new buffer index is 0") local buf = Bitbuf.new() pass(t, buf:Index() == 0, "buffer index is 0") pass(t, buf:Len() == 0, "buffer length is 0") bits(t, buf, "") buf:SetIndex(10) pass(t, buf:Index() == 10, "buffer index set to 10") pass(t, buf:Len() == 10, "buffer length grows to 10") bits(t, buf, "0000000000") buf:SetIndex(5) pass(t, buf:Index() == 5, "buffer index set to 5") pass(t, buf:Len() == 10, "buffer length still 10") bits(t, buf, "0000000000") buf:SetIndex(202) pass(t, buf:Index() == 202, "buffer index set to 202") pass(t, buf:Len() == 202, "buffer length grows to 202") bits(t, buf, string.rep("0", 202)) buf:SetIndex(20) pass(t, buf:Index() == 20, "buffer index set to 20") pass(t, buf:Len() == 202, "buffer length still 202") bits(t, buf, string.rep("0", 202)) buf:SetIndex(-10) pass(t, buf:Index() == 0, "setting negative buffer index clamps to 0") bits(t, buf, string.rep("0", 202)) local buf = Bitbuf.new() for i = 0, 256 do buf:SetIndex(i) if buf:Index() ~= i then t:Errorf("[%d]: got index %d", i, buf:Index()) return end if buf:Len() ~= i then t:Errorf("[%d]: got length %d", i, buf:Len()) return end local want = string.rep("0", i) local got = explodeBuf(buf) if got ~= want then local r = {compError(want, got)} r[1] = string.format("[%d]: %s", i, r[1]) t:Errorf(unpack(r)) return end end end function T.TestBuffer_Fits(t, require) local Bitbuf = require() local suite = { lengths = unitSuite.lengths, sizes = unitSuite.sizes, } testSuite(t, Bitbuf, suite, function(buf, l, i, s, _) if buf:Fits(s) ~= (i+s <= l) then return "%d+%d > %d", i, s, l end end) end function T.TestBuffer_WritePad(t, require) local Bitbuf = require() local suite = { lengths = unitSuite.lengths, sizes = unitSuite.sizes, ones = true, } testSuite(t, Bitbuf, suite, function(buf, l, i, s, _) buf:WritePad(s) local expi = i + s local explen = math.max(expi, l) if buf:Len() ~= explen then return "expected length %d, got %d", explen, buf:Len() end if buf:Index() ~= expi then return "expected index %d, got %d", expi, buf:Index() end local want = string.rep("1", i) .. string.rep("0", s) .. string.rep("1", l-i-s) local got = explodeBuf(buf) return compare(want, got) end) end function T.TestBuffer_ReadPad(t, require) local Bitbuf = require() local suite = { lengths = unitSuite.lengths, sizes = unitSuite.sizes, ones = true, } testSuite(t, Bitbuf, suite, function(buf, l, i, s, _) buf:ReadPad(s) local expi = i + s local explen = math.max(expi, l) if buf:Len() ~= explen then return "expected length %d, got %d", explen, buf:Len() end if buf:Index() ~= expi then return "expected index %d, got %d", expi, buf:Index() end local want = string.rep("1", l) .. string.rep("0", explen-l) local got = explodeBuf(buf) return compare(want, got) end) end function T.TestBuffer_WriteAlign(t, require) local Bitbuf = require() local suite = { lengths = unitSuite.lengths, sizes = unitSuite.sizes, ones = true, } testSuite(t, Bitbuf, suite, function(buf, l, i, s, _) buf:WriteAlign(s) local expi = s == 0 and i or math.ceil(i/s)*s local explen = math.max(expi, l) if buf:Len() ~= explen then return "expected length %d, got %d", explen, buf:Len() end if buf:Index() ~= expi then return "expected index %d, got %d", expi, buf:Index() end local want = string.rep("1", i) .. string.rep("0", expi-i) .. string.rep("1", l-i-(expi-i)) local got = explodeBuf(buf) return compare(want, got) end) end function T.TestBuffer_ReadAlign(t, require) local Bitbuf = require() local suite = { lengths = unitSuite.lengths, sizes = unitSuite.sizes, ones = true, } testSuite(t, Bitbuf, suite, function(buf, l, i, s, _) buf:ReadAlign(s) local expi = s == 0 and i or math.ceil(i/s)*s local explen = math.max(expi, l) if buf:Len() ~= explen then return "expected length %d, got %d", explen, buf:Len() end if buf:Index() ~= expi then return "expected index %d, got %d", expi, buf:Index() end local want = string.rep("1", l) .. string.rep("0", explen-l) local got = explodeBuf(buf) return compare(want, got) end) end function T.TestBuffer_Reset(t, require) local Bitbuf = require() local buf = Bitbuf.fromString(pi64Bits) buf:Reset() pass(t, buf:Len() == 0, "reset buffer length is 0") pass(t, buf:Index() == 0, "reset buffer index is 0") pass(t, buf:String() == "", "reset buffer content is empty") end function T.TestBuffer_WriteBytes(t, require) local Bitbuf = require() local suite = { lengths = unitSuite.lengths, sizes = unitSuite.sizes, } testSuite(t, Bitbuf, suite, function(buf, l, i, s, _) local b = ones(s) buf:WriteBytes(b) local expi = i + #b*8 local explen = math.max(expi, l) if buf:Len() ~= explen then return "expected length %d, got %d", explen, buf:Len() end if buf:Index() ~= expi then return "expected index %d, got %d", expi, buf:Index() end local want = string.rep("0", i) .. string.rep("1", s) .. string.rep("0", explen-i-s) local got = explodeBuf(buf) return compare(want, got) end) end function T.TestBuffer_ReadBytes(t, require) local Bitbuf = require() local suite = { lengths = unitSuite.lengths, sizes = unitSuite.sizes, } testSuite(t, Bitbuf, suite, function(buf, l, i, s, _) local a = ones(s) buf:WriteBytes(a) buf:SetIndex(i) local exps = math.ceil(s/8) local b = buf:ReadBytes(exps) local expi = i + #a*8 local explen = math.max(expi, l) if buf:Len() ~= explen then return "expected length %d, got %d", explen, buf:Len() end if buf:Index() ~= expi then return "expected index %d, got %d", expi, buf:Index() end local want = string.rep("1", s) .. string.rep("0", exps*8-s) local got = explode(b) return compare(want, got) end) end function T.TestBuffer_WriteUint(t, require) local Bitbuf = require() fail(t, function() return Bitbuf.new():WriteUint(54, 0) end, "size 54 not in range [0,53]") fail(t, function() return Bitbuf.new():WriteUint(-1, 0) end, "size -1 not in range [0,53]") testSuite(t, Bitbuf, intSuite, function(buf, l, i, s, v) buf:WriteUint(s, v.value) local expi = i + s local explen = math.max(expi, l) if buf:Len() ~= explen then return "expected length %d, got %d", explen, buf:Len() end if buf:Index() ~= expi then return "expected index %d, got %d", expi, buf:Index() end local want = string.rep("0", i) .. string.sub(v.bits, 1, s) .. string.rep("0", explen-i-s) local got = explodeBuf(buf) return compare(want, got) end) end function T.TestBuffer_ReadUint(t, require) local Bitbuf = require() testSuite(t, Bitbuf, intSuite, function(buf, l, i, s, v) buf:WriteUint(s, v.value) buf:SetIndex(i) local value = buf:ReadUint(s) local expi = i + s local explen = math.max(expi, l) if buf:Len() ~= explen then return "expected length %d, got %d", explen, buf:Len() end if buf:Index() ~= expi then return "expected index %d, got %d", expi, buf:Index() end local want = v.value % 2^s if value ~= want then return "expected value %d, got %d", want, value end end) end function T.TestBuffer_WriteBool(t, require) local Bitbuf = require() local suite = { lengths = unitSuite.lengths, sizes = unitSuite.sizes, values = { {value = 0}, {value = 1}, }, } testSuite(t, Bitbuf, suite, function(buf, l, i, s, v) for i = 1, s do buf:WriteBool(v == 1) end local expi = i + s local explen = math.max(expi, l) if buf:Len() ~= explen then return "expected length %d, got %d", explen, buf:Len() end if buf:Index() ~= expi then return "expected index %d, got %d", expi, buf:Index() end local want = string.rep("0", i) .. string.rep(v == 1 and "1" or "0", s) .. string.rep("0", explen-i-s) local got = explodeBuf(buf) return compare(want, got) end) end function T.TestBuffer_ReadBool(t, require) local Bitbuf = require() t:Log("false") local suite = { lengths = unitSuite.lengths, sizes = unitSuite.sizes, } testSuite(t, Bitbuf, suite, function(buf, l, i, s, _) for j = 1, s do if buf:ReadBool() ~= false then return "expected false" end local expi = i + j local explen = math.max(expi, l) if buf:Len() ~= explen then return "expected length %d, got %d", explen, buf:Len() end if buf:Index() ~= expi then return "expected index %d, got %d", expi, buf:Index() end end end) t:Log("true") suite.ones = true testSuite(t, Bitbuf, suite, function(buf, l, i, s, _) for j = 1, s do local v = i+j <= l if buf:ReadBool() ~= v then return "expected " .. (v and "true" or "false") end local expi = i + j local explen = math.max(expi, l) if buf:Len() ~= explen then return "expected length %d, got %d", explen, buf:Len() end if buf:Index() ~= expi then return "expected index %d, got %d", expi, buf:Index() end end end) end function T.TestBuffer_WriteByte(t, require) local Bitbuf = require() local suite = { lengths = unitSuite.lengths, values = 255, } testSuite(t, Bitbuf, suite, function(buf, l, i, _, v) buf:WriteByte(v.value) local expi = i + 8 local explen = math.max(expi, l) if buf:Len() ~= explen then return "expected length %d, got %d", explen, buf:Len() end if buf:Index() ~= expi then return "expected index %d, got %d", expi, buf:Index() end local want = string.rep("0", i) .. v.bits .. string.rep("0", explen-i-8) local got = explodeBuf(buf) return compare(want, got) end) end function T.TestBuffer_ReadByte(t, require) local Bitbuf = require() local suite = { lengths = unitSuite.lengths, values = 255, } testSuite(t, Bitbuf, suite, function(buf, l, i, _, v) buf:WriteByte(v.value) buf:SetIndex(i) local value = buf:ReadByte(s) local expi = i + 8 local explen = math.max(expi, l) if buf:Len() ~= explen then return "expected length %d, got %d", explen, buf:Len() end if buf:Index() ~= expi then return "expected index %d, got %d", expi, buf:Index() end local want = v.value if value ~= want then return "expected value %d, got %d", want, value end end) end function T.TestBuffer_WriteInt(t, require) local Bitbuf = require() fail(t, function() return Bitbuf.new():WriteUint(54, 0) end, "size 54 not in range [0,53]") fail(t, function() return Bitbuf.new():WriteUint(-1, 0) end, "size -1 not in range [0,53]") testSuite(t, Bitbuf, intSuite, function(buf, l, i, s, v) buf:WriteInt(s, v.value) local expi = i + s local explen = math.max(expi, l) if buf:Len() ~= explen then return "expected length %d, got %d", explen, buf:Len() end if buf:Index() ~= expi then return "expected index %d, got %d", expi, buf:Index() end local want = string.rep("0", i) .. string.sub(v.bits, 1, s) .. string.rep("0", explen-i-s) local got = explodeBuf(buf) return compare(want, got) end) end local function uint2int(size, v) local n = 2^size v = v % n if v >= n/2 then return v - n end return v end function T.TestBuffer_ReadInt(t, require) local Bitbuf = require() testSuite(t, Bitbuf, intSuite, function(buf, l, i, s, v) buf:WriteInt(s, v.value) buf:SetIndex(i) local value = buf:ReadInt(s) local expi = i + s local explen = math.max(expi, l) if buf:Len() ~= explen then return "expected length %d, got %d", explen, buf:Len() end if buf:Index() ~= expi then return "expected index %d, got %d", expi, buf:Index() end local want = uint2int(s, v.value) if value ~= want then return "expected value %d, got %d", want, value end end) end function T.TestBuffer_WriteFloat(t, require) local Bitbuf = require() local buf = Bitbuf.new() buf:WriteFloat(32, math.pi) pass(t, buf:Len() == 32, "buffer length is 32") pass(t, buf:Index() == 32, "buffer index is 32") pass(t, buf:String() == pi32Bits, "32-bit pi") local buf = Bitbuf.new() buf:WriteFloat(64, math.pi) pass(t, buf:Len() == 64, "buffer length is 64") pass(t, buf:Index() == 64, "buffer index is 64") pass(t, buf:String() == pi64Bits, "64-bit pi") fail(t, function() buf:WriteFloat(1, 0) end, "invalid size") end function T.TestBuffer_ReadFloat(t, require) local Bitbuf = require() local pi32 = string.unpack("<f", string.pack("<f", math.pi)) local buf = Bitbuf.fromString(pi32Bits) pass(t, buf:ReadFloat(32) == pi32, "32-bit pi") pass(t, buf:Index() == 32, "buffer index is 32") local buf = Bitbuf.fromString(pi64Bits) pass(t, buf:ReadFloat(64) == math.pi, "64-bit pi") pass(t, buf:Index() == 64, "buffer index is 32") fail(t, function() buf:ReadFloat(1, 0) end, "invalid size") end function T.TestBuffer_WriteUfixed(t, require) local Bitbuf = require() --TODO: WriteUfixed end function T.TestBuffer_ReadUfixed(t, require) local Bitbuf = require() --TODO: ReadUfixed end function T.TestBuffer_WriteFixed(t, require) local Bitbuf = require() --TODO: WriteFixed end function T.TestBuffer_ReadFixed(t, require) local Bitbuf = require() --TODO: ReadFixed end function T.TestIsBuffer(t, require) local Bitbuf = require() pass(t, Bitbuf.isBuffer(42) == false, "42 is not a Buffer") pass(t, Bitbuf.isBuffer(Bitbuf.new()) == true, "result of new is a Buffer") pass(t, Bitbuf.isBuffer(Bitbuf.fromString("")) == true, "result of fromString is a Buffer") end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Benchmarks local sample = { unsigned = 3634604713, signed = -1487121065, float32 = math.pi, float64 = math.pi, string = "", bool = {}, } do local n = 100000 local t = table.create(n) for i = 1, n do t[i] = string.char(math.random(0, 255)) end sample.string = table.concat(t) end do local t = table.create(1000) for i = 1, 1000 do t[i] = math.random(0, 1) == 1 end sample.bool = t end function T.BenchmarkNew(b, require) local Bitbuf = require() b:ResetTimer() for i = 1, b.N do local buf = Bitbuf.new() end end local function benchmarkWriteBool(n) return function(b, require) local Bitbuf = require() local buf = Bitbuf.new() b:ResetTimer() for i = 1, b.N do buf:SetIndex(0) for j = 1, n do buf:WriteBool(sample.bool[j]) end end end end T.BenchmarkWriteBool_N1 = benchmarkWriteBool(1) T.BenchmarkWriteBool_N10 = benchmarkWriteBool(10) T.BenchmarkWriteBool_N100 = benchmarkWriteBool(100) T.BenchmarkWriteBool_N1000 = benchmarkWriteBool(1000) local function benchmarkReadBool(n) return function(b, require) local Bitbuf = require() local buf = Bitbuf.new() for i = 1, n do buf:WriteBool(sample.bool[i]) end b:ResetTimer() for i = 1, b.N do buf:SetIndex(0) for j = 1, n do local v = buf:ReadBool() end end end end T.BenchmarkReadBool_N1 = benchmarkReadBool(1) T.BenchmarkReadBool_N10 = benchmarkReadBool(10) T.BenchmarkReadBool_N100 = benchmarkReadBool(100) T.BenchmarkReadBool_N1000 = benchmarkReadBool(1000) local function benchmarkWriteUint(n) return function(b, require) local Bitbuf = require() local buf = Bitbuf.new() b:ResetTimer() for i = 1, b.N do buf:SetIndex(0) for j = 1, n do buf:WriteUint(32, sample.unsigned) end end end end T.BenchmarkWriteUint_N1 = benchmarkWriteUint(1) T.BenchmarkWriteUint_N10 = benchmarkWriteUint(10) T.BenchmarkWriteUint_N100 = benchmarkWriteUint(100) T.BenchmarkWriteUint_N1000 = benchmarkWriteUint(1000) local function benchmarkWriteUint_Unaligned(n) return function(b, require) local Bitbuf = require() local buf = Bitbuf.new() b:ResetTimer() for i = 1, b.N do buf:SetIndex(0) buf:WriteBool(true) for j = 1, n do buf:WriteUint(32, sample.unsigned) end end end end T.BenchmarkWriteUint_Unaligned_N1 = benchmarkWriteUint_Unaligned(1) T.BenchmarkWriteUint_Unaligned_N10 = benchmarkWriteUint_Unaligned(10) T.BenchmarkWriteUint_Unaligned_N100 = benchmarkWriteUint_Unaligned(100) T.BenchmarkWriteUint_Unaligned_N1000 = benchmarkWriteUint_Unaligned(1000) local function benchmarkReadUint(n) return function(b, require) local Bitbuf = require() local buf = Bitbuf.new() for j = 1, n do buf:WriteUint(32, sample.unsigned) end b:ResetTimer() for i = 1, b.N do buf:SetIndex(0) for j = 1, n do local v = buf:ReadUint(32) end end end end T.BenchmarkReadUint_N1 = benchmarkReadUint(1) T.BenchmarkReadUint_N10 = benchmarkReadUint(10) T.BenchmarkReadUint_N100 = benchmarkReadUint(100) T.BenchmarkReadUint_N1000 = benchmarkReadUint(1000) local function benchmarkReadUint_Unaligned(n) return function(b, require) local Bitbuf = require() local buf = Bitbuf.new() buf:WriteBool(true) for j = 1, n do buf:WriteUint(32, sample.unsigned) end b:ResetTimer() for i = 1, b.N do buf:SetIndex(0) local v = buf:ReadBool() for j = 1, n do local v = buf:ReadUint(32) end end end end T.BenchmarkReadUint_Unaligned_N1 = benchmarkReadUint_Unaligned(1) T.BenchmarkReadUint_Unaligned_N10 = benchmarkReadUint_Unaligned(10) T.BenchmarkReadUint_Unaligned_N100 = benchmarkReadUint_Unaligned(100) T.BenchmarkReadUint_Unaligned_N1000 = benchmarkReadUint_Unaligned(1000) function T.BenchmarkWriteInt(b, require) local Bitbuf = require() local buf = Bitbuf.new() b:ResetTimer() for i = 1, b.N do buf:SetIndex(0) buf:WriteInt(32, sample.signed) end end function T.BenchmarkReadInt(b, require) local Bitbuf = require() local buf = Bitbuf.new() buf:WriteInt(32, sample.signed) b:ResetTimer() for i = 1, b.N do buf:SetIndex(0) local v = buf:ReadInt(32) end end function T.BenchmarkWriteFloat32(b, require) local Bitbuf = require() local buf = Bitbuf.new() b:ResetTimer() for i = 1, b.N do buf:SetIndex(0) buf:WriteFloat(32, sample.float32) end end function T.BenchmarkReadFloat32(b, require) local Bitbuf = require() local buf = Bitbuf.new() buf:WriteFloat(32, sample.float32) b:ResetTimer() for i = 1, b.N do buf:SetIndex(0) local v = buf:ReadFloat(32) end end function T.BenchmarkWriteFloat64(b, require) local Bitbuf = require() local buf = Bitbuf.new() b:ResetTimer() for i = 1, b.N do buf:SetIndex(0) buf:WriteFloat(64, sample.float64) end end function T.BenchmarkReadFloat64(b, require) local Bitbuf = require() local buf = Bitbuf.new() buf:WriteFloat(64, sample.float64) b:ResetTimer() for i = 1, b.N do buf:SetIndex(0) buf:ReadFloat(64) end end local function benchmarkWriteString(n) return function(b, require) local Bitbuf = require() local buf = Bitbuf.new() local s = string.sub(sample.string, 1, n) b:ResetTimer() for i = 1, b.N do buf:SetIndex(0) buf:WriteUint(32, #s) buf:WriteBytes(s) end end end T.BenchmarkWriteString_L1 = benchmarkWriteString(1) T.BenchmarkWriteString_L10 = benchmarkWriteString(10) T.BenchmarkWriteString_L100 = benchmarkWriteString(100) T.BenchmarkWriteString_L1000 = benchmarkWriteString(1000) T.BenchmarkWriteString_L10000 = benchmarkWriteString(10000) T.BenchmarkWriteString_L100000 = benchmarkWriteString(100000) local function benchmarkReadString(n) return function(b, require) local Bitbuf = require() local buf = Bitbuf.new() local s = string.sub(sample.string, 1, n) buf:WriteUint(32, #s) buf:WriteBytes(s) b:ResetTimer() for i = 1, b.N do buf:SetIndex(0) local n = buf:ReadUint(32) local v = buf:ReadBytes(n) end end end T.BenchmarkReadString_L1 = benchmarkReadString(1) T.BenchmarkReadString_L10 = benchmarkReadString(10) T.BenchmarkReadString_L100 = benchmarkReadString(100) T.BenchmarkReadString_L1000 = benchmarkReadString(1000) T.BenchmarkReadString_L10000 = benchmarkReadString(10000) T.BenchmarkReadString_L100000 = benchmarkReadString(100000) local function benchmarkWriteString_Unaligned(n) return function(b, require) local Bitbuf = require() local buf = Bitbuf.new() local s = string.sub(sample.string, 1, n) b:ResetTimer() for i = 1, b.N do buf:SetIndex(0) buf:WriteBool(true) buf:WriteUint(32, #s) buf:WriteBytes(s) end end end T.BenchmarkWriteString_Unaligned_L1 = benchmarkWriteString_Unaligned(1) T.BenchmarkWriteString_Unaligned_L10 = benchmarkWriteString_Unaligned(10) T.BenchmarkWriteString_Unaligned_L100 = benchmarkWriteString_Unaligned(100) T.BenchmarkWriteString_Unaligned_L1000 = benchmarkWriteString_Unaligned(1000) T.BenchmarkWriteString_Unaligned_L10000 = benchmarkWriteString_Unaligned(10000) T.BenchmarkWriteString_Unaligned_L100000 = benchmarkWriteString_Unaligned(100000) local function benchmarkReadString_Unaligned(n) return function(b, require) local Bitbuf = require() local buf = Bitbuf.new() local s = string.sub(sample.string, 1, n) buf:WriteBool(true) buf:WriteUint(32, #s) buf:WriteBytes(s) b:ResetTimer() for i = 1, b.N do buf:SetIndex(0) buf:ReadBool() local n = buf:ReadUint(32) local v = buf:ReadBytes(n) end end end T.BenchmarkReadString_Unaligned_L1 = benchmarkReadString_Unaligned(1) T.BenchmarkReadString_Unaligned_L10 = benchmarkReadString_Unaligned(10) T.BenchmarkReadString_Unaligned_L100 = benchmarkReadString_Unaligned(100) T.BenchmarkReadString_Unaligned_L1000 = benchmarkReadString_Unaligned(1000) T.BenchmarkReadString_Unaligned_L10000 = benchmarkReadString_Unaligned(10000) T.BenchmarkReadString_Unaligned_L100000 = benchmarkReadString_Unaligned(100000) local function benchmarkString(n) local s = string.sub(sample.string, 1, n) return function(b, require) local Bitbuf = require() local buf = Bitbuf.new() buf:WriteBytes(s) b:ResetTimer() for i = 1, b.N do local v = buf:String() end end end T.BenchmarkString_L1 = benchmarkString(1) T.BenchmarkString_L10 = benchmarkString(10) T.BenchmarkString_L100 = benchmarkString(100) T.BenchmarkString_L1000 = benchmarkString(1000) T.BenchmarkString_L10000 = benchmarkString(10000) T.BenchmarkString_L100000 = benchmarkString(100000) local function benchmarkFromString(n) local s = string.sub(sample.string, 1, n) return function(b, require) local Bitbuf = require() b:ResetTimer() for i = 1, b.N do local buf = Bitbuf.fromString(s) end end end T.BenchmarkFromString_L1 = benchmarkFromString(1) T.BenchmarkFromString_L10 = benchmarkFromString(10) T.BenchmarkFromString_L100 = benchmarkFromString(100) T.BenchmarkFromString_L1000 = benchmarkFromString(1000) T.BenchmarkFromString_L10000 = benchmarkFromString(10000) T.BenchmarkFromString_L100000 = benchmarkFromString(100000) return T
-- @module ae.ui.SlideLeftGesture -- @group UI -- @brief Slide left gesture. local SlideLeftGesture = ae.oo.class() -- @func -- @brief Creates a slide left gesture with no listener. -- @return The gesture. -- @func -- @brief Creates a slide left gesture. -- @param listener The function called when the gesture is detected. -- @return The gesture. function SlideLeftGesture.new(listener) local self = ae.oo.new(SlideLeftGesture) SlideLeftGesture.construct(self,listener) return self end -- @func -- @brief Creates a slide left gesture with no listener. -- @func -- @brief Creates a slide left gesture. -- @param listener The function called when the gesture is detected. function SlideLeftGesture.construct(self,listener) self.listener = listener self.triggerDistance = 0.1 self.touchDownX = {} end -- @brief Sets the listener. -- @param listener The listener. function SlideLeftGesture:setListener(listener) self.listener = listener end -- @brief Invoked on touch down event. -- @param pointerId The pointer identifier. -- @param x The X-coordinate at which the event occured. -- @param y The Y-coordinate at which the event occured. function SlideLeftGesture:touchDown(pointerId,x,y) self.touchDownX[pointerId] = x end -- @brief Invoked on touch move event. -- @param pointerId The pointer identifier. -- @param x The X-coordinate at which the event occured. -- @param y The Y-coordinate at which the event occured. function SlideLeftGesture:touchMove(pointerId,x,y) end -- @brief Invoked on touch up event. -- @param pointerId The pointer identifier. -- @param x The X-coordinate at which the event occured. -- @param y The Y-coordinate at which the event occured. function SlideLeftGesture:touchUp(pointerId,x,y) if self.touchDownX[pointerId] then local distance = self.touchDownX[pointerId] - x if distance >= self.triggerDistance and self.listener then self.listener(pointerId) return true end end self.touchDownX[pointerId] = nil return false end -- @brief Gets a string which represents the gesture. -- @return The string representing the gesture. function SlideLeftGesture:__tostring() return ae.oo.tostring('ae.ui.SlideLeftGesture', 'triggerDistance=' .. tostring(self.triggerDistance) .. ', listener=' .. tostring(self.listener),super.__tostring(self)) end return SlideLeftGesture
--DiskOS API Loader local Globals = (...) or {} local apiloader = fs.load("System/api.lua") setfenv(apiloader,Globals) apiloader() return Globals
workspace "Charcoal Engine" architecture "x64" configurations{ "Debug", "Release" } startproject "Sandbox" flags { "MultiProcessorCompile" } outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}" IncludeDir = {} IncludeDir["GLFW"] = "Charcoal/vendor/GLFW/include" IncludeDir["Glad"] = "Charcoal/vendor/Glad/include" IncludeDir["ImGui"] = "Charcoal/vendor/ImGui" IncludeDir["GLM"] = "Charcoal/vendor/GLM" IncludeDir["stb_image"] = "Charcoal/vendor/stb_image" group "Dependencies" include "Charcoal/vendor/GLFW" include "Charcoal/vendor/Glad" include "Charcoal/vendor/ImGui" group "" group "Tools" include "tools/CMFCompiler" include "tools/CharcoalEditor" group "" newoption { trigger = "toolset", value = "Compiler", description = "Choose toolset for compiling on windows", allowed = { { "clang", "Clang" }, { "msvc", "Visual Studio" } } } project "Charcoal" location "Charcoal" kind "StaticLib" language "C++" cppdialect "C++17" staticruntime "on" targetdir ("bin/" .. outputdir .. "/%{prj.name}") objdir ("bin-int/" .. outputdir .. "/%{prj.name}") files { "%{prj.name}/src/Charcoal/**.h", "%{prj.name}/src/Charcoal/**.cpp", "%{prj.name}/src/Charcoal.h", "%{prj.name}/src/chpch.h", "%{prj.name}/src/chpch.cpp", "%{prj.name}/src/Platform/OpenGL/**.h", "%{prj.name}/src/Platform/OpenGL/**.cpp", "%{prj.name}/vendor/stb_image/stb_image.h", "%{prj.name}/vendor/stb_image/stb_image.cpp" } includedirs { "%{prj.name}/src", "%{prj.name}/vendor/spdlog/include", "%{IncludeDir.GLFW}", "%{IncludeDir.Glad}", "%{IncludeDir.ImGui}", "%{IncludeDir.GLM}", "%{IncludeDir.stb_image}", "%{IncludeDir.tinyobjloader}", "%{IncludeDir.tinygltf}" } links { "GLFW", "Glad", "ImGui" } defines { "GLFW_INCLUDE_NONE", "_CRT_SECURE_NO_WARNINGS" } pchheader "chpch.h" pchsource "%{prj.name}/src/chpch.cpp" filter "options:toolset=clang" toolset "clang" buildoptions { "-Wno-deprecated-declarations" } filter "system:windows" systemversion "latest" defines { "CH_PLATFORM_WINDOWS" } files { "%{prj.name}/src/Platform/Windows/**.h", "%{prj.name}/src/Platform/Windows/**.cpp", } filter "system:linux" toolset "gcc" defines { "CH_PLATFORM_LINUX" } files { "%{prj.name}/src/Platform/Linux/**.h", "%{prj.name}/src/Platform/Linux/**.cpp", } filter "configurations:Debug" runtime "Debug" symbols "On" defines { "CH_ENABLE_ASSERTS", "CH_DEBUG" } filter "configurations:Release" defines "CH_RELEASE" runtime "Release" optimize "On" project "Sandbox" location "Sandbox" kind "ConsoleApp" language "C++" cppdialect "C++17" staticruntime "on" targetdir ("bin/" .. outputdir .. "/%{prj.name}") objdir ("bin-int/" .. outputdir .. "/%{prj.name}") files { "%{prj.name}/src/**.h", "%{prj.name}/src/**.cpp" } includedirs { "Charcoal/src", "Charcoal/vendor/spdlog/include", "%{IncludeDir.GLM}", "%{IncludeDir.ImGui}" } links { "Charcoal", "GLFW", "Glad", "ImGui" } filter "options:toolset=clang" toolset "gcc" -- links -- { -- "shell32.lib", -- "gdi32.lib" -- } -- linkoptions -- { -- "-v" -- } filter "system:windows" systemversion "latest" defines { "CH_PLATFORM_WINDOWS" } filter "system:linux" toolset "gcc" links { "X11", "dl", "pthread", } defines { "CH_PLATFORM_LINUX" } filter "configurations:Debug" defines "CH_DEBUG" runtime "Debug" symbols "On" filter "configurations:Release" defines "CH_RELEASE" runtime "Release" optimize "On"
----------------------------------- -- Area: Mamool Ja Training Grounds (Preemptive Strike) -- Mob: Puk Executioner ----------------------------------- function onMobDeath(mob, player, isKiller) end
-- An empty stage with no walls. Load it up and do whatever you want. function configure(stageBuilder) stageBuilder:setSize(1200, 800) stageBuilder:setBattleMode(true) end
test_game_module = {} local other_module = nil; function test_game_module:reload() --other_module = script_module:find_module("other_module"); end function test_game_module:awake() test_game_module.reload(); end function test_game_module:init() print("test_game_module init!----"); script_module:add_class_cb("Player", test_game_module, test_game_module.class_common_event); end function test_game_module:after_init() print("test_game_module after_init!----"); local playerObject = script_module:create_object(NFGUID(), 1, 0, "Player", "", NFDataList()); --property callback script_module:add_prop_cb(playerObject, "MAXHP", self, self.max_prop_cb); script_module:set_prop_int(playerObject,"MAXHP",100); --record callback script_module:add_record_cb(playerObject, "TaskList", self, self.task_list_cb); local varTask = NFDataList(); varTask:add_string("Task_From_Lua"); varTask:add_int(1); varTask:add_int(1); script_module:add_row(playerObject, "TaskList", varTask); --script_module:set_record_int(playerObject, "TaskList", 0, 1, 3); --script_module:set_record_string(playerObject, "TaskList", 0, 0, "NewStr_Task_From_Lua"); --event callback script_module:add_event_cb(playerObject, 1, self, self.event_cb); local dataList = NFDataList(); dataList:add_int(21); dataList:add_float(22.5); dataList:add_string("str23"); local ident = NFGUID(); ident.head = 241; ident.data = 242; dataList:add_object(ident); script_module:do_event(playerObject, 1, dataList); --Hearback script_module:add_schedule(playerObject, "add_game_schedule", self, self.schedule, 5, 55555); script_module:add_module_schedule("add_game_module_schedule", self, self.module_schedule, 10, 55555); end function test_game_module:ready_execute() print("test_game_module ready_execute!"); end function test_game_module:before_shut() print("test_game_module before_shut!"); end function test_game_module:shut() print("test_game_module shut!"); end function test_game_module:max_prop_cb(id, propertyName, oldVar, newVar) local oldValue = oldVar:int(); local newValue = newVar:int(); print("Hello Lua max_prop_cb oldVar:" .. tostring(oldValue) .. " newVar:" .. tostring(newValue)); end function test_game_module:task_list_cb(id, recordName, nOpType, row, col, oldVar, newVar) print("Hello Lua task_list_cb ") if nOpType == RecordOptype.Add then print(" nOpType:".. tostring(nOpType) .. ""); end if nOpType == RecordOptype.Update then if col == 0 then local nOldVar = oldVar:string(); local nNewVar = newVar:string(); print(" nOpType:".. tostring(nOpType).. " oldVar:".. tostring(nOldVar) .." newVar:" .. tostring(nNewVar) .. ""); end if col == 1 then local nOldVar = oldVar:int(); local nNewVar = newVar:int(); print(" nOpType:".. tostring(nOpType).. " oldVar:".. tostring(nOldVar) .." newVar:" .. tostring(nNewVar) .. ""); end end end function test_game_module:event_cb(id, eventID, arg) local nValue = arg:int(0); local fValue = arg:float(1); local strValue = arg:string(2); local ident = arg:object(3); local head = ident.head; local data = ident.data; print("Hello Lua EventCallBack eventID:".. eventID .. ""); print("\r\targ:nValue:".. tostring(nValue) .. " fValue:"..tostring(fValue).. " strValue:"..tostring(strValue).." ident:".. ident:tostring() .. ""); end function test_game_module:schedule(id, heartBeat, time, count) local obj = NFDataList(); --local s = os.clock() local s = script_module:time(); if oldTime == nil then oldTime = s end print("Hello Lua HeartCallBac666666:".. heartBeat .. " Time:" .. (s-oldTime) .. ""); oldTime = s; end function test_game_module:module_schedule(heartBeat, time, count) print("Hello Lua Module HeartCallBack666:".. heartBeat .. " Time:" .. time .. ""); end function test_game_module:class_common_event(id, className, eventID, varData) print("class_common_event, ClassName: " .. tostring(className) .. " EventID: " .. tostring(eventID) .. ""); end
local widget = require("widget") local json = require("json") local mime = require("mime") ------------------------------------------------------------------------------ -- Declarations ------------------------------------------------------------------------------ local competition = {} local boxSize local blur, group, scrollView, textObject, background local renderList, renderText, closeSelectingPanel, getCompetitionList, createGroup, hideGroup, showGroup, createBlur, participate, getAdditionalInfo local image, imageDir, isFromGallery local infoForm local panelIsRendered = false local hold = false ------------------------------------------------------------------------------ -- RENDER FUNCTIONS ------------------------------------------------------------------------------ function competition:showSelectingPanel(imageParam, imageDirParam, isFromGalleryParam) panelIsRendered = true image = imageParam imageDir = imageDirParam isFromGallery = isFromGalleryParam createBlur() createGroup() renderText(texts.showSavedPicture.pleaseWait, function() showGroup(getCompetitionList) end) end ------------------------------------------------------------------------------ -- FUNCTION ------------------------------------------------------------------------------ closeSelectingPanel = function() if not panelIsRendered then return end local function removeGroup() display.remove(group) group = nil display.remove(blur) blur = nil display.remove(scrollView) scrollView = nil display.remove(infoForm) infoForm = nil end transition.to(blur, {alpha = 0}) transition.to(group, {y = centerY + screenHeight, alpha = 0, onComplete = removeGroup}) transition.to(scrollView, {y = centerY + screenHeight, alpha = 0, onComplete = removeGroup}) panelIsRendered = false return true end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ getCompetitionList = function() if not panelIsRendered then return end local function networkListener(event) print(event.status) if event.status == 200 then local list = json.decode(event.response) if #list > 0 then renderList(list) else renderText(texts.showSavedPicture.noCompetition) end else renderText(texts.showSavedPicture.problemInFetchingList) end end local parent = appConfig:getParent() local headers = {} headers["Content-Type"] = "application/json" headers["user_code"] = parent.user_code local params = {} params.headers = headers network.request( urls.getCompetitionList, "GET", networkListener, params ) end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ renderList = function(list) if not panelIsRendered then return end if scrollView then display.remove(scrollView) scrollView = nil end if textObject then display.remove(textObject) textObject = nil end local function titleTouchListener(event) audio.stop(clickSoundCannel) audio.play(clickSound, clickPlayOptions) transition.to(scrollView, {y = centerY + screenHeight }) getAdditionalInfo(event.target.id) end local options, competitionTitle local titleFontSize = 55 local fontSize = 50 local marginTop = 85 local marginRight = 20 local x = 0 local initialY = 170 scrollView = widget.newScrollView( { width = background.width * .96, height = background.height * .9, scrollWidth = background.width * 10, horizontalScrollDisabled = true, verticalScrollingDisabled = false, hideBackground = true, }) scrollView.x = centerX scrollView.y = centerY + screenHeight local options = { text = texts.showSavedPicture.competitionList, anchorX = .5, x = scrollView.width / 2, y = 50, font = fonts.lalezar, fontSize = titleFontSize, } local listTitle = display.newText( options ) scrollView:insert(listTitle) listTitle:setFillColor(235/255, 96/255, 9/255, 1) for i = 1, #list do options = { text = list[i].title, anchorX = 1, x = scrollView.width - 40, y = initialY + (i - 1) * marginTop, font = fonts.lalezar, fontSize = fontSize, } competitionTitle = display.newText( options ) competitionTitle:setFillColor( 80 / 255, 80 / 255, 80 / 255, 1) competitionTitle.anchorX, competitionTitle.anchorY = 1, .5 competitionTitle.id = list[i].id scrollView:insert(competitionTitle) -- competitionTitle:addEventListener("touch", titleTouchListener) competitionTitle:addEventListener("tap", titleTouchListener) end transition.to(scrollView, {y = centerY }) end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ getAdditionalInfo = function(competitionID) if not panelIsRendered then return end local titleFontSize = 55 infoForm = display.newGroup() group:insert(infoForm) infoForm.x, infoForm.y = -centerX, centerY local options = { parent = infoForm, text = texts.showSavedPicture.additionalInfo, parent = infoForm, x = centerX, y = centerY - 215, font = fonts.lalezar, fontSize = titleFontSize, } local title = display.newText( options ) title:setFillColor(255/255, 128/255, 55/255, 1) local textColor = { 80 / 255, 80 / 255, 80 / 255 , 1} local city = native.newTextField( centerX + 0, centerY - 110, 400, 70) city.align = "right" city.size = 28 city.placeholder = texts.showSavedPicture.cityPlaceholder infoForm:insert(city) options = { parent = infoForm, text = texts.showSavedPicture.cityTag, x = centerX + 330, y = city.y, font = fonts.lalezar, fontSize = 35 } local cityTag = display.newText(options) cityTag:setFillColor( 80 / 255, 80 / 255, 80 / 255) local tag = native.newTextField( centerX + 0, centerY - 35, 400, 70) tag.align = "right" tag.size = 28 tag.placeholder = texts.showSavedPicture.tagPlaceholder infoForm:insert(tag) options = { parent = infoForm, text = texts.showSavedPicture.tagTag, x = centerX + 300, y = tag.y, font = fonts.lalezar, fontSize = 35 } local tagTag = display.newText(options) tagTag:setFillColor( 80 / 255, 80 / 255, 80 / 255) local description = native.newTextBox( centerX + 0, centerY + 75, 400, 140) infoForm:insert(description) description.align = "right" description.isEditable = true description.isFontSizeScaled = true description.size = 28 description.align = "right" description.placeholder = texts.showSavedPicture.descriptionPlaceholder options = { parent = infoForm, text = texts.showSavedPicture.descriptionTag, x = centerX + 300, y = description.y, font = fonts.lalezar, fontSize = 35 } local descriptionTag = display.newText(options) descriptionTag:setFillColor( 80 / 255, 80 / 255, 80 / 255) local confirmBackground = display.newRoundedRect( infoForm, centerX, centerY + screenHeight / 4, 220, 90, 10) confirmBackground:setFillColor(0 / 255, 169 / 255, 126 / 255) confirmBackground.name = "confirm" confirmBackground.fill.effect = "filter.grayscale" local options = { parent = infoForm, text = texts.newUser.confirm, x = confirmBackground.x, y = confirmBackground.y, font = fonts.lalezar, fontSize = 35 } local confirm = display.newText(options) local function textListener( event ) local target = event.target if ( event.phase == "began" ) then elseif ( event.phase == "ended" or event.phase == "submitted" ) then elseif ( event.phase == "editing" ) then if city.text ~= "" and tag.text ~= "" and description.text ~= "" then isValid = true confirmBackground.fill.effect = nil else isValid = false confirmBackground.fill.effect = "filter.grayscale" end end end local function buttonTouchHandlers(event) if not isValid and event.target.name == "confirm" then return end if event.phase == "began" then audio.stop(clickSoundCannel) audio.play(clickSound, clickPlayOptions) event.target.width = event.target.width * clickResizeFactor event.target.height = event.target.height * clickResizeFactor display.getCurrentStage():setFocus( event.target ) event.target.isFocus = true end if not event.target.isFocus then return false end if event.phase == "ended" then event.target.width = event.target.width / clickResizeFactor event.target.height = event.target.height / clickResizeFactor if event.target.name == "confirm" then participate(competitionID, city.text, tag.text, description.text) transition.to(infoForm, { y = centerY, alpha = 0}) end event.target.isFocus = false display.getCurrentStage():setFocus(nil) end end city:addEventListener( "userInput", textListener ) tag:addEventListener( "userInput", textListener ) description:addEventListener( "userInput", textListener ) confirmBackground:addEventListener("touch", buttonTouchHandlers) transition.to(infoForm, { y = -centerY + 30}) end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ participate = function(competitionID, city, tag, description) if not panelIsRendered then return end local b64text local path = system.pathForFile( image, imageDir ) local fileHandle = io.open( path, "rb" ) if fileHandle then if isFromGallery then b64text = "data:image/jpg;base64,"..mime.b64( fileHandle:read( "*a" )) else b64text = "data:image/png;base64,"..mime.b64( fileHandle:read( "*a" )) end io.close( fileHandle ) local user = appConfig:getUserInfo(appConfig:getUserName()) local parent = appConfig:getParent() local params = {} params.headers = {} params.headers["Content-Type"] = "application/json" params.headers["user_code"] = parent.user_code params.headers["racing_id"] = competitionID params.timeout = 10 print(parent.user_code) print(competitionID) local tempFilePath = system.pathForFile( "temp.json", system.TemporaryDirectory ) local tempFile = io.open(tempFilePath, "w") tempFile:write(json.encode( { first_name = user.name, last_name = user.lastName, birth_year = tonumber(user.birthYear), birth_month = tonumber(user.birthMonth), birth_day = tonumber(user.birthDay), gender = user.gender, city = city, tag = tag, desciption = description, url = b64text })) io.close(tempFile) local function networkListener(event) print("^^^^^^^^^^^^^^^event.status") print(event.status) renderText(event.status) print("^^^^^^^^^^^^^^^event.status") print(event.status == -1) if (event.status == -1) then print('yutuyt') hold = false renderText(texts.showSavedPicture.internetError) elseif (event.isError) then print ("jygjgjhghuytuytuytuyt") hold = false renderText(texts.showSavedPicture.problemInParticipation) renderText(event.status) else if ( event.phase == "began" ) then elseif ( event.phase == "progress" ) then elseif ( event.phase == "ended" ) then hold = false if event.status == 201 then renderText(texts.showSavedPicture.successfulParticipation) else print(event.status) if (event.status == -1) then print('9999999') hold = false renderText(texts.showSavedPicture.internetError) else renderText(texts.showSavedPicture.problemInParticipation) renderText(event.status) end end end end end hold = true renderText(texts.showSavedPicture.pleaseWait) network.upload( urls.participateInCompetition, "POST", networkListener, params, "temp.json", system.TemporaryDirectory, "application/json") else renderText(texts.showSavedPicture.problemInSendingImage) end end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ renderText = function(text, callBack) if not panelIsRendered then return end if scrollView then display.remove(scrollView) scrollView = nil end if textObject then display.remove(textObject) textObject = nil end local options = { text = text, parent = group, fontSize = 46, x = background.x, font = fonts.lalezar } textObject = display.newText( options ) textObject:setFillColor( 80 / 255, 80 / 255, 80 / 255) if callBack then callBack() end end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ createGroup = function() if not panelIsRendered then return end if screenWidth < screenHeight then boxSize = screenWidth * .4 else boxSize = screenHeight * .4 end -- create a display group to contain the picker group = display.newGroup() group.x, group.y = centerX - boxSize * .075, centerY + screenHeight group.alpha = 0 -- create a bounding box for the picker background = display.newRoundedRect(group, 0, 0, boxSize * 2.5, boxSize * 1.75, boxSize / 5) background:setFillColor(247 / 255, 247 / 255, 247 / 255) background.x, background.y = boxSize * .075, boxSize * .075 background:setStrokeColor(0 / 255, 169 / 255, 126 / 255, 1) background.strokeWidth = boxSize * .04 background:addEventListener("touch", function() return true end) background:addEventListener("tap", function() return true end) end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ hideGroup = function(callBack) if (not panelIsRendered) or (group.y == centerY + screenHeight) then return end transition.to(group, {y = centerY + screenHeight, alpha = 1, onComplete = callBack}) end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ showGroup = function(callBack) if (not panelIsRendered) or (group.y == centerY - boxSize * .075) then return end transition.to(group, {y = centerY - boxSize * .075, alpha = 1, onComplete = callBack}) end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ createBlur = function() if not panelIsRendered then return end blur = display.captureScreen() blur.x, blur.y = centerX, centerY blur:setFillColor(.4, .4, .4) blur.fill.effect = "filter.blur" blur.alpha = 0 transition.to(blur, {alpha = 1}) blur:addEventListener("tap", function() if hold then return true else closeSelectingPanel () end end) blur:addEventListener("touch", function() return true end) transition.to(blur, {alpha = 1}) end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ return competition
-- oUF_Simple: templates/party -- zork, 2016 ----------------------------- -- Variables ----------------------------- local A, L = ... ----------------------------- -- CreatePartyStyle ----------------------------- if not L.C.party or not L.C.party.enabled then return end local function CreatePartyStyle(self) --config self.cfg = L.C.party --settings self.settings = {} self.settings.template = "party" self.settings.setupFrame = false self.settings.setupHeader = true self.settings.createDrag = false --style L.F.CreateStyle(self) end L.F.CreatePartyStyle = CreatePartyStyle
local oop = require("diffview.oop") local M = {} ---@class LogEntry ---@field path_args string[] ---@field commit Commit ---@field files FileEntry[] ---@field status string ---@field stats GitStats ---@field single_file boolean ---@field folded boolean local LogEntry = oop.Object LogEntry = oop.create_class("LogEntry") function LogEntry:init(opt) self.path_args = opt.path_args self.commit = opt.commit self.files = opt.files self.folded = true self.single_file = opt.single_file self:update_status() self:update_stats() end function LogEntry:destroy() for _, file in ipairs(self.files) do file:destroy() end end function LogEntry:update_status() self.status = nil for _, file in ipairs(self.files) do if self.status and file.status ~= self.status then self.status = "M" return elseif self.status ~= file.status then self.status = file.status end end if not self.status then self.status = "X" end end function LogEntry:update_stats() self.stats = { additions = 0, deletions = 0 } for _, file in ipairs(self.files) do if file.stats then self.stats.additions = self.stats.additions + file.stats.additions self.stats.deletions = self.stats.deletions + file.stats.deletions end end end M.LogEntry = LogEntry return M
local z = ... local function tonum(s, p) if not s or (p and s:sub(1, 1) ~= p) then return 9 end return tonumber(s:sub(2, 2)) end local function uc(n) return "Unknown "..n.." command" end return function(o, p1, p2, pv, n, wf, rf) package.loaded[z] = nil z = nil local p = tonum(p1, 'P') local e = not p and "Port not specified" or (o == 0 and uc(n) or nil) if not e and o > 1 then local v = pv and tonum(p2, 'V') or p2 e = wf and (not v and n.." value to set not specified" or wf(p, v)) or uc(n) return true, p, v end if e then return false, p, e else return true, p, (pv and "V" or "")..rf(p) end end
--[[ * Natural Selection 2 - Combat++ Mod * Authors: * WhiteWizard * * Toggles the Combat HUD on and off during the count down sequence. * * Wrapped Functions: * 'Alien:OnCountDown' - Turns the Combat HUD off while the count down sequence is executing. * 'Alien:OnCountDownEnd' - Turns the Combat HUD back on after the count down sequence is complete. ]] local ns2_Alien_OnCountDown = Alien.OnCountDown function Alien:OnCountDown() ns2_Alien_OnCountDown(self) ClientUI.SetScriptVisibility("CPPGUIAlienCombatHUD", "Countdown", false) end local ns2_Alien_OnCountDownEnd = Alien.OnCountDownEnd function Alien:OnCountDownEnd() ns2_Alien_OnCountDownEnd(self) ClientUI.SetScriptVisibility("CPPGUIAlienCombatHUD", "Countdown", true) end
local pss_id = ARGV[1]; local cluster = ARGV[2]; local failure_set = "{BA}:BROKER_PSS_FAILURES:" .. pss_id local hgetall = function (key) local bulk = redis.call("HGETALL", key) local result = {} local nextkey for i, v in ipairs(bulk) do if i % 2 == 1 then nextkey = v else result[nextkey] = v end end return result end -- TODO: Maybe do this, to reduce memory usage of the Lua script -- http://danoyoung.blogspot.ca/2015/12/lua-scripting-with-redis.html, but with HSCAN local assignations = hgetall("{BA}:PSS_BRANCH_ASSIGNATIONS") for i_branch_id, i_pss_id in pairs(assignations) do if i_pss_id == pss_id then redis.call("HMSET", "{BA}:PSS_BRANCH_ASSIGNATIONS", i_branch_id, "SHUTTINGDOWN" .. pss_id) end end redis.call("SADD", "{BA}:PSS_INSTANCES_SHUTTINGDOWN", pss_id) redis.call("ZREM", "{BA}:PSS_INSTANCES", pss_id) redis.call("DEL", failure_set);
local Component = class() Xile.Component = Component local _mtcache ={} local metatable = function(component) local mt = _mtcache[component] if mt == nil then mt = getmetatable(component) _mtcache[component] = mt end return mt end local getname = function(component) if component == nil then return nil end if type(component) == "string" then return component end local name = component.name if name == nil then local mt = metatable(component) name = (mt and mt.name) end if name == nil then local bt,rt,ct = Xile.type(component) name = ct end name = name or component return name end local _cache = setmetatable({},{__mode="k"}) Component.getname = function(k) local n = _cache[k] if n == nil then n = getname(k) _cache[k] = n end return n end Component.metatable = metatable function Component:init() end
AddCSLuaFile( "cl_init.lua" ) AddCSLuaFile( "shared.lua" ) include('shared.lua') ENT.WireDebugName = "PID" function ENT:Initialize() /* Make Physics work */ self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) /* Set wire I/O */ self.Inputs = Wire_CreateInputs(self, { "In", "Set Point", "Enable" }) self.Outputs = Wire_CreateOutputs(self, { "Out" }) /* Initialize values */ self.set = 0 self.inval = 0 self.p = 0 self.i = 0 self.d = 0 self.dcut = 0 self.ilim = 0 self.iterm = 0 self.enabled = 1 self.limit = 100 local phys = self:GetPhysicsObject() if (phys:IsValid() == true) then phys:Wake() end end function ENT:Think() /* Make sure the gate updates even if we don't receive any input */ self:TriggerInput() end function ENT:SetupGains(p, i, d, dcut, ilim, limit) /* Called by creator to set options */ self.p = p self.i = i self.d = d self.dcut = dcut self.ilim = ilim self.limit = limit self.lasttime = CurTime() self.lasterror = 0 self.iterm = 0 end function ENT:TriggerInput(iname, value) /* Change variables to reflect input */ if (iname == "Set Point") then self.set = value return end if (iname == "In") then self.inval = value end if (iname == "Enable") then self.enabled = value return end /* If we're not enabled, set the output to zero and exit */ if (self.enabled == 0) then Wire_TriggerOutput(self, "Out", 0) return end /* Define some local variables */ local error = self.set - self.inval local dt = CurTime() - self.lasttime /* Calculate derivative term (de/dt) , check for divide by zero */ local dterm = 0 if (dt>0) then dterm = (error - self.lasterror)/dt end dterm = dterm * self.d /* If the derivative term is less than the cutoff, evaluate the integral term */ if (math.abs(dterm) < self.dcut) then self.iterm = self.iterm + self.i * error * dt end /* Bound the integral term to the user limit */ if (self.iterm > self.ilim && error > 0) then self.iterm = self.ilim end if (self.iterm < -self.ilim && error < 0) then self.iterm = -self.ilim end /* Setup for next time */ self.lasttime = CurTime() self.lasterror = error /* Output it */ self.out = (self.p * error) + self.iterm + dterm /* Limit the output to whatever */ if (math.abs(self.out) > self.limit) then if (self.out>=0) then self.out = self.limit else self.out = -self.limit end end Wire_TriggerOutput(self, "Out", self.out) end
--// Initialization local RunService = game:GetService("RunService") local HttpService = game:GetService("HttpService") local PlayerService = game:GetService("Players") local ReplicatedStorage = game:GetService("ReplicatedStorage") local LocalizationService = game:GetService("LocalizationService") local Overture = require(ReplicatedStorage:WaitForChild("Overture")) local GetDeviceType = Overture:GetRemoteFunction("GA-GetDeviceType") local GetViewportSize = Overture:GetRemoteFunction("GA-GetViewportSize") local API = {} API.__index = API API.DefaultData = {} API.StoredPlayerData = {} local RobloxVersion, LuaVersion = getfenv().version(), _VERSION local ValueReplacements = {[true] = "1", [false] = "0"} local UserAgentMasks = { ["Mobile"] = "(Linux; Android)", ["Tablet"] = "(Linux; Android 6.0.1; SHIELD Tablet K1 Build/MRA58K; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/55.0.2883.91" } --// Variables API._Debug = RunService:IsStudio() API.CollectEndpoint = string.format("http://www.google-analytics.com%s/collect", API._Debug and "/debug" or "") API.BatchEndpoint = string.format("http://www.google-analytics.com%s/batch", API._Debug and "/debug" or "") --// Functions function GetDeviceType.OnServerInvoke() --/ Prevents remote queue overflow end function GetViewportSize.OnServerInvoke() --/ Prevents remote queue overflow end local function MergeTables(...) local NewTable = {} for _, Table in ipairs({...}) do for Index, Value in next, Table do NewTable[Index] = Value end end return NewTable end local function RemovePlayerNames(SubmittedString) local RemovedPlayerId, FoundCount = 1, nil local NewString = SubmittedString for _, Player in next, PlayerService:GetPlayers() do NewString, FoundCount = string.gsub(NewString, Player.Name, string.format("<Player%i>", RemovedPlayerId)) if FoundCount > 0 then RemovedPlayerId += 1 end end return NewString end local function EncodeQuery(Data) local DataText = "" for Key, Value in next, Data do DataText = DataText .. string.format("&%s=%s", HttpService:UrlEncode(Key), HttpService:UrlEncode(ValueReplacements[Value] or Value) ) end return string.sub(DataText, 2) end local function EncodeBatch(BatchData) local DataText = "" for Index, Batch in next, BatchData do if Index > 1 then DataText = (DataText .. "/n") end DataText = (DataText .. EncodeQuery()) end end local function GetUserId(Player) return (typeof(Player) == "Instance" and Player.UserId or Player) end local function GetPlayerLocalization(Player) local Player = (typeof("Instance") and Player or PlayerService:GetPlayerByUserId(Player)) local Success, GeoID = pcall(function() return LocalizationService:GetCountryRegionForPlayerAsync(Player) end) if Player and Success then return GeoID end end local function GetUserAgent(Player) local Player = (typeof("Instance") and Player or PlayerService:GetPlayerByUserId(Player)) local DeviceType = GetDeviceType:InvokeClient(Player) return UserAgentMasks[DeviceType] or "" end function API:GetIdentificationData(Player) if not Player then return { ["cid"] = game.JobId, ["ds"] = "Server", } end local UserId = GetUserId(Player) local Player = (typeof("Instance") and Player or PlayerService:GetPlayerByUserId(Player)) local PlayerData = self.StoredPlayerData[UserId] if PlayerData then return PlayerData end PlayerData = { ["ds"] = "Player", ["uid"] = UserId, ["cid"] = string.sub(HttpService:GenerateGUID(), 2, -2), ["ua"] = string.format("Roblox/%s Lua/%s %s", RobloxVersion, LuaVersion, GetUserAgent(Player)), ["vp"] = GetViewportSize:InvokeClient(Player), ["cs"] = Player.FollowUserId > 0 and "Followed" or nil, ["ul"] = LocalizationService:GetTranslatorForPlayerAsync(Player).LocaleId, ["geoid"] = GetPlayerLocalization(Player), } self.StoredPlayerData[UserId] = PlayerData return PlayerData end function API:FlushPlayerData(Player) self.StoredPlayerData[GetUserId(Player)] = nil end function API:SendRequest(Data) return xpcall( HttpService.PostAsync, warn, HttpService, API.CollectEndpoint, EncodeQuery(MergeTables(self.DefaultData, Data)) ) end function API:ReportException(Player, Exception, IsFatal) assert(Exception ~= nil, "Event argument \"Exception\" is required.") return self:SendRequest(MergeTables(self:GetIdentificationData(Player), { ["t"] = "exception", ["exd"] = RemovePlayerNames(Exception), ["exf"] = IsFatal or false, })) end function API:ReportEvent(Player, Category, Action, Label, Value, Overrides) assert(Player ~= nil, "Event argument \"Player\" is required.") assert(Action ~= nil, "Event argument \"Action\" is required.") return self:SendRequest(MergeTables(self:GetIdentificationData(Player), { ["t"] = "event", ["ec"] = Category or "Game", ["ea"] = Action, ["el"] = Label, ["ev"] = Value, }, Overrides)) end function API:EnableAutoPlayerReporting() local function LoadPlayer(...) local Args = {...} coroutine.wrap(function(Player) self:ReportEvent(Player, nil, "Joining", game.PlaceId, nil, {["sc"] = "start"}) end)(Args[#Args]) end PlayerService.PlayerAdded:Connect(LoadPlayer) table.foreach(PlayerService:GetPlayers(), LoadPlayer) PlayerService.PlayerRemoving:Connect(function(Player) self:ReportEvent(Player, nil, "Leaving", game.PlaceId, nil, {["sc"] = "end"}) self:FlushPlayerData(Player) end) coroutine.wrap(function() while wait(60 * 5) do for _, Player in next, PlayerService:GetPlayers() do self:ReportEvent(Player, nil, "Heartbeat") end end end)() end function API.new(MeasurementId, Overrides) local self = setmetatable({}, API) self.MeasurementId = MeasurementId self.DefaultData = MergeTables({ ["v"] = 1, ["tid"] = self.MeasurementId, ["aip"] = true, ["av"] = game.PlaceVersion, }, Overrides) return self end return API
local assets= { Asset("ANIM", "anim/flint.zip"), } local function shine(inst) inst.task = nil inst.AnimState:PlayAnimation("sparkle") inst.AnimState:PushAnimation("idle") inst.task = inst:DoTaskInTime(4+math.random()*5, function() shine(inst) end) end local function fn(Sim) local inst = CreateEntity() inst.entity:AddTransform() inst.entity:AddAnimState() MakeInventoryPhysics(inst) inst.entity:AddSoundEmitter() inst.AnimState:SetRayTestOnBB(true); inst.AnimState:SetBank("flint") inst.AnimState:SetBuild("flint") inst.AnimState:PlayAnimation("idle") inst:AddComponent("edible") inst.components.edible.foodtype = "ELEMENTAL" inst.components.edible.hungervalue = 1 inst:AddComponent("tradable") inst:AddComponent("stackable") inst.components.stackable.maxsize = TUNING.STACK_SIZE_SMALLITEM inst:AddComponent("inspectable") inst:AddComponent("inventoryitem") --shine(inst) return inst end return Prefab( "common/inventory/flint", fn, assets)
--prints current time and position --[====[ position ======== Reports the current time: date, clock time, month, and season. Also reports location: z-level, cursor position, window size, and mouse location. ]====] local months = { 'Granite, in early Spring.', 'Slate, in mid Spring.', 'Felsite, in late Spring.', 'Hematite, in early Summer.', 'Malachite, in mid Summer.', 'Galena, in late Summer.', 'Limestone, in early Autumn.', 'Sandstone, in mid Autumn.', 'Timber, in late Autumn.', 'Moonstone, in early Winter.', 'Opal, in mid Winter.', 'Obsidian, in late Winter.', } --Fortress mode counts 1200 ticks per day and 403200 per year --Adventurer mode counts 86400 ticks to a day and 29030400 ticks per year --Twelve months per year, 28 days to every month, 336 days per year local julian_day = math.floor(df.global.cur_year_tick / 1200) + 1 local month = math.floor(julian_day / 28) + 1 --days and months are 1-indexed local day = julian_day % 28 local time_of_day = math.floor(df.global.cur_year_tick_advmode / 336) local second = time_of_day % 60 local minute = math.floor(time_of_day / 60) % 60 local hour = math.floor(time_of_day / 3600) % 24 print('Time:') print(' The time is '..string.format('%02d:%02d:%02d', hour, minute, second)) print(' The date is '..string.format('%05d-%02d-%02d', df.global.cur_year, month, day)) print(' It is the month of '..months[month]) --TODO: print(' It is the Age of '..age_name) print('Place:') print(' The z-level is z='..df.global.window_z) print(' The cursor is at x='..df.global.cursor.x..', y='..df.global.cursor.y) print(' The window is '..df.global.gps.dimx..' tiles wide and '..df.global.gps.dimy..' tiles high') if df.global.gps.mouse_x == -1 then print(' The mouse is not in the DF window') else print(' The mouse is at x='..df.global.gps.mouse_x..', y='..df.global.gps.mouse_y..' within the window') end --TODO: print(' The fortress is at '..x, y..' on the world map ('..worldsize..' square)')
help( [[ This module loads Circos 0.68 Circos is a software package for visualizing data and information. It visualizes data in a circular layout — this makes Circos ideal for exploring relationships between objects or positions. There are other reasons why a circular layout is advantageous, not the least being the fact that it is attractive. ]]) whatis("Loads Circos") local version = "0.68" local base = "/cvmfs/oasis.opensciencegrid.org/osg/modules/circos/"..version prepend_path("PATH", pathJoin(base, "bin")) prepend_path("PERL5LIB", pathJoin(base,"lib")) load('cpan/perl-5.10') family('circos')
local P = require("core.packet") local GRE = require("lib.protocol.gre") local Datagram = require("lib.protocol.datagram") local Ethernet = require("lib.protocol.ethernet") local IPV4 = require("lib.protocol.ipv4") local IPV6 = require("lib.protocol.ipv6") local TCP = require("lib.protocol.tcp") local ffi = require("ffi") require("networking_magic_numbers") local function clone_table(t, changes) changes = changes or {} local res = {} for k, v in pairs(t) do res[k] = v end for k, v in pairs(changes) do res[k] = v end return res end local function make_payload(len) local buf = ffi.new('char[?]', len) for i=0,len-1 do buf[i] = (i + 128) % 256 end return ffi.string(buf, len) end -- Returns an array of payload fragments. local function split_payload(payload, payload_len, fragment_len) -- add fragment_payload_len-1 to handle case when payload_len is divisible by fragment_payload_len -- want to compute (payload_len + fragment_len - 1) // fragment_payload_len but lua5.1 has no integer division local dividend = payload_len + fragment_len - 1 local num_fragments = (dividend - dividend % fragment_len) / fragment_len local fragments = {} for i=1,num_fragments do local curr_fragment_len = fragment_len if i == num_fragments then curr_fragment_len = payload_len - fragment_len * (num_fragments-1) end local fragment = string.sub(payload, (i-1) * fragment_len + 1, math.min(i * fragment_len, payload_len)) fragments[i] = fragment end return fragments, num_fragments end local PacketSynthesisContext = {} local function parse_mac(mac) if mac then return Ethernet:pton(mac) else return nil end end local function parse_addr(addr, use_ipv6) if addr then if use_ipv6 then return IPV6:pton(addr) else return IPV4:pton(addr) end else return nil end end -- Arguments (all optional): -- spike_mac (string) -- MAC address of the spike. -- router_mac (string) -- MAC address of the router. -- backend_vip_addr (string) -- Virtual IP address of the backend that -- the client queries. -- client_addr (string) -- IP address of the client. -- spike_internal_addr (string) -- Internal IP address of the spike. -- other_spike_internal_addr (string) -- Internal IP address of another -- spike that redirects IP fragments to this spike. -- backend_vip_port (int) -- Backend port that the client queires. -- client_port (int) -- Port that the client queries from. -- ttl (int) -- TTL for IP headers. -- mtu (int) -- MTU of network. function PacketSynthesisContext:new(network_config) local parsed_network_config = clone_table(network_config, { spike_mac = parse_mac(network_config.spike_mac), router_mac = parse_mac(network_config.router_mac), backend_vip_addr = parse_addr(network_config.backend_vip_addr, false), client_addr = parse_addr(network_config.client_addr, false), spike_internal_addr = parse_addr(network_config.spike_internal_addr, false), other_spike_internal_addr = parse_addr(network_config.other_spike_internal_addr, false), backend_vip_ipv6_addr = parse_addr(network_config.backend_vip_ipv6_addr, true), client_ipv6_addr = parse_addr(network_config.client_ipv6_addr, true), spike_internal_ipv6_addr = parse_addr(network_config.spike_internal_ipv6_addr, true), other_spike_internal_ipv6_addr = parse_addr(network_config.other_spike_internal_ipv6_addr, true) }) return setmetatable({ network_config = parsed_network_config, datagram = nil, datagram_len = 0 }, { __index = PacketSynthesisContext }) end function PacketSynthesisContext:new_packet() self.datagram = Datagram:new(nil, nil, {delayed_commit = true}) self.datagram_len = 0 end -- Arguments: -- payload (binary) -- Payload data to append. -- payload_len (int) -- Length of payload. function PacketSynthesisContext:add_payload(config) config = config or {} local payload_len = config.payload_len or 100 local payload = config.payload or make_payload(payload_len) self.datagram:payload(payload, payload_len) self.datagram_len = self.datagram_len + payload_len end -- Arguments: -- src_addr (binary, default client_addr) -- Source IP address. -- dst_addr (binary, default backend_vip_addr) -- Destination IP -- address. -- inner_prot/l4_prot (int, default L4_TCP) -- Inner protocol. -- ip_flags (int, default 0) -- Flags. -- ttl (int, default network_config.ttl or 30) -- TTL. -- ip_payload_len (int, default datagram_len) -- Length of payload, -- including L4 header. function PacketSynthesisContext:make_ip_header(config) config = config or {} local l3_prot = config.l3_prot or self.network_config.l3_prot or L3_IPV4 local payload_length = config.ip_payload_len or self.datagram_len local ip_header if l3_prot == L3_IPV6 then ip_header = IPV6:new({ src = config.src_ipv6_addr or config.src_addr or self.network_config.client_ipv6_addr, dst = config.dst_ipv6_addr or config.dst_addr or self.network_config.backend_vip_ipv6_addr, next_header = config.inner_prot or config.l4_prot or L4_TCP, hop_limit = config.ttl or self.network_config.ttl or 30 }) ip_header:payload_length(payload_length) elseif l3_prot == L3_IPV4 then ip_header = IPV4:new({ src = config.src_addr or self.network_config.client_addr, dst = config.dst_addr or self.network_config.backend_vip_addr, protocol = config.inner_prot or config.l4_prot or L4_TCP, flags = config.ip_flags or 0, frag_off = config.frag_off or 0, ttl = config.ttl or self.network_config.ttl or 30 }) local ip_header_size = ip_header:sizeof() ip_header:total_length(ip_header_size + payload_length) ip_header:checksum() else assert(false, 'invalid l3_prot') end return ip_header end function PacketSynthesisContext:add_ip_header(config) local ip_header = self:make_ip_header(config) self.datagram:push(ip_header) self.datagram_len = self.datagram_len + ip_header:sizeof() end -- TCP checksum requires the IP header, so it is easier to implement -- adding both at once. -- Arguments: -- src_port (int, default client_port) -- Source port. -- dst_port (int, default backend_vip_port) -- Destination port. -- tcp_payload (binary, default datagram:data()) -- Payload. -- tcp_payload_len (int, default length of datagram) -- Length of -- tcp_payload. function PacketSynthesisContext:make_tcp_ip_headers(config) config = config or {} local tcp_header = TCP:new({ src_port = config.src_port or self.network_config.client_port, dst_port = config.dst_port or self.network_config.backend_vip_port }) local tcp_header_size = tcp_header:sizeof() -- TCP data offset field is in units of 32-bit words tcp_header:offset(tcp_header_size / 4) local tcp_payload = config.tcp_payload local tcp_payload_len = config.tcp_payload_len if not tcp_payload then self.datagram:commit() tcp_payload, tcp_payload_len = self.datagram:data() end local ip_header = self:make_ip_header(clone_table(config, { ip_payload_len = tcp_payload_len + tcp_header_size })) tcp_header:checksum(tcp_payload, tcp_payload_len, ip_header) return tcp_header, ip_header end function PacketSynthesisContext:add_tcp_ip_headers(config) local tcp_header, ip_header = self:make_tcp_ip_headers(config) self.datagram:push(tcp_header) self.datagram:push(ip_header) self.datagram_len = self.datagram_len + tcp_header:sizeof() + ip_header:sizeof() end -- Arguments: -- inner_prot/l3_prot (int, default L3_IPV4) -- Inner protocol. function PacketSynthesisContext:add_gre_header(config) config = config or {} local gre_header = GRE:new({ protocol = config.inner_prot or config.l3_prot or L3_IPV4 }) self.datagram:push(gre_header) self.datagram_len = self.datagram_len + gre_header:sizeof() end -- Arguments: -- other_spike_internal_addr (binary, -- default network_config.other_spike_internal_addr) -- -- Address of spike sending the packet. -- spike_internal_addr (binary, default_network_config.spike_internal_addr) -- -- Address of spike (receiving the packet). function PacketSynthesisContext:add_spike_to_spike_ip_header(config) config = config or {} self:add_ip_header(clone_table(config, { src_addr = config.other_spike_internal_addr or self.network_config.other_spike_internal_addr, dst_addr = config.spike_internal_addr or self.network_config.spike_internal_addr })) end -- Arguments: -- spike_internal_addr (binary, default network_config.spike_internal_addr) -- -- Address of spike. -- backend_addr (binary, required) -- Address of backend that the packet -- is sent to. function PacketSynthesisContext:add_spike_to_backend_ip_header(config) config = config or {} self:add_ip_header(clone_table(config, { src_addr = config.spike_internal_addr or self.network_config.spike_internal_addr, src_ipv6_addr = config.spike_internal_ipv6_addr or self.network_config.spike_internal_ipv6_addr, dst_addr = config.backend_addr })) end -- Arguments: -- src_mac (binary, default router_mac) -- Source MAC address. -- dst_mac (binary, default spike_mac) -- Destination MAC address. -- inner_prot/l3_prot (int, default L3_IPV4) -- Inner protocol. function PacketSynthesisContext:add_ethernet_header(config) config = config or {} local eth_header = Ethernet:new({ src = config.src_mac or self.network_config.router_mac, dst = config.dst_mac or self.network_config.spike_mac, type = config.inner_prot or config.l3_prot or L3_IPV4 }) self.datagram:push(eth_header) self.datagram_len = self.datagram_len + eth_header:sizeof() end function PacketSynthesisContext:get_packet() self.datagram:commit() return self.datagram:packet() end -- Returns a packet similar to what Spike would receive in the normal case. function PacketSynthesisContext:make_in_packet_normal(config) config = config or {} self:new_packet() self:add_payload(config) self:add_tcp_ip_headers(config) self:add_ethernet_header(config) return self:get_packet() end -- Returns a packet similar to what Spike would receive in the case when -- an IPv4 fragment has been redirected to it. function PacketSynthesisContext:make_in_packet_redirected_ipv4_fragment( config ) config = config or {} self:new_packet() self:add_payload(config) self:add_ip_header(config) self:add_gre_header(config) self:add_spike_to_spike_ip_header(clone_table(config,{ inner_prot = L4_GRE, ip_flags = false, frag_off = 0 })) self:add_ethernet_header(config) return self:get_packet() end -- Arguments: -- mtu (default network_config.mtu) -- MTU of network. function PacketSynthesisContext:make_ipv4_fragments(config) config = config or {} self:new_packet() self:add_payload(config) local tcp_header, ip_header = self:make_tcp_ip_headers(config) self.datagram:push(tcp_header) self.datagram_len = self.datagram_len + tcp_header:sizeof() local p = self:get_packet() local ip_payload_len = self.datagram_len local ip_payload = ffi.string(p.data, ip_payload_len) local mtu = config.mtu or self.network_config.mtu or 100 local fragment_len = mtu - IP_HEADER_LENGTH -- fragment length must be a multiple of 8 fragment_len = fragment_len - fragment_len % 8 local fragments, num_fragments = split_payload( ip_payload, ip_payload_len, fragment_len ) P.free(p) return fragments, num_fragments end -- Returns a set of packets similar to what Spike would receive -- in the case when a set of IPv4 fragments have been redirected to it. function PacketSynthesisContext:make_in_packets_redirected_ipv4_fragments( config ) config = config or {} local fragments, num_fragments = self:make_ipv4_fragments(config) local packets = {} local curr_offset = 0 for i=1,num_fragments do local ip_flags = 0 if i ~= num_fragments then ip_flags = IP_MF_FLAG end -- fragment offset field is units of 8-byte blocks local frag_len = string.len(fragments[i]) local frag_off = curr_offset / 8 packets[i] = self:make_in_packet_redirected_ipv4_fragment( clone_table(config, { payload = fragments[i], payload_len = frag_len, ip_flags = ip_flags, frag_off = frag_off }) ) curr_offset = curr_offset + frag_len end return packets, num_fragments end function PacketSynthesisContext:make_out_packet_normal(config) config = config or {} self:new_packet() self:add_payload(config) self:add_tcp_ip_headers(config) self:add_gre_header(config) local l3_prot = config.outer_l3_prot or config.l3_prot self:add_spike_to_backend_ip_header(clone_table(config, { l3_prot = l3_prot, inner_prot = L4_GRE })) self:add_ethernet_header(clone_table(config, { src_mac = self.network_config.spike_mac, dst_mac = self.network_config.router_mac, l3_prot = l3_prot })) return self:get_packet() end return PacketSynthesisContext
require("stategraphs/commonstates") local function GetScalePercent(inst) return (inst.components.scaler.scale - TUNING.ROCKY_MIN_SCALE) / (TUNING.ROCKY_MAX_SCALE - TUNING.ROCKY_MIN_SCALE) end local function PlayLobSound(inst, sound) inst.SoundEmitter:PlaySoundWithParams(sound, {size=GetScalePercent(inst)}) end local actionhandlers = { ActionHandler(ACTIONS.TAKEITEM, "rocklick"), ActionHandler(ACTIONS.PICKUP, "rocklick"), ActionHandler(ACTIONS.EAT, "eat"), } local events = { CommonHandlers.OnLocomote(false, true), CommonHandlers.OnFreeze(), CommonHandlers.OnAttack(), CommonHandlers.OnAttacked(), CommonHandlers.OnDeath(), CommonHandlers.OnSleep(), EventHandler("gotosleep", function(inst) inst.sg:GoToState("sleep") end), EventHandler("entershield", function(inst) inst.sg:GoToState("shield_start") end), EventHandler("exitshield", function(inst) inst.sg:GoToState("shield_end") end), } local function pickrandomstate(inst, choiceA, choiceB, chance) if math.random() >= chance then inst.sg:GoToState(choiceA) else inst.sg:GoToState(choiceB) end end local states = { State{ name = "idle_tendril", tags = {"idle", "canrotate"}, onenter = function(inst, playanim) inst.Physics:Stop() if playanim then inst.AnimState:PlayAnimation(playanim) inst.AnimState:PushAnimation("idle_tendrils") else inst.AnimState:PlayAnimation("idle_tendrils") end end, timeline = { TimeEvent(5*FRAMES, function(inst) PlayLobSound(inst, "dontstarve/creatures/rocklobster/idle") end), TimeEvent(20*FRAMES, function(inst) PlayLobSound(inst, "dontstarve/creatures/rocklobster/idle") end), }, events= { EventHandler("animover", function(inst) inst.sg:GoToState("idle") end), }, }, State{ name = "eat", tags = {"idle"}, onenter = function(inst, playanim) inst.Physics:Stop() inst.AnimState:PlayAnimation("idle_tendrils") PlayLobSound(inst, "dontstarve/creatures/rocklobster/foley") end, timeline = { TimeEvent(0*FRAMES, function(inst) PlayLobSound(inst, "dontstarve/creatures/rocklobster/foley") end), TimeEvent(8*FRAMES, function(inst) inst:PerformBufferedAction() PlayLobSound(inst, "dontstarve/creatures/rocklobster/idle") end), TimeEvent(20*FRAMES, function(inst) PlayLobSound(inst, "dontstarve/creatures/rocklobster/foley") end), }, events= { EventHandler("animover", function(inst) inst.sg:GoToState("idle") end), }, }, State{ name = "taunt", tags = {"busy"}, onenter = function(inst) inst.Physics:Stop() inst.AnimState:PlayAnimation("taunt") PlayLobSound(inst, "dontstarve/creatures/rocklobster/foley") PlayLobSound(inst, "dontstarve/creatures/rocklobster/taunt") end, timeline = { TimeEvent(10*FRAMES, function(inst) PlayLobSound(inst, "dontstarve/creatures/rocklobster/foley") end), TimeEvent(30*FRAMES, function(inst) PlayLobSound(inst, "dontstarve/creatures/rocklobster/foley") end), }, events= { EventHandler("animover", function(inst) inst.sg:GoToState("idle") end), }, }, State{ name = "rocklick", tags = {"busy"}, onenter = function(inst) inst.Physics:Stop() inst.AnimState:PlayAnimation("rocklick_pre") inst.AnimState:PushAnimation("rocklick_loop") inst.AnimState:PushAnimation("rocklick_pst", false) end, timeline = { TimeEvent(5*FRAMES, function(inst) PlayLobSound(inst, "dontstarve/creatures/rocklobster/foley") end), TimeEvent(10*FRAMES, function(inst) PlayLobSound(inst, "dontstarve/creatures/rocklobster/attack") end), TimeEvent(20*FRAMES, function(inst) PlayLobSound(inst, "dontstarve/creatures/rocklobster/foley") end), TimeEvent(25*FRAMES, function(inst) inst:PerformBufferedAction() end ), TimeEvent(35*FRAMES, function(inst) PlayLobSound(inst, "dontstarve/creatures/rocklobster/foley") end), }, events= { EventHandler("animqueueover", function(inst) inst.sg:GoToState("idle") end), }, }, State{ name = "shield_start", tags = {"busy", "hiding"}, onenter = function(inst) inst.AnimState:PlayAnimation("hide") PlayLobSound(inst, "dontstarve/creatures/rocklobster/foley") PlayLobSound(inst, "dontstarve/creatures/rocklobster/hide") inst.Physics:Stop() end, events= { EventHandler("animover", function(inst) inst.sg:GoToState("shield") end ), }, }, State{ name = "shield", tags = {"busy", "hiding"}, onenter = function(inst) --If taking fire damage, spawn fire effect. inst.components.health:SetAbsorptionAmount(TUNING.ROCKY_ABSORB) inst.AnimState:PlayAnimation("hide_loop") inst.components.health:StartRegen(TUNING.ROCKY_REGEN_AMOUNT, TUNING.ROCKY_REGEN_PERIOD) inst.sg:SetTimeout(3) end, onexit = function(inst) inst.components.health:SetAbsorptionAmount(0) inst.components.health:StopRegen() end, ontimeout = function(inst) inst.sg:GoToState("shield") end, timeline = { TimeEvent(20*FRAMES, function(inst) PlayLobSound(inst, "dontstarve/creatures/rocklobster/sleep") end), }, }, State{ name = "shield_end", tags = {"busy", "hiding"}, onenter = function(inst) inst.AnimState:PlayAnimation("unhide") PlayLobSound(inst, "dontstarve/creatures/rocklobster/foley") end, timeline = { TimeEvent(10*FRAMES, function(inst) PlayLobSound(inst, "dontstarve/creatures/rocklobster/foley") end), }, events= { EventHandler("animqueueover", function(inst) inst.sg:GoToState("idle") end ), }, }, } CommonStates.AddWalkStates(states, { starttimeline = { TimeEvent(0*FRAMES, function(inst) PlayLobSound(inst, "dontstarve/creatures/rocklobster/foley") end), }, walktimeline = { TimeEvent(1*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/rocklobster/footstep") end), TimeEvent(8*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/rocklobster/footstep") end), TimeEvent(12*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/rocklobster/footstep") end), TimeEvent(15*FRAMES, function(inst) PlayLobSound(inst, "dontstarve/creatures/rocklobster/foley") end), TimeEvent(26*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/rocklobster/footstep") end), TimeEvent(30*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/rocklobster/footstep") end), }, endtimeline = { TimeEvent(0*FRAMES, function(inst) PlayLobSound(inst, "dontstarve/creatures/rocklobster/foley") end), }, }) CommonStates.AddSleepStates(states, { starttimeline = { TimeEvent(0*FRAMES, function(inst) PlayLobSound(inst, "dontstarve/creatures/rocklobster/foley") end), }, sleeptimeline = { TimeEvent(0*FRAMES, function(inst) PlayLobSound(inst, "dontstarve/creatures/rocklobster/sleep") end), TimeEvent(20*FRAMES, function(inst) PlayLobSound(inst, "dontstarve/creatures/rocklobster/foley") end), }, endtimeline ={ TimeEvent(0*FRAMES, function(inst) PlayLobSound(inst, "dontstarve/creatures/rocklobster/foley") end), }, }) local function hitanim(inst) if inst:HasTag("hiding") then return "hide_hit" else return "hit" end end local combatanims = { hit = hitanim, } CommonStates.AddCombatStates(states, { attacktimeline = { TimeEvent(0*FRAMES, function(inst) PlayLobSound(inst, "dontstarve/creatures/rocklobster/foley") end), TimeEvent(0*FRAMES, function(inst) PlayLobSound(inst, "dontstarve/creatures/rocklobster/attack") end), TimeEvent(5*FRAMES, function(inst) PlayLobSound(inst, "dontstarve/creatures/rocklobster/foley") end), TimeEvent(8*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/rocklobster/clawsnap_small") end), TimeEvent(12*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/rocklobster/clawsnap_small") end), TimeEvent(13*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/rocklobster/attack_whoosh") end), TimeEvent(20*FRAMES, function(inst) inst.SoundEmitter:PlaySound("dontstarve/creatures/rocklobster/clawsnap") end), TimeEvent(20*FRAMES, function(inst) inst.components.combat:DoAttack() end), TimeEvent(25*FRAMES, function(inst) PlayLobSound(inst, "dontstarve/creatures/rocklobster/foley") end), TimeEvent(30*FRAMES, function(inst) PlayLobSound(inst, "dontstarve/creatures/rocklobster/foley") end), }, hittimeline = { TimeEvent(0*FRAMES, function(inst) PlayLobSound(inst, "dontstarve/creatures/rocklobster/hurt") end), TimeEvent(0*FRAMES, function(inst) PlayLobSound(inst, "dontstarve/creatures/rocklobster/foley") end), }, deathtimeline = { TimeEvent(0*FRAMES, function(inst) PlayLobSound(inst, "dontstarve/creatures/rocklobster/death") PlayLobSound(inst, "dontstarve/creatures/rocklobster/explode") end), }, }, combatanims) CommonStates.AddFrozenStates(states) CommonStates.AddIdle(states, "idle_tendril", nil , { TimeEvent(5*FRAMES, function(inst) PlayLobSound(inst, "dontstarve/creatures/rocklobster/foley") end), TimeEvent(30*FRAMES, function(inst) PlayLobSound(inst,"dontstarve/creatures/rocklobster/foley") end), }) return StateGraph("rocky", states, events, "idle", actionhandlers)
local DialogCfg = { ["ShopFrame"] = {parentTag = "MapSceneUIRootMid"}, ["Role_Frame"] = {parentTag = "MapSceneUIRootMid"}, ["PvpArena_Frame"] = {parentTag = "MapSceneUIRootMid"}, ["NewChatFrame"] = {parentTag = "MapSceneUIRootMid"}, ["DrawCard/newDrawCardFrame"] = {parentTag = "MapSceneUIRootMid"}, ["HeroComposeFrame"] = {parentTag = "MapSceneUIRootMid"}, ["mapSceneUI/newMapSceneActivity"] = {parentTag = ""}, ["mapSceneUI/QuestGuideTip"] = {parentTag = ""}, ["DrawSliderFrame"] = {Ignore = true} } local TeamOrFighting = { -- ["newSelectMap/newSelectMap"] = {tip = TeamOrFightingTip}, -- ["newSelectMap/newGoCheckpoint"] = {tip = TeamOrFightingTip}, -- ["PvpArena_Frame"] = {tip = TeamOrFightingTip}, -- ["guild_pvp/GuildPVPJoinPanel"] = {tip = TeamOrFightingTip}, -- ["PveArenaFrame"] = {tip = TeamOrFightingTip}, } local MapTeamOrFighting = { [25] = {Dialog = "newUnion/newUnionFrame"}, [26] = {Dialog = "Manor_Overview"}, ["map_chouka"] = {Dialog = "DrawCard/newDrawCardFrame"}, [12] = {Dialog = "DrawCard/newDrawCardFrame"}, } local function GetCfg(name) return DialogCfg[name] end local function CheckDialog(name) if TeamOrFighting[name] then if SceneStack.GetBattleStatus() then showDlgError(nil, "战斗内无法进行该操作") return false end if utils.SGKTools.GetTeamState() then showDlgError(nil, "队伍内无法进行该操作") return false end end return true end local function CheckMap(id) if MapTeamOrFighting[id] then if MapTeamOrFighting[id].Dialog then DialogStack.Push(MapTeamOrFighting[id].Dialog) return false else if SceneStack.GetBattleStatus() then showDlgError(nil, "战斗内无法进行该操作") return false end if utils.SGKTools.GetTeamState() then showDlgError(nil, "队伍内无法进行该操作") return false end end end return true end return { GetCfg = GetCfg, CheckDialog = CheckDialog, CheckMap = CheckMap, }
isStarting = true function Update(dt) if (isStarting == true) then timer = 0 step = 1 children = gameObject:GetChildren() for i = 1, #children do if(i == 1)then children[i]:Active(true) else children[i]:Active(false) end end isStarting = false end timer = timer + dt; --str = "Timer value:" .. timer .. "\n" --Log(str) if(timer > 0.1) then if(step == 1 or step == 7) then children[6]:Active(false) children[1]:Active(true) step = 2 else StepAnimation(step) step = step + 1 end timer = 0; end end function StepAnimation(step) children[step - 1]:Active(false) children[step]:Active(true) end
<%- partial('../sidebar') %> <div id='content'> <div class='panel'> <div class='header'> <ul class='breadcrumb'> <li><a href='/'>主页</a><span class='divider'>/</span></li> <li class='active'>Top100 积分榜</li> </ul> </div> <div class='inner'> <% if type(users) == 'table' and #users > 0 then %> <table class='table table-condensed table-striped'> <thead> <th>#</th><th>用户名</th><th>积分</th><th>主题数</th><th>评论数</th> </thead> <tbody> <%- partial('./top100_user',{collection = users, as = 'user'}) %> </tbody> </table> <% else %> <p>还没有用户</p> <% end %> </div> </div> </div>
-- CONFIG -- Author: KingAmond & Bucky function sendForbiddenMessage(message) TriggerEvent("chatMessage", "", {0, 0, 0}, "^1" .. message) end function _DeleteEntity(entity) Citizen.InvokeNative(0xAE3CBE5BF394C9C9, Citizen.PointerValueIntInitialized(entity)) end
------------------------------------------------------------ -- SoloFrames.lua -- -- Abin -- 2012/1/03 ------------------------------------------------------------ local _, addon = ... local frame = addon:CreateGroupParent("CompactRaidSoloFrame") addon.soloFrame = frame RegisterStateDriver(frame, "visibility", "[group] hide; show") local playerButton = CreateFrame("Button", frame:GetName().."Player", frame, "AbinCompactRaidUnitButtonTemplate") playerButton:SetAttribute("unit", "player") playerButton:SetPoint("TOPLEFT") playerButton:Show() local petButton = CreateFrame("Button", frame:GetName().."Pet", frame, "AbinCompactRaidUnitButtonTemplate") petButton:SetAttribute("unit", "pet") RegisterStateDriver(petButton, "visibility", "[nopet] hide; [vehicleui] hide; show") function addon:GetSoloFramesMatrix() local hasPet = petButton:IsVisible() local count = hasPet and 2 or 1 if addon.db.grouphoriz then return count, 1, hasPet else return 1, count, hasPet end end local function UpdateLayout() local horiz, spacing = addon:GetLayoutData() petButton:ClearAllPoints() if horiz then petButton:SetPoint("LEFT", playerButton, "RIGHT", spacing, 0) else petButton:SetPoint("TOP", playerButton, "BOTTOM", 0, -spacing) end end addon:RegisterOptionCallback("grouphoriz", UpdateLayout) addon:RegisterOptionCallback("spacing", UpdateLayout)
local Factory = cc.import(".Factory") local NginxWorkerBootstrap = cc.class("NginxWorkerBootstrap") function NginxWorkerBootstrap:ctor(appKeys, globalConfig) self._configs = Factory.makeAppConfigs(appKeys, globalConfig, package.path) end function NginxWorkerBootstrap:runapp(appRootPath) --cc.dump(self._configs) local appConfig = self._configs[appRootPath] local workerInstance = Factory.create(appConfig, "NginxWorkerInstance") return workerInstance:run() end return NginxWorkerBootstrap
-- Manifest resource_manifest_version '77731fab-63ca-442c-a67b-abc70f28dfa5' description 'iJob by Izio.' ui_page 'ui/ui.html' -- Server server_scripts { 'iJob_server.lua', 'classe/job.lua', '@mysql-async/lib/MySQL.lua', } -- Client client_scripts { 'iJob_client.lua', 'gui.lua' } -- NUI Files files { 'ui/ui.html', 'ui/scripts.js', 'ui/style.css', 'ui/jquery-3.2.1.min.js', -- }
local PANEL = {} function PANEL:Init() self:SetSize(200, 150) self:Center() self:SetTitle("ATM") self:MakePopup() local bankBalance = LocalPlayer():GetSyncVar(SYNC_BANKMONEY, 0) local prefix = impulse.Config.CurrencyPrefix local parent = self self.balance = vgui.Create("DLabel", self) self.balance:SetText("Balance: "..prefix..bankBalance) self.balance:SetFont("Impulse-Elements18") self.balance:SizeToContents() self.balance:SetPos(100 - (self.balance:GetWide()/2), 30) self.withdrawInput = vgui.Create("DTextEntry", self) self.withdrawInput:SetPos(10, 70) self.withdrawInput:SetSize(120, 20) self.withdrawInput:SetNumeric(true) self.withdrawButton = vgui.Create("DButton", self) self.withdrawButton:SetText("Withdraw") self.withdrawButton:SetPos(135, 70) self.withdrawButton:SetSize(55, 20) function self.withdrawButton:DoClick() if parent.withdrawInput:GetValue() == "" then return true end local num = tonumber(parent.withdrawInput:GetValue()) if not num then return end net.Start("impulseATMWithdraw") net.WriteUInt(math.floor(num), 32) net.SendToServer() end self.depositInput = vgui.Create("DTextEntry", self) self.depositInput:SetPos(10, 100) self.depositInput:SetSize(120, 20) self.depositInput:SetNumeric(true) self.despoitButton = vgui.Create("DButton", self) self.despoitButton:SetText("Deposit") self.despoitButton:SetPos(135, 100) self.despoitButton:SetSize(55, 20) function self.despoitButton:DoClick() if parent.depositInput:GetValue() == "" then return true end local num = tonumber(parent.depositInput:GetValue()) if not num then return end net.Start("impulseATMDeposit") net.WriteUInt(math.floor(num), 32) net.SendToServer() end end function PANEL:SetBalance(m) self.balance:SetText("Balance: "..impulse.Config.CurrencyPrefix..m) self.balance:SizeToContents() self.balance:SetPos(100 - (self.balance:GetWide()/2), 30) end function PANEL:Think() local curMoney = LocalPlayer():GetSyncVar(SYNC_BANKMONEY, 0) self.lastMoney = self.lastMoney or curMoney if self.lastMoney != curMoney then self:SetBalance(curMoney) end end vgui.Register("impulseATMMenu", PANEL, "DFrame")
--[[ Loading of crop definition stored in a csv file. The import is extendable, so new columns in the config file are imported to new field in the table. First line: Header Second line should be default crop, where several default values are stored. Actual columns: Name Name of the crop. Is used for registering all nodes and craftitems Enabled void crop is not registered in the game an value crop is registered with configured features hijack text Which crop of other mod should be hijacked (not to use in mod:farming) next_plant text For wild crop the name of the cultured crop. By change you get the seed or harvest of the cultured one Must be a name of another crop in this list Rarety How often the crop spawn in the wild Rarety_grass_drop Change to get crop as drop item when digging grass Rarety_junglegrass_drop Change to get crop as drop item when digging jungle grass Rarety_decoration Rarety for register_decoration function: It will appear on new generated maps beside abm function Steps Amount of steps the growing needs till full grown plant. Must be set harvest_max Max. amount of harvest or seed you can dig out of full grown plant eat_hp eat health point: How many HP you get by eating the seed. drink for thirst mods: How much Drink point you get by eating the harvest or seed to_culture void crop can be generated during mapgen and spawn randomly on grassland any value crop can not be find randomly on the map. The seed has to be found in the wild form or crafted. to_dig void any value has_harvest void drops seed which can be used for planting new crops any value drops harvest, where the seed has to be crafted out of the harvest on_soil void can be planted everywhere where the conditions are met (temperature etc.) any value crap can be found in the wild, but planted only on wet soil, without checking for temperature etc. punchable void the plant has to be dug to get harvest or seed any value by punching the last step of the crop, you get one seed and the plant change to second last stage infectable void any value the plant can be infected, where the crop does not give any seed or harvest and may infect other crops nearby Higher values means more infectable wiltable void 1 Wilt is going one step back, like Berries: They loose the fruits, but grow again 2 Plant wilt and remove itself after time. During wilt you can harvest straw if defined. For grain 3 crop is spreading seed around and go one step back or dies like nettles is_bush void any value define a bush with a mesh instead of tiles infection_defense any value can protect nearby crop against infection. value give range of protection seed_extractable any value crop gives normally only harvest, out of which no seeds can be crafted, like tea. no_seed void any value use_flail void any value extension to define crafting recipe: With flail you get the seeds out of harvest and kind of fibres/straw use_trellis void any value the crop needs kind of trellis for growing. the trellis is recyclable: You get the trellis back by digging the plant at any stage. for_coffee void any value extension to define crafting recipes to brew coffee out of seed for_flour void any value extension to define crafting recipes to craft normal flour out of seed seed_roastable any value seed can be roasted in a oven, needs "crop_roasted.png" value is used as roast time seed_grindable any value seed can be grinded, e.g. in a coffee grinder, needs "crop_grind.png" or value in grind damage_per_second any value damage a player get while in a node with this crop, e.g. thorns of raspberries liquid_viscosity any value resistance a player sees while walking through a field temperature_min/_max Range of temperature inside the crop can grow. humidity_min/_max Range of humidity elevation_min/_max Height range the crop can be found light_min Minimun amount of light needed for growing. Crop can be planted only on placed where light_min is reached at midday. It is also needed for calculating the grow_time. With more light at midday the crop grows faster. light_max If node light exceed this value after grow time, the timer starts again without growing. infect_rate_base Normal infect rate for crops infect_rate_monoculture Infect rate if many crops are standing nearby. spread_rate Full grown crops can spread to neighbor block grow_time_mean mean grow time to next step wilt_time Time for wilt of a crop straw text extension for using flail: item name of fibre to craft out of harvest beside seeds culture_rate rate to get cultured variant out of wild form. seed_drop name of seed you get from plant: grapes drops seed which normally lead to wild wine. Only with a trellis you get cultured whine with higher harvest. With normal grapes and a trellis you get the "seed" for cultured wine. grind name of item for grinded seed spawn_by text only with rarety_deco: set spawn_by in register_decoration ]] local S = farming.intllib farming.path = minetest.get_modpath("farming") local has_value = basic_functions.has_value local crop_cols={ col_num={"rarety","steps","harvest_max","eat_hp","temperature_min","temperature_max", "humidity_min","humidity_max","elevation_min","elevation_max","light_min","light_max", "infect_rate_base","infect_rate_monoculture","spread_rate","grow_time_mean","roast_time", "wilt_time","rarety_grass_drop","rarety_decoration"}, groups_num={"to_culture","to_dig","has_harvest","on_soil","punchable","infectable","is_bush", "seed_extractable","use_flail","use_trellis","snappy","infection_defence","seed_roastable", "seed_grindable","for_flour","for_coffee","damage_per_second","liquid_viscosity","wiltable"}} local crop_definition = basic_functions.import_csv(farming.path.."/crops.txt",crop_cols) -- for the default entry is checked, which numeric values are filled -- this values are copied into void fields of the crops if crop_definition["default"] ~= nil then default_crop = crop_definition["default"] local test_values = {} -- check, which numeric columns exist in default entry for i,d in pairs(crop_cols.col_num) do if default_crop[d] ~= nil then table.insert(test_values,1,d) end end -- check for each crop, if value can be copied from default entry for i,tdef in pairs(crop_definition) do if tdef.name ~= default_crop.name then for j,colu in pairs(test_values) do if tdef[colu] == nil then crop_definition[tdef.name][colu] = default_crop[colu] end end end end end -- register crops for i,tdef in pairs(crop_definition) do if i ~= "default" then -- only register when crop is enabled if tdef.enabled then local starttime=os.clock() farming.register_plant(tdef) print("farming registering "..tdef.name.." in "..(math.floor(1000000*(os.clock()-starttime))/1000).." milliseconds") else print("farming "..tdef.name.." disabled") end end end local no_items=tonumber(#farming.grass_drop.items) local tgd={items={}} for i,gdrop in pairs(farming.grass_drop.items) do if gdrop.rarity ~= nil then gdrop.rarity=gdrop.rarity * (1 + no_items - tonumber(i)) end table.insert(tgd.items,gdrop) end minetest.override_item("default:grass_5",{drop=tgd}) minetest.override_item("default:grass_4",{drop=tgd}) local no_items=tonumber(#farming.junglegrass_drop.items) local tgd={items={}} for i,gdrop in pairs(farming.junglegrass_drop.items) do if gdrop.rarity ~= nil then gdrop.rarity=gdrop.rarity * (1 + no_items - tonumber(i)) end table.insert(tgd.items,gdrop) end minetest.override_item("default:junglegrass",{drop=tgd})
require("config") require("patterns") local jsonInterface = require("jsonInterface") tableHelper = require("tableHelper") local BasePlayer = require("player.base") local Player = class("Player", BasePlayer) function Player:__init(pid, playerName) BasePlayer.__init(self, pid, playerName) -- Replace characters not allowed in filenames self.accountName = string.gsub(self.accountName, patterns.invalidFileCharacters, "_") self.accountFile = tes3mp.GetCaseInsensitiveFilename(os.getenv("MOD_DIR").."/player/", self.accountName .. ".json") if self.accountFile == "invalid" then self.hasAccount = false self.accountFile = self.accountName .. ".json" else self.hasAccount = true end end function Player:CreateAccount() jsonInterface.save("player/" .. self.accountFile, self.data) self.hasAccount = true end function Player:Save() if self.hasAccount then jsonInterface.save("player/" .. self.accountFile, self.data, config.playerKeyOrder) end end function Player:Load() self.data = jsonInterface.load("player/" .. self.accountFile) -- JSON doesn't allow numerical keys, but we use them, so convert -- all string number keys into numerical keys tableHelper.fixNumericalKeys(self.data) end return Player
return { -- Polar Night dark_black = '#181818', -- bg black = '#282828', bright_black = '#8d8d8d', gray = '#4c566a', -- Custom darkish_black = '#3B414D', grayish = '#667084', -- Snow Storm dark_white = '#b0b0b0', white = '#e7e7e7', bright_white = '#f8f8f8', -- Frost cyan = '#218693', -- classes, types and primitives. bright_cyan = '#77dfd8', -- declarations, calls and execution statements of functions, methods and routines. blue = '#569cd6', -- keywords, support characters, operators, tags, units, punctuations intense_blue = '#9cd9f0', -- pragmas, comment keywords and pre-processor statements. -- Aurora red = '#fab1ab', -- deletions and errors orange = '#d08770', -- annotations and decorators yellow = '#f6dc69', -- modifications, warning and escape characters green = '#d1fa71', -- additions and string purple = '#c586c0' -- integers and floating point numbers }
local lpeg = require'lpeg' local rawset = rawset local gsub = string.gsub local find = string.find local V = lpeg.V local P = lpeg.P local R = lpeg.R local C = lpeg.C local S = lpeg.S local Cg = lpeg.Cg local Ct = lpeg.Ct local Cf = lpeg.Cf local Cc = lpeg.Cc local Cmt = lpeg.Cmt local STRICT = {} local TWITCH = {} local LOOSE = {} local UPPER = R('AZ') local LOWER = R('az') local DIGIT = R('09') local LETTER = UPPER + LOWER local DASH = P'-' local SPACE = P' ' local CRLF = P'\r\n' local LF = P'\n' local HEXDIGIT = DIGIT + R('AF') + R('af') local SPECIAL = S'[]\\`_^{|}' local OCTET = DIGIT * DIGIT^-2 local VALID_OCTET = P'1' * DIGIT * DIGIT + P'2' * (R'04'*DIGIT + P'5'*R'05') + DIGIT * DIGIT^-1 local IP4 = VALID_OCTET * P'.' * VALID_OCTET * P'.' * VALID_OCTET * P'.' * VALID_OCTET local H16 = HEXDIGIT * HEXDIGIT^-3 local HG = H16 * P':' local LS32 = HG * H16 + IP4 local escapes = setmetatable({}, { __index = function(_,k) return k end, }) escapes['\\'] = '\\' escapes[':'] = ';' escapes['s'] = ' ' escapes['r'] = '\r' escapes['n'] = '\n' local function create_unescape_tag_val(replacement) return function(_,_,val) if #val == 0 then return true, replacement end if not find(val,'\\',1,true) then return true,val end val = gsub(val,'\\(.?)',escapes) return true, val end end local function create_base_grammar(params) if not params then params = {} end local empty_replacement = false local missing_replacement = false if params.empty_tag_replacement ~= nil then empty_replacement = params.empty_tag_replacement end if params.missing_tag_replacement ~= nil then missing_replacement = params.missing_tag_replacement end if params.remove_empty_tags then empty_replacement = nil end if params.remove_missing_tags then missing_replacement = nil end local grammar = { 'message', message = (P'@' * Cg(V'tags','tags'))^-1 * (P':' * Cg(Ct(V'source'),'source'))^-1 * Cg(V'command','command') * (V'space' * Cg(Ct(V'params'),'params'))^0 * (CRLF + LF + -P(1)), tags = Cf(Ct'' * (V'tag' * (P';' * V'tag')^0),rawset) * V'space', tag = Cg(C(V'tag_key') * ( (P'=' * V'tag_value') + V'tag_missing')), tag_key = P'+'^-1 * ( V'tag_vendor' * P'/' )^-1 * V'tag_name', tag_vendor = V'host', tag_name = (LETTER + DIGIT + DASH)^1, tag_value = Cmt(V'tag_raw_value', create_unescape_tag_val(empty_replacement)), tag_raw_value = R('\001\009','\011\12','\014\031','\033\058','\060\255')^0, tag_missing = Cc(missing_replacement), -- we create a distinct 'userhost' type, -- so that we can override it -- grammar source = (Cg(V'host','host') * V'space') + ( (Cg(V'nick','nick') * (P'!' * Cg(V'user','user'))^-1 * (P'@' * Cg(V'userhost','host'))^-1) * V'space'), userhost = V'host', command = (LETTER^1) + (DIGIT * DIGIT * DIGIT), params = (C(V'middle') * (V'space' * V'params')^0) + (':' * C(V'trailing')), middle = V'nospcrlfcl' * (P':' + V'nospcrlfcl')^0, trailing = (P':' + P' ' + V'nospcrlfcl')^0, host = V'hostaddr' + (V'hostname' - (OCTET * '.' * OCTET * '.' * OCTET * '.' * OCTET)), hostname = V'label' * (P'.' * V'label')^0, hostaddr = V'ip4addr' + V'ip6addr', ip4addr = IP4, ip6addr = HG * HG * HG * HG * HG * HG * LS32 + P'::' * HG * HG * HG * HG * HG * LS32 + H16^-1 * P'::' * HG * HG * HG * HG * LS32 + (HG * HG^-1 + P':') * P':' * HG * HG * HG * LS32 + (HG * HG^-2 + P':') * P':' * HG * HG * LS32 + (HG * HG^-3 + P':') * P':' * HG * LS32 + (HG * HG^-4 + P':') * P':' * LS32 + (HG * HG^-5 + P':') * P':' * H16 + (HG * HG^-6 + P':') * P':', label = (LETTER + DIGIT) * (LETTER + DIGIT + DASH)^0 * (LETTER + DIGIT)^0, nick = (LETTER + SPECIAL) * (LETTER + DIGIT + SPECIAL + P'-')^0, user = R('\001\009','\011\012','\014\031','\033\063','\065\255')^1, space = SPACE^1, nonwhite = R('\001\009','\011\012','\014\031','\033\255'), nospcrlfcl = R('\001\009','\011\012','\014\031','\033\057','\059\255'), } return grammar end local strict_grammar = {} local twitch_grammar = { userhost = (V'twitchusername' * P'.' * V'host') + V'host', nick = V'twitchusername', user = V'twitchusername', twitchusername = (LETTER + DIGIT) * (LETTER + DIGIT + P'_')^0, } local loose_grammar = { -- a lot of IRC servers let users "cloak" their IP/hostname -- and includes characters not allowed in DNS, like: -- :nick!~user@user/nick/etc -- so we override the userhost to just allow anything besides CR, LF, Space userhost = V'nonwhite'^1, -- let the loose grammar accept anything for a nick, besides !@ nick = R('\001\009','\011\012','\014\031','\034\063','\065\255')^1, -- tag vendor, don't check for actual hostnames and ip addresses tag_vendor = (R('\001\009','\011\012','\014\031','\033\046','\048\058','\062\255') + P('\060'))^1, -- tag name, allow anything besides =;' ' tag_name = (R('\001\009','\011\012','\014\031','\033\046','\048\058','\062\255') + P('\060'))^1, } local Strict = { grammar = strict_grammar, parse = function(self,str,init) init = init or 1 local msg, pos = self.parser:match(str,init) return msg, pos end, } local Twitch = { grammar = twitch_grammar, parse = Strict.parse, } local Loose = { grammar = loose_grammar, parse = Strict.parse, } local Strict__mt = { __index = Strict, __name = 'irc-parser.strict', __call = Strict.parse, } local Twitch__mt = { __index = Twitch, __name = 'irc-parser.twitch', __call = Twitch.parse, } local Loose__mt = { __index = Loose, __name = 'irc-parser.loose', __call = Loose.parse, } local typ_map = { [1] = Loose__mt, [2] = Strict__mt, [3] = Twitch__mt, ['loose'] = Loose__mt, [LOOSE] = Loose__mt, ['strict'] = Strict__mt, [STRICT] = Strict__mt, ['twitch'] = Twitch__mt, [TWITCH] = Twitch__mt, } local function new(typ,params) if not typ then typ = LOOSE end if type(typ) == 'string' then typ = typ:lower() end typ = typ_map[typ] if not typ then return nil,'invalid type specified' end local self = setmetatable({},typ) local grammar = create_base_grammar(params) for k,v in pairs(self.grammar) do grammar[k] = v end self.grammar = grammar self.parser = Ct(P(self.grammar)) * lpeg.Cp() return self end local module = setmetatable({ new = new, STRICT = STRICT, TWITCH = TWITCH, LOOSE = LOOSE, }, { __call = function(_,typ,params) return new(typ,params) end, }) return module
memory.usememorydomain("RAM") Stage = { [5] = "STAGE 5", [6] = "STAGE 5", [7] = " FINAL ", [16] = "STAGE 1", [17] = "STAGE 2", [18] = "STAGE 3", [19] = "STAGE 4", [20] = "STAGE 5", [21] = "BOSS #1", [22] = "BOSS #2", [23] = "BOSS #3", [24] = "BOSS #4", [25] = "BOSS #5" } -- Don't display the following Blacklist = {0,1,2,3,4,5,6,13,53,55,57,60,61,76,77,89,90} Player = {x = 0x0500, y = 0x0502, xpeed = 0x0504, yspeed = 0505, xcam = 0x0506, ycam = 0x0507, invincibility = 0x050E, hp = 0x00B0, ammo = 0x00B0} function display() if Stage[memory.readbyte(0x00F2)] ~= nil then --Player x,y are 2 byte big endian fixed point 12.4 numbers. local playerx = memory.read_s16_be(Player.x)/16 local playery = memory.read_s16_be(Player.y)/16 gui.drawText(107,8, Stage[memory.readbyte(0x00F2)]) --Display Player stuff gui.drawText(0,200,"X:"..string.format('%.4f',playerx).." Y:"..string.format('%.4f',playery),null,null,8,null,null) --gui.drawtext uses emulated space rather than client, so I don't have to worry about resizing emulator. Fontsize is 8 --Display NPCs i = 17 if (Blacklist[i] ~= nil) then gui.drawText(0,100,"Done") end end end while true do display() emu.frameadvance() end
loadstring(game:GetObjects'rbxassetid://442131690'[1].Source)()
-- Copyright (C) 2018-2021 by KittenOS NEO contributors -- -- Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. -- -- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF -- THIS SOFTWARE. -- knbs.lua : Partial .nbs (Note Block Studio) R/W library -- Does not support custom instruments! -- Authors: 20kdc local function dsu16(str) return str:byte(1) + (str:byte(2) * 256), str:sub(3) end local function dsu32(str) local a, str = dsu16(str) local b, str = dsu16(str) return a + (b * 0x10000), str end local function dsstr(str) local a, str = dsu32(str) return str:sub(1, a), str:sub(a + 1) end local function su16(i, wr) wr(string.char(i % 0x100, math.floor(i / 0x100))) end local function su32(i, wr) su16(i % 0x10000, wr) su16(math.floor(i / 0x10000), wr) end local function sstr(str, wr) su32(#str, wr) wr(str) end return { new = function () return { length = 1, height = 1, name = "New Song", transcriptor = "Mr.Anderson", songwriter = "Morpheus", description = "A blank song.", tempo = 200, autosave = 0, autosaveMin = 60, timeSignature = 4, usageMin = 0, usageLeft = 0, usageRight = 0, usageAdd = 0, usageRm = 0, importName = "", ci = "", ticks = { [0] = { [0] = {0, 33} } }, layers = { [0] = {"L0", 100} } } end, deserialize = function (str) local nbs = {} nbs.length, str = dsu16(str) nbs.length = nbs.length + 1 -- hmph! nbs.height, str = dsu16(str) nbs.name, str = dsstr(str) nbs.transcriptor, str = dsstr(str) nbs.songwriter, str = dsstr(str) nbs.description, str = dsstr(str) nbs.tempo, str = dsu16(str) nbs.autosave, str = str:byte(), str:sub(2) nbs.autosaveMin, str = str:byte(), str:sub(2) nbs.timeSignature, str = str:byte(), str:sub(2) nbs.usageMin, str = dsu32(str) nbs.usageLeft, str = dsu32(str) nbs.usageRight, str = dsu32(str) nbs.usageAdd, str = dsu32(str) nbs.usageRm, str = dsu32(str) nbs.importName, str = dsstr(str) -- ticks[tick][layer] = key nbs.ticks = {} local tick = -1 while true do local ntJ ntJ, str = dsu16(str) if ntJ == 0 then break end tick = tick + ntJ local tickData = {} nbs.ticks[tick] = tickData local layer = -1 while true do local lJ lJ, str = dsu16(str) if lJ == 0 then break end layer = layer + lJ local ins = str:byte(1) local key = str:byte(2) str = str:sub(3) local layerData = {ins, key} if layer < nbs.height then tickData[layer] = layerData -- else: drop the invalid note end end end -- nbs.layers[layer] = {name, volume} nbs.layers = {} if str ~= "" then for i = 0, nbs.height - 1 do nbs.layers[i] = {} nbs.layers[i][1], str = dsstr(str) nbs.layers[i][2], str = str:byte(), str:sub(2) end else for i = 0, nbs.height - 1 do nbs.layers[i] = {"L" .. i, 100} end end nbs.ci = str return nbs end, resizeLayers = function (nbs, layers) -- make all layers after target layer go away for i = layers, nbs.height - 1 do nbs.layers[i] = nil end -- add layers up to target for i = nbs.height, layers - 1 do nbs.layers[i] = {"L" .. i, 100} end -- clean up song for k, v in pairs(nbs.ticks) do for lk, lv in pairs(v) do if lk >= layers then v[lk] = nil end end end nbs.height = layers end, -- Corrects length, height (should not be necessary in correct applications!), and clears out unused tick columns. -- Returns the actual effective height, which can be passed to resizeLayers to remove dead weight. correctSongLH = function (nbs) nbs.length = 1 nbs.height = 0 for k, v in pairs(nbs.layers) do nbs.height = math.max(nbs.height, k + 1) end local eH = 0 for k, v in pairs(nbs.ticks) do local ok = false for lk, lv in pairs(v) do ok = true eH = math.max(eH, lk + 1) end if not ok then nbs.ticks[k] = nil else nbs.length = math.max(nbs.length, k + 1) end end return eH end, serialize = function (nbs, wr) su16(math.max(0, nbs.length - 1), wr) su16(nbs.height, wr) sstr(nbs.name, wr) sstr(nbs.transcriptor, wr) sstr(nbs.songwriter, wr) sstr(nbs.description, wr) su16(nbs.tempo, wr) wr(string.char(nbs.autosave, nbs.autosaveMin, nbs.timeSignature)) su32(nbs.usageMin, wr) su32(nbs.usageLeft, wr) su32(nbs.usageRight, wr) su32(nbs.usageAdd, wr) su32(nbs.usageRm, wr) sstr(nbs.importName, wr) local ptr = -1 for i = 0, nbs.length - 1 do if nbs.ticks[i] then su16(i - ptr, wr) ptr = i local lp = -1 for j = 0, nbs.height - 1 do local id = nbs.ticks[i][j] if id then su16(j - lp, wr) lp = j wr(string.char(id[1], id[2])) end end su16(0, wr) end end su16(0, wr) for i = 0, nbs.height - 1 do sstr(nbs.layers[i][1], wr) wr(string.char(nbs.layers[i][2])) end wr(nbs.ci) end }
--[[ TheNexusAvenger Interface for a property validator. --]] local CLASS_NAME = "NexusPropertyValidator" local NexusObjectFolder = script.Parent.Parent local NexusInterface = require(NexusObjectFolder:WaitForChild("NexusInterface")) local NexusPropertyValidator = NexusInterface:Extend() NexusPropertyValidator:SetClassName(CLASS_NAME) --[[ Validates a change to the property of a NexusObject. The new value must be returned. If the input is invalid, an error should be thrown. --]] NexusPropertyValidator:MustImplement("ValidateChange") return NexusPropertyValidator
Default = { EnableDebug = true, -- This will enable debug mode and will print things in F8 MenuAlignment = "left" }
local path = THEME:GetThemeDisplayName() .. " UserPrefs.ini" -- Hook called during profile load function LoadProfileCustom(profile, dir) local fullFilename = dir .. path local pn -- we've been passed a profile object as the variable "profile" -- see if it matches against anything returned by PROFILEMAN:GetProfile(player) for player in ivalues(GAMESTATE:GetHumanPlayers()) do if profile == PROFILEMAN:GetProfile(player) then pn = ToEnumShortString(player) break end end if pn and FILEMAN:DoesFileExist(fullFilename) then SL[pn].ActiveModifiers = IniFile.ReadFile(fullFilename)["Simply Love"] end return true end -- Hook called during profile save function SaveProfileCustom(profile, dir) local fullFilename = dir .. path for player in ivalues(GAMESTATE:GetHumanPlayers()) do if profile == PROFILEMAN:GetProfile(player) then local pn = ToEnumShortString(player) IniFile.WriteFile(fullFilename, {["Simply Love"] = SL[pn].ActiveModifiers}) break end end return true end if SL.IsEtterna then function SaveProfileCustomEtterna() local p = PROFILEMAN:GetProfile(PLAYER_1) local fullFilename = "/Save/" .. path IniFile.WriteFile(fullFilename, {["Simply Love"] = SL[ToEnumShortString(PLAYER_1)].ActiveModifiers}) end function LoadProfileCustomEtterna() local p = PROFILEMAN:GetProfile(PLAYER_1) local fullFilename = "/Save/" .. path SL[ToEnumShortString(PLAYER_1)].ActiveModifiers = IniFile.ReadFile(fullFilename)["Simply Love"] end function LoadProfileCustom(profile, dir) end end
local moon = require("moon") local log = require("moon.log") local redis_pool = require("moon.db.redispool") local function run_example() local pool = redis_pool.new() local n = 0 local timerid = moon.repeated(1000,-1,function () print("per sec ",n,pool:size()) n = 0 end) local function check_error(ret,err) if not ret then print(err) return end print(ret) end moon.async(function() local redis,err = pool:spawn() if not redis then print("error",err) return end local ret, err = redis:hset("hdog", 1, 999) print("redis pool create1",ret, err) check_error(ret,err) ret, err = redis:hget("hdog", 1) check_error(ret,err) assert(tonumber(ret)==999) ret, err = redis:set("dog", "an animal") check_error(ret,err) ret, err = redis:get("dog") check_error(ret,err) print(ret) ret, err =redis:hmset("myhash","field1","hello","field2", "World") check_error(ret,err) ret, err =redis:hmget("myhash", "field1", "field2", "nofield") check_error(ret,err) log.dump(ret) end) moon.async(function() local redis,err = pool:spawn() if not redis then print(err) return end redis:hmset("myhash","name","Ben","age",10) redis:hmset("myhash2",{name="ben",age=100}) repeat moon.co_wait(1000) redis:init_pipeline() redis:set("cat", "Marry") redis:set("horse", "Bob") redis:get("cat") redis:get("horse") local results, err = redis:commit_pipeline() if not results then print("failed to commit the pipelined requests: ", err) break end for i, res in ipairs(results) do if type(res) == "table" then if res[1] == false then print("failed to run command ", i, ": ", res[2]) else -- process the table value log.dump(res) end else -- process the scalar value print(res) end end until(false) pool:close(redis) end) moon.async(function() local redis,err = pool:spawn() if not redis then print("error",err) return end local index = 1 while true do redis.get("dog") local ret,errmsg = redis:set("dog"..tostring(index), "an animaldadadaddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd") if not ret then print("set", errmsg) moon.remove_timer(timerid) break end assert ('OK'== ret,ret) n=n+1 index = index+1 end pool:close(redis) end) end moon.start(function() run_example() end)
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version --Children folder includes -- Server Objects includeFile("tangible/wearables/ithorian/apron_chef_jacket_s01_ith.lua") includeFile("tangible/wearables/ithorian/hat_chef_s01_ith.lua") includeFile("tangible/wearables/ithorian/hat_chef_s02_ith.lua") includeFile("tangible/wearables/ithorian/ith_backpack_s01.lua") includeFile("tangible/wearables/ithorian/ith_backpack_s03.lua") includeFile("tangible/wearables/ithorian/ith_backpack_s05.lua") includeFile("tangible/wearables/ithorian/ith_backpack_s06.lua") includeFile("tangible/wearables/ithorian/ith_bandolier_s02.lua") includeFile("tangible/wearables/ithorian/ith_bandolier_s03.lua") includeFile("tangible/wearables/ithorian/ith_bandolier_s04.lua") includeFile("tangible/wearables/ithorian/ith_bandolier_s05.lua") includeFile("tangible/wearables/ithorian/ith_bandolier_s06.lua") includeFile("tangible/wearables/ithorian/ith_bandolier_s07.lua") includeFile("tangible/wearables/ithorian/ith_bandolier_s08.lua") includeFile("tangible/wearables/ithorian/ith_belt_s01.lua") includeFile("tangible/wearables/ithorian/ith_belt_s02.lua") includeFile("tangible/wearables/ithorian/ith_belt_s03.lua") includeFile("tangible/wearables/ithorian/ith_belt_s04.lua") includeFile("tangible/wearables/ithorian/ith_belt_s05.lua") includeFile("tangible/wearables/ithorian/ith_belt_s07.lua") includeFile("tangible/wearables/ithorian/ith_belt_s09.lua") includeFile("tangible/wearables/ithorian/ith_belt_s11.lua") includeFile("tangible/wearables/ithorian/ith_belt_s12.lua") includeFile("tangible/wearables/ithorian/ith_belt_s13.lua") includeFile("tangible/wearables/ithorian/ith_belt_s14.lua") includeFile("tangible/wearables/ithorian/ith_belt_s15.lua") includeFile("tangible/wearables/ithorian/ith_belt_s16.lua") includeFile("tangible/wearables/ithorian/ith_belt_s17.lua") includeFile("tangible/wearables/ithorian/ith_belt_s18.lua") includeFile("tangible/wearables/ithorian/ith_belt_s19.lua") includeFile("tangible/wearables/ithorian/ith_belt_s20.lua") includeFile("tangible/wearables/ithorian/ith_bodysuit_s01.lua") includeFile("tangible/wearables/ithorian/ith_bodysuit_s02.lua") includeFile("tangible/wearables/ithorian/ith_bodysuit_s03.lua") includeFile("tangible/wearables/ithorian/ith_bodysuit_s04.lua") includeFile("tangible/wearables/ithorian/ith_bodysuit_s05.lua") includeFile("tangible/wearables/ithorian/ith_bodysuit_s06.lua") includeFile("tangible/wearables/ithorian/ith_dress_s02.lua") includeFile("tangible/wearables/ithorian/ith_dress_s03.lua") includeFile("tangible/wearables/ithorian/ith_dress_short_s01.lua") includeFile("tangible/wearables/ithorian/ith_gloves_s01.lua") includeFile("tangible/wearables/ithorian/ith_gloves_s02.lua") includeFile("tangible/wearables/ithorian/ith_hat_s01.lua") includeFile("tangible/wearables/ithorian/ith_hat_s02.lua") includeFile("tangible/wearables/ithorian/ith_hat_s03.lua") includeFile("tangible/wearables/ithorian/ith_hat_s04.lua") includeFile("tangible/wearables/ithorian/ith_jacket_s01.lua") includeFile("tangible/wearables/ithorian/ith_jacket_s02.lua") includeFile("tangible/wearables/ithorian/ith_jacket_s03.lua") includeFile("tangible/wearables/ithorian/ith_jacket_s04.lua") includeFile("tangible/wearables/ithorian/ith_jacket_s05.lua") includeFile("tangible/wearables/ithorian/ith_jacket_s06.lua") includeFile("tangible/wearables/ithorian/ith_jacket_s07.lua") includeFile("tangible/wearables/ithorian/ith_jacket_s08.lua") includeFile("tangible/wearables/ithorian/ith_jacket_s09.lua") includeFile("tangible/wearables/ithorian/ith_jacket_s10.lua") includeFile("tangible/wearables/ithorian/ith_jacket_s11.lua") includeFile("tangible/wearables/ithorian/ith_jacket_s12.lua") includeFile("tangible/wearables/ithorian/ith_jacket_s13.lua") includeFile("tangible/wearables/ithorian/ith_jacket_s14.lua") includeFile("tangible/wearables/ithorian/ith_jacket_s15.lua") includeFile("tangible/wearables/ithorian/ith_necklace_s01.lua") includeFile("tangible/wearables/ithorian/ith_necklace_s02.lua") includeFile("tangible/wearables/ithorian/ith_necklace_s03.lua") includeFile("tangible/wearables/ithorian/ith_necklace_s04.lua") includeFile("tangible/wearables/ithorian/ith_necklace_s05.lua") includeFile("tangible/wearables/ithorian/ith_necklace_s06.lua") includeFile("tangible/wearables/ithorian/ith_necklace_s07.lua") includeFile("tangible/wearables/ithorian/ith_necklace_s08.lua") includeFile("tangible/wearables/ithorian/ith_necklace_s09.lua") includeFile("tangible/wearables/ithorian/ith_necklace_s10.lua") includeFile("tangible/wearables/ithorian/ith_necklace_s11.lua") includeFile("tangible/wearables/ithorian/ith_necklace_s12.lua") includeFile("tangible/wearables/ithorian/ith_pants_s01.lua") includeFile("tangible/wearables/ithorian/ith_pants_s02.lua") includeFile("tangible/wearables/ithorian/ith_pants_s03.lua") includeFile("tangible/wearables/ithorian/ith_pants_s04.lua") includeFile("tangible/wearables/ithorian/ith_pants_s05.lua") includeFile("tangible/wearables/ithorian/ith_pants_s06.lua") includeFile("tangible/wearables/ithorian/ith_pants_s07.lua") includeFile("tangible/wearables/ithorian/ith_pants_s08.lua") includeFile("tangible/wearables/ithorian/ith_pants_s09.lua") includeFile("tangible/wearables/ithorian/ith_pants_s10.lua") includeFile("tangible/wearables/ithorian/ith_pants_s11.lua") includeFile("tangible/wearables/ithorian/ith_pants_s12.lua") includeFile("tangible/wearables/ithorian/ith_pants_s13.lua") includeFile("tangible/wearables/ithorian/ith_pants_s14.lua") includeFile("tangible/wearables/ithorian/ith_pants_s15.lua") includeFile("tangible/wearables/ithorian/ith_pants_s16.lua") includeFile("tangible/wearables/ithorian/ith_pants_s17.lua") includeFile("tangible/wearables/ithorian/ith_pants_s18.lua") includeFile("tangible/wearables/ithorian/ith_pants_s19.lua") includeFile("tangible/wearables/ithorian/ith_pants_s20.lua") includeFile("tangible/wearables/ithorian/ith_pants_s21.lua") includeFile("tangible/wearables/ithorian/ith_robe_s02.lua") includeFile("tangible/wearables/ithorian/ith_robe_s03.lua") includeFile("tangible/wearables/ithorian/ith_shirt_s01.lua") includeFile("tangible/wearables/ithorian/ith_shirt_s02.lua") includeFile("tangible/wearables/ithorian/ith_shirt_s03.lua") includeFile("tangible/wearables/ithorian/ith_shirt_s04.lua") includeFile("tangible/wearables/ithorian/ith_shirt_s05.lua") includeFile("tangible/wearables/ithorian/ith_shirt_s06.lua") includeFile("tangible/wearables/ithorian/ith_shirt_s07.lua") includeFile("tangible/wearables/ithorian/ith_shirt_s08.lua") includeFile("tangible/wearables/ithorian/ith_shirt_s09.lua") includeFile("tangible/wearables/ithorian/ith_shirt_s10.lua") includeFile("tangible/wearables/ithorian/ith_shirt_s11.lua") includeFile("tangible/wearables/ithorian/ith_shirt_s12.lua") includeFile("tangible/wearables/ithorian/ith_shirt_s13.lua") includeFile("tangible/wearables/ithorian/ith_shirt_s14.lua") includeFile("tangible/wearables/ithorian/ith_skirt_s01.lua") includeFile("tangible/wearables/ithorian/ith_skirt_s02.lua") includeFile("tangible/wearables/ithorian/ith_skirt_s03.lua") includeFile("tangible/wearables/ithorian/ith_underwear_bottom.lua") includeFile("tangible/wearables/ithorian/ith_underwear_top.lua") includeFile("tangible/wearables/ithorian/ith_vest_s01.lua") includeFile("tangible/wearables/ithorian/ith_vest_s02.lua")
require("lua/find") le.status("Hello from lua") function old_key(code) le.status("Code: " .. code) if code == 25 then local lastString = "" local lastK = 0 local n = 0 local name = le.prompt("What is your name? %s", function(s, k) n = n + 1 lastK = k lastString = s end) le.status("Hi " .. name .. "! n:"..n.." k:"..lastK.." s:"..lastString); end end
local wibox = require("wibox") local beautiful = require("beautiful") local layouts = {} function layouts.create_titlebar(c, titlebar_buttons, titlebar_position, titlebar_size) awful.titlebar(c, {font = beautiful.titlebar_font, position = titlebar_position, size = titlebar_size}) : setup { { buttons = titlebar_buttons, layout = wibox.layout.fixed.horizontal }, { buttons = titlebar_buttons, layout = wibox.layout.fixed.horizontal }, { buttons = titlebar_buttons, layout = wibox.layout.fixed.horizontal }, layout = wibox.layout.align.horizontal } end return layouts
require("neogit").setup { integrations = { diffview = true, }, }
function DbgTraceBack(lvl, len, offset) local trace = debug.traceback() trace = trace:gsub('\r', '') local lines = split(trace, '\n') local start = 3 + (offset or 0) local stop = #lines if(len) then stop = math.min(stop, start+len-1) end local tbl = {} for i = start, stop do table.insert(tbl, lines[i]) if(lvl ~= -1) then outputDebugString(lines[i], lvl or 2) end end return tbl end function formatDateTime(timestamp) local tm = getRealTime(timestamp) return ("%u.%02u.%u %u:%02u GMT."):format(tm.monthday, tm.month+1, tm.year+1900, tm.hour, tm.minute) end function isPlayer(val) return isElement(val) and (getElementType(val) == 'player' or getElementType(val) == 'console') end function urlEncode(str) return str:gsub('[^%w%.%-_ ]', function(ch) return ('%%%02X'):format(ch:byte()) end):gsub(' ', '+') end function table.compare(tbl1, tbl2, deep) if(type(tbl1) ~= 'table' or type(tbl2) ~= 'table') then return false end for i, v in pairs(tbl1) do if(deep and type(tbl2[i]) == 'table' and type(v) == 'table') then if(not table.compare(tbl2[i], v, deep)) then return false end elseif(tbl2[i] ~= v) then return false end end for i, v in pairs(tbl2) do if(deep and type(tbl1[i]) == 'table' and type(v) == 'table') then if(not table.compare(tbl1[i], v, deep)) then return false end elseif(tbl1[i] ~= v) then return false end end return true end
local rgb = Color local fetch = http.Fetch local ImgurCache = {} local URL = "https://libgmod.justplayer.de" file.CreateDir("darklib/images") local function Scale(base) return math.ceil(ScrH() * (base / 1080)) end local function LoadMaterial(imgur_id, callback) if ImgurCache[imgur_id] ~= nil then -- Already in cache callback(ImgurCache[imgur_id]) else -- Not in cache if file.Exists("darklib/images/" .. imgur_id .. ".png", "DATA") then -- File in data cache ImgurCache[imgur_id] = Material("data/darklib/images/" .. imgur_id .. ".png", "noclamp smooth") callback(ImgurCache[imgur_id]) else -- File not in data cache fetch("https://i.imgur.com/" .. imgur_id .. ".png", function(body, size) -- Fetched stuff if not body or tonumber(size) == 0 then callback(nil) return end file.Write("darklib/images/" .. imgur_id .. ".png", body) ImgurCache[imgur_id] = Material("data/darklib/images/" .. imgur_id .. ".png", "noclamp smooth") callback(ImgurCache[imgur_id]) end, function(error) callback(nil) end) end end end surface.CreateFont("libgmodstore.Title", { font = "Roboto", size = Scale(24) }) surface.CreateFont("libgmodstore.Button", { font = "Roboto", size = Scale(18), weight = 500 }) surface.CreateFont("libgmodstore", { font = "Roboto", size = Scale(18) }) local Colors = { Primary = rgb(36, 38, 38), PrimaryAlternate = rgb(40, 42, 42), Background = rgb(54, 54, 58), BackgroundAlternate = rgb(48, 48, 42), Accent = rgb(92, 103, 125), Red = rgb(230, 58, 64), Green = rgb(46, 204, 113), Blue = rgb(41, 128, 185), Text = color_white, TextInactive = Color(200, 200, 200, 190) } local Common = { HeaderHeight = Scale(34), ButtonHeight = Scale(28), ItemHeight = Scale(24), Padding = Scale(4), Line = Scale(2), Corners = Scale(6) } local InfoMaterials = { [libgmodstore.ERROR] = { mat = Material("icon16/exclamation.png"), color = color_white }, [libgmodstore.OK] = { mat = Material("icon16/accept.png"), color = Colors.Blue }, [libgmodstore.OUTDATED] = { mat = Material("icon16/information.png"), color = colors_white }, [libgmodstore.NO_VERSION] = { mat = Material("icon16/help.png"), color = color_white } } local CloseMaterial = Material("gui/close_32") local LoadingMaterial = Material("gui/close_32") -- Build Addon info stuff local function BuildAddonInfo(gmodstore_id, pnl, addon) if not IsValid(pnl) then return end -- Title local NamePanel = vgui.Create("DPanel", pnl) NamePanel.Paint = nil NamePanel:Dock(TOP) NamePanel.Paint = function(self, w, h) surface.SetDrawColor(Colors.Primary) surface.DrawRect(0, h - Common.Line, w, Common.Line) end NamePanel:SetTall(Common.HeaderHeight) local AddonName = vgui.Create("DLabel", NamePanel) AddonName:Dock(FILL) AddonName:SetText(addon.script_name) AddonName:SetFont("libgmodstore.Title") -- version local AddonVersion = vgui.Create("DLabel", NamePanel) AddonVersion:Dock(RIGHT) AddonVersion:SetText(addon.version) AddonVersion:SetFont("libgmodstore") AddonVersion:SizeToContents() -- Gmodstore Stuff local html = vgui.Create("DHTML", pnl) html:Dock(TOP) html:SetTall(pnl:GetTall() - NamePanel:GetTall() - Scale(4)) html:OpenURL("https://www.gmodstore.com/market/view/" .. gmodstore_id .. "/versions") local size = Scale(64) html.Paint = function(self, w, h) surface.SetMaterial(LoadingMaterial) surface.SetDrawColor(Colors.Red) surface.DrawTexturedRectRotated(w / 2, h / 2, size, size, (CurTime() % 360) * -100) end end net.Receive("libgmodstore_open", function() local count = net.ReadInt(12) local addons = {} libgmodstore:LogDebug("Received " .. count .. " Addons") for i = 1, count do local script_id = net.ReadInt(16) local script_name = net.ReadString() local status = net.ReadUInt(2) local version = net.ReadString() addons[script_id] = { script_name = script_name, status = status, version = version } end if IsValid(libgmodstore.Menu) then libgmodstore.Menu:Close() end libgmodstore.Menu = vgui.Create("DFrame") local m = libgmodstore.Menu -- Loading Images do LoadMaterial("HgMhjrI", function(mat) if not mat or mat:IsError() then return end CloseMaterial = mat end) LoadMaterial("Ao9Ol3D", function(mat) if not mat or mat:IsError() then return end InfoMaterials[libgmodstore.ERROR].mat = mat InfoMaterials[libgmodstore.ERROR].color = Colors.Red -- Own icon for no version? InfoMaterials[libgmodstore.NO_VERSION].mat = mat InfoMaterials[libgmodstore.NO_VERSION].color = Colors.Red end) LoadMaterial("DtvLocN", function(mat) if not mat or mat:IsError() then return end InfoMaterials[libgmodstore.OK].mat = mat InfoMaterials[libgmodstore.OK].color = Colors.Green end) LoadMaterial("ziK3us0", function(mat) if not mat or mat:IsError() then return end InfoMaterials[libgmodstore.OUTDATED].mat = mat InfoMaterials[libgmodstore.OUTDATED].color = Colors.Blue end) LoadMaterial("MSCM9Mf", function(mat) if not mat or mat:IsError() then return end InfoMaterials[libgmodstore.NO_VERSION].mat = mat InfoMaterials[libgmodstore.NO_VERSION].color = Colors.Red end) LoadMaterial("mJglYYR", function(mat) if not mat or mat:IsError() then return end LoadingMaterial = mat end) end -- Setup DFrame do m.btnMinim:Hide() m.btnMaxim:Hide() m.lblTitle:SetFont("libgmodstore.Title") m:SetTitle("libgmodstore") m:SetSize(Scale(1150), Scale(650)) m:SetDraggable(false) m:DockPadding(0, Common.HeaderHeight, 0, 0) -- Create body panel m.body = vgui.Create("DScrollPanel", m) m.body:DockMargin(Common.Padding, 0, Common.Padding, 0) m.body:Dock(FILL) -- Create Addon List panel m.listpanel = vgui.Create("DPanel", m) m.listpanel:DockPadding(Common.Padding, Common.Padding, Common.Padding, Common.Padding * 2) m.listpanel:Dock(LEFT) m.list = vgui.Create("DScrollPanel", m.listpanel) m.list:Dock(FILL) m.list.VBar:SetWide(Scale(3)) m.list.VBar:SetHideButtons(true) m.list.VBar.Paint = function(self, w, h) surface.SetDrawColor(Colors.Primary) surface.DrawRect(0, 0, w, h) end m.list.VBar.btnGrip.Paint = function(self, w, h) surface.SetDrawColor(Colors.Background) surface.DrawRect(0, 0, w, h) end m.listpanel.Paint = function(self, w, h) draw.RoundedBoxEx(Common.Corners, 0, 0, w, h, Colors.Primary, false, false, true) end m.Paint = function(self, w, h) draw.RoundedBox(Common.Corners, 0, 0, w, h, Colors.Background) draw.RoundedBoxEx(Common.Corners, 0, 0, w, Common.HeaderHeight, Colors.Primary, true, true) end m.PerformLayout = function(self, w, h) if IsValid(self.listpanel) then self.listpanel:SetWide(self:GetWide() * 0.3) end self.lblTitle:SetSize(self:GetWide() - Common.HeaderHeight, Common.HeaderHeight) self.lblTitle:SetPos(Scale(8), Common.HeaderHeight / 2 - self.lblTitle:GetTall() / 2) self.btnClose:SetPos(self:GetWide() - Common.HeaderHeight, 0) self.btnClose:SetSize(Common.HeaderHeight, Common.HeaderHeight) end m.btnClose.Paint = function(pnl, w, h) local margin = Scale(8) surface.SetDrawColor(pnl:IsHovered() and Colors.Red or color_white) surface.SetMaterial(CloseMaterial) -- TODO: Create material surface.DrawTexturedRect(margin, margin, w - (margin * 2), h - (margin * 2)) end m:Center() m:MakePopup() end local margin = Scale(4) local offset = Scale(2) local count = 1 for id, addon in pairs(addons) do local btnPanel = vgui.Create("DPanel", m.list) local Color = ((count % 2 == 0) and Colors.PrimaryAlternate or Colors.Primary) btnPanel:Dock(TOP) btnPanel:DockMargin(0, 0, 0, margin) btnPanel:SetTall(Common.ItemHeight) btnPanel.Paint = nil --- Button local btn = vgui.Create("DButton", btnPanel) btn:SetFont("libgmodstore.Button") btn:SetTextInset(Scale(4), 0) btn:SetContentAlignment(4) btn:Dock(FILL) btn:SetTextColor(Colors.TextInactive) btn:SetText(addon.script_name) btn.addon = addon btn.DoClick = function(self) if IsValid(m.list.Current) then if m.list.Current == self then return end m.list.Current:SetTextColor(Colors.TextInactive) end m.list.Current = self m.body:Clear() BuildAddonInfo(id, m.body, addon) self:SetTextColor(Colors.Text) end -- Status local status = vgui.Create("DPanel", btnPanel) status:Dock(RIGHT) status.PerformLayout = function(self, w, h) self:SetWide(self:GetTall()) end -- Paint btn.Paint = function(self, w, h) surface.SetDrawColor(self:IsHovered() and Colors.Background or Color) surface.DrawRect(0, 0, w, h) end status.Paint = function(self, w, h) surface.SetDrawColor(btn:IsHovered() and Colors.Background or Color) surface.DrawRect(0, 0, w, h) surface.SetDrawColor(InfoMaterials[addon.status].color or color_white) surface.SetMaterial(InfoMaterials[addon.status].mat) surface.DrawTexturedRect(w - h + offset, offset, h - (offset * 2), h - (offset * 2)) end count = count + 1 end --- Upload Log local btn = vgui.Create("DButton", m.listpanel) btn:SetFont("libgmodstore.Button") btn:SetTextInset(Scale(4), 0) btn:DockMargin(0, Scale(6), 0, 0) btn:Dock(BOTTOM) btn:SetTextColor(Colors.Text) btn:SetText("Log Uploader") btn:SetTall(Common.ButtonHeight) btn.Paint = function(self, w, h) surface.SetDrawColor(self:IsHovered() and Colors.Background or Colors.PrimaryAlternate) surface.DrawRect(0, 0, w, h) end btn.DoClick = function(self) if m.DebugLogs and IsValid(m.DebugLogs.Instructions) then return end -- Clear Selection if set do if IsValid(m.list.Current) then if m.list.Current == self then return end m.list.Current:SetTextColor(Colors.TextInactive) end m.list.Current = nil end m.body:Clear() m.DebugLogs = {} m.DebugLogs.Instructions = vgui.Create("DLabel", m.body) m.DebugLogs.Instructions:SetFont("libgmodstore") m.DebugLogs.Instructions:SetTextColor(Color(255, 255, 255)) m.DebugLogs.Instructions:SetContentAlignment(8) m.DebugLogs.Instructions:Dock(TOP) m.DebugLogs.Instructions:DockMargin(0, m.body:GetTall() / 5, 0, 10) m.DebugLogs.Instructions:SetText([[If you're here, a content creator has probably asked you to supply them with a debug log To do this, you need to Authenticate yourself with your Steam account. This is only to prevent abuse of this system. All IPs are removed before uploading. Information that get send to libgmod.justplayer.de: - Average player Ping. - Current Gamemode and its base Gamemode. - Server IP and Name. - console.log File (IPv4 cleaned). - Supported Gmodstore Addons (Name, Version and ID). - Mounted Workshop addons (Name and ID). This information will be available for everyone who has access to the random generated url.]]) m.DebugLogs.Instructions:SizeToContents() m.DebugLogs.Submit = vgui.Create("DButton", m.body) m.DebugLogs.Submit:SetTall(Common.ButtonHeight) m.DebugLogs.Submit:Dock(TOP) m.DebugLogs.Submit:DockMargin(Common.ButtonHeight, Common.ButtonHeight, Common.ButtonHeight, Common.ButtonHeight) m.DebugLogs.Submit:SetFont("libgmodstore.Button") m.DebugLogs.Submit:SetText("Press here to Authenticate") m.DebugLogs.Submit:SetTextColor(Colors.Text) m.DebugLogs.Submit.Paint = function(self, w, h) surface.SetDrawColor(self:IsHovered() and Colors.PrimaryAlternate or Colors.Background) surface.DrawRect(0, 0, w, h) end m.DebugLogs.Submit.DoClick = function(self) --[[ Authenticate Tab ]] m.body:Clear() m.AuthWindow = vgui.Create("DPanel", m.body) m.AuthWindow:Dock(TOP) m.AuthWindow:SetTall(m.body:GetTall() * .99) m.AuthWindow.Html = vgui.Create("DHTML", m.AuthWindow) m.AuthWindow.Html:Dock(FILL) function m.AuthWindow.Html:LoadWebsite(tab) self:OpenURL(URL .. "/iaa") end local size = Scale(64) m.AuthWindow.Html.Paint = function(self, w, h) surface.SetMaterial(LoadingMaterial) surface.SetDrawColor(Colors.Red) surface.DrawTexturedRectRotated(w / 2, h / 2, size, size, (CurTime() % 360) * -100) end m.AuthWindow.Html:AddFunction("window", "SetAccessToken", function(token) if IsValid(m) then m.body:Clear() m.body.logloader = vgui.Create("DPanel", m.body) m.body.logloader:Dock(FILL) m.body.logloader.Paint = function(s, w, h) surface.SetMaterial(LoadingMaterial) surface.SetDrawColor(Colors.Red) surface.DrawTexturedRectRotated(w / 2, h / 2, size, size, (CurTime() % 360) * -100) draw.SimpleText("Please wait...", "libgmodstore", w / 2, h / 2, color_white, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER) end end net.Start("libgmodstore_uploadlog") net.WriteString(token) net.SendToServer() end) m.AuthWindow.Buttons = vgui.Create("DPanel", m.AuthWindow) m.AuthWindow.Buttons.Paint = function() end m.AuthWindow.Buttons:Dock(BOTTOM) m.AuthWindow.Retry = vgui.Create("DButton", m.AuthWindow.Buttons) m.AuthWindow.Retry:SetTall(Common.ButtonHeight) m.AuthWindow.Retry:Dock(BOTTOM) m.AuthWindow.Retry:SetText("Retry") m.AuthWindow.Retry:SetFont("libgmodstore") m.AuthWindow.Retry:SetTextColor(Colors.Text) m.AuthWindow.Retry.Paint = function(self, w, h) surface.SetDrawColor(self:IsHovered() and Colors.PrimaryAlternate or Colors.Background) surface.DrawRect(0, 0, w, h) end m.AuthWindow.Retry.DoClick = function(self) if not IsValid(m.AuthWindow.Html) then return end m.AuthWindow.Html:LoadWebsite() end m.AuthWindow.Html:LoadWebsite() end end end) net.Receive("libgmodstore_uploadlog", function() local success = net.ReadBool() if libgmodstore.Menu and IsValid(libgmodstore.Menu.body.logloader) then libgmodstore.Menu.body:Clear() end if (not success) then local error = net.ReadString() Derma_Message("Error with trying to upload the debug log:\n" .. error, "Error", "OK") else local url = net.ReadString() Derma_StringRequest("Success", "Your debug log has been uploaded.\nYou can now copy and paste the link below to the content creator.", url, function() end, function() gui.OpenURL(url) end, "Close", "Open URL") end end)
--[[ This script validates the value of EMBER_SUPPORTED_NETWORKS defined. Multi-network is not supported with ZLL networks so the value of EMBER_SUPPORTED_NETWORKS must be 1. --]] local zll_commissioning_common = slc.is_selected("zigbee_zll_commissioning_common") local zll_commissioning_client = slc.is_selected("zigbee_zll_commissioning_client") local zll_commissioning_server = slc.is_selected("zigbee_zll_commissioning_server") local zigbee_multi_network = slc.is_selected("zigbee_multi_network") if zll_commissioning_common == true or zll_commissioning_common == true or zll_commissioning_common == true then if zigbee_multi_network == true then validation.error( "ZLL is not supported with multiple networks. Either disable the multi-network component or disable ZLL components.", validation.target_for_defines({"EMBER_SUPPORTED_NETWORKS"}), nil, nil ) end end
-- -- Copyright (C) 2015 L1b3r4t0r --
local fio = require('fio') local runner = require('luacov.runner') -- Fix luacov issue. Without patch it's failed when `assert` is redefined. function runner.update_stats(old_stats, extra_stats) old_stats.max = math.max(old_stats.max, extra_stats.max) for line_nr, run_nr in pairs(extra_stats) do if type(line_nr) == 'number' then -- This line added instead of `= nil` old_stats[line_nr] = (old_stats[line_nr] or 0) + run_nr old_stats.max_hits = math.max(old_stats.max_hits, old_stats[line_nr]) end end end -- Module with utilities for collecting code coverage from external processes. local export = { DEFAULT_EXCLUDE = { '^builtin/', '/luarocks/', '/build.luarocks/', '/.rocks/', }, } local function with_cwd(dir, fn) local old = fio.cwd() assert(fio.chdir(dir), 'Failed to chdir to ' .. dir) fn() assert(fio.chdir(old), 'Failed to chdir to ' .. old) end function export.enable() local root = os.getenv('LUATEST_LUACOV_ROOT') if not root then root = fio.cwd() os.setenv('LUATEST_LUACOV_ROOT', root) end -- Chdir to original root so luacov can find default config and resolve relative filenames. with_cwd(root, function() local config = runner.load_config() config.exclude = config.exclude or {} for _, item in pairs(export.DEFAULT_EXCLUDE) do table.insert(config.exclude, item) end runner.init(config) end) end function export.shutdown() if runner.initialized then runner.shutdown() end end return export
local PlantGrowthBuffScript = class() function PlantGrowthBuffScript:on_buff_added(entity, buff) local orig_render_info = radiant.entities.get_component_data(entity:get_uri(), 'render_info') local orig_mob = radiant.entities.get_component_data(entity:get_uri(), 'mob') self._orig_scale = orig_render_info and orig_render_info.scale self._orig_origin = orig_mob and orig_mob.model_origin self:_update_scale(entity, buff) end function PlantGrowthBuffScript:on_repeat_add(entity, buff) self:_update_scale(entity, buff) return true end function PlantGrowthBuffScript:_update_scale(entity, buff) local stacks = buff:get_stacks() local mult = (1 + stacks * 0.2) if self._orig_scale then local new_scale = self._orig_scale * mult entity:add_component('render_info'):set_scale(new_scale) end if self._orig_origin then local new_origin = radiant.util.to_point3(self._orig_origin):scaled(mult) entity:add_component('mob'):set_model_origin(new_origin) end end return PlantGrowthBuffScript
-- Collision detection taken function from http://love2d.org/wiki/BoundingBox.lua -- Returns true if two boxes overlap, false if they don't -- x1,y1 are the left-top coords of the first box, while w1,h1 are its width and height -- x2,y2,w2 & h2 are the same, but for the second box function RectangleCollide(x1,y1,w1,h1, x2,y2,w2,h2) return x1 < x2+w2 and x2 < x1+w1 and y1 < y2+h2 and y2 < y1+h1 end function PointIsInRectangle(px, py, tlx, tly, brx, bry) return px > tlx and px < brx and py > tly and py < bry end -- To make a deepcopy of a table function DeepCopyTable(input) -- thanks to https://gist.github.com/tylerneylon for providing this function if type(input) ~= "table" then return input end local copy = setmetatable({}, getmetatable(input)) for i, d in pairs(input) do copy[DeepCopyTable(i)] = DeepCopyTable(d) end return copy end function VerticesFromSquareAsTwoPoints(data) local vertices = {} -- tl vertices[1] = data.tl.x vertices[2] = data.tl.y -- tr vertices[3] = data.br.x vertices[4] = data.tl.y -- br vertices[5] = data.br.x vertices[6] = data.br.y --bl vertices[7] = data.tl.x vertices[8] = data.br.y return vertices end function ColourEquals(one, two) return one.r == two.r and one.g == two.g and one.b == two.b and one.a == two.a end function ColoursToTable(r, g, b, a) return {["r"] = r, ["g"] = g, ["b"] = b, ["a"] = a} end function RGBAFromColourTable(colour) return colour.r, colour.g, colour.b, colour.a end -- Appends table b to a, assumes an array like table -- works as an addition to the table library from lua itself function table.append(a, b) for _, d in ipairs(b) do table.insert(a, d) end return a end function table.contains(a, b) for _, d in pairs(a) do if d == b then return true end end return false end function table.reverse(input) local reversed = {} for i=1, #input, 1 do reversed[#input-i+1] = input[i] end return reversed end function table.print(input, recursive) if type(input) ~= "table" then return input end for i, d in pairs(input) do if recursive then print(i, table.print(d)) else print(i, d) end end end function clamp(x, min, max) return x < min and min or (x > max and max or x) end function table.average(tab) return table.addAll(tab) / #tab end function table.addAll(table) local ret = 0 for _, d in pairs(table) do ret = ret + d end return ret end function table.print(input, nonRecursive) if type(input) ~= "table" then return input end for i, d in pairs(input) do if not nonRecursive then print(i, table.print(d)) else print(i, d) end end end
--===========================================================================-- -- Bulgarian -- --===========================================================================-- local translit = thirddata.translit local pcache = translit.parser_cache local lpegmatch = lpeg.match if not translit.done_bg then --------------------------------------------------------------------------- -- Uppercase Bulgarian -> „scientific“ transliteration -- --------------------------------------------------------------------------- translit.bg_upp = translit.make_add_dict{ ["А"] = "A", ["Б"] = "B", ["В"] = "V", ["Г"] = "G", ["Д"] = "D", ["Е"] = "E", ["Ж"] = "Ž", ["З"] = "Z", ["И"] = "I", ["Й"] = "J", ["К"] = "K", ["Л"] = "L", ["М"] = "M", ["Н"] = "N", ["О"] = "O", ["П"] = "P", ["Р"] = "R", ["С"] = "S", ["Т"] = "T", ["У"] = "U", ["Ф"] = "F", ["Х"] = "Ch", ["Ц"] = "C", ["Ч"] = "Č", ["Ш"] = "Š", ["Щ"] = "Št", ["Ъ"] = "Ă", ["Ь"] = "′", ["Ю"] = "Ju", ["Я"] = "Ja", } translit.tables["Bulgarian \\quotation{scientific} transliteration uppercase"] = translit.bg_upp --------------------------------------------------------------------------- -- Lowercase Bulgarian -> „scientific“ transliteration -- --------------------------------------------------------------------------- translit.bg_low = translit.make_add_dict{ ["а"] = "a", ["б"] = "b", ["в"] = "v", ["г"] = "g", ["д"] = "d", ["е"] = "e", ["ж"] = "ž", ["з"] = "z", ["и"] = "i", ["й"] = "j", ["к"] = "k", ["л"] = "l", ["м"] = "m", ["н"] = "n", ["о"] = "o", ["п"] = "p", ["р"] = "r", ["с"] = "s", ["т"] = "t", ["у"] = "u", ["ф"] = "f", ["х"] = "ch", ["ц"] = "c", ["ч"] = "č", ["ш"] = "š", ["щ"] = "št", ["ъ"] = "ă", ["ь"] = "′", ["ю"] = "ju", ["я"] = "ja", } translit.tables["Bulgarian \\quotation{scientific} transliteration lowercase"] = translit.bg_low translit.done_bg = true end local P, Cs = lpeg.P, lpeg.Cs local addrules = translit.addrules local utfchar = translit.utfchar local function bulgarian (mode) local bulgarian_parser if mode == "de" then local bg = translit.bg_upp + translit.bg_low local p_bg = addrules(bg) bulgarian_parser = Cs((p_bg / bg + utfchar)^0) else return nil end return bulgarian_parser end translit.methods["bg_de"] = function (text) local p = pcache["bg_de"] if not p then p = bulgarian("de") pcache["bg_de"] = p end return p and lpegmatch(p, text) or "" end -- vim:ft=lua:sw=4:ts=4
-- -- Client API Emulation -- -- Intended to be used for unit testing WoW addons. -- -- !!WARNING!! Do not include in any WoW addon .toc file. !!WARNING!! -- -- (c) Fitzcairn of Cenarion Circle -- [email protected] -- Include the utils file. -- This will also error out the load if for some reason this is included -- in a toc file inadvertently. require('Util') local U = FitzUtils; -- -- Blizzard API Emulation -- Stubs for required Blizzard API functions to allow for unit testing. -- -- The global test state, populated by ResetClientTestState(). local g_test_state = {} -- Data structure describing the state of our emulated wow client -- This is used by the API emulation, and will be copied and modified -- in unit tests to set up the test. local g_test_state_template = { -- Slash commands SlashCmdList = {}, -- User class user_class = "Rogue", -- Action bar state possess_bar_visible = nil, curr_action_bar_page = 1, bonus_bar_offset = 0, extra_bar_visibility = { BL = nil, BR = nil, RB = nil, RB2 = nil, }, -- Spell list for tests. spell = { -- EXAMPLE: -- { -- id = 1234, -- name = "spell", -- rank = "Rank 1", -- icon = "/path/to/fake/icon", -- powerCost = 50, -- isFunnel = false, -- powerType = 0, -- castingTime = 100, -- minRange = 0, -- maxRange = 5, -- }, }, -- Item list for tests item = { -- EXAMPLE: -- { -- id = 1234, -- name = "item", -- link = "item:1234", -- quality = 4, -- iLevel = 232, -- reqLevel = 80, -- class = "Weapon", -- subclass = "Guns", -- maxStack = 1, -- equipSlot = 15, -- icon = "/path/to/fake/icon", -- vendorPrice = 1, -- }, }, -- Equipmentset list for tests. equipmentset = { -- EXAMPLE: -- { -- name = "Set", -- icon = "/path/to/fake/icon", -- setId = 1234, -- }, }, -- Macro list for tests. macro = { -- EXAMPLE: -- { -- name = "test", -- icon = "/path/to/fake/icon", -- body = "/cast Spell", -- } }, -- Bind table, populated from the bar state (below) by ResetClientTestState. binds = { -- Example: ACTIONBUTTON1 = {"bind", "bind", ...} }, -- Action bar slot tables in order of slot ID. Among other things, -- each slot has an action with a type and an id that references into -- the table for that tyle. ResetClientTestState will populate _G -- with these. Binds will be assigned in the test setup. bar = { { name = "ActionButton1", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON1", action = { type = "spell", id = "test" } }, { name = "ActionButton2", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON2", action = { type = "spell", id = "test" } }, { name = "ActionButton3", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON3", action = { type = "spell", id = "test" } }, { name = "ActionButton4", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON4", action = { type = "spell", id = "test" } }, { name = "ActionButton5", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON5", action = { type = "spell", id = "test" } }, { name = "ActionButton6", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON6", action = { type = "spell", id = "test" } }, { name = "ActionButton7", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON7", action = { type = "spell", id = "test" } }, { name = "ActionButton8", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON8", action = { type = "spell", id = "test" } }, { name = "ActionButton9", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON9", action = { type = "spell", id = "test" } }, { name = "ActionButton10", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON10", action = { type = "spell", id = "test" } }, { name = "ActionButton11", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON11", action = { type = "spell", id = "test" } }, { name = "ActionButton12", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON12", action = { type = "spell", id = "test" } }, { name = "BonusActionButton1", binds = {}, buttonType = "BONUSACTIONBUTTON", cmd = "BONUSACTIONBUTTON1", action = { type = "spell", id = "test" } }, { name = "BonusActionButton2", binds = {}, buttonType = "BONUSACTIONBUTTON", cmd = "BONUSACTIONBUTTON2", action = { type = "spell", id = "test" } }, { name = "BonusActionButton3", binds = {}, buttonType = "BONUSACTIONBUTTON", cmd = "BONUSACTIONBUTTON3", action = { type = "spell", id = "test" } }, { name = "BonusActionButton4", binds = {}, buttonType = "BONUSACTIONBUTTON", cmd = "BONUSACTIONBUTTON4", action = { type = "spell", id = "test" } }, { name = "BonusActionButton5", binds = {}, buttonType = "BONUSACTIONBUTTON", cmd = "BONUSACTIONBUTTON5", action = { type = "spell", id = "test" } }, { name = "BonusActionButton6", binds = {}, buttonType = "BONUSACTIONBUTTON", cmd = "BONUSACTIONBUTTON6", action = { type = "spell", id = "test" } }, { name = "BonusActionButton7", binds = {}, buttonType = "BONUSACTIONBUTTON", cmd = "BONUSACTIONBUTTON7", action = { type = "spell", id = "test" } }, { name = "BonusActionButton8", binds = {}, buttonType = "BONUSACTIONBUTTON", cmd = "BONUSACTIONBUTTON8", action = { type = "spell", id = "test" } }, { name = "BonusActionButton9", binds = {}, buttonType = "BONUSACTIONBUTTON", cmd = "BONUSACTIONBUTTON9", action = { type = "spell", id = "test" } }, { name = "BonusActionButton10", binds = {}, buttonType = "BONUSACTIONBUTTON", cmd = "BONUSACTIONBUTTON10", action = { type = "spell", id = "test" } }, { name = "BonusActionButton11", binds = {}, buttonType = "BONUSACTIONBUTTON", cmd = "BONUSACTIONBUTTON11", action = { type = "spell", id = "test" } }, { name = "BonusActionButton12", binds = {}, buttonType = "BONUSACTIONBUTTON", cmd = "BONUSACTIONBUTTON12", action = { type = "spell", id = "test" } }, { name = "MultiBarRightButton1", binds = {}, buttonType = "MULTIACTIONBAR3BUTTON", cmd = "MULTIACTIONBAR3BUTTON1", action = { type = "spell", id = "test" } }, { name = "MultiBarRightButton2", binds = {}, buttonType = "MULTIACTIONBAR3BUTTON", cmd = "MULTIACTIONBAR3BUTTON2", action = { type = "spell", id = "test" } }, { name = "MultiBarRightButton3", binds = {}, buttonType = "MULTIACTIONBAR3BUTTON", cmd = "MULTIACTIONBAR3BUTTON3", action = { type = "spell", id = "test" } }, { name = "MultiBarRightButton4", binds = {}, buttonType = "MULTIACTIONBAR3BUTTON", cmd = "MULTIACTIONBAR3BUTTON4", action = { type = "spell", id = "test" } }, { name = "MultiBarRightButton5", binds = {}, buttonType = "MULTIACTIONBAR3BUTTON", cmd = "MULTIACTIONBAR3BUTTON5", action = { type = "spell", id = "test" } }, { name = "MultiBarRightButton6", binds = {}, buttonType = "MULTIACTIONBAR3BUTTON", cmd = "MULTIACTIONBAR3BUTTON6", action = { type = "spell", id = "test" } }, { name = "MultiBarRightButton7", binds = {}, buttonType = "MULTIACTIONBAR3BUTTON", cmd = "MULTIACTIONBAR3BUTTON7", action = { type = "spell", id = "test" } }, { name = "MultiBarRightButton8", binds = {}, buttonType = "MULTIACTIONBAR3BUTTON", cmd = "MULTIACTIONBAR3BUTTON8", action = { type = "spell", id = "test" } }, { name = "MultiBarRightButton9", binds = {}, buttonType = "MULTIACTIONBAR3BUTTON", cmd = "MULTIACTIONBAR3BUTTON9", action = { type = "spell", id = "test" } }, { name = "MultiBarRightButton10", binds = {}, buttonType = "MULTIACTIONBAR3BUTTON", cmd = "MULTIACTIONBAR3BUTTON10", action = { type = "spell", id = "test" } }, { name = "MultiBarRightButton11", binds = {}, buttonType = "MULTIACTIONBAR3BUTTON", cmd = "MULTIACTIONBAR3BUTTON11", action = { type = "spell", id = "test" } }, { name = "MultiBarRightButton12", binds = {}, buttonType = "MULTIACTIONBAR3BUTTON", cmd = "MULTIACTIONBAR3BUTTON12", action = { type = "spell", id = "test" } }, { name = "MultiBarLeftButton1", binds = {}, buttonType = "MULTIACTIONBAR4BUTTON", cmd = "MULTIACTIONBAR4BUTTON1", action = { type = "spell", id = "test" } }, { name = "MultiBarLeftButton2", binds = {}, buttonType = "MULTIACTIONBAR4BUTTON", cmd = "MULTIACTIONBAR4BUTTON2", action = { type = "spell", id = "test" } }, { name = "MultiBarLeftButton3", binds = {}, buttonType = "MULTIACTIONBAR4BUTTON", cmd = "MULTIACTIONBAR4BUTTON3", action = { type = "spell", id = "test" } }, { name = "MultiBarLeftButton4", binds = {}, buttonType = "MULTIACTIONBAR4BUTTON", cmd = "MULTIACTIONBAR4BUTTON4", action = { type = "spell", id = "test" } }, { name = "MultiBarLeftButton5", binds = {}, buttonType = "MULTIACTIONBAR4BUTTON", cmd = "MULTIACTIONBAR4BUTTON5", action = { type = "spell", id = "test" } }, { name = "MultiBarLeftButton6", binds = {}, buttonType = "MULTIACTIONBAR4BUTTON", cmd = "MULTIACTIONBAR4BUTTON6", action = { type = "spell", id = "test" } }, { name = "MultiBarLeftButton7", binds = {}, buttonType = "MULTIACTIONBAR4BUTTON", cmd = "MULTIACTIONBAR4BUTTON7", action = { type = "spell", id = "test" } }, { name = "MultiBarLeftButton8", binds = {}, buttonType = "MULTIACTIONBAR4BUTTON", cmd = "MULTIACTIONBAR4BUTTON8", action = { type = "spell", id = "test" } }, { name = "MultiBarLeftButton9", binds = {}, buttonType = "MULTIACTIONBAR4BUTTON", cmd = "MULTIACTIONBAR4BUTTON9", action = { type = "spell", id = "test" } }, { name = "MultiBarLeftButton10", binds = {}, buttonType = "MULTIACTIONBAR4BUTTON", cmd = "MULTIACTIONBAR4BUTTON10", action = { type = "spell", id = "test" } }, { name = "MultiBarLeftButton11", binds = {}, buttonType = "MULTIACTIONBAR4BUTTON", cmd = "MULTIACTIONBAR4BUTTON11", action = { type = "spell", id = "test" } }, { name = "MultiBarLeftButton12", binds = {}, buttonType = "MULTIACTIONBAR4BUTTON", cmd = "MULTIACTIONBAR4BUTTON12", action = { type = "spell", id = "test" } }, { name = "MultiBarBottomRightButton1", binds = {}, buttonType = "MULTIACTIONBAR2BUTTON", cmd = "MULTIACTIONBAR2BUTTON1", action = { type = "spell", id = "test" } }, { name = "MultiBarBottomRightButton2", binds = {}, buttonType = "MULTIACTIONBAR2BUTTON", cmd = "MULTIACTIONBAR2BUTTON2", action = { type = "spell", id = "test" } }, { name = "MultiBarBottomRightButton3", binds = {}, buttonType = "MULTIACTIONBAR2BUTTON", cmd = "MULTIACTIONBAR2BUTTON3", action = { type = "spell", id = "test" } }, { name = "MultiBarBottomRightButton4", binds = {}, buttonType = "MULTIACTIONBAR2BUTTON", cmd = "MULTIACTIONBAR2BUTTON4", action = { type = "spell", id = "test" } }, { name = "MultiBarBottomRightButton5", binds = {}, buttonType = "MULTIACTIONBAR2BUTTON", cmd = "MULTIACTIONBAR2BUTTON5", action = { type = "spell", id = "test" } }, { name = "MultiBarBottomRightButton6", binds = {}, buttonType = "MULTIACTIONBAR2BUTTON", cmd = "MULTIACTIONBAR2BUTTON6", action = { type = "spell", id = "test" } }, { name = "MultiBarBottomRightButton7", binds = {}, buttonType = "MULTIACTIONBAR2BUTTON", cmd = "MULTIACTIONBAR2BUTTON7", action = { type = "spell", id = "test" } }, { name = "MultiBarBottomRightButton8", binds = {}, buttonType = "MULTIACTIONBAR2BUTTON", cmd = "MULTIACTIONBAR2BUTTON8", action = { type = "spell", id = "test" } }, { name = "MultiBarBottomRightButton9", binds = {}, buttonType = "MULTIACTIONBAR2BUTTON", cmd = "MULTIACTIONBAR2BUTTON9", action = { type = "spell", id = "test" } }, { name = "MultiBarBottomRightButton10", binds = {}, buttonType = "MULTIACTIONBAR2BUTTON", cmd = "MULTIACTIONBAR2BUTTON10", action = { type = "spell", id = "test" } }, { name = "MultiBarBottomRightButton11", binds = {}, buttonType = "MULTIACTIONBAR2BUTTON", cmd = "MULTIACTIONBAR2BUTTON11", action = { type = "spell", id = "test" } }, { name = "MultiBarBottomRightButton12", binds = {}, buttonType = "MULTIACTIONBAR2BUTTON", cmd = "MULTIACTIONBAR2BUTTON12", action = { type = "spell", id = "test" } }, { name = "MultiBarBottomLeftButton1", binds = {}, buttonType = "MULTIACTIONBAR1BUTTON", cmd = "MULTIACTIONBAR1BUTTON1", action = { type = "spell", id = "test" } }, { name = "MultiBarBottomLeftButton2", binds = {}, buttonType = "MULTIACTIONBAR1BUTTON", cmd = "MULTIACTIONBAR1BUTTON2", action = { type = "spell", id = "test" } }, { name = "MultiBarBottomLeftButton3", binds = {}, buttonType = "MULTIACTIONBAR1BUTTON", cmd = "MULTIACTIONBAR1BUTTON3", action = { type = "spell", id = "test" } }, { name = "MultiBarBottomLeftButton4", binds = {}, buttonType = "MULTIACTIONBAR1BUTTON", cmd = "MULTIACTIONBAR1BUTTON4", action = { type = "spell", id = "test" } }, { name = "MultiBarBottomLeftButton5", binds = {}, buttonType = "MULTIACTIONBAR1BUTTON", cmd = "MULTIACTIONBAR1BUTTON5", action = { type = "spell", id = "test" } }, { name = "MultiBarBottomLeftButton6", binds = {}, buttonType = "MULTIACTIONBAR1BUTTON", cmd = "MULTIACTIONBAR1BUTTON6", action = { type = "spell", id = "test" } }, { name = "MultiBarBottomLeftButton7", binds = {}, buttonType = "MULTIACTIONBAR1BUTTON", cmd = "MULTIACTIONBAR1BUTTON7", action = { type = "spell", id = "test" } }, { name = "MultiBarBottomLeftButton8", binds = {}, buttonType = "MULTIACTIONBAR1BUTTON", cmd = "MULTIACTIONBAR1BUTTON8", action = { type = "spell", id = "test" } }, { name = "MultiBarBottomLeftButton9", binds = {}, buttonType = "MULTIACTIONBAR1BUTTON", cmd = "MULTIACTIONBAR1BUTTON9", action = { type = "spell", id = "test" } }, { name = "MultiBarBottomLeftButton10", binds = {}, buttonType = "MULTIACTIONBAR1BUTTON", cmd = "MULTIACTIONBAR1BUTTON10", action = { type = "spell", id = "test" } }, { name = "MultiBarBottomLeftButton11", binds = {}, buttonType = "MULTIACTIONBAR1BUTTON", cmd = "MULTIACTIONBAR1BUTTON11", action = { type = "spell", id = "test" } }, { name = "MultiBarBottomLeftButton12", binds = {}, buttonType = "MULTIACTIONBAR1BUTTON", cmd = "MULTIACTIONBAR1BUTTON12", action = { type = "spell", id = "test" } }, { name = "ActionButton1", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON1", action = { type = "spell", id = "test" } }, { name = "ActionButton2", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON2", action = { type = "spell", id = "test" } }, { name = "ActionButton3", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON3", action = { type = "spell", id = "test" } }, { name = "ActionButton4", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON4", action = { type = "spell", id = "test" } }, { name = "ActionButton5", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON5", action = { type = "spell", id = "test" } }, { name = "ActionButton6", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON6", action = { type = "spell", id = "test" } }, { name = "ActionButton7", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON7", action = { type = "spell", id = "test" } }, { name = "ActionButton8", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON8", action = { type = "spell", id = "test" } }, { name = "ActionButton9", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON9", action = { type = "spell", id = "test" } }, { name = "ActionButton10", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON10", action = { type = "spell", id = "test" } }, { name = "ActionButton11", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON11", action = { type = "spell", id = "test" } }, { name = "ActionButton12", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON12", action = { type = "spell", id = "test" } }, { name = "ActionButton1", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON1", action = { type = "spell", id = "test" } }, { name = "ActionButton2", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON2", action = { type = "spell", id = "test" } }, { name = "ActionButton3", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON3", action = { type = "spell", id = "test" } }, { name = "ActionButton4", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON4", action = { type = "spell", id = "test" } }, { name = "ActionButton5", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON5", action = { type = "spell", id = "test" } }, { name = "ActionButton6", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON6", action = { type = "spell", id = "test" } }, { name = "ActionButton7", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON7", action = { type = "spell", id = "test" } }, { name = "ActionButton8", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON8", action = { type = "spell", id = "test" } }, { name = "ActionButton9", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON9", action = { type = "spell", id = "test" } }, { name = "ActionButton10", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON10", action = { type = "spell", id = "test" } }, { name = "ActionButton11", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON11", action = { type = "spell", id = "test" } }, { name = "ActionButton12", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON12", action = { type = "spell", id = "test" } }, { name = "ActionButton1", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON1", action = { type = "spell", id = "test" } }, { name = "ActionButton2", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON2", action = { type = "spell", id = "test" } }, { name = "ActionButton3", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON3", action = { type = "spell", id = "test" } }, { name = "ActionButton4", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON4", action = { type = "spell", id = "test" } }, { name = "ActionButton5", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON5", action = { type = "spell", id = "test" } }, { name = "ActionButton6", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON6", action = { type = "spell", id = "test" } }, { name = "ActionButton7", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON7", action = { type = "spell", id = "test" } }, { name = "ActionButton8", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON8", action = { type = "spell", id = "test" } }, { name = "ActionButton9", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON9", action = { type = "spell", id = "test" } }, { name = "ActionButton10", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON10", action = { type = "spell", id = "test" } }, { name = "ActionButton11", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON11", action = { type = "spell", id = "test" } }, { name = "ActionButton12", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON12", action = { type = "spell", id = "test" } }, { name = "ActionButton1", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON1", action = { type = "spell", id = "test" } }, { name = "ActionButton2", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON2", action = { type = "spell", id = "test" } }, { name = "ActionButton3", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON3", action = { type = "spell", id = "test" } }, { name = "ActionButton4", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON4", action = { type = "spell", id = "test" } }, { name = "ActionButton5", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON5", action = { type = "spell", id = "test" } }, { name = "ActionButton6", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON6", action = { type = "spell", id = "test" } }, { name = "ActionButton7", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON7", action = { type = "spell", id = "test" } }, { name = "ActionButton8", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON8", action = { type = "spell", id = "test" } }, { name = "ActionButton9", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON9", action = { type = "spell", id = "test" } }, { name = "ActionButton10", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON10", action = { type = "spell", id = "test" } }, { name = "ActionButton11", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON11", action = { type = "spell", id = "test" } }, { name = "ActionButton12", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON12", action = { type = "spell", id = "test" } }, { name = "ActionButton1", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON1", action = { type = "spell", id = "test" } }, { name = "ActionButton2", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON2", action = { type = "spell", id = "test" } }, { name = "ActionButton3", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON3", action = { type = "spell", id = "test" } }, { name = "ActionButton4", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON4", action = { type = "spell", id = "test" } }, { name = "ActionButton5", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON5", action = { type = "spell", id = "test" } }, { name = "ActionButton6", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON6", action = { type = "spell", id = "test" } }, { name = "ActionButton7", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON7", action = { type = "spell", id = "test" } }, { name = "ActionButton8", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON8", action = { type = "spell", id = "test" } }, { name = "ActionButton9", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON9", action = { type = "spell", id = "test" } }, { name = "ActionButton10", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON10", action = { type = "spell", id = "test" } }, { name = "ActionButton11", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON11", action = { type = "spell", id = "test" } }, { name = "ActionButton12", binds = {}, buttonType = "ACTIONBUTTON", cmd = "ACTIONBUTTON12", action = { type = "spell", id = "test" } }, } } -- API emulations. function IsPossessBarVisible() return g_test_state.possess_bar_visible end function GetActionBarPage() return g_test_state.curr_action_bar_page end function GetActionBarToggles() local s = g_test_state.extra_bar_visibility return s.BL, s.BR, s.RB, s.RB2 end function GetBonusBarOffset() return g_test_state.bonus_bar_offset end -- [4.0.1] This now returns type, spell_id, sub_type instead of -- type, id, sub_type, spell_id function GetActionInfo(slot) local type, id, subType = nil, nil, nil, nil if g_test_state.bar[slot] then local a = g_test_state.bar[slot].action if g_test_state[a.type][a.id] then if a.type == "spell" then type, id, subType = a.type, g_test_state.spell[a.id].id, a.type else type, id, subType = a.type, a.id, nil end -- TODO: add emulation for companions and mounts. end end return type, id, subType, spellID end function GetActionTexture(slot) local tex = nil if g_test_state.bar[slot] then local a = g_test_state.bar[slot].action if g_test_state[a.type][a.id] then tex = g_test_state[a.type][a.id].icon end end return tex end function GetBindingKey(cmd) if not g_test_state.binds[cmd] then return "" end return unpack(g_test_state.binds[cmd].binds) end function GetEquipmentSetInfo(index) local name, icon, setID = nil, nil, nil if g_test_state.equipmentset[index] then local e = g_test_state.equipmentset[index] name, icon, setID = e.name, e.icon, nil end return name, icon, setID end function GetItemInfo(item) local name, link, quality, iLevel, reqLevel, class, subclass, maxStack, equipSlot, icon, vendorPrice = nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil if g_test_state.item[item] then i = g_test_state.item[item] name, link, quality, iLevel, reqLevel, class, subclass, maxStack, equipSlot, icon, vendorPrice = i.name, i.link, i.quality, i.iLevel, i.reqLevel, i.class, i.subclass, i.maxStack, i.equipSlot, i.icon, i.vendorPrice end return name, link, quality, iLevel, reqLevel, class, subclass, maxStack, equipSlot, icon, vendorPrice end function GetMacroInfo(id) local name, icon, body = nil, nil, nil if g_test_state.macro[id] then local m = g_test_state.macro[id] name, icon, body = m.name, m.icon, m.body end return name, icon, body end function GetSpellInfo(spell) local name, rank, icon, powerCost, isFunnel, powerType, castingTime, minRange, maxRange = nil, nil, nil, nil, nil, nil, nil, nil, nil if g_test_state.spell[spell] then s = g_test_state.spell[spell] name, rank, icon, powerCost, isFunnel, powerType, castingTime, minRange, maxRange = s.name, s.rank, s.icon, s.powerCost, s.isFunnel, s.powerType, s.castingTime, s.minRange, s.maxRange end return name, rank, icon, powerCost, isFunnel, powerType, castingTime, minRange, maxRange end function GetSpellTexture(name) local t, _ = select(3, GetSpellInfo(name)) return t end function GetLocale() return "US" end function GetNumShapeshiftForms() return 4 end function UnitClass() return g_test_state.class end -- Available in wow's lua version. function strtrim(str) str = string.match(str, '^%s*(.-)%s*$') return str end -- Create SlashCmdList so the libraries will load. -- This will be overridden in unit tests later. SlashCmdList = {} -- -- Non-WoW API Emulation -- -- Define LibStub so the ACE libraries can load. function LibStub(...) return { NewDataObject = function(...) return end } end -- -- Emulation API Helpers -- -- Reset the test state back to the original defined above, -- creating a copy for modification and letting whatever was -- set. function ResetClientTestState() g_test_state = U:DeepCopy(g_test_state_template) -- Add the bar slots into _G to emulate WoW's env. for _,b in ipairs(g_test_state.bar) do _G[b.name] = b end return g_test_state end -- Add a spell/item/equipmentset/macro to the test state. function AddTestAction(type, id, name, icon) assert(g_test_state[type]) assert(id ~= nil and name) if not icon then icon = name end link = type..":"..name local action = g_test_state[type][id] or {} action.id = id action.name = name action.link = link action.icon = icon g_test_state[type][id] = action end -- Add a spell/item/equipmentset/macro to a slot. function AddTestActionToSlot(slot, type, id) assert(g_test_state.bar[slot]) -- ok slot assert(g_test_state[type][id]) -- ok action local b = g_test_state.bar[slot].action b.type = type b.id = id end -- Add one or more a keybinds for a slot. function AddTestKeybind(replace, slot, ...) assert(g_test_state.bar[slot]) local b = g_test_state.bar[slot] local binds = {...} if replace then b.binds = binds else for _,bind in ipairs(binds) do table.insert(b.binds, bind) end end g_test_state.binds[b.cmd] = b end -- Set the unit class function TestSetUnitClass(class) g_test_state.unit_class = class end
---@class Time local Time = { -- [[Time Methods]] -- ---Returns the total number of days that the time object represents. ---@param self Time ---@return number toDays = function(self) end, ---Returns the total number of hours that the time object represents. ---@param self Time ---@return number toHours = function(self) end, ---Returns the total number of milliseconds that the time object represents. ---@param self Time ---@return number toMilliseconds = function(self) end, ---Returns the total number of minutes that the time object represents. ---@param self Time ---@return number toMinutes = function(self) end, ---Returns the total number of seconds that the time object represents. ---@param self Time ---@return number toSeconds = function(self) end, ---Returns a human-readable string built from the set of normalized time values that the object represents. ---@param self Time ---@return string toString = function(self) end, ---Returns a table of normalized time values that represent the time object in a more accessible form. ---This table is **not** compatible with `os.date`. ---@param self Time ---@return table toTable = function(self) end, ---Returns the total number of weeks that the time object represents. ---@param self Time ---@return number toWeeks = function(self) end, } return Time
tier=settings.startup["advanced-electric-enabled-tiers"].value -- advanced accumulator require("prototypes.entity.advanced-accumulator") require("prototypes.item.advanced-accumulator") if tier == "advanced" or tier == "elite" or tier == "ultimate" then require("prototypes.crafting.advanced-accumulator") require("prototypes.technology.advanced-accumulator") end -- advanced solar require("prototypes.entity.advanced-solar") require("prototypes.item.advanced-solar") if tier == "advanced" or tier == "elite" or tier == "ultimate" then require("prototypes.crafting.advanced-solar") require("prototypes.technology.advanced-solar") end -- elite accumulator require("prototypes.entity.elite-accumulator") require("prototypes.item.elite-accumulator") if tier == "elite" or tier == "ultimate" then require("prototypes.crafting.elite-accumulator") require("prototypes.technology.elite-accumulator") end -- elite solar require("prototypes.entity.elite-solar") require("prototypes.item.elite-solar") if tier == "elite" or tier == "ultimate" then require("prototypes.crafting.elite-solar") require("prototypes.technology.elite-solar") end -- ultimate accumulator require("prototypes.entity.ultimate-accumulator") require("prototypes.item.ultimate-accumulator") if tier == "ultimate" then require("prototypes.crafting.ultimate-accumulator") require("prototypes.technology.ultimate-accumulator") end -- ultimate solar require("prototypes.entity.ultimate-solar") require("prototypes.item.ultimate-solar") if tier == "ultimate" then require("prototypes.crafting.ultimate-solar") require("prototypes.technology.ultimate-solar") end data.raw["accumulator"]["accumulator"].fast_replaceable_group = "accumulator" data.raw["solar-panel"]["solar-panel"].fast_replaceable_group = "solar-panel" if mods["FactorioExtended-Plus-Power"] == nil then data.raw["accumulator"]["accumulator"].next_upgrade = "advanced-accumulator" data.raw["solar-panel"]["solar-panel"].next_upgrade = "advanced-solar" end if mods["5dim_core"] then require("prototypes.item-group-5dim") end
local ContentProvider = game:GetService("ContentProvider") local includes = script.Parent local Themer = require(includes:WaitForChild("Themer")) --- local DOUBLE_CLICK_TIME = 0.5 local RIGHT_ARROW_IMAGE = "rbxassetid://367872391" local DOWN_ARROW_IMAGE = "rbxassetid://913309373" local SCROLLBAR_IMAGES = { Top = "rbxassetid://590077572", Middle = "rbxassetid://590077572", Bottom = "rbxassetid://590077572", } local WIDGET_INFO = { WIDGET_ID = "PropertiesMod", WIDGET_DEFAULT_TITLE = "Properties", WIDGET_PLUGINGUI_INFO = DockWidgetPluginGuiInfo.new(Enum.InitialDockState.Float, true, false, 265, 400, 265, 250) } --- local Widget = { Categories = {}, PropertyRows = {}, } local APIData local APILib local Settings local propertyNameColumnWidth = 0 local plugin local widget local propertiesListScrollingFrame local propertiesListUIListLayout local function getPropertyNormalName(className, propertyName) return className .. "/" .. propertyName end local function parsePropertyNormalName(propertyNormalName) return string.match(propertyNormalName, "(.+)/(.+)") end local function isPropertyNotScriptable(className, propertyName) local property = APIData.Classes[className].Properties[propertyName] return property.Tags.NotScriptable end local function getEditorColumnWidth() local actualWidth = math.max(Settings.Config.EditorColumnWidth, widget.AbsoluteSize.X - propertyNameColumnWidth) if (propertiesListUIListLayout.AbsoluteContentSize.Y > widget.AbsoluteSize.Y) and (propertiesListUIListLayout.AbsoluteContentSize.X <= widget.AbsoluteSize.X) then return actualWidth - 18 else return actualWidth end end local function getListWidth() return propertyNameColumnWidth + getEditorColumnWidth() end local function newPropertyRow(className, propertyName) local normalName = getPropertyNormalName(className, propertyName) if Widget.PropertyRows[normalName] then return end local row = Instance.new("Frame") row.Name = normalName row.Size = UDim2.new(0, getListWidth(), 0, Settings.Config.RowHeight) row.BorderSizePixel = 0 row.BackgroundTransparency = 1 local propertyNameCell = Instance.new("Frame") propertyNameCell.AnchorPoint = Vector2.new(0, 0.5) propertyNameCell.Position = UDim2.new(0, 0, 0.5, 0) propertyNameCell.Size = UDim2.new(0, propertyNameColumnWidth, 0, Settings.Config.RowHeight) propertyNameCell.Name = "PropertyName" local editorCell = Instance.new("Frame") editorCell.AnchorPoint = Vector2.new(1, 0.5) editorCell.Position = UDim2.new(1, 0, 0.5, 0) editorCell.Size = UDim2.new(0, getEditorColumnWidth(), 0, Settings.Config.RowHeight) editorCell.Name = "Editor" -- populate local isNative = APIData.Classes[className].Properties[propertyName].Native local isReadOnly = APILib:IsPropertyReadOnly(className, propertyName) local isNotScriptable = isPropertyNotScriptable(className, propertyName) local propertyNameLabel = Instance.new("TextButton") propertyNameLabel.AnchorPoint = Vector2.new(0, 0.5) propertyNameLabel.Size = UDim2.new(1, -24, 1, 0) propertyNameLabel.Position = UDim2.new(0, 24, 0.5, 0) propertyNameLabel.Active = true propertyNameLabel.BackgroundTransparency = 1 propertyNameLabel.BorderSizePixel = 0 propertyNameLabel.AutoButtonColor = false propertyNameLabel.Font = Enum.Font.SourceSans propertyNameLabel.TextSize = Settings.Config.TextSize propertyNameLabel.TextXAlignment = Enum.TextXAlignment.Left propertyNameLabel.TextYAlignment = Enum.TextYAlignment.Center propertyNameLabel.Text = propertyName Themer.SyncProperties(propertyNameCell, { BackgroundColor3 = Enum.StudioStyleGuideColor.TableItem, BorderColor3 = Enum.StudioStyleGuideColor.Border }) Themer.SyncProperties(editorCell, { BackgroundColor3 = Enum.StudioStyleGuideColor.TableItem, BorderColor3 = Enum.StudioStyleGuideColor.Border }) if isNotScriptable then Themer.SyncProperty(propertyNameLabel, "TextColor3", Enum.StudioStyleGuideColor.ErrorText) else Themer.SyncProperty(propertyNameLabel, "TextColor3", {Enum.StudioStyleGuideColor.MainText, isReadOnly and Enum.StudioStyleGuideModifier.Disabled or Enum.StudioStyleGuideModifier.Default}) end propertyNameLabel.MouseButton2Click:Connect(function() if (not isNative) then return end local rmbMenu = plugin:CreatePluginMenu("PropertiesMod") rmbMenu:AddNewAction("ViewOnDevHub", "View on DevHub").Triggered:Connect(function() plugin:OpenWikiPage("api-reference/property/" .. className .. "/" .. propertyName) end) rmbMenu:ShowAsync() rmbMenu:Destroy() end) propertyNameCell.MouseEnter:Connect(function() if (isReadOnly or isNotScriptable) then return end Themer.SyncProperty(propertyNameCell, "BackgroundColor3", {Enum.StudioStyleGuideColor.TableItem, Enum.StudioStyleGuideModifier.Hover}) end) propertyNameCell.MouseLeave:Connect(function() if (isReadOnly or isNotScriptable) then return end Themer.SyncProperty(propertyNameCell, "BackgroundColor3", Enum.StudioStyleGuideColor.TableItem) end) propertyNameCell:GetPropertyChangedSignal("AbsoluteSize"):Connect(function() editorCell.Size = UDim2.new(0, getEditorColumnWidth(), 0, Settings.Config.RowHeight) row.Size = UDim2.new(0, getListWidth(), 0, Settings.Config.RowHeight) end) propertyNameLabel.Parent = propertyNameCell propertyNameCell.Parent = row editorCell.Parent = row Widget.PropertyRows[normalName] = row -- nameCells[normalName] = propertyNameCell -- editorCells[normalName] = editorCell return row end local function createCategoryContainer(categoryName) if (Widget.Categories[categoryName]) then return end local isToggled do if (type(Settings.CategoryStateMemory[categoryName]) == "boolean") then isToggled = Settings.CategoryStateMemory[categoryName] else isToggled = true end end local categoryFrame = Instance.new("Frame") categoryFrame.Name = categoryName categoryFrame.BackgroundTransparency = 1 categoryFrame.Visible = false local header = Instance.new("Frame") header.Name = "Header" header.AnchorPoint = Vector2.new(0.5, 0) header.Size = UDim2.new(1, 0, 0, Settings.Config.RowHeight) header.Position = UDim2.new(0.5, 0, 0, 0) header.BorderSizePixel = 0 local headerToggle = Instance.new("ImageButton") headerToggle.Name = "Toggle" headerToggle.AnchorPoint = Vector2.new(0, 0.5) headerToggle.Size = UDim2.new(0, 24, 0, 24) headerToggle.Position = UDim2.new(0, 0, 0.5, 0) headerToggle.BackgroundTransparency = 1 headerToggle.Image = isToggled and RIGHT_ARROW_IMAGE or DOWN_ARROW_IMAGE local headerText = Instance.new("TextButton") headerText.Name = "HeaderText" headerText.AnchorPoint = Vector2.new(1, 0.5) headerText.Size = UDim2.new(1, -24, 1, 0) headerText.Position = UDim2.new(1, 0, 0.5, 0) headerText.AutoButtonColor = false headerText.BackgroundTransparency = 1 headerText.Font = Enum.Font.SourceSansBold headerText.TextSize = Settings.Config.TextSize headerText.TextXAlignment = Enum.TextXAlignment.Left headerText.TextYAlignment = Enum.TextYAlignment.Center headerText.Text = categoryName local categoryPropertiesListUI = Instance.new("Frame") categoryPropertiesListUI.Name = "PropertiesList" categoryPropertiesListUI.AnchorPoint = Vector2.new(0.5, 1) categoryPropertiesListUI.Position = UDim2.new(0.5, 0, 1, 0) categoryPropertiesListUI.BackgroundTransparency = 1 categoryPropertiesListUI.BorderSizePixel = 0 categoryPropertiesListUI.Visible = isToggled local categoryPropertiesListUIListLayout = propertiesListUIListLayout:Clone() local function toggle() isToggled = (not isToggled) Settings.CategoryStateMemory[categoryName] = isToggled headerToggle.Image = isToggled and RIGHT_ARROW_IMAGE or DOWN_ARROW_IMAGE categoryPropertiesListUI.Visible = isToggled local tableSize = categoryPropertiesListUIListLayout.AbsoluteContentSize categoryPropertiesListUI.Size = isToggled and UDim2.new(0, getListWidth(), 0, tableSize.Y) or UDim2.new(0, getListWidth(), 0, 0) end Themer.SyncProperty(header, "BackgroundColor3", Enum.StudioStyleGuideColor.MainBackground) Themer.SyncProperty(headerToggle, "ImageColor3", Enum.StudioStyleGuideColor.ButtonText) Themer.SyncProperty(headerText, "TextColor3", Enum.StudioStyleGuideColor.BrightText) headerToggle.MouseButton1Click:Connect(toggle) local lastClickTime = 0 headerText.MouseButton1Down:Connect(function() local now = tick() if ((now - lastClickTime) < DOUBLE_CLICK_TIME) then toggle() lastClickTime = 0 else lastClickTime = now end end) categoryPropertiesListUI:GetPropertyChangedSignal("AbsoluteSize"):Connect(function() categoryFrame.Size = UDim2.new(0, getListWidth(), 0, categoryPropertiesListUI.AbsoluteSize.Y + Settings.Config.RowHeight) end) categoryPropertiesListUIListLayout:GetPropertyChangedSignal("AbsoluteContentSize"):Connect(function() local tableSize = categoryPropertiesListUIListLayout.AbsoluteContentSize categoryPropertiesListUI.Size = isToggled and UDim2.new(0, getListWidth(), 0, tableSize.Y) or UDim2.new(0, getListWidth(), 0, 0) end) categoryPropertiesListUI.Size = UDim2.new(0, getListWidth(), 0, Settings.Config.RowHeight) headerToggle.Parent = header headerText.Parent = header categoryPropertiesListUIListLayout.Parent = categoryPropertiesListUI header.Parent = categoryFrame categoryPropertiesListUI.Parent = categoryFrame categoryFrame.Parent = propertiesListScrollingFrame Widget.Categories[categoryName] = { UI = categoryFrame, TableUI = categoryPropertiesListUI } return Widget.Categories[categoryName] end --- function Widget.Init(pluginObj, settings, apiLib) plugin = pluginObj widget = plugin:CreateDockWidgetPluginGui(WIDGET_INFO.WIDGET_ID, WIDGET_INFO.WIDGET_PLUGINGUI_INFO) widget.Archivable = false widget.ZIndexBehavior = Enum.ZIndexBehavior.Sibling widget.Name = WIDGET_INFO.WIDGET_ID widget.Title = WIDGET_INFO.WIDGET_DEFAULT_TITLE propertiesListScrollingFrame = Instance.new("ScrollingFrame") propertiesListScrollingFrame.Name = "PropertiesListContainer" propertiesListScrollingFrame.AnchorPoint = Vector2.new(0.5, 0.5) propertiesListScrollingFrame.Size = UDim2.new(1, 0, 1, 0) propertiesListScrollingFrame.Position = UDim2.new(0.5, 0, 0.5, 0) propertiesListScrollingFrame.CanvasSize = UDim2.new(0, 0, 0, 0) propertiesListScrollingFrame.CanvasPosition = Vector2.new(0, 0) propertiesListScrollingFrame.HorizontalScrollBarInset = Enum.ScrollBarInset.Always propertiesListScrollingFrame.VerticalScrollBarInset = Enum.ScrollBarInset.Always propertiesListScrollingFrame.VerticalScrollBarPosition = Enum.VerticalScrollBarPosition.Right propertiesListScrollingFrame.TopImage = SCROLLBAR_IMAGES.Top propertiesListScrollingFrame.MidImage = SCROLLBAR_IMAGES.Middle propertiesListScrollingFrame.BottomImage = SCROLLBAR_IMAGES.Bottom propertiesListScrollingFrame.BorderSizePixel = 1 propertiesListScrollingFrame.ScrollBarThickness = 18 propertiesListScrollingFrame.ClipsDescendants = true propertiesListUIListLayout = Instance.new("UIListLayout") propertiesListUIListLayout.FillDirection = Enum.FillDirection.Vertical propertiesListUIListLayout.HorizontalAlignment = Enum.HorizontalAlignment.Left propertiesListUIListLayout.SortOrder = Enum.SortOrder.Name propertiesListUIListLayout.VerticalAlignment = Enum.VerticalAlignment.Top propertiesListUIListLayout.Padding = UDim.new(0, 1) Themer.SyncProperties(propertiesListScrollingFrame, { ScrollBarImageColor3 = Enum.StudioStyleGuideColor.ScrollBar, BackgroundColor3 = Enum.StudioStyleGuideColor.Mid, BorderColor3 = Enum.StudioStyleGuideColor.Border, }) propertiesListUIListLayout:GetPropertyChangedSignal("AbsoluteContentSize"):Connect(function() local contentSize = propertiesListUIListLayout.AbsoluteContentSize propertiesListScrollingFrame.CanvasSize = UDim2.new(0, contentSize.X, 0, contentSize.Y) end) widget:GetPropertyChangedSignal("AbsoluteSize"):Connect(function() for _, propertyRow in pairs(Widget.PropertyRows) do propertyRow:FindFirstChild("Editor").Size = UDim2.new(0, getEditorColumnWidth(), 0, Settings.Config.RowHeight) propertyRow.Size = UDim2.new(0, getListWidth(), 0, Settings.Config.RowHeight) end end) Settings = settings APILib = apiLib.APILib APIData = apiLib.APIData propertiesListUIListLayout.Parent = propertiesListScrollingFrame propertiesListScrollingFrame.Parent = widget end function Widget.Unload() if widget then widget:Destroy() widget = nil end if propertiesListScrollingFrame then propertiesListScrollingFrame:Destroy() propertiesListScrollingFrame = nil end if propertiesListUIListLayout then propertiesListUIListLayout:Destroy() propertiesListUIListLayout = nil end Widget.Categories = {} Widget.ProeprtyRows = {} Settings = nil APILib = nil APIData = nil plugin = nil end function Widget.ResetRowVisibility() for _, row in pairs(Widget.PropertyRows) do row.Visible = false end end function Widget.SetRowVisibility(normalName, visibility) local propertyRow = Widget.PropertyRows[normalName] if (not propertyRow) then return end propertyRow.Visible = visibility end function Widget.ResetCategoryVisibility() for _, category in pairs(Widget.Categories) do category.UI.Visible = false end end function Widget.SetCategoryVisibility(categoryName, visibility) local category = Widget.Categories[categoryName] if (not category) then return end category.UI.Visible = visibility end function Widget.AddRow(className, propertyName, visibility) if (not widget) then return end if (not APIData) then return end local normalName = getPropertyNormalName(className, propertyName) if Widget.PropertyRows[normalName] then return end local propertyData = APIData.Classes[className].Properties[propertyName] local category = propertyData.Category local categoryTableUI = Widget.Categories[category] and Widget.Categories[category].TableUI or createCategoryContainer(category).TableUI local newRow = newPropertyRow(className, propertyName) newRow.Visible = visibility newRow.Parent = categoryTableUI -- resort rows end -- optimise sorting by keeping track of the categories that need to be sorted and then doing them at once instead of multiple passes function Widget.AddRows(rows) if (not widget) then return end if (not APIData) then return end local categoriesToBeResorted = {} for i = 1, #rows do local row = rows[i] local className, propertyName, visibility = row[1], row[2], row[3] local normalName = getPropertyNormalName(className, propertyName) if (not Widget.PropertyRows[normalName]) then local propertyData = APIData.Classes[className].Properties[propertyName] local category = propertyData.Category local categoryTableUI = Widget.Categories[category] and Widget.Categories[category].TableUI or createCategoryContainer(category).TableUI local newRow = newPropertyRow(className, propertyName) categoriesToBeResorted[category] = true newRow.Visible = visibility newRow.Parent = categoryTableUI end end local categoryRows = {} for categoryName in pairs(categoriesToBeResorted) do local category = Widget.Categories[categoryName] local categoryTableUI = category.TableUI for _, categoryRow in pairs(categoryTableUI:GetChildren()) do if categoryRow:IsA("GuiObject") then categoryRows[#categoryRows + 1] = categoryRow.Name end end if (#categoryRows > 0) then table.sort(categoryRows, function(a, b) local _, propertyNameA = parsePropertyNormalName(a) local _, propertyNameB = parsePropertyNormalName(b) return propertyNameA < propertyNameB end) for i, categoryRowName in ipairs(categoryRows) do Widget.PropertyRows[categoryRowName].LayoutOrder = i end end end end function Widget.GetPropertyNormalName(className, propertyName) return getPropertyNormalName(className, propertyName) end function Widget.ParsePropertyNormalName(normalName) return parsePropertyNormalName(normalName) end function Widget.SetPropertyNameColumnWidth(newWidth) if (not widget) then return end propertyNameColumnWidth = newWidth for _, propertyRow in pairs(Widget.PropertyRows) do propertyRow:FindFirstChild("PropertyName").Size = UDim2.new(0, propertyNameColumnWidth, 0, Settings.Config.RowHeight) end end function Widget.ResetScrollPosition() if (not widget) then return end propertiesListScrollingFrame.CanvasPosition = Vector2.new(0, 0) end ContentProvider:PreloadAsync({ RIGHT_ARROW_IMAGE, DOWN_ARROW_IMAGE, SCROLLBAR_IMAGES.Top, SCROLLBAR_IMAGES.Middle, SCROLLBAR_IMAGES.Bottom, }) return Widget
Locales['pl'] = { ['valid_this_purchase'] = 'Potwierdasz zakup?', ['yes'] = 'Tak', ['no'] = 'Nie', ['not_enough_money'] = 'Nie masz wystarczająco hajsu', ['press_menu'] = 'Kliknij ~INPUT_CONTEXT~ aby wyswietlic menu', ['clothes'] = 'Ubrania', ['you_paid'] = 'Zapłaciłeś ~g~$%s~s~', ['save_in_dressing'] = 'Chcesz zapisać swój strój w swojej nieruchomosci?', ['name_outfit'] = 'Nazwa stroju', ['saved_outfit'] = 'Strój zapisany!', }
function indexOf(haystack, needle) for idx,straw in pairs(haystack) do if straw == needle then return idx end end return -1 end function getDigits(n, le, digits) while n > 0 do local r = n % 10 if r == 0 or indexOf(digits, r) > 0 then return false end le = le - 1 digits[le + 1] = r n = math.floor(n / 10) end return true end function removeDigit(digits, le, idx) local pows = { 1, 10, 100, 1000, 10000 } local sum = 0 local pow = pows[le - 2 + 1] for i = 1, le do if i ~= idx then sum = sum + digits[i] * pow pow = math.floor(pow / 10) end end return sum end function main() local lims = { {12, 97}, {123, 986}, {1234, 9875}, {12345, 98764} } local count = { 0, 0, 0, 0, 0 } local omitted = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, } for i,_ in pairs(lims) do local nDigits = {} local dDigits = {} for j = 1, i + 2 - 1 do nDigits[j] = -1 dDigits[j] = -1 end for n = lims[i][1], lims[i][2] do for j,_ in pairs(nDigits) do nDigits[j] = 0 end local nOk = getDigits(n, i + 2 - 1, nDigits) if nOk then for d = n + 1, lims[i][2] + 1 do for j,_ in pairs(dDigits) do dDigits[j] = 0 end local dOk = getDigits(d, i + 2 - 1, dDigits) if dOk then for nix,_ in pairs(nDigits) do local digit = nDigits[nix] local dix = indexOf(dDigits, digit) if dix >= 0 then local rn = removeDigit(nDigits, i + 2 - 1, nix) local rd = removeDigit(dDigits, i + 2 - 1, dix) if (n / d) == (rn / rd) then count[i] = count[i] + 1 omitted[i][digit + 1] = omitted[i][digit + 1] + 1 if count[i] <= 12 then print(string.format("%d/%d = %d/%d by omitting %d's", n, d, rn, rd, digit)) end end end end end end end end print() end for i = 2, 5 do print("There are "..count[i - 2 + 1].." "..i.."-digit fractions of which:") for j = 1, 9 do if omitted[i - 2 + 1][j + 1] > 0 then print(string.format("%6d have %d's omitted", omitted[i - 2 + 1][j + 1], j)) end end print() end end main()
----------------------------------------- -- Spell: Cura -- Restores hp in area of effect. Self target only -- From what I understand, Cura's base potency is the same as Cure II's. -- With Afflatus Misery Bonus, it can be as potent as a Curaga III -- Modeled after our cure_ii.lua, which was modeled after the below reference -- Shamelessly stolen from http://members.shaw.ca/pizza_steve/cure/Cure_Calculator.html ----------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/magic") require("scripts/globals/msg") ----------------------------------------- function onMagicCastingCheck(caster,target,spell) if (caster:getID() ~= target:getID()) then return tpz.msg.basic.CANNOT_PERFORM_TARG else return 0 end end function onSpellCast(caster,target,spell) local divisor = 0 local constant = 0 local basepower = 0 local power = 0 local basecure = 0 local final = 0 local minCure = 60 if (USE_OLD_CURE_FORMULA == true) then power = getCurePowerOld(caster) divisor = 1 constant = 20 if (power > 170) then divisor = 35.6666 constant = 87.62 elseif (power > 110) then divisor = 2 constant = 47.5 end else power = getCurePower(caster) if (power < 70) then divisor = 1 constant = 60 basepower = 40 elseif (power < 125) then divisor = 5.5 constant = 90 basepower = 70 elseif (power < 200) then divisor = 7.5 constant = 100 basepower = 125 elseif (power < 400) then divisor = 10 constant = 110 basepower = 200 elseif (power < 700) then divisor = 20 constant = 130 basepower = 400 else divisor = 999999 constant = 145 basepower = 0 end end if (USE_OLD_CURE_FORMULA == true) then basecure = getBaseCureOld(power,divisor,constant) else basecure = getBaseCure(power,divisor,constant,basepower) end --Apply Afflatus Misery Bonus to Final Result if (caster:hasStatusEffect(tpz.effect.AFFLATUS_MISERY)) then if (caster:getID() == target:getID()) then -- Let's use a local var to hold the power of Misery so the boost is applied to all targets, caster:setLocalVar("Misery_Power", caster:getMod(tpz.mod.AFFLATUS_MISERY)) end local misery = caster:getLocalVar("Misery_Power") --THIS IS LARELY SEMI-EDUCATED GUESSWORK. THERE IS NOT A --LOT OF CONCRETE INFO OUT THERE ON CURA THAT I COULD FIND --Not very much documentation for Cura II known at all. --As with Cura, the Afflatus Misery bonus can boost this spell up --to roughly the level of a Curaga 3. For Cura I vs Curaga II, --this is document at ~175HP, 15HP less than the cap of 190HP. So --for Cura II, i'll go with 15 less than the cap of Curaga III (390): 375 --So with lack of available formula documentation, I'll go with that. --printf("BEFORE AFFLATUS MISERY BONUS: %d", basecure) basecure = basecure + misery if (basecure > 375) then basecure = 375 end --printf("AFTER AFFLATUS MISERY BONUS: %d", basecure) --Afflatus Misery Mod Gets Used Up caster:setMod(tpz.mod.AFFLATUS_MISERY, 0) end final = getCureFinal(caster,spell,basecure,minCure,false) final = final + (final * (target:getMod(tpz.mod.CURE_POTENCY_RCVD)/100)) --Applying server mods.... final = final * CURE_POWER target:addHP(final) target:wakeUp() --Enmity for Cura is fixed, so its CE/VE is set in the SQL and not calculated with updateEnmityFromCure spell:setMsg(tpz.msg.basic.AOE_HP_RECOVERY) local mpBonusPercent = (final*caster:getMod(tpz.mod.CURE2MP_PERCENT))/100 if (mpBonusPercent > 0) then caster:addMP(mpBonusPercent) end return final end
require("CLRPackage") Forms = CLRPackage("System.Windows.Forms", "System.Windows.Forms") Drawing = CLRPackage("System.Drawing", "System.Drawing") LuaInterface = CLRPackage("LuaInterface", "LuaInterface") IO = CLRPackage("System.IO", "System.IO") System = CLRPackage("System", "System") Form=Forms.Form TextBox=Forms.TextBox Label=Forms.Label ListBox=Forms.ListBox Button=Forms.Button Point=Drawing.Point Size=Drawing.Size Lua=LuaInterface.Lua OpenFileDialog=Forms.OpenFileDialog File=IO.File StreamReader=IO.StreamReader FileMode=IO.FileMode ScrollBars=Forms.ScrollBars FormBorderStyle=Forms.FormBorderStyle FormStartPosition=Forms.FormStartPosition function clear_click(sender,args) code:Clear() end function execute_click(sender,args) results.Items:Clear() result=lua:DoString(code.Text) if result then for i=0,result.Length-1 do results.Items:Add(result[i]) end end end function load_click(sender,args) open_file:ShowDialog() file=StreamReader(open_file.FileName) code.Text=file:ReadToEnd() file:Close() end form = Form() code = TextBox() label1 = Label() execute = Button() clear = Button() results = ListBox() label2 = Label() load = Button() lua = Lua() --lua:OpenBaseLib() -- steffenj: Open*Lib() functions no longer exist open_file = OpenFileDialog() form:SuspendLayout() code.Location = Point(16, 24) code.Multiline = true code.Name = "Code" code.Size = Size(440, 128) code.ScrollBars = ScrollBars.Vertical code.TabIndex = 0 code.Text = "" label1.Location = Point(16, 8) label1.Name = "label1" label1.Size = Size(100, 16) label1.TabIndex = 1 label1.Text = "Lua Code:" execute.Location = Point(96, 160) execute.Name = "Execute" execute.TabIndex = 2 execute.Text = "Execute" execute.Click:Add(execute_click) clear.Location = Point(176, 160) clear.Name = "Clear" clear.TabIndex = 3 clear.Text = "Clear" clear.Click:Add(clear_click) results.Location = Point(16, 208) results.Name = "Results" results.Size = Size(440, 95) results.TabIndex = 4 label2.Location = Point(16, 192) label2.Name = "label2" label2.Size = Size(100, 16) label2.TabIndex = 5 label2.Text = "Results:" load.Location = Point(16, 160) load.Name = "Load" load.TabIndex = 6 load.Text = "Load..." load.Click:Add(load_click) open_file.DefaultExt = "lua" open_file.Filter = "Lua Scripts|*.lua|All Files|*.*" open_file.Title = "Pick a File" form.AutoScaleBaseSize = Size(5, 13) form.ClientSize = Size(472, 315) form.Controls:Add(load) form.Controls:Add(label2) form.Controls:Add(results) form.Controls:Add(clear) form.Controls:Add(execute) form.Controls:Add(label1) form.Controls:Add(code) form.Name = "MainForm" form.Text = "LuaNet" form.FormBorderStyle = FormBorderStyle.Fixed3D form.StartPosition = FormStartPosition.CenterScreen form:ResumeLayout(false) form:ShowDialog()
local help = [[ -- That didn't work. Are you doing something like this? require "try_catch" try { function() -- Do your thing here error('oops') -- Code after an error never executed end, catch { -- optional function(error) print('caught error: ' .. error) end }, ensure { -- optional function() -- This will always run (with any return value ignored) end } } ]] function catch(what) assert(type(what) == 'table' and type(what[1]) == 'function', help) return {'catch', what[1]} end function ensure(what) assert(type(what) == 'table' and type(what[1]) == 'function', help) return {'ensure', what[1]} end function try(what) assert(type(what) == 'table' and type(what[1]) == 'function', help) local lcatch, lensure if what[2] then assert(type(what[2]) == 'table' and (what[2][1] == 'catch' or what[2][1] == 'ensure') and type(what[2][2]) == 'function', help) if what[2][1] == 'catch' then lcatch = what[2][2] if what[3] then assert(type(what[3]) == 'table' and what[3][1] == 'ensure' and type(what[3][2]) == 'function', help) lensure = what[3][2] end else lensure = what[2][2] end end local status, result = pcall(what[1]) if not status and lcatch then result = lcatch(result) end if lensure then lensure() end return result end
local M = {} -- Default options for the theme M.config = { -- This enables the Neovim background to set either onedark or onelight dark_theme = "onedark", -- The default dark theme light_theme = "onelight", -- The default light theme theme = function() if vim.o.background == "dark" then return M.config.dark_theme else return M.config.light_theme end end, colors = {}, -- Override default colors hlgroups = {}, -- Override default highlight groups filetype_hlgroups = {}, -- Override default highlight groups for specific filetypes filetype_hlgroups_ignore = { -- Filetypes which are ignored when applying filetype highlight groups filetypes = { "^aerial$", "^alpha$", "^fugitive$", "^fugitiveblame$", "^help$", "^minimap$", "^neo--tree$", "^neo--tree--popup$", "^NvimTree$", "^packer$", "^qf$", "^startify$", "^startuptime$", "^terminal$", "^toggleterm$", "^undotree$", }, buftypes = { "^terminal$" }, }, plugins = { -- Enable/Disable specific plugins aerial = true, barbar = true, dashboard = true, gitsigns_nvim = true, hop = true, indentline = true, lsp_saga = true, marks = true, native_lsp = true, neo_tree = true, notify = true, nvim_cmp = true, nvim_dap = true, nvim_dap_ui = true, nvim_hlslens = true, nvim_tree = true, nvim_ts_rainbow = true, packer = true, polygot = true, startify = true, telescope = true, toggleterm = true, treesitter = true, trouble_nvim = true, vim_ultest = true, which_key_nvim = true, }, styles = { strings = "NONE", -- Style that is applied to strings comments = "NONE", -- Style that is applied to comments keywords = "NONE", -- Style that is applied to keywords functions = "NONE", -- Style that is applied to functions variables = "NONE", -- Style that is applied to variables virtual_text = "NONE", -- Style that is applied to virtual text }, options = { bold = false, -- Use the themes opinionated bold styles? italic = false, -- Use the themes opinionated italic styles? underline = false, -- Use the themes opinionated underline styles? undercurl = false, -- Use the themes opinionated undercurl styles? cursorline = false, -- Use cursorline highlighting? transparency = false, -- Use a transparent background? terminal_colors = false, -- Use the theme's colors for Neovim's :terminal? window_unfocussed_color = false, -- When the window is out of focus, change the normal background? }, } ---Apply the users custom config on top of the default ---@param user_config table ---@return nil function M.set_config(user_config) local utils = require("onedarkpro.utils") -- Merge the config tables user_config = user_config or {} M.config = utils.tbl_deep_extend(M.config, user_config) -- Overwrite the default plugins config with the user's if user_config.plugins then for plugin, _ in pairs(M.config.plugins) do if user_config.plugins["all"] == false then M.config.plugins[plugin] = false end if user_config.plugins[plugin] then M.config.plugins[plugin] = user_config.plugins[plugin] end end end -- Enable the cursorline in Neovim if M.config.options.highlight_cursorline or M.config.options.cursorline then vim.wo.cursorline = true end end return M
function SetPedsToCalm(exists, handle, iter) if exists then SetBlockingOfNonTemporaryEvents(handle, true) SetPedFleeAttributes(handle, 0, 0) SetPedCombatAttributes(handle, 17, 1) local exists, handle = FindNextPed(iter) SetPedsToCalm(exists, handle, iter) else EndFindPed(iter) end end Citizen.CreateThread(function() while true do Citizen.Wait(1) local player = PlayerId() SetEveryoneIgnorePlayer(player, true) SetPoliceIgnorePlayer(player, true) SetDispatchCopsForPlayer(player, false) EnableDispatchService(1, false) EnableDispatchService(2, false) EnableDispatchService(3, false) EnableDispatchService(5, false) EnableDispatchService(8, false) EnableDispatchService(9, false) EnableDispatchService(10, false) EnableDispatchService(11, false) SetPlayerCanBeHassledByGangs(player, false) SetIgnoreLowPriorityShockingEvents(player, true) SetPlayerWantedLevel(player, 0, false) SetPlayerWantedLevelNow(player, false) SetPlayerWantedLevel(player, 0, false) local iter, handle = FindFirstPed() SetPedsToCalm(true, handle, iter) end end)
local M = {} M.config = function() local g = vim.g vim.o.termguicolors = true --nvimtree g.nvim_tree_side = "left" g.nvim_tree_width = 25 g.nvim_tree_ignore = {".git", "node_modules", ".cache"} g.nvim_tree_auto_open = 0 g.nvim_tree_auto_close = 0 g.nvim_tree_quit_on_open = 0 g.nvim_tree_follow = 1 g.nvim_tree_indent_markers = 1 g.nvim_tree_hide_dotfiles = 1 g.nvim_tree_git_hl = 1 g.nvim_tree_root_folder_modifier = ":~" g.nvim_tree_allow_resize = 1 g.nvim_tree_show_icons = { git = 1, folders = 1, files = 1 } g.nvim_tree_icons = { default = '', symlink = '', git = { unstaged = "", staged = "✓", unmerged = "", renamed = "", untracked = "", deleted = "", ignored = "" }, folder = { default = "", open = "", empty = "", empty_open = "", symlink = "", symlink_open = "", }, lsp = { hint = "", info = "", warning = "", error = "", } } -- hide line numbers , statusline in specific buffers! vim.api.nvim_exec( [[ au BufEnter term://* setlocal nonumber au BufEnter,BufWinEnter,WinEnter,CmdwinEnter * if bufname('%') == "NvimTree" | set laststatus=0 | else | set laststatus=2 | endif au BufEnter term://* set laststatus=0 ]], false ) end return M
function bitflag(address, bit) return { address = address, bit = bit } end
local module = {async = true} local common = game:GetService('ReplicatedStorage').Common local effects = require(common.Gui.Effects) local fader = require(common.Fade) local phases = { require(script.Assets), require(script.Data), } local loaded = Instance.new('BindableEvent') local total = #phases local finished = false local phase = 0 local gui local function Destroy() gui:Destroy() end local function Finish() finished = true loaded:Fire() local tween = fader.Fade(gui, 1, TweenInfo.new(2)) tween.Completed:Wait() Destroy() end local function AllowSkip() if finished then return end local button = gui:WaitForChild('Skip') local connection button.Visible = true effects.Start(button) connection = button.Activated:Connect(function() connection:Disconnect() button.Active = false Finish() end) end function module.Start(_, hud) if finished then return end gui = hud:WaitForChild('Loading') gui.Visible = true for _, content in ipairs(phases) do local function Execute() content.Start(gui) phase += 1 if phase == total then Finish() end if content.mandatory then task.delay(15, AllowSkip) end end task.spawn(Execute) end return finished or loaded.Event:Wait() end return module
local Cell = require 'src/ConwaysGameOfLife/Cell' local life_state = require 'src/ConwaysGameOfLife/life_state_enum' local function table_length(t) local count = 0 for _ in pairs(t) do count = count + 1 end return count end local function get_number_of_live_neighbors_in_col(state, row, col) if col >= 1 and col <= table_length(state[row]) then return state[row][col] end return 0 end local function get_number_of_live_neighbors_in_row(state, row, col) local live_neighbors = 0 if row >= 1 and row <= table_length(state) then live_neighbors = live_neighbors + get_number_of_live_neighbors_in_col(state, row, col - 1) live_neighbors = live_neighbors + state[row][col] live_neighbors = live_neighbors + get_number_of_live_neighbors_in_col(state, row, col + 1) end return live_neighbors end local function get_number_of_alive_neighbors(state, row, col) local live_neighbors = 0 live_neighbors = live_neighbors + get_number_of_live_neighbors_in_row(state, row - 1, col) live_neighbors = live_neighbors + get_number_of_live_neighbors_in_row(state, row + 1, col) live_neighbors = live_neighbors + get_number_of_live_neighbors_in_col(state, row, col - 1) live_neighbors = live_neighbors + get_number_of_live_neighbors_in_col(state, row, col + 1) return live_neighbors end local function update(instance) local state = instance:get_state() for row_index, row in ipairs(instance._private.grid) do local _row = {} for column_index, cell in ipairs(row) do local number_of_alive_neighbors = get_number_of_alive_neighbors(state, row_index, column_index) cell:update(number_of_alive_neighbors) end end end local function get_state(instance) local grid_state = {} for _, row in ipairs(instance._private.grid) do local _row = {} for _, cell in ipairs(row) do table.insert(_row, cell:get_state()) end table.insert(grid_state, _row) end return grid_state end return function(_grid) local grid = {} for _, row in ipairs(_grid) do local _row = {} for _, state in ipairs(row) do table.insert(_row, Cell(state)) end table.insert(grid, _row) end return { get_state = get_state, update = update, _private = { grid = grid, } } end