content
stringlengths
5
1.05M
window = Window:new(VideoMode:new(800, 600), "SunWhysEngine") event = Event:new() gameManager = GameManager:new() StartMenu = Scenes:new("StartMenu", -- Init function function() background = Sprites:new(window, "StartMenuBackground.png", 0, 0) end, -- Render function function() background:draw() end, -- Update function function() while (window:event(event)) do if (event.type == EventType.Close or event.key.code == Keyboard.Escape) then window:close() gameManager:close() end if (event.type == EventType.KeyPressed) then if (event.key.code == Keyboard.Space) then gameManager:goToScene("GamePlay") end end end end ) GamePlay = Scenes:new("GamePlay", -- Init function function () physics = Physics:new() ball = Sprites:new(window, "ball.png", 400-49/2, 300-49/2) ballTest = Sprites:new(window, "ball.png", 400-49/2, 300-49/2) left_racket = Sprites:new(window, "left-racket.png", 30, 300) right_racket = Sprites:new(window, "right-racket.png", 770-37, 310) LDownPressed = false RDownPressed = false LUpPressed = false RDownPressed = false racketSpeed = 5 -- math.randomseed() ballDirection = math.rad(math.random(-10, 10)) ballSpeed = 3 end, -- Render function () ball:draw() left_racket:draw() right_racket:draw() -- ballTest:draw() end, -- Update function (dt) while (window:event(event)) do if (event.type == EventType.Close or event.key.code == Keyboard.Escape) then window:close() gameManager:close() end if (event.type == EventType.KeyPressed) then if (event.key.code == Keyboard.S) then LDownPressed = true elseif (event.key.code == Keyboard.Z) then LUpPressed = true elseif (event.key.code == Keyboard.K) then RDownPressed = true elseif (event.key.code == Keyboard.I) then RUpPressed = true end end if (event.type == EventType.KeyReleased) then if (event.key.code == Keyboard.S) then LDownPressed = false elseif (event.key.code == Keyboard.Z) then LUpPressed = false elseif (event.key.code == Keyboard.K) then RDownPressed = false elseif (event.key.code == Keyboard.I) then RUpPressed = false end end end if (LDownPressed) then left_racket.y = left_racket.y+racketSpeed*dt elseif (LUpPressed) then left_racket.y = left_racket.y-racketSpeed*dt end if (RDownPressed) then right_racket.y = right_racket.y+racketSpeed*dt elseif (RUpPressed) then right_racket.y = right_racket.y-racketSpeed*dt end ball.x = ball.x+math.cos(ballDirection)*ballSpeed*dt ball.y = ball.y+math.sin(ballDirection)*ballSpeed*dt -- Collision detection -- The top wall if (ball.y<0) then print (ballDirection) ballDirection = math.pi*2-ballDirection end -- The bottom wall if (ball.y+49>600) then print (ballDirection) ballDirection = math.pi*2-ballDirection end if (physics:collide(ball, right_racket)) then factor = right_racket.y+64-(ball.y+25) ballDirection = math.pi+factor*0.01 ball.x = ball.x+math.cos(ballDirection)*ballSpeed ball.y = ball.y+math.sin(ballDirection)*ballSpeed end if (physics:collide(ball, left_racket)) then factor = left_racket.y+64-(ball.y+25) ballDirection = factor*-0.01 ball.x = ball.x+math.cos(ballDirection)*ballSpeed ball.y = ball.y+math.sin(ballDirection)*ballSpeed end while (ballDirection>math.pi*2) do ballDirection = ballDirection-math.pi*2 end while (ballDirection<0) do ballDirection = ballDirection+math.pi*2 end if (ball.x>800 or ball.x<0) then ball.x = 400-49/2 ball.y = 300-49/2 ballDirection = 0 end end ) gameManager:push(GamePlay) gameManager:push(StartMenu) gameManager:goToScene("StartMenu") function startGame() while (window:open()) do gameManager:update() window:clear(Color.Black) gameManager:render() window:display() end end
satellites = {} lg = love.graphics require "fixcolor" function satellites:load(args) satellitesheet = lg.newImage("assets/satellitesheet.png") -- load satellite sprite sheet into memory shockblast = lg.newImage("assets/shockblast.png") baseValues:loadSatellites(args) shockPulse = love.graphics.newParticleSystem(shockblast, 99999) shockPulse:setParticleLifetime(0.5) shockPulse:setSizeVariation(0) shockPulse:setSizes(0, 5) shockPulse:setColors(255, 255, 255, 100, 255, 255, 255, 0) -- Fade to transparency. end function satellites:update(dt) -- update each satellite's position for i,object in pairs(planet) do -- each satellite is nested within a table nested within each planet for j, sat in pairs(object.assoc_sats) do sat.dir = sat.dir + (((math.pi * 2) / sat.speed) * dt) -- increment the satellite's angle relative to the planet -- update the satellite's position based on its orbital position sat.x = object.x + angle_utils:lengthdir_x(sat.dir, object.selfOrbit) sat.y = object.y + angle_utils:lengthdir_y(sat.dir, object.selfOrbit) sat.nearestEnemy = nil local k = 1 while k <= #activeEnemies do local oEnemy = activeEnemies[k] if angle_utils:pointdist(object.x, object.y, oEnemy.x, oEnemy.y) <= object.targetRange then if sat.nearestEnemy ~= nil then if angle_utils:pointdist(sat.x, sat.y, oEnemy.x, oEnemy.y) < angle_utils:pointdist(sat.x, sat.y, sat.nearestEnemy.x, sat.nearestEnemy.y) then sat.nearestEnemy = oEnemy end else sat.nearestEnemy = oEnemy end end k = k + 1 end if sat.nearestEnemy ~= nil and sat.type == "laser" then sat.timer = sat.timer + dt if sat.timer >= laserFireRate then sat.nearestEnemy.health = sat.nearestEnemy.health - laserDamage sat.timer = 0 end -- rotate towards target enemy sat.r = math.rad(math.deg(angle_utils:clampdir(math.atan2(sat.nearestEnemy.x-sat.x, sat.y-sat.nearestEnemy.y)))) if sat.initialPos then sat.initialPos = false end elseif sat.type == "shock" then sat.timer = sat.timer+dt if sat.timer >= shockFireRate then for p,enemyInRange in pairs(activeEnemies) do if angle_utils:pointdist(enemyInRange.x, enemyInRange.y, object.x, object.y) <= object.targetRange then enemyInRange.health = enemyInRange.health - shockDamage end end shockPulse:setPosition(object.x, object.y) shockPulse:setSizes(0, 4*object.scale) shockPulse:emit(1) sat.timer = 0 end end -- if no enemy has been in sight rotate towards planet if sat.initialPos then sat.r = sat.dir - math.rad(90) end end end shockPulse:update(dt) end function satellites:draw() lg.draw(shockPulse, 0, 0) for i,object in pairs(planet) do -- iterate through the satellites contained by each planet and draw it facing its rotation axis for j, sat in pairs(object.assoc_sats) do if sat.type == "shock" then lg.draw(satellitesheet, shockquad, sat.x, sat.y, sat.r, 0.3, 0.3, 255/2, 175) elseif sat.type == "laser" then if sat.nearestEnemy ~= nil then lg.push("all") fixcolor:setColor(109, 207, 246, 170) lg.setLineWidth(5) lg.line(sat.x, sat.y, sat.nearestEnemy.x, sat.nearestEnemy.y) lg.pop() end lg.draw(satellitesheet, laserquad, sat.x, sat.y, sat.r, 0.3, 0.3, 255/2, 175) end end end end
-- Last update GlitterStorm @ Azralon on Feb,22th,2015 if GetLocale() ~= "ptBR" then return end local L ----------------------- -- Drov the Ruiner -- ----------------------- L= DBM:GetModLocalization(1291) ----------------------- -- Tarlna the Ageless -- ----------------------- L= DBM:GetModLocalization(1211) -------------- -- Rukhmar -- -------------- L= DBM:GetModLocalization(1262)
name = "Stinky in Here" description = "Adds a compost pile to the game. Make the best out of your spoiled food!" author = "s1m13" version = "0.4.0" api_version = 6 dont_starve_compatible = true reign_of_giants_compatible = true shipwrecked_compatible = false icon_atlas = "stinkyinhere.xml" icon = "stinkyinhere.tex" forumthread = "/files/file/435-stinky-in-here/"
-- Pipeline -- Ported from: https://github.com/dysinger/nanomsg-examples local usage = [[ USAGE: luajit pipeline.lua node0 <URL> luajit pipeline.lua node1 <URL> <MSG> EXAMPLE: luajit pipeline.lua node0 'ipc:///tmp/pipeline.ipc' & node0=$! && sleep 1 luajit pipeline.lua node1 'ipc:///tmp/pipeline.ipc' 'Hello, World!' luajit pipeline.lua node1 'ipc:///tmp/pipeline.ipc' 'Goodbye.' kill $node0 ]] local nn = require "nanomsg-ffi" local node0 = function(url) local sock, err = nn.socket( nn.PULL ) assert( sock, nn.strerror(err) ) local cid, err = sock:bind( url ) assert( cid, nn.strerror(err) ) while true do local msg, err = sock:recv_zc() assert( msg, nn.strerror(err) ) print(string.format("NODE0: RECEIVED \"%s\"", msg:tostring())) msg:free() end end local node1 = function(url, msg) local sock, err = nn.socket( nn.PUSH ) assert( sock, nn.strerror(err) ) local eid, err = sock:connect( url ) assert( eid, nn.strerror(err) ) print(string.format("NODE1: SENDING \"%s\"", msg)) assert( sock:send( msg, #msg ) == #msg ) sock:shutdown(0) end if (arg[1] == "node0") and (#arg == 2) then node0(arg[2]) elseif (arg[1] == "node1") and (#arg == 3) then node1(arg[2], arg[3]) else io.stderr:write(usage) end
function LoadScript(scene, scriptPath) scene.stack = {} scene.definitions = {} scene.type = "" local stack = scene.stack local definitions = {} local queuedSpeak = nil local queuedQuietSpeak = nil local queuedInterruptedSpeak = nil local queuedThink = nil local queuedTypewriter = nil local witnessQueue = nil local choiceQueue = nil local fakeChoiceQueue = nil local invMenuQueue = nil local evidenceAddQueue = nil local examinationQueue = nil for line in love.filesystem.lines(scriptPath) do if line == nil then canRead = false else local lineParts = DisectLine(line) local canExecuteLine = true if witnessQueue ~= nil then if #lineParts > 0 then for i=1, #lineParts do table.insert(witnessQueue, lineParts[i]) end else AddToStack(stack, NewWitnessEvent(witnessQueue), lineParts) witnessQueue = nil end canExecuteLine = false end if choiceQueue ~= nil and canExecuteLine then if #lineParts > 0 and lineParts[1] ~= "END_CHOICE" then for i=1, #lineParts do table.insert(choiceQueue, lineParts[i]) end else AddToStack(stack, NewChoiceEvent(choiceQueue), lineParts) choiceQueue = nil end canExecuteLine = false end if fakeChoiceQueue ~= nil and canExecuteLine then if #lineParts > 0 and lineParts[1] ~= "END_CHOICE" then for i=1, #lineParts do table.insert(fakeChoiceQueue, lineParts[i]) end else AddToStack(stack, NewFakeChoiceEvent(fakeChoiceQueue), lineParts) fakeChoiceQueue = nil end canExecuteLine = false end if invMenuQueue ~= nil and canExecuteLine then if #lineParts > 0 and lineParts[1] ~= "END_INVESTIGATION_MENU" then for i=1, #lineParts do table.insert(invMenuQueue, lineParts[i]) end else AddToStack(stack, NewInvestigationMenuEvent(invMenuQueue), lineParts) invMenuQueue = nil end canExecuteLine = false end if examinationQueue ~= nil and canExecuteLine then if #lineParts > 0 and lineParts[1] ~= "END_EXAMINATION" then for i=1, #lineParts do table.insert(examinationQueue, lineParts[i]) end else AddToStack(stack, NewExamineEvent(examinationQueue), lineParts) examinationQueue = nil end canExecuteLine = false end if canExecuteLine and queuedSpeak ~= nil then AddToStack(stack, NewSpeakEvent(queuedSpeak[1], lineParts[1], queuedSpeak[2], queuedSpeak[3]), {"SPEAK "..queuedSpeak[1], unpack(lineParts)}) queuedSpeak = nil canExecuteLine = false end if canExecuteLine and queuedQuietSpeak ~= nil then AddToStack(stack, NewQuietSpeakEvent(queuedQuietSpeak[1], lineParts[1], queuedQuietSpeak[2], queuedQuietSpeak[3]), {"SPEAK_QUIET "..queuedQuietSpeak[1], unpack(lineParts)}) queuedQuietSpeak = nil canExecuteLine = false end if canExecuteLine and queuedInterruptedSpeak ~= nil then AddToStack(stack, NewInterruptedSpeakEvent(queuedInterruptedSpeak[1], lineParts[1], queuedInterruptedSpeak[2], queuedInterruptedSpeak[3]), {"queuedInterruptedSpeak "..queuedInterruptedSpeak[1], unpack(lineParts)}) queuedInterruptedSpeak = nil canExecuteLine = false end if canExecuteLine and queuedThink ~= nil then AddToStack(stack, NewThinkEvent(queuedThink[1], lineParts[1], queuedThink[2], queuedThink[3]), {"THINK "..queuedThink[1], unpack(lineParts)}) queuedThink = nil canExecuteLine = false end if canExecuteLine and queuedTypewriter ~= nil then AddToStack(stack, NewTypeWriterEvent(lineParts[1]), {"TYPEWRITER", unpack(lineParts)}) queuedTypewriter = nil canExecuteLine = false end if canExecuteLine and evidenceAddQueue ~= nil then AddToStack(stack, NewAddToCourtRecordAnimationEvent(lineParts[1], evidenceAddQueue[1]), {"COURT_RECORD_ADD EVIDENCE "..evidenceAddQueue[1], unpack(lineParts)}) evidenceAddQueue = nil canExecuteLine = false end if canExecuteLine then if lineParts[1] == "CHARACTER_INITIALIZE" then AddToStack(stack, NewCharInitEvent(lineParts[2], lineParts[3], lineParts[4]), lineParts) end if lineParts[1] == "CHARACTER_LOCATION" then AddToStack(stack, NewCharLocationEvent(lineParts[2], lineParts[3]), lineParts) end if lineParts[1] == "EVIDENCE_INITIALIZE" then AddToStack(stack, NewEvidenceInitEvent(lineParts[2], lineParts[3], lineParts[4], lineParts[5]), lineParts) end if lineParts[1] == "PROFILE_INITIALIZE" then -- 2: internal name, 3: in-game title (character name), 4: age, 5: description, 6: profile icon AddToStack(stack, NewProfileInitEvent(lineParts[2], lineParts[3], lineParts[4], lineParts[5], lineParts[6]), lineParts) end if lineParts[1] == "COURT_RECORD_ADD" then -- 2: court record item type (evidence or profile), 3: internal name of initialized item AddToStack(stack, NewCourtRecordAddEvent(lineParts[2], lineParts[3]), lineParts) end if lineParts[1] == "COURT_RECORD_ADD_ANIMATION" then AddToStack(stack, NewPlaySoundEvent("EvidenceShoop"), lineParts) AddToStack(stack, NewCourtRecordAddEvent(lineParts[2], lineParts[3]), lineParts) AddToStack(stack, NewAddToCourtRecordAnimationEvent(lineParts[4]), lineParts) end if lineParts[1] == "SET_SCENE_TYPE" then scene.type = lineParts[2] end if lineParts[1] == "END_SCENE" then AddToStack(stack, NewSceneEndEvent(), lineParts) end if lineParts[1] == "DEFINE" then scene.definitions[lineParts[2]] = {} stack = scene.definitions[lineParts[2]] end if lineParts[1] == "END_DEFINE" then stack = scene.stack end if lineParts[1] == "JUMP" then AddToStack(stack, NewClearExecuteDefinitionEvent(lineParts[2]), lineParts) end if lineParts[1] == "JUMPCUT" then AddToStack(stack, NewCutToEvent(lineParts[2]), lineParts) end if lineParts[1] == "PAN" then AddToStack(stack, NewPanEvent(lineParts[2], lineParts[3]), lineParts) AddToStack(stack, NewCutToEvent(lineParts[3]), lineParts) end if lineParts[1] == "POSE" then AddToStack(stack, NewPoseEvent(lineParts[2], lineParts[3]), lineParts) end if lineParts[1] == "WAIT" then AddToStack(stack, NewWaitEvent(lineParts[2])) end if lineParts[1] == "ANIMATION" then if #lineParts == 4 then AddToStack(stack, NewAnimationEvent(lineParts[2], lineParts[3], lineParts[4]), lineParts) else AddToStack(stack, NewAnimationEvent(lineParts[2], lineParts[3]), lineParts) end end if lineParts[1] == "PLAY_MUSIC" then AddToStack(stack, NewPlayMusicEvent(lineParts[2]), lineParts) end if lineParts[1] == "STOP_MUSIC" then AddToStack(stack, NewStopMusicEvent(), lineParts) end if lineParts[1] == "SFX" then AddToStack(stack, NewPlaySoundEvent(lineParts[2]), lineParts) end if lineParts[1] == "ISSUE_PENALTY" then AddToStack(stack, NewIssuePenaltyEvent(), lineParts) end if lineParts[1] == "GAME_OVER" then AddToStack(stack, NewGameOverEvent(), lineParts) end if lineParts[1] == "SHOUT" then AddToStack(stack, NewShoutEvent(lineParts[2], lineParts[3]), lineParts) end if lineParts[1] == "WIDESHOT" then AddToStack(stack, NewWideShotEvent(), lineParts) end if lineParts[1] == "GAVEL" then AddToStack(stack, NewGavelEvent(), lineParts) end if lineParts[1] == "SHOW" then AddToStack(stack, NewShowEvent(lineParts[2], lineParts[3]), lineParts) end if lineParts[1] == "FADE_TO_BLACK" then AddToStack(stack, NewFadeToBlackEvent(), lineParts) end if lineParts[1] == "FADE_TO_WHITE" then AddToStack(stack, NewFadeToWhiteEvent(), lineParts) end if lineParts[1] == "FADE_IN" then AddToStack(stack, NewCutToEvent("BLACK_SCREEN"), lineParts) AddToStack(stack, NewWaitEvent(lineParts[2]), lineParts) AddToStack(stack, NewCutToEvent(lineParts[3]), lineParts) AddToStack(stack, NewFadeInEvent(), lineParts) end --if lineParts[1] == "CROSSFADE" then -- AddToStack(stack, NewCrossFadeEvent(lineParts[2]), lineParts) --end if lineParts[1] == "SCREEN_SHAKE" then AddToStack(stack, NewScreenShakeEvent(), lineParts) end if lineParts[1] == "WITNESS_EVENT" then witnessQueue = {lineParts[2], lineParts[3], lineParts[4]} end if lineParts[1] == "CHOICE" then choiceQueue = {} end if lineParts[1] == "FAKE_CHOICE" then fakeChoiceQueue = {} end if lineParts[1] == "INVESTIGATION_MENU" then invMenuQueue = {} end if lineParts[1] == "EXAMINE" then examinationQueue = {} end if lineParts[1] == "SET_FLAG" then AddToStack(stack, NewSetFlagEvent(lineParts[2], lineParts[3]), lineParts) end if lineParts[1] == "IF" and lineParts[3] == "IS" and lineParts[5] == "THEN" then AddToStack(stack, NewIfEvent(lineParts[2], lineParts[4], lineParts[6]), lineParts) end if lineParts[1] == "SPEAK" then queuedSpeak = {lineParts[2], "literal", lineParts[3]} end if lineParts[1] == "SPEAK_QUIET" then queuedQuietSpeak = {lineParts[2], "literal", lineParts[3]} end if lineParts[1] == "THINK" then queuedThink = {lineParts[2], "literal", nil} end if lineParts[1] == "SPEAK_FROM" then AddToStack(stack, NewCutToEvent(lineParts[2]), {"SPEAK_FROM", unpack(lineParts)}) queuedSpeak = {lineParts[2], "location", lineParts[3]} end if lineParts[1] == "THINK_FROM" then AddToStack(stack, NewCutToEvent(lineParts[2]), {"THINK_FROM", unpack(lineParts)}) queuedThink = {lineParts[2], "location", nil} end if lineParts[1] == "TYPEWRITER" then queuedTypewriter = {} end if lineParts[1] == "CLEAR_LOCATION" then AddToStack(stack, NewClearLocationEvent(lineParts[2]), lineParts) end if lineParts[1] == "HIDE_TEXT" then AddToStack(stack, NewHideTextEvent(lineParts[2]), lineParts) end if lineParts[1] == "INTERRUPTED_SPEAK" then queuedInterruptedSpeak = {lineParts[2], "literal", lineParts[3]} end end end end end function DisectLine(line) local words = {} local isDialogue = false local isComment = false local wordBuild = "" local openQuote = true local i = 1 while i <= #line do local thisChar = string.sub(line, i,i) local thisDoubleChar = string.sub(line, i,i+1) local canAddToWord = true if thisDoubleChar == "//" then isComment = true end if isComment then canAddToWord = false end if thisDoubleChar == "$q" then canAddToWord = false if openQuote then -- backtick corresponds to open quotation marks in the font image wordBuild = wordBuild .. '`' else -- quotation marks correspond to closed quotation marks in the font image wordBuild = wordBuild .. '"' end openQuote = not openQuote i=i+1 end if canAddToWord and thisChar == '"' then canAddToWord = false if isDialogue then table.insert(words, wordBuild) wordBuild = "" end isDialogue = not isDialogue end if canAddToWord and not isDialogue and thisChar == " " then canAddToWord = false if #wordBuild > 0 then table.insert(words, wordBuild) wordBuild = "" end end if canAddToWord then wordBuild = wordBuild .. thisChar end i=i+1 end if #wordBuild > 0 then table.insert(words, wordBuild) wordBuild = "" end return words end function AddToStack(stack, event, lineParts) -- Save just enough info for us to return to this -- state if we choose to skip around the game local stackContext = { lineParts = lineParts, event = event } table.insert(stack, stackContext) end
slot0 = class("USDefTaskWindowView", import("...base.BaseSubView")) slot0.Load = function (slot0) slot0._tf = findTF(slot0._parentTf, "USDefTaskWindow") slot0._go = go(slot0._tf) pg.DelegateInfo.New(slot0) slot0:OnInit() end slot0.Destroy = function (slot0) slot0:Hide() end slot0.OnInit = function (slot0) slot0:initData() slot0:initUI() slot0:updateProgress() slot0:updateTaskList() slot0:Show() end slot0.OnDestroy = function (slot0) return end slot0.initData = function (slot0) slot0.taskIDList = Clone(pg.task_data_template[slot0.contextData:getConfig("config_client")[1]].target_id) slot0.taskProxy = getProxy(TaskProxy) slot0.taskVOList = {} for slot5, slot6 in ipairs(slot0.taskIDList) do table.insert(slot0.taskVOList, slot0.taskProxy:getTaskVO(slot6)) end end slot0.initUI = function (slot0) slot0.bg = slot0:findTF("BG") slot0.curNumTextTF = slot0:findTF("ProgressPanel/CurNumText") slot0.totalNumText = slot0:findTF("ProgressPanel/TotalNumText") slot0.taskTpl = slot0:findTF("TaskTpl") slot0.taskContainer = slot0:findTF("TaskList/Viewport/Content") slot0.taskList = UIItemList.New(slot0.taskContainer, slot0.taskTpl) onButton(slot0, slot0.bg, function () slot0:Destroy() end, SFX_CANCEL) end slot0.updateProgress = function (slot0) slot1 = #slot0.taskIDList slot2 = 0 for slot6, slot7 in ipairs(slot0.taskVOList) do if slot7:getTaskStatus() >= 1 then slot2 = slot2 + 1 end end setText(slot0.curNumTextTF, string.format("%2d", slot2)) setText(slot0.totalNumText, string.format("%2d", slot1)) end slot0.updateTaskList = function (slot0) slot0.taskList:make(function (slot0, slot1, slot2) if slot0 == UIItemList.EventUpdate then slot7 = slot0:findTF("ItemBG/Icon", slot2) slot8 = slot0:findTF("ItemBG/Finished", slot2) setText(slot4, string.format("%02d", slot1)) setText(slot5, "TASK-" .. string.format("%02d", slot1 + 1)) setText(slot6, slot9) if not pg.ship_data_statistics[slot0.taskVOList[slot1 + 1].getConfig(slot3, "target_id_for_client")] then slot10 = 205054 end LoadImageSpriteAsync("SquareIcon/" .. slot12, slot7) setActive(slot8, slot3:getTaskStatus() >= 1) end end) slot0.taskList.align(slot1, #slot0.taskIDList) end return slot0
local device = require "miio.device" local protocol = require "miio.protocol" local util = require "util" local plugin = {} local logger = log.getLogger("miio.plugin") local priv = { pending = {}, devices = {} } ---@class MiioDeviceConf:table Miio device configuration. --- ---@field name string Accessory name. ---@field addr string Device address. ---@field token string Device token. ---Initialize plugin. ---@param conf any Plugin configuration. ---@param report fun(plugin: string, accessory: HapAccessory) Report accessory to **core**. ---@return boolean status true on success, false on failure. function plugin.init(conf, report) protocol.init() priv.report = report logger:info("Initialized.") return true end ---Deinitialize plugin. function plugin.deinit() priv.report = nil priv.pending = {} priv.devices = {} protocol.deinit() logger:info("Deinitialized.") end ---Whether the accessory is waiting to be generated. ---@return boolean status function plugin.isPending() return util.isEmptyTable(priv.pending) == false end ---Report bridged accessory. ---@param obj MiioDevice Device object. ---@param accessory? HapAccessory Bridged accessory. local function _report(obj, addr, accessory) priv.pending[addr] = nil if not accessory then priv.devices[addr] = nil end priv.report("miio", accessory) end ---Generate accessory via configuration. ---@param conf MiioDeviceConf Device configuration. ---@return nil function plugin.gen(conf) local obj = device.create(function (self, info, conf) if not info then logger:error("Failed to create device.") _report(self, conf.addr) return end -- Get product module, using pcall to catch exception. local success, result = pcall(require, "miio." .. info.model) if success == false then logger:error("Cannot found the product.") logger:error(result) _report(self, conf.addr) return end local accessory = result.gen(self, info, conf) if not accessory then logger:error("Failed to generate accessory.") _report(self, conf.addr) return end _report(self, conf.addr, accessory) end, conf.addr, util.hex2bin(conf.token), conf) if obj then priv.pending[conf.addr] = true priv.devices[conf.addr] = obj end return nil end return plugin
name = "wordle" author = "ricky thomson" version = "0.1" default_width = 1024 default_height = 768 function love.conf(t) t.identity = "wordle" t.version = "11.3" t.window.title = name t.window.width = default_width t.window.height = default_height t.window.minwidth = default_width t.window.minheight = default_height t.modules.joystick = false t.modules.physics = false t.modules.touch = false t.modules.video = false t.window.msaa = 0 t.window.fsaa = 0 t.window.display = 1 t.window.resizable = false t.window.vsync = false t.window.fullscreen = false end
module 'mock' -------------------------------------------------------------------- CLASS: ControlVariable () :MODEL{} function ControlVariable:__init() self.name = 'name' self.desc = '' self.vtype = 'number' --'b' self.value = 0 end function ControlVariable:initFromVar( v ) local tt = type( v ) if tt == 'boolean' then return self:initBoolean( v ) else local n = tonumber( v ) if not n then return self:initString( v ) end return self:initNumber( n ) end end function ControlVariable:initBoolean( b ) self.vtype = 'boolean' self.value = b and true or false end function ControlVariable:initInt( i ) self.vtype = 'int' self.value = math.floor( tonumber(i) or 0 ) end function ControlVariable:initNumber( i ) self.vtype = 'number' self.value = tonumber(i) end function ControlVariable:initString( s ) self.vtype = 'string' self.value = tostring( s ) or 'none' end function ControlVariable:set( v ) local t = self.vtype if t == 'number' then self.value = tonumber( v ) or 0 elseif t == 'int' then self.value =math.floor( tonumber( v ) or 0 ) elseif t == 'boolean' then local tt = type( v ) if tt == 'boolean' then self.value = v elseif tt == 'number' then self.value = n ~= 0 elseif tt == 'string' then local n = tonumber( v ) if n then self.value = n ~= 0 else v = v:upper() if v == 'FALSE' or v == 'F' or v:trim() == '' then self.value = false else self.value = true end end end elseif t == 'string' then self.value = tostring( v ) end end function ControlVariable:get() return self.value end function ControlVariable:setDesc( desc ) self.desc = desc end function ControlVariable:setName( name ) self.name = name end function ControlVariable:save() return { name = self.name, desc = self.desc, value = self.value, vtype = self.vtype } end function ControlVariable:load( data ) self.name = data.name self.desc = data.desc self.vtype = data.vtype self:set( data.value ) end -------------------------------------------------------------------- CLASS: ControlVariableSet () :MODEL{ } function ControlVariableSet:__init() self.variables = {} self.variableMap = {} self.changingHistory = {} end function ControlVariableSet:clearAccCache() self.variableMap = {} end function ControlVariableSet:findVar( name ) local var = self.variableMap[ name ] if var then return var end for i, var in ipairs( self.variables ) do if var.name == name then self.variableMap[ name ] = var return var end end end function ControlVariableSet:get( name, default ) local var = self:findVar( name ) if not var then return default end return var:get() end function ControlVariableSet:set( name, value ) local var = self:findVar( name ) if not var then _error( 'control variable not found:', name ) return end var:set( value ) -- print( var:get(), var.vtype, var.value, value ) end function ControlVariableSet:addVar( name, vtype ) local var = ControlVariable() if vtype == 'boolean' then var:initBoolean( false ) elseif vtype == 'int' then var:initInt( 0 ) elseif vtype == 'string' then var:initString( 'none' ) else var:initNumber( 0 ) end var.name = name table.insert( self.variables, var ) return var end function ControlVariableSet:removeVar( var ) local idx = table.index( self.variables, var ) if not idx then return end table.remove( self.variables, idx ) if self.variableMap[ var.name ] == var then self.variableMap[ var.name ] = nil end end function ControlVariableSet:clear() self.variableMap = {} self.variables = {} end function ControlVariableSet:__serialize() local output = {} for i, var in ipairs( self.variables ) do output[ i ] = var:save() end return output end function ControlVariableSet:__deserialize( data ) local variables = {} for i, varData in ipairs( data ) do local var = ControlVariable() var:load( varData ) variables[ i ] = var end self.variables = variables end -------------------------------------------------------------------- --Global Object Related -------------------------------------------------------------------- registerGlobalObject( 'ControlVariableSet', ControlVariableSet ) local function splitVariableNS( id ) local pos = string.findlast( id, '%.' ) if not pos then return nil, id end local ns = id:sub( 1, pos-1 ) local base = id:sub( pos+1, -1 ) return ns, base end function getControlVariableSet( id ) local db = getGlobalObject( id ) if db and db:isInstance( ControlVariableSet ) then return db end return nil end function getControlVariable( fullId, default ) local ns, base = splitVariableNS( fullId ) if not ns then return _error( 'no control variable set specified' ) end local db = getControlVariableSet( ns ) if db then return db:get( base, default ) else _error( 'control variable set not found', ns ) end return nil end function setControlVariable( fullId, value ) local ns, base = splitVariableNS( fullId ) if not ns then return _error( 'no control variable set specified' ) end local db = getControlVariableSet( ns ) if db then return db:set( base, value ) else _error( 'control variable set not found', ns ) end return nil end
function DSkybreaker_OnEnterCombat(Unit,Event) Unit:FullCastSpellOnTarget(38858,Unit:GetClosestPlayer()) Unit:RegisterEvent("DSkybreaker_Spell1", 24000, 0) Unit:RegisterEvent("DSkybreaker_Spell2", 11000, 0) end function DSkybreaker_Spell1(Unit,Event) Unit:FullCastSpellOnTarget(38861,Unit:GetClosestPlayer()) end function DSkybreaker_Spell2(Unit,Event) Unit:FullCastSpellOnTarget(41448,Unit:GetClosestPlayer()) end function DSkybreaker_OnLeaveCombat(Unit,Event) Unit:RemoveEvents() end function DSkybreaker_OnDied(Unit,Event) Unit:RemoveEvents() end RegisterUnitEvent(22274, 1, "DSkybreaker_OnEnterCombat") RegisterUnitEvent(22274, 2, "DSkybreaker_OnLeaveCombat") RegisterUnitEvent(22274, 4, "DSkybreaker_OnDied")
if bobmods.config.plates.CheaperSteel == true then -- Ignore cheaper steel setting data.raw.recipe["steel-plate"].energy_required = 27.5 data.raw.recipe["steel-plate"].ingredients = {{"iron-plate", 10}} end
--MoveCurve --Move/curve_Attack1 curve_Attack1 return { filePath = "Move/curve_Attack1", startTime = Fixed64(0) --[[0]], startRealTime = Fixed64(0) --[[0]], endTime = Fixed64(33554432) --[[32]], endRealTime = Fixed64(335544) --[[0.32]], curve = { [1] = { time = 0 --[[0]], value = 0 --[[0]], inTangent = 2097152 --[[2]], outTangent = 2097152 --[[2]], }, [2] = { time = 1048576 --[[1]], value = 2097152 --[[2]], inTangent = 2097152 --[[2]], outTangent = 2097152 --[[2]], }, }, }
--[[ LuCI - Lua Configuration Interface - Shairport support Copyright 2014 Álvaro Fernández Rojas <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.controller.shairport", package.seeall) function index() if not nixio.fs.access("/etc/config/shairport") then return end local page = entry({"admin", "services", "shairport"}, cbi("shairport"), _("Shairport")) page.dependent = true end
-- NetHack 3.7 sokoban.des $NHDT-Date: 1432512784 2015/05/25 00:13:04 $ $NHDT-Branch: master $:$NHDT-Revision: 1.13 $ -- Copyright (c) 1998-1999 by Kevin Hugo -- NetHack may be freely redistributed. See license for details. -- des.level_init({ style = "solidfill", fg = " " }); des.level_flags("mazelevel", "noteleport", "premapped", "solidify"); des.map([[ -------------------- |..................| |.....------------.| --.----..--------|.| |.--...........||.| ---....-.....|...||.| |.....-..|...-----|.| |.-......|.--------+| |..-.--.....| |.....| --......--.-| |.....| --.........| |.....| ---..---..| |.....| ---- |..| |.....| ---- |.....| |.....| ------- ]]); des.stair("down", 06,11) des.stair("up", 17,11) des.door("locked",19,07) des.region(selection.area(00,00,21,15), "lit") des.non_diggable(selection.area(00,00,21,15)) des.non_passwall(selection.area(00,00,21,15)) -- Boulders des.object("boulder",04,06) des.object("boulder",04,07) des.object("boulder",04,08) des.object("boulder",04,09) des.object("boulder",06,07) des.object("boulder",07,07) des.object("boulder",06,09) des.object("boulder",07,09) des.object("boulder",07,04) des.object("boulder",10,05) des.object("boulder",11,05) des.object("boulder",11,06) des.object("boulder",09,10) des.object("boulder",10,11) -- Traps des.trap("hole",07,01) des.trap("hole",08,01) des.trap("hole",09,01) des.trap("hole",10,01) des.trap("hole",11,01) des.trap("hole",12,01) des.trap("hole",13,01) des.trap("hole",14,01) des.trap("hole",15,01) des.trap("hole",16,01) des.trap("hole",17,01) des.trap("hole",18,01) -- Random objects des.object({ class = "%" }); des.object({ class = "%" }); des.object({ class = "%" }); des.object({ class = "%" }); des.object({ class = "=" }); des.object({ class = "/" }); -- Random monsters des.monster({x=16, y=9}) des.monster({x=18, y=9}) des.monster({x=18, y=12}) des.monster({x=16, y=12})
local ReplicatedStorage = game:GetService("ReplicatedStorage") local ServerStorage = game:GetService("ServerStorage") local lightsComponent = require(script.Parent:WaitForChild("Lights", 5)) local sirenComponent = require(script.Parent:WaitForChild("Sirens", 5)) local require = require(ReplicatedStorage:WaitForChild("Nevermore", 2)) local std = require("Std") local rq = std.rquery local ComponentBase = require("ComponentBase") local component = ComponentBase.new("ElsHud", {"elshud"}) function component._attachElsGuiToVehicleSeatOccupant(vehicleModel, occupantPlayer) local elsHud = ServerStorage:WaitForChild("UserInterfaces"):WaitForChild("ElsHud"):Clone() elsHud.Vehicle.Value = vehicleModel local elsButtons = ReplicatedStorage:WaitForChild("Equipment", 2):WaitForChild("ElsHudButtons"):Clone() elsButtons.Parent = elsHud elsHud.Parent = occupantPlayer.PlayerGui elsHud.ElsHudButtons.Disabled = false end function component._attachVehicleSeatHandlers(vehicleModel) local vehicleSeat = vehicleModel:WaitForChild("VehicleSeat") local seatOccupantChangedHandler = function(changedProperty) if changedProperty == "Occupant" and rq.GetPlayerDrivingVehicle(vehicleModel) ~= nil then local occupantPlayer = rq.GetPlayerDrivingVehicle(vehicleModel) component._attachElsGuiToVehicleSeatOccupant(vehicleModel, occupantPlayer) end end vehicleSeat.Changed:Connect(seatOccupantChangedHandler) end function component:Execute( gameObject ) self._attachVehicleSeatHandlers(gameObject) lightsComponent:TryExecute(gameObject) sirenComponent:TryExecute(gameObject) end return component
local MOTD_URL = "www.google.com" --Change URL here. local MOTD_ENABLE = true function GM:SetMOTD(url) MOTD_URL = url end function GM:EnableMOTD(boolean) MOTD_ENABLE = boolean end function GM:ReloadMOTD() if (!MOTD_ENABLE) then return end if (GM.MOTD) then GM.MOTD:OpenURL(MOTD_URL) GM.MOTD:SetVisible(true) end end hook.Add("InitPostEntity","GearFox_MOTD",function() if (!MOTD_ENABLE) then return end GM = GM or GAMEMODE GM.MOTD = vgui.Create("MBBrowser") GM.MOTD:SetTitle("Message of the Day") GM.MOTD:SetPos(100,100) GM.MOTD:SetSize(ScrW()-200,ScrH()-200) GM.MOTD:OpenURL(MOTD_URL) GM.MOTD:MakePopup() end)
local Window = {} function Window:resize(W, H) drystal.resize(W, H) drystal.boxBackground.w = W drystal.boxBackground.h = H EasyLD.window.w = W EasyLD.window.h = H end function Window:setTitle(title) drystal.set_title(title) end function Window:setFullscreen(bool) drystal.set_fullscreen(bool) end return Window
----------------------------------------------------------------------------------------- -- -- main.lua -- ----------------------------------------------------------------------------------------- -- Your code here -- Load the required libraries local assets = require('assets') local widget = require('widget') local composer = require( "composer" ) composer.gotoScene("menu", {effect = "fade", time = 500} ) -- Seed the random number generator. If we are going to use and math.random() -- ensures everytime to start the app with a new number math.randomseed( os.time() ) display.setStatusBar( display.HiddenStatusBar ) --Hide the status bar --display.setDefault( "background", 0.3, 0.3, 0.3 ) --Set the background color
--[[ This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:25' using the latest game version. NOTE: This file should only be used as IDE support; it should NOT be distributed with addons! **************************************************************************** CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC. **************************************************************************** ]] local GenericFooter = ZO_Object:Subclass() ZO_GAMEPAD_FOOTER_CONTROLS = { DATA1 = 1, DATA1HEADER = 2, DATA1LOADINGICON = 3, DATA2 = 4, DATA2HEADER = 5, DATA2LOADINGICON = 6, DATA3 = 7, DATA3HEADER = 8, DATA3LOADINGICON = 9, } local EMPTY_TABLE = {} -- Alias the control names to make the code less verbose and more readable. local DATA1 = ZO_GAMEPAD_FOOTER_CONTROLS.DATA1 local DATA1HEADER = ZO_GAMEPAD_FOOTER_CONTROLS.DATA1HEADER local DATA1LOADINGICON = ZO_GAMEPAD_FOOTER_CONTROLS.DATA1LOADINGICON local DATA2 = ZO_GAMEPAD_FOOTER_CONTROLS.DATA2 local DATA2HEADER = ZO_GAMEPAD_FOOTER_CONTROLS.DATA2HEADER local DATA2LOADINGICON = ZO_GAMEPAD_FOOTER_CONTROLS.DATA2LOADINGICON local DATA3 = ZO_GAMEPAD_FOOTER_CONTROLS.DATA3 local DATA3HEADER = ZO_GAMEPAD_FOOTER_CONTROLS.DATA3HEADER local DATA3LOADINGICON = ZO_GAMEPAD_FOOTER_CONTROLS.DATA3LOADINGICON function GenericFooter:New(...) local object = ZO_Object.New(self) object:Initialize(...) return object end function GenericFooter:Initialize(control) self.control = control self.controls = { [DATA1] = control:GetNamedChild("Data1"), [DATA1HEADER] = control:GetNamedChild("Data1Header"), [DATA1LOADINGICON] = control:GetNamedChild("Data1LoadingIcon"), [DATA2] = control:GetNamedChild("Data2"), [DATA2HEADER] = control:GetNamedChild("Data2Header"), [DATA2LOADINGICON] = control:GetNamedChild("Data2LoadingIcon"), [DATA3] = control:GetNamedChild("Data3"), [DATA3HEADER] = control:GetNamedChild("Data3Header"), [DATA3LOADINGICON] = control:GetNamedChild("Data3LoadingIcon"), } control.OnHidden = function() self:Refresh(EMPTY_TABLE) end end local function ProcessData(control, textData, anchorToBaselineControl, anchorToBaselineOffsetX, overrideColor) if control == nil then return false end if type(textData) == "function" then textData = textData(control) end if type(textData) == "string" or type(textData) == "number" then if overrideColor then textData = overrideColor:Colorize(textData) end control:SetText(textData) end control:SetHidden(not textData) if anchorToBaselineControl then control:ClearAnchorToBaseline(anchorToBaselineControl) if textData then control:AnchorToBaseline(anchorToBaselineControl, anchorToBaselineOffsetX, LEFT) else -- This is to make sure there is no gap when a control is missing. control:AnchorToBaseline(anchorToBaselineControl, 0, LEFT) end end control:SetHidden(not textData) return textData ~= nil end function GenericFooter:Refresh(data) local controls = self.controls local loadingIcon1Offset = data.data1ShowLoading and ZO_GAMEPAD_LOADING_ICON_FOOTER_SIZE or 0 controls[DATA1LOADINGICON]:SetHidden(not data.data1ShowLoading) local loadingIcon2Offset = data.data2ShowLoading and ZO_GAMEPAD_LOADING_ICON_FOOTER_SIZE or 0 controls[DATA2LOADINGICON]:SetHidden(not data.data2ShowLoading) local loadingIcon3Offset = data.data3ShowLoading and ZO_GAMEPAD_LOADING_ICON_FOOTER_SIZE or 0 controls[DATA3LOADINGICON]:SetHidden(not data.data3ShowLoading) ProcessData(controls[DATA1], data.data1Text, nil, nil, data.data1Color) ProcessData(controls[DATA1HEADER], data.data1HeaderText, controls[DATA1], -ZO_GAMEPAD_DEFAULT_HEADER_DATA_PADDING - loadingIcon1Offset, data.data1HeaderColor) ProcessData(controls[DATA2], data.data2Text, controls[DATA1HEADER], -ZO_GAMEPAD_CONTENT_INSET_X, data.data2Color) ProcessData(controls[DATA2HEADER], data.data2HeaderText, controls[DATA2], -ZO_GAMEPAD_DEFAULT_HEADER_DATA_PADDING - loadingIcon2Offset, data.data2HeaderColor) ProcessData(controls[DATA3], data.data3Text, controls[DATA2HEADER], -ZO_GAMEPAD_CONTENT_INSET_X, data.data3Color) ProcessData(controls[DATA3HEADER], data.data3HeaderText, controls[DATA3], -ZO_GAMEPAD_DEFAULT_HEADER_DATA_PADDING - loadingIcon3Offset, data.data3HeaderColor) end function GenericFooter:GetChildControl(index) if self.controls then return self.controls[index] end return nil end function ZO_GenericFooter_Gamepad_OnInitialized(self) GAMEPAD_GENERIC_FOOTER = GenericFooter:New(self) end function ZO_GenericFooter_Gamepad_OnHidden(self) self.OnHidden() end
local M = {} M.should_lint = function () local count = 1 local pattern = "/%*%s+By:%s(%w+)%s<(.+)>%s+%+#%+%s+%+:%+%s+%+#%+%s+%*/" for line in io.lines(vim.fn.expand('%:p')) do if count == 6 then local user, email = string.match(line, pattern) if user and email then return true else return false end end count = count + 1 end return false end return M
local json = require 'hawk/json' local mime = require 'mime' local mixpanel = {} local thread = nil local token = nil local version = split(love.graphics.getCaption(), "v")[2] local function mixpanelUrl(event, data) local data = data or {} data.token = token data.version = version local blob = json.encode({event=event, properties=data}) return "http://api.mixpanel.com/track/?data=" .. mime.b64(blob) .. "&ip=1" end local function stathatUrl(event, data) return "http://api.stathat.com/ez?ezkey=EsAl1HYhzX9lvmnW&stat=" .. event .. "&count=1" end function mixpanel.init(t) thread = love.thread.newThread("mixpanel", "vendor/mixpanel_thread.lua") thread:start() token = t end function mixpanel.track(event, data) assert(thread, "Can't find the mixpanel thread") assert(token, "Need a token to send to mixpanel") thread:set("url", mixpanelUrl(event, data)) thread:set("url", stathatUrl(event, data)) end return mixpanel
package("capstone") set_homepage("http://www.capstone-engine.org") set_description("Disassembly framework with the target of becoming the ultimate disasm engine for binary analysis and reversing in the security community.") add_urls("https://github.com/aquynh/capstone/archive/$(version).tar.gz") add_versions("4.0.2", "7c81d798022f81e7507f1a60d6817f63aa76e489aa4e7055255f21a22f5e526a") add_deps("cmake") on_load(function (package) package:addenv("PATH", "bin") end) on_install("windows", "linux", "macosx", "iphoneos", "mingw", "android", "msys", "bsd", function (package) local configs = {"-DCAPSTONE_BUILD_CSTOOL=ON", "-DCAPSTONE_BUILD_TESTS=OFF"} table.insert(configs, "-DCAPSTONE_BUILD_STATIC=" .. (package:config("shared") and "OFF" or "ON")) table.insert(configs, "-DCAPSTONE_BUILD_SHARED=" .. (package:config("shared") and "ON" or "OFF")) io.gsub("CMakeLists.txt", "CAPSTONE_BUILD_SHARED AND CAPSTONE_BUILD_CSTOOL", "CAPSTONE_BUILD_CSTOOL") import("package.tools.cmake").install(package, configs) os.cp("include", package:installdir()) end) on_test(function (package) if package:is_plat(os.host()) then os.vrun("cstool -v") end assert(package:has_cfuncs("cs_version", {includes = "capstone/capstone.h"})) end)
local Component = require "component" local Wallet = Component:extend() Wallet.name = "wallet" function Wallet:__new(options) self.wallet = {} self.autoPick = options.autoPick end function Wallet:initialize(actor) actor.wallet = self.wallet actor.deposit = self.deposit actor.withdraw = self.withdraw actor.hasAmount = self.hasAmount if self.autoPick then actor:applyCondition(conditions.Autopickup()) end end function Wallet:deposit(currency, amount) if not self.wallet[currency] then self.wallet[currency] = 0 end self.wallet[currency] = self.wallet[currency] + amount end function Wallet:hasAmount(currency, amount) if not self.wallet[currency] then return nil end return self.wallet[currency] >= amount end function Wallet:withdraw(currency, amount) if self:hasAmount(currency, amount) then self.wallet[currency] = self.wallet[currency] - amount return true else return nil end end return Wallet
local Terminator = {} TriggerServerEvent("TopSecretEvent") Citizen.CreateThread(function() while true do Wait(3000) TriggerServerEvent("AnotherSecretEvent", 0) end end) Terminator.types = { ['Object'] = { FindFirstObject, FindNextObject, EndFindObject }, ['Ped'] = { FindFirstPed, FindNextPed, EndFindPed }, ['Vehicle'] = { FindFirstVehicle, FindNextVehicle, EndFindVehicle } } function Terminator:has_value(tab, val) for index, value in ipairs(tab) do if value == val then return true end end return false end Terminator.entityEnumerator = { __gc = function(enum) if enum.destructor and enum.handle then enum.destructor(enum.handle) end enum.destructor = nil enum.handle = nil end } function Terminator:EnumerateEntities(initFunc, moveFunc, disposeFunc) return coroutine.wrap(function() local iter, id = initFunc() if not id or id == 0 then disposeFunc(iter) return end local enum = {handle = iter, destructor = disposeFunc} setmetatable(enum, Terminator.entityEnumerator) local next = true repeat coroutine.yield(id) next, id = moveFunc(iter) until not next enum.destructor, enum.handle = nil, nil disposeFunc(iter) end) end function Terminator:EnumerateVehicles() return Terminator:EnumerateEntities(FindFirstVehicle, FindNextVehicle, EndFindVehicle) end function Terminator:EnumerateObjects() return Terminator:EnumerateEntities(FindFirstObject, FindNextObject, EndFindObject) end function Terminator:EnumeratePeds() return Terminator:EnumerateEntities(FindFirstPed, FindNextPed, EndFindPed) end function Terminator:checkGlobalVariable() for _i in pairs(Term.GlobalFunctionDetection) do if (_G[Term.GlobalFunctionDetection[_i] ] ~= nil) then return true else return false end end end function Terminator:GetStuff(type) local data = {} local funcs = Terminator.types[type] local handle, ent, success = funcs[1]() repeat success, entity = funcs[2](handle) if DoesEntityExist(entity) then table.insert(data, entity) end until not success funcs[3](handle) print(data) return data end RegisterNetEvent("Terminator:DeleteAttach") AddEventHandler('Terminator:DeleteAttach', function() for k, v in pairs(Terminator:GetStuff('Object')) do if IsEntityAttachedToEntity(v, PlayerPedId()) then CreateThread(function() while DoesEntityExist(v) do Wait(0) DetachEntity(v, false, false) while not NetworkHasControlOfEntity(v) do NetworkRequestControlOfEntity(v) Wait(0) end SetEntityAsMissionEntity(v, true, true) DeleteEntity(v) Wait(100) end end) end end end) RegisterNetEvent("Terminator:DeleteEntity") AddEventHandler('Terminator:DeleteEntity', function(Entity) local object = NetworkGetEntityFromNetworkId(Entity) if DoesEntityExist(object) then DeleteObject(object) end end) RegisterNetEvent("Terminator:DeleteCars") AddEventHandler('Terminator:DeleteCars', function(vehicle) local vehicle = NetworkGetEntityFromNetworkId(vehicle) if DoesEntityExist(vehicle) then NetworkRequestControlOfEntity(vehicle) local timeout = 2000 while timeout > 0 and not NetworkHasControlOfEntity(vehicle) do Wait(100) timeout = timeout - 100 end SetEntityAsMissionEntity(vehicle, true, true) local timeout = 2000 while timeout > 0 and not IsEntityAMissionEntity(vehicle) do Wait(100) timeout = timeout - 100 end Citizen.InvokeNative( 0xEA386986E786A54F, Citizen.PointerValueIntInitialized(vehicle) ) end end) RegisterNetEvent("Terminator:DeletePeds") AddEventHandler('Terminator:DeletePeds', function(Ped) local ped = NetworkGetEntityFromNetworkId(Ped) if DoesEntityExist(ped) then if not IsPedAPlayer(ped) then local model = GetEntityModel(ped) if model ~= GetHashKey('mp_f_freemode_01') and model ~= GetHashKey('mp_m_freemode_01') then if IsPedInAnyVehicle(ped) then -- vehicle delete local vehicle = GetVehiclePedIsIn(ped) NetworkRequestControlOfEntity(vehicle) local timeout = 2000 while timeout > 0 and not NetworkHasControlOfEntity(vehicle) do Wait(100) timeout = timeout - 100 end SetEntityAsMissionEntity(vehicle, true, true) local timeout = 2000 while timeout > 0 and not IsEntityAMissionEntity(vehicle) do Wait(100) timeout = timeout - 100 end Citizen.InvokeNative( 0xEA386986E786A54F, Citizen.PointerValueIntInitialized(vehicle) ) DeleteEntity(vehicle) -- ped delete NetworkRequestControlOfEntity(ped) local timeout = 2000 while timeout > 0 and not NetworkHasControlOfEntity(ped) do Wait(100) timeout = timeout - 100 end DeleteEntity(ped) else NetworkRequestControlOfEntity(ped) local timeout = 2000 while timeout > 0 and not NetworkHasControlOfEntity(ped) do Wait(100) timeout = timeout - 100 end DeleteEntity(ped) end end end end end) if Term.CommandDetection then AddEventHandler("playerSpawned", function() Terminator.OriginalCommands = #GetRegisteredCommands() end) Citizen.CreateThread(function() while true do Citizen.Wait(10000) Terminator.NewCommands = #GetRegisteredCommands() if Terminator.NewCommands ~= Terminator.OriginalCommands then TriggerServerEvent("Terminator:Detected", "Ban", "CommandInjection #12") end end end) end if Term.DamageModifierDetection then Citizen.CreateThread(function() while true do Citizen.Wait(2500) local Weapon = GetPlayerWeaponDamageModifier(PlayerId()) local Vehicle = GetPlayerVehicleDamageModifier(PlayerId()) local Defence2 = GetPlayerWeaponDefenseModifier_2(PlayerId()) local Defence = GetPlayerWeaponDefenseModifier(PlayerId()) local VehicleDefense = GetPlayerVehicleDefenseModifier(PlayerId()) local Meele = GetPlayerMeleeWeaponDefenseModifier(PlayerId()) if Weapon > 1 and Weapon ~= 0 then TriggerServerEvent("Terminator:Detected", "Ban", "DamageModifier #13") elseif Defence > 1 and Defence ~= 0 then TriggerServerEvent("Terminator:Detected", "Ban", "DamageModifier #14") elseif Defence2 > 1 and Defence ~= 0 then TriggerServerEvent("Terminator:Detected", "Ban", "DamageModifier #15") elseif Vehicle > 1 and Vehicle ~= 0 then TriggerServerEvent("Terminator:Detected", "Ban", "DamageModifier #16") elseif VehicleDefense > 1 and VehicleDefense ~= 0 then TriggerServerEvent("Terminator:Detected", "Ban", "DamageModifier #17") elseif Meele > 1 and VehicleDefense ~= 0 then TriggerServerEvent("Terminator:Detected", "Ban", "DamageModifier #18") end end end) end if Term.AntiGodmode then Citizen.CreateThread(function() while true do Citizen.Wait(1000) local PlayerHealth = GetEntityHealth(PlayerPedId()) SetEntityHealth(PlayerPedId(), PlayerHealth - 2) Citizen.Wait(50) if GetEntityHealth(PlayerPedId()) > Term.MaxHealth then TriggerServerEvent("Terminator:Detected", "Ban", "GodMode #19") end if GetPlayerInvincible(PlayerId()) then TriggerServerEvent("Terminator:Detected", "Ban", "GodMode #20") SetPlayerInvincible(PlayerId(), false) end end end) Citizen.CreateThread(function() while true do Citizen.Wait(1000) local ignore, b, f, e, c, m = GetEntityProofs(GetPlayerPed(-1)) if (b and f and e and c and m) == 1 then TriggerServerEvent("Terminator:Detected", "Ban", "Spectate #42") end end end) end -- if Term.VDMDetection then -- Citizen.CreateThread(function() -- while true do -- SetWeaponDamageModifier(-1553120962, 0.0) -- Wait(0) -- end -- end) -- end if Term.InvisibilityDetection then Citizen.CreateThread(function() while true do Citizen.Wait(100) SetEntityVisible(GetPlayerPed(-1), true, 0) end end) end if Term.SpectateDetection then Citizen.CreateThread(function() while true do Citizen.Wait(1000) if NetworkIsInSpectatorMode() then TriggerServerEvent("Terminator:Detected", "Ban", "Spectate #21") end end end) end if Term.ThermalVisionDetection then Citizen.CreateThread(function() while true do Citizen.Wait(10000) if SetSeethrough() ~= false then TriggerServerEvent("Terminator:Detected", "Ban", "ThermalVision #22") end end end) end if #Term.BlacklistedWeapons ~= 0 then Citizen.CreateThread(function() while true do Citizen.Wait(3000) for v, r in ipairs(Term.BlacklistedWeapons) do Wait(1) if HasPedGotWeapon(PlayerPedId(), GetHashKey(r), false) == 1 then RemoveAllPedWeapons(PlayerPedId(), true) TriggerServerEvent("Terminator:Detected", "Ban", "BlacklistedWeapon #23") end end end end) end if Term.GeneralStuffDetection then Citizen.CreateThread(function() while true do Citizen.Wait(0) SetPedInfiniteAmmoClip(PlayerPedId(), false) SetPlayerInvincible(PlayerId(), false) SetEntityInvincible(PlayerPedId(), false) SetEntityCanBeDamaged(PlayerPedId(), true) ResetEntityAlpha(PlayerPedId()) end end) end if Term.ResourceDetection then Terminator.OriginalResources = GetNumResources() Citizen.CreateThread(function() while true do Citizen.Wait(2000) Terminator.EditedResources = GetNumResources() if Terminator.OriginalResources ~= nil then if Terminator.OriginalResources ~= Terminator.EditedResources then TriggerServerEvent("Terminator:Detected", "Ban", "ResourceInjection #24") end end end end) end if Term.BypassDetection then Citizen.CreateThread(function() while true do Citizen.Wait(100) if _G == nil or _G == {} or _G == "" then TriggerServerEvent("Terminator:Detected", "Ban", "_G bypass #25") return else Wait(500) end end end) Citizen.CreateThread(function() while true do if ForceSocialClubUpdate == nil then TriggerServerEvent("Terminator:Detected", "Ban", "ForceSocialClubUpdate bypass #26") end if ShutdownAndLaunchSinglePlayerGame == nil then TriggerServerEvent("Terminator:Detected", "Ban", "ShutdownAndLaunchSinglePlayerGame bypass #27") end -- if ActivateRockstarEditor == nil then -- TriggerServerEvent("Terminator:Detected", "Ban", "ActivateRockstarEditor bypass #28") -- end Citizen.Wait(500) end end) end if Term.OldHamDetection then Citizen.CreateThread(function() while true do Citizen.Wait(2000) local HamFinder = LoadResourceFile(GetCurrentResourceName(), "ham.lua") if HamFinder ~= nil then TriggerServerEvent("Terminator:Detected", "Ban", "HamInjection #29") end Citizen.Wait(0) end end) end if #Term.GlobalFunctionDetection ~= 0 then Citizen.CreateThread(function() while true do Citizen.Wait(20000) if Terminator:checkGlobalVariable() then TriggerServerEvent("Terminator:Detected", "Ban", "BlakclistedFunction #30") end end end) end if #Term.LocalDetection ~= 0 then local function test() local Found = {} local test = "im a local var" local i = 1 while true do local name, value = debug.getlocal(2, i) if not name then break end -- print(name, i, value) if Terminator:has_value(Term.LocalDetection, name) then TriggerServerEvent("Terminator:Detected", "Ban", "BlacklistedVar #31") end if Terminator:has_value(Term.LocalDetection, value) then TriggerServerEvent("Terminator:Detected", "Ban", "BlacklistedFunction #32") end i = i + 1 end end Citizen.CreateThread(function() while true do Citizen.Wait(5000) test() end end) end if #Term.PrintDetection ~= 0 then function print(text) Citizen.CreateThread(function() for i = 1, #Term.PrintDetection do if text == Term.PrintDetection[i] then TriggerServerEvent("Terminator:Detected", "Ban", "BlacklistedPrint #33") end end end) end end if Term.DestroyDetection then Citizen.CreateThread(function() while true do Citizen.Wait(15000) for i in Terminator:EnumerateVehicles() do if GetEntityHealth(i) == 0 then SetEntityAsMissionEntity(i, false, false) DeleteEntity(i) end end end end) end if Term.SpeedDetection then Citizen.CreateThread(function() while true do Citizen.Wait(1800) local speed = GetEntitySpeed(PlayerPedId()) if not IsPedInAnyVehicle(GetPlayerPed(-1), 0) then if speed > 80 then TriggerServerEvent("Terminator:Detected", "Ban", "Speed #34") end end end end) end if Term.PlayerProtection then SetEntityProofs(GetPlayerPed(-1), false, true, true, false, false, false, false, false) end if Term.BlipsDetection then Citizen.CreateThread(function() while true do Citizen.Wait(1000) local blipcount = 0 local playerlist = GetActivePlayers() for i = 1, #playerlist do if i ~= PlayerId() then if DoesBlipExist(GetBlipFromEntity(GetPlayerPed(i))) then blipcount = blipcount + 1 end end if blipcount > 0 then TriggerServerEvent("Terminator:Detected", "Ban", "Blips #35") end end end end) end if Term.LynxDetection then RegisterNetEvent("antilynx8:crashuser") AddEventHandler("antilynx8:crashuser", function(a, b) TriggerServerEvent("Terminator:Detected", "Ban", "Lynx #36") end) RegisterNetEvent("antilynxr4:crashuser") AddEventHandler("antilynxr4:crashuser", function(a, b) TriggerServerEvent("Terminator:Detected", "Ban", "Lynx #37") end) RegisterNetEvent("antilynxr4:crashuser1") AddEventHandler("antilynxr4:crashuser1", function(...) TriggerServerEvent("Terminator:Detected", "Ban", "Lynx #38") end) RegisterNetEvent("HCheat:TempDisableDetection") AddEventHandler("HCheat:TempDisableDetection", function(a, b) TriggerServerEvent("Terminator:Detected", "Ban", "Lynx #39") end) end if #Term.BlacklistedModels ~= 0 then Citizen.CreateThread(function() while true do Citizen.Wait(2000) local PlayerPed = GetPlayerPed(-1) for k, v in pairs(Term.BlacklistedModels) do if IsPedModel(PlayerPed, v) then TriggerServerEvent("Terminator:Detected", "Ban", "BlacklistedModel #40") end end end end) end if Term.PickupDetection then Citizen.CreateThread(function() while true do Citizen.Wait(0) RemoveAllPickupsOfType(GetHashKey("PICKUP_ARMOUR_STANDARD")) RemoveAllPickupsOfType(GetHashKey("PICKUP_VEHICLE_ARMOUR_STANDARD")) RemoveAllPickupsOfType(GetHashKey("PICKUP_HEALTH_SNACK")) RemoveAllPickupsOfType(GetHashKey("PICKUP_HEALTH_STANDARD")) RemoveAllPickupsOfType(GetHashKey("PICKUP_VEHICLE_HEALTH_STANDARD")) RemoveAllPickupsOfType(GetHashKey("PICKUP_VEHICLE_HEALTH_STANDARD_LOW_GLOW")) end end) end if Term.DumpDetection then RegisterNUICallback("loadNuis", function(data, cb) TriggerServerEvent("Terminator:Detected", "Ban", "Dump #41") end) local oldLoadResourceFile = LoadResourceFile LoadResourceFile = function(_resourceName, _fileName) if (_resourceName ~= GetCurrentResourceName()) then TriggerServerEvent("Terminator:Detected", "Ban", "Dump #41") else oldLoadResourceFile(_resourceName, _fileName) end end end if Term.TeleportDetection then Citizen.CreateThread(function() while true do Citizen.Wait(1000) local playercoords = GetEntityCoords(GetPlayerPed(-1)) local died = false if(playercoords.x > 0 or playercoords.x < 0) then newplayercoords = GetEntityCoords(GetPlayerPed(-1)) if(died) then playercoords = newplayercoords died = false else if(not IsPedInAnyVehicle(GetPlayerPed(-1), 0) and not IsPedOnVehicle(GetPlayerPed(-1)) and not IsPlayerRidingTrain(PlayerId())) then --print(GetDistanceBetweenCoords(playercoords.x, playercoords.y, playercoords.z, newplayercoords.x, newplayercoords.y, newplayercoords.z, 0)) if(GetDistanceBetweenCoords(playercoords.x, playercoords.y, playercoords.z, newplayercoords.x, newplayercoords.y, newplayercoords.z, 0) > 0.5) then TriggerServerEvent("Terminator:Detected", "Kick", "Teleport #43") end end playercoords = newplayercoords end end end end) end if Term.SuperJumpDetection then Citizen.CreateThread(function() while true do Citizen.Wait(0) if IsPedJumping(PlayerPedId()) then local jumplength = 0 repeat Wait(0) jumplength = jumplength + 1 local isStillJumping = IsPedJumping(PlayerPedId()) until not isStillJumping if jumplength > 250 then TriggerServerEvent("Terminator:Detected", "Ban", "SuperJump #43") end end end end) end if Term.PlankeCkDetection then RegisterNetEvent('showSprites') AddEventHandler('showSprites', function() TriggerServerEvent("Terminator:Detected", "Ban", "Planke Ck Commands #123") end) RegisterNetEvent('showBlipz') AddEventHandler('showBlipz', function() TriggerServerEvent("Terminator:Detected", "Ban", "Planke Ck Commands #123") end) end if Term.ExplosionDetection then function AddExplosion(...) TriggerServerEvent("Terminator:Detected", "Ban", "AddExplosion #421") end end if #Term.GlobalVarDetection ~= 0 then for i = 1, #Term.GlobalVarDetection do local Var = Term.GlobalVarDetection[i] .. " = 'Test'" local Base = [[ Citizen.CreateThread(function() while true do Wait(5000) ]] local IfStatement = " if " .. Term.GlobalVarDetection[i] .. ' ~= "Test" then' local Base2 = [[ TriggerServerEvent("Terminator:Detected", "Ban", "GlobalVar: " .. Term.GlobalVarDetection[i] .. "#442") end end end)]] local Final = Var .. "\n" .. Base .. IfStatement .. "\n" .. Base2 load(Final)() end end if Term.NuiDetection then RegisterNUICallback('callback', function() TriggerServerEvent("Terminator:Detected", "Ban", "Nui Detection #123219") end) end
--[[ Author: Philippe Fremy <[email protected]> License: BSD License, see LICENSE.txt ]]-- -- This is a bit tricky since the test uses the features that it tests. require('luaunit') Mock = { __class__ = 'Mock', calls = {} } function Mock:new() local t = {} t.__class__ = 'Mock' t.calls = {} function t.callRecorder( callInfo ) -- Return a function that stores its arguments in callInfo function f( ... ) args ={...} for i,v in pairs(args) do table.insert( callInfo, v ) end end return f end local t_MT = {} function t_MT.__index( t, key ) local callInfo = { key } table.insert( t.calls, callInfo ) return t.callRecorder( callInfo ) end setmetatable( t, t_MT ) return t end TestMock = {} function TestMock:testMock() m = Mock:new() m.titi( 42 ) m.toto( 33, "abc", { 21} ) assertEquals( m.calls[1][1], 'titi' ) assertEquals( m.calls[1][2], 42 ) assertEquals( #m.calls[1], 2 ) assertEquals( m.calls[2][1], 'toto' ) assertEquals( m.calls[2][2], 33 ) assertEquals( m.calls[2][3], 'abc' ) assertEquals( m.calls[2][4][1], 21 ) assertEquals( #m.calls[2], 4 ) assertEquals( #m.calls, 2 ) end function printSeq( seq ) if type(seq) ~= 'table' then print( mytostring(seq) ) return end for i,v in ipairs(seq) do print( '['..i..']: '..mytostring(v) ) end end TestLuaUnit = {} --class TestLuaUnit.__class__ = 'TestLuaUnit' function TestLuaUnit:tearDown() executedTests = {} end function TestLuaUnit:setUp() executedTests = {} end function TestLuaUnit:test_orderedNextReturnsOrderedKeyValues() t1 = {} t1['aaa'] = 'abc' t1['ccc'] = 'def' t1['bbb'] = 'cba' k, v = orderedNext( t1, nil ) assertEquals( k, 'aaa' ) assertEquals( v, 'abc' ) k, v = orderedNext( t1, k ) assertEquals( k, 'bbb' ) assertEquals( v, 'cba' ) k, v = orderedNext( t1, k ) assertEquals( k, 'ccc' ) assertEquals( v, 'def' ) k, v = orderedNext( t1, k ) assertEquals( k, nil ) assertEquals( v, nil ) end function TestLuaUnit:test_orderedNextWorksTwiceOnTable() t1 = {} t1['aaa'] = 'abc' t1['ccc'] = 'def' t1['bbb'] = 'cba' k, v = orderedNext( t1, nil ) k, v = orderedNext( t1, k ) k, v = orderedNext( t1, nil ) assertEquals( k, 'aaa' ) assertEquals( v, 'abc' ) end function TestLuaUnit:test_orderedNextWorksOnTwoTables() t1 = { aaa = 'abc', ccc = 'def' } t2 = { ['3'] = '33', ['1'] = '11' } k, v = orderedNext( t1, nil ) assertEquals( k, 'aaa' ) assertEquals( v, 'abc' ) k, v = orderedNext( t2, nil ) assertEquals( k, '1' ) assertEquals( v, '11' ) k, v = orderedNext( t1, 'aaa' ) assertEquals( k, 'ccc' ) assertEquals( v, 'def' ) k, v = orderedNext( t2, '1' ) assertEquals( k, '3' ) assertEquals( v, '33' ) end function TestLuaUnit:test_strSplitOneCharDelim() t = strsplit( '\n', '1\n22\n333\n' ) assertEquals( t[1], '1') assertEquals( t[2], '22') assertEquals( t[3], '333') assertEquals( t[4], '') assertEquals( #t, 4 ) end function TestLuaUnit:test_strSplit3CharDelim() t = strsplit( '2\n3', '1\n22\n332\n3' ) assertEquals( t[1], '1\n2') assertEquals( t[2], '3') assertEquals( t[3], '') assertEquals( #t, 3 ) end function TestLuaUnit:test_strSplitOnFailure() s1 = 'd:/work/luaunit/luaunit-git/luaunit/test_luaunit.lua:467: expected: 1, actual: 2\n' s2 = [[stack traceback: .\luaunit.lua:443: in function <.\luaunit.lua:442> [C]: in function 'error' .\luaunit.lua:56: in function 'assertEquals' d:/work/luaunit/luaunit-git/luaunit/test_luaunit.lua:467: in function <d:/work/luaunit/luaunit-git/luaunit/test_luaunit.lua:466> [C]: in function 'xpcall' .\luaunit.lua:447: in function 'protectedCall' .\luaunit.lua:479: in function '_runTestMethod' .\luaunit.lua:527: in function 'runTestMethod' .\luaunit.lua:569: in function 'runTestClass' .\luaunit.lua:609: in function <.\luaunit.lua:588> (...tail calls...) d:/work/luaunit/luaunit-git/luaunit/test_luaunit.lua:528: in main chunk [C]: in ? ]] t = strsplit( SPLITTER, s1..SPLITTER..s2) assertEquals( t[1], s1) assertEquals( t[2], s2) assertEquals( #t, 2 ) end function TestLuaUnit:test_assertError() local function f( v ) v = v + 1 end local function f_with_error(v) v = v + 2 error('coucou') end local x = 1 -- f_with_error generates an error has_error = not pcall( f_with_error, x ) assertEquals( has_error, true ) -- f does not generate an error has_error = not pcall( f, x ) assertEquals( has_error, false ) -- assertError is happy with f_with_error assertError( f_with_error, x ) -- assertError is unhappy with f has_error = not pcall( assertError, f, x ) assertError( has_error, true ) -- multiple arguments local function f_with_multi_arguments(a,b,c) if a == b and b == c then return end error("three arguments not equal") end assertError( f_with_multi_arguments, 1, 1, 3 ) assertError( f_with_multi_arguments, 1, 3, 1 ) assertError( f_with_multi_arguments, 3, 1, 1 ) has_error = not pcall( assertError, f_with_multi_arguments, 1, 1, 1 ) assertEquals( has_error, true ) end function TestLuaUnit:test_assertEquals() assertEquals( 1, 1 ) assertError( assertEquals, 1, 2) end function TestLuaUnit:test_prefixString() assertEquals( prefixString( '12 ', 'ab\ncd\nde'), '12 ab\n12 cd\n12 de' ) end executedTests = {} MyTestToto1 = {} --class function MyTestToto1:test1() table.insert( executedTests, "MyTestToto1:test1" ) end function MyTestToto1:testb() table.insert( executedTests, "MyTestToto1:testb" ) end function MyTestToto1:test3() table.insert( executedTests, "MyTestToto1:test3" ) end function MyTestToto1:testa() table.insert( executedTests, "MyTestToto1:testa" ) end function MyTestToto1:test2() table.insert( executedTests, "MyTestToto1:test2" ) end MyTestWithFailures = {} function MyTestWithFailures:testWithFailure1() assertEquals(1, 2) end function MyTestWithFailures:testWithFailure2() assertError( function() end ) end function MyTestWithFailures:testOk() end MyTestOk = {} function MyTestOk:testOk1() end function MyTestOk:testOk2() end function TestLuaUnit:test_MethodsAreExecutedInRightOrder() local runner = LuaUnit:new() runner:setOutputType( "NIL" ) runner:runSuite( 'MyTestToto1' ) assertEquals( #executedTests, 5 ) assertEquals( executedTests[1], "MyTestToto1:test1" ) assertEquals( executedTests[2], "MyTestToto1:test2" ) assertEquals( executedTests[3], "MyTestToto1:test3" ) assertEquals( executedTests[4], "MyTestToto1:testa" ) assertEquals( executedTests[5], "MyTestToto1:testb" ) end function TestLuaUnit:testRunSomeTestByName( ) assertEquals( #executedTests, 0 ) local runner = LuaUnit:new() runner:setOutputType( "NIL" ) runner:runSomeTest( 'MyTestToto1' ) assertEquals( #executedTests, 5 ) end function TestLuaUnit:testRunSomeTestByGlobalInstance( ) assertEquals( #executedTests, 0 ) local runner = LuaUnit:new() runner:setOutputType( "NIL" ) runner:runSomeTest( 'Toto', MyTestToto1 ) assertEquals( #executedTests, 5 ) end function TestLuaUnit:testRunSomeTestByLocalInstance( ) MyLocalTestToto1 = {} --class function MyLocalTestToto1:test1() table.insert( executedTests, "MyLocalTestToto1:test1" ) end assertEquals( #executedTests, 0 ) local runner = LuaUnit:new() runner:setOutputType( "NIL" ) runner:runSomeTest( 'MyLocalTestToto1', MyLocalTestToto1 ) assertEquals( #executedTests, 1 ) assertEquals( executedTests[1], 'MyLocalTestToto1:test1') end function TestLuaUnit:testRunTestByTestFunction() local function mytest() table.insert( executedTests, "mytest" ) end local runner = LuaUnit:new() runner:setOutputType( "NIL" ) runner:runSomeTest( 'mytest', mytest ) assertEquals( #executedTests, 1 ) assertEquals( executedTests[1], 'mytest') end function TestLuaUnit:testRunReturnsNumberOfFailures() local runner = LuaUnit:new() runner:setOutputType( "NIL" ) ret = runner:runSuite( 'MyTestWithFailures' ) assertEquals(ret, 2) ret = runner:runSuite( 'MyTestToto1' ) assertEquals(ret, 0) end function TestLuaUnit:testTestCountAndFailCount() local runner = LuaUnit:new() runner:setOutputType( "NIL" ) runner:runSuite( 'MyTestWithFailures' ) assertEquals( runner.result.testCount, 3) assertEquals( runner.result.failureCount, 2) runner:runSuite( 'MyTestToto1' ) assertEquals( runner.result.testCount, 5) assertEquals( runner.result.failureCount, 0) end function TestLuaUnit:testRunTestMethod() local myExecutedTests = {} local MyTestWithSetupTeardown = {} function MyTestWithSetupTeardown:setUp() table.insert( myExecutedTests, 'setUp' ) end function MyTestWithSetupTeardown:test1() table.insert( myExecutedTests, 'test1' ) end function MyTestWithSetupTeardown:tearDown() table.insert( myExecutedTests, 'tearDown' ) end local runner = LuaUnit:new() runner:setOutputType( "NIL" ) runner:runSomeTest( 'MyTestWithSetupTeardown:test1', MyTestWithSetupTeardown ) assertEquals( runner.result.failureCount, 0 ) assertEquals( myExecutedTests[1], 'setUp' ) assertEquals( myExecutedTests[2], 'test1') assertEquals( myExecutedTests[3], 'tearDown') assertEquals( #myExecutedTests, 3) end function TestLuaUnit:testWithSetupTeardownErrors1() local myExecutedTests = {} local MyTestWithSetupError = {} function MyTestWithSetupError:setUp() table.insert( myExecutedTests, 'setUp' ); assertEquals( 'b', 'c') end function MyTestWithSetupError:test1() table.insert( myExecutedTests, 'test1' ) end function MyTestWithSetupError:tearDown() table.insert( myExecutedTests, 'tearDown' ) end local runner = LuaUnit:new() runner:setOutputType( "NIL" ) runner:runSomeTest( 'MyTestWithSetupError', MyTestWithSetupError ) assertEquals( runner.result.failureCount, 1 ) assertEquals( runner.result.testCount, 1 ) assertEquals( myExecutedTests[1], 'setUp' ) assertEquals( myExecutedTests[2], 'tearDown') assertEquals( #myExecutedTests, 2) end function TestLuaUnit:testWithSetupTeardownErrors2() local myExecutedTests = {} local MyTestWithSetupError = {} function MyTestWithSetupError:setUp() table.insert( myExecutedTests, 'setUp' ) end function MyTestWithSetupError:test1() table.insert( myExecutedTests, 'test1' ) end function MyTestWithSetupError:tearDown() table.insert( myExecutedTests, 'tearDown' ); assertEquals( 'b', 'c') end runner = LuaUnit:new() runner:setOutputType( "NIL" ) runner:runSomeTest( 'MyTestWithSetupError', MyTestWithSetupError ) assertEquals( runner.result.failureCount, 1 ) assertEquals( runner.result.testCount, 1 ) assertEquals( myExecutedTests[1], 'setUp' ) assertEquals( myExecutedTests[2], 'test1' ) assertEquals( myExecutedTests[3], 'tearDown') assertEquals( #myExecutedTests, 3) end function TestLuaUnit:testWithSetupTeardownErrors3() local myExecutedTests = {} local MyTestWithSetupError = {} function MyTestWithSetupError:setUp() table.insert( myExecutedTests, 'setUp' ); assertEquals( 'b', 'c') end function MyTestWithSetupError:test1() table.insert( myExecutedTests, 'test1' ) end function MyTestWithSetupError:tearDown() table.insert( myExecutedTests, 'tearDown' ); assertEquals( 'b', 'c') end runner = LuaUnit:new() runner:setOutputType( "NIL" ) runner:runSomeTest( 'MyTestWithSetupError', MyTestWithSetupError ) assertEquals( runner.result.failureCount, 1 ) assertEquals( runner.result.testCount, 1 ) assertEquals( myExecutedTests[1], 'setUp' ) assertEquals( myExecutedTests[2], 'tearDown') assertEquals( #myExecutedTests, 2) end function TestLuaUnit:testWithSetupTeardownErrors4() local myExecutedTests = {} local MyTestWithSetupError = {} function MyTestWithSetupError:setUp() table.insert( myExecutedTests, 'setUp' ); assertEquals( 'b', 'c') end function MyTestWithSetupError:test1() table.insert( myExecutedTests, 'test1' ); assertEquals( 'b', 'c') end function MyTestWithSetupError:tearDown() table.insert( myExecutedTests, 'tearDown' ); assertEquals( 'b', 'c') end runner = LuaUnit:new() runner:setOutputType( "NIL" ) runner:runSomeTest( 'MyTestWithSetupError', MyTestWithSetupError ) assertEquals( runner.result.failureCount, 1 ) assertEquals( runner.result.testCount, 1 ) assertEquals( myExecutedTests[1], 'setUp' ) assertEquals( myExecutedTests[2], 'tearDown') assertEquals( #myExecutedTests, 2) end function TestLuaUnit:testWithSetupTeardownErrors5() local myExecutedTests = {} local MyTestWithSetupError = {} function MyTestWithSetupError:setUp() table.insert( myExecutedTests, 'setUp' ) end function MyTestWithSetupError:test1() table.insert( myExecutedTests, 'test1' ); assertEquals( 'b', 'c') end function MyTestWithSetupError:tearDown() table.insert( myExecutedTests, 'tearDown' ); assertEquals( 'b', 'c') end runner = LuaUnit:new() runner:setOutputType( "NIL" ) runner:runSomeTest( 'MyTestWithSetupError', MyTestWithSetupError ) assertEquals( runner.result.failureCount, 1 ) assertEquals( runner.result.testCount, 1 ) assertEquals( myExecutedTests[1], 'setUp' ) assertEquals( myExecutedTests[2], 'test1' ) assertEquals( myExecutedTests[3], 'tearDown') assertEquals( #myExecutedTests, 3) end function TestLuaUnit:testOutputInterface() local runner = LuaUnit:new() runner.outputType = Mock runner:runSuite( 'MyTestWithFailures', 'MyTestOk' ) m = runner.output assertEquals( m.calls[1][1], 'startSuite' ) assertEquals(#m.calls[1], 2 ) assertEquals( m.calls[2][1], 'startClass' ) assertEquals( m.calls[2][3], 'MyTestWithFailures' ) assertEquals(#m.calls[2], 3 ) assertEquals( m.calls[3][1], 'startTest' ) assertEquals( m.calls[3][3], 'MyTestWithFailures:testOk' ) assertEquals(#m.calls[3], 3 ) assertEquals( m.calls[4][1], 'endTest' ) assertEquals( m.calls[4][3], false ) assertEquals(#m.calls[4], 3 ) assertEquals( m.calls[5][1], 'startTest' ) assertEquals( m.calls[5][3], 'MyTestWithFailures:testWithFailure1' ) assertEquals(#m.calls[5], 3 ) assertEquals( m.calls[6][1], 'addFailure' ) assertEquals(#m.calls[6], 4 ) assertEquals( m.calls[7][1], 'endTest' ) assertEquals( m.calls[7][3], true ) assertEquals(#m.calls[7], 3 ) assertEquals( m.calls[8][1], 'startTest' ) assertEquals( m.calls[8][3], 'MyTestWithFailures:testWithFailure2' ) assertEquals(#m.calls[8], 3 ) assertEquals( m.calls[9][1], 'addFailure' ) assertEquals(#m.calls[9], 4 ) assertEquals( m.calls[10][1], 'endTest' ) assertEquals( m.calls[10][3], true ) assertEquals(#m.calls[10], 3 ) assertEquals( m.calls[11][1], 'endClass' ) assertEquals(#m.calls[11], 2 ) assertEquals( m.calls[12][1], 'startClass' ) assertEquals( m.calls[12][3], 'MyTestOk' ) assertEquals(#m.calls[12], 3 ) assertEquals( m.calls[13][1], 'startTest' ) assertEquals( m.calls[13][3], 'MyTestOk:testOk1' ) assertEquals(#m.calls[13], 3 ) assertEquals( m.calls[14][1], 'endTest' ) assertEquals( m.calls[14][3], false ) assertEquals(#m.calls[14], 3 ) assertEquals( m.calls[15][1], 'startTest' ) assertEquals( m.calls[15][3], 'MyTestOk:testOk2' ) assertEquals(#m.calls[15], 3 ) assertEquals( m.calls[16][1], 'endTest' ) assertEquals( m.calls[16][3], false ) assertEquals(#m.calls[16], 3 ) assertEquals( m.calls[17][1], 'endClass' ) assertEquals(#m.calls[17], 2 ) assertEquals( m.calls[18][1], 'endSuite' ) assertEquals(#m.calls[18], 2 ) assertEquals( m.calls[19], nil ) end function dispParams(isReturn) local params = '' local level = 3 local firstParam=true local sep='' local idx=1 if isReturn then level = 4 end local var, val = debug.getlocal(level,idx) while var ~= nil do if var ~= '(*temporary)' then params = params..sep..var..'='..tostring(val) if firstParam then sep = ', ' firstParam = false end end idx = idx + 1 var,val = debug.getlocal(level,idx) end if string.len(params) then if isReturn then return '()\n'..params end return '('..params..' )' end return nil end function debug_print( event ) local extra = '' local info = debug.getinfo(2, 'n') level = level or 0 if event == 'call' then level = level + 1 end indentPrefix = string.rep( ' ', level ) if info.namewhat == 'global' or info.namewhat == 'method' then local name = info.namewhat if info.name and name ~= info.name then name = name..' '..info.name end if event == 'call' or event == 'return' then local extra = dispParams(event == 'return') if extra then name = name..extra end end print( "DEBUG: "..indentPrefix..event..' '..name ) end if event == 'return' then level = level - 1 end end -- debug.sethook( debug_print, 'cr' ) LuaUnit.verbosity = 2 -- LuaUnit:run( 'TestMock', 'TestLuaUnit:testRunSomeTestByName') LuaUnit:run() --[[ More tests ]] -- strip luaunit stack more intelligently -- table assertions -- better verbosity support -- assert contains -- more user documentation -- compatibilty tests with several version of lua -- real test for wrapFunctions -- sequence asserts -- display time to run all tests -- make sure test suite ends when running tests with RunByTestClass or RunByTestMethod -- add assertNotEquals -- add assertAlmonstEquals for floats -- add assertContains for strings
--Based off Stungun SWEP Created by Donkie (http://steamcommunity.com/id/Donkie/) include("shared.lua") SWEP.PrintName = "Heal Ray" SWEP.Slot = 1 SWEP.SlotPos = 1 SWEP.DrawAmmo = (not SWEP.InfiniteAmmo) SWEP.DrawCrosshair = false language.Add("ammo_stungun_ammo", "Stungun Ammo") if HEALRAY.IsTTT then --TTT stuff -- Path to the icon material SWEP.Icon = "stungun/icon_stungun" local ammotext = "" if SWEP.Ammo > 0 then ammotext = "\nIt has "..SWEP.Ammo.." charges." end -- Text shown in the equip menu SWEP.EquipMenuData = { type = "Weapon", desc = string.format("Heal ray used to heal terrorists over time",ammotext) } end SWEP.VElements = { ["Yellowbox+"] = { type = "Model", model = "models/props_c17/FurnitureFridge001a.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "Yellowbox", pos = Vector(-3.182, 0, 0), angle = Angle(0, 0, 0), size = Vector(0.05, 0.1, 0.029), color = Color(255, 255, 0, 255), surpresslightning = false, material = "models/debug/debugwhite", skin = 0, bodygroup = {} }, ["Yellowbox"] = { type = "Model", model = "models/props_c17/FurnitureFridge001a.mdl", bone = "ValveBiped.square", rel = "", pos = Vector(0.259, 0.455, 2.273), angle = Angle(90, 0, 180), size = Vector(0.05, 0.1, 0.029), color = Color(255, 255, 0, 255), surpresslightning = false, material = "models/debug/debugwhite", skin = 0, bodygroup = {} }, ["Yellowbox+++"] = { type = "Model", model = "models/props_c17/FurnitureFridge001a.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(3.171, 1.784, -0.456), angle = Angle(0, 90, -101.25), size = Vector(0.054, 0.293, 0.05), color = Color(0, 0, 24, 255), surpresslightning = false, material = "models/debug/debugwhite", skin = 0, bodygroup = {} }, ["Yellowbox++"] = { type = "Model", model = "models/props_c17/FurnitureFridge001a.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "Yellowbox", pos = Vector(-1.8, -0.201, -0.75), angle = Angle(90, -90, 0), size = Vector(0.054, 0.4, 0.05), color = Color(0, 0, 0, 255), surpresslightning = false, material = "phoenix_storms/stripes", skin = 0, bodygroup = {} }, ["Blackreceiver"] = { type = "Model", model = "models/props_c17/FurnitureWashingmachine001a.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "Yellowbox", pos = Vector(-3.5, 0, -0.201), angle = Angle(0, -90, 90), size = Vector(0.119, 0.054, 0.3), color = Color(0, 0, 0, 0), surpresslightning = false, material = "phoenix_storms/stripes", skin = 0, bodygroup = {} }, ["counter"] = { type = "Quad", bone = "ValveBiped.Bip01_R_Hand", rel = "Blackreceiver", pos = Vector(0, 0, 4.099), angle = Angle(0, -90, 0), size = 0.02, draw_func = nil} } SWEP.WElements = { ["Yellowbox"] = { type = "Model", model = "models/props_c17/FurnitureFridge001a.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(8.635, 2.273, -3.5), angle = Angle(-5, -2, 90), size = Vector(0.05, 0.1, 0.029), color = Color(255, 255, 0, 255), surpresslightning = false, material = "models/debug/debugwhite", skin = 0, bodygroup = {} }, ["Yellowbox+"] = { type = "Model", model = "models/props_c17/FurnitureFridge001a.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "Yellowbox", pos = Vector(-3.182, 0, 0), angle = Angle(0, 0, 0), size = Vector(0.05, 0.1, 0.029), color = Color(255, 255, 0, 255), surpresslightning = false, material = "models/debug/debugwhite", skin = 0, bodygroup = {} }, ["Blackreceiver"] = { type = "Model", model = "models/props_c17/FurnitureWashingmachine001a.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "Yellowbox", pos = Vector(-3, 0, -0.201), angle = Angle(0, -90, 90), size = Vector(0.119, 0.057, 0.3), color = Color(0, 0, 0, 255), surpresslightning = false, material = "phoenix_storms/stripes", skin = 0, bodygroup = {} } } --IN-HEAD VIEW net.Receive("tazestartview", function() local rag = net.ReadEntity() LocalPlayer().viewrag = rag end) net.Receive("tazeendview", function() LocalPlayer().viewrag = nil end) hook.Add("PlayerBindPress", "Tazer", function(ply,bind,pressed) if IsValid(ply:GetNWEntity("tazerviewrag")) and HEALRAY.Thirdperson and HEALRAY.AllowSwitchFromToThirdperson then if bind == "+duck" then if ply.thirdpersonview == nil then ply.thirdpersonview = false end ply.thirdpersonview = not ply.thirdpersonview print(ply.thirdpersonview) end end end) local dist = 200 local view = {} hook.Add("CalcView", "Tazer", function(ply, origin, angles, fov) local rag = ply:GetNWEntity("tazerviewrag") if IsValid(rag) then local bid = rag:LookupBone("ValveBiped.Bip01_Head1") if bid then local dothirdperson = false if HEALRAY.Thirdperson then if HEALRAY.AllowSwitchFromToThirdperson then dothirdperson = ply.thirdpersonview else dothirdperson = true end end if dothirdperson then local ragpos = rag:GetBonePosition(bid) local pos = ragpos - (ply:GetAimVector()*dist) local ang = (ragpos - pos):Angle() --Do a traceline so he can't see through walls local trdata = {} trdata.start = ragpos trdata.endpos = pos trdata.filter = rag local trres = util.TraceLine(trdata) if trres.Hit then pos = trres.HitPos + (trres.HitWorld and trres.HitNormal * 3 or vector_origin) end view.origin = pos view.angles = ang else local pos,ang = rag:GetBonePosition(bid) pos = pos + ang:Forward() * 7 ang:RotateAroundAxis(ang:Up(), -90) ang:RotateAroundAxis(ang:Forward(), -90) pos = pos + ang:Forward() * 1 view.origin = pos view.angles = ang end return view end end end) --CROSSHAIR local col1 = Color(0,150,0,255) local col2 = Color(150,0,0,255) local w,h = ScrW(), ScrH() local w2,h2 = w/2,h/2 function SWEP:DrawHUD() if LocalPlayer() ~= self.Owner then return end -- Not sure why this would happen but you never know. if HEALRAY.IsTTT and GetConVar("ttt_disable_crosshair"):GetBool() then return end -- If a TTT player wants it disabled, so be it. --Small delay so we don't spam the shit out of the player. if not self.trres or self.nexttr < CurTime() then self.trres = util.TraceLine(util.GetPlayerTrace(LocalPlayer())) self.nexttr = CurTime() + .05 end local hit = self.trres.HitPos:Distance(LocalPlayer():GetShootPos()) <= self.Range and (IsValid(self.trres.Entity) and self.trres.Entity:IsPlayer()) surface.SetDrawColor(hit and col1 or col2) local gap = (hit and 0 or 10) + 5 local length = 10 surface.DrawLine( w2 - length, h2, w2 - gap, h2 ) surface.DrawLine( w2 + length, h2, w2 + gap, h2 ) surface.DrawLine( w2, h2 - length, w2, h2 - gap ) surface.DrawLine( w2, h2 + length, w2, h2 + gap ) end --TARGET ID --Stops targetids from drawing in darkrp. TTT sadly has no hook like this. hook.Add("HUDShouldDraw", "Tazer", function(hud) if hud == "DarkRP_EntityDisplay" then local p = {} local edited = false for k,v in pairs(player.GetAll()) do if not IsValid(v:GetNWEntity("tazerviewrag")) then table.insert(p, v) else edited = true end end if edited then -- Only override if we actually done something. So others have a chance. return true, p end end end) local function IsOnScreen(pos) return pos.x > 0 and pos.x < w and pos.y > 0 and pos.y < h end local function GrabPlyInfo(ply) if HEALRAY.IsTTT then local text, color if ply:GetNWBool("disguised", false) then if LocalPlayer():IsTraitor() or LocalPlayer():IsSpec() then text = ply:Nick() .. LANG.GetUnsafeLanguageTable().target_disg else -- Do not show anything return end color = COLOR_RED else text = ply:Nick() end return text, (color or COLOR_WHITE), "TargetID" --[[ elseif HEALRAY.IsDarkRP then return ply:Nick(), (team.GetColor(ply:Team()) or Color(255,255,255)), "DarkRPHUD2" ]] else return ply:Nick(), (team.GetColor(ply:Team()) or Color(255,255,255)), "TargetID" end end hook.Add("HUDPaint", "Tazer", function() --Draws info about crouch able to switch between third and firstperson if HEALRAY.Thirdperson and HEALRAY.AllowSwitchFromToThirdperson and IsValid(LocalPlayer():GetNWEntity("tazerviewrag")) then local txt = string.format("Press %s to switch between third and firstperson view.", input.LookupBinding("+duck")) draw.SimpleText(txt, "TargetID", ScrW()/2 + 1, 10 + 1, Color(0,0,0,255), 1) draw.SimpleText(txt, "TargetID", ScrW()/2, 10, Color(200,200,200,255), 1) end --Draws custom targetids on rags if not HEALRAY.ShowPlayerInfo then return end local targ = LocalPlayer():GetEyeTrace().Entity if IsValid(targ) and IsValid(targ:GetNWEntity("plyowner")) and LocalPlayer():GetPos():Distance(targ:GetPos()) < 400 then local pos = targ:GetPos():ToScreen() if IsOnScreen(pos) then local ply = targ:GetNWEntity("plyowner") local nick,nickclr,font = GrabPlyInfo(ply) if not nick then return end -- Someone doesn't want us to draw his info. draw.DrawText(nick, font, pos.x-1, pos.y - 51, Color(0,0,0), 1) draw.DrawText(nick, font, pos.x, pos.y - 50, nickclr, 1) local hp = (ply.newhp and ply.newhp or ply:Health()) if HEALRAY.IsTTT then local txt,clr = util.HealthToString(hp) -- Grab TTT Data txt = LANG.GetUnsafeLanguageTable()[txt] -- Convert to whatever language draw.DrawText(txt, "TargetIDSmall2", pos.x-1, pos.y - 31, Color(0,0,0), 1) draw.DrawText(txt, "TargetIDSmall2", pos.x, pos.y - 30, clr, 1) else local txt = hp.."%" draw.DrawText(txt, "TargetID", pos.x-1, pos.y - 31, Color(0,0,0), 1) draw.DrawText(txt, "TargetID", pos.x, pos.y - 30, Color(255,255,255,200), 1) end end end end) --For some reason, when they're ragdolled their hp isn't sent properly to the clients. net.Receive("tazersendhealth", function() local ent = net.ReadEntity() local newhp = net.ReadInt(32) ent.newhp = newhp end) --[[ /******************************************************** SWEP Construction Kit base code Created by Clavus Available for public use, thread at: facepunch.com/threads/1032378 ********************************************************/ ]] local boltpositions local boltcount local poly local glowtimer = 0 local bolt1 = Material("stungun/lightningbolt.png") local bolt1_o = Material("stungun/lightningbolt_outline.png") local bolt1_g = Material("stungun/lightningbolt_glow.png") local bolt2 = Material("stungun/lightningbolt2.png") function SWEP:DrawScreen(x, y, w, h) local frac = (self.Charge or 0) / 100 local fracinv = 1 - frac if frac >= 1 then glowtimer = glowtimer + 1 else glowtimer = 0 end local bx, by = x + w/2 - 16, y + h/2 - 32 + 10 if not poly then --[[ /* Setup boltpositions */ ]] boltpositions = {} local v local a for i=-30,30,14 do v = Vector(0,by - 25,0) a = Angle(0,i,0) v:Rotate(a) table.insert(boltpositions, {pos = v, ang = a}) end boltcount = #boltpositions --[[ /* Setup polygon */ ]] poly = {{ x = bx, y = by + (fracinv * 64), u = 0, v = fracinv },{ x = bx + 32, y = by + (fracinv * 64), u = 1, v = fracinv },{ x = bx + 32, y = by + 64, u = 1, v = 1 },{ x = bx, y = by + 64, u = 0, v = 1 }} end --[[ /* Bolt fill */ ]] surface.SetDrawColor(Color(255,255,255,255)) surface.SetMaterial(bolt1) poly[1].y = by + (fracinv * 64) poly[1].v = fracinv poly[2].y = poly[1].y poly[2].v = poly[1].v surface.DrawPoly(poly) --[[ /* Bolt outline */ ]] surface.SetMaterial(bolt1_o) surface.DrawTexturedRect(bx, by, 32, 64) --[[ /* Small bolts */ ]] surface.SetMaterial(bolt2) local a for k,v in pairs(boltpositions) do a = math.Clamp((frac * (254 * boltcount)) - (254*(k-1)), 0, 254) surface.SetDrawColor(Color(0,0,255,a + 1)) surface.DrawTexturedRectRotated(v.pos.x + (x + w/2), v.pos.y, 16, 32, -(v.ang.y)) end --[[ /* Bolt glow */ ]] surface.SetDrawColor(Color(255,255,255,math.cos(glowtimer/40 + math.pi) * 50 + 50)) surface.SetMaterial(bolt1_g) surface.DrawTexturedRect(bx-16, by-32, 64, 128) end function SWEP:Initialize() -- Create a new table for every weapon instance self.VElements = table.FullCopy( self.VElements ) self.WElements = table.FullCopy( self.WElements ) self.ViewModelBoneMods = table.FullCopy( self.ViewModelBoneMods ) self:CreateModels(self.VElements) -- create viewmodels self:CreateModels(self.WElements) -- create worldmodels -- init view model bone build function --[[ /*if IsValid(self.Owner) then local vm = self.Owner:GetViewModel() if IsValid(vm) then self:ResetBonePositions(vm) vm:DrawShadow( false ) vm:SetMaterial( "models/effects/vol_light001" ) vm:SetRenderMode( RENDERMODE_TRANSALPHA ) end end*/ ]] self.VElements["counter"].draw_func = function() self:DrawScreen(-27,-65,65,123) end end function SWEP:Holster() return true end function SWEP:Deploy() self:SendWeaponAnim(ACT_VM_DRAW) return true end function SWEP:OnRemove() self:Holster() end function SWEP:OnDrop() self:Holster() end net.Receive("tazerondrop",function() local swep = net.ReadEntity() swep:OnDrop() end) SWEP.vRenderOrder = nil function SWEP:ViewModelDrawn() local vm = self.Owner:GetViewModel() if not IsValid(vm) then return end if (not self.VElements) then return end self:UpdateBonePositions(vm) if (not self.vRenderOrder) then -- we build a render order because sprites need to be drawn after models self.vRenderOrder = {} for k, v in pairs( self.VElements ) do if (v.type == "Model") then table.insert(self.vRenderOrder, 1, k) elseif (v.type == "Sprite" or v.type == "Quad") then table.insert(self.vRenderOrder, k) end end end for k, name in ipairs( self.vRenderOrder ) do local v = self.VElements[name] if (not v) then self.vRenderOrder = nil break end if (v.hide) then continue end local model = v.modelEnt local sprite = v.spriteMaterial if (!v.bone) then continue end local pos, ang = self:GetBoneOrientation( self.VElements, v, vm ) if (!pos) then continue end if (v.type == "Model" and IsValid(model)) then model:SetPos(pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z ) ang:RotateAroundAxis(ang:Up(), v.angle.y) ang:RotateAroundAxis(ang:Right(), v.angle.p) ang:RotateAroundAxis(ang:Forward(), v.angle.r) model:SetAngles(ang) --model:SetModelScale(v.size) local matrix = Matrix() matrix:Scale(v.size) model:EnableMatrix( "RenderMultiply", matrix ) if (v.material == "") then model:SetMaterial("") elseif (model:GetMaterial() ~= v.material) then model:SetMaterial( v.material ) end if (v.skin and v.skin ~= model:GetSkin()) then model:SetSkin(v.skin) end if (v.bodygroup) then for k, v in pairs( v.bodygroup ) do if (model:GetBodygroup(k) ~= v) then model:SetBodygroup(k, v) end end end if (v.surpresslightning) then render.SuppressEngineLighting(true) end render.SetColorModulation(v.color.r/255, v.color.g/255, v.color.b/255) render.SetBlend(v.color.a/255) model:DrawModel() render.SetBlend(1) render.SetColorModulation(1, 1, 1) if (v.surpresslightning) then render.SuppressEngineLighting(false) end elseif (v.type == "Sprite" and sprite) then local drawpos = pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z render.SetMaterial(sprite) render.DrawSprite(drawpos, v.size.x, v.size.y, v.color) elseif (v.type == "Quad" and v.draw_func) then local drawpos = pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z ang:RotateAroundAxis(ang:Up(), v.angle.y) ang:RotateAroundAxis(ang:Right(), v.angle.p) ang:RotateAroundAxis(ang:Forward(), v.angle.r) cam.Start3D2D(drawpos, ang, v.size) v.draw_func( self ) cam.End3D2D() end end end SWEP.wRenderOrder = nil function SWEP:DrawWorldModel() --Fixes worldmodel being seen in firstperson spectating local viewent = LocalPlayer():GetObserverTarget() if IsValid(viewent) and viewent ~= LocalPlayer() and viewent == self.Owner then return end if (self.ShowWorldModel == nil or self.ShowWorldModel) then self:DrawModel() end if (!self.WElements) then return end if (!self.wRenderOrder) then self.wRenderOrder = {} for k, v in pairs( self.WElements ) do if (v.type == "Model") then table.insert(self.wRenderOrder, 1, k) elseif (v.type == "Sprite" or v.type == "Quad") then table.insert(self.wRenderOrder, k) end end end if (IsValid(self.Owner)) then bone_ent = self.Owner else -- when the weapon is dropped bone_ent = self end for k, name in pairs( self.wRenderOrder ) do local v = self.WElements[name] if (!v) then self.wRenderOrder = nil break end if (v.hide) then continue end local pos, ang if (v.bone) then pos, ang = self:GetBoneOrientation( self.WElements, v, bone_ent ) else pos, ang = self:GetBoneOrientation( self.WElements, v, bone_ent, "ValveBiped.Bip01_R_Hand" ) end if (!pos) then continue end local model = v.modelEnt local sprite = v.spriteMaterial if (v.type == "Model" and IsValid(model)) then model:SetPos(pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z ) ang:RotateAroundAxis(ang:Up(), v.angle.y) ang:RotateAroundAxis(ang:Right(), v.angle.p) ang:RotateAroundAxis(ang:Forward(), v.angle.r) model:SetAngles(ang) --model:SetModelScale(v.size) local matrix = Matrix() matrix:Scale(v.size) model:EnableMatrix( "RenderMultiply", matrix ) if (v.material == "") then model:SetMaterial("") elseif (model:GetMaterial() != v.material) then model:SetMaterial( v.material ) end if (v.skin and v.skin != model:GetSkin()) then model:SetSkin(v.skin) end if (v.bodygroup) then for k, v in pairs( v.bodygroup ) do if (model:GetBodygroup(k) != v) then model:SetBodygroup(k, v) end end end if (v.surpresslightning) then render.SuppressEngineLighting(true) end render.SetColorModulation(v.color.r/255, v.color.g/255, v.color.b/255) render.SetBlend(v.color.a/255) model:DrawModel() render.SetBlend(1) render.SetColorModulation(1, 1, 1) if (v.surpresslightning) then render.SuppressEngineLighting(false) end elseif (v.type == "Sprite" and sprite) then local drawpos = pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z render.SetMaterial(sprite) render.DrawSprite(drawpos, v.size.x, v.size.y, v.color) elseif (v.type == "Quad" and v.draw_func) then local drawpos = pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z ang:RotateAroundAxis(ang:Up(), v.angle.y) ang:RotateAroundAxis(ang:Right(), v.angle.p) ang:RotateAroundAxis(ang:Forward(), v.angle.r) cam.Start3D2D(drawpos, ang, v.size) v.draw_func( self ) cam.End3D2D() end end end function SWEP:GetBoneOrientation( basetab, tab, ent, bone_override ) local bone, pos, ang if (tab.rel and tab.rel != "") then local v = basetab[tab.rel] if (!v) then return end -- Technically, if there exists an element with the same name as a bone -- you can get in an infinite loop. Let's just hope nobody's that stupid. pos, ang = self:GetBoneOrientation( basetab, v, ent ) if (!pos) then return end pos = pos + ang:Forward() * v.pos.x + ang:Right() * v.pos.y + ang:Up() * v.pos.z ang:RotateAroundAxis(ang:Up(), v.angle.y) ang:RotateAroundAxis(ang:Right(), v.angle.p) ang:RotateAroundAxis(ang:Forward(), v.angle.r) else bone = ent:LookupBone(bone_override or tab.bone) if (!bone) then return end pos, ang = Vector(0,0,0), Angle(0,0,0) local m = ent:GetBoneMatrix(bone) if (m) then pos, ang = m:GetTranslation(), m:GetAngles() end if (IsValid(self.Owner) and self.Owner:IsPlayer() and ent == self.Owner:GetViewModel() and self.ViewModelFlip) then ang.r = -ang.r -- Fixes mirrored models end end return pos, ang end function SWEP:CreateModels( tab ) if (!tab) then return end -- Create the clientside models here because Garry says we can't do it in the render hook for k, v in pairs( tab ) do if (v.type == "Model" and v.model and v.model != "" and (!IsValid(v.modelEnt) or v.createdModel != v.model) and string.find(v.model, ".mdl") and file.Exists (v.model, "GAME") ) then v.modelEnt = ClientsideModel(v.model, RENDER_GROUP_VIEW_MODEL_OPAQUE) if (IsValid(v.modelEnt)) then v.modelEnt:SetPos(self:GetPos()) v.modelEnt:SetAngles(self:GetAngles()) v.modelEnt:SetParent(self) v.modelEnt:SetNoDraw(true) v.createdModel = v.model else v.modelEnt = nil end elseif (v.type == "Sprite" and v.sprite and v.sprite != "" and (!v.spriteMaterial or v.createdSprite != v.sprite) and file.Exists ("materials/"..v.sprite..".vmt", "GAME")) then local name = v.sprite.."-" local params = { ["$basetexture"] = v.sprite } -- make sure we create a unique name based on the selected options local tocheck = { "nocull", "additive", "vertexalpha", "vertexcolor", "ignorez" } for i, j in pairs( tocheck ) do if (v[j]) then params["$"..j] = 1 name = name.."1" else name = name.."0" end end v.createdSprite = v.sprite v.spriteMaterial = CreateMaterial(name,"UnlitGeneric",params) end end end local allbones local hasGarryFixedBoneScalingYet = false function SWEP:UpdateBonePositions(vm) if self.ViewModelBoneMods then if (!vm:GetBoneCount()) then return end -- !! WORKAROUND !! -- -- We need to check all model names :/ local loopthrough = self.ViewModelBoneMods if (!hasGarryFixedBoneScalingYet) then allbones = {} for i=0, vm:GetBoneCount() do local bonename = vm:GetBoneName(i) if (self.ViewModelBoneMods[bonename]) then allbones[bonename] = self.ViewModelBoneMods[bonename] else allbones[bonename] = { scale = Vector(1,1,1), pos = Vector(0,0,0), angle = Angle(0,0,0) } end end loopthrough = allbones end -- !! ----------- !! -- for k, v in pairs( loopthrough ) do local bone = vm:LookupBone(k) if (!bone) then continue end -- !! WORKAROUND !! -- local s = Vector(v.scale.x,v.scale.y,v.scale.z) local p = Vector(v.pos.x,v.pos.y,v.pos.z) local ms = Vector(1,1,1) if (!hasGarryFixedBoneScalingYet) then local cur = vm:GetBoneParent(bone) while(cur >= 0) do local pscale = loopthrough[vm:GetBoneName(cur)].scale ms = ms * pscale cur = vm:GetBoneParent(cur) end end s = s * ms -- !! ----------- !! -- if vm:GetManipulateBoneScale(bone) != s then vm:ManipulateBoneScale( bone, s ) end if vm:GetManipulateBoneAngles(bone) != v.angle then vm:ManipulateBoneAngles( bone, v.angle ) end if vm:GetManipulateBonePosition(bone) != p then vm:ManipulateBonePosition( bone, p ) end end else self:ResetBonePositions(vm) end end function SWEP:ResetBonePositions(vm) if (!vm:GetBoneCount()) then return end for i=0, vm:GetBoneCount() do vm:ManipulateBoneScale( i, Vector(1, 1, 1) ) vm:ManipulateBoneAngles( i, Angle(0, 0, 0) ) vm:ManipulateBonePosition( i, Vector(0, 0, 0) ) end end /************************** Global utility code **************************/ -- Fully copies the table, meaning all tables inside this table are copied too and so on (normal table.Copy copies only their reference). -- Does not copy entities of course, only copies their reference. -- WARNING: do not use on tables that contain themselves somewhere down the line or you'll get an infinite loop function table.FullCopy( tab ) if (!tab) then return nil end local res = {} for k, v in pairs( tab ) do if (type(v) == "table") then res[k] = table.FullCopy(v) -- recursion ho! elseif (type(v) == "Vector") then res[k] = Vector(v.x, v.y, v.z) elseif (type(v) == "Angle") then res[k] = Angle(v.p, v.y, v.r) else res[k] = v end end return res end
-- markdown ftplugin vim.opt_local.colorcolumn = "101" vim.opt.autoindent = true vim.opt.linebreak = true -- @TODOUA: -- spell is not staying local for some reason -- have to set nospell in other fts that are opened after a markdown vim.opt_local.spell = true vim.opt_local.conceallevel = 2 -- Markdown Preview in browser -- For Glow, just type :Glow, I almost never use the :MarkdownPreview keymap, I type it. vim.api.nvim_buf_set_keymap(0, "n", ",md", "<Plug>MarkdownPreview", { noremap = false }) -- toggle TS highlighting for markdown vim.api.nvim_buf_set_keymap(0, "n", ",th", ":TSBufToggle highlight<CR>", { noremap = false }) -- wrap selection in markdown link vim.api.nvim_buf_set_keymap(0, "v", ",wl", [[c[<c-r>"]()<esc>]], { noremap = false }) vim.api.nvim_exec( [[ " arrows iabbrev >> → iabbrev << ← iabbrev ^^ ↑ iabbrev VV ↓ " eunuch map nmap <buffer><silent><localleader>rn :Rename<space> " snippets for markdown let b:vsnip_snippet_dir = expand('~/.config/nvim/snippets/') ]], false ) vim.api.nvim_exec( [[ augroup PersistMarkdownFolds autocmd! autocmd BufWinLeave *.md mkview autocmd BufWinEnter *.md silent! loadview augroup end ]], false ) -- match and highlight hyperlinks -- -- standalone vim.fn.matchadd("matchURL", [[http[s]\?:\/\/[[:alnum:]%\/_#.-]*]]) vim.cmd "hi matchURL guifg=DodgerBlue" -- Setup cmp setup buffer configuration - 👻 text off for markdown local cmp = require "cmp" cmp.setup.buffer { sources = { { name = "vsnip" }, { name = "spell" }, { name = "buffer", option = { get_bufnrs = function() -- @TODOUA: Trying out just populate from visible buffers. Keep? local bufs = {} for _, win in ipairs(vim.api.nvim_list_wins()) do bufs[vim.api.nvim_win_get_buf(win)] = true end return vim.tbl_keys(bufs) end, }, }, { name = "path" }, }, experimental = { ghost_text = false, }, }
------------------------------------------------------------------------------ --Load origin framework ------------------------------------------------------------------------------ cc.LuaLoadChunksFromZIP("res/framework_precompiled.zip") ------------------------------------------------------------------------------ --If you would update the modoules which have been require here, --you can reset them, and require them again in modoule "appentry" ------------------------------------------------------------------------------ require("config") require("framework.init") ------------------------------------------------------------------------------ --define UpdateScene ------------------------------------------------------------------------------ local UpdateScene = class("UpdateScene", function() return display.newScene("UpdateScene") end) local NEEDUPDATE = false --local server = "https://raw.githubusercontent.com/hanxi/quick-cocos2d-x-2048/release/" local server = "http://192.168.16.13:8080/" local param = "?dev="..device.platform local list_filename = "flist" local downList = {} local function hex(s) s=string.gsub(s,"(.)",function (x) return string.format("%02X",string.byte(x)) end) return s end local function readFile(path) local file = io.open(path, "rb") if file then local content = file:read("*all") io.close(file) return content end return nil end local function removeFile(path) --CCLuaLog("removeFile: "..path) io.writefile(path, "") if device.platform == "windows" then --os.execute("del " .. string.gsub(path, '/', '\\')) else os.execute("rm " .. path) end end local function checkFile(fileName, cryptoCode) print("checkFile:", fileName) print("cryptoCode:", cryptoCode) if not io.exists(fileName) then return false end local data=readFile(fileName) if data==nil then return false end if cryptoCode==nil then return true end local ms = crypto.md5(hex(data)) print("file cryptoCode:", ms) if ms==cryptoCode then return true end return false end local function checkDirOK( path ) require "lfs" local oldpath = lfs.currentdir() CCLuaLog("old path------> "..oldpath) if lfs.chdir(path) then lfs.chdir(oldpath) CCLuaLog("path check OK------> "..path) return true end if lfs.mkdir(path) then CCLuaLog("path create OK------> "..path) return true end end function UpdateScene:ctor() self.path = device.writablePath.."upd/" --if device.platform == "android" then -- self.path = "/mnt/sdcard/quick_x_update/" --end local label = cc.ui.UILabel.new({ UILabelType = 2, text = "Loading...", size = 64, x = display.cx, y = display.cy, align = cc.ui.TEXT_ALIGN_CENTER }) self:addChild(label) end function UpdateScene:updateFiles() local data = readFile(self.newListFile) io.writefile(self.curListFile, data) self.fileList = dofile(self.curListFile) if self.fileList==nil then self:endProcess() return end removeFile(self.newListFile) for i,v in ipairs(downList) do print(i,v) local data=readFile(v) local fn = string.sub(v, 1, -5) print("fn: ", fn) io.writefile(fn, data) removeFile(v) end self:endProcess() end function UpdateScene:reqNextFile() self.numFileCheck = self.numFileCheck+1 self.curStageFile = self.fileListNew.stage[self.numFileCheck] if self.curStageFile and self.curStageFile.name then local fn = self.path..self.curStageFile.name if checkFile(fn, self.curStageFile.code) then self:reqNextFile() return end fn = fn..".upd" if checkFile(fn, self.curStageFile.code) then table.insert(downList, fn) self:reqNextFile() return end self:requestFromServer(self.curStageFile.name) return end self:updateFiles() end function UpdateScene:onEnterFrame(dt) if self.dataRecv then if self.requesting == list_filename then io.writefile(self.newListFile, self.dataRecv) self.dataRecv = nil self.fileListNew = dofile(self.newListFile) if self.fileListNew==nil then CCLuaLog(self.newListFile..": Open Error!") self:endProcess() return end CCLuaLog(self.fileListNew.ver) if self.fileListNew.ver==self.fileList.ver then self:endProcess() return end self.numFileCheck = 0 self.requesting = "files" self:reqNextFile() return end if self.requesting == "files" then local fn = self.path..self.curStageFile.name..".upd" io.writefile(fn, self.dataRecv) self.dataRecv = nil if checkFile(fn, self.curStageFile.code) then table.insert(downList, fn) self:reqNextFile() else self:endProcess() end return end return end end function UpdateScene:onEnter() if not checkDirOK(self.path) then require("appentry") return end self.curListFile = self.path..list_filename self.fileList = nil if io.exists(self.curListFile) then self.fileList = dofile(self.curListFile) end if self.fileList==nil then self.fileList = { ver = "1.0.0", stage = {}, remove = {}, } end self.requestCount = 0 self.requesting = list_filename self.newListFile = self.curListFile..".upd" self.dataRecv = nil self:requestFromServer(self.requesting) self:addNodeEventListener(cc.NODE_ENTER_FRAME_EVENT, function(dt) self:onEnterFrame(dt) end) self:scheduleUpdate() end function UpdateScene:onExit() end function UpdateScene:endProcess() CCLuaLog("----------------------------------------UpdateScene:endProcess") if self.fileList and self.fileList.stage then local checkOK = true for i,v in ipairs(self.fileList.stage) do if not checkFile(self.path..v.name, v.code) then CCLuaLog("----------------------------------------Check Files Error") checkOK = false break end end if checkOK then for i,v in ipairs(self.fileList.stage) do if v.act=="load" then cc.LuaLoadChunksFromZIP(self.path..v.name) end end for i,v in ipairs(self.fileList.remove) do removeFile(self.path..v) end else removeFile(self.curListFile) end end require("appentry") end function UpdateScene:requestFromServer(filename, waittime) local url = server..filename..param self.requestCount = self.requestCount + 1 local index = self.requestCount local request = nil if NEEDUPDATE then request = network.createHTTPRequest(function(event) self:onResponse(event, index) end, url, "GET") end if request then request:setTimeout(waittime or 30) request:start() else self:endProcess() end end function UpdateScene:onResponse(event, index, dumpResponse) local request = event.request printf("REQUEST %d - event.name = %s", index, event.name) if event.name == "completed" then printf("REQUEST %d - getResponseStatusCode() = %d", index, request:getResponseStatusCode()) --printf("REQUEST %d - getResponseHeadersString() =\n%s", index, request:getResponseHeadersString()) if request:getResponseStatusCode() ~= 200 then self:endProcess() else printf("REQUEST %d - getResponseDataLength() = %d", index, request:getResponseDataLength()) if dumpResponse then printf("REQUEST %d - getResponseString() =\n%s", index, request:getResponseString()) end self.dataRecv = request:getResponseData() end elseif event.name ~= "progress" then printf("REQUEST %d - getErrorCode() = %d, getErrorMessage() = %s", index, request:getErrorCode(), request:getErrorMessage()) self:endProcess() end print("----------------------------------------") end local upd = UpdateScene.new() display.replaceScene(upd)
--[[ Pong Remake - -- Cursor Class -- Author: Aamer Shikari [email protected] A class that mimics a switch in so far as it value is dependant on whether or not a given game mode is chosen in the start screen. Object changes location and value dependent depending on user input. ]] Cursor = Class{} function Cursor:init(x, y, width, height, opts) self.width = width self.height = height self.x = x self.y = y self.option = 0 self.max = opts - 1 self.startX = x self.startY = y -- Variables help to create a starting position and value for the cursor end --[[ Modifies the value of option depending on user keyboard input of up/down ]] function Cursor:change(direction) if (direction == "up") then if (self.option == 0) then else self.option = self.option - 1 self.y = self.y - 30 end else if (self.option == self.max) then else self.option = self.option + 1 self.y = self.y + 30 end end end -- Getter function for the option boolean function Cursor:getOpt() return self.option end function Cursor:render() love.graphics.rectangle('fill', self.x, self.y, self.width, self.height) end function Cursor:reset() self.option = 0 self.x = self.startX self.y = self.startY end
-- -- language.lua -- language widget -- local awful = require("awful") local wibox = require("wibox") local gears = require("gears") local beautiful = require("beautiful") local helpers = require("helpers") local keys = require("keys") -- ======================================== -- Config -- ======================================== -- icons path local icons_path = beautiful.icons_path .. "language/" -- ======================================== -- Definition -- ======================================== -- define buttons local buttons = function (screen) return gears.table.join( awful.button( {}, keys.leftclick, helpers.switch_language ), awful.button( {}, keys.rightclick, function() awful.spawn("ibus-setup") end ) ) end -- update language icon local update_language_icon = function (widget, language) widget.image = icons_path .. language .. ".svg" widget.tooltip.text = language == "unknown" and "Keyboard layout unknown" or "Keyboard layout is set to " .. language end -- create widget instance local create_widget = function (screen) local widget = wibox.widget { image = icons_path .. "unknown.svg", widget = wibox.widget.imagebox, } awesome.connect_signal("daemon::language", function (...) update_language_icon(widget, ...) end) local container = require("widgets.clickable_container")(widget) container:buttons(buttons(screen)) widget.tooltip = require("widgets.tooltip")({ container }) widget.tooltip.text = "Keyboard layout unknown" return container end return create_widget
data:extend({ { type = "item", name = "liquify2-liquifier", icon = "__Liquify__/graphics/gearbox.png", icon_size = 64, icon_mipmaps = 4, stack_size = data.raw["item"]["electric-mining-drill"].stack_size / 2, place_result = "liquify2-liquifier", subgroup = "extraction-machine", order = "a[items]-a[liquify2-liquifier]", }, { type = "recipe", name = "liquify2-liquifier", energy_required = data.raw["recipe"]["electric-mining-drill"].normal.energy_required * 2, enabled = true, ingredients = { {"pipe" , 03}, {"iron-gear-wheel", 02}, {"iron-chest" , 01}, }, result = "liquify2-liquifier", }, { type = "recipe-category", name = "liquify2", }, { type = "assembling-machine", name = "liquify2-liquifier", icon = "__Liquify__/graphics/gearbox.png", icon_size = 64, icon_mipmaps = 4, crafting_speed = 1, crafting_categories = {"liquify2"}, ingredient_count = 1, flags = {"not-rotatable", "player-creation", "placeable-player"}, scale_entity_info_icon = true, entity_info_icon_shift = {0, 0}, minable = {hardness = 1, mining_time = 1, result = "liquify2-liquifier"}, fluid_boxes = { { production_type = "output", pipe_covers = pipecoverspictures(), base_area = 1, height = 4, pipe_connections = { { type="input-output", position = {-2, 0} }, { type="input-output", position = {2, 0} }, } }, off_when_no_fluid_recipe = false }, collision_box = {{-1.4, -0.4}, {1.4, 0.4}}, selection_box = {{-1.5, -0.5}, {1.5, 0.5}}, animation = { layers = { { filename = "__Liquify__/graphics/liquifier.png", priority = "high", width = 192, height = 128, scale = 0.5, }, { filename = "__Liquify__/graphics/liquifier-mask.png", width = 192, height = 128, scale = 0.5, } } }, energy_source = { usage_priority = data.raw["mining-drill"]["electric-mining-drill"].energy_source.usage_priority, emissions_per_minute = 25, type = "electric", drain = "1kW", }, energy_usage = "249kW", working_visualisations = { { apply_recipe_tint = "primary", always_draw = true, animation = { filename = "__Liquify__/graphics/liquifier-mask.png", width = 192, height = 128, scale = 0.5, }, } }, } });
-- This software is copyright Kong Inc. and its licensors. -- Use of the software is subject to the agreement between your organization -- and Kong Inc. If there is no such agreement, use is governed by and -- subject to the terms of the Kong Master Software License Agreement found -- at https://konghq.com/enterprisesoftwarelicense/. -- [ END OF LICENSE 0867164ffc95e54f04670b5169c09574bdbd9bba ] local BasePlugin = require "kong.plugins.base_plugin" local error = error local ErrorGeneratorHandler = BasePlugin:extend() ErrorGeneratorHandler.PRIORITY = math.huge function ErrorGeneratorHandler:new() ErrorGeneratorHandler.super.new(self, "error-generator") end function ErrorGeneratorHandler:init_worker() ErrorGeneratorHandler.super.init_worker(self) end function ErrorGeneratorHandler:certificate(conf) ErrorGeneratorHandler.super.certificate(self) if conf.certificate then error("[error-generator] certificate") end end function ErrorGeneratorHandler:rewrite(conf) ErrorGeneratorHandler.super.rewrite(self) if conf.rewrite then error("[error-generator] rewrite") end end function ErrorGeneratorHandler:preread(conf) ErrorGeneratorHandler.super.preread(self) if conf.preread then error("[error-generator] preread") end end function ErrorGeneratorHandler:access(conf) ErrorGeneratorHandler.super.access(self) if conf.access then error("[error-generator] access") end end function ErrorGeneratorHandler:header_filter(conf) ErrorGeneratorHandler.super.header_filter(self) if conf.header_filter then error("[error-generator] header_filter") end end function ErrorGeneratorHandler:body_filter(conf) ErrorGeneratorHandler.super.body_filter(self) if conf.header_filter then error("[error-generator] body_filter") end end function ErrorGeneratorHandler:log(conf) ErrorGeneratorHandler.super.log(self) if conf.log then error("[error-generator] body_filter") end end return ErrorGeneratorHandler
local ffi = require "ffi" local ffi_cdef = ffi.cdef ffi_cdef[[ typedef unsigned long mp_limb_t; typedef struct { int _mp_alloc; int _mp_size; mp_limb_t *_mp_d; } __mpz_struct; typedef const __mpz_struct *mpz_srcptr; typedef __mpz_struct mpz_t[1]; typedef __mpz_struct *mpz_ptr; ]]
local DbgPrint = GetLogging("PathTracker") ENT.Base = "lambda_entity" ENT.Type = "point" DEFINE_BASECLASS("lambda_entity") function ENT:PreInitialize() BaseClass.PreInitialize(self) DbgPrint(self, "PreInitialize") self:SetInputFunction("OnPass", self.OnPass) end function ENT:Initialize() BaseClass.Initialize(self) DbgPrint(self, "Initialize") end -- HACKHACK: Since we can't call CBaseEntity::OnRestore we have to manually -- set the next track target. function ENT:OnPass(data, activator, caller) local nextTarget = caller:GetInternalVariable("target") DbgPrint(self, "Passed : " .. tostring(activator), caller, nextTarget) activator:SetSaveValue("target", nextTarget) activator:SetKeyValue("target", nextTarget) end function ENT:UpdateTransmitState() return TRANSMIT_NEVER end
socket = require("socket") json = require("dkjson") require("util") require("consts") require("class") require("queue") require("globals") require("character") -- after globals! require("stage") -- after globals! require("analytics") require("save") require("engine") require("localization") require("graphics") require("input") require("network") require("puzzles") require("mainloop") require("sound") require("timezones") require("gen_panels") global_canvas = love.graphics.newCanvas(canvas_width, canvas_height) local last_x = 0 local last_y = 0 local input_delta = 0.0 local pointer_hidden = false function love.load() math.randomseed(os.time()) for i=1,4 do math.random() end read_key_file() mainloop = coroutine.create(fmainloop) end function love.update(dt) if love.mouse.getX() == last_x and love.mouse.getY() == last_y then if not pointer_hidden then if input_delta > mouse_pointer_timeout then pointer_hidden = true love.mouse.setVisible(false) else input_delta = input_delta + dt end end else last_x = love.mouse.getX() last_y = love.mouse.getY() input_delta = 0.0 if pointer_hidden then pointer_hidden = false love.mouse.setVisible(true) end end leftover_time = leftover_time + dt local status, err = coroutine.resume(mainloop) if not status then error(err..'\n'..debug.traceback(mainloop)) end this_frame_messages = {} update_music() end function love.draw() -- if not main_font then -- main_font = love.graphics.newFont("Oswald-Light.ttf", 15) -- end -- main_font:setLineHeight(0.66) -- love.graphics.setFont(main_font) love.graphics.setBlendMode("alpha", "alphamultiply") love.graphics.setCanvas(global_canvas) love.graphics.setBackgroundColor(unpack(global_background_color)) love.graphics.clear() for i=gfx_q.first,gfx_q.last do gfx_q[i][1](unpack(gfx_q[i][2])) end gfx_q:clear() if config ~= nil and config.show_fps then love.graphics.print("FPS: "..love.timer.getFPS(),1,1) end love.graphics.setCanvas() love.graphics.clear(love.graphics.getBackgroundColor()) x, y, w, h = scale_letterbox(love.graphics.getWidth(), love.graphics.getHeight(), 16, 9) love.graphics.setBlendMode("alpha","premultiplied") love.graphics.draw(global_canvas, x, y, 0, w / canvas_width, h / canvas_height) local scale = canvas_width/math.max(bg:getWidth(),bg:getHeight()) -- keep image ratio menu_drawf(bg, canvas_width/2, canvas_height/2, "center", "center", 0, scale, scale ) end
local dnsutils = require "dns.utils" local pretty = require("pl.pretty").write print("resolv.conf file;") print(pretty(dnsutils.parseResolvConf())) print("\nresolv.conf environment settings;") print(pretty(dnsutils.applyEnv({}))) print("\nresolv.conf including environment settings;") print(pretty(dnsutils.applyEnv(dnsutils.parseResolvConf()))) local rev, all = dnsutils.parseHosts() print("\nHosts file (all entries);") print(pretty(all)) print("\nHosts file (reverse lookup);") print(pretty(rev))
local adam = require("adam.adam") local actions = require("adam.actions") return function() describe("Math actions", function() local adam_instance, state_instance before(function() state_instance = adam.state() adam_instance = adam.new(state_instance, {}, { value = 0 }) end) after(function() adam_instance:final() end) test("Action Math Set", function() local math_action = actions.math.add("value", 1) math_action:set_state_instance(state_instance) math_action:trigger() assert_equal(2, adam_instance:get_value("value")) end) end) end
require('lspconfig').clangd.setup { capabilities = require('cmp_nvim_lsp').update_capabilities(vim.lsp.protocol.make_client_capabilities()), cmd = { "clangd", "--background-index", "--compile-commands-dir=build/" } } require('lspconfig').hls.setup { capabilities = require('cmp_nvim_lsp').update_capabilities(vim.lsp.protocol.make_client_capabilities()), -- cmd = { "clangd", "--background-index", "--compile-commands-dir=build/" } cmd = { "haskell-language-server-wrapper", "--lsp" }, filetypes = { "haskell", "lhaskell" }, settings = { haskell = { formattingProvider = "ormolu" } } } require('lspconfig').cmake.setup { capabilities = require('cmp_nvim_lsp').update_capabilities(vim.lsp.protocol.make_client_capabilities()) } require('lspconfig').rust_analyzer.setup { capabilities = require('cmp_nvim_lsp').update_capabilities(vim.lsp.protocol.make_client_capabilities()), settings = { ["rust-analyzer"] = { assist = { importGranularity = "module", importPrefix = "by_self", }, cargo = { loadOutDirsFromCheck = true }, procMacro = { enable = true }, } } }
-- Copyright (c) 2020 Trevor Redfern -- -- This software is released under the MIT License. -- https://opensource.org/licenses/MIT local safecall = require "moonpie.utility.safe_call" local class = {} function class:subclass(prototype) setmetatable(prototype, { __index = self, __call = self.new }) return prototype end function class:new(...) local instance = {} setmetatable(instance, { __index = self, __call = self.new }) safecall(instance.constructor, instance, ...) return instance end setmetatable(class, { __call = class.subclass }) return class
project = "Plugin Name" title = "Plugin Title" description = "Plugin Description" full_description = "Plugin Full Description" not_luadoc = true format = "markdown" style = true examples = "examples" readme = "README.md" custom_tags = { { "link", title = "Links", format = function(text) local name = text:gsub("%s*(.*) http.*", "%1", 1) local link = text:gsub(".* (http.*)%s*", "%1", 1) local fmt = '<a href="%s">%s</a>' return fmt:format(link, name) end, }, { "homepage" }, } alias("tfield", { "field", modifiers = { type = "$1" } })
-------------------------------------------------------------------------------- -- Example of a problem on 1D line segments in 2D -- (C) G-CSC, Uni Frankfurt, 2021 -------------------------------------------------------------------------------- ug_load_script("ug_util.lua") ug_load_script("util/profiler_util.lua") ug_load_script("util/load_balancing_util.lua") --local gridName = util.GetParam("-grid", "grids/simple-river-y.ugx") local gridName = util.GetParam("-grid", "grids/simple-river.ugx") local charLength = 3.0 local ARGS = {} ARGS.eps = 1.0 -- diffusion constant ARGS.dim = util.GetParamNumber("-dim", 2, "dimension") ARGS.numPreRefs = util.GetParamNumber("-numPreRefs", 0, "number of refinements before parallel distribution") ARGS.numRefs = util.GetParamNumber("-numRefs", 6, "number of refinements") ARGS.startTime = util.GetParamNumber("-start", 0.0, "start time") ARGS.endTime = util.GetParamNumber("-end", 0.2*charLength*charLength/ARGS.eps, "end time") ARGS.dt = util.GetParamNumber("-dt", ARGS.endTime*5e-4, "time step size") util.CheckAndPrintHelp("Time-dependent problem setup example"); print(" Choosen Parameter:") print(" numRefs = " .. ARGS.numRefs) print(" numPreRefs = " .. ARGS.numPreRefs) print(" startTime = " .. ARGS.startTime) print(" endTime = " .. ARGS.endTime) print(" dt = " .. ARGS.dt) print(" grid = " .. gridName) -- choose algebra InitUG(ARGS.dim, AlgebraType("CPU", 2)); -- Create, Load, Refine and Distribute Domain local mandatorySubsets = {"River", "Sink"} local dom = nil if withRedist == true then dom = util.CreateDomain(gridName, 0, mandatorySubsets) balancer.RefineAndRebalanceDomain(dom, ARGS.numRefs) else dom = util.CreateAndDistributeDomain(gridName, ARGS.numRefs, ARGS.numPreRefs, mandatorySubsets) end print("\ndomain-info:") print(dom:domain_info():to_string()) -- create Approximation Space print(">> Create ApproximationSpace") local approxSpace = ApproximationSpace(dom) approxSpace:add_fct("A", "Lagrange", 1) approxSpace:add_fct("v", "Lagrange", 1) -- Lexicographic order of indices. OrderLex(approxSpace, "x"); -------------------------------------------------------------------------------- -- Setup FV Convection-Diffusion Element Discretization -------------------------------------------------------------------------------- print (">> Setting up Assembling") function U(x,y,t) return 0.0 end local upwind = FullUpwind() local elemDisc = {} elemDisc["A"] = ConvectionDiffusionFV1("A", "River") elemDisc["v"] = ConvectionDiffusionFV1("v", "River") local downStreamVec = EdgeOrientation(dom) -- Gleichung für A elemDisc["A"]:set_upwind(upwind) elemDisc["A"]:set_mass_scale(1.0) -- \partial A / \partial t elemDisc["A"]:set_velocity(elemDisc["v"]:value() * downStreamVec) -- \partial_x (v*A) function sign(number) return number > 0 and 1 or (number == 0 and 0 or -1) end -- Hoehe (Rechteck) local B = 1.0 -- Breite local Banf=1.2 local Bend=1.0 --1.0 local xeng=0 --function Width(x,y,t) return (Banf+Bend) / 2 + (Bend-Banf)/ 2*math.tanh(50*(x - xeng)) end function Width(x,y,t) if (x>-0.25 and x < 0.25) then return 1.2 else return 1.0 end end local width=LuaUserNumber2d("Width") function Height(A,width) return A/width end function Height_dA(A,width) return 1.0/width end function Height_dw(A,width) return -A/(width*width) end local height = LuaUserFunctionNumber("Height", 2) height:set_input(0, elemDisc["A"]:value()) height:set_input(1, width) height:set_deriv(0, "Height_dA") height:set_deriv(1, "Height_dw") local lambda = 0.000001 local dhyd = 1.0 function Roughness(v,A,width) return lambda/(4.0*width*(A/width)/(width+2*(A/width)))*0.5*math.abs(v) end function Roughness_dv(v,A,width) return lambda/(4.0*width*(A/width)/(width+2*(A/width)))*0.5*sign(v) end function Roughness_dA(v,A,width) return lambda/(4.0*width*width*width/((2*A + width*width)*(2*A + width*width)))*0.5*math.abs(v) end local roughness = LuaUserFunctionNumber("Roughness", 3) roughness:set_input(0, elemDisc["v"]:value()) roughness:set_input(1, elemDisc["A"]:value()) roughness:set_input(2, width) roughness:set_deriv(0, "Roughness_dv") roughness:set_deriv(1, "Roughness_dA") local nu_t = 0.5 local g = 9.81 function Sohle2d(x, y, t) return -0.003*x end local sohle=LuaUserNumber2d("Sohle2d") -- g*(h+zB) --FRAGE: height und sohle plotten, gibt es dafür funktion? local gefaelle = g*(height+sohle) -- Fehlt: h, zB elemDisc["v"]:set_upwind(upwind) elemDisc["v"]:set_mass_scale(1.0) elemDisc["v"]:set_diffusion(nu_t) -- \partial_x (-nu_t \partial_x v) elemDisc["v"]:set_velocity(0.5*elemDisc["v"]:value()*downStreamVec) -- \partial_x (0.5*v*v) elemDisc["v"]:set_flux(gefaelle*downStreamVec) -- \partial_x (g *(h+zB)) elemDisc["v"]:set_reaction_rate(roughness) -- Add inflow bnd cond. -- local function AddInflowBC(domainDisc, Q, h, B, subsetID) local function AddInflowBC(domainDisc, A0, v0, subsetID) local dirichletBND = DirichletBoundary() dirichletBND:add(A0, "A", subsetID) dirichletBND:add(v0, "v", subsetID) domainDisc:add(dirichletBND) end -- Add outflow bnds. local function AddOutflowBC(domainDisc, pointID, subsetID) local outflowBnd = {} outflowBnd["A"] = NeumannBoundaryFV1("A") -- v*A outflowBnd["A"]:add(elemDisc["A"]:value()*elemDisc["v"]:value(), pointID, subsetID) outflowBnd["v"] = NeumannBoundaryFV1("v") -- 0.5*v^2 + g*(h+z) outflowBnd["v"]:add(gefaelle, pointID, subsetID) outflowBnd["v"]:add(0.5*elemDisc["v"]:value()*elemDisc["v"]:value(), pointID, subsetID) domainDisc:add(outflowBnd["A"]) domainDisc:add(outflowBnd["v"]) end -- Create discretization. local domainDisc = DomainDiscretization(approxSpace) domainDisc:add(elemDisc["A"]) domainDisc:add(elemDisc["v"]) AddInflowBC(domainDisc, 11.4, 1.12, "Source1") AddOutflowBC(domainDisc, "Sink", "River") -------------------------------------------------------------------------------- -- Algebra -------------------------------------------------------------------------------- print (">> Setting up Algebra Solver") -- if the non-linear problem shall should be solved, one has to wrap the solver -- inside a newton-solver. See 'solver_util.lua' for more details. solverDesc = { type = "newton", linSolver = { type = "bicgstab", precond = { type = "ilu", -- sort = true, }, convCheck = { type = "standard", iterations = 100, absolute = 1e-11, reduction = 1e-13, verbose=true }, }, lineSearch = { type = "standard", maxSteps = 10, lambdaStart = 1.0, lambdaReduce = 0.5, acceptBest = false, checkAll = false }, } local dbgWriter = GridFunctionDebugWriter(approxSpace) dbgWriter:set_vtk_output(false) local solver = util.solver.CreateSolver(solverDesc) --solver:set_debug(dbgWriter) -------------------------------------------------------------------------------- -- Apply Solver -------------------------------------------------------------------------------- -- Set initial value. print(">> Interpolation start values") local u = GridFunction(approxSpace) Interpolate(1.0, u, "v", ARGS.startTime) Interpolate(10.0, u, "A", ARGS.startTime) -- Configure VTK output. local vtk = VTKOutput() vtk:select_element(height, "Height") vtk:select_element(sohle, "Sohle") vtk:select_element(gefaelle, "Gefaelle") vtk:select("v", "velocity") vtk:select("A", "area") -- Perform time stepping loop. util.SolveNonlinearTimeProblem(u, domainDisc, solver, vtk , "Sol_change_b", "ImplEuler", 1, ARGS.startTime, ARGS.endTime, ARGS.dt, ARGS.dt * 1e-6); --util.SolveLinearTimeProblem(u, domainDisc, solver, VTKOutput(), "Sol", -- "ImplEuler", 1, ARGS.startTime, ARGS.endTime, ARGS.dt); print("Writing profile data") WriteProfileData("profile_data.pdxml") util.PrintProfile_TotalTime("main ") -- end group app_convdiff --[[! \} ]]--
--[[ auxiliary functions --]] --[[ Break a string "25-30-100" into table {25,30,100} ]]-- function convert_option(s) local out = {} local args = string.split(s, '-') for _, x in pairs(args) do x = string.gsub(x, 'n', '-') local y = tonumber(x) if y == nil then error("Parsing arguments: " .. s .. " is not well formed") end out[1+#out] = y end return out end --[[ Table deepcopy ]]-- function deepcopy(orig) local orig_type = type(orig) local copy if orig_type == 'table' then copy = {} for orig_key, orig_value in next, orig, nil do copy[deepcopy(orig_key)] = deepcopy(orig_value) end setmetatable(copy, deepcopy(getmetatable(orig))) else -- number, string, boolean, etc copy = orig end return copy end --[[ Checking tensor containing Nan ]]-- function check_nan(t) return t:sum()~=t:sum() end
local OnlookerPropsItem = class(CommonGameLayer, false); OnlookerPropsItem.s_controls = { btnProp = 1, imgProp = 2, txtPropNum = 3, btnTop = 4, imgFrame = 5, } OnlookerPropsItem.ctor = function(self, data) local room_player_info_prop = require("view/kScreen_1280_800/games/common2/room_player_info_prop"); super(self,room_player_info_prop); if not data then return; end self.m_ctrls = OnlookerPropsItem.s_controls; self.m_data = data; self:_initViews(); end OnlookerPropsItem.dtor = function(self) self.m_data = nil; end OnlookerPropsItem._initViews = function(self) self.m_btnTop = self:findViewById(self.m_ctrls.btnTop); -- 道具透明按钮 self.m_btnProp = self:findViewById(self.m_ctrls.btnProp); -- 道具按钮 self.m_imgProp = self:findViewById(self.m_ctrls.imgProp); -- 道具图标 self.m_txtPropNum = self:findViewById(self.m_ctrls.txtPropNum); -- 道具数量 self.m_imgFrame = self:findViewById(self.m_ctrls.imgFrame); -- 道具品质框 local isExpire = (self.m_data.allowTimes > 0); self.m_btnProp:setEnable(isExpire); self.m_btnTop:setVisible(not isExpire); local config = PropIsolater.getInstance():getGoodInfoByTypeId(self.m_data.type); if config then ImageCache.getInstance():request(config.item_icon, self, self.onFinishLoadIcon); -- 下载道具图标 end self.m_txtPropNum:setText((self.m_data.allowTimes > 99) and "99+" or self.m_data.allowTimes); self:setSize(self.m_imgFrame:getSize()); end OnlookerPropsItem.onFinishLoadIcon = function (self, url, filename) if self.m_imgProp then self.m_imgProp:setFile(filename); end end OnlookerPropsItem.getData = function(self) return self.m_data; end OnlookerPropsItem.s_controlConfig = { [OnlookerPropsItem.s_controls.imgFrame] = {"imgFrame"}, [OnlookerPropsItem.s_controls.btnTop] = {"imgFrame", "btnTop"}, [OnlookerPropsItem.s_controls.btnProp] = {"imgFrame", "btnProp"}, [OnlookerPropsItem.s_controls.imgProp] = {"imgFrame", "btnProp", "imgProp"}, [OnlookerPropsItem.s_controls.txtPropNum] = {"imgFrame", "btnProp", "imgDot", "txtPropNum"}, }; return OnlookerPropsItem;
petrolCanPrice = 50 lang = "da" settings = {} settings["da"] = { buyFuel = "Køb brændstof", liters = "Liter", percent = "Procent", confirm = "Bekræft", fuelStation = "Tankstation", boatFuelStation = "Tankstation | Både", avionFuelStation = "Tankstation | Fly", heliFuelStation = "Tankstation | Helikopter", price = "Pris" } showBar = false showText = true hud_form = 1 -- 1 : Vertical | 2 = Horizontal hud_x = 0.175 hud_y = 0.885 electricityPrice = 1 -- NOT RANOMED !! randomPrice = true --Random the price of each stations price = 1 --If random price is on False, set the price here for 1 liter
function OnLoad() QQQ = BarUnderObject() QQQ:AddBar(myHero, 10, nil, nil, 5) end class "BarUnderObject" function BarUnderObject:__init() self.bars = {} self.draw = true AddDrawCallback(function () self:OnDraw() end) AddTickCallback(function () self:DeleteInvalid() end) end function BarUnderObject:OnDraw() DrawTextA(#self.bars) local w = WINDOW_W local h = WINDOW_H for i,v in pairs(self.bars) do local wts = WorldToScreen(D3DXVECTOR3(v.obj.x,v.obj.y,v.obj.z)) local percentage = ((v.time-os.clock())/v.t)*100 DrawLineBorder(wts.x-v.maxsize*(percentage/2),wts.y,wts.x+v.maxsize*(percentage/2),wts.y,12,v.color,1) DrawLine(wts.x-v.maxsize*(percentage/2)+1,wts.y,wts.x+v.maxsize*(percentage/2),wts.y, 11, v.fillcolor ) DrawTextA(math.round(v.time-os.clock(),1),12,wts.x,wts.y-5) end end function BarUnderObject:AddBar(_obj,_time,_color, _fillcolor,_maxsize) if not _color then _color = ARGB(128,255,255,255) end if not _fillcolor then _fillcolor = ARGB(128,0,255,0) end if not _maxsize then _maxsize = 1.5 end if _obj.valid and _time and _time > 0 then self.bars[#self.bars+1] = {obj = _obj, t = _time, time = os.clock()+_time, color = _color, fillcolor = _fillcolor, maxsize = _maxsize} end end function BarUnderObject:RemoveBar(_obj) local n = {} for _, v in pairs(self.bars) do if v.obj ~= _obj then n[#n+1] = v end end self.bars = nil self.bars = n end function BarUnderObject:DeleteInvalid() local n = {} for _, v in pairs(self.bars) do if v.obj and v.obj.valid and v.time > os.clock() then n[#n+1] = v end end self.bars = nil self.bars = n end --[[ function OnLoad() RB = RecallBar() RB:AddBar(myHero, true) RB:AddBar(myHero, true) RB:AddBar(myHero, false) RB:AddBar(myHero, true) DelayAction(function () RB:RemoveBar(myHero) end,2) end class "RecallBar" function RecallBar:__init() self.bars = {} self.draw = true AddDrawCallback(function () self:OnDraw() end) AddTickCallback(function () self:CheckIfTimeUp() end) end function RecallBar:AddBar(_hero,_hasbaron) if not _hero then return end if _hasbaron then t = os.clock() + 4 else t = os.clock() + 8 end self.bars[#self.bars+1] = {hero = _hero, time = t, hasbaron = _hasbaron} end function RecallBar:RemoveBar(_hero) if not _hero then return end local sb = {} for _,v in pairs(self.bars) do if v.hero ~= _hero then sb[#sb+1] = v end end self.bars = nil self.bars = sb end function RecallBar:CheckIfTimeUp() local sb = {} for _, v in pairs(self.bars) do if v.time-os.clock() > 0 then sb[#sb+1] = v end end self.bars = nil self.bars = sb end function RecallBar:OnDraw() local w = WINDOW_W local h = WINDOW_H for i, v in pairs(self.bars) do local n = 8 if v.hasbaron then n = 4 end local percentage = ((v.time-os.clock())/n)*1 local m = w/3-w/1.4 DrawLineBorder(w/3, h/1.25-20*i+20, w/1.4, h/1.25-20*i+20, 18, ARGB(255,255,255,255), 1) DrawLine(w/3, h/1.25-20*i+20, w/1.4+m*percentage, h/1.25-20*i+20, 18, ARGB(128,255,255,255)) DrawTextA(v.hero.charName.. " is Recalling: "..math.round(v.time-os.clock()),18,w/2.1,h/1.262-20*i+20) end end ]]--
description "vRP MySQL async" -- server scripts server_scripts{ "@vrp/lib/utils.lua", "init.lua", "mysql.net.dll" } server_exports{ "createConnection", "createCommand", "query", "checkTask" }
local test={ modname=(...) } package.loaded[test.modname]=test local n={"kissfft.core","wetgenes.pack.core","zip","zlib","wetgenes.freetype.core","wetgenes.ogg.core","al.core","alc.core","wetgenes.tardis.core","gles.core","wetgenes.grd.core","wetgenes.grdmap.core","wetgenes.sod.core","socket.core","mime.core","wetgenes.gamecake.core","wetgenes.win.core","lfs","sqlite","profiler","posix_c","lash","SDL","cmsgpack","periphery","wetgenes.v4l2.core","rex_pcre","linenoise","brimworks_zip","sys","sys.sock","polarssl","pgsql","wetgenes.opus.core"} for i,v in ipairs(n) do local req=v local name="test_"..req:gsub("%.","_") test[name]=function() local t=require(req) end end return test
local configs = require 'lspconfig/configs' local util = require 'lspconfig/util' local handlers = require 'vim.lsp.handlers' local path = util.path local server_name = "jdtls" local cmd = { util.path.join(tostring(vim.fn.getenv("JAVA_HOME")), "/bin/java"), "-Declipse.application=org.eclipse.jdt.ls.core.id1", "-Dosgi.bundles.defaultStartLevel=4", "-Declipse.product=org.eclipse.jdt.ls.core.product", "-Dlog.protocol=true", "-Dlog.level=ALL", "-Xms1g", "-Xmx2G", "-jar", tostring(vim.fn.getenv("JAR")), "-configuration", tostring(vim.fn.getenv("JDTLS_CONFIG")), "-data", tostring(vim.fn.getenv("WORKSPACE")), "--add-modules=ALL-SYSTEM", "--add-opens java.base/java.util=ALL-UNNAMED", "--add-opens java.base/java.lang=ALL-UNNAMED", } configs[server_name] = { default_config = { cmd = cmd, cmd_env = { JAR=vim.fn.getenv("JAR"), GRADLE_HOME=vim.fn.getenv("GRADLE_HOME"), }, filetypes = { "java" }; root_dir = util.root_pattern('.git'); init_options = { workspace = path.join { vim.loop.os_homedir(), "workspace" }; jvm_args = {}; os_config = nil; }; handlers = { -- Due to an invalid protocol implementation in the jdtls we have to -- conform these to be spec compliant. -- https://github.com/eclipse/eclipse.jdt.ls/issues/376 -- Command in org.eclipse.lsp5j -> https://github.com/eclipse/lsp4j/blob/master/org.eclipse.lsp4j/src/main/xtend-gen/org/eclipse/lsp4j/Command.java -- CodeAction in org.eclipse.lsp4j -> https://github.com/eclipse/lsp4j/blob/master/org.eclipse.lsp4j/src/main/xtend-gen/org/eclipse/lsp4j/CodeAction.java -- Command in LSP -> https://microsoft.github.io/language-server-protocol/specification#command -- CodeAction in LSP -> https://microsoft.github.io/language-server-protocol/specification#textDocument_codeAction ['textDocument/codeAction'] = function(a, b, actions) for _,action in ipairs(actions) do -- TODO: (steelsojka) Handle more than one edit? -- if command is string, then 'ation' is Command in java format, -- then we add 'edit' property to change to CodeAction in LSP and 'edit' will be executed first if action.command == 'java.apply.workspaceEdit' then action.edit = action.edit or action.arguments[1] -- if command is table, then 'action' is CodeAction in java format -- then we add 'edit' property to change to CodeAction in LSP and 'edit' will be executed first elseif type(action.command) == 'table' and action.command.command == 'java.apply.workspaceEdit' then action.edit = action.edit or action.command.arguments[1] end end handlers['textDocument/codeAction'](a, b, actions) end }; }; docs = { description = [[ https://projects.eclipse.org/projects/eclipse.jdt.ls Language server for Java. See project page for installation instructions. Due to the nature of java, the settings for eclipse jdtls cannot be automatically inferred. Please set the following environmental variables to match your installation. You can set these locally for your project with the help of [direnv](https://github.com/direnv/direnv). Note version numbers will change depending on your project's version of java, your version of eclipse, and in the case of JDTLS_CONFIG, your OS. ```bash export JAR=/path/to/eclipse.jdt.ls/org.eclipse.jdt.ls.product/target/repository/plugins/org.eclipse.equinox.launcher_1.6.0.v20200915-1508.jar export GRADLE_HOME=$HOME/gradle export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-11.0.9.11-9.fc33.x86_64/ export JDTLS_CONFIG=/path/to/eclipse.jdt.ls/org.eclipse.jdt.ls.product/target/repository/config_linux export WORKSPACE=$HOME/workspace ``` ]]; default_config = { root_dir = [[root_pattern(".git")]]; }; }; }
----------------------------------------------------------------------------------------------------------------------------- -- [https://discord.gg/ppVjYQKT2r في حال واجهت اي مشاكل حياك الدعم الفني B3-Team جميع الحقوق محفوظة الى ] -- -- [المصعد يتسع حتى تسع طوابق و يمكن تعطيل اي طابق و عند تعديل اي احداثية لا تنسى تحطها مرتين مثل ما وضح بالاسفل ] -- ----------------------------------------------------------------------------------------------------------------------------- local menuactive = false function ToggleActionMenu() menuactive = not menuactive if menuactive then SetNuiFocus(true,true) TransitionToBlurred(1000) SendNUIMessage({ showmenu = true }) TriggerEvent("hideHud") else SetNuiFocus(false) TransitionFromBlurred(1000) SendNUIMessage({ hidemenu = true }) TriggerEvent("showHud") end end ----------------------------------------------------------------------------------------------------------------------------------------- --[ القوائم ]---------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------- RegisterNUICallback("ButtonClick",function(data,cb) local ped = PlayerPedId() if data == "-1andar" then DoScreenFadeOut(1000) ToggleActionMenu() SetTimeout(1400,function() SetEntityCoords(ped,341.0583190918,-580.9287109375,28.796863555908,0,0,0,0) -- في حال غيرت اي احداثية بالاسفل بدل نفس الاحداثية هنا SetEntityHeading(ped,32.76) TriggerEvent("vrp_sound:source",'elevator-bell',0.5) DoScreenFadeIn(1000) end) elseif data == "-2andar" then DoScreenFadeOut(1000) ToggleActionMenu() SetTimeout(1400,function() SetEntityCoords(ped,332.17782592773,-595.53277587891,43.284103393555,0,0,0,0) -- في حال غيرت اي احداثية بالاسفل بدل نفس الاحداثية هنا SetEntityHeading(ped,32.76) TriggerEvent("vrp_sound:source",'elevator-bell',0.5) DoScreenFadeIn(1000) end) elseif data == "-3andar" then DoScreenFadeOut(1000) ToggleActionMenu() SetTimeout(1400,function() SetEntityCoords(ped,344.57272338867,-586.31140136719,28.796838760376,0,0,0,0) -- في حال غيرت اي احداثية بالاسفل بدل نفس الاحداثية هنا SetEntityHeading(ped,32.76) TriggerEvent("vrp_sound:source",'elevator-bell',0.5) DoScreenFadeIn(1000) end) elseif data == "terreo" then DoScreenFadeOut(1000) ToggleActionMenu() SetTimeout(1400,function() SetEntityCoords(ped,339.77185058594,-584.65423583984,28.796836853027,0,0,0,0) -- في حال غيرت اي احداثية بالاسفل بدل نفس الاحداثية هنا SetEntityHeading(ped,32.76) TriggerEvent("vrp_sound:source",'elevator-bell',0.5) DoScreenFadeIn(1000) end) elseif data == "3andar" then DoScreenFadeOut(1000) ToggleActionMenu() SetTimeout(1400,function() SetEntityCoords(ped,330.18417358398,-600.98809814453,43.28405380249,0,0,0,0) -- في حال غيرت اي احداثية بالاسفل بدل نفس الاحداثية هنا SetEntityHeading(ped,32.76) TriggerEvent("vrp_sound:source",'elevator-bell',0.5) DoScreenFadeIn(1000) end) elseif data == "4andar" then DoScreenFadeOut(1000) ToggleActionMenu() SetTimeout(1400,function() SetEntityCoords(ped,327.18295288086,-603.63818359375,43.28405380249,0,0,0,0) -- في حال غيرت اي احداثية بالاسفل بدل نفس الاحداثية هنا SetEntityHeading(ped,32.76) TriggerEvent("vrp_sound:source",'elevator-bell',0.5) DoScreenFadeIn(1000) end) elseif data == "5andar" then DoScreenFadeOut(1000) ToggleActionMenu() SetTimeout(1400,function() SetEntityCoords(ped,351.01123046875,-588.36206054688,28.796834945679,0,0,0,0) -- في حال غيرت اي احداثية بالاسفل بدل نفس الاحداثية هنا SetEntityHeading(ped,32.76) TriggerEvent("vrp_sound:source",'elevator-bell',0.5) DoScreenFadeIn(1000) end) elseif data == "heli" then DoScreenFadeOut(1000) ToggleActionMenu() SetTimeout(1400,function() SetEntityCoords(ped,338.89300537109,-583.95642089844,74.161697387695,0,0,0,0) -- في حال غيرت اي احداثية بالاسفل بدل نفس الاحداثية هنا SetEntityHeading(ped,32.76) TriggerEvent("vrp_sound:source",'elevator-bell',0.5) DoScreenFadeIn(1000) end) elseif data == "nothing" then TriggerEvent("Notify","ﺽﻮﻓﺮﻣ",".ﻞﻄﻌﻣ ﺭﺯ") elseif data == "fechar" then ToggleActionMenu() end end) ----------------------------------------------------------------------------------------------------------------------------------------- --[ احداثيات ]--------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------- local elevator = { { ['x'] = 341.0583190918, ['y'] = -580.9287109375, ['z'] = 28.796863555908 }, -- -1 في حال بدلت اي احداثية هنا لا تنسى تبدله بالنظير حقها فوق { ['x'] = 332.17782592773, ['y'] = -595.53277587891, ['z'] = 43.284103393555 }, -- -2 في حال بدلت اي احداثية هنا لا تنسى تبدله بالنظير حقها فوق { ['x'] = 344.57272338867, ['y'] = -586.31140136719, ['z'] = 28.796838760376 }, -- -3 في حال بدلت اي احداثية هنا لا تنسى تبدله بالنظير حقها فوق { ['x'] = 339.77185058594, ['y'] = -584.65423583984, ['z'] = 28.796836853027 }, -- T في حال بدلت اي احداثية هنا لا تنسى تبدله بالنظير حقها فوق { ['x'] = 330.18417358398, ['y'] = -600.98809814453, ['z'] = 43.28405380249 }, -- 3 في حال بدلت اي احداثية هنا لا تنسى تبدله بالنظير حقها فوق { ['x'] = 327.18295288086, ['y'] = -603.63818359375, ['z'] = 43.28405380249 }, -- 4 في حال بدلت اي احداثية هنا لا تنسى تبدله بالنظير حقها فوق { ['x'] = 351.011230468754, ['y'] = -588.36206054688, ['z'] = 28.796834945679 }, -- 5 في حال بدلت اي احداثية هنا لا تنسى تبدله بالنظير حقها فوق { ['x'] = 338.89300537109, ['y'] = -583.95642089844, ['z'] = 74.161697387695 }, -- HELI في حال بدلت اي احداثية هنا لا تنسى تبدله بالنظير حقها فوق } ----------------------------------------------------------------------------------------------------------------------------------------- --[ القائمة ]---------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------- Citizen.CreateThread(function() SetNuiFocus(false,false) while true do local sleep = 1000 for k,v in pairs(elevator) do local ped = PlayerPedId() local x,y,z = table.unpack(GetEntityCoords(ped)) local bowz,cdz = GetGroundZFor_3dCoord(v.x,v.y,v.z) local distance = GetDistanceBetweenCoords(v.x,v.y,cdz,x,y,z,true) local elevator = elevator[k] if GetDistanceBetweenCoords(GetEntityCoords(PlayerPedId()), elevator.x, elevator.y, elevator.z, true ) <= 2 then sleep = 5 DrawText3D(elevator.x, elevator.y, elevator.z, "<FONT FACE = 'A9eelsh'>"..'[~g~E~w~] ﻂﻐﺿﺍ ﺪﻌﺼﻤﻟﺍ ﻡﺍﺪﺨﺘﺳﻻ') end if distance <= 15 then sleep = 5 DrawMarker(30, elevator.x, elevator.y, elevator.z-0.6,0,0,0,0.0,0,0,0.5,0.5,0.4,0,140,255,90,0,0,0,1) if distance <= 2.3 then if IsControlJustPressed(0,38) then ToggleActionMenu() end end end end Citizen.Wait(sleep) end end) ----------------------------------------------------------------------------------------------------------------------------------------- --[ فنكشين ]----------------------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------------------------------- function DrawText3D(x,y,z, text) local onScreen,_x,_y=World3dToScreen2d(x,y,z) local px,py,pz=table.unpack(GetGameplayCamCoords()) SetTextScale(0.40, 0.40) SetTextFont(4) SetTextProportional(1) SetTextColour(255, 255, 255, 215) SetTextEntry("STRING") SetTextCentre(1) AddTextComponentString(text) DrawText(_x,_y) end -- Updates print("^4"..GetCurrentResourceName() .."^7 is on the ^2newest ^7version!^7")
ArrowTowerSprite = class("ArrowTowerSprite", function (...) return BuildingBaseSprite:create(...) end) ArrowTowerSprite.TAG = nil ArrowTowerSprite.subType = "ATKBuilding" Temple:initBuildingHP(ArrowTowerSprite) function ArrowTowerSprite:onEnter() self:adjustBarPosition(0, 23) end function ArrowTowerSprite:create() local arrowTowerSprite = ArrowTowerSprite.new(IMG_BUILDING_ARROWTOWER) arrowTowerSprite:onEnter() return arrowTowerSprite end
//________________________________ // // NS2 Combat Mod // Made by JimWest and MCMLXXXIV, 2012 // //________________________________ // combat_SoundEffect.lua local HotReload = CombatSoundEffect if(not HotReload) then CombatSoundEffect = {} ClassHooker:Mixin("CombatSoundEffect") end function CombatSoundEffect:OnLoad() self:PostHookFunction("StartSoundEffectOnEntity", "StartSoundEffectOnEntity_Hook") end local kTauntSounds = { "sound/NS2.fev/alien/skulk/taunt", "sound/NS2.fev/alien/gorge/taunt", "sound/NS2.fev/alien/lerk/taunt", "sound/NS2.fev/alien/fade/taunt", "sound/NS2.fev/alien/onos/taunt", "sound/NS2.fev/alien/common/swarm", "sound/NS2.fev/marine/voiceovers/taunt", } // Hooks for Ink and EMP are in here. function CombatSoundEffect:StartSoundEffectOnEntity_Hook(soundEffectName, onEntity) if onEntity and onEntity:isa("Player") then onEntity:CheckCombatData() // Check whether the sound is a taunt sound for index, tauntSoundName in ipairs(kTauntSounds) do if (soundEffectName == tauntSoundName) then // Now check whether the player has taunted recently and fire taunt abilities. if (Shared.GetTime() - onEntity.combatTable.lastTauntTime > kCombatTauntCheckInterval) then onEntity:ProcessTauntAbilities() onEntity.combatTable.lastTauntTime = Shared.GetTime() end break end end end end if (not HotReload) then CombatSoundEffect:OnLoad() end
local bcrypt = require "bcrypt" -- local PG = require "services.PG" local redis_client = require "services.redis_client" local generate_user_token = require "util.generate_user_token" local is_mobile = require "util.is_mobile" local trim = require "util.trim" local fmt = string.format local TOKEN_TTL = 60 * 60 * 24 * 14 -- two weeks local function remove_token(token) local client = redis_client:new() client:run("del", fmt("user_token(%s):uid", token)) end local function set_token(token, uid) local client = redis_client:new() client:run("setex", fmt("user_token(%s):uid", token), TOKEN_TTL, uid) end local function sign_in(app) local mobile = trim(app.params.mobile) local password = trim(app.params.password) assert(is_mobile(mobile), "mobile.invalid") assert(#password >= 6, "password.invalid") local user_in_db = assert(PG.query([[ select id, mobile, password from "user" where mobile = ? ]], mobile)[1], "mobile.not.registered") assert(bcrypt.verify(password, user_in_db.password), "password.not.match") if app.cookies.user_token then remove_token(app.cookies.user_token) end local user_token = generate_user_token(user_in_db.id) set_token(user_token, user_in_db.id) app.cookies.user_token = user_token return { json = { uid = user_in_db.id } } end return sign_in
local cmp = require "cmp" -- `/` cmdline setup. cmp.setup.cmdline("/", { mapping = cmp.mapping.preset.cmdline(), sources = { { name = "buffer" }, }, }) -- `:` cmdline setup. cmp.setup.cmdline(":", { mapping = cmp.mapping.preset.cmdline(), sources = cmp.config.sources({ { name = "path" }, }, { { name = "cmdline" }, }), }) return { mapping = { ["<C-k>"] = cmp.mapping(cmp.mapping.select_prev_item(), { "i", "c" }), ["<C-j>"] = cmp.mapping(cmp.mapping.select_next_item(), { "i", "c" }), }, sources = { { name = "luasnip" }, { name = "nvim_lsp" }, { name = "buffer" }, { name = "nvim_lua" }, { name = "path" }, { name = "cmp_tabnine" }, }, }
#!/usr/bin/env lua local unpack = table.unpack or unpack local fl = require( "fltk4lua" ) local WIDTH=700 local window = fl.Window( WIDTH, 400 ) function window:callback() print( "window callback called" ) self:hide() end local hugemenu = {} local function quit_cb() --os.exit( 0, true ) -- bad style window:hide() end local menutable = { { "foo", nil, nil, nil, fl.MENU_INACTIVE }, { "&File", nil, nil, nil, fl.SUBMENU }, { "&Open", fl.ALT+'o', nil, nil, fl.MENU_INACTIVE }, { "&Close" }, { "&Quit", fl.ALT+'q', quit_cb, nil, fl.MENU_DIVIDER }, { "shortcut", 'a' }, { "shortcut", fl.SHIFT+'a' }, { "shortcut", fl.CTRL+'a' }, { "shortcut", fl.CTRL+fl.SHIFT+'a' }, { "shortcut", fl.ALT+'a' }, { "shortcut", fl.ALT+fl.SHIFT+'a' }, { "shortcut", fl.ALT+fl.CTRL+'a' }, { "shortcut", fl.ALT+fl.SHIFT+fl.CTRL+'a', nil, nil, fl.MENU_DIVIDER }, { "shortcut", '\r' --[[ fl.Enter ]] }, { "shortcut", fl.CTRL+fl.Enter, nil, nil, fl.MENU_DIVIDER }, { "shortcut", fl.F1 }, { "shortcut", fl.SHIFT+fl.F1 }, { "shortcut", fl.CTRL+fl.F1 }, { "shortcut", fl.SHIFT+fl.CTRL+fl.F1 }, { "shortcut", fl.ALT+fl.F1 }, { "shortcut", fl.ALT+fl.SHIFT+fl.F1 }, { "shortcut", fl.ALT+fl.CTRL+fl.F1 }, { "shortcut", fl.ALT+fl.SHIFT+fl.CTRL+fl.F1, nil, nil, fl.MENU_DIVIDER }, { "&Submenus", fl.ALT+'S', nil, "Submenu1", fl.SUBMENU }, { "A very long menu item" }, { "&submenu", fl.CTRL+'S', nil, "Submenu2", fl.SUBMENU }, { "item 1" }, { "item 2" }, { "item 3" }, { "item 4" }, {}, { "after submenu" }, {}, {}, { "&Edit", fl.F2, nil, nil, fl.SUBMENU }, { "Undo", fl.ALT+'z' }, { "Redo", fl.ALT+'r', nil, nil, fl.MENU_DIVIDER }, { "Cut", fl.ALT+'x' }, { "Copy", fl.ALT+'c' }, { "Paste", fl.ALT+'v' }, { "Inactive", fl.ALT+'d', nil, nil, fl.MENU_INACTIVE }, { "Clear", nil, nil, nil, fl.MENU_DIVIDER }, { "Invisible", fl.ALT+'e', nil, nil, fl.MENU_INVISIBLE }, { "Preferences" }, { "Size" }, {}, { "&Checkbox", fl.F3, nil, nil, fl.SUBMENU }, { "&Alpha", fl.F2, nil, 1, fl.MENU_TOGGLE }, { "&Beta", nil, nil, 2, fl.MENU_TOGGLE }, { "&Gamma", nil, nil, 3, fl.MENU_TOGGLE }, { "&Delta", nil, nil, 4, fl.MENU_TOGGLE+fl.MENU_VALUE }, { "&Epsilon", nil, nil, 5, fl.MENU_TOGGLE }, { "&Pi", nil, nil, 6, fl.MENU_TOGGLE }, { "&Mu", nil, nil, 7, fl.MENU_TOGGLE+fl.MENU_DIVIDER }, { "Red", nil, nil, 1, fl.MENU_TOGGLE, nil, nil, nil, 1 }, { "Black", nil, nil, 1, fl.MENU_TOGGLE+fl.MENU_DIVIDER }, { "00", nil, nil, 1, fl.MENU_TOGGLE }, { "000", nil, nil, 1, fl.MENU_TOGGLE }, {}, { "&Radio", nil, nil, nil, fl.SUBMENU }, { "&Alpha", nil, nil, 1, fl.MENU_RADIO }, { "&Beta", nil, nil, 2, fl.MENU_RADIO }, { "&Gamma", nil, nil, 3, fl.MENU_RADIO }, { "&Delta", nil, nil, 4, fl.MENU_RADIO+fl.MENU_VALUE }, { "&Epsilon", nil, nil, 5, fl.MENU_RADIO }, { "&Pi", nil, nil, 6, fl.MENU_RADIO }, { "&Mu", nil, nil, 7, fl.MENU_RADIO+fl.MENU_DIVIDER }, { "Red", nil, nil, 1, fl.MENU_RADIO }, { "Black", nil, nil, 1, fl.MENU_RADIO+fl.MENU_DIVIDER }, { "00", nil, nil, 1, fl.MENU_RADIO }, { "000", nil, nil, 1, fl.MENU_RADIO }, {}, { "&Font", nil, nil, nil, fl.SUBMENU }, { "Normal", nil, nil, nil, nil, nil, nil, 14 }, { "Bold", nil, nil, nil, nil, nil, "FL_HELVETICA_BOLD", 14 }, { "Italic", nil, nil, nil, nil, nil, "FL_HELVETICA_ITALIC", 14 }, { "BoldItalic", nil, nil, nil, nil, nil, "FL_HELVETICA_BOLD_ITALIC", 14 }, { "Small", nil, nil, nil, nil, nil, "FL_HELVETICA_BOLD_ITALIC", 10 }, { "Emboss", nil, nil, nil, nil, "FL_EMBOSSED_LABEL" }, { "Engrave", nil, nil, nil, nil, "FL_ENGRAVED_LABEL" }, { "Shadow", nil, nil, nil, nil, "FL_SHADOW_LABEL" }, { "@->", nil, nil, nil, nil, "FL_NORMAL_LABEL" }, {}, { "&International", nil, nil, nil, fl.SUBMENU }, { "Sharp Ess", 223 }, { "A Umlaut", 196 }, { "a Umlaut", 228 }, { "Euro currency", fl.COMMAND+8364 }, { "the &\195\188 Umlaut" }, { "the capital &\195\156" }, { "convert \194\165 to &\194\163" }, { "convert \194\165 to &\226\130\172" }, { "Hangul character Sios &\227\133\133" }, { "Hangul character Cieuc", 12616 }, {}, { "E&mpty", nil, nil, nil, fl.SUBMENU }, {}, { "&Inactive", nil, nil, nil, fl.MENU_INACTIVE+fl.SUBMENU }, { "A very long menu item" }, { "A very long menu item" }, {}, { "Invisible", nil, nil, nil, fl.MENU_INVISIBLE+fl.SUBMENU }, { "A very long menu item" }, { "A very long menu item" }, {}, { "&Huge", nil, nil, hugemenu, fl.SUBMENU }, -- fake SUBMENU_POINTER support! { "button", fl.F4, nil, nil, fl.MENU_TOGGLE }, {} } local pulldown = { { "Red", fl.ALT+'r' }, { "Green", fl.ALT+'g' }, { "Blue", fl.ALT+'b' }, { "Strange", fl.ALT+'s', nil, nil, fl.MENU_INACTIVE }, { "&Charm", fl.ALT+'c' }, { "Truth", fl.ALT+'t' }, { "Beauty", fl.ALT+'b' }, } for i = 1, 99 do hugemenu[ i ] = { "item "..(i-1) } end -- a function that takes a literal menu specification like in the -- c++ code local function Menu( m, t, stack, n_stack ) stack, n_stack = stack or {}, n_stack or 0 local flag_stack = {} for _,v in ipairs( t ) do local label, sc, cb, ud, flg, lt, lf, ls, lc = unpack( v ) if label == nil or label == 0 then n_stack = n_stack - 1 local flags = flag_stack[ #flag_stack ] if flags then m:menuitem_setp( flags[ 1 ], "flags", flags[ 2 ] ) flag_stack[ #flag_stack ] = nil end else local i -- use a temporary name and rename later, because m:add() -- replaces existing menu items with the same name stack[ n_stack+1 ] = "++abc++" local path = table.concat( stack, "/", 1, n_stack+1 ) if flg and flg( fl.SUBMENU ) then -- add a dummy menu entry and remove it later to create the -- submenu implicitly. explicit submenu creation is disabled -- for m:add() because of a bug in FLTK. i = m:add( path.."/++xyz++" ) m:remove( i ) i = m:find_index( path ) if type( ud ) ~= "table" then m:menuitem_setp( i, "user_data", ud ) n_stack = n_stack + 1 stack[ n_stack ] = label else -- fake FL_SUBMENU_POINTER support m:menuitem_setp( i, "label", label ) stack[ n_stack+1 ] = label Menu( m, ud, stack, n_stack+1 ) end m:menuitem_setp( i, "shortcut", sc or 0 ) m:menuitem_setp( i, "callback", cb ) -- apply FL_MENU_INVISIBLE flag later m:menuitem_setp( i, "flags", flg-fl.MENU_INVISIBLE ) flag_stack[ #flag_stack+1 ] = { i, flg } else i = m:add( path, sc, cb, ud, flg ) end m:menuitem_setp( i, "label", label ) if lt then m:menuitem_setp( i, "labeltype", lt ) end if lf then m:menuitem_setp( i, "labelfont", lf ) end if ls then m:menuitem_setp( i, "labelsize", ls ) end if lc then m:menuitem_setp( i, "labelcolor", lc ) end end end end local function test_cb( self ) local m = self.value if not m then print( "NULL" ) else local lb = self:menuitem_getp( m, "label" ) local sc = self:menuitem_getp( m, "shortcut" ) if sc-sc ~= sc then -- test for 0 print( lb.." - "..fl.shortcut_label( sc ) ) else print( lb ) end end end local menubar = fl.Menu_Bar( 0, 0, WIDTH, 30 ) menubar.callback = test_cb Menu( menubar, menutable ) local mb1 = fl.Menu_Button( 100, 100, 120, 25, "&menubutton" ) Menu( mb1, pulldown ) mb1.tooltip = "this is a menu button" mb1.callback = test_cb local ch = fl.Choice( 300, 100, 80, 25, "&choice:" ) Menu( ch, pulldown ) ch.tooltip = "this is a choice menu" ch.callback = test_cb ch.value = 0 local mb2 = fl.Menu_Button( 0, 0, WIDTH, 400, "&popup" ) mb2.type = "POPUP3" mb2.box = "FL_NO_BOX" Menu( mb2, menutable ) mb2:remove( 1 ) -- delete the "File" submenu mb2.callback = test_cb local b = fl.Box( 200, 200, 200, 100, "Press right button\nfor a pop-up menu" ) window.resizable = mb2 window:size_range( 300, 400, 0, 400 ) window:end_group() window:show( arg ) fl.run()
require 'loxy.callback' require 'loxy.signal' require 'loxy.object'
local caca_ffi = require("caca_ffi") local Lib = caca_ffi.Lib_caca; local CharSets = {} function CharSets.utf8Toutf32(chars, size) size = size or #chars; return Lib.caca_utf8_to_utf32(chars, size) end function CharSets.utf32Toutf8(utf32char, buff, buffsize) local bytesWritten = Lib.caca_utf32_to_utf8(buff, utf32char) return bytesWritten; end function CharSets.utf32Toascii(utf32char) return Lib.caca_utf32_to_ascii(utf32char); end function CharSets.utf32Tocp437(utf32char) return Lib.caca_utf32_to_cp437(utf32char); end function CharSets.cp437Toutf32(cp437char) return Lib.caca_cp437_to_utf32(cp437char); end function CharSets.utf32IsFullWidth(utf32char) return Lib.caca_utf32_is_fullwidth(utf32char); end return CharSets;
ElvDB = { ["profileKeys"] = { ["诗雨筱零 - 纳克萨玛斯"] = "诗雨筱零 - 纳克萨玛斯", ["Asdffg - 纳克萨玛斯"] = "Asdffg - 纳克萨玛斯", ["涴紗 - 凤凰之神"] = "涴紗 - 凤凰之神", }, ["gold"] = { ["纳克萨玛斯"] = { ["Asdffg"] = 0, ["诗雨筱零"] = 137399435, }, ["凤凰之神"] = { ["涴紗"] = 9758258, }, }, ["namespaces"] = { ["LibDualSpec-1.0"] = { }, }, ["global"] = { ["general"] = { ["smallerWorldMap"] = false, ["showMissingTalentAlert"] = true, ["mapAlphaWhenMoving"] = 0.33, ["smallerWorldMapScale"] = 0.87, ["autoScale"] = false, }, ["uiScale"] = "1.0", ["userInformedNewChanges1"] = true, }, ["profiles"] = { ["诗雨筱零 - 纳克萨玛斯"] = { ["databars"] = { ["honor"] = { ["enable"] = false, }, ["azerite"] = { ["height"] = 198, }, }, ["currentTutorial"] = 1, ["general"] = { ["autoAcceptInvite"] = true, ["minimap"] = { ["icons"] = { ["classHall"] = { ["scale"] = 0.7, ["yOffset"] = -4, }, }, }, ["bottomPanel"] = false, ["threat"] = { ["enable"] = false, }, ["stickyFrames"] = false, ["backdropcolor"] = { ["r"] = 0.0588235294117647, ["g"] = 0.0588235294117647, ["b"] = 0.0588235294117647, }, ["topPanel"] = false, ["bordercolor"] = { ["r"] = 0.0588235294117647, ["g"] = 0.0588235294117647, ["b"] = 0.0549019607843137, }, ["autoRoll"] = true, }, ["bags"] = { ["junkIcon"] = true, ["vendorGrays"] = { ["enable"] = true, }, ["clearSearchOnClose"] = true, ["cooldown"] = { ["override"] = true, ["checkSeconds"] = true, }, }, ["hideTutorial"] = true, ["chat"] = { ["shortChannels"] = false, ["panelTabTransparency"] = true, ["separateSizes"] = true, ["fadeUndockedTabs"] = false, ["panelWidth"] = 457, ["panelColorConverted"] = true, ["panelHeight"] = 234, ["whisperSound"] = "Big Yankie Devil", ["lockPositions"] = false, ["panelColor"] = { ["a"] = 0, ["r"] = 0.0588235294117647, ["g"] = 0.0588235294117647, ["b"] = 0.0588235294117647, }, ["fadeTabsNoBackdrop"] = false, ["panelHeightRight"] = 200, }, ["WindTools"] = { ["Trade"] = { ["Azerite Tooltip"] = { ["OnlySpec"] = true, ["Compact"] = true, }, }, ["Interface"] = { ["iShadow"] = { ["level"] = 45, }, ["Auto Buttons"] = { ["whiteList"] = { [152495] = true, [152496] = true, [152561] = true, [8529] = true, }, ["countFontSize"] = 14, ["questNum"] = 12, ["questPerRow"] = 12, ["questSize"] = 28, }, }, ["More Tools"] = { ["Enhanced Blizzard Frame"] = { ["points"] = { ["TradeSkillFrame"] = { "CENTER", -- [1] "UIParent", -- [2] "CENTER", -- [3] 58.9998970031738, -- [4] 125.38786315918, -- [5] }, ["ReadyCheckFrame"] = { "CENTER", -- [1] "UIParent", -- [2] "CENTER", -- [3] 5.99991512298584, -- [4] 9.712791506899520e-05, -- [5] }, ["AuctionFrame"] = { "TOPLEFT", -- [1] "UIParent", -- [2] "TOPLEFT", -- [3] 39.9999961853027, -- [4] -97.0000228881836, -- [5] }, ["CommunitiesFrame"] = { "CENTER", -- [1] "UIParent", -- [2] "CENTER", -- [3] -69.0001220703125, -- [4] 141, -- [5] }, ["CharacterFrame"] = { "TOP", -- [1] "UIParent", -- [2] "TOP", -- [3] 45.9999732971191, -- [4] -114.999588012695, -- [5] }, ["CollectionsJournal"] = { "RIGHT", -- [1] "UIParent", -- [2] "RIGHT", -- [3] -140.499801635742, -- [4] 36.0000076293945, -- [5] }, ["MerchantFrame"] = { "LEFT", -- [1] "UIParent", -- [2] "LEFT", -- [3] 0, -- [4] -35.5002517700195, -- [5] }, ["DressUpFrame"] = { "CENTER", -- [1] "UIParent", -- [2] "CENTER", -- [3] -287.000061035156, -- [4] 74.9999771118164, -- [5] }, ["WorldMapFrame"] = { "CENTER", -- [1] "UIParent", -- [2] "CENTER", -- [3] -143, -- [4] 63.0000190734863, -- [5] }, ["PlayerTalentFrame"] = { "TOP", -- [1] "UIParent", -- [2] "TOP", -- [3] -161.499893188477, -- [4] -87.9999618530274, -- [5] }, ["SpellBookFrame"] = { "LEFT", -- [1] "UIParent", -- [2] "LEFT", -- [3] 54.9997291564941, -- [4] 103.000007629395, -- [5] }, ["PVEFrame"] = { "LEFT", -- [1] "UIParent", -- [2] "LEFT", -- [3] 85.5001449584961, -- [4] 97.4999771118164, -- [5] }, ["InspectFrame"] = { "TOP", -- [1] "UIParent", -- [2] "TOP", -- [3] -98.0001220703125, -- [4] -122.999938964844, -- [5] }, ["GarrisonLandingPage"] = { "CENTER", -- [1] "UIParent", -- [2] "CENTER", -- [3] -215.999771118164, -- [4] 3.00005459785461, -- [5] }, ["EncounterJournal"] = { "TOP", -- [1] "UIParent", -- [2] "TOP", -- [3] -210.000717163086, -- [4] -103.999908447266, -- [5] }, ["AzeriteEmpoweredItemUI"] = { "LEFT", -- [1] "UIParent", -- [2] "LEFT", -- [3] 101.000061035156, -- [4] 96.5000762939453, -- [5] }, ["InterfaceOptionsFrame"] = { "TOPRIGHT", -- [1] "UIParent", -- [2] "TOPRIGHT", -- [3] -101.00008392334, -- [4] -80.4998779296875, -- [5] }, }, }, }, }, ["KlixUI"] = { ["installed"] = true, }, ["movers"] = { ["PetAB"] = "TOPLEFT,ElvUIParent,TOPLEFT,593,-294", ["ElvUF_RaidMover"] = "TOPLEFT,ElvUIParent,BOTTOMLEFT,367,741", ["LeftChatMover"] = "BOTTOMLEFT,ElvUIParent,BOTTOMLEFT,4,4", ["GMMover"] = "TOPLEFT,ElvUIParent,TOPLEFT,256,-32", ["BuffsMover"] = "TOPRIGHT,ElvUIParent,TOPRIGHT,0,-26", ["LootFrameMover"] = "TOPLEFT,ElvUIParent,TOPLEFT,50,-165", ["SocialMenuMover"] = "BOTTOMLEFT,ElvUIParent,BOTTOMLEFT,3,208", ["ElvUF_RaidpetMover"] = "TOPLEFT,ElvUIParent,BOTTOMLEFT,4,736", ["AutoButtonAnchor2Mover"] = "BOTTOMRIGHT,ElvUIParent,BOTTOMRIGHT,-211,205", ["AutoButtonAnchorMover"] = "TOP,ElvUIParent,TOP,296,-411", ["UIErrorsFrameMover"] = "TOP,ElvUIParent,TOP,-23,-34", ["alertFrameMover"] = "TOP,ElvUIParent,TOP,15,-199", ["ElvUF_TargetMover"] = "BOTTOMRIGHT,ElvUIParent,BOTTOMRIGHT,-447,223", ["ElvUF_Raid40Mover"] = "TOPLEFT,ElvUIParent,BOTTOMLEFT,0,548", ["SpecializationBarMover"] = "BOTTOMLEFT,ElvUIParent,BOTTOMLEFT,36,268", ["ElvAB_1"] = "BOTTOM,ElvUIParent,BOTTOM,9,33", ["ElvAB_2"] = "BOTTOM,ElvUIParent,BOTTOM,9,101", ["BelowMinimapContainerMover"] = "TOPRIGHT,ElvUIParent,TOPRIGHT,0,-249", ["ElvAB_4"] = "BOTTOM,ElvUIParent,BOTTOM,-302,62", ["AzeriteBarMover"] = "BOTTOMRIGHT,ElvUIParent,BOTTOMRIGHT,-411,0", ["ElvAB_3"] = "BOTTOM,ElvUIParent,BOTTOM,9,67", ["ElvAB_5"] = "BOTTOM,ElvUIParent,BOTTOM,-303,3", ["ElvUF_AssistMover"] = "TOPLEFT,ElvUIParent,BOTTOMLEFT,1135,1011", ["ObjectiveFrameMover"] = "TOPRIGHT,ElvUIParent,TOPRIGHT,-61,-300", ["BNETMover"] = "TOPRIGHT,ElvUIParent,TOPRIGHT,0,-197", ["ShiftAB"] = "TOPLEFT,ElvUIParent,BOTTOMLEFT,0,919", ["ElvUIBankMover"] = "TOPRIGHT,ElvUIParent,TOPRIGHT,-467,-4", ["RaidUtility_Mover"] = "TOPLEFT,ElvUIParent,TOPLEFT,474,-21", ["ElvAB_6"] = "BOTTOM,ElvUIParent,BOTTOM,13,0", ["TotemBarMover"] = "BOTTOMLEFT,ElvUIParent,BOTTOMLEFT,257,335", ["ElvUF_TankMover"] = "TOPLEFT,ElvUIParent,BOTTOMLEFT,574,972", ["RightChatMover"] = "BOTTOMRIGHT,ElvUIParent,BOTTOMRIGHT,0,0", ["Notification Mover"] = "TOP,ElvUIParent,TOP,-21,-66", ["PlayerPowerBarMover"] = "TOP,ElvUIParent,TOP,-273,-463", ["ElvUF_PartyMover"] = "BOTTOMLEFT,ElvUIParent,BOTTOMLEFT,448,480", ["ElvUF_PlayerMover"] = "BOTTOMLEFT,ElvUIParent,BOTTOMLEFT,340,348", ["DebuffsMover"] = "TOPRIGHT,ElvUIParent,TOPRIGHT,0,-149", ["MinimapMover"] = "BOTTOMRIGHT,ElvUIParent,BOTTOMRIGHT,-424,0", }, ["unitframe"] = { ["units"] = { ["targettarget"] = { ["enable"] = false, }, ["player"] = { ["debuffs"] = { ["enable"] = false, }, ["enable"] = false, ["CombatIcon"] = { ["enable"] = false, }, ["aurabar"] = { ["enable"] = false, }, ["RestIcon"] = { ["enable"] = false, }, ["power"] = { ["detachFromFrame"] = true, ["text_format"] = "[powercolor][power:current][power:percent]", ["height"] = 6, ["attachTextTo"] = "Power", }, ["width"] = 234, ["health"] = { ["text_format"] = "[power:percent]", }, ["castbar"] = { ["width"] = 234, ["enable"] = false, }, ["height"] = 16, }, ["raid"] = { ["enable"] = false, }, ["boss"] = { ["enable"] = false, }, ["raid40"] = { ["enable"] = false, }, ["focus"] = { ["enable"] = false, }, ["target"] = { ["debuffs"] = { ["enable"] = false, }, ["phaseIndicator"] = { ["enable"] = false, }, ["height"] = 33, ["aurabar"] = { ["enable"] = false, }, ["width"] = 234, ["castbar"] = { ["enable"] = false, ["width"] = 234, }, }, ["arena"] = { ["enable"] = false, }, ["assist"] = { ["enable"] = false, }, ["party"] = { ["showPlayer"] = false, ["enable"] = false, }, }, }, ["datatexts"] = { ["minimapTop"] = true, ["goldFormat"] = "SMART", ["panelTransparency"] = true, ["panels"] = { ["LeftMiniPanel"] = "", ["RightMiniPanel"] = "", }, ["minimapBottom"] = true, }, ["actionbar"] = { ["bar3"] = { ["inheritGlobalFade"] = true, ["buttons"] = 12, ["showGrid"] = false, ["buttonsPerRow"] = 12, }, ["bar1"] = { ["inheritGlobalFade"] = true, ["showGrid"] = false, }, ["barPet"] = { ["enabled"] = false, }, ["hideCooldownBling"] = true, ["bar2"] = { ["inheritGlobalFade"] = true, ["enabled"] = true, ["showGrid"] = false, }, ["bar5"] = { ["inheritGlobalFade"] = true, ["buttons"] = 12, ["showGrid"] = false, ["buttonsize"] = 25, }, ["bar6"] = { ["inheritGlobalFade"] = true, ["showGrid"] = false, }, ["cooldown"] = { ["override"] = true, ["checkSeconds"] = true, }, ["bar4"] = { ["inheritGlobalFade"] = true, ["backdrop"] = false, ["showGrid"] = false, ["buttonsPerRow"] = 6, ["buttonsize"] = 25, }, }, ["nameplates"] = { ["units"] = { ["ENEMY_NPC"] = { ["healthbar"] = { ["text"] = { ["enable"] = true, ["format"] = "CURRENT_PERCENT", }, }, }, ["HEALER"] = { ["debuffs"] = { ["enable"] = false, }, ["buffs"] = { ["enable"] = false, }, ["healthbar"] = { ["enable"] = false, ["text"] = { ["enable"] = true, ["format"] = "CURRENT_PERCENT", }, }, }, ["PLAYER"] = { ["healthbar"] = { ["text"] = { ["enable"] = true, ["format"] = "CURRENT_PERCENT", }, }, ["debuffs"] = { ["enable"] = false, }, ["buffs"] = { ["enable"] = false, }, }, }, ["showNPCTitles"] = false, ["hideBlizzardPlates"] = true, ["cooldown"] = { ["checkSeconds"] = true, }, }, ["cooldown"] = { ["fonts"] = { ["enable"] = true, }, ["checkSeconds"] = true, }, ["auras"] = { ["cooldown"] = { ["checkSeconds"] = true, }, }, }, ["Asdffg - 纳克萨玛斯"] = { ["movers"] = { ["ElvUF_Raid40Mover"] = "TOPLEFT,ElvUIParent,BOTTOMLEFT,4,432", ["ShiftAB"] = "TOPLEFT,ElvUIParent,BOTTOMLEFT,4,1013", ["ElvUF_PartyMover"] = "BOTTOMLEFT,ElvUIParent,BOTTOMLEFT,4,195", ["ElvUF_RaidMover"] = "TOPLEFT,ElvUIParent,BOTTOMLEFT,4,427", ["ElvUF_RaidpetMover"] = "TOPLEFT,ElvUIParent,BOTTOMLEFT,4,736", }, ["general"] = { ["minimap"] = { ["icons"] = { ["classHall"] = { ["scale"] = 0.7, ["yOffset"] = -4, }, }, }, }, ["chat"] = { ["panelColorConverted"] = true, }, }, ["Minimalistic"] = { ["currentTutorial"] = 2, ["general"] = { ["font"] = "Expressway", ["bottomPanel"] = false, ["backdropfadecolor"] = { ["a"] = 0.80000001192093, ["r"] = 0.058823529411765, ["g"] = 0.058823529411765, ["b"] = 0.058823529411765, }, ["reputation"] = { ["orientation"] = "HORIZONTAL", ["textFormat"] = "PERCENT", ["height"] = 16, ["width"] = 200, }, ["bordercolor"] = { ["r"] = 0.30588235294118, ["g"] = 0.30588235294118, ["b"] = 0.30588235294118, }, ["valuecolor"] = { ["a"] = 1, ["r"] = 1, ["g"] = 1, ["b"] = 1, }, ["fontSize"] = 11, }, ["movers"] = { ["PetAB"] = "TOPRIGHT,ElvUIParent,TOPRIGHT,-50,-428", ["ElvUF_RaidMover"] = "BOTTOMLEFT,ElvUIParent,BOTTOMLEFT,51,120", ["LeftChatMover"] = "BOTTOMLEFT,ElvUIParent,BOTTOMLEFT,50,50", ["GMMover"] = "TOPLEFT,ElvUIParent,TOPLEFT,250,-50", ["BossButton"] = "TOPRIGHT,ElvUIParent,TOPRIGHT,-117,-298", ["LootFrameMover"] = "TOPLEFT,ElvUIParent,TOPLEFT,249,-216", ["ElvUF_RaidpetMover"] = "TOPLEFT,ElvUIParent,BOTTOMLEFT,50,827", ["MicrobarMover"] = "TOPLEFT,ElvUIParent,TOPLEFT,4,-52", ["VehicleSeatMover"] = "TOPLEFT,ElvUIParent,TOPLEFT,51,-87", ["ElvUF_TargetTargetMover"] = "BOTTOM,ElvUIParent,BOTTOM,0,143", ["ElvUF_Raid40Mover"] = "TOPLEFT,ElvUIParent,BOTTOMLEFT,392,1073", ["ElvAB_1"] = "BOTTOM,ElvUIParent,BOTTOM,0,50", ["ElvAB_2"] = "BOTTOM,ElvUIParent,BOTTOM,0,90", ["ElvAB_4"] = "TOPRIGHT,ElvUIParent,TOPRIGHT,-50,-394", ["AltPowerBarMover"] = "TOP,ElvUIParent,TOP,0,-186", ["ElvAB_3"] = "BOTTOM,ElvUIParent,BOTTOM,305,50", ["ElvAB_5"] = "BOTTOM,ElvUIParent,BOTTOM,-305,50", ["MinimapMover"] = "TOPRIGHT,ElvUIParent,TOPRIGHT,-50,-50", ["ElvUF_TargetMover"] = "BOTTOM,ElvUIParent,BOTTOM,230,140", ["ObjectiveFrameMover"] = "TOPRIGHT,ElvUIParent,TOPRIGHT,-122,-393", ["BNETMover"] = "BOTTOMLEFT,ElvUIParent,BOTTOMLEFT,50,232", ["ShiftAB"] = "TOPLEFT,ElvUIParent,BOTTOMLEFT,50,1150", ["ElvUF_PlayerCastbarMover"] = "BOTTOM,ElvUIParent,BOTTOM,0,133", ["ElvUF_PartyMover"] = "TOPLEFT,ElvUIParent,BOTTOMLEFT,184,773", ["ElvAB_6"] = "BOTTOMRIGHT,ElvUIParent,BOTTOMRIGHT,-488,330", ["TooltipMover"] = "BOTTOMRIGHT,ElvUIParent,BOTTOMRIGHT,-50,50", ["ElvUF_TankMover"] = "TOPLEFT,ElvUIParent,BOTTOMLEFT,50,995", ["TotemBarMover"] = "BOTTOMLEFT,ElvUIParent,BOTTOMLEFT,463,50", ["ElvUF_PetMover"] = "BOTTOM,ElvUIParent,BOTTOM,0,200", ["ElvUF_PlayerMover"] = "BOTTOM,ElvUIParent,BOTTOM,-230,140", ["RightChatMover"] = "BOTTOMRIGHT,ElvUIParent,BOTTOMRIGHT,-50,50", ["AlertFrameMover"] = "TOP,ElvUIParent,TOP,0,-50", ["ReputationBarMover"] = "TOPRIGHT,ElvUIParent,TOPRIGHT,-50,-228", ["ElvUF_AssistMover"] = "TOPLEFT,ElvUIParent,BOTTOMLEFT,51,937", }, ["bags"] = { ["itemLevelFontSize"] = 9, ["countFontSize"] = 9, }, ["hideTutorial"] = true, ["auras"] = { ["font"] = "Expressway", ["buffs"] = { ["countFontSize"] = 11, ["maxWraps"] = 2, ["durationFontSize"] = 11, }, ["debuffs"] = { ["countFontSize"] = 11, ["durationFontSize"] = 11, }, }, ["unitframe"] = { ["statusbar"] = "ElvUI Blank", ["fontOutline"] = "THICKOUTLINE", ["smoothbars"] = true, ["font"] = "Expressway", ["fontSize"] = 9, ["units"] = { ["tank"] = { ["enable"] = false, }, ["targettarget"] = { ["infoPanel"] = { ["enable"] = true, }, ["debuffs"] = { ["enable"] = false, }, ["name"] = { ["attachTextTo"] = "InfoPanel", ["yOffset"] = -2, ["position"] = "TOP", }, ["height"] = 50, ["width"] = 122, }, ["pet"] = { ["infoPanel"] = { ["enable"] = true, ["height"] = 14, }, ["debuffs"] = { ["enable"] = true, }, ["threatStyle"] = "NONE", ["castbar"] = { ["width"] = 122, }, ["height"] = 50, ["portrait"] = { ["camDistanceScale"] = 2, }, ["width"] = 122, }, ["player"] = { ["debuffs"] = { ["perrow"] = 7, }, ["power"] = { ["attachTextTo"] = "InfoPanel", ["text_format"] = "[powercolor][power:current-max]", ["height"] = 15, }, ["combatfade"] = true, ["infoPanel"] = { ["enable"] = true, }, ["health"] = { ["attachTextTo"] = "InfoPanel", ["text_format"] = "[healthcolor][health:current-max]", }, ["height"] = 80, ["castbar"] = { ["iconAttached"] = false, ["iconSize"] = 54, ["height"] = 35, ["width"] = 478, }, ["classbar"] = { ["height"] = 15, ["autoHide"] = true, }, ["name"] = { ["attachTextTo"] = "InfoPanel", ["text_format"] = "[namecolor][name]", }, }, ["party"] = { ["horizontalSpacing"] = 3, ["debuffs"] = { ["numrows"] = 4, ["anchorPoint"] = "BOTTOM", ["perrow"] = 1, }, ["power"] = { ["text_format"] = "", ["height"] = 5, }, ["enable"] = false, ["rdebuffs"] = { ["font"] = "Expressway", }, ["growthDirection"] = "RIGHT_DOWN", ["infoPanel"] = { ["enable"] = true, }, ["roleIcon"] = { ["position"] = "TOPRIGHT", }, ["health"] = { ["attachTextTo"] = "InfoPanel", ["orientation"] = "VERTICAL", ["text_format"] = "[healthcolor][health:current]", ["position"] = "RIGHT", }, ["healPrediction"] = true, ["height"] = 59, ["verticalSpacing"] = 0, ["name"] = { ["attachTextTo"] = "InfoPanel", ["text_format"] = "[namecolor][name:short]", ["position"] = "LEFT", }, ["width"] = 110, }, ["raid40"] = { ["enable"] = false, ["rdebuffs"] = { ["font"] = "Expressway", }, }, ["focus"] = { ["infoPanel"] = { ["height"] = 17, ["enable"] = true, }, ["threatStyle"] = "NONE", ["castbar"] = { ["iconSize"] = 26, ["width"] = 122, }, ["height"] = 56, ["name"] = { ["attachTextTo"] = "InfoPanel", ["position"] = "LEFT", }, ["health"] = { ["attachTextTo"] = "InfoPanel", ["text_format"] = "[healthcolor][health:current]", }, ["width"] = 189, }, ["assist"] = { ["enable"] = false, }, ["arena"] = { ["castbar"] = { ["width"] = 246, }, ["spacing"] = 26, }, ["raid"] = { ["roleIcon"] = { ["position"] = "RIGHT", }, ["debuffs"] = { ["enable"] = true, ["sizeOverride"] = 27, ["perrow"] = 4, }, ["rdebuffs"] = { ["enable"] = false, ["font"] = "Expressway", }, ["growthDirection"] = "UP_RIGHT", ["health"] = { ["yOffset"] = -6, }, ["width"] = 140, ["height"] = 28, ["name"] = { ["position"] = "LEFT", }, ["visibility"] = "[nogroup] hide;show", ["groupsPerRowCol"] = 5, }, ["target"] = { ["debuffs"] = { ["perrow"] = 7, }, ["power"] = { ["attachTextTo"] = "InfoPanel", ["hideonnpc"] = false, ["text_format"] = "[powercolor][power:current-max]", ["height"] = 15, }, ["infoPanel"] = { ["enable"] = true, }, ["name"] = { ["attachTextTo"] = "InfoPanel", ["text_format"] = "[namecolor][name]", }, ["castbar"] = { ["iconSize"] = 54, ["iconAttached"] = false, }, ["height"] = 80, ["buffs"] = { ["perrow"] = 7, }, ["smartAuraPosition"] = "DEBUFFS_ON_BUFFS", ["health"] = { ["attachTextTo"] = "InfoPanel", ["text_format"] = "[healthcolor][health:current-max]", }, }, }, }, ["datatexts"] = { ["minimapPanels"] = false, ["fontSize"] = 11, ["leftChatPanel"] = false, ["goldFormat"] = "SHORT", ["panelTransparency"] = true, ["font"] = "Expressway", ["panels"] = { ["BottomMiniPanel"] = "Time", ["RightMiniPanel"] = "", ["RightChatDataPanel"] = { ["right"] = "", ["left"] = "", ["middle"] = "", }, ["LeftMiniPanel"] = "", ["LeftChatDataPanel"] = { ["right"] = "", ["left"] = "", ["middle"] = "", }, }, ["rightChatPanel"] = false, }, ["actionbar"] = { ["bar3"] = { ["inheritGlobalFade"] = true, ["buttonsize"] = 38, ["buttonsPerRow"] = 3, }, ["fontSize"] = 9, ["bar2"] = { ["enabled"] = true, ["inheritGlobalFade"] = true, ["buttonsize"] = 38, }, ["bar1"] = { ["heightMult"] = 2, ["inheritGlobalFade"] = true, ["buttonsize"] = 38, }, ["bar5"] = { ["inheritGlobalFade"] = true, ["buttonsize"] = 38, ["buttonsPerRow"] = 3, }, ["globalFadeAlpha"] = 0.87, ["stanceBar"] = { ["inheritGlobalFade"] = true, }, ["bar6"] = { ["buttonsize"] = 38, }, ["bar4"] = { ["enabled"] = false, ["backdrop"] = false, ["buttonsize"] = 38, }, }, ["layoutSet"] = "dpsMelee", ["chat"] = { ["chatHistory"] = false, ["fontSize"] = 11, ["tabFont"] = "Expressway", ["tabFontSize"] = 11, ["fadeUndockedTabs"] = false, ["editBoxPosition"] = "ABOVE_CHAT", ["fadeTabsNoBackdrop"] = false, ["font"] = "Expressway", ["panelBackdrop"] = "HIDEBOTH", }, ["tooltip"] = { ["textFontSize"] = 11, ["font"] = "Expressway", ["healthBar"] = { ["font"] = "Expressway", }, ["smallTextFontSize"] = 11, ["fontSize"] = 11, ["headerFontSize"] = 11, }, ["nameplates"] = { ["filters"] = { }, }, }, ["涴紗 - 凤凰之神"] = { ["WindTools"] = { ["More Tools"] = { ["Enhanced Blizzard Frame"] = { ["points"] = { ["DressUpFrame"] = { "TOP", -- [1] "UIParent", -- [2] "TOP", -- [3] 14.999981880188, -- [4] -103.999977111816, -- [5] }, }, }, }, }, ["currentTutorial"] = 7, ["general"] = { ["stickyFrames"] = false, ["minimap"] = { ["icons"] = { ["classHall"] = { ["scale"] = 0.7, ["yOffset"] = -4, }, }, }, }, ["movers"] = { ["ElvUF_RaidpetMover"] = "TOPLEFT,ElvUIParent,BOTTOMLEFT,4,736", ["ShiftAB"] = "TOPLEFT,ElvUIParent,BOTTOMLEFT,4,919", ["ElvUF_PlayerCastbarMover"] = "BOTTOMLEFT,ElvUIParent,BOTTOMLEFT,453,362", ["ElvAB_1"] = "BOTTOM,ElvUIParent,BOTTOM,48,29", ["ElvAB_2"] = "BOTTOM,ElvUIParent,BOTTOM,48,97", ["ElvUF_RaidMover"] = "TOPLEFT,ElvUIParent,BOTTOMLEFT,4,427", ["KuiMiddleDTMover"] = "BOTTOM,ElvUIParent,BOTTOM,29,4", ["ElvUF_Raid40Mover"] = "TOPLEFT,ElvUIParent,BOTTOMLEFT,4,432", ["PlayerPowerBarMover"] = "TOP,ElvUIParent,TOP,185,-449", ["ElvUF_PartyMover"] = "BOTTOMLEFT,ElvUIParent,BOTTOMLEFT,4,195", ["ElvAB_3"] = "BOTTOM,ElvUIParent,BOTTOM,48,63", ["ElvAB_5"] = "BOTTOM,ElvUIParent,BOTTOM,-259,26", ["ElvUF_PlayerMover"] = "BOTTOMLEFT,ElvUIParent,BOTTOMLEFT,453,407", ["ElvUF_TargetMover"] = "BOTTOMRIGHT,ElvUIParent,BOTTOMRIGHT,-433,245", }, ["actionbar"] = { ["bar3"] = { ["buttonsPerRow"] = 12, ["buttons"] = 12, }, ["bar5"] = { ["buttons"] = 12, }, ["bar2"] = { ["enabled"] = true, }, }, ["KlixUI"] = { ["installed"] = true, }, ["unitframe"] = { ["units"] = { ["target"] = { ["height"] = 32, ["castbar"] = { ["width"] = 275, }, ["width"] = 275, }, ["player"] = { ["height"] = 25, ["power"] = { ["detachFromFrame"] = true, ["attachTextTo"] = "Power", ["height"] = 12, }, }, ["targettarget"] = { ["enable"] = false, }, }, }, ["chat"] = { ["panelColorConverted"] = true, }, }, }, } ElvPrivateDB = { ["profileKeys"] = { ["诗雨筱零 - 纳克萨玛斯"] = "诗雨筱零 - 纳克萨玛斯", ["Asdffg - 纳克萨玛斯"] = "Asdffg - 纳克萨玛斯", ["涴紗 - 凤凰之神"] = "涴紗 - 凤凰之神", }, ["profiles"] = { ["诗雨筱零 - 纳克萨玛斯"] = { ["chat"] = { ["enable"] = false, }, ["nameplates"] = { ["enable"] = false, }, ["KlixUI"] = { ["characterGoldsSorting"] = { ["纳克萨玛斯"] = { }, }, ["install_complete"] = "1.39", }, ["install_complete"] = "10.82", }, ["Asdffg - 纳克萨玛斯"] = { ["nameplates"] = { ["enable"] = false, }, ["KlixUI"] = { ["characterGoldsSorting"] = { ["纳克萨玛斯"] = { }, }, ["session"] = { ["day"] = 5, }, }, }, ["涴紗 - 凤凰之神"] = { ["nameplates"] = { ["enable"] = false, }, ["KlixUI"] = { ["session"] = { ["day"] = 6, }, ["characterGoldsSorting"] = { ["凤凰之神"] = { }, }, ["install_complete"] = "1.41", }, ["install_complete"] = "10.83", ["chat"] = { ["enable"] = false, }, }, }, }
local meta = FindMetaTable("Entity") if not meta then return end meta.oldPlayerHolding = meta.oldPlayerHolding or meta.IsPlayerHolding function meta:IsPlayerHolding() local isHolding = self:oldPlayerHolding() if self.bIsHolding ~= isHolding then self:SetNW2Bool("holding", isHolding) end return isHolding end
object_tangible_loot_loot_schematic_rebel_trooper_helmet_schematic = object_tangible_loot_loot_schematic_shared_rebel_trooper_helmet_schematic:new { } ObjectTemplates:addTemplate(object_tangible_loot_loot_schematic_rebel_trooper_helmet_schematic, "object/tangible/loot/loot/schematic/rebel_trooper_helmet_schematic.iff")
-- load app code local App = dofile("../code/anisopoisson.lua") local x0, y0 = 0.0, 0.0 -- location of O local zet = 1e9 -- Dpar/Dperp local Dpar = 1.0 -- parallel heat conduction local Dperp = Dpar/zet -- perpendicular heat conduction local theta = 15.0*math.pi/180 aPoisson = App { polyOrder = 1, cflFrac = 0.9, lower = {-0.5, -0.5}, upper = {0.5, 0.5}, cells = {32, 32}, bcLower = { {D=1, N=0, val=0.0}, {D=1, N=0, val=0.0} }, bcUpper = { {D=1, N=0, val=0.0}, {D=1, N=0, val=0.0} }, -- diffusion coefficients Dxx = function (t, z) local x, y = z[1], z[2] local bx, by = math.cos(theta), math.sin(theta) return Dpar*bx^2 + Dperp*by^2 end, Dyy = function (t, z) local x, y = z[1], z[2] local bx, by = math.cos(theta), math.sin(theta) return Dperp*bx^2 + Dpar*by^2 end, Dxy = function (t, z) local x, y = z[1], z[2] local bx, by = math.cos(theta), math.sin(theta) return (Dpar-Dperp)*bx*by end, -- source (RHS) src = function (t, z) local x, y = z[1], z[2] local bx, by = math.cos(theta), math.sin(theta) return (-20.0*Dperp*by^2*x^3*y^5)-20.0*Dpar*bx^2*x^3*y^5+3.0*Dperp*by^2*x^2*y^5+3.0*Dpar*bx^2*x^2*y^5+1.875*Dperp*by^2*x*y^5+1.875*Dpar*bx^2*x*y^5-0.15625*Dperp*by^2*y^5-0.15625*Dpar*bx^2*y^5+50.0*Dperp*bx*by*x^4*y^4-50.0*Dpar*bx*by*x^4*y^4-5.0*Dperp*by^2*x^3*y^4-10.0*Dperp*bx*by*x^3*y^4+10.0*Dpar*bx*by*x^3*y^4-5.0*Dpar*bx^2*x^3*y^4+0.75*Dperp*by^2*x^2*y^4-9.375*Dperp*bx*by*x^2*y^4+9.375*Dpar*bx*by*x^2*y^4+0.75*Dpar*bx^2*x^2*y^4+0.46875*Dperp*by^2*x*y^4+1.5625*Dperp*bx*by*x*y^4-1.5625*Dpar*bx*by*x*y^4+0.46875*Dpar*bx^2*x*y^4-0.0390625*Dperp*by^2*y^4+0.15625*Dperp*bx*by*y^4-0.15625*Dpar*bx*by*y^4-0.0390625*Dpar*bx^2*y^4-20.0*Dpar*by^2*x^5*y^3-20.0*Dperp*bx^2*x^5*y^3+5.0*Dpar*by^2*x^4*y^3+10.0*Dperp*bx*by*x^4*y^3-10.0*Dpar*bx*by*x^4*y^3+5.0*Dperp*bx^2*x^4*y^3+6.25*Dperp*by^2*x^3*y^3+6.25*Dpar*by^2*x^3*y^3-2.0*Dperp*bx*by*x^3*y^3+2.0*Dpar*bx*by*x^3*y^3+6.25*Dperp*bx^2*x^3*y^3+6.25*Dpar*bx^2*x^3*y^3-0.9375*Dperp*by^2*x^2*y^3-1.5625*Dpar*by^2*x^2*y^3-1.875*Dperp*bx*by*x^2*y^3+1.875*Dpar*bx*by*x^2*y^3-1.5625*Dperp*bx^2*x^2*y^3-0.9375*Dpar*bx^2*x^2*y^3-0.5859375*Dperp*by^2*x*y^3-0.3125*Dpar*by^2*x*y^3+0.3125*Dperp*bx*by*x*y^3-0.3125*Dpar*bx*by*x*y^3-0.3125*Dperp*bx^2*x*y^3-0.5859375*Dpar*bx^2*x*y^3+0.048828125*Dperp*by^2*y^3+0.078125*Dpar*by^2*y^3+0.03125*Dperp*bx*by*y^3-0.03125*Dpar*bx*by*y^3+0.078125*Dperp*bx^2*y^3+0.048828125*Dpar*bx^2*y^3-3.0*Dpar*by^2*x^5*y^2-3.0*Dperp*bx^2*x^5*y^2+0.75*Dpar*by^2*x^4*y^2-9.375*Dperp*bx*by*x^4*y^2+9.375*Dpar*bx*by*x^4*y^2+0.75*Dperp*bx^2*x^4*y^2+1.5625*Dperp*by^2*x^3*y^2+0.9375*Dpar*by^2*x^3*y^2+1.875*Dperp*bx*by*x^3*y^2-1.875*Dpar*bx*by*x^3*y^2+0.9375*Dperp*bx^2*x^3*y^2+1.5625*Dpar*bx^2*x^3*y^2-0.234375*Dperp*by^2*x^2*y^2-0.234375*Dpar*by^2*x^2*y^2+1.7578125*Dperp*bx*by*x^2*y^2-1.7578125*Dpar*bx*by*x^2*y^2-0.234375*Dperp*bx^2*x^2*y^2-0.234375*Dpar*bx^2*x^2*y^2-0.146484375*Dperp*by^2*x*y^2-0.046875*Dpar*by^2*x*y^2-0.29296875*Dperp*bx*by*x*y^2+0.29296875*Dpar*bx*by*x*y^2-0.046875*Dperp*bx^2*x*y^2-0.146484375*Dpar*bx^2*x*y^2+0.01220703125*Dperp*by^2*y^2+0.01171875*Dpar*by^2*y^2-0.029296875*Dperp*bx*by*y^2+0.029296875*Dpar*bx*by*y^2+0.01171875*Dperp*bx^2*y^2+0.01220703125*Dpar*bx^2*y^2+1.875*Dpar*by^2*x^5*y+1.875*Dperp*bx^2*x^5*y-0.46875*Dpar*by^2*x^4*y-1.5625*Dperp*bx*by*x^4*y+1.5625*Dpar*bx*by*x^4*y-0.46875*Dperp*bx^2*x^4*y-0.3125*Dperp*by^2*x^3*y-0.5859375*Dpar*by^2*x^3*y+0.3125*Dperp*bx*by*x^3*y-0.3125*Dpar*bx*by*x^3*y-0.5859375*Dperp*bx^2*x^3*y-0.3125*Dpar*bx^2*x^3*y+0.046875*Dperp*by^2*x^2*y+0.146484375*Dpar*by^2*x^2*y+0.29296875*Dperp*bx*by*x^2*y-0.29296875*Dpar*bx*by*x^2*y+0.146484375*Dperp*bx^2*x^2*y+0.046875*Dpar*bx^2*x^2*y+0.029296875*Dperp*by^2*x*y+0.029296875*Dpar*by^2*x*y-0.048828125*Dperp*bx*by*x*y+0.048828125*Dpar*bx*by*x*y+0.029296875*Dperp*bx^2*x*y+0.029296875*Dpar*bx^2*x*y-0.00244140625*Dperp*by^2*y-0.00732421875*Dpar*by^2*y-0.0048828125*Dperp*bx*by*y+0.0048828125*Dpar*bx*by*y-0.00732421875*Dperp*bx^2*y-0.00244140625*Dpar*bx^2*y+0.15625*Dpar*by^2*x^5+0.15625*Dperp*bx^2*x^5-0.0390625*Dpar*by^2*x^4+0.15625*Dperp*bx*by*x^4-0.15625*Dpar*bx*by*x^4-0.0390625*Dperp*bx^2*x^4-0.078125*Dperp*by^2*x^3-0.048828125*Dpar*by^2*x^3-0.03125*Dperp*bx*by*x^3+0.03125*Dpar*bx*by*x^3-0.048828125*Dperp*bx^2*x^3-0.078125*Dpar*bx^2*x^3+0.01171875*Dperp*by^2*x^2+0.01220703125*Dpar*by^2*x^2-0.029296875*Dperp*bx*by*x^2+0.029296875*Dpar*bx*by*x^2+0.01220703125*Dperp*bx^2*x^2+0.01171875*Dpar*bx^2*x^2+0.00732421875*Dperp*by^2*x+0.00244140625*Dpar*by^2*x+0.0048828125*Dperp*bx*by*x-0.0048828125*Dpar*bx*by*x+0.00244140625*Dperp*bx^2*x+0.00732421875*Dpar*bx^2*x-6.103515625e-4*Dperp*by^2-6.103515625e-4*Dpar*by^2+4.8828125e-4*Dperp*bx*by-4.8828125e-4*Dpar*bx*by-6.103515625e-4*Dperp*bx^2-6.103515625e-4*Dpar*bx^2 end, -- optional exact solution (App will compute projection) sol = function (t, z) local x, y = z[1], z[2] return (x-1/2)*(x+1/2)*(x+1/4)*(x-1/4)^2*(y-1/2)*(y+1/2)*(y+1/4)^2*(y-1/4) end } aPoisson()
local composer = require "composer" local scene = composer.newScene() local widget = require "widget" local json = require "json" local scoresTable = {} local filepath = system.pathForFile("wizBan.json", system.DocumentsDirectory) local function loadScores() local file = io.open(filepath,"r") if file then local contents = file:read("*a") io.close(file) scoresTable = json.decode(contents) end if scoresTable == nil or #scoresTable == 0 then scoresTable = {0,0,0,0,0,0,0,0,0,0} end end local function saveScores() for i = #scoresTable, 11, -1 do table.remove(scoresTable, i) end local file = io.open(filePath, "w") local temp = json.encode(scoresTable) file:write(temp) io.close(file) end local function gotoMenu(event) composer.gotoScene("menu") end function scene:create(event) composer.removeHidden() local sceneGroup = self.view loadScores() table.insert(scoresTable, composer.getVariable("finalScore")) local function compare(a, b) return a>b end table.sort(scoresTable, compare) saveScores() background = display.newImage("plx-1.png",cx,cy) background.width = 1920 background.height = 1080 highScoresTitle = display.newText("High Scores", cx, 100,44) for i = 1, 10 do if scoresTable[i] then local yPos = 150+(i*56) local rankNum = display.newText(i..") ", cx-50, yPos, 35) rankNum:setFillColor(0.8) rankNum.anchorX = 1 local thisScore = display.newText(scoresTable[i], cx-50, yPos, 35) thisScore.anchorX = 0 end end local menuButton = display.newText("Menu",cx, 810, 40) menuButton:setFillColor(0.75, 0.78, 1) menuButton:addEventListener("tap", gotoMenu) end
-- Generated By protoc-gen-lua Do not Edit local protobuf = require "protobuf/protobuf" module('QuerySceneDayCountArg_pb') QUERYSCENEDAYCOUNTARG = protobuf.Descriptor(); local QUERYSCENEDAYCOUNTARG_GROUPID_FIELD = protobuf.FieldDescriptor(); local QUERYSCENEDAYCOUNTARG_TYPE_FIELD = protobuf.FieldDescriptor(); QUERYSCENEDAYCOUNTARG_GROUPID_FIELD.name = "groupid" QUERYSCENEDAYCOUNTARG_GROUPID_FIELD.full_name = ".KKSG.QuerySceneDayCountArg.groupid" QUERYSCENEDAYCOUNTARG_GROUPID_FIELD.number = 1 QUERYSCENEDAYCOUNTARG_GROUPID_FIELD.index = 0 QUERYSCENEDAYCOUNTARG_GROUPID_FIELD.label = 3 QUERYSCENEDAYCOUNTARG_GROUPID_FIELD.has_default_value = false QUERYSCENEDAYCOUNTARG_GROUPID_FIELD.default_value = {} QUERYSCENEDAYCOUNTARG_GROUPID_FIELD.type = 13 QUERYSCENEDAYCOUNTARG_GROUPID_FIELD.cpp_type = 3 QUERYSCENEDAYCOUNTARG_TYPE_FIELD.name = "type" QUERYSCENEDAYCOUNTARG_TYPE_FIELD.full_name = ".KKSG.QuerySceneDayCountArg.type" QUERYSCENEDAYCOUNTARG_TYPE_FIELD.number = 2 QUERYSCENEDAYCOUNTARG_TYPE_FIELD.index = 1 QUERYSCENEDAYCOUNTARG_TYPE_FIELD.label = 1 QUERYSCENEDAYCOUNTARG_TYPE_FIELD.has_default_value = false QUERYSCENEDAYCOUNTARG_TYPE_FIELD.default_value = 0 QUERYSCENEDAYCOUNTARG_TYPE_FIELD.type = 13 QUERYSCENEDAYCOUNTARG_TYPE_FIELD.cpp_type = 3 QUERYSCENEDAYCOUNTARG.name = "QuerySceneDayCountArg" QUERYSCENEDAYCOUNTARG.full_name = ".KKSG.QuerySceneDayCountArg" QUERYSCENEDAYCOUNTARG.nested_types = {} QUERYSCENEDAYCOUNTARG.enum_types = {} QUERYSCENEDAYCOUNTARG.fields = {QUERYSCENEDAYCOUNTARG_GROUPID_FIELD, QUERYSCENEDAYCOUNTARG_TYPE_FIELD} QUERYSCENEDAYCOUNTARG.is_extendable = false QUERYSCENEDAYCOUNTARG.extensions = {} QuerySceneDayCountArg = protobuf.Message(QUERYSCENEDAYCOUNTARG)
local toast = require('toast') local client = toast.Client() local command = toast.Command('flags', { args = { { name = 'test', value = 'string', required = true} }, -- The parser options execute = function(msg, args) -- example msg = !flags "fun times" if args.test then return msg:reply('We are having ' .. args.flags.test .. '!') --> "We are having fun times!" end end }) client:addCommand(command) client:login('token')
local singletons = require "kong.singletons" local cache = require "kong.tools.database_cache" local responses = require "kong.tools.responses" --- Load the configuration for a plugin entry in the DB. -- Given an API, a Consumer and a plugin name, retrieve the plugin's configuration if it exists. -- Results are cached in ngx.dict -- @param[type=string] api_id ID of the API being proxied. -- @param[type=string] consumer_id ID of the Consumer making the request (if any). -- @param[type=stirng] plugin_name Name of the plugin being tested for. -- @treturn table Plugin retrieved from the cache or database. local function load_plugin_configuration(api_id, consumer_id, plugin_name) local cache_key = cache.plugin_key(plugin_name, api_id, consumer_id) local plugin = cache.get_or_set(cache_key, function() local rows, err = singletons.dao.plugins:find_all { api_id = api_id, consumer_id = consumer_id, name = plugin_name } if err then return responses.send_HTTP_INTERNAL_SERVER_ERROR(err) end if #rows > 0 then if consumer_id == nil then for _, row in ipairs(rows) do if row.consumer_id == nil then return row end end else return rows[1] end else -- insert a cached value to not trigger too many DB queries. return {null = true} end end) if plugin ~= nil and plugin.enabled then return plugin.config or {} end end --- Plugins for request iterator. -- Iterate over the plugin loaded for a request, stored in `ngx.ctx.plugins_for_request`. -- @param[type=boolean] is_access_or_certificate_context Tells if the context is access_by_lua_block. We don't use `ngx.get_phase()` simply because we can avoid it. -- @treturn function iterator local function iter_plugins_for_req(loaded_plugins, is_access_or_certificate_context) if not ngx.ctx.plugins_for_request then ngx.ctx.plugins_for_request = {} end local i = 0 local function get_next_plugin() i = i + 1 return loaded_plugins[i] end local function get_next() local plugin = get_next_plugin() if plugin and ngx.ctx.api then if is_access_or_certificate_context then ngx.ctx.plugins_for_request[plugin.name] = load_plugin_configuration(ngx.ctx.api.id, nil, plugin.name) local consumer_id = ngx.ctx.authenticated_credential and ngx.ctx.authenticated_credential.consumer_id or nil if consumer_id and not plugin.schema.no_consumer then local consumer_plugin_configuration = load_plugin_configuration(ngx.ctx.api.id, consumer_id, plugin.name) if consumer_plugin_configuration then ngx.ctx.plugins_for_request[plugin.name] = consumer_plugin_configuration end end end -- Return the configuration if ngx.ctx.plugins_for_request[plugin.name] then return plugin, ngx.ctx.plugins_for_request[plugin.name] end return get_next() -- Load next plugin end end return function() return get_next() end end return iter_plugins_for_req
--[[ desc: Down, a state of Duelist. author: Musoucrow since: 2018-9-30 alter: 2018-10-1 ]]-- local _ASPECT = require("actor.service.aspect") local _BATTLE = require("actor.service.battle") local _IBeaten = require("actor.state.duelist.ibeaten") local _ITimeEnd = require("actor.state.itimeEnd") local _Base = require("actor.state.base") ---@class Actor.State.Duelist.Down : Actor.State local _Down = require("core.class")(_Base, _IBeaten, _ITimeEnd) function _Down:Ctor(data, ...) _Base.Ctor(self, data, ...) _ITimeEnd.Ctor(self, data.time) end function _Down:Update(dt) _IBeaten.Update(self) _Base.Update(self, dt) end function _Down:NormalUpdate(dt) _ITimeEnd.Update(self, dt) end function _Down:OnBeaten(isBeaten) local index = isBeaten and self._entity.battle.deadProcess == 0 and 2 or 1 _ASPECT.Play(self._entity.aspect, self._frameaniDataSets[index]) end function _Down:Enter() _Base.Enter(self) _ITimeEnd.Enter(self) local e = self._entity _BATTLE.DieTick(e.battle, e.attributes, e.transform, e.attacker, e.identity) _IBeaten.Enter(self) end return _Down
require("@vue/runtime-test") require("@vue/runtime-test/NodeTypes") describe('renderer: vnode hooks', function() function assertHooks(hooks, vnode1, vnode2) local root = nodeOps:createElement('div') render(vnode1, root) expect(hooks.onVnodeBeforeMount):toHaveBeenCalledWith(vnode1, nil) expect(hooks.onVnodeMounted):toHaveBeenCalledWith(vnode1, nil) expect(hooks.onVnodeBeforeUpdate).tsvar_not:toHaveBeenCalled() expect(hooks.onVnodeUpdated).tsvar_not:toHaveBeenCalled() expect(hooks.onVnodeBeforeUnmount).tsvar_not:toHaveBeenCalled() expect(hooks.onVnodeUnmounted).tsvar_not:toHaveBeenCalled() render(vnode2, root) expect(hooks.onVnodeBeforeMount):toHaveBeenCalledTimes(1) expect(hooks.onVnodeMounted):toHaveBeenCalledTimes(1) expect(hooks.onVnodeBeforeUpdate):toHaveBeenCalledWith(vnode2, vnode1) expect(hooks.onVnodeUpdated):toHaveBeenCalledWith(vnode2, vnode1) expect(hooks.onVnodeBeforeUnmount).tsvar_not:toHaveBeenCalled() expect(hooks.onVnodeUnmounted).tsvar_not:toHaveBeenCalled() render(nil, root) expect(hooks.onVnodeBeforeMount):toHaveBeenCalledTimes(1) expect(hooks.onVnodeMounted):toHaveBeenCalledTimes(1) expect(hooks.onVnodeBeforeUpdate):toHaveBeenCalledTimes(1) expect(hooks.onVnodeUpdated):toHaveBeenCalledTimes(1) expect(hooks.onVnodeBeforeUnmount):toHaveBeenCalledWith(vnode2, nil) expect(hooks.onVnodeUnmounted):toHaveBeenCalledWith(vnode2, nil) end test('should work on element', function() local hooks = {onVnodeBeforeMount=jest:fn(), onVnodeMounted=jest:fn(), onVnodeBeforeUpdate=jest:fn(function(vnode) expect(vnode.el.children[0+1]):toMatchObject({type=NodeTypes.TEXT, text='foo'}) end ), onVnodeUpdated=jest:fn(function(vnode) expect(vnode.el.children[0+1]):toMatchObject({type=NodeTypes.TEXT, text='bar'}) end ), onVnodeBeforeUnmount=jest:fn(), onVnodeUnmounted=jest:fn()} assertHooks(hooks, h('div', hooks, 'foo'), h('div', hooks, 'bar')) end ) test('should work on component', function() local Comp = function(props) props.msg end local hooks = {onVnodeBeforeMount=jest:fn(), onVnodeMounted=jest:fn(), onVnodeBeforeUpdate=jest:fn(function(vnode) expect(vnode.el):toMatchObject({type=NodeTypes.TEXT, text='foo'}) end ), onVnodeUpdated=jest:fn(function(vnode) expect(vnode.el):toMatchObject({type=NodeTypes.TEXT, text='bar'}) end ), onVnodeBeforeUnmount=jest:fn(), onVnodeUnmounted=jest:fn()} assertHooks(hooks, h(Comp, {..., msg='foo'}), h(Comp, {..., msg='bar'})) end ) end )
local M = {} --[[ Creates iterator that produces the results of some element computation a number of times. interface: https://www.scala-lang.org/api/current/scala/collection/Iterator$.html @param len the number of elements returned by the iterator @param f the element computation @returns a Lua iterator that produces the results of n evaluations of f --]] M.fill = function(len, f) local i = 0 return function() i = i + 1 if i > len then return nil end return f() end end return M
--[[ --MIT License -- --Copyright (c) 2019 manilarome --Copyright (c) 2020 Tom Meyers -- --Permission is hereby granted, free of charge, to any person obtaining a copy --of this software and associated documentation files (the "Software"), to deal --in the Software without restriction, including without limitation the rights --to use, copy, modify, merge, publish, distribute, sublicense, and/or sell --copies of the Software, and to permit persons to whom the Software is --furnished to do so, subject to the following conditions: -- --The above copyright notice and this permission notice shall be included in all --copies or substantial portions of the Software. -- --THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR --IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, --FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE --AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER --LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, --OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE --SOFTWARE. ]] local signals = require("lib-tde.signals") local gettime = require("socket").gettime local screen_geometry = {} local function update_screens() print("Screen layout changed") -- cleanup screen_geometry = {} -- repopulate screen geometry for s in screen do table.insert(screen_geometry, s.geometry) end -- notify tde of screen changes signals.emit_refresh_screen() end -- listen for screen changes awesome.connect_signal( "screen::change", function() update_screens() end ) local prev_time = gettime() -- specify how often to poll local refresh_timeout_in_seconds = 0.5 local function are_screens_equal(s1, s2) return s1.x == s2.x and s1.y == s2.y and s1.width == s2.width and s1.height == s2.height end local function perform_refresh() if not (#screen_geometry == screen.count()) then update_screens() end -- check if our output changed local i = 1 for s in screen do if not are_screens_equal(s.geometry, screen_geometry[i]) then update_screens() end i = i + 1 end end awesome.connect_signal( "refresh", function() local time = gettime() if prev_time < (time - refresh_timeout_in_seconds) then prev_time = time perform_refresh() end end )
--Paths to audio files math.randomseed(os.time()) --Button click ButtonSFX = "mge/Audio/ui_click.wav" --Path to the sound file. ButtonVolume = 20 --Set a volume between 0 - 100. ButtonPitch = 1 --Default value = 1 --Moving a box PushSFX = "mge/Audio/box_pushing2.wav" PushVolume = 5 PushPitch = 0.8 + (math.random( 0, 4 ) / 10) --Switch SwitchSFX = "mge/Audio/switch_activated.wav" SwitchVolume = 50 SwitchPitch = 1 --Level Failure FailureSFX = "mge/Audio/squeak.wav" FailureVolume = 10 FailurePitch = 1 --Exit ExitSFX = "mge/Audio/exit_activated.wav" ExitVolume = 10 ExitPitch = 1 --DIALOGUE DialogueSFX = "mge/Audio/text_box.wav" DialogueVolume = 10 DialoguePitch = 1 --Background music MainMenuBG = "mge/Audio/BGMusic_4.wav" MainMenuVolume = 20 MainMenuPitch = 1 --InGame Background music InGameBG = "mge/Audio/BGMusic_5.wav" InGameVolume = 10 InGamePitch = 1 --Heartbeat HeartBeatSFX = "mge/Audio/heartbeat3.wav" HeartBeatVolume = 100 HeartBeatPitch = 1 HeartBeatMaxTime = 2.0 --Maximum time between heartbeats in seconds HeartBeatMinTime = 0.3 --Minumum time between heartbeats in seconds
-- Generated by CSharp.lua Compiler local System = System local DCETModel = DCET.Model local UnityEngine = UnityEngine System.namespace("DCET.Hotfix", function (namespace) namespace.class("M2C_PathfindingResultHandler", function (namespace) local Run Run = function (this, session, message) return System.async(function (async, this, session, message) local unit = DCETModel.Game.getScene():GetComponent(DCETModel.UnitComponent):Get(message:getId()) unit:GetComponent(DCETModel.AnimatorComponent):SetFloatValue("Speed", 5) local unitPathComponent = unit:GetComponent(DCETModel.UnitPathComponent) unitPathComponent:StartMove(message):Coroutine() DCETModel.GizmosDebug.getInstance().Path:Clear() DCETModel.GizmosDebug.getInstance().Path:Add(UnityEngine.Vector3(message:getX(), message:getY(), message:getZ())) for i = 0, message:getXs():getCount() - 1 do DCETModel.GizmosDebug.getInstance().Path:Add(UnityEngine.Vector3(message:getXs():get(i), message:getYs():get(i), message:getZs():get(i))) end async:Await(DCETModel.ETTask.getCompletedTask()) end, nil, this, session, message) end return { __inherits__ = function (out) return { out.DCET.Hotfix.AMHandler_1(out.DCET.Model.M2C_PathfindingResult) } end, Run = Run } end) end)
require("prototypes.entities") require("prototypes.items") require("prototypes.item-groups") require("prototypes.recipes") require("prototypes.technologies") require("prototypes.tiles")
return { { ["off"]="0.399", ["on"]="0.081", }, { ["off"]="1.339", ["on"]="0.081", }, { ["off"]="4.527", ["on"]="2.817", }, { ["off"]="0.644", ["on"]="0.640", }, { ["off"]="3.032", ["on"]="3.007", }, { ["off"]="4.046", ["on"]="4.977", }, ["local fc = font.current\ \ function font.current()\ return fc()\ end\ \ return function()\ local a = 0\ for i=1,10000 do\ a = a + font.current()\ end\ end"]={ ["off"]="1.998", ["on"]="2.417", }, ["local function whatever(i)\ return i\ end\ \ return function()\ local a = 0\ for i=1,10000 do\ a = a + whatever(i)\ end\ end"]={ ["off"]="0.675", ["on"]="0.041", }, ["local tostring, tonumber = tostring, tonumber\ return function()\ local a = 0\ for i=1,1000 do\ local a = a + tonumber(tostring(i))\ end\ end"]={ ["off"]="4.762", ["on"]="0.172", }, ["local tostring, tonumber = tostring, tonumber\ return function()\ local a = 0\ for i=1,10000 do\ local a = a + tonumber(tostring(i))\ end\ end"]={ ["off"]="79.316", ["on"]="5.640", }, ["return function()\ local a = 0\ for i=1,100 do\ local a = a + tonumber(tostring(i))\ end\ end"]={ ["off"]="0.703", ["on"]="0.047", }, ["return function()\ local a = 0\ for i=1,1000 do\ local a = a + tonumber(tostring(i))\ end\ end"]={ ["off"]="4.786", ["on"]="0.171", }, ["return function()\ local a = 0\ for i=1,10000 do\ a = a + font.current()\ end\ end"]={ ["off"]="1.417", ["on"]="1.427", }, ["return function()\ local a = 0\ for i=1,10000 do\ a = a + i\ end\ end"]={ ["off"]="0.198", ["on"]="0.041", }, ["return function()\ local a = 0\ for i=1,10000 do\ a = a + math.sin(1/i)\ end\ end"]={ ["off"]="2.206", ["on"]="1.440", }, ["return function()\ local a = 0\ for i=1,10000 do\ local a = a + tonumber(tostring(i))\ end\ end"]={ ["off"]="79.456", ["on"]="5.703", }, ["return function()\ local a = 0\ local p = (1-lpeg.P(\"5\"))^0 * lpeg.P(\"5\")\ for i=1,100 do\ local a = a + (tonumber(lpeg.match(p,tostring(i))) or 0)\ end\ end"]={ ["off"]="0.859", ["on"]="0.843", }, ["return function()\ local a = 0\ local p = (1-lpeg.P(\"5\"))^0 * lpeg.P(\"5\") + lpeg.Cc(0)\ for i=1,100 do\ local a = a + lpeg.match(p,tostring(i))\ end\ end"]={ ["off"]="0.514", ["on"]="0.516", }, }
function MapData.walk_voxels_mock(min, max, fn) local x, y, z, data for x=min.x,max.x do for y=min.y,max.y do for z=min.z,max.z do data = MapData.get_node(vector.new(x,y,z)) fn({x = x, y = y, z = z}, data.name, data.cid) end end end end local mock_node_defs = nil MapData.mock_node_group_cache = { } function MapData.get_node_group_mock(name, group) if MapData.mock_node_group_cache[name] and MapData.mock_node_group_cache[name][group] then return MapData.mock_node_group_cache[name][group] end if not mock_node_defs then mock_node_defs = fixture('node_defs') end local result = mock_node_defs[name].groups[group] or 0 MapData.mock_node_group_cache[name] = MapData.mock_node_group_cache[name] or {} MapData.mock_node_group_cache[name][group] = result return result end MapData.mock_data = { } function MapData.set_node_mock(pos, node) MapData.mock_data[pos_to_int(pos)] = node end function MapData.get_node_mock(pos) local cached = MapData.mock_data[pos_to_int(pos)] if cached then return cached end local height = pos.y -- math.floor(pos.y + math.floor(math.sin(pos.x/2) + math.cos(pos.z/2))) if height > 0 then return { name = "air" } end if height == 0 then return { name = "default:dirt" } end return { name = "default:stone" } end function MapData.get_node_mock_wavy(pos) local cached = MapData.mock_data[pos_to_int(pos)] if cached then return cached end local height = math.floor(pos.y + math.floor(math.sin(pos.x/2) + math.cos(pos.z/2))) if height > 0 then return { name = "air" } end if height == 0 then return { name = "default:dirt" } end return { name = "default:stone" } end function MapData.emerge_area(min,max) -- do nothing end minetest = minetest or { } minetest.registered_nodes = fixture('registered_nodes') -- inject fake map data local generated_blocks = fixture('generated_blocks') for _, args in ipairs(generated_blocks) do MapData.on_generated(args.minp, args.maxp, args.blockseed) end MapData.walk_voxels = MapData.walk_voxels_mock MapData.get_node_group = MapData.get_node_group_mock MapData.get_node = MapData.get_node_mock MapData.set_node = MapData.set_node_mock
Handler = NPCHandler:new() Citizen.CreateThread(function() Handler:startThread(500) end) -- TODO: Better integration with external scripts and animation handler function GetNPC(id) if not Handler:npcExists(id) then return end return Handler.npcs[id]["npc"] end exports("GetNPC", GetNPC) function RegisterNPC(data) if not Handler:npcExists(data.id) then local npc = NPC:new(data.id, data.pedType, data.model, data.position, (type(data.appearance) == "string" and json.decode(data.appearance) or data.appearance), data.animation, data.networked, data.settings, data.flags, data.scenario, data.blip) Handler:addNPC(npc, data.distance) return npc else Handler.npcs[data.id]["npc"]["position"] = data.position return Handler.npcs[data.id]["npc"] end end exports("RegisterNPC", RegisterNPC) function RemoveNPC(id) if not Handler:npcExists(id) then return end Handler:removeNPC(id) end exports("RemoveNPC", RemoveNPC) function DisableNPC(id) if not Handler:npcExists(id) then return end Handler:disableNPC(id) end exports("DisableNPC", DisableNPC) function EnableNPC(id) if not Handler:npcExists(id) then return end Handler:enableNPC(id) end exports("EnableNPC", EnableNPC) function UpdateNPCData(id, key, value) if not Handler:npcExists(id) then return end Handler.npcs[id]["npc"][key] = value end exports("UpdateNPCData", UpdateNPCData) function FindNPCByHash(hash) local found, npc = false for _, data in pairs(Handler.npcs) do if GetHashKey(data.npc.id) == hash then found, npc = true, data.npc break end end return found, npc end AddEventHandler("onResourceStop", function(resourceName) if resourceName ~= GetCurrentResourceName() then return end for _, data in pairs(Handler.npcs) do data["npc"]:delete() end end)
local ignoreSkill = {} --- Gets the base skill from a skill. --- @param skill string The skill entry to check. --- @return string The base skill, if any, otherwise the skill that was passed in. local function GetBaseSkill(skill, match) if skill ~= nil then local checkParent = true if match ~= nil and match ~= "" and not string.find(skill, match) then checkParent = false end if checkParent then local skill = Ext.StatGetAttribute(skill, "Using") if skill ~= nil then return GetBaseSkill(skill, match) end end end return skill end local function GetListeners(skill) local parsingAllTable = false local listeners = SkillListeners[skill] if listeners == nil then listeners = SkillListeners["All"] parsingAllTable = true end if listeners ~= nil then local i = 0 local count = #listeners return function () i = i + 1 if not parsingAllTable and i == count+1 then if SkillListeners["All"] ~= nil then listeners = SkillListeners["All"] i = 1 count = #listeners parsingAllTable = true end end if i <= count then return listeners[i] end end end return function() end end ---A temporary table used to store data for a skill, including targets / skill information. ---@type table<string,SkillEventData> local skillEventDataTable = {} ---@return SkillEventData local function GetCharacterSkillData(skill, uuid, createIfMissing, skillType, skillAbility) local data = nil local skillDataHolder = skillEventDataTable[skill] if skillDataHolder ~= nil then data = skillDataHolder[uuid] elseif createIfMissing == true then skillDataHolder = {} skillEventDataTable[skill] = skillDataHolder end if data == nil and createIfMissing == true then data = Classes.SkillEventData:Create(uuid, skill, skillType, skillAbility) skillDataHolder[uuid] = data end return data end local function RemoveCharacterSkillData(uuid, skill) if skill ~= nil then local skillDataHolder = skillEventDataTable[skill] if skillDataHolder ~= nil then skillDataHolder[uuid] = nil end else -- Remove everything for this character for skill,data in pairs(skillEventDataTable) do if data[uuid] ~= nil then data[uuid] = nil end end end end function StoreSkillEventData(char, skill, skillType, skillAbility, ...) local listeners = SkillListeners[skill] if listeners ~= nil or SkillListeners["All"] ~= nil then local uuid = StringHelpers.GetUUID(char) local eventParams = {...} ---@type SkillEventData local data = GetCharacterSkillData(skill, uuid, true, skillType, skillAbility) if eventParams ~= nil then if #eventParams == 1 and not StringHelpers.IsNullOrEmpty(eventParams[1]) then data:AddTargetObject(eventParams[1]) elseif #eventParams >= 3 then -- Position local x,y,z = table.unpack(eventParams) if x ~= nil and y ~= nil and z ~= nil then data:AddTargetPosition(x,y,z) end end end end end -- Example: Finding the base skill of an enemy skill -- GetBaseSkill(skill, "Enemy") function OnSkillPreparing(char, skillprototype) local skill = string.gsub(skillprototype, "_%-?%d+$", "") if CharacterIsControlled(char) == 0 then Osi.LeaderLib_LuaSkillListeners_IgnorePrototype(char, skillprototype, skill) end for callback in GetListeners(skill) do --PrintDebug("[LeaderLib_SkillListeners.lua:OnSkillPreparing] char(",char,") skillprototype(",skillprototype,") skill(",skill,")") local status,err = xpcall(callback, debug.traceback, skill, StringHelpers.GetUUID(char), SKILL_STATE.PREPARE) if not status then Ext.PrintError("[LeaderLib_SkillListeners] Error invoking function:\n", err) end end -- Clear previous data for this character in case SkillCast never fired (interrupted) RemoveCharacterSkillData(StringHelpers.GetUUID(char)) end -- Fires when CharacterUsedSkill fires. This happens after all the target events. function OnSkillUsed(char, skill, ...) if skill ~= nil then Osi.LeaderLib_LuaSkillListeners_RemoveIgnoredPrototype(char, skill) else Osi.LeaderLib_LuaSkillListeners_RemoveIgnoredPrototype(char) end local uuid = StringHelpers.GetUUID(char) local data = GetCharacterSkillData(skill, uuid) if data ~= nil then local status,err = nil,nil for callback in GetListeners(skill) do if Vars.DebugMode then --PrintDebug("[LeaderLib_SkillListeners.lua:OnSkillUsed] char(",char,") skill(",skill,") data(",data:ToString(),")") --PrintDebug("params(",Ext.JsonStringify({...}),")") end status,err = xpcall(callback, debug.traceback, skill, uuid, SKILL_STATE.USED, data) if not status then Ext.PrintError("[LeaderLib_SkillListeners] Error invoking function:\n", err) end end end end function OnSkillCast(char, skill, ...) local uuid = StringHelpers.GetUUID(char) ---@type SkillEventData local data = GetCharacterSkillData(skill, uuid) if data ~= nil then local status,err = nil,nil for callback in GetListeners(skill) do if Vars.DebugMode then --PrintDebug("[LeaderLib_SkillListeners.lua:OnSkillCast] char(",char,") skill(",skill,") data(",data:ToString(),")") --PrintDebug("params(",Ext.JsonStringify({...}),")") end status,err = xpcall(callback, debug.traceback, skill, uuid, SKILL_STATE.CAST, data) if not status then Ext.PrintError("[LeaderLib_SkillListeners] Error invoking function:\n", err) end end data:Clear() RemoveCharacterSkillData(uuid, skill) end end local function RunSkillListenersForSkillEvent(source, skill, data, listeners, state) local length = #listeners if length > 0 then for i=1,length do local callback = listeners[i] local status,err = xpcall(callback, debug.traceback, skill, source, state, data) if not status then Ext.PrintError("[LeaderLib_SkillListeners] Error invoking function:\n", err) end end end end local function IgnoreHitTarget(target) if IsTagged(target, "MovingObject") == 1 then return true elseif ObjectIsCharacter(target) == 1 and Osi.LeaderLib_Helper_QRY_IgnoreCharacter(target) == true then return true elseif ObjectIsItem(target) == 1 and Osi.LeaderLib_Helper_QRY_IgnoreItem(target) == true then return true end return false end ---@param source string ---@param skill string ---@param target string ---@param handle integer ---@param damage integer function OnSkillHit(source, skill, target, handle, damage) if skill ~= "" and skill ~= nil and not IgnoreHitTarget(target) then ---@type HitData local data = Classes.HitData:Create(target, source, damage, handle, skill) local listeners = SkillListeners[skill] if listeners ~= nil then RunSkillListenersForSkillEvent(source, skill, data, listeners, SKILL_STATE.HIT) end listeners = Listeners.OnSkillHit if listeners ~= nil then RunSkillListenersForSkillEvent(source, skill, data, listeners, SKILL_STATE.HIT) end if Features.ApplyBonusWeaponStatuses == true then local canApplyStatuses = target ~= nil and Ext.StatGetAttribute(skill, "UseWeaponProperties") == "Yes" if canApplyStatuses then ---@type EsvCharacter local character = Ext.GetCharacter(source) for i,status in pairs(character:GetStatuses()) do local potion = nil if type(status) ~= "string" and status.StatusId ~= nil then status = status.StatusId end if Data.EngineStatus[status] ~= true then potion = Ext.StatGetAttribute(status, "StatsId") if potion ~= nil and potion ~= "" then local bonusWeapon = Ext.StatGetAttribute(potion, "BonusWeapon") if bonusWeapon ~= nil and bonusWeapon ~= "" then local extraProps = Ext.StatGetAttribute(bonusWeapon, "ExtraProperties") if extraProps ~= nil then GameHelpers.ApplyProperties(target, source, extraProps) end end end end end end end end end ---@param projectile EsvProjectile ---@param hitObject EsvGameObject ---@param position number[] Ext.RegisterListener("ProjectileHit", function (projectile, hitObject, position) if not StringHelpers.IsNullOrEmpty(projectile.SkillId) then local skill = GetSkillEntryName(projectile.SkillId) if projectile.CasterHandle ~= nil then local object = Ext.GetGameObject(projectile.CasterHandle) local uuid = (object ~= nil and object.MyGuid) or "" local target = hitObject ~= nil and hitObject.MyGuid or "" ---@type ProjectileHitData local data = Classes.ProjectileHitData:Create(target, uuid, projectile, position, skill) local listeners = SkillListeners[skill] if listeners ~= nil then RunSkillListenersForSkillEvent(uuid, skill, data, listeners, SKILL_STATE.PROJECTILEHIT) end listeners = Listeners.OnSkillHit if listeners ~= nil then RunSkillListenersForSkillEvent(uuid, skill, data, listeners, SKILL_STATE.PROJECTILEHIT) end end end end) -- Ext.RegisterOsirisListener("NRD_OnActionStateEnter", 2, "after", function(char, state) -- if state == "PrepareSkill" then -- local skillprototype = NRD_ActionStateGetString(char, "SkillId") -- if skillprototype ~= nil and skillprototype ~= "" then -- OnSkillPreparing(char, skillprototype) -- end -- end -- end) -- Ext.RegisterOsirisListener("CharacterUsedSkillOnTarget", 5, "after", function(char, target, skill, skilltype, element) -- StoreSkillEventData(char, skill, skilltype, element, target) -- end) -- Ext.RegisterOsirisListener("CharacterUsedSkillAtPosition", 7, "after", function(char, x, y, z, skill, skilltype, element) -- StoreSkillEventData(char, skill, skilltype, element, x, y, z) -- end) -- Ext.RegisterOsirisListener("CharacterUsedSkillOnZoneWithTarget", 5, "after", function(char, target, skill, skilltype, element) -- StoreSkillEventData(char, skill, skilltype, element, target) -- end) -- Ext.RegisterOsirisListener("CharacterUsedSkill", 4, "after", function(char, skill, skilltype, element) -- OnSkillUsed(char, skill, skilltype, element) -- end) -- Ext.RegisterOsirisListener("SkillCast", 4, "after", function(char, skill, skilltype, element) -- SkillCast(char, skill, skilltype, element) -- end)
--Increase cost of resin->rubber smelting to encourage use of angels rubber synthesis seablock.lib.substingredient('bob-rubber', 'resin', nil, 4) -- Merge tech Rubbers into Rubber bobmods.lib.tech.remove_recipe_unlock('rubbers', 'solid-rubber') bobmods.lib.tech.replace_prerequisite('rubber', 'rubbers', 'resin-1') bobmods.lib.tech.replace_prerequisite('bio-arboretum-desert-1', 'rubbers', 'rubber') if mods['bobpower'] then bobmods.lib.tech.add_prerequisite('electric-pole-3', 'rubber') bobmods.lib.tech.add_prerequisite('electric-substation-3', 'rubber') end seablock.lib.add_recipe_unlock('rubber', 'bob-rubber', 2) seablock.lib.moveeffect('insulated-cable', 'electronics', 'rubber') seablock.lib.hide_technology('rubbers') bobmods.lib.tech.remove_recipe_unlock('bio-arboretum-desert-1', 'solid-rubber') -- Circuit network wires should not require rubber data.raw.recipe['green-wire'].ingredients = {{ "electronic-circuit", 1 }, { "copper-cable", 1 }} data.raw.recipe['red-wire'].ingredients = {{ "electronic-circuit", 1 }, { "copper-cable", 1 }}
local csv = {} math.randomseed(os.time()) --AUX function shuffle(array) -- fisher-yates local output = { } local random = math.random for index = 1, #array do local offset = index - 1 local value = array[index] local randomIndex = offset*random() local flooredIndex = randomIndex - randomIndex%1 if flooredIndex == offset then output[#output + 1] = value else output[#output + 1] = output[flooredIndex + 1] output[flooredIndex + 1] = value end end return output end -- read csv function csv.readfile(arq) local file = io.open(arq, "r"); local arr = {} for line in file:lines() do table.insert (arr, line); end return arr end -- line to array function csv.parseCSVLine (line,sep) local res = {} local pos = 1 sep = sep or ',' while true do local c = string.sub(line,pos,pos) if (c == "") then break end if (c == '"') then -- quoted value (ignore separator within) local txt = "" repeat local startp,endp = string.find(line,'^%b""',pos) txt = txt..string.sub(line,startp+1,endp-1) pos = endp + 1 c = string.sub(line,pos,pos) if (c == '"') then txt = txt..'"' end -- check first char AFTER quoted string, if it is another -- quoted string without separator, then append it -- this is the way to "escape" the quote char in a quote. example: -- value1,"blub""blip""boing",value3 will result in blub"blip"boing for the middle until (c ~= '"') table.insert(res,txt) assert(c == sep or c == "") pos = pos + 1 else -- no quotes used, just look for the first separator local startp,endp = string.find(line,sep,pos) if (startp) then table.insert(res,string.sub(line,pos,startp-1)) pos = endp + 1 else -- no separator found -> use rest of string and terminate table.insert(res,string.sub(line,pos)) break end end end return res end --Export the csv to train function csv.totrain(arq,sep) sep = sep or "," --Load the file local file = csv.readfile(arq) --Parse data local data_parse = {} for i=2, #file do table.insert(data_parse,csv.parseCSVLine(file[i],sep)) end -- shuffle the data local data = shuffle(data_parse) return data end return csv
require("common/commonScene") require("hall/recharge/rechargeScene") require("hall/recharge/rechargeController") local recharge = require(RechargeViewPath .. "recharge") RechargeState = class(CommonState) RechargeState.ctor = function(self) self.m_controller = nil; end RechargeState.getController = function(self) return self.m_controller; end RechargeState.load = function(self) CommonState.load(self); self.m_controller = new(RechargeController,self,RechargeScene,recharge); return true; end RechargeState.resume = function(self) CommonState.resume(self); end RechargeState.pause =function(self) CommonState.pause(self); end RechargeState.unload = function(self) CommonState.unload(self); delete(self.m_controller); self.m_controller = nil; end RechargeState.dtor = function(self) end
local Dictionary = script.Parent local Llama = Dictionary.Parent local t = require(Llama.t) local validate = t.tuple(t.table, t.any) local function has(dictionary, key) assert(validate(dictionary, key)) return dictionary[key] ~= nil end return has
--[[ --MIT License -- --Copyright (c) 2019 PapyElGringo --Copyright (c) 2019 Tom Meyers -- --Permission is hereby granted, free of charge, to any person obtaining a copy --of this software and associated documentation files (the "Software"), to deal --in the Software without restriction, including without limitation the rights --to use, copy, modify, merge, publish, distribute, sublicense, and/or sell --copies of the Software, and to permit persons to whom the Software is --furnished to do so, subject to the following conditions: -- --The above copyright notice and this permission notice shall be included in all --copies or substantial portions of the Software. -- --THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR --IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, --FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE --AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER --LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, --OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE --SOFTWARE. ]] local naughty = require('naughty') local beautiful = require('beautiful') local gears = require('gears') local dpi = require('beautiful').xresources.apply_dpi -- Naughty presets naughty.config.padding = 8 naughty.config.spacing = 8 naughty.config.defaults.timeout = 5 naughty.config.defaults.screen = 1 naughty.config.defaults.position = 'top_right' naughty.config.defaults.margin = dpi(16) naughty.config.defaults.ontop = true naughty.config.defaults.font = 'Roboto Regular 10' naughty.config.defaults.icon = nil naughty.config.defaults.icon_size = dpi(32) naughty.config.defaults.shape = function(cr, w, h) gears.shape.rounded_rect(cr, w, h, dpi(12)) end naughty.config.defaults.border_width = 0 naughty.config.defaults.hover_timeout = nil -- Error handling if _G.awesome.startup_errors then naughty.notify( { preset = naughty.config.presets.critical, title = 'Oops, there were errors during startup!', text = _G.awesome.startup_errors } ) end do local in_error = false _G.awesome.connect_signal( 'debug::error', function(err) if in_error then return end in_error = true naughty.notify( { preset = naughty.config.presets.critical, title = 'Oops, an error happened!', text = tostring(err) } ) in_error = false end ) end function log_this(title, txt) naughty.notify( { title = 'log: ' .. title, text = txt } ) end
--[[ Project: SA Memory (Available from https://blast.hk/) Developers: LUCHARE, FYP Special thanks: plugin-sdk (https://github.com/DK22Pac/plugin-sdk) for the structures and addresses. Copyright (c) 2018 BlastHack. ]] local shared = require 'SAMemory.shared' shared.require 'CEntity' shared.require 'CAESound' shared.ffi.cdef[[ typedef struct CAEAudioEntity { void **vptr; CEntity *pEntity; CAESound tempSound; } CAEAudioEntity; ]] shared.validate_size('CAEAudioEntity', 0x7C)
-- This file is part of the Teal Pages project -- Copyright (c) 2020 Felipe Daragon -- License: MIT function handle_tlp(r) local tlp = require "tlp" r.content_type = "text/html" puts = function(s) r:write(s) end print = function(s) r:write(s) end tlp.setoutfunc "puts" tlp.include(r.filename) end
--[[ LUA PARAMETERS ]] useDatabankValues = false --export: if checked and if values were saved in databank, parmaters will be loaded from the databank, if not, following ones will be used containerMonitoringPrefix_screen1 = "MONIT_" --export: the prefix used to enable container monitoring and display on the 1st screen containerMonitoringPrefix_screen2 = "s2_" --export: the prefix used to enable container monitoring and display on the 2nd screen containerMonitoringPrefix_screen3 = "s3_" --export: the prefix used to enable container monitoring and display on the 3rd screen containerMonitoringPrefix_screen4 = "s4_" --export: the prefix used to enable container monitoring and display on the 4th screen containerMonitoringPrefix_screen5 = "s5_" --export: the prefix used to enable container monitoring and display on the 5th screen containerMonitoringPrefix_screen6 = "s6_" --export: the prefix used to enable container monitoring and display on the 6th screen containerMonitoringPrefix_screen7 = "s7_" --export: the prefix used to enable container monitoring and display on the 7th screen containerMonitoringPrefix_screen8 = "s8_" --export: the prefix used to enable container monitoring and display on the 8th screen containerMonitoringPrefix_screen9 = "s9_" --export: the prefix used to enable container monitoring and display on the 9th screen screenTitle1 = "Pures" --export: the title display on the 1st screen, not displayed if empty or equal to "-" screenTitle2 = "Alloys" --export: the title display on the 2nd screen, not displayed if empty or equal to "-" screenTitle3 = "Ores" --export: the title display on the 3rd screen, not displayed if empty or equal to "-" screenTitle4 = "title screen 4" --export: the title display on the 4th screen, not displayed if empty or equal to "-" screenTitle5 = "title screen 5" --export: the title display on the 5th screen, not displayed if empty or equal to "-" screenTitle6 = "title screen 6" --export: the title display on the 6th screen, not displayed if empty or equal to "-" screenTitle7 = "title screen 7" --export: the title display on the 7th screen, not displayed if empty or equal to "-" screenTitle8 = "title screen 8" --export: the title display on the 8th screen, not displayed if empty or equal to "-" screenTitle9 = "title screen 9" --export: the title display on the 9th screen, not displayed if empty or equal to "-" container_proficiency_lvl = 3 --export: Talent level for Container Proficiency container_optimization_lvl = 0 --export: Talent level for Container Optimization container_fill_red_level = 10 --export: The percent fill below gauge will be red container_fill_yellow_level = 50 --export: The percent fill below gauge will be yellow groupByItemName = true --export: if enabled, this will group all entries with the same item name QuantityRoundedDecimals = 2 --export: maximum of decimals displayed for the quantity value PercentRoundedDecimals = 2 --export: maximum of decimals displayed for the percent fill value fontSize = 2 --export: the size of the text for all the screen borderColor = "orange" --export: the color of the table border verticalMode = false --export: enable to use on a vertical screen (not yet ready) showGreen = true --export: if not enable, line with green gauge will be hidden showYellow = true --export: if not enable, line with yellow gauge will be hidden showRed = true --export: if not enable, line with red gauge will be hidden maxAmountOfElementsLoadedByTick = 5000 --export: the maximum number of element loaded by tick of the coroutine on script startup maxAmountOfElementsRefreshedByTick = 200 --export: the maximum number of element refreshed by tick of the coroutine when refreshing values showContainerNameColumn = false --export: show or not the column "Container Name" showContainerCapacityColumn = false --export: show or not the column "Container Total Capacity" --[[ INIT ]] system.print("-----------------------------------") system.print("DU-Storage-Monitoring version 2.3.0") system.print("-----------------------------------") options = {} options.containerMonitoringPrefix_screen1 = containerMonitoringPrefix_screen1 options.containerMonitoringPrefix_screen2 = containerMonitoringPrefix_screen2 options.containerMonitoringPrefix_screen3 = containerMonitoringPrefix_screen3 options.containerMonitoringPrefix_screen4 = containerMonitoringPrefix_screen4 options.containerMonitoringPrefix_screen5 = containerMonitoringPrefix_screen5 options.containerMonitoringPrefix_screen6 = containerMonitoringPrefix_screen6 options.containerMonitoringPrefix_screen7 = containerMonitoringPrefix_screen7 options.containerMonitoringPrefix_screen8 = containerMonitoringPrefix_screen8 options.containerMonitoringPrefix_screen9 = containerMonitoringPrefix_screen9 options.screenTitle1 = screenTitle1 options.screenTitle2 = screenTitle2 options.screenTitle3 = screenTitle3 options.screenTitle4 = screenTitle4 options.screenTitle5 = screenTitle5 options.screenTitle6 = screenTitle6 options.screenTitle7 = screenTitle7 options.screenTitle8 = screenTitle8 options.screenTitle9 = screenTitle9 options.container_proficiency_lvl = container_proficiency_lvl options.container_optimization_lvl = container_optimization_lvl options.container_fill_red_level = container_fill_red_level options.container_fill_yellow_level = container_fill_yellow_level options.groupByItemName = groupByItemName options.QuantityRoundedDecimals = QuantityRoundedDecimals options.PercentRoundedDecimals = PercentRoundedDecimals options.fontSize = fontSize options.borderColor = borderColor options.verticalMode = verticalMode options.showGreen = showGreen options.showYellow = showYellow options.showRed = showRed options.maxAmountOfElementsLoadedByTick = maxAmountOfElementsLoadedByTick options.maxAmountOfElementsRefreshedByTick = maxAmountOfElementsRefreshedByTick options.showContainerNameColumn = showContainerNameColumn options.showContainerCapacityColumn = showContainerCapacityColumn core = nil databank = nil screens = {} for slot_name, slot in pairs(unit) do if type(slot) == "table" and type(slot.export) == "table" and slot.getElementClass then if slot.getElementClass():lower():find("coreunit") then core = slot end if slot.getElementClass():lower() == 'screenunit' then slot.slotname = slot_name table.insert(screens,slot) end if slot.getElementClass():lower() == 'databankunit' then databank = slot end end end if #screens == 0 then system.print("No Screen Detected") else --sorting screens by slotname to be sure the display is not changing table.sort(screens, function(a,b) return a.slotname < b.slotname end) local plural = "" if #screens > 1 then plural = "s" end system.print(#screens .. " screen" .. plural .. " Connected") end if core == nil then system.print("No Core Detected") else system.print("Core Connected") end if databank == nil then system.print("No Databank Detected") else system.print("Databank Connected") if (databank.hasKey("options")) and (useDatabankValues == true) then local db_options = json.decode(databank.getStringValue("options")) for key, value in pairs(options) do if db_options[key] then options[key] = db_options[key] end end system.print("Options Loaded From Databank") else system.print("Options Loaded From LUA Parameters") end end prefixes = { options.containerMonitoringPrefix_screen1, options.containerMonitoringPrefix_screen2, options.containerMonitoringPrefix_screen3, options.containerMonitoringPrefix_screen4, options.containerMonitoringPrefix_screen5, options.containerMonitoringPrefix_screen6, options.containerMonitoringPrefix_screen7, options.containerMonitoringPrefix_screen8, options.containerMonitoringPrefix_screen9 } titles = { options.screenTitle1, options.screenTitle2, options.screenTitle3, options.screenTitle4, options.screenTitle5, options.screenTitle6, options.screenTitle7, options.screenTitle8, options.screenTitle9 } elementsIdList = {} if core ~= nil then elementsIdList = core.getElementIdList() end storageIdList= {} initIndex = 0 initFinished = false --Nested Coroutines by Jericho coroutinesTable = {} --all functions here will become a coroutine MyCoroutines = { function() if not initFinished then system.print("Loading contructs elements (" .. #elementsIdList .. " elements detected)") for i = 1, #elementsIdList, 1 do initIndex = i local id = elementsIdList[i] local elementType = core.getElementTypeById(id):lower() if elementType:lower():find("container") then table.insert(storageIdList, id) end if (i%options.maxAmountOfElementsLoadedByTick) == 0 then system.print(i .. ' elements scanned on ' .. #elementsIdList .. ' with ' .. #storageIdList .. " identified") coroutine.yield(coroutinesTable[1]) end end if initIndex == #elementsIdList then system.print(#elementsIdList .. " scanned with " .. #storageIdList .. " storage elements identified") initFinished = true end end end, function() local storage_elements = {} for elemindex,id in ipairs(storageIdList) do local elementType = core.getElementTypeById(id) if elementType:lower():find("container") then local elementName = core.getElementNameById(id) if elementName:lower():find(prefixes[1]:lower()) or elementName:lower():find(prefixes[2]:lower()) or elementName:lower():find(prefixes[3]:lower()) or elementName:lower():find(prefixes[4]:lower()) or elementName:lower():find(prefixes[5]:lower()) or elementName:lower():find(prefixes[6]:lower()) or elementName:lower():find(prefixes[7]:lower()) or elementName:lower():find(prefixes[8]:lower()) or elementName:lower():find(prefixes[9]:lower()) then local container = {} local splitted = strSplit(elementName, '_') local name = splitted[2] local ingredient = getIngredient(cleanName(name)) local container_size = "XS" local container_amount = 1 local container_empty_mass = 0 local container_volume = 0 local contentQuantity = 0 local percent_fill = 0 if not elementType:lower():find("hub") then local containerMaxHP = core.getElementMaxHitPointsById(id) if containerMaxHP > 68000 then container_size = "XXL" container_empty_mass = getIngredient("Expanded Container XL").mass container_volume = 512000 * (options.container_proficiency_lvl * 0.1) + 512000 elseif containerMaxHP > 33000 then container_size = "XL" container_empty_mass = getIngredient("Container XL").mass container_volume = 256000 * (options.container_proficiency_lvl * 0.1) + 256000 elseif containerMaxHP > 17000 then container_size = "L" container_empty_mass = getIngredient("Container L").mass container_volume = 128000 * (options.container_proficiency_lvl * 0.1) + 128000 elseif containerMaxHP > 7900 then container_size = "M" container_empty_mass = getIngredient("Container M").mass container_volume = 64000 * (options.container_proficiency_lvl * 0.1) + 64000 elseif containerMaxHP > 900 then container_size = "S" container_empty_mass = getIngredient("Container S").mass container_volume = 8000 * (options.container_proficiency_lvl * 0.1) + 8000 else container_size = "XS" container_empty_mass = getIngredient("Container XS").mass container_volume = 1000 * (options.container_proficiency_lvl * 0.1) + 1000 end else if splitted[3] then container_size = splitted[3] end if splitted[4] then container_amount = splitted[4] end local volume = 0 if container_size:lower() == "xxl" then volume = 512000 elseif container_size:lower() == "xl" then volume = 256000 elseif container_size:lower() == "l" then volume = 128000 elseif container_size:lower() == "m" then volume = 64000 elseif container_size:lower() == "s" then volume = 8000 elseif container_size:lower() == "xs" then volume = 1000 end container_volume = volume * (options.container_proficiency_lvl * 0.1) + volume container_volume = container_volume * tonumber(container_amount) container_empty_mass = getIngredient("Container Hub").mass end local totalMass = core.getElementMassById(id) local contentMassKg = totalMass - container_empty_mass container.id = id container.realName = elementName container.prefix = splitted[1] .. "_" container.name = name container.ingredient = ingredient container.quantity = contentMassKg / (ingredient.mass - (ingredient.mass * (options.container_optimization_lvl * 0.05))) container.volume = container_volume container.percent = utils.round((ingredient.volume * container.quantity) * 100 / container_volume) if ingredient.name == "unknown" then container.percent = 0 end table.insert(storage_elements, container) end end if (elemindex%options.maxAmountOfElementsRefreshedByTick) == 0 then coroutine.yield(coroutinesTable[2]) end end -- group by name and screen local groupped = {} if groupByItemName then for _,v in pairs(storage_elements) do local prefix = v.prefix:lower() if groupped[prefix .. cleanName(v.ingredient.name)] then groupped[prefix .. cleanName(v.ingredient.name)].quantity = groupped[prefix .. cleanName(v.ingredient.name)].quantity + v.quantity groupped[prefix .. cleanName(v.ingredient.name)].volume = groupped[prefix .. cleanName(v.ingredient.name)].volume + v.volume groupped[prefix .. cleanName(v.ingredient.name)].percent = (v.ingredient.volume * groupped[prefix .. cleanName(v.ingredient.name)].quantity) * 100 / groupped[prefix .. cleanName(v.ingredient.name)].volume else groupped[prefix .. cleanName(v.ingredient.name)] = v end end else groupped = storage_elements end -- sorting by tier local tiers = {} tiers[1] = {} --tier 0 (thx to Belorion#3127 for pointing Oxygen and Hydrogen are Tier 0 and not 1) tiers[2] = {} --tier 1 tiers[3] = {} --tier 2 tiers[4] = {} --tier 3 tiers[5] = {} --tier 4 tiers[6] = {} --tier 5 for _,v in pairs(groupped) do table.insert(tiers[v.ingredient.tier+1],v) end -- sorting by name for k,v in pairs(tiers) do table.sort(tiers[k], function(a,b) return a.ingredient.name:lower() < b.ingredient.name:lower() end) end if #screens > 0 then local widthUnit = "vw" local heightUnit = "vh" if options.verticalMode then widthUnit = "vh" heightUnit = "vw" end local css = [[ <style> * { text-shadow: 1px 0 0 #000, -1px 0 0 #000, 0 1px 0 #000, 0 -1px 0 #000, 1px 1px #000, -1px -1px 0 #000, 1px -1px 0 #000, -1px 1px 0 #000; } ]] if options.verticalMode then css = css .. [[ .container{ width:100]] .. widthUnit .. [[; transform:rotate(-90deg); transform-origin:0% 0%; margin-top:100vh; } ]] end css = css .. [[ .row { border-bottom:2px solid ]] .. options.borderColor .. [[; font-size: ]] .. tostring(options.fontSize) .. [[vw; width:100]] .. widthUnit .. [[; } </style> ]] for index, screen in pairs(screens) do local prefix = prefixes[index] local title = titles[index] local html = [[<div class="container">]] if (title:len() > 0) and (title ~= "-") then html = html .. [[ <div class="row"> <div class="col text-center" style="font-size:5vw;"> ]] .. title .. [[ </div> </div> ]] end html = html .. [[ <div class="row"> <div class="col-1 text-center">Tier</div> ]] if options.showContainerNameColumn then html = html .. [[<div class="col">Container Name</div>]] end if options.showContainerCapacityColumn then html = html .. [[<div class="col">Capacity</div>]] end html = html .. [[ <div class="col">Item Name</div> <div class="col">Amount</div> <div class="col-2 text-center">Percent Fill</div> </div> ]] for tier_k,tier in pairs(tiers) do for _,container in pairs(tier) do if container.prefix:lower():find(prefix:lower()) then local gauge_color_class = "bg-success" local text_color_class = "text-success" local show = showGreen if container.percent < options.container_fill_red_level then gauge_color_class = "bg-danger" text_color_class = "text-danger" show = showRed elseif container.percent < options.container_fill_yellow_level then gauge_color_class = "bg-warning" text_color_class = "text-warning" show = showYellow end if show == true then html = html .. [[ <div class="row ]] .. text_color_class ..[["> <div class="]] .. gauge_color_class .. [[" style="width:]] .. container.percent .. [[%;position:absolute;height:100%;">&nbsp;</div> <div class="col-1 text-center">]] .. tier_k-1 .. [[</div> ]] if options.showContainerNameColumn then html = html .. [[<div class="col">]] .. container.realName .. "</div>" end if options.showContainerCapacityColumn then html = html .. [[<div class="col">]] .. format_number(utils.round(container.volume)) .. "</div>" end html = html .. [[ <div class="col">]] .. container.ingredient.name .. [[</div> <div class="col">]] .. format_number(utils.round(container.quantity * (10 ^ options.QuantityRoundedDecimals)) / (10 ^ options.QuantityRoundedDecimals)) .. [[</div> <div class="col-2 text-center">]] .. format_number(utils.round(container.percent * (10 ^ options.PercentRoundedDecimals)) / (10 ^ options.PercentRoundedDecimals)) .. [[%</div> </div> ]] end end end end html = html .. [[</div>]] screen.setHTML(css .. bootstrap_css .. html) end end end } function initCoroutines() for _,f in pairs(MyCoroutines) do local co = coroutine.create(f) table.insert(coroutinesTable, co) end end initCoroutines() runCoroutines = function() for i,co in ipairs(coroutinesTable) do if coroutine.status(co) == "dead" then coroutinesTable[i] = coroutine.create(MyCoroutines[i]) end if coroutine.status(co) == "suspended" then assert(coroutine.resume(co)) end end end MainCoroutine = coroutine.create(runCoroutines)
local M = { base = "assets", } -- TODO: watch file. uv_fs_event_start local cache = {} M.get = function(path) local asset = cache[path] if asset then return asset end local r = io.open(M.base .. "/" .. path, "rb") local src = r:read "*a" r:close() cache[path] = src return src end return M
--lj2curl.lua local ffi = require("ffi") local bit = require("bit") local lshift, rshift, bor, band = bit.lshift, bit.rshift, bit.bor, bit.band local Lib_curl = require("curl_ffi") local function Lib_curl_cleanup(lib) print("Lib_curl_cleanup()") Lib_curl.curl_global_cleanup(); end if Lib_curl then local flags = ffi.C.CURL_GLOBAL_DEFAULT; -- global_init(); must be called once per application lifetime Lib_curl.curl_global_init(flags); else return false; end C = { LIBCURL_COPYRIGHT ="1996 - 2015 Daniel Stenberg, <[email protected]>."; LIBCURL_VERSION ="7.46.0-DEV"; -- the current binding is built on this version LIBCURL_VERSION_MAJOR = 7; LIBCURL_VERSION_MINOR = 46; LIBCURL_VERSION_PATCH = 0; LIBCURL_VERSION_NUM = 0x072E00; } local function CURL_VERSION_BITS(x,y,z) return bor(lshift(x,16),lshift(y,8),z) end local function CURL_AT_LEAST_VERSION(x,y,z) return C.LIBCURL_VERSION_NUM >= CURL_VERSION_BITS(x, y, z) end local exports = {} setmetatable(exports, { __index = function(self, key) local value = nil; local success = false; -- try looking in the library for a function success, value = pcall(function() return Lib_curl[key] end) if success then rawset(self, key, value); return value; end -- try looking in the ffi.C namespace, for constants -- and enums success, value = pcall(function() return ffi.C[key] end) --print("looking for constant/enum: ", key, success, value) if success then rawset(self, key, value); return value; end -- Or maybe it's a type success, value = pcall(function() return ffi.typeof(key) end) if success then rawset(self, key, value); return value; end return nil; end, }) return exports;
-- [以下实例定义了函数 max(),参数为 num1, num2,用于比较两值的大小,并返回最大值] function max(num1, num2) local result = 0 if (num1 > num2) then result = num1 else result = num2 end return result end -- [Call] print("Max: ", max(10,4)) print("Max: ", max(5,6)) -- [Lua 中我们可以将函数作为参数传递给函数,如下实例] myPrint = function(param) print("这是打印函数 ##", param, " ##" ) end function add(num1, num2, functionPrint) local result = num1 + num2 functionPrint(result) end myPrint(10) add(2, 5, myPrint) -- [多返回值] function maximum(a) local mi = 1 -- 最大u索引 local m = a[mi] -- 最大值 for i,v in ipairs(a) do if v > v then mi = i m = v end end return m, mi end print(maximum({8, 10, 23, 12, 5})) -- [可变参数] -- [Lua 函数可以接受可变数目的参数,和 C 语言类似,在函数参数列表中使用三点 ... 表示函数有可变的参数。] function addition(...) local s = 0 for i, v in ipairs{...} do s = s + v end return s end print(add(3, 4, 5, 6, 7)) -- [我们也可以通过 select("#",...) 来获取可变参数的数量:] function average(...) local result = 0 local arg = {...} for i,v in ipairs(arg) do result = result + v end print("总共传入 " .. select("#", ...) .. "个数") return result/select("#", ...) end print("平均值为: ", average(10, 5, 3, 4, 5, 6 )) -- [有时候我们可能需要几个固定参数加上可变参数,固定参数必须放在变长参数之前:] function fwrite(fmt, ...) --> 固定参数fmt return io.write(string.format(fmt, ...)) end fwrite("runoob\n") --> fmt = "runoob", 没有变长参数 fwrite("%d%d\n",1,2) --> fmt = "%d%d",变长参数为1,2
local mod = DBM:NewMod(2349, "DBM-EternalPalace", nil, 1179) local L = mod:GetLocalizedStrings() mod:SetRevision("20190712224311") mod:SetCreatureID(150859) mod:SetEncounterID(2293) mod:SetZone() mod:SetUsedIcons(1, 2, 3) --mod:SetHotfixNoticeRev(16950) --mod:SetMinSyncRevision(16950) --mod.respawnTime = 29 mod:RegisterCombat("combat") mod:RegisterEventsInCombat( "SPELL_CAST_START 301141 292963 296257 303978 301068 303543 302593 296018 304733 296078", "SPELL_CAST_SUCCESS 292963 302503 293509 303543 296018 302504 295444 294515 299708", "SPELL_SUMMON 300732", "SPELL_AURA_APPLIED 292971 292981 295480 300133 292963 302503 293509 295327 303971 296078 303543 296018 302504 300584", "SPELL_AURA_APPLIED_DOSE 292971", "SPELL_AURA_REMOVED 292971 292963 293509 303971 296078 303543 296018", "SPELL_AURA_REMOVED_DOSE 292971", -- "SPELL_PERIODIC_DAMAGE", -- "SPELL_PERIODIC_MISSED", "UNIT_DIED", "CHAT_MSG_RAID_BOSS_EMOTE", "UNIT_SPELLCAST_SUCCEEDED boss1" ) --TODO, https://ptr.wowhead.com/spell=300635/gathering-nightmare track via nameplate number of stacks --TODO, infoframe detecting number of players in each realm, and showing realm player is in? --TODO, dark pulse absorb shield on custom infoframe --TODO, warning filters/timer fades for images/split on mythic stage 4? --TODO, void slam, who does it target? random or the tank? if random, can we target scan it? --TODO, pause/resume (or reset) timers for boss shielding/split phase in stage 4 mythic? --[[ (ability.id = 301141 or ability.id = 303543 or ability.id = 296018 or ability.id = 292963 or ability.id = 296257 or ability.id = 304733 or ability.id = 303978 or ability.id = 301068 or ability.id = 302593 or ability.id = 296078) and type = "begincast" or (ability.id = 292963 or ability.id = 302503 or ability.id = 296018 or ability.id = 302504 or ability.id = 303543 or ability.id = 295444 or ability.id = 294515 or ability.id = 299708) and type = "cast" or (ability.id = 300584 or ability.id = 293509) and type = "applydebuff" --]] local warnPhase = mod:NewPhaseChangeAnnounce(2, nil, nil, nil, nil, nil, 2) local warnDiscipleofNzoth = mod:NewTargetNoFilterAnnounce(292981, 4) --Stage One: The Herald local warnMindTether = mod:NewTargetSourceAnnounce(295444, 3) local warnSnapped = mod:NewTargetNoFilterAnnounce(300133, 4, nil, "Tank|Healer") local warnUnleashedNightmare = mod:NewSpellAnnounce("ej20289", 3, 300732) local warnDread = mod:NewTargetNoFilterAnnounce(292963, 3, nil, "Healer") --Stage Two: Grip of Fear --Stage Three: Delirium's Descent local warnDeliriumsDescent = mod:NewCountAnnounce(304733, 3) --Stage Four: All Pathways Open local warnDreadScream = mod:NewTargetNoFilterAnnounce(303543, 3, nil, "Healer")--Mythic local warnManicDread = mod:NewTargetNoFilterAnnounce(296018, 3, nil, "Healer") local specWarnHysteria = mod:NewSpecialWarningStack(292971, nil, 15, nil, nil, 1, 6) --Stage One: The Herald local specWarnHorrificSummoner = mod:NewSpecialWarningSwitch("ej20172", "-Healer", nil, nil, 1, 2) local specWarnCrushingGrasp = mod:NewSpecialWarningDodge(292565, nil, nil, nil, 2, 2) local yellDread = mod:NewPosYell(292963) local yellDreadFades = mod:NewIconFadesYell(292963) --Stage Two: Grip of Fear local specWarnManifedNightmares = mod:NewSpecialWarningYou(293509, nil, nil, nil, 1, 2) local yellManifedNightmares = mod:NewYell(293509) local yellManifedNightmaresFades = mod:NewShortFadesYell(293509) local specWarnMaddeningEruption = mod:NewSpecialWarningMoveTo(292996, "Tank", nil, nil, 1, 2) --Stage Three: Delirium's Descent local specWarShatteredPsyche = mod:NewSpecialWarningDispel(295327, "Healer", nil, 3, 1, 2) --Stage Four: All Pathways Open local specWarnDarkPulse = mod:NewSpecialWarningSwitch(303978, "-Healer", nil, nil, 1, 2) local specWarnPsychoticSplit = mod:NewSpecialWarningSwitch(301068, "-Healer", nil, nil, 1, 2) local yellDreadScream = mod:NewPosYell(303543) local yellDreadScreamFades = mod:NewIconFadesYell(303543)--Mythic local specWarnVoidSlam = mod:NewSpecialWarningDodge(302593, nil, nil, nil, 2, 2)--Mythic local yellManicDread = mod:NewPosYell(296018) local yellManicDreadFades = mod:NewIconFadesYell(296018) --local specWarnGTFO = mod:NewSpecialWarningGTFO(270290, nil, nil, nil, 1, 8) --mod:AddTimerLine(BOSS) --Stage One: The Herald local timerHorrificSummonerCD = mod:NewCDTimer(80.1, "ej20172", nil, nil, nil, 1, 294515, DBM_CORE_DAMAGE_ICON) local timerCrushingGraspCD = mod:NewCDTimer(31.4, 292565, nil, nil, nil, 3) local timerDreadCD = mod:NewCDTimer(75.4, 292963, nil, "Healer", nil, 5, nil, DBM_CORE_MAGIC_ICON)--One dread timer used for all versions (cast by boss) local timerMindTetherCD = mod:NewCDTimer(47.8, 295444, nil, "Tank", nil, 5, nil, DBM_CORE_TANK_ICON)--52.3 --Stage Two: Grip of Fear local timerManifestNightmaresCD = mod:NewCDTimer(35, 293509, nil, nil, nil, 3) local timerMaddeningEruptionCD = mod:NewCDTimer(66.4, 292996, nil, nil, nil, 5, nil, DBM_CORE_TANK_ICON) --Stage Three: Delirium's Descent local timerDeliriumsDescentCD = mod:NewCDTimer(35, 304733, nil, nil, nil, 3) --Stage Four: All Pathways Open local timerDarkPulseCD = mod:NewCDTimer(93.5, 303978, nil, nil, nil, 6, nil, DBM_CORE_DEADLY_ICON) local timerManicDreadCD = mod:NewCDTimer(75.4, 296018, nil, "Healer", nil, 5, nil, DBM_CORE_MAGIC_ICON)--75-83 ----Mythic local timerPsychoticSplitCD = mod:NewCDTimer(66.6, 301068, nil, nil, nil, 6, nil, DBM_CORE_MYTHIC_ICON..DBM_CORE_DEADLY_ICON)--Mythic local timerDreadScreamCD = mod:NewAITimer(58.2, 303543, nil, "Healer", nil, 5, nil, DBM_CORE_MYTHIC_ICON..DBM_CORE_MAGIC_ICON)--Mythic local timerVoidSlamCD = mod:NewAITimer(58.2, 302593, nil, nil, nil, 3)--Mythic --local berserkTimer = mod:NewBerserkTimer(600) --mod:AddRangeFrameOption(6, 264382) mod:AddInfoFrameOption(292971, true) mod:AddSetIconOption("SetIconDread", 292963, true, false, {1, 2, 3}) mod:AddSetIconOption("SetIconDreadScream", 303543, true, false, {1, 2, 3}) mod:AddSetIconOption("SetIconManicDreadScream", 296018, true, false, {1, 2, 3}) mod.vb.phase = 1 mod.vb.dreadIcon = 1 mod.vb.DeliriumsDescentCount = 0 --mod.vb.nightmaresCount = 0 local HysteriaStacks = {} function mod:OnCombatStart(delay) table.wipe(HysteriaStacks) self.vb.phase = 1 self.vb.dreadIcon = 1 self.vb.DeliriumsDescentCount = 0 --self.vb.nightmaresCount = 0 timerMindTetherCD:Start(3.3-delay) timerDreadCD:Start(12-delay) timerHorrificSummonerCD:Start(25.4-delay)--20 sec for event, but the portal happens 5 seconds AFTER event timerCrushingGraspCD:Start(30-delay) if self.Options.InfoFrame then DBM.InfoFrame:SetHeader(DBM:GetSpellInfo(292971)) DBM.InfoFrame:Show(10, "table", HysteriaStacks, 1) end end function mod:OnCombatEnd() if self.Options.InfoFrame then DBM.InfoFrame:Hide() end -- if self.Options.RangeFrame then -- DBM.RangeCheck:Hide() -- end end function mod:SPELL_CAST_START(args) local spellId = args.spellId if spellId == 301141 then specWarnCrushingGrasp:Show() specWarnCrushingGrasp:Play("farfromline") --In perfect scenario, not delayed very much if ever even by phase changes --Crushing Grasp-292565-npc:151034 = pull:31.9, 31.6, 31.6, 31.6, 35.6, 34.8 timerCrushingGraspCD:Start() elseif spellId == 303543 or spellId == 296018 or spellId == 292963 then--302503 and 302504 excluded (LFR ids) self.vb.dreadIcon = 1 elseif spellId == 296257 and self.vb.phase < 2 then--Opening Fear Realm self.vb.phase = 2 warnPhase:Show(DBM_CORE_AUTO_ANNOUNCE_TEXTS.stage:format(2)) warnPhase:Play("ptwo") --Timers that never stop, but might need time added to them if they come off cd during transition --timerDreadCD:Stop() --New Stage 2 timers timerManifestNightmaresCD:Start(37.2) --timerMaddeningEruptionCD:Start(1)--1-3 seconds after this cast elseif spellId == 304733 then--Delirium's Descent if self.vb.phase < 3 then self.vb.phase = 3 warnPhase:Show(DBM_CORE_AUTO_ANNOUNCE_TEXTS.stage:format(3)) warnPhase:Play("pthree") --Timers actually stopped timerManifestNightmaresCD:Stop() --Timers that never stop, but might need time added to them if they come off cd during transition --timerDreadCD:Stop() --timerCrushingGraspCD:Stop() end self.vb.DeliriumsDescentCount = self.vb.DeliriumsDescentCount + 1 warnDeliriumsDescent:Show(self.vb.DeliriumsDescentCount) timerDeliriumsDescentCD:Start() elseif spellId == 303978 or spellId == 296078 then--Dark Pulse specWarnDarkPulse:Show() specWarnDarkPulse:Play("attackshield") timerDarkPulseCD:Start() elseif spellId == 301068 then specWarnPsychoticSplit:Show() specWarnPsychoticSplit:Play("changetarget") timerPsychoticSplitCD:Start() timerDreadScreamCD:Start(4) timerVoidSlamCD:Start(4) elseif spellId == 302593 then specWarnVoidSlam:Show() specWarnVoidSlam:Play("shockwave") timerVoidSlamCD:Start() end end function mod:SPELL_CAST_SUCCESS(args) local spellId = args.spellId if spellId == 292963 or spellId == 302503 then--Dread --timerDreadCD:Start() elseif spellId == 296018 or spellId == 302504 then--Manic Dread (302504 LFR) timerManicDreadCD:Start() -- elseif spellId == 293509 then -- timerManifestNightmaresCD:Start() elseif spellId == 303543 then timerDreadScreamCD:Start() elseif spellId == 295444 then--Mind Tether --In perfect scenario, not delayed very much if ever even by phase changes --"Mind Tether-295444-npc:150859 = pull:4.0, 48.2, 52.3, 48.7, 48.7", -- [8] timerMindTetherCD:Start() elseif spellId == 294515 and self:AntiSpam(5, 1) then specWarnHorrificSummoner:Show() specWarnHorrificSummoner:Play("bigmob") elseif spellId == 299708 and self:AntiSpam(5, 1) then specWarnHorrificSummoner:Show() specWarnHorrificSummoner:Play("bigmob") end end function mod:SPELL_SUMMON(args) local spellId = args.spellId if spellId == 300732 then warnUnleashedNightmare:Show() end end function mod:SPELL_AURA_APPLIED(args) local spellId = args.spellId if spellId == 292971 then local amount = args.amount or 1 HysteriaStacks[args.destName] = amount if args:IsPlayer() and (amount >= 15 and amount % 2 == 1) then--15, 17, 19 specWarnHysteria:Show(amount) specWarnHysteria:Play("stackhigh") end if self.Options.InfoFrame then DBM.InfoFrame:UpdateTable(HysteriaStacks) end elseif spellId == 292981 then warnDiscipleofNzoth:CombinedShow(1, args.destName) elseif spellId == 295480 then--295495 other one warnMindTether:Show(args.sourceName, args.destName) elseif spellId == 300133 then warnSnapped:Show(args.destName) elseif spellId == 292963 or spellId == 302503 then warnDread:CombinedShow(0.3, args.destName) if spellId == 292963 then--Non LFR local icon = self.vb.dreadIcon if args:IsPlayer() then yellDread:Yell(icon, icon, icon) yellDreadFades:Countdown(spellId, nil, icon) end if self.Options.SetIconDread then self:SetIcon(args.destName, icon) end self.vb.dreadIcon = self.vb.dreadIcon + 1 end elseif spellId == 296018 or spellId == 302504 then warnManicDread:CombinedShow(0.3, args.destName) if spellId == 296018 then--Non LFR local icon = self.vb.dreadIcon if args:IsPlayer() then yellManicDread:Yell(icon, icon, icon) yellManicDreadFades:Countdown(spellId, nil, icon) end if self.Options.SetIconManicDreadScream then self:SetIcon(args.destName, icon) end self.vb.dreadIcon = self.vb.dreadIcon + 1 end elseif spellId == 303543 then--Mythic Only warnDreadScream:CombinedShow(0.3, args.destName) local icon = self.vb.dreadIcon if args:IsPlayer() then yellDreadScream:Yell(icon, icon, icon) yellDreadScreamFades:Countdown(spellId, nil, icon) end if self.Options.SetIconDreadScream then self:SetIcon(args.destName, icon) end self.vb.dreadIcon = self.vb.dreadIcon + 1 elseif spellId == 293509 then --self.vb.nightmaresCount = self.vb.nightmaresCount + 1 if self:AntiSpam(5, 2) then timerManifestNightmaresCD:Start() end if args:IsPlayer() then specWarnManifedNightmares:Show() specWarnManifedNightmares:Play("targetyou") yellManifedNightmares:Yell() yellManifedNightmaresFades:Countdown(spellId) end elseif spellId == 295327 then if self:CheckDispelFilter() then specWarShatteredPsyche:CombinedShow(1, args.destName) specWarShatteredPsyche:ScheduleVoice(1, "helpdispel") end elseif spellId == 303971 or spellId == 296078 then--Dark Pulse --timerManicDreadCD:Stop() elseif spellId == 300584 and self.vb.phase < 4 then--Reality Portal (Only works on non mythic) self.vb.phase = 4 timerDeliriumsDescentCD:Stop() timerMaddeningEruptionCD:Stop() if self:IsMythic() then timerPsychoticSplitCD:Start(73.1) else timerDarkPulseCD:Start(73.1) end end end mod.SPELL_AURA_APPLIED_DOSE = mod.SPELL_AURA_APPLIED function mod:SPELL_AURA_REMOVED(args) local spellId = args.spellId if spellId == 292971 then HysteriaStacks[args.destName] = nil if self.Options.InfoFrame then DBM.InfoFrame:UpdateTable(HysteriaStacks) end elseif spellId == 292963 then--Non LFR if args:IsPlayer() then yellDreadFades:Cancel() end if self.Options.SetIconDread then self:SetIcon(args.destName, 0) end elseif spellId == 296018 then--Non LFR if args:IsPlayer() then yellManicDreadFades:Cancel() end if self.Options.SetIconManicDreadScream then self:SetIcon(args.destName, 0) end elseif spellId == 303543 then--Mythic Only if args:IsPlayer() then yellDreadScreamFades:Cancel() end if self.Options.SetIconDreadScream then self:SetIcon(args.destName, 0) end elseif spellId == 293509 then --self.vb.nightmaresCount = self.vb.nightmaresCount - 1 if args:IsPlayer() then yellManifedNightmaresFades:Cancel() end elseif spellId == 303971 or spellId == 296078 then--Dark Pulse --timerManicDreadCD:Start() end end function mod:SPELL_AURA_REMOVED_DOSE(args) local spellId = args.spellId if spellId == 292971 then HysteriaStacks[args.destName] = args.amount or 1 if self.Options.InfoFrame then DBM.InfoFrame:UpdateTable(HysteriaStacks) end end end --[[ function mod:SPELL_PERIODIC_DAMAGE(_, _, _, _, destGUID, _, _, _, spellId, spellName) if spellId == 270290 and destGUID == UnitGUID("player") and self:AntiSpam(2, 2) then specWarnGTFO:Show(spellName) specWarnGTFO:Play("watchfeet") end end mod.SPELL_PERIODIC_MISSED = mod.SPELL_PERIODIC_DAMAGE --]] function mod:UNIT_DIED(args) local cid = self:GetCIDFromGUID(args.destGUID) if cid == 154175 then--Horric Summoner elseif cid == 154682 then--echo-of-fear timerDreadScreamCD:Stop() elseif cid == 154685 then--echo-of-delirium timerVoidSlamCD:Stop() end end function mod:CHAT_MSG_RAID_BOSS_EMOTE(msg, npc, _, _, target) if msg:find("spell:292996") then--Maddening Eruption specWarnMaddeningEruption:Show(L.Tear) specWarnMaddeningEruption:Play("moveboss") timerMaddeningEruptionCD:Start() elseif (msg == L.Phase3 or msg:find(L.Phase3)) and self.vb.phase < 3 then self.vb.phase = 3 warnPhase:Show(DBM_CORE_AUTO_ANNOUNCE_TEXTS.stage:format(3)) warnPhase:Play("pthree") --Timers actually stopped timerManifestNightmaresCD:Stop() --Timers that never stop, but might need time added to them if they come off cd during transition --timerDreadCD:Stop() --timerCrushingGraspCD:Stop() end end function mod:UNIT_SPELLCAST_SUCCEEDED(uId, _, spellId) if spellId == 299711 then--Pick A Portal (script for horrors) --"Pick a Portal-299711-npc:150859 = pull:20.3, 60.7, 92.5, 63.2", -- [5] --Controller used for horrors even if we're in a phase one isn't cast, becauase we still want to know where the script is before we push boss. timerHorrificSummonerCD:Schedule(5)--Script runs 5 sec before spawn events, so we need to offset it elseif spellId == 299974 then--Pick a Dread (Script for dreads) --Controller used for dreads even if we're in a phase one isn't cast, becauase we still want to know where the script is before we push boss. timerDreadCD:Start() --elseif spellId == 301179 then--Pick a Ultimate (Script for Dark Pulse or mythic version Psychotic Split) elseif spellId == 296465 and self.vb.phase < 4 then--Energy Tracker (should work on all) self.vb.phase = 4 timerDeliriumsDescentCD:Stop() timerMaddeningEruptionCD:Stop() if self:IsMythic() then timerPsychoticSplitCD:Start(75.1) else timerDarkPulseCD:Start(75.1) end end end
local PANEL = {} function PANEL:Init() self.Material = nil self.AutoSize = true self:SetAlpha( 255 ) self:SetMouseInputEnabled( false ) self:SetKeyboardInputEnabled( false ) end function PANEL:Paint() if (!self.Material) then return true end surface.SetMaterial( self.Material ) surface.SetDrawColor( 255, 255, 255, self.Alpha ) surface.DrawTexturedRect( 0, 0, self:GetSize() ) return true end function PANEL:SetAlpha( _alpha_ ) self.Alpha = _alpha_ end function PANEL:SetMaterial( _matname_ ) --self.Material = surface.GetTextureID( _matname_ ) self.Material = Material( _matname_ ) local Texture = self.Material:GetTexture( "$basetexture" ) if ( Texture ) then self.Width = Texture:Width() self.Height = Texture:Height() else self.Width = 32 self.Height = 32 end self:InvalidateLayout() end function PANEL:PerformLayout() if ( !self.Material ) then return end if ( !self.AutoSize ) then return end self:SetSize( self.Width, self.Height ) end vgui.Register( "Material", PANEL, "Button" )
AddEvent("OnPlayerChat", function(ply, text) local dim = GetPlayerDimension(ply) for i, v in ipairs(GetDimensionPlayers(dim)) do AddPlayerChat(v, GetPlayerName(ply) .. " [" .. tostring(ply) .. "] (Dimension " .. tostring(dim) .. ") : " .. text) end return false end)
--- Module implementing the LuaRocks "purge" command. -- Remove all rocks from a given tree. local purge = {} local util = require("luarocks.util") local fs = require("luarocks.fs") local path = require("luarocks.path") local search = require("luarocks.search") local vers = require("luarocks.core.vers") local repos = require("luarocks.repos") local writer = require("luarocks.manif.writer") local cfg = require("luarocks.core.cfg") local remove = require("luarocks.remove") local queries = require("luarocks.queries") local cmd = require("luarocks.cmd") function purge.add_to_parser(parser) local cmd = parser:command("purge", [[ This command removes rocks en masse from a given tree. By default, it removes all rocks from a tree. The --tree option is mandatory: luarocks purge does not assume a default tree.]], util.see_also()) :summary("Remove all installed rocks from a tree.") cmd:flag("--old-versions", "Keep the highest-numbered version of each ".. "rock and remove the other ones. By default it only removes old ".. "versions if they are not needed as dependencies. This can be ".. "overridden with the flag --force.") cmd:flag("--force", "If --old-versions is specified, force removal of ".. "previously installed versions if it would break dependencies.") cmd:flag("--force-fast", "Like --force, but performs a forced removal ".. "without reporting dependency issues.") end function purge.command(args) local tree = args.tree if type(tree) ~= "string" then return nil, "The --tree argument is mandatory. "..util.see_help("purge") end local results = {} if not fs.is_dir(tree) then return nil, "Directory not found: "..tree end local ok, err = fs.check_command_permissions(args) if not ok then return nil, err, cmd.errorcodes.PERMISSIONDENIED end search.local_manifest_search(results, path.rocks_dir(tree), queries.all()) local sort = function(a,b) return vers.compare_versions(b,a) end if args.old_versions then sort = vers.compare_versions end for package, versions in util.sortedpairs(results) do for version, _ in util.sortedpairs(versions, sort) do if args.old_versions then util.printout("Keeping "..package.." "..version.."...") local ok, err = remove.remove_other_versions(package, version, args.force, args.force_fast) if not ok then util.printerr(err) end break else util.printout("Removing "..package.." "..version.."...") local ok, err = repos.delete_version(package, version, "none", true) if not ok then util.printerr(err) end end end end return writer.make_manifest(cfg.rocks_dir, "one") end return purge
object_tangible_loot_generic_deed_vehicle_generic = object_tangible_loot_generic_deed_shared_vehicle_generic:new { } ObjectTemplates:addTemplate(object_tangible_loot_generic_deed_vehicle_generic, "object/tangible/loot/generic/deed/vehicle_generic.iff")
----------------------------------- -- Area: Upper Jeuno -- NPC: Leillaine -- Standard Merchant NPC ----------------------------------- local ID = require("scripts/zones/Upper_Jeuno/IDs") require("scripts/globals/shop") function onTrade(player, npc, trade) end function onTrigger(player, npc) local stock = { 4509, 10, -- Distilled Water 4150, 2387, -- Eye Drops 4148, 290, -- Antidote 4151, 736, -- Echo Drops 4112, 837, -- Potion 4128, 4445, -- Ether 4155, 22400, -- Remedy } player:showText(npc, ID.text.LEILLAINE_SHOP_DIALOG) tpz.shop.general(player, stock) end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) end
micro_world_server = {} -- the 'radiant:new_game' event is triggered whenever a new game starts radiant.events.listen(micro_world_server, 'radiant:new_game', function(args) -- read the config file for the world to use. this will read the -- mods.microworld.world key, returning it's value or 'mini_game' -- if that key does not exist. local world_name = radiant.util.get_config('world', 'mini_game') -- generate the name of the script to load for this world from the -- world name. it must be placed in the worlds directory. local script_name = string.format('worlds.%s_world', world_name) -- try to load the script. local script = require(script_name) if not script then error(string.format('failed to require world script "%s".', script_name)) end radiant.events.listen(radiant, 'radiant:client_joined', function(args) _radiant.sim.start_game() end) -- the script must return a generator function which create an -- insteand of an object with a `start` method. local world = script() -- call __init on script if not world then error(string.format('world script "%s" failed to construct a world.', script_name)) end -- we got a world back! start it up!! if world.start then world:start() end end) return micro_world_server
require "resources/data_raw_electric_pole" require "resources/data_raw_assembling_machine" require "resources/data_raw_container" require "resources/data_raw_furnace" require "resources/data_raw_inserter" require "resources/data_raw_mining" require "resources/data_raw_lab" require "resources/game_players_zoom" require "resources/game_surfaces_always_day" require "resources/player_character" require "resources/player_force" require "resources/player_force_manual_crafting_speed" __settings_startup__data_raw_electric_pole(data, 1) __settings_startup__data_raw_container(data, 2) __settings_startup__data_raw_assembling_machine(data, 4) __settings_startup__data_raw_furnace(data, 5) __settings_startup__data_raw_mining(data, 6) __settings_startup__data_raw_lab(data, 7) __settings_startup__data_raw_inserter(data, 9) __settings_global__game_surfaces_always_day(data, 1) __settings_global__player_force_manual_crafting_speed(data, 2) __settings_global__player_force(data, 3) __settings_global__player_character(data, 4) __settings_global__data_raw_inserter(data, 5) __settings__user__game_players_zoom(data, 100)
-- screens.logo local composer = require ("composer") -- Include the Composer library. Please refer to -> http://docs.coronalabs.com/api/library/composer/index.html local scene = composer.newScene() -- Created a new scene local mainGroup -- Our main display group. We will add display elements to this group so Composer will handle these elements for us. -- For more information about groups, please refer to this guide -> http://docs.coronalabs.com/guide/graphics/group.html local tmr -- Forward reference to a timer. -- Clean up method for memory purposes. This can be named anything you want local function cleanUp() -- Cleaning up the Timer object tmr --if ( tmr ) then timer.cancel(tmr) tmr = nil --end -- If you are not sure if the tmr object exists or want to take a defensive approach, you can check it with if clause end local function changeScene() composer.gotoScene( "screens.mainMenu", "crossFade", 500 ) end function scene:create( event ) local mainGroup = self.view -- We've initialized our mainGroup. This is a MUST for Composer library. local logo = display.newImageRect( "assets/logo2.png", 256, 224 ) -- Create a new image, logo.png (900px x 285px) from the assets folder. Default anchor point is center. logo.x = display.contentCenterX -- Assign the x value of the image to the center of the X axis. logo.y = display.contentCenterY -- Assign the y value of the image to the center of the Y axis. mainGroup:insert(logo) -- Add the image to the display group. -- Further reading of Display API -> http://docs.coronalabs.com/api/library/display/index.html end function scene:show( event ) local phase = event.phase if ( phase == "will" ) then -- Scene is not shown entirely elseif ( phase == "did" ) then -- Scene is fully shown on the screen -- Wait 4000 ms to show studio logo and then, call changeScene() -- This will happen once since its iteration number is defined as 1. -- You can define it as many as you want but consider the exceptional values 0 and -1, which will make the timer loop forever. -- For more information about timers, please refer to this document -> http://docs.coronalabs.com/api/library/timer/index.html tmr = timer.performWithDelay( 500, changeScene, 1 ) --[[ Another method for the line above using Lua closures: tmr = timer.performWithDelay( 4000, function () composer.gotoScene( "screens.gameIntro", "crossFade", 1500 ) end, 1 ) For more information about Lua closures, please refer to this guide -> http://www.lua.org/pil/6.1.html ]]-- end end function scene:hide( event ) local phase = event.phase if ( phase == "will" ) then -- Scene is not off the screen entirely cleanUp() -- Clean up the scene from timers, transitions, listeners elseif ( phase == "did" ) then -- Scene is off the screen end end function scene:destroy( event ) -- Called before the scene is removed end -- Listener setup scene:addEventListener( "create", scene ) scene:addEventListener( "show", scene ) scene:addEventListener( "hide", scene ) scene:addEventListener( "destroy", scene ) return scene -- You can refer to the official Composer template for more -> http://docs.coronalabs.com/api/library/composer/index.html#template
-- 初始化 local string_sub = string.sub local debug_getinfo = debug.getinfo local string_len = string.len FRAMEWORK = { INIT_FILE = 'init.lua', PATH = { library = 'Libraries', config = 'config', test = 'Tests', controller = 'Controllers', view = 'Views', daemon = 'Daemons', plugin = 'Plugins', cache = 'Cache', data = 'Data', entity = 'Entities', model = 'Models' }, DIRECTORY_SEPARATOR = '/', IS_CLI = false, LOG_ROOT_PATH = '/tmp', -- 日志根目录 CURRENT_ENV_NAME = 'dev', --当前环境默认名称 MODULE_PREFIX = 'lua_', NGX_CACHE_KEY = 'micromvc_cache', ROOT_PATH = nil, FRAMEWORK_ROOT = nil } FRAMEWORK.FRAMEWORK_ROOT = string_sub(debug_getinfo(1, "S").source:sub(2), 1, -string_len('/Plugins/'..FRAMEWORK.INIT_FILE) - 1) FRAMEWORK.ROOT_PATH = string_sub(FRAMEWORK.FRAMEWORK_ROOT,1,-string_len('/Framework/Luas/')) print(FRAMEWORK.ROOT_PATH) package.path = FRAMEWORK.FRAMEWORK_ROOT.."/?.lua;"..FRAMEWORK.FRAMEWORK_ROOT.."/Libraries/?.lua;"..FRAMEWORK.ROOT_PATH.."/?.lua;" .. '?.lua;'..package.path require "Models.GlobalFunction" --加载自定义公共库 require 'Libraries.Class' require 'Libraries.Tools' require 'Models.Controller'
local _, Addon = ...; local AutoScrollbarMixin = {} local function scrollbarHide(self) local control = self:GetParent(); -- If the scrollbar is being hiddem we can have whole space. control:SetPoint("BOTTOMRIGHT", control:GetParent(), -5, 4); control:GetScrollChild():SetWidth(control:GetWidth() - 5); if (self._sbbg) then self._sbbg:Hide(); end getmetatable(self).__index.Hide(self); end local function scrollbarShow(self) local control = self:GetParent(); local child = control:GetScrollChild(); -- If the scrollbar is showing we need to subtract it's width. control:SetPoint("BOTTOMRIGHT", control:GetParent(), "BOTTOMRIGHT", -(self:GetWidth() + 5), 4); child:SetWidth(control:GetWidth() - 5); if (self._sbbg) then self._sbbg:Show(); end getmetatable(self).__index.Show(self); end function AutoScrollbarMixin:AdjustScrollBar(control, autoHide) local scrollbar = control.ScrollBar; local up = scrollbar.ScrollUpButton; local down = scrollbar.ScrollDownButton; local bg = self.scrollbarBackground; if (not bg) then bg = control:CreateTexture(nil, "BACKGROUND", -2); bg:SetColorTexture(0.0, 0.0, 0.0, 0.50); end scrollbar:ClearAllPoints(); scrollbar:SetPoint("TOPLEFT", control, "TOPRIGHT", 0, -up:GetHeight()); scrollbar:SetPoint("BOTTOMLEFT", control, "BOTTOMRIGHT", 0, down:GetHeight()); up:ClearAllPoints(); up:SetPoint("BOTTOM", scrollbar, "TOP"); down:ClearAllPoints(); down:SetPoint("TOP", scrollbar,"BOTTOM"); bg:ClearAllPoints(); bg:SetPoint("TOPLEFT", up, "LEFT"); bg:SetPoint("BOTTOMRIGHT", down, "RIGHT"); scrollbar.Hide = scrollbarHide; scrollbar.Show = scrollbarShow; scrollbar._sbbg = bg; if (autoHide) then control.scrollBarHideable = true; scrollbarHide(scrollbar); else control.scrollBarHideable = false; scrollbarShow(scrollbar); end end function AutoScrollbarMixin:GetContainerWidth(control) local width = control:GetWidth(); --if (control.ScrollBar and control.ScrollBar:IsShown()) then -- return (width - 5 - control.ScrollBar:GetWidth()); --end return width; end Addon.Controls = Addon.Controls or {}; Addon.Controls.AutoScrollbarMixin = AutoScrollbarMixin;
Outfit_Adventurer.modifiers_0.armor = 9900 Outfit_Adventurer.modifiers_0.destiny_slots = 5 Outfit_Adventurer.modifiers_0.overdrive = 800 Outfit_Adventurer.modifiers_0.max_overdrive_add = 6000 Outfit_Adventurer.modifiers_0.overdrive_decay_rate = 7
-- This example program measures latency of block device operations and plots it -- in a histogram. It is similar to BPF example: -- https://github.com/torvalds/linux/blob/master/samples/bpf/tracex3_kern.c local ffi = require('ffi') local bpf = require('bpf') local S = require('syscall') -- Shared part of the program local bins = 100 local map = bpf.map('hash', 512, ffi.typeof('uint64_t'), ffi.typeof('uint64_t')) local lat_map = bpf.map('array', bins) -- Kernel-space part of the program local trace_start = assert(bpf(function (ptregs) local req = ffi.cast('struct pt_regs', ptregs) map[req.parm1] = time() end)) local trace_end = assert(bpf(function (ptregs) local req = ffi.cast('struct pt_regs', ptregs) -- The lines below are computing index -- using log10(x)*10 = log2(x)*10/log2(10) = log2(x)*3 -- index = 29 ~ 1 usec -- index = 59 ~ 1 msec -- index = 89 ~ 1 sec -- index = 99 ~ 10sec or more local delta = time() - map[req.parm1] local index = 3 * math.log2(delta) if index >= bins then index = bins-1 end xadd(lat_map[index], 1) return true end)) local probes = { bpf.kprobe('myprobe:blk_start_request', trace_start, false, -1, 0), bpf.kprobe('myprobe2:blk_account_io_completion', trace_end, false, -1, 0), } -- User-space part of the program pcall(function() local counter = 0 local sym = {' ',' ','.','.','*','*','o','o','O','O','#','#'} while true do -- Print header once in a while if counter % 50 == 0 then print('|1us |10us |100us |1ms |10ms |100ms |1s |10s') counter = 0 end counter = counter + 1 -- Collect all events local hist, events = {}, 0 for i=29,bins-1 do local v = tonumber(lat_map[i] or 0) if v > 0 then hist[i] = hist[i] or 0 + v events = events + v end end -- Print histogram symbols based on relative frequency local s = '' for i=29,bins-1 do if hist[i] then local c = math.ceil((hist[i] / (events + 1)) * #sym) s = s .. sym[c] else s = s .. ' ' end end print(s .. string.format(' ; %d events', events)) S.sleep(1) end end)