content
stringlengths 5
1.05M
|
---|
--! subpump
--@ commons control firstrun periodic
--@ threedofpump depthcontrol
DepthControl = Periodic.new(UpdateRate, Depth_Control)
SelectAltitudeImpl(ThreeDoFPump)
SelectPitchImpl(ThreeDoFPump)
SelectRollImpl(ThreeDoFPump)
function Update(I) -- luacheck: ignore 131
C = Commons.new(I)
FirstRun(I)
if not C:IsDocked() then
DepthControl:Tick(I)
Depth_Apply(I)
ThreeDoFPump.Update(I)
end
end
|
MenuUIManager = MenuUIManager or BeardLib:ManagerClass("MenuUI")
function MenuUIManager:init()
self._menus = {}
-- Deprecated, try not to use.
BeardLib.managers.menu_ui = self
end
function MenuUIManager:AddMenu(menu)
table.insert(self._menus, menu)
end
function MenuUIManager:RemoveMenu(menu)
table.delete(self._menus, menu)
end
function MenuUIManager:Menus()
return self._menus
end
function MenuUIManager:GetActiveMenu()
local mc = managers.mouse_pointer._mouse_callbacks
local last = mc[#mc]
if last and last.menu_ui_object then
return last.menu_ui_object
end
return nil
end
function MenuUIManager:DisableInput()
self._input_disabled = true
end
function MenuUIManager:EnableInput()
self._input_disabled = nil
self._enable_input_t = nil
end
function MenuUIManager:InputEnabled()
return not self._input_disabled
end
function MenuUIManager:InputDisabled()
return self._input_disabled
end
function MenuUIManager:InputAllowed(...)
if self:InputDisabled() then
return false
end
local menu = self:GetActiveMenu()
return not menu or menu.allow_full_input == true
end
function MenuUIManager:CloseMenuEvent()
self:DisableInput()
self._enable_input_t = Application:time() + 0.01
end
function MenuUIManager:Update(t, dt)
if self._input_disabled and self._enable_input_t and self._enable_input_t <= t then
self:EnableInput()
end
end
--Part of making BeardLib a little more consistent. Function names are PascalCase.
MenuUIManager.add_menu = MenuUIManager.AddMenu
MenuUIManager.remove_menu = MenuUIManager.RemoveMenu
MenuUIManager.get_active_menu = MenuUIManager.GetActiveMenu
MenuUIManager.disable_input = MenuUIManager.DisableInput
MenuUIManager.enable_input = MenuUIManager.EnableInput
MenuUIManager.input_enabled = MenuUIManager.InputEnabled
MenuUIManager.input_disabled = MenuUIManager.InputDisabled
MenuUIManager.input_allowed = MenuUIManager.InputAllowed
MenuUIManager.close_menu_event = MenuUIManager.CloseMenuEvent
|
add_requires("sol2 >=3.2.3", "fmt >=8.1.1", "lyra >=1.6")
add_rules("mode.debug", "mode.release")
set_languages("c++20")
target("lua-config-formatter")
set_kind("binary")
add_files("src/*.cpp")
add_headerfiles("src/*.h")
add_packages("sol2", "fmt", "lyra")
|
GameInfo = {
["Name"] = "Chess",
["Version"] = "0.0.1",
}
function Main()
print("Chess. Yeah. You lose your a failure. ")
end
Main()
|
--[[
Cops and Robbers: Ammunation & Weapon Scripts
Created by RhapidFyre
These files contain all the features to purchasing and obtaining weapons
from stores. Eventually the `cnr_pickups` resource will be merged in here
Contributors:
-
Created 01/01/2020
--]]
resource_manifest_version '05cfa83c-a124-4cfa-a768-c24a5811d8f9'
ui_page "nui/ui.html"
dependency {'cnrobbers'}
files {
"nui/img/WEAPON_PISTOL50.png", "nui/img/WEAPON_SAWNOFFSHOTGUN.png",
"nui/img/WEAPON_PISTOL.png", "nui/img/WEAPON_KNUCKLE.png",
"nui/img/WEAPON_ASSAULTRIFLE.png", "nui/img/WEAPON_CARBINERIFLE.png",
"nui/img/WEAPON_PETROLCAN.png", "nui/img/WEAPON_PUMPSHOTGUN.png",
"nui/img/WEAPON_SMG.png", "nui/img/WEAPON_REVOLVER.png",
"nui/img/WEAPON_BULLPUPRIFLE.png", "nui/img/WEAPON_MARKSMANRIFLE.png",
"nui/img/WEAPON_FLAREGUN.png", "nui/img/WEAPON_KNIFE.png",
"nui/ui.html", "nui/ui.js", "nui/ui.css"
}
client_scripts {
"sh_config.lua",
"cl_config.lua",
"cl_ammunation.lua"
}
server_scripts {
"sh_config.lua",
"sv_config.lua",
"sv_ammunation.lua"
}
server_exports {'RevokeAllWeapons'}
exports {
'InsideGunRange' -- Checks if player is in a no-crime reporting area (gun range)
}
|
--Check whether you enable/disable dgs update system..
--If you don't trust dgs.. Please Disable It In "config.txt"
local check = fileExists("update.cfg") and fileOpen("update.cfg") or fileCreate("update.cfg")
local version = tonumber(fileRead(check,fileGetSize(check))) or 0
fileClose(check)
setElementData(resourceRoot,"Version",version)
if dgsConfig.updateSystemDisabled then return end
local _fetchRemote = fetchRemote
function fetchRemote(...)
if not hasObjectPermissionTo(getThisResource(),"function.fetchRemote",true) then
outputDebugString("[DGS]Request 'fetchRemote', but access denied. Use the command 'aclrequest allow dgs all'",2)
return false
end
return _fetchRemote(...)
end
RemoteVersion = 0
ManualUpdate = false
updateTimer = false
updatePeriodTimer = false
function checkUpdate()
outputDebugString("[DGS]Connecting to github...")
fetchRemote("https://raw.githubusercontent.com/thisdp/dgs/master/update.cfg",function(data,err)
if err == 0 then
RemoteVersion = tonumber(data)
if not ManualUpdate then
if RemoteVersion > version then
outputDebugString("[DGS]Remote Version Got [Remote:"..data.." Current:"..version.."].")
outputDebugString("[DGS]Update? Command: updatedgs")
if isTimer(updateTimer) then killTimer(updateTimer) end
updateTimer = setTimer(function()
if RemoteVersion > version then
outputDebugString("[DGS]Remote Version Got [Remote:"..RemoteVersion.." Current:"..version.."].")
outputDebugString("[DGS]Update? Command: updatedgs")
else
killTimer(updateTimer)
end
end,dgsConfig.updateCheckNoticeInterval*60000,0)
else
outputDebugString("[DGS]Current Version("..version..") is the latest!")
end
else
startUpdate()
end
else
outputDebugString("[DGS]Can't Get Remote Version ("..err..")")
end
end)
end
if dgsConfig.updateCheckAuto then
checkUpdate()
updatePeriodTimer = setTimer(checkUpdate,dgsConfig.updateCheckInterval*3600000,0)
end
addCommandHandler("updatedgs",function(player)
local account = getPlayerAccount(player)
local accName = getAccountName(account)
local isAdmin = isObjectInACLGroup("user."..accName,aclGetGroup("Admin")) or isObjectInACLGroup("user."..accName,aclGetGroup("Console"))
if isAdmin then
outputDebugString("[DGS]Player "..getPlayerName(player).." attempt to update dgs (Allowed)")
outputDebugString("[DGS]Preparing for updating dgs")
outputChatBox("[DGS]Preparing for updating dgs",root,0,255,0)
if RemoteVersion > version then
startUpdate()
else
ManualUpdate = true
checkUpdate()
end
else
outputChatBox("[DGS]Access Denined!",player,255,0,0)
outputDebugString("[DGS]Player "..getPlayerName(player).." attempt to update dgs (Denied)!",2)
end
end)
function startUpdate()
ManualUpdate = false
setTimer(function()
outputDebugString("[DGS]Requesting Update Data (From github)...")
fetchRemote("https://raw.githubusercontent.com/thisdp/dgs/master/meta.xml",function(data,err)
if err == 0 then
outputDebugString("[DGS]Update Data Acquired")
if fileExists("updated/meta.xml") then
fileDelete("updated/meta.xml")
end
local meta = fileCreate("updated/meta.xml")
fileWrite(meta,data)
fileClose(meta)
outputDebugString("[DGS]Requesting Verification Data...")
getGitHubTree()
else
outputDebugString("[DGS]Can't Get Remote Update Data (ERROR:"..err..")",2)
end
end)
end,50,1)
end
preUpdate = {}
fileHash = {}
UpdateCount = 0
folderGetting = {}
function getGitHubTree(path,nextPath)
nextPath = nextPath or ""
fetchRemote(path or "https://api.github.com/repos/thisdp/dgs/git/trees/master",function(data,err)
if err == 0 then
local theTable = fromJSON(data)
folderGetting[theTable.sha] = nil
for k,v in pairs(theTable.tree) do
if (v.path ~= "styleMapper.lua" and fileExists("styleManager/styleMapper.lua")) and v.path ~= "meta.xml" then
local thePath = nextPath..(v.path)
if v.mode == "040000" then
folderGetting[v.sha] = true
getGitHubTree(v.url,thePath.."/")
else
fileHash[thePath] = v.sha
end
end
end
if not next(folderGetting) then
checkFiles()
end
else
outputDebugString("[DGS]Failed To Get Verification Data, Please Try Again Later (API Cool Down 60 mins)!",2)
end
end)
end
function checkFiles()
local xml = xmlLoadFile("updated/meta.xml")
for k,v in pairs(xmlNodeGetChildren(xml)) do
if xmlNodeGetName(v) == "script" or xmlNodeGetName(v) == "file" then
local path = xmlNodeGetAttribute(v,"src")
if not string.find(path,"styleMapper.lua") and path ~= "meta.xml" then
local sha = ""
if fileExists(path) then
local file = fileOpen(path)
local size = fileGetSize(file)
local text = fileRead(file,size)
fileClose(file)
sha = hash("sha1","blob " .. size .. "\0" ..text)
end
if sha ~= fileHash[path] then
outputDebugString("[DGS]Update Required: ("..path..")")
table.insert(preUpdate,path)
end
end
end
end
DownloadFiles()
end
function DownloadFiles()
UpdateCount = UpdateCount + 1
if not preUpdate[UpdateCount] then
DownloadFinish()
return
end
outputDebugString("[DGS]Requesting ("..UpdateCount.."/"..(#preUpdate or "Unknown").."): "..tostring(preUpdate[UpdateCount]).."")
fetchRemote("https://raw.githubusercontent.com/thisdp/dgs/master/"..preUpdate[UpdateCount],function(data,err,path)
if err == 0 then
local size = 0
if fileExists(path) then
local file = fileOpen(path)
size = fileGetSize(file)
fileClose(file)
fileDelete(path)
end
local file = fileCreate(path)
fileWrite(file,data)
local newsize = fileGetSize(file)
fileClose(file)
outputDebugString("[DGS]File Got ("..UpdateCount.."/"..#preUpdate.."): "..path.." [ "..size.."B -> "..newsize.."B ]")
else
outputDebugString("[DGS]Download Failed: "..path.." ("..err..")!",2)
end
if preUpdate[UpdateCount+1] then
DownloadFiles()
else
DownloadFinish()
end
end,"",false,preUpdate[UpdateCount])
end
function DownloadFinish()
outputDebugString("[DGS]Changing Config File")
if fileExists("update.cfg") then
fileDelete("update.cfg")
end
local file = fileCreate("update.cfg")
fileWrite(file,tostring(RemoteVersion))
fileClose(file)
if fileExists("meta.xml") then
backupStyleMapper()
fileDelete("meta.xml")
end
recoverStyleMapper()
outputDebugString("[DGS]Update Complete ( "..#preUpdate.." File"..(#preUpdate==1 and "" or "s").." Changed )")
outputDebugString("[DGS]Please Restart DGS")
outputChatBox("[DGS]Update Complete ( "..#preUpdate.." File"..(#preUpdate==1 and "" or "s").." Changed )",root,0,255,0)
preUpdate = {}
UpdateCount = 0
end
addCommandHandler("dgsver",function(pla,cmd)
local vsdd
if fileExists("update.cfg") then
local file = fileOpen("update.cfg")
local vscd = fileRead(file,fileGetSize(file))
fileClose(file)
vsdd = tonumber(vscd)
if vsdd then
outputDebugString("[DGS]Version: "..vsdd,3)
else
outputDebugString("[DGS]Version State is damaged! Please use /updatedgs to update",1)
end
else
outputDebugString("[DGS]Version State is damaged! Please use /updatedgs to update",1)
end
if getPlayerName(pla) ~= "Console" then
if vsdd then
outputChatBox("[DGS]Version: "..vsdd,pla,0,255,0)
else
outputChatBox("[DGS]Version State is damaged! Please use /updatedgs to update",pla,255,0,0)
end
end
end)
styleBackupStr = ""
locator = [[ <export]]
function backupStyleMapper()
if dgsConfig.backupMeta then
fileCopy("meta.xml","meta.xml.bak",true)
end
assert(fileExists("meta.xml"),"[DGS] Please rename the meta xml as meta.xml")
local meta = fileOpen("meta.xml")
local str = fileRead(meta,fileGetSize(meta))
local startStr = "<!----$Add Your Styles Here---->"
local endStr = "<!----&Add Your Styles Here---->"
local startPos = str:find(startStr)
local endPos = str:find(endStr)
styleBackupStr = str:sub(startPos,endPos-1).."<!--&Add Your Styles Here-->"
fileClose(meta)
if fileExists("styleMapperBackup.bak") then
fileDelete("styleMapperBackup.bak")
end
if dgsConfig.backupStyleMeta then
local file = fileCreate("styleMapperBackup.bak")
fileWrite(file,styleBackupStr)
fileClose(file)
end
end
function recoverStyleMapper()
assert(styleBackupStr ~= "","[DGS] Failed to recover style mapper")
local meta = fileOpen("updated/meta.xml")
local str = fileRead(meta,fileGetSize(meta))
fileClose(meta)
local newMeta = fileCreate("meta.xml")
local startStr = "<!----$Add Your Styles Here---->"
local startPos = str:find(startStr)
local exportPos = str:find(locator)
local scriptsStr = str:sub(1,startPos-1)
local exportsStr = str:sub(exportPos)
fileWrite(newMeta,scriptsStr..styleBackupStr.."\r\n"..exportsStr)
fileClose(newMeta)
fileDelete("updated/meta.xml")
end
|
return {'vee','veearts','veeartsenijkunde','veeartsenijkundig','veeartsenijkundige','veeartsenijschool','veeauto','veebedrijf','veebeslag','veebezetting','veeboer','veeboot','veedief','veediefstal','veedrijver','veefokker','veefokkerij','veeg','veegactie','veegmachine','veegmes','veegploeg','veegsel','veegster','veegvast','veegwagen','veegwet','veehandel','veehandelaar','veehoeder','veehouder','veehouderij','veehouderijbedrijf','veehoudersbedrijf','veehoudster','veejay','veekeuring','veekoek','veekoopman','veekoper','veel','veelal','veelarmig','veelbeduidend','veelbekeken','veelbelovend','veelbeluisterd','veelbesproken','veelbetekenend','veelbewogen','veelbezongen','veelbloemig','veelduidigheid','veeleer','veeleisend','veelgebruikt','veelgeciteerde','veelgehoord','veelgelezen','veelgeliefd','veelgemaakt','veelgeplaagd','veelgeprezen','veelgeroemd','veelgevraagd','veelgodendom','veelgoderij','veelheid','veelhoek','veelhoekig','veelhoofdig','veeljarig','veelkleurendruk','veelkleurig','veelkleurigheid','veelkoppig','veelledig','veelluik','veelmeer','veelomvattend','veelpleger','veelprater','veelschrijver','veelschrijverij','veelsnarig','veelsoortig','veelstemmig','veelszins','veeltalig','veeltaligheid','veelte','veelterm','veeltijds','veelverdiener','veelvlak','veelvlakkig','veelvoet','veelvoorkomend','veelvormig','veelvormigheid','veelvoud','veelvoudig','veelvraat','veelvuldig','veelvuldigheid','veelwetend','veelweter','veelweterij','veelwijverij','veelzeggend','veelzijdig','veelzijdigheid','veem','veemarkt','veemarkthal','veembaas','veemgericht','veen','veenachtig','veenarbeider','veenbaas','veenbes','veenbodem','veenbrand','veenbranden','veenbrug','veenderij','veengebied','veengraver','veengrond','veenkoloniaal','veenkolonie','veenlaag','veenlijk','veenmoeras','veenmol','veenmos','veenplas','veenpluis','veenput','veenrook','veenweidegebied','veenwerker','veepacht','veepest','veer','veerboot','veerbootramp','veercomfort','veerdienst','veergeld','veerhaven','veerhavens','veerhuis','veerklok','veerknecht','veerkracht','veerkrachtig','veerkrachtigheid','veerlieden','veerloon','veerman','veerploeg','veerpont','veerring','veerschip','veerschipper','veerschuit','veerslot','veersysteem','veertien','veertiendaags','veertiende','veertienduizend','veertienhonderd','veertienhonderdste','veertienjarig','veertienjarigen','veertiental','veertig','veertigdagentijd','veertigduizend','veertiger','veertigjarig','veertigplusser','veertigste','veertigtal','veertigurengebed','veertigurig','veertrommel','veerverbinding','veerweg','veesector','veest','veestal','veestapel','veesten','veeteelt','veeteeltbedrijf','veeteeltconsulent','veeteeltkundig','veeteeltsector','veeteler','veetransport','veevervoer','veevoeder','veevoederbedrijf','veevoederfabriek','veevoederindustrie','veevoedersector','veevoer','veewagen','veeweide','veeweider','veeziekte','veellezer','veegdienst','veekraal','veertigurenweek','veelkantig','veelknopig','veelslachtig','veelwaardig','veevervoerder','veelgelaagd','veehouderijsector','veenpakket','veenvorming','veehouderijtak','veelomvattendheid','veelstemmigheid','veenbedrijf','veendijk','veengroei','veenland','veenlandschap','veenpolder','veenwater','veenweide','veenweidelandschap','veerconstante','veerdam','veerdruk','veerenergie','veermechanisme','veerooster','veerspanning','veerwild','veevoeding','veevoerindustrie','veevoersector','veelvolkerenstaat','veeprijskamp','veekering','veeboerderij','veenontginning','veenwinning','veerpoot','veetransporteur','veelerveen','veen','veendam','veendammer','veendams','veenendaal','veenendaals','veenendaler','veens','veere','veerle','veenboer','veenstra','veenema','veeke','veeken','veeneman','veenvliet','veeger','veelenturf','veenbrink','veenker','veentjer','veenis','veenhoven','veensma','veelers','veeninga','veeartsen','veeartsenijscholen','veeboeren','veeboten','veefokkers','veegde','veegden','veegmachines','veegmessen','veegt','veegvaste','veehoeders','veehouders','veekeuringen','veekoeken','veekopers','veelarmige','veelbekritiseerde','veelbelovende','veelbelovender','veelbetekenende','veelbetekenender','veelbezochte','veelbloemige','veeleisende','veeleisender','veelgebruikte','veelgelaagde','veelgeliefde','veelgemaakte','veelgenoemde','veelgeplaagde','veelgestelde','veelgevraagde','veelhoeken','veelhoekige','veelhoofdige','veeljarige','veelkantige','veelkleurige','veelknopige','veelledige','veelomvattende','veelpraters','veelrijders','veelschrijvers','veelslachtige','veelsnarige','veelsoortige','veelstemmige','veelt','veeltalige','veeltermen','veeltjes','veelvlakken','veelvlakkige','veelvoorkomende','veelvormige','veelvouden','veelvoudige','veelvraten','veelvuldige','veelvuldiger','veelwaardige','veelweters','veelzeggende','veelzijdige','veemarkten','veemgerichten','veemrechters','veenachtige','veenarbeiders','veenbazen','veenbessen','veenboeren','veenbruggen','veendampen','veende','veenden','veenderijen','veengravers','veengronden','veenkolonies','veenkolonien','veenmollen','veenplassen','veenputten','veenweidegebieden','veenwerkers','veerboten','veerde','veerden','veerdiensten','veergelden','veerhuizen','veerkrachtige','veerkrachtiger','veerkrachtigere','veerkrachtigste','veerlui','veerploegen','veerponten','veerschepen','veerschippers','veerschuiten','veersloten','veerstoepen','veert','veertiendaagse','veertienjarige','veertigers','veertigjarige','veertje','veertjes','veertrommels','veerwegen','veestallen','veestten','veeteeltconsulenten','veetransporteurs','veevervoerders','veevoederfabrikanten','veevoeders','veevoerfabrikanten','veevoerproducenten','veewagens','veeziekten','veeziektes','veel','veebedrijven','veedieven','veedrijvers','veegacties','veegploegen','veehandelaars','veehandelaren','veehouderijbedrijven','veehouderijen','veejays','veekoopmannen','veelde','veelkoppige','veelplegers','veelverdieners','veelzijdiger','veemarkthallen','veengebieden','veenkoloniale','veenlijken','veenmoerassen','veenmossen','veertigplussers','veertigtallen','veertigurige','veerverbindingen','vees','veestapels','veestte','veeteeltkundige','veetelers','veetransporten','veefokkerijen','veelbeluisterde','veelgehoorde','veelgeroemde','veegst','veelbeduidende','veekralen','veellezers','veertigurenweken','veerse','veeres','veerles','veenbodems','veegwagens','veehouderijsectoren','veendijken','veenlagen','veenpolders','veerbootje','veeroosters','veerpoten','veeteeltbedrijven','veevoederbedrijven','veenontginningen','veertienen','veersystemen','veeprijskampen','veeboerderijen','veermannen','veehouderijtakken','veevoederfabrieken','veenpakketten','veediefstallen','veerringen','veendamse','veenendaalse','veense'}
|
local waves = {
[1] = {{name = "small-biter", amount = 10}},
[2] = {{name = "small-biter", amount = 20}},
[3] = {{name = "small-biter", amount = 40}},
[4] = {{name = "small-biter", amount = 80}, {name = "small-spitter", amount = 10}},
[5] = {{name = "small-biter", amount = 80}, {name = "small-spitter", amount = 20}},
[6] = {{name = "small-biter", amount = 80}, {name = "small-spitter", amount = 40}},
[7] = {{name = "small-biter", amount = 80}, {name = "small-spitter", amount = 80}},
[8] = {{name = "medium-biter", amount = 10}, {name = "small-spitter", amount = 80}},
[9] = {{name = "medium-biter", amount = 20}, {name = "small-spitter", amount = 80}},
[10] = {{name = "medium-biter", amount = 40}, {name = "small-spitter", amount = 80}},
[11] = {{name = "medium-biter", amount = 80}, {name = "small-spitter", amount = 80}},
[12] = {{name = "medium-biter", amount = 80}, {name = "medium-spitter", amount = 10}},
[13] = {{name = "medium-biter", amount = 80}, {name = "medium-spitter", amount = 20}},
[14] = {{name = "medium-biter", amount = 80}, {name = "medium-spitter", amount = 40}},
[15] = {{name = "medium-biter", amount = 80}, {name = "medium-spitter", amount = 80}},
[16] = {{name = "big-biter", amount = 10}, {name = "medium-spitter", amount = 80}},
[17] = {{name = "big-biter", amount = 20}, {name = "medium-spitter", amount = 80}},
[18] = {{name = "big-biter", amount = 40}, {name = "medium-spitter", amount = 80}},
[19] = {{name = "big-biter", amount = 80}, {name = "medium-spitter", amount = 80}},
[20] = {{name = "big-biter", amount = 80}, {name = "big-spitter", amount = 10}},
[21] = {{name = "big-biter", amount = 80}, {name = "big-spitter", amount = 20}},
[22] = {{name = "big-biter", amount = 80}, {name = "big-spitter", amount = 40}},
[23] = {{name = "big-biter", amount = 80}, {name = "big-spitter", amount = 80}},
[24] = {{name = "behemoth-biter", amount = 10}, {name = "big-spitter", amount = 80}},
[25] = {{name = "behemoth-biter", amount = 20}, {name = "big-spitter", amount = 80}},
[26] = {{name = "behemoth-biter", amount = 40}, {name = "big-spitter", amount = 80}},
[27] = {{name = "behemoth-biter", amount = 80}, {name = "big-spitter", amount = 80}},
[28] = {{name = "behemoth-biter", amount = 80}, {name = "behemoth-spitter", amount = 10}},
[29] = {{name = "behemoth-biter", amount = 80}, {name = "behemoth-spitter", amount = 20}},
[30] = {{name = "behemoth-biter", amount = 80}, {name = "behemoth-spitter", amount = 40}},
[31] = {{name = "behemoth-biter", amount = 80}, {name = "behemoth-spitter", amount = 80}}
}
return waves
|
local Widget = require "widgets/widget"
local VisibleDebuffSlot = require "widgets/visibledebuffslot"
local SLOTDIST = 60
local VisibleDebuffContainer =
Class(
Widget,
function(self, owner)
Widget._ctor(self, "Visibledebuffcontainer")
self.owner = owner
self.buffslots = {}
self:SetHAnchor(1)
self:SetVAnchor(2)
end
)
function VisibleDebuffContainer:AddBuff(name, ent, percent, activated, ispositive)
if not self.buffslots[name] then
self.buffslots[name] = self:AddChild(VisibleDebuffSlot(self.owner, name, ent, percent, activated))
self.buffslots[name].OnBuffEntityRemove = function()
self:RemoveBuff(name)
end
self.buffslots[name].ispositive = ispositive
self:Sort()
self.owner:ListenForEvent("onremove", self.buffslots[name].OnBuffEntityRemove, ent)
end
self.buffslots[name]:SetBuff(percent, activated)
end
function VisibleDebuffContainer:RemoveBuff(name)
local ent = self.buffslots[name]:GetBuffEntity()
self.owner:RemoveEventCallback("onremove", self.buffslots[name].OnBuffEntityRemove, ent)
self.buffslots[name]:Kill()
self.buffslots[name] = nil
self:Sort()
end
function VisibleDebuffContainer:Sort()
local index = 1
for name, buffslot in pairs(self.buffslots) do
local x, y, z = buffslot.ispositive and 0 or SLOTDIST, SLOTDIST * (index - 1), 0
buffslot:SetPosition(x, y, z)
index = index + 1
end
end
return VisibleDebuffContainer
|
local PLUGIN = PLUGIN;
Clockwork.kernel:IncludePrefixed("cl_hooks.lua");
Clockwork.kernel:IncludePrefixed("cl_plugin.lua");
Clockwork.kernel:IncludePrefixed("sv_plugin.lua");
Clockwork.kernel:IncludeDirectory("blueprints/", true);
for k, v in pairs(file.Find(Clockwork.kernel:GetSchemaFolder().."/plugins/craftingmenu/plugin/blueprints/*.lua", "LUA", "namedesc")) do
Clockwork.kernel:IncludePrefixed(Clockwork.kernel:GetSchemaFolder().."/plugins/craftingmenu/plugin/blueprints/"..v);
end;
Clockwork.option:SetKey("name_crafting", "Crafting");
Clockwork.option:SetKey("description_crafting", "Combine various items to make new items.");
Clockwork.config:ShareKey("crafting_cost");
Clockwork.config:ShareKey("craftingMenu");
|
local handle = io.popen("git rev-parse --is-inside-work-tree")
local isGit = handle:read("*a")
print(isGit)
|
-- test_spec.lua
local xml_text = [[
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE pdf2xml SYSTEM "pdf2xml.dtd">
<pdf2xml producer="poppler" version="0.73.0">
<page number="1" position="absolute" top="0" left="0" height="1262" width="892">
<fontspec id="0" size="12" family="YIUXTL+LMRoman10" color="#000000"/>
<text top="186" left="223" width="75" height="20" font="0">Hello world</text>
<text top="1038" left="455" width="7" height="20" font="0">1</text>
</page>
</pdf2xml>
]]
expose("exposed test for pdftomarkup", function()
local pdftomarkup = require("pdftomarkup")
local parser = pdftomarkup.new()
it("should load parser", function()
assert.truthy(type(parser) == "table")
end)
parser:parse_xml(xml_text)
for k,v in pairs(parser.dom.root) do
print(k,v)
end
-- tests can go here
-- more tests pertaining to the top level
end)
|
local listeners = {}
local INPUT = require 'Core.Modules.interface-input'
local LIST = require 'Core.Modules.interface-list'
local INFO = require 'Data.info'
listeners.but_add = function(target)
BLOCKS.group.isVisible = false
NEW_BLOCK = require 'Interfaces.new-block'
NEW_BLOCK.create()
end
listeners.but_play = function(target)
BLOCKS.group.isVisible = false
START = require 'Core.Simulation.start'
START.new()
end
listeners.but_list = function(target)
if #BLOCKS.group.blocks ~= 0 then
local list = {STR['button.remove'], STR['button.copy'], STR['button.comment']}
BLOCKS.group[8]:setIsLocked(true, 'vertical')
if BLOCKS.group.isVisible then
LIST.new(list, MAX_X, target.y - target.height / 2, 'down', function(e)
BLOCKS.group[8]:setIsLocked(false, 'vertical')
if e.index ~= 0 then
ALERT = false
INDEX_LIST = e.index
BLOCKS.group[3].isVisible = true
BLOCKS.group[4].isVisible = false
BLOCKS.group[5].isVisible = false
BLOCKS.group[6].isVisible = false
BLOCKS.group[7].isVisible = true
for i = 1, #BLOCKS.group.blocks do
BLOCKS.group.blocks[i].x = BLOCKS.group.blocks[i].x + 20
BLOCKS.group.blocks[i].checkbox:setState({isOn = false})
BLOCKS.group.blocks[i].checkbox.isVisible = true
BLOCKS.group.blocks[i].rects.isVisible = false
end
MORE_LIST = e.text ~= STR['button.copy']
BLOCKS.group[3].text = '(' .. e.text .. ')'
end
end, nil, nil, 1)
else
BLOCKS.group[8]:setIsLocked(false, 'vertical')
end
end
end
listeners.but_okay = function(target)
local data = GET_GAME_CODE(CURRENT_LINK)
ALERT = true
LAST_CHECKBOX = 0
BLOCKS.group[3].text = ''
BLOCKS.group[3].isVisible = false
BLOCKS.group[4].isVisible = true
BLOCKS.group[5].isVisible = true
BLOCKS.group[6].isVisible = true
BLOCKS.group[7].isVisible = false
for i = 1, #BLOCKS.group.blocks do
BLOCKS.group.blocks[i].x = BLOCKS.group.blocks[i].x - 20
BLOCKS.group.blocks[i].checkbox.isVisible = false
BLOCKS.group.blocks[i].rects.isVisible = true
end
if INDEX_LIST == 1 then
for i = #BLOCKS.group.blocks, 1, -1 do
if BLOCKS.group.blocks[i].checkbox.isOn then
BLOCKS.group.scrollHeight = BLOCKS.group.scrollHeight - BLOCKS.group.blocks[i].block.height + 4
if BLOCKS.group.blocks[i].data.event then BLOCKS.group.scrollHeight = BLOCKS.group.scrollHeight - 24 end
BLOCKS.group.blocks[i]:removeSelf()
table.remove(BLOCKS.group.blocks, i)
table.remove(data.scripts[CURRENT_SCRIPT].params, i)
end
end
for i = 1, #BLOCKS.group.blocks do
local y = i == 1 and 50 or BLOCKS.group.blocks[i - 1].y + BLOCKS.group.blocks[i - 1].block.height / 2 + BLOCKS.group.blocks[i].height / 2 - 4
if BLOCKS.group.blocks[i].data.event then y = y + 24 end BLOCKS.group.blocks[i].y = y BLOCKS.group[8]:setScrollHeight(BLOCKS.group.scrollHeight)
end
elseif INDEX_LIST == 2 then
for i = 1, #BLOCKS.group.blocks do
if BLOCKS.group.blocks[i].checkbox.isOn then
BLOCKS.group.blocks[i].checkbox:setState({isOn = false})
local scrollY = select(2, BLOCKS.group[8]:getContentPosition())
local diffY = BLOCKS.group[8].y - BLOCKS.group[8].height / 2
local targetY = math.abs(scrollY) + diffY + CENTER_Y - 150
local blockIndex = i
local blockData = COPY_TABLE(BLOCKS.group.blocks[i].data)
if blockData.event then
table.insert(data.scripts[CURRENT_SCRIPT].params, blockIndex, blockData)
BLOCKS.new(blockData.name, blockIndex, blockData.event, blockData.params, blockData.comment, blockData.nested)
for j = blockIndex + 2, #BLOCKS.group.blocks do
if BLOCKS.group.blocks[j + blockIndex - i].data.event then break end
blockIndex, blockData = blockIndex + 1, COPY_TABLE(BLOCKS.group.blocks[j + blockIndex - i].data)
table.insert(data.scripts[CURRENT_SCRIPT].params, blockIndex, blockData)
BLOCKS.new(blockData.name, blockIndex, blockData.event, blockData.params, blockData.comment, blockData.nested)
end
SET_GAME_CODE(CURRENT_LINK, data)
display.getCurrentStage():setFocus(BLOCKS.group.blocks[i])
BLOCKS.group.blocks[i].click = true
BLOCKS.group.blocks[i].move = true
newMoveLogicBlock({target = BLOCKS.group.blocks[i]}, BLOCKS.group, BLOCKS.group[8])
else
table.insert(data.scripts[CURRENT_SCRIPT].params, blockIndex, blockData)
BLOCKS.new(blockData.name, blockIndex, blockData.event, blockData.params, blockData.comment)
SET_GAME_CODE(CURRENT_LINK, data)
display.getCurrentStage():setFocus(BLOCKS.group.blocks[blockIndex])
BLOCKS.group.blocks[blockIndex].click = true
BLOCKS.group.blocks[blockIndex].move = true
newMoveLogicBlock({target = BLOCKS.group.blocks[blockIndex]}, BLOCKS.group, BLOCKS.group[8])
end
break
end
end
for i = 1, #BLOCKS.group.blocks do
if BLOCKS.group.blocks[i].checkbox.isOn then
BLOCKS.group.blocks[i].checkbox:setState({isOn = false})
end
end
elseif INDEX_LIST == 3 then
for i = #BLOCKS.group.blocks, 1, -1 do
if BLOCKS.group.blocks[i].checkbox.isOn then
BLOCKS.group.blocks[i].checkbox:setState({isOn = false})
if BLOCKS.group.blocks[i].data.comment then
data.scripts[CURRENT_SCRIPT].params[i].comment = false
BLOCKS.group.blocks[i].block:setFillColor(INFO.getBlockColor(BLOCKS.group.blocks[i].data.name, false))
BLOCKS.group.blocks[i].data.comment = false
else
data.scripts[CURRENT_SCRIPT].params[i].comment = true
BLOCKS.group.blocks[i].block:setFillColor(INFO.getBlockColor(BLOCKS.group.blocks[i].data.name, true))
BLOCKS.group.blocks[i].data.comment = true
end
if BLOCKS.group.blocks[i].data.event then
for j = i + 1, #BLOCKS.group.blocks do
if BLOCKS.group.blocks[j].data.event then break end
data.scripts[CURRENT_SCRIPT].params[j].comment = BLOCKS.group.blocks[i].data.comment
BLOCKS.group.blocks[j].block:setFillColor(INFO.getBlockColor(BLOCKS.group.blocks[j].data.name, BLOCKS.group.blocks[i].data.comment))
BLOCKS.group.blocks[j].data.comment = BLOCKS.group.blocks[i].data.comment
end
end
end
end
elseif INDEX_LIST == 4 then
for i = 1, #BLOCKS.group.blocks do
if BLOCKS.group.blocks[i].checkbox.isOn then
BLOCKS.group.blocks[i].checkbox:setState({isOn = false})
if #BLOCKS.group.blocks[i].data.nested > 0 then
for j = 1, #BLOCKS.group.blocks[i].data.nested do
local blockIndex, blockData = i + j, COPY_TABLE(BLOCKS.group.blocks[i].data.nested[j])
table.insert(data.scripts[CURRENT_SCRIPT].params, blockIndex, blockData)
BLOCKS.new(blockData.name, blockIndex, blockData.event, blockData.params, blockData.comment)
end
data.scripts[CURRENT_SCRIPT].params[i].nested, BLOCKS.group.blocks[i].data.nested = {}, {}
else
for j = i + 1, #BLOCKS.group.blocks do
if BLOCKS.group.blocks[i + 1].data.event then break end
table.insert(BLOCKS.group.blocks[i].data.nested, BLOCKS.group.blocks[i + 1].data)
BLOCKS.group.scrollHeight = BLOCKS.group.scrollHeight - BLOCKS.group.blocks[i + 1].block.height + 4
if BLOCKS.group.blocks[i + 1].data.event then BLOCKS.group.scrollHeight = BLOCKS.group.scrollHeight - 24 end
BLOCKS.group.blocks[i + 1]:removeSelf() table.remove(BLOCKS.group.blocks, i + 1)
table.remove(data.scripts[CURRENT_SCRIPT].params, i + 1)
end
for i = 1, #BLOCKS.group.blocks do
local y = i == 1 and 50 or BLOCKS.group.blocks[i - 1].y + BLOCKS.group.blocks[i - 1].block.height / 2 + BLOCKS.group.blocks[i].height / 2 - 4
if BLOCKS.group.blocks[i].data.event then y = y + 24 end BLOCKS.group.blocks[i].y = y BLOCKS.group[8]:setScrollHeight(BLOCKS.group.scrollHeight)
end
data.scripts[CURRENT_SCRIPT].params[i].nested = BLOCKS.group.blocks[i].data.nested
end
break
end
end
end
for i = 1, #BLOCKS.group.blocks do BLOCKS.group.blocks[i].checkbox:setState({isOn = false}) end
if INDEX_LIST ~= 2 then SET_GAME_CODE(CURRENT_LINK, data) end
end
return function(e)
if BLOCKS.group.isVisible and (ALERT or e.target.button == 'but_okay') then
if e.phase == 'began' then
display.getCurrentStage():setFocus(e.target)
e.target.click = true
if e.target.button == 'but_list'
then e.target.width, e.target.height = 103 / 1.2, 84 / 1.2
else e.target.alpha = 0.6 end
elseif e.phase == 'moved' and (math.abs(e.x - e.xStart) > 30 or math.abs(e.y - e.yStart) > 30) then
e.target.click = false
if e.target.button == 'but_list'
then e.target.width, e.target.height = 103, 84
else e.target.alpha = 0.9 end
elseif e.phase == 'ended' or e.phase == 'cancelled' then
display.getCurrentStage():setFocus(nil)
if e.target.click then
e.target.click = false
if e.target.button == 'but_list'
then e.target.width, e.target.height = 103, 84
else e.target.alpha = 0.9 end
listeners[e.target.button](e.target)
end
end
return true
end
end
|
swirl_prong_pack_leader = Creature:new {
objectName = "@mob/creature_names:swirl_prong_pack_leader",
socialGroup = "prong",
faction = "",
level = 32,
chanceHit = 0.4,
damageMin = 305,
damageMax = 320,
baseXp = 3188,
baseHAM = 8600,
baseHAMmax = 10500,
armor = 1,
resists = {135,15,15,15,-1,-1,-1,15,-1},
meatType = "meat_herbivore",
meatAmount = 125,
hideType = "hide_leathery",
hideAmount = 90,
boneType = "bone_mammal",
boneAmount = 80,
milkType = "milk_wild",
milk = 65,
tamingChance = 0.25,
ferocity = 0,
pvpBitmask = ATTACKABLE,
creatureBitmask = PACK + HERD,
optionsBitmask = AIENABLED,
diet = CARNIVORE,
templates = {"object/mobile/swirl_prong_hue.iff"},
hues = { 16, 17, 18, 19, 20, 21, 22, 23 },
scale = 1.25,
lootGroups = {},
weapons = {},
conversationTemplate = "",
attacks = {
}
}
CreatureTemplates:addCreatureTemplate(swirl_prong_pack_leader, "swirl_prong_pack_leader")
|
--[[
MIT License
Copyright (c) 2021 Michael Wiesendanger
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 mod = rgpvpw
local me = {}
mod.testCombatEventsEnemyAvoidPriestEn = me
me.tag = "TestCombatEventsEnemyAvoidPriestEn"
local testGroupName = "CombatEventsEnemyAvoidPriestEn"
local testCategory = "priest"
function me.Test()
mod.testReporter.StartTestGroup(testGroupName)
me.CollectTestCases()
mod.testReporter.PlayTestQueueWithDelay(function()
mod.testReporter.StopTestGroup() -- asyncron finish of testgroup
end)
end
function me.CollectTestCases()
mod.testReporter.AddToTestQueueWithDelay(me.TestCombatEventEnemyAvoidDevouringPlagueResisted)
mod.testReporter.AddToTestQueueWithDelay(me.TestCombatEventEnemyAvoidDevouringPlagueImmune)
mod.testReporter.AddToTestQueueWithDelay(me.TestCombatEventEnemyAvoidBlackoutResisted)
mod.testReporter.AddToTestQueueWithDelay(me.TestCombatEventEnemyAvoidBlackoutImmune)
mod.testReporter.AddToTestQueueWithDelay(me.TestCombatEventEnemyAvoidManaBurnResisted)
mod.testReporter.AddToTestQueueWithDelay(me.TestCombatEventEnemyAvoidManaBurnImmune)
mod.testReporter.AddToTestQueueWithDelay(me.TestCombatEventEnemyAvoidMindControlResisted)
mod.testReporter.AddToTestQueueWithDelay(me.TestCombatEventEnemyAvoidMindControlImmune)
mod.testReporter.AddToTestQueueWithDelay(me.TestCombatEventEnemyAvoidPsychicScreamResisted)
mod.testReporter.AddToTestQueueWithDelay(me.TestCombatEventEnemyAvoidPsychicScreamImmune)
mod.testReporter.AddToTestQueueWithDelay(me.TestCombatEventEnemyAvoidShadowWordPainResisted)
mod.testReporter.AddToTestQueueWithDelay(me.TestCombatEventEnemyAvoidShadowWordPainImmune)
mod.testReporter.AddToTestQueueWithDelay(me.TestCombatEventEnemyAvoidSilenceResisted)
mod.testReporter.AddToTestQueueWithDelay(me.TestCombatEventEnemyAvoidSilenceImmune)
mod.testReporter.AddToTestQueueWithDelay(me.TestCombatEventEnemyAvoidVampiricEmbraceResisted)
mod.testReporter.AddToTestQueueWithDelay(me.TestCombatEventEnemyAvoidVampiricEmbraceImmune)
end
function me.TestCombatEventEnemyAvoidDevouringPlagueResisted()
mod.testHelper.TestCombatEventSpellMissed(
"TestCombatEventEnemyAvoidDevouringPlagueResisted",
testCategory,
"Devouring Plague",
RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_ENEMY,
RGPVPW_CONSTANTS.MISS_TYPES.RESIST
)
end
function me.TestCombatEventEnemyAvoidDevouringPlagueImmune()
mod.testHelper.TestCombatEventSpellMissed(
"TestCombatEventEnemyAvoidDevouringPlagueImmune",
testCategory,
"Devouring Plague",
RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_ENEMY,
RGPVPW_CONSTANTS.MISS_TYPES.IMMUNE
)
end
function me.TestCombatEventEnemyAvoidBlackoutResisted()
mod.testHelper.TestCombatEventSpellMissed(
"TestCombatEventEnemyAvoidBlackoutResisted",
testCategory,
"Blackout",
RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_ENEMY,
RGPVPW_CONSTANTS.MISS_TYPES.RESIST
)
end
function me.TestCombatEventEnemyAvoidBlackoutImmune()
mod.testHelper.TestCombatEventSpellMissed(
"TestCombatEventEnemyAvoidBlackoutImmune",
testCategory,
"Blackout",
RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_ENEMY,
RGPVPW_CONSTANTS.MISS_TYPES.IMMUNE
)
end
function me.TestCombatEventEnemyAvoidManaBurnResisted()
mod.testHelper.TestCombatEventSpellMissed(
"TestCombatEventEnemyAvoidManaBurnResisted",
testCategory,
"Mana Burn",
RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_ENEMY,
RGPVPW_CONSTANTS.MISS_TYPES.RESIST
)
end
function me.TestCombatEventEnemyAvoidManaBurnImmune()
mod.testHelper.TestCombatEventSpellMissed(
"TestCombatEventEnemyAvoidManaBurnImmune",
testCategory,
"Mana Burn",
RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_ENEMY,
RGPVPW_CONSTANTS.MISS_TYPES.IMMUNE
)
end
function me.TestCombatEventEnemyAvoidMindControlResisted()
mod.testHelper.TestCombatEventSpellMissed(
"TestCombatEventEnemyAvoidMindControlResisted",
testCategory,
"Mind Control",
RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_ENEMY,
RGPVPW_CONSTANTS.MISS_TYPES.RESIST
)
end
function me.TestCombatEventEnemyAvoidMindControlImmune()
mod.testHelper.TestCombatEventSpellMissed(
"TestCombatEventEnemyAvoidMindControlImmune",
testCategory,
"Mind Control",
RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_ENEMY,
RGPVPW_CONSTANTS.MISS_TYPES.IMMUNE
)
end
function me.TestCombatEventEnemyAvoidPsychicScreamResisted()
mod.testHelper.TestCombatEventSpellMissed(
"TestCombatEventEnemyAvoidPsychicScreamResisted",
testCategory,
"Psychic Scream",
RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_ENEMY,
RGPVPW_CONSTANTS.MISS_TYPES.RESIST
)
end
function me.TestCombatEventEnemyAvoidPsychicScreamImmune()
mod.testHelper.TestCombatEventSpellMissed(
"TestCombatEventEnemyAvoidPsychicScreamImmune",
testCategory,
"Psychic Scream",
RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_ENEMY,
RGPVPW_CONSTANTS.MISS_TYPES.IMMUNE
)
end
function me.TestCombatEventEnemyAvoidShadowWordPainResisted()
mod.testHelper.TestCombatEventSpellMissed(
"TestCombatEventEnemyAvoidShadowWordPainResisted",
testCategory,
"Shadow Word: Pain",
RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_ENEMY,
RGPVPW_CONSTANTS.MISS_TYPES.RESIST
)
end
function me.TestCombatEventEnemyAvoidShadowWordPainImmune()
mod.testHelper.TestCombatEventSpellMissed(
"TestCombatEventEnemyAvoidShadowWordPainImmune",
testCategory,
"Shadow Word: Pain",
RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_ENEMY,
RGPVPW_CONSTANTS.MISS_TYPES.IMMUNE
)
end
function me.TestCombatEventEnemyAvoidSilenceResisted()
mod.testHelper.TestCombatEventSpellMissed(
"TestCombatEventEnemyAvoidSilenceResisted",
testCategory,
"Silence",
RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_ENEMY,
RGPVPW_CONSTANTS.MISS_TYPES.RESIST
)
end
function me.TestCombatEventEnemyAvoidSilenceImmune()
mod.testHelper.TestCombatEventSpellMissed(
"TestCombatEventEnemyAvoidSilenceImmune",
testCategory,
"Silence",
RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_ENEMY,
RGPVPW_CONSTANTS.MISS_TYPES.IMMUNE
)
end
function me.TestCombatEventEnemyAvoidVampiricEmbraceResisted()
mod.testHelper.TestCombatEventSpellMissed(
"TestCombatEventEnemyAvoidVampiricEmbraceResisted",
testCategory,
"Vampiric Embrace",
RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_ENEMY,
RGPVPW_CONSTANTS.MISS_TYPES.RESIST
)
end
function me.TestCombatEventEnemyAvoidVampiricEmbraceImmune()
mod.testHelper.TestCombatEventSpellMissed(
"TestCombatEventEnemyAvoidVampiricEmbraceImmune",
testCategory,
"Vampiric Embrace",
RGPVPW_CONSTANTS.SPELL_TYPES.MISSED_ENEMY,
RGPVPW_CONSTANTS.MISS_TYPES.IMMUNE
)
end
|
package.path = package.path .. ";../?.lua;?.lua;lib/?.lua"
local Component = require( "lib.component" )
local Button = Component:extend{
className = "Button",
width = 64, height = 48,
xfloat = 2, yfloat = 2
}
function Button:create ( ID, x, y, width, height )
local newOne = self:new()
newOne.ID = ID or newOne.ID
newOne.x = x or newOne.x
newOne.y = y or newOne.y
newOne.width = width or newOne.width
newOne.height = height or newOne.height
return newOne
end
function Button:handleEvent ( evt )
self:super().handleEvent ( self, evt )
end
function Button:detectEvent ( evt )
self:setHitRegion( self.x, self.y, self.width, self.height )
return self:super().detectEvent( self, evt )
end
function Button:paint ()
--self:super().paint( self )
local shadowRate = 0.15
if self.parent:isMouseHover( self ) then
if self.parent:isMousePress( self ) then
if self.parent:isFocusOn( self ) then
self.parent:drawRectWire( self.x - self.xspace + self.xfloat*(1 + shadowRate/2), self.y - self.yspace + self.yfloat*(1 + shadowRate/2), self.width + self.xspace*3 + self.xfloat*shadowRate, self.height + self.yspace*3 + self.yfloat*shadowRate, 0xff0000 )
end
self.parent:drawRect( self.x + self.xspace + self.xfloat*(1 + shadowRate/2), self.y + self.yspace + self.yfloat*(1 + shadowRate/2), self.width, self.height, 0 )
self.parent:drawRect( self.x + self.xfloat*(1 + shadowRate/2), self.y + self.yfloat*(1 + shadowRate/2), self.width, self.height, 0xffffff )
else
if self.parent:isFocusOn( self ) then
self.parent:drawRectWire( self.x - self.xspace + self.xfloat*(1 + shadowRate/2), self.y - self.yspace + self.yfloat*(1 + shadowRate/2), self.width + self.xspace*3 + self.xfloat*shadowRate, self.height + self.yspace*3 + self.yfloat*shadowRate, 0xff0000 )
end
self.parent:drawRect( self.x + self.xfloat*(1 + shadowRate/2), self.y + self.yfloat*(1 + shadowRate/2), self.width + self.xspace + self.xfloat*shadowRate, self.height + self.yspace + self.yfloat*shadowRate, 0 )
self.parent:drawRect( self.x, self.y, self.width, self.height, 0xffffff )
end
else
if self.parent:isFocusOn( self ) then
self.parent:drawRectWire( self.x - self.xspace + self.xfloat*(1 + shadowRate/2), self.y - self.yspace + self.yfloat*(1 + shadowRate/2), self.width + self.xspace*3 + self.xfloat*shadowRate, self.height + self.yspace*3 + self.yfloat*shadowRate, 0xff0000 )
end
self.parent:drawRect( self.x + self.xfloat*(1 + shadowRate/2), self.y + self.yfloat*(1 + shadowRate/2), self.width + self.xspace + self.xfloat*shadowRate, self.height + self.yspace + self.yfloat*shadowRate, 0 )
self.parent:drawRect( self.x, self.y, self.width, self.height, 0xaaaaaa )
end
end
function Button:onKeyDown( evt )
if self.parent:isKeyEntered( evt, self.parent:getPlatformConst().KEYRETURN ) then
self:onClick( evt )
end
end
return Button
|
--[[
author:{JanRoid}
time:2019-5-6
Description: 提示弹框
]]
local ViewBase = cc.load("mvc").ViewBase;
local NoticePop = class("NoticePop",ViewBase)
function NoticePop.getInstance( )
if not NoticePop.s_instance then
NoticePop.s_instance = NoticePop.new()
end
return NoticePop.s_instance
end
function NoticePop:ctor()
ViewBase.ctor(self)
self:init()
end
function NoticePop:init(viewLayout)
local root = g_NodeUtils:getRootNodeInCreator("creator/layout/notice.ccreator")
self:add(root)
self:setVisible(false)
self.m_lbTitle = self:seekNodeByName("lb_title")
self.m_txContent = self:seekNodeByName("tx_content")
self.m_btnOK = self:seekNodeByName("btn_ok")
self.m_btnTrans = self:seekNodeByName("btn_trans")
self.m_btnOK:addClickEventListener(function()
self:onOkBtnClick()
end)
self.m_btnTrans:addClickEventListener(function()
end)
local node = cc.Director:getInstance():getNotificationNode()
if node then
node:add(self)
end
end
function NoticePop:setContent(title, content)
if title then
self.m_lbTitle:setString(title)
end
if content then
self.m_txContent:setXMLData(content)
end
return self
end
function NoticePop:addBtnListener(obj,func)
self.m_obj = obj
self.m_func = func
return self
end
function NoticePop:onOkBtnClick( )
if self.m_func then
self.m_func(self.m_obj)
end
self:hidden()
end
function NoticePop:show()
if not self:isVisible() then
self:setVisible(true)
end
end
function NoticePop:hidden()
if self:isVisible() then
self:setVisible(false)
end
self:clear()
end
function NoticePop:clear( )
self.m_func = nil
self.m_obj = nil
end
return NoticePop
|
local isRequestAnim = false
local requestedemote = ''
-- Some of the work here was done by Super.Cool.Ninja / rubbertoe98
-- https://forum.fivem.net/t/release-nanimstarget/876709
-----------------------------------------------------------------------------------------------------
-- Commands / Events --------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------
if Config.SharedEmotesEnabled then
RegisterCommand('nearby', function(source, args, raw)
if #args > 0 then
local emotename = string.lower(args[1])
target, distance = GetClosestPlayer()
if(distance ~= -1 and distance < 3) then
if DP.Shared[emotename] ~= nil then
dict, anim, ename = table.unpack(DP.Shared[emotename])
TriggerServerEvent("ServerEmoteRequest", GetPlayerServerId(target), emotename)
SimpleNotify(Config.Languages[lang]['sentrequestto']..GetPlayerName(target).." ~w~(~g~"..ename.."~w~)")
else
EmoteChatMessage("'"..emotename.."' "..Config.Languages[lang]['notvalidsharedemote'].."")
end
else
SimpleNotify(Config.Languages[lang]['nobodyclose'])
end
else
MearbysOnCommand()
end
end, false)
end
RegisterNetEvent("SyncPlayEmote")
AddEventHandler("SyncPlayEmote", function(emote, player)
EmoteCancel()
Wait(300)
-- wait a little to make sure animation shows up right on both clients after canceling any previous emote
if DP.Shared[emote] ~= nil then
if OnEmotePlay(DP.Shared[emote]) then end return
elseif DP.Dances[emote] ~= nil then
if OnEmotePlay(DP.Dances[emote]) then end return
end
end)
RegisterNetEvent("SyncPlayEmoteSource")
AddEventHandler("SyncPlayEmoteSource", function(emote, player)
-- Thx to Poggu for this part!
local pedInFront = GetPlayerPed(GetClosestPlayer())
local heading = GetEntityHeading(pedInFront)
local coords = GetOffsetFromEntityInWorldCoords(pedInFront, 0.0, 1.0, 0.0)
if (DP.Shared[emote]) and (DP.Shared[emote].AnimationOptions) then
local SyncOffsetFront = DP.Shared[emote].AnimationOptions.SyncOffsetFront
if SyncOffsetFront then
coords = GetOffsetFromEntityInWorldCoords(pedInFront, 0.0, SyncOffsetFront, 0.0)
end
end
SetEntityHeading(PlayerPedId(), heading - 180.1)
SetEntityCoordsNoOffset(PlayerPedId(), coords.x, coords.y, coords.z, 0)
EmoteCancel()
Wait(300)
if DP.Shared[emote] ~= nil then
if OnEmotePlay(DP.Shared[emote]) then end return
elseif DP.Dances[emote] ~= nil then
if OnEmotePlay(DP.Dances[emote]) then end return
end
end)
RegisterNetEvent("ClientEmoteRequestReceive")
AddEventHandler("ClientEmoteRequestReceive", function(emotename, etype)
isRequestAnim = true
requestedemote = emotename
if etype == 'Dances' then
_,_,remote = table.unpack(DP.Dances[requestedemote])
else
_,_,remote = table.unpack(DP.Shared[requestedemote])
end
PlaySound(-1, "NAV", "HUD_AMMO_SHOP_SOUNDSET", 0, 0, 1)
SimpleNotify(Config.Languages[lang]['doyouwanna']..remote.."~w~)")
end)
Citizen.CreateThread(function()
while true do
Citizen.Wait(5)
if IsControlJustPressed(1, 246) and isRequestAnim then
target, distance = GetClosestPlayer()
if(distance ~= -1 and distance < 3) then
if DP.Shared[requestedemote] ~= nil then
_,_,_,otheremote = table.unpack(DP.Shared[requestedemote])
elseif DP.Dances[requestedemote] ~= nil then
_,_,_,otheremote = table.unpack(DP.Dances[requestedemote])
end
if otheremote == nil then otheremote = requestedemote end
TriggerServerEvent("ServerValidEmote", GetPlayerServerId(target), requestedemote, otheremote)
isRequestAnim = false
else
SimpleNotify(Config.Languages[lang]['nobodyclose'])
end
elseif IsControlJustPressed(1, 182) and isRequestAnim then
SimpleNotify(Config.Languages[lang]['refuseemote'])
isRequestAnim = false
end
end
end)
-----------------------------------------------------------------------------------------------------
------ Functions and stuff --------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------
function GetPlayerFromPed(ped)
for _,player in ipairs(GetActivePlayers()) do
if GetPlayerPed(player) == ped then
return player
end
end
return -1
end
function GetPedInFront()
local player = PlayerId()
local plyPed = GetPlayerPed(player)
local plyPos = GetEntityCoords(plyPed, false)
local plyOffset = GetOffsetFromEntityInWorldCoords(plyPed, 0.0, 1.3, 0.0)
local rayHandle = StartShapeTestCapsule(plyPos.x, plyPos.y, plyPos.z, plyOffset.x, plyOffset.y, plyOffset.z, 10.0, 12, plyPed, 7)
local _, _, _, _, ped2 = GetShapeTestResult(rayHandle)
return ped2
end
function MearbysOnCommand(source, args, raw)
local NearbysCommand = ""
for a in pairsByKeys(DP.Shared) do
NearbysCommand = NearbysCommand .. ""..a..", "
end
EmoteChatMessage(NearbysCommand)
EmoteChatMessage(Config.Languages[lang]['emotemenucmd'])
end
function SimpleNotify(message)
SetNotificationTextEntry("STRING")
AddTextComponentString(message)
DrawNotification(0,1)
end
function GetClosestPlayer()
local players = GetPlayers()
local closestDistance = -1
local closestPlayer = -1
local ply = PlayerPedId()
local plyCoords = GetEntityCoords(ply, 0)
for index,value in ipairs(players) do
local target = GetPlayerPed(value)
if(target ~= ply) then
local targetCoords = GetEntityCoords(GetPlayerPed(value), 0)
local distance = #(targetCoords - plyCoords)
if(closestDistance == -1 or closestDistance > distance) then
closestPlayer = value
closestDistance = distance
end
end
end
return closestPlayer, closestDistance
end
function GetPlayers()
local players = {}
for i = 0, 255 do
if NetworkIsPlayerActive(i) then
table.insert(players, i)
end
end
return players
end
|
local day_name_to_number = {
Sunday = 1,
Monday = 2,
Tuesday = 3,
Wednesday = 4,
Thursday = 5,
Friday = 6,
Saturday = 7
}
local function matching_days(config)
local meetup_day = day_name_to_number[config.day]
local days = {}
for day = 1, math.huge do
local date = os.date('*t', os.time({
year = config.year,
month = config.month,
day = day
}))
if date.month ~= config.month then break end
if date.wday == meetup_day then
table.insert(days, day)
end
end
return days
end
local function first_teenth(t)
for _, v in ipairs(t) do
if v > 12 then return v end
end
end
local function last(t)
return t[#t]
end
local function ordinal(t, which)
return t[({
first = 1,
second = 2,
third = 3,
fourth = 4
})[which]]
end
return function(config)
local days = matching_days(config)
if config.week == 'teenth' then
return first_teenth(days)
elseif config.week == 'last' then
return last(days)
else
return ordinal(days, config.week)
end
end
|
function main()
print("hello world")
end
main()
|
database = {
levels = {
[248972157] = "level.lua"
},
entities = {
[591432690] = "player.lua", -- ENTITY_PLAYER
[315271780] = "ground.lua", -- ENTITY_GROUND
[1675181212] = "groundRough.lua", -- ENTITY_GROUND_ROUGH
[592045845] = "portal.lua", -- ENTITY_PORTAL,
[2979648629] = "waitingPlayers.lua", -- ENTITY_WAITING_PLAYERS
[491081606] = "player1Win.lua", -- ENTITY_PLAYER_ONE_WIN
[2872810798] = "player2Win.lua", -- ENTITY_PLAYER_TWO_WIN
[1316782920] = "youLose.lua",
[2252448813] = "youWin.lua"
},
meshes = {
[3415080175] = "spaceCraft1.obj", -- MESH_SPACECRAFT
[3061288721] = "floor.obj", -- MESH_FLOOR
[2381128972] = "groundTile.obj", -- MESH_GROUND
[4214878900] = "groundTileRough.obj", -- MESH_GROUND_ROUGH
[2795621949] = "portal.obj", -- MESH_PORTAL
[2992890141] = "waiting-players.obj", -- MESH_WAITING_PLAYERS
[1317505198] = "player1Win.obj", -- MESH_PLAYER_ONE_WIN
[1730504262] = "player2Win.obj", -- MESH_PLAYER_TWO_WIN
[1982698336] = "youLose.obj",
[3313820357] = "youWin.obj"
},
textures = {
[2300579869] = {
file = "floor.png"
}
},
shaders = {
[2946951896] = { -- SHADER_DEFAULT
fragFile = "simple_frag.glsl",
vertFile = "simple_vert.glsl",
uniforms = {
"material.ambient",
"material.diffuse",
"material.specular"
}
}
},
sounds = {
[2016780361] = { -- SOUND_BACKGROUND_MUSIC
file = "background.ogg"
},
[3989746563] = { -- SOUND_POWERUP
file = "powerup.wav"
}
},
events = {
[1994444546] = { -- EVENT_TYPE_PLAYER_CONNECTED
args = {
"clientId"
}
},
[415743068] = { -- EVENT_TYPE_PLAYER_DISCONNECTED
args = {
"clientId"
}
},
[1770460267] = { -- EVENT_TYPE_INPUT_PLAYER
args = {
"entityId",
"inputBitmask"
}
},
[791803502] = { -- EVENT_TYPE_ENTITY_SPAWN
args = {
"entityId",
"prototypeId"
}
},
[697357692] = { -- EVENT_TYPE_ASSIGN_PLAYER
args = {
"entityId",
"clientId"
}
},
[501658455] = { -- EVENT_TYPE_ENTITY_DESTROY
args = {
"entityId"
}
},
[2577080706] = { -- MESSAGE_PHYSICS_SYNC
args = {
"entityId",
"posX",
"posY",
"posZ",
"rotX",
"rotY",
"rotZ",
"velX",
"velZ",
"velA"
}
},
[3819351460] = { -- EVENT_TYPE_LEVEL_LOAD_SERVER
args = {
"levelId"
}
},
[3302156521] = { -- EVENT_TYPE_PLAY_SOUND
args = {
"soundId"
}
},
[3655313229] = { -- EVENT_TYPE_PLAYER_WIN
args = {
"entityId"
}
}
}
}
|
padez = {"months", "months"}
months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}
|
-- Copyright (c) Jérémie N'gadi
--
-- All rights reserved.
--
-- Even if 'All rights reserved' is very clear :
--
-- You shall not use any piece of this software in a commercial product / service
-- You shall not resell this software
-- You shall not provide any facility to install this particular software in a commercial product / service
-- If you redistribute this software, you must link to ORIGINAL repository at https://github.com/ESX-Org/es_extended
-- This copyright should appear in every part of the project code
self.Id = 0
self.Data = {}
self.Cache = {
player = {
ped = 0,
coords = vector3(0.0, 0.0, 0.0)
},
current = {
marker = {},
npc = {},
},
using = {},
}
self.Register = function(data)
local idx = -1
for i=1, #self.Data, 1 do
if self.Data[i].name == data.name then
idx = i
break
end
end
if self.Id >= 65535 then
data.__id = 1
else
data.__id = self.Id + 1
end
data.size = (type(data.size) == 'number') and {x = data.size, y = data.size, z = data.size} or data.size
if data.faceCamera == nil then data.faceCamera = false end
if data.bobUpAndDown == nil then data.bobUpAndDown = false end
if data.rotate == nil then data.rotate = false end
self.Id = data.__id
if idx == -1 then
self.Data[#self.Data + 1] = data
else
self.Data[idx] = data
end
end
|
package.path = "src/?.lua;" .. package.path
require("busted.runner")()
require("assertions.appender_assertions")
local SelectAppender = require("exasolvs.queryrenderer.SelectAppender")
local function assert_yields(expected, original_query)
assert.append_yields(SelectAppender, expected, original_query)
end
local function assert_select_error(expected, original_query)
assert.append_error(SelectAppender, expected, original_query)
end
describe("SelectAppender", function()
it("renders SELECT *", function()
local original_query = {
type = "select",
from = {type = "table", name = "T1"}
}
assert_yields('SELECT * FROM "T1"', original_query)
end)
it("renders SELECT * from a table with given schema", function()
local original_query = {
type = "select",
from = {type = "table", schema = "S1", name = "T1"}
}
assert_yields('SELECT * FROM "S1"."T1"', original_query)
end)
it("renders a SELECT with a table and two columns", function()
local original_query = {
type = "select",
selectList = {
{type = "column", name = "C1", tableName = "T1"},
{type = "column", name = "C2", tableName = "T1"}
},
from = {type = "table", name = "T1"}
}
assert_yields('SELECT "T1"."C1", "T1"."C2" FROM "T1"', original_query)
end)
describe("renders literal", function()
local literals = {
{
input = {type = "literal_null"},
expected = "null"
},
{
input = {type = "literal_string", value = "a_string"},
expected = "'a_string'"
},
{
input = {type = "literal_double", value = 3.1415},
expected = "3.1415"},
{
input = {type = "literal_exactnumeric", value = 9876543210},
expected = "9876543210"
},
{
input = {type = "literal_bool", value = true},
expected = "true"
},
{
input = {type = "literal_date", value = "2015-12-01"},
expected = "DATE '2015-12-01'"
},
{
input = {type = "literal_timestamp", value = "2015-12-01 12:01:01.1234"},
expected = "TIMESTAMP '2015-12-01 12:01:01.1234'"
},
{
input = {type = "literal_timestamputc", value = "2015-12-01 12:01:01.1234"},
expected = "TIMESTAMP '2015-12-01 12:01:01.1234'"
}
}
for _, literal in ipairs(literals) do
it("(" .. literal.input.type .. ") " .. tostring(literal.input.value), function()
local original_query = {
type = "select",
selectList = { literal.input },
from = {type = "table", name = "T1"}
}
assert_yields('SELECT ' .. literal.expected ..' FROM "T1"', original_query)
end)
end
end)
it("renders a single predicate filter", function()
local original_query = {
type = "select",
selectList = {{type = "column", name ="NAME", tableName = "MONTHS"}},
from = {type = "table", name = "MONTHS"},
filter = {
type = "predicate_greater",
left = {type = "column", name="DAYS_IN_MONTH", tableName = "MONTHS"},
right = {type = "literal_exactnumeric", value = "30"}
}
}
assert_yields('SELECT "MONTHS"."NAME" FROM "MONTHS" WHERE ("MONTHS"."DAYS_IN_MONTH" > 30)', original_query)
end)
it("renders nested predicate filter", function()
local original_query = {
type = "select",
selectList = {{type = "column", name ="NAME", tableName = "MONTHS"}},
from = {type = "table", name = "MONTHS"},
filter = {
type = "predicate_and",
expressions = {{
type = "predicate_equal",
left = {type = "literal_string", value = "Q3"},
right = {type = "column", name="QUARTER", tableName = "MONTHS"}
}, {
type = "predicate_greater",
left = {type = "column", name="DAYS_IN_MONTH", tableName = "MONTHS"},
right = {type = "literal_exactnumeric", value = "30"}
}
}
}
}
assert_yields('SELECT "MONTHS"."NAME" FROM "MONTHS" WHERE ((\'Q3\' = "MONTHS"."QUARTER") '
.. 'AND ("MONTHS"."DAYS_IN_MONTH" > 30))', original_query)
end)
it("renders a unary NOT filter", function()
local original_query = {
type = "select",
selectList = {{type = "column", name = "NAME", tableName = "MONTHS"}},
from = {type = "table", name = "MONTHS"},
filter = {
type = "predicate_not",
expression = {
type = "predicate_equal",
left = {type = "literal_string", value = "Q3"},
right = {type = "column", name="QUARTER", tableName = "MONTHS"}
},
}
}
assert_yields('SELECT "MONTHS"."NAME" FROM "MONTHS" WHERE (NOT (\'Q3\' = "MONTHS"."QUARTER"))',
original_query)
end)
it("renders a scalar function in a filter in the WHERE clause", function()
local original_query = {
type = "select",
selectList = {
{type = "column", name = "LASTNAME", tableName = "PEOPLE"}
},
from = {type = "table", name = "PEOPLE"},
filter = {
type = "predicate_equal",
left = {
type = "function_scalar",
name = "LOWER",
arguments = {
{type = "column", name = "FIRSTNAME", tableName = "PEOPLE"},
}
},
right = {type = "literal_string", value = "eve"}
}
}
assert_yields([[SELECT "PEOPLE"."LASTNAME" FROM "PEOPLE" WHERE (LOWER("PEOPLE"."FIRSTNAME") = 'eve')]],
original_query)
end)
it("renders the predicate IN in the where clause", function()
local original_query = {
type = "select",
selectList = {{type = "literal_string", value = "hello"}},
from = {type = "table", name = "T1"},
filter = {
type = "predicate_in_constlist",
expression = {type = "column", name = "C1", tableName = "T1"},
arguments = {
{type = "literal_string", value = "A1"},
{type = "literal_string", value = "A2"}
}
}
}
assert_yields([[SELECT 'hello' FROM "T1" WHERE ("T1"."C1" IN ('A1', 'A2'))]], original_query)
end)
it("renders a sub-SELECT", function()
local original_query = {
type = "select",
selectList = {
{type = "column", name = "NAME", tableName = "FRUITS"},
{type = "column", name = "SUGAR_PERCENTAGE", tableName = "FRUITS"}
},
from = {type = "table", name = "FRUITS"},
filter = {
type = "predicate_greater",
left = {type = "column", name = "SUGAR_PERCENTAGE", tableName = "FRUITS"},
right = {
type = "sub_select",
selectList ={{type = "column", name = "SUGAR_PERCENTAGE", tableName = "SNACKS"}},
from = {type = "table", name = "SNACKS"},
filter = {
type = "predicate_equal",
left = {type = "column", name = "CATEGORY", tableName = "SNACKS"},
right = {type = "literal_string", value = "desert"}
}
}
}
}
assert_yields('SELECT "FRUITS"."NAME", "FRUITS"."SUGAR_PERCENTAGE" FROM "FRUITS"'
.. ' WHERE ("FRUITS"."SUGAR_PERCENTAGE"'
.. ' > ('
.. 'SELECT "SNACKS"."SUGAR_PERCENTAGE" FROM "SNACKS" WHERE ("SNACKS"."CATEGORY" = \'desert\'))'
.. ')', original_query)
end)
it("renders a JOIN clause", function()
for join_type, join_keyword in pairs(SelectAppender.get_join_types()) do
local original_query = {
type = "select",
selectList = {
{type = "column", name = "AMOUNT", tableName = "ORDERS"},
{type = "column", name = "NAME", tableName = "ITEMS"},
},
from = {
type = "join",
join_type = join_type,
left = {type = "table", name = "ORDERS"},
right = {type = "table", name = "ITEMS"},
condition = {
type = "predicate_equal",
left = {type = "column", name = "ITEM_ID", tableName = "ORDERS"},
right = {type = "column", name = "ITEM_ID", tableName = "ITEMS"}
}
}
}
assert_yields('SELECT "ORDERS"."AMOUNT", "ITEMS"."NAME"'
.. ' FROM "ORDERS" ' .. join_keyword .. ' JOIN "ITEMS"'
.. ' ON ("ORDERS"."ITEM_ID" = "ITEMS"."ITEM_ID")', original_query)
end
end)
describe("renders a LIMIT clause", function()
it("without OFFSET", function()
local original_query = {
type = "select",
from = {
type = "table", name = "T1"
},
limit = {numElements = 10}
}
assert_yields('SELECT * FROM "T1" LIMIT 10', original_query)
end)
it("with OFFSET", function()
local original_query = {
type = "select",
from = {
type = "table", name = "T2"
},
limit = {numElements = 20, offset = 8}
}
assert_yields('SELECT * FROM "T2" LIMIT 20 OFFSET 8', original_query)
end)
end)
describe("renders an ORDER BY clause", function()
local unsorted_query = {
type = "select",
selectList = {{type = "column", name = "NAME", tableName = "USERS"}},
from = {type = "table", name = "USERS"},
}
local variants = {
{
order = {
{type = "order_by_element", expression = {type = "column", name = "ID", tableName = "USERS"}}
},
expected = 'ORDER BY "USERS"."ID"'
},
{
order = {
{
type = "order_by_element",
expression = {type = "column", name = "NUMBER", tableName = "USERS"},
isAscending = true
}
},
expected = 'ORDER BY "USERS"."NUMBER" ASC'
},
{
order = {
{
type = "order_by_element",
expression = {type = "column", name = "NUMBER", tableName = "USERS"},
isAscending = false
}
},
expected = 'ORDER BY "USERS"."NUMBER" DESC'
},
{
order = {
{
type = "order_by_element",
expression = {type = "column", name = "NUMBER", tableName = "USERS"},
nullsLast = true
}
},
expected = 'ORDER BY "USERS"."NUMBER" NULLS LAST'
},
{
order = {
{
type = "order_by_element",
expression = {type = "column", name = "NUMBER", tableName = "USERS"},
nullsLast = false
}
},
expected = 'ORDER BY "USERS"."NUMBER" NULLS FIRST'
},
{
order = {
{
type = "order_by_element",
expression = {type = "column", name = "ID", tableName = "USERS"},
},
{
type = "order_by_element",
expression = {type = "column", name = "NUMBER", tableName = "USERS"},
nullsLast = false,
isAscending = true
}
},
expected = 'ORDER BY "USERS"."ID", "USERS"."NUMBER" ASC NULLS FIRST'
},
}
for _, variant in ipairs(variants) do
it(variant.expected, function()
local original_query = unsorted_query
original_query.orderBy = variant.order
assert_yields('SELECT "USERS"."NAME" FROM "USERS" ' .. variant.expected, original_query)
end)
end
end)
it("raises an error if the WHERE clause type is unknown", function()
local original_query = {
type = "select",
selectList = {
{type = "literal_bool", value = false}
},
from = {
type = "unknown"
}
}
assert_select_error("unknown SQL FROM clause type", original_query)
end)
it("raises an error if the JOIN type is unknown", function()
local original_query = {
type = "select",
selectList = {
{type = "literal_bool", value = false}
},
from = {
type = "join",
join_type = "join_type_illegal"
}
}
assert_select_error("unknown join type 'join_type_illegal'", original_query)
end)
it("raises an error if the predicate type is unknown", function()
local original_query = {
type = "select",
selectList = {
{type = "predicate_illegal"}
}
}
assert_select_error("unknown SQL predicate type 'predicate_illegal'", original_query)
end)
it("raises an error if the expression type is unknown", function()
local original_query = {
type = "select",
selectList = {
{type = "illegal expression type"}
},
}
assert_select_error("unknown SQL expression type 'illegal expression type'", original_query)
end)
it("raises an error if the data type is unknown", function()
local original_query = {
type = "select",
selectList = {
{
type = "function_scalar_cast", name = "CAST",
dataType = {type = "illegal"},
arguments = {
{type = "literal_string", value = "100"}
}
}
}
}
assert_select_error("unknown data type", original_query)
end)
end)
|
module("logger", package.seeall)
require 'lib.date'
function to_s(level, ...)
local args = {...}
-- first argument is format string.
local str = args[1]
table.remove(args, 1)
-- replace %s to string variable
for k, v in pairs(args) do
local to_str = v
if type(v) == "table" then
to_str = table.tostring(v)
end
str = string.format(str, to_str)
end
local t = date.now()
-- [Time][Level] [LogContent]
local f = "[%s][%s] %s"
local result = string.format(f, t, level, str)
return result
end
function info(...)
local s = to_s("INFO", ...)
print(s)
end
function error(...)
local s = to_s("ERROR", ...)
print(s)
end
|
-- $Id: //depot/Projects/StarWars_Expansion/Run/Data/Scripts/AI/SpaceMode/TurboAttackLocation.lua#2 $
--/////////////////////////////////////////////////////////////////////////////////////////////////
--
-- (C) Petroglyph Games, Inc.
--
--
-- ***** ** * *
-- * ** * * *
-- * * * * *
-- * * * * * * * *
-- * * *** ****** * ** **** *** * * * ***** * ***
-- * ** * * * ** * ** ** * * * * ** ** ** *
-- *** ***** * * * * * * * * ** * * * *
-- * * * * * * * * * * * * * * *
-- * * * * * * * * * * ** * * * *
-- * ** * * ** * ** * * ** * * * *
-- ** **** ** * **** ***** * ** *** * *
-- * * *
-- * * *
-- * * *
-- * * * *
-- **** * *
--
--/////////////////////////////////////////////////////////////////////////////////////////////////
-- C O N F I D E N T I A L S O U R C E C O D E -- D O N O T D I S T R I B U T E
--/////////////////////////////////////////////////////////////////////////////////////////////////
--
-- $File: //depot/Projects/StarWars_Expansion/Run/Data/Scripts/AI/SpaceMode/TurboAttackLocation.lua $
--
-- Original Author: James Yarrow
--
-- $Author: Andre_Arsenault $
--
-- $Change: 55814 $
--
-- $DateTime: 2006/10/02 16:55:52 $
--
-- $Revision: #2 $
--
--/////////////////////////////////////////////////////////////////////////////////////////////////
require("pgevents")
--
-- Plan for corvettes to exploit their anti-fighter capabilities while using turbo or power to weapons.
--
function Definitions()
DebugMessage("%s -- In Definitions", tostring(Script))
Category = "Turbo_Attack_Location"
TaskForce = {
-- First Task Force
{
"MainForce"
,"DenyHeroAttach"
,"Corellian_Corvette | Corellian_Gunboat | Tartan_Patrol_Cruiser | Slave_I | Sundered_Heart = 1, 3"
}
}
IgnoreTarget = true
AllowEngagedUnits = true
needs_turbo = false
was_attacked = false
DebugMessage("%s -- Done Definitions", tostring(Script))
end
function MainForce_Thread()
BlockOnCommand(MainForce.Produce_Force());
QuickReinforce(PlayerObject, AITarget, MainForce)
MainForce.Enable_Attack_Positioning(false)
-- Move into position while avoiding threat and without stopping for attacks on the way
needs_turbo = true
Try_Ability(MainForce, "Turbo")
BlockOnCommand(MainForce.Move_To(AITarget))
MainForce.Activate_Ability("Turbo", false)
needs_turbo = false
-- Clear out the area, while it remains favorable for this type of attack.
MainForce.Set_As_Goal_System_Removable(false)
while (EvaluatePerception("Good_Turbo_Attack_Location_Opportunity", PlayerObject, AITarget) > 0) do
enemy = Find_Nearest(MainForce, "SmallShip", PlayerObject, false)
--enemy = Find_Nearest(MainForce, "Fighter", PlayerObject, false)
if TestValid(enemy) then -- FIX and (MainForce.Get_Distance(enemy) < 1000) then
BlockOnCommand(MainForce.Attack_Target(enemy))
else
break
end
end
-- Try to flee to a safe spot after the tactical strike
if was_attacked then
escape_loc = FindTarget(MainForce, "Space_Area_Is_Hidden", "Tactical_Location", 1.0, 5000.0)
if escape_loc then
needs_turbo = true
MainForce.Activate_Ability("Turbo", true)
BlockOnCommand(MainForce.Move_To(escape_loc))
end
end
ScriptExit()
end
-- Make sure that units don't sit idle at the end of their move order, waiting for others
function MainForce_Unit_Move_Finished(tf, unit)
if Attacking and not unit.Has_Attack_Target() then
DebugMessage("%s -- %s reached end of move, giving new order", tostring(Script), tostring(unit))
-- Assist the tf with whatever is holding it up
kill_target = FindDeadlyEnemy(tf)
if TestValid(kill_target) then
unit.Attack_Target(kill_target)
else
unit.Attack_Move(tf)
end
end
end
-- Try to recover use of turbo or power to weapons if it was lost while we were trying to use it.
function MainForce_Unit_Ability_Ready(tf, unit, ability)
--MessageBox("%s -- Recovering %s for %s!", tostring(Script), ability, tostring(unit))
if ability == "Turbo" and needs_turbo then
unit.Activate_Ability("Turbo", true)
end
-- Default handler behavior is still desired
Default_Unit_Ability_Ready(tf, unit, ability)
end
-- Register if we were attacked, and use default behavior as well.
function MainForce_Unit_Damaged(tf, unit, attacker, deliberate)
if deliberate then
was_attacked = true
end
-- Default handler behavior is still desired
Default_Unit_Damaged(tf, unit, attacker, deliberate)
end
|
local MaximumNumberOfBags = 6;
local MAJOR, MINOR = "WowApi-1.0", 1
local WowApiHelper, oldminor = LibStub:NewLibrary(MAJOR, MINOR)
if not WowApiHelper then return end
WowApiHelper.Const = {
["CostType"] = {
Mana = 0,
SoulShards = 7
}
}
--[[
Count in the bag the numer of availabled items
]]
function WowApiHelper:GetItemCount(itemId)
local itemCount = 0
local numberItemId = tonumber(itemId)
for bagIndx = 1, MaximumNumberOfBags do
local itemByBag = GetContainerNumSlots(bagIndx)
if itemByBag > 0 then
for indx = 1, itemByBag do
local itemLink = GetContainerItemLink(bagIndx, indx)
if (itemLink) then
local _, itemID = strsplit(":", itemLink)
if (tonumber(itemID) == numberItemId) then
itemCount = itemCount + 1
end
end
end
end
end
return itemCount
end
--[[
Gets the specific cost of a spell
]]
function WowApiHelper:GetSpellCostByType(spellId, costType)
local cost = GetSpellPowerCost(spellId);
for indx, data in pairs(cost) do
if (data.type == costType) then
return data.cost;
end
end
return nil;
end
|
AddCSLuaFile()
local function null() end
properties.Add("photon_siren", {
MenuLabel = "Siren Model",
Order = 2,
MenuIcon = "photon/ui/menu-siren.png",
Filter = function(self, ent, ply)
if not IsValid(ent) then
return false
end
if not ent:IsVehicle() then
return false
end
if not ent:Photon() then
return false
end
if not ent:IsEMV() then
return false
end
return true
end,
MenuOpen = function(self, option, ent)
local sirens = EMVU.GetSirenTable()
local submenu = option:AddSubMenu()
local primarySubmenu = submenu:AddSubMenu("Primary", null)
local secondarySubmenu = submenu:AddSubMenu("Secondary", null)
local categories = {}
categories["Other"] = true
for _, siren in pairs(sirens) do
if siren.Category then
categories[siren.Category] = true
end
end
for category, siren in SortedPairs(categories) do
categories[category] = {primarySubmenu:AddSubMenu(category, null), secondarySubmenu:AddSubMenu(category, null)}
end
for idx, siren in ipairs(sirens) do
local key = tostring(idx)
local category = siren.Category or "Other"
local selected = tostring(ent:Photon_SirenSet()) == key
categories[category][1]:AddOption(siren.Name, function()
EMVU.Net:SirenSet(idx, ent, false)
end):SetChecked(selected)
if not selected then
categories[category][2]:AddOption(siren.Name, function()
EMVU.Net:SirenSet(idx, ent, true)
end):SetChecked(tostring(ent:Photon_AuxSirenSet()) == key)
end
end
primarySubmenu:AddOption("None", function()
EMVU.Net:SirenSet(0, ent, false)
end):SetChecked(ent:Photon_SirenSet() == 0)
secondarySubmenu:AddOption("None", function()
EMVU.Net:SirenSet(0, ent, true)
end):SetChecked(ent:Photon_AuxSirenSet() == 0)
end,
Action = null
})
properties.Add("photon_liveries", {
MenuLabel = "Vehicle Livery",
Order = 3,
MenuIcon = "photon/ui/menu-livery.png",
Filter = function(self, ent, ply)
if not IsValid(ent) then
return false
end
if not ent:Photon() then
return false
end
if not ent:IsEMV() then
return false
end
if not ent.VehicleName then
return false
end
if not ply:InVehicle() then
return false
end
if ply:GetVehicle() ~= ent then
return false
end
local liveries = EMVU.Liveries[ent.VehicleName]
if not liveries then
return false
end
return true
end,
MenuOpen = function(self, option, ent)
local liveries = EMVU.Liveries[ent.VehicleName]
local lCount = table.Count(liveries)
local submenu = option:AddSubMenu()
for key, data in SortedPairs(liveries) do
local category = lCount > 1 and table.Count(data) > 1 and submenu:AddSubMenu(key) or submenu
for name, _ in SortedPairs(data) do
category:AddOption(name, function()
EMVU.Net:Livery(key, name)
end)
end
end
end,
Action = null
})
properties.Add("photon_autoskin", {
MenuLabel = "Vehicle Liveries",
Order = 3,
MenuIcon = "photon/ui/menu-livery.png",
Filter = function(self, ent, ply)
if not IsValid(ent) then
return false
end
if not ent:Photon() then
return false
end
if not ent:IsEMV() then
return false
end
if not ent.VehicleName then
return false
end
local mdl = ent:GetModel()
local mdlId = Photon.AutoSkins.TranslationTable[mdl]
if not mdlId then
return false
end
if not istable(Photon.AutoSkins.Available[mdlId]) then
return false
end
return true
end,
MenuOpen = function(self, option, ent)
local mdl = ent:GetModel()
local mdlId = Photon.AutoSkins.TranslationTable[mdl]
local skinTable = Photon.AutoSkins.Available[mdlId]
local submenu = option:AddSubMenu()
for category, subSkins in pairs(skinTable) do
if category ~= "/" then
local categoryMenu = submenu:AddSubMenu(category, null)
for _, skinInfo in pairs(subSkins) do
categoryMenu:AddOption(skinInfo.Name, function()
EMVU.Net.ApplyAutoSkin(ent, skinInfo.Texture)
end)
end
end
end
if istable(skinTable["/"]) then
for _, skinInfo in pairs(skinTable["/"]) do
submenu:AddOption(skinInfo.Name, function()
EMVU.Net.ApplyAutoSkin(ent, skinInfo.Texture)
end)
end
end
end,
Action = null
})
properties.Add("photon_licenseplates", {
MenuLabel = "License Plate",
Order = 4,
MenuIcon = "photon/ui/menu-license.png",
Filter = function(self, ent, ply)
if not IsValid(ent) then
return false
end
if not ent:Photon() then
return false
end
if not ent:IsEMV() then
return false
end
if not ent:EMVName() then
return false
end
if not ent:Photon_LicensePlate() then
return false
end
return true
end,
MenuOpen = function(self, option, ent)
local skinTable = Photon.LicensePlates.Available
local submenu = option:AddSubMenu()
for category, subSkins in pairs(skinTable) do
if category ~= "/" then
local categoryMenu = submenu:AddSubMenu(category, null)
for _, skinInfo in pairs(subSkins) do
categoryMenu:AddOption(skinInfo.Name, function()
EMVU.Net.ApplyLicenseMaterial(ent, skinInfo.Texture)
end)
end
end
end
if istable(skinTable["/"]) then
for _, skinInfo in pairs(skinTable["/"]) do
submenu:AddOption(skinInfo.Name, function()
EMVU.Net.ApplyLicenseMaterial(ent, skinInfo.Texture)
end)
end
end
end,
Action = null
})
properties.Add("photon_wheels", {
MenuLabel = "Wheel Style",
Order = 5,
MenuIcon = "photon/ui/menu-wheel.png",
Filter = function(self, ent, ply)
if not IsValid(ent) then
return false
end
if not ent:Photon() then
return false
end
if not ent:Photon_WheelEnabled() then
return false
end
return true
end,
MenuOpen = function(self, option, ent)
local options = Photon.Vehicles.WheelOptions[ent.VehicleName]
local submenu = option:AddSubMenu()
local selected = tostring(ent:Photon_WheelOption())
for index, data in pairs(options) do
submenu:AddOption(data.Name, function()
EMVU.Net:WheelOption(index, ent)
end):SetChecked(tostring(index) == selected)
end
end,
Action = null
})
properties.Add("photon_preset", {
MenuLabel = "Emergency Lights",
Order = 1,
MenuIcon = "photon/ui/menu-lights.png",
Filter = function(self, ent, ply)
if not IsValid(ent) then
return false
end
if not ent:Photon() then
return false
end
if not ent:IsEMV() then
return false
end
if not ent:Photon_PresetEnabled() then
return false
end
local options = EMVU.PresetIndex[ent.VehicleName]
if not options then
return false
end
if not istable(options) then
return false
end
if #options <= 1 then
return false
end
return true
end,
MenuOpen = function(self, option, ent)
local options = EMVU.PresetIndex[ent.VehicleName]
local submenu = option:AddSubMenu()
local selected = tostring(ent:Photon_ELPresetOption())
for idx, data in ipairs(options) do
submenu:AddOption(data.Name, function()
EMVU.Net:Preset(idx, ent)
end):SetChecked(tostring(idx) == selected)
end
end,
Action = null
})
properties.Add("photon_selection", {
MenuLabel = "Equipment",
Order = 1,
MenuIcon = "photon/ui/menu-lights.png",
Filter = function(self, ent, ply)
if not IsValid(ent) then
return false
end
if not ent:Photon() then
return false
end
if not ent:IsEMV() then
return false
end
if not ent:Photon_SelectionEnabled() then
return false
end
return true
end,
MenuOpen = function(self, option, ent)
local options = EMVU.Selections[ent.VehicleName]
local submenu = option:AddSubMenu()
for catIndex, cat in ipairs(options) do
if not cat.Name then
cat.Name = "Unspecified #" .. catIndex
print("[Photon] Selection with the index #" .. catIndex .. " has no name specified.")
end
if #cat.Options == 2 and (cat.Options[1].Name == "None" or cat.Options[2].Name == "None") then
local selected = ent:Photon_SelectionOption(catIndex)
local isActive = cat.Options[selected].Name ~= "None"
local addedOption
if selected == 1 then
addedOption = submenu:AddOption(cat.Name, function()
EMVU.Net.Selection(ent, catIndex, 2)
end)
else
addedOption = submenu:AddOption(cat.Name, function()
EMVU.Net.Selection(ent, catIndex, 1)
end)
end
addedOption:SetChecked(isActive)
else
local category = submenu:AddSubMenu(cat.Name, null)
local subCategories = {}
for index, option in pairs(cat.Options) do
local opt
if not option.Name then
option.Name = "Unspecified #" .. index
print("[Photon] Option in selection '" .. cat.Name .. "' with the index #" .. index .. " has no name specified.")
end
if option.Category then
if not subCategories[option.Category] then
subCategories[option.Category] = category:AddSubMenu(option.Category)
end
opt = subCategories[option.Category]:AddOption(option.Name, function()
EMVU.Net.Selection(ent, catIndex, index)
end)
else
opt = category:AddOption(option.Name, function()
EMVU.Net.Selection(ent, catIndex, index)
end)
end
if ent:Photon_SelectionOption(catIndex) == index then
opt:SetChecked(true)
end
end
end
end
end,
Action = null
})
properties.Add("photon_configuration", {
MenuLabel = "Configurations",
Order = 5,
MenuIcon = "photon/ui/menu-presets.png",
Filter = function(self, ent, ply)
if not IsValid(ent) then
return false
end
if not ent:Photon() then
return false
end
if not ent:IsEMV() then
return false
end
if not ent:Photon_SelectionEnabled() then
return false
end
if not ent:Photon_SupportsConfigurations() then
return false
end
if not ent:Photon_GetAvailableConfigurations() then
return false
end
return true
end,
MenuOpen = function(self, option, ent)
local options = ent:Photon_GetAvailableConfigurations() or {}
local submenu = option:AddSubMenu()
local categories = {}
for index, data in pairs(options) do
local sub = submenu
if data.Category and (not tobool(data.Category) == false) then
local newCat = categories[tostring(data.Category)]
if not newCat then
categories[tostring(data.Category)] = submenu:AddSubMenu(tostring(data.Category), null)
newCat = categories[tostring(data.Category)]
end
sub = newCat
end
sub:AddOption(data.Name, function()
ent:Photon_ApplyEquipmentConfiguration(index)
end)
end
end,
Action = null
})
|
-- Copyright 2006-2020 Mitchell mitchell.att.foicica.com. See License.txt.
-- OCaml LPeg lexer.
local lexer = require('lexer')
local token, word_match = lexer.token, lexer.word_match
local P, S = lpeg.P, lpeg.S
local lex = lexer.new('caml')
-- Whitespace.
lex:add_rule('whitespace', token(lexer.WHITESPACE, lexer.space^1))
-- Keywords.
lex:add_rule('keyword', token(lexer.KEYWORD, word_match[[
and as asr begin class closed constraint do done downto else end exception
external failwith false flush for fun function functor if in include incr
inherit land let load los lsl lsr lxor match method mod module mutable new not
of open option or parser private raise rec ref regexp sig stderr stdin stdout
struct then to true try type val virtual when while with
]]))
-- Types.
lex:add_rule('type', token(lexer.TYPE, word_match[[
bool char float int string unit
]]))
-- Functions.
lex:add_rule('function', token(lexer.FUNCTION, word_match[[
abs abs_float acos asin atan atan2 at_exit bool_of_string ceil char_of_int
classify_float close_in close_in_noerr close_out close_out_noerr compare cos
cosh decr epsilon_float exit exp failwith float float_of_int float_of_string
floor flush flush_all format_of_string frexp fst ignore in_channel_length incr
infinity input input_binary_int input_byte input_char input_line input_value
int_of_char int_of_float int_of_string invalid_arg ldexp log log10 max
max_float max_int min min_float min_int mod modf mod_float nan open_in
open_in_bin open_in_gen open_out open_out_bin open_out_gen out_channel_length
output output_binary_int output_byte output_char output_string output_value
pos_in pos_out pred prerr_char prerr_endline prerr_float prerr_int
prerr_newline prerr_string print_char print_endline print_float print_int
print_newline print_string raise read_float read_int read_line really_input
seek_in seek_out set_binary_mode_in set_binary_mode_out sin sinh snd sqrt
stderr stdin stdout string_of_bool string_of_float string_of_format
string_of_int succ tan tanh truncate
]]))
-- Identifiers.
lex:add_rule('identifier', token(lexer.IDENTIFIER, lexer.word))
-- Strings.
local sq_str = lexer.range("'", true)
local dq_str = lexer.range('"', true)
lex:add_rule('string', token(lexer.STRING, sq_str + dq_str))
-- Comments.
lex:add_rule('comment', token(lexer.COMMENT,
lexer.range('(*', '*)', false, false, true)))
-- Numbers.
lex:add_rule('number', token(lexer.NUMBER, lexer.number))
-- Operators.
lex:add_rule('operator', token(lexer.OPERATOR, S('=<>+-*/.,:;~!#%^&|?[](){}')))
return lex
|
-- Display bag filter icon
hooksecurefunc("ContainerFrame_OnShow", function (self)
local id = self:GetID()
self.FilterIcon:Hide()
if (id > 0 and not IsInventoryItemProfessionBag("player", ContainerIDToInventoryID(id))) then
for i = LE_BAG_FILTER_FLAG_EQUIPMENT, NUM_LE_BAG_FILTER_FLAGS do
local active = false
if (id > NUM_BAG_SLOTS) then
active = GetBankBagSlotFlag(id - NUM_BAG_SLOTS, i)
else
active = GetBagSlotFlag(id, i)
end
if (active) then
self.FilterIcon.Icon:SetAtlas(BAG_FILTER_ICONS[i], true)
self.FilterIcon:Show()
break
end
end
end
end)
-- Display coin icon on junk items
hooksecurefunc("ContainerFrame_Update", function (self)
local id = self:GetID()
local name = self:GetName()
local itemButton
local texture, itemCount, locked, quality, readable, _, itemLink, isFiltered, noValue, itemID
for i = 1, self.size do
itemButton = _G[name.."Item"..i]
texture, itemCount, locked, quality, readable, _, itemLink, isFiltered, noValue, itemID = GetContainerItemInfo(id, itemButton:GetID())
-- Junk
itemButton.JunkIcon:Hide()
local itemLocation = ItemLocation:CreateFromBagAndSlot(id, itemButton:GetID())
if C_Item.DoesItemExist(itemLocation) then
local isJunk = quality == LE_ITEM_QUALITY_POOR and not noValue and MerchantFrame:IsShown()
itemButton.JunkIcon:SetShown(isJunk)
end
end
end)
|
---获取设备的详情
--- Created by lgy.
--- DateTime: 2017/9/6 下午9:16
---
--./wrk -t2 -c2 -d1s --script='./ujing/get_devices.lua' http://it-wx-test.zhinengxiyifang.cn/api/Stores/593fb353eef9d1e463000002/devices?filter=%7B%22where%22:%7B%22isRemoved%22:false%7D,%22include%22:%7B%22deviceType%22:%22deviceWashModels%22%7D%7D
--./wrk -t2 -c20 -d20s --script='./ujing/get_devices.lua' http://it-wx-test.zhinengxiyifang.cn/api/Stores/593fb353eef9d1e463000002/devices?filter=%7B%22where%22:%7B%22isRemoved%22:false%7D,%22include%22:%7B%22deviceType%22:%22deviceWashModels%22%7D%7D
wrk.method = "GET"
wrk.headers["Content-Type"] = "application/json"
wrk.headers["Accept"] = "application/json"
--[[
response = function(status, headers, body)
print(status)
print(headers)
print(body)
end
--]]
|
-- Credit: LaughingLeader
function getSkillEntryName(skill)
local skillId = string.gsub(skill, "_%-?%d+$", "")
return skillId
end
local function hasScoundrelSkills(character)
local result = 0
for k, skillId in pairs(OdinScoundrelOverhaul.ScoundrelSkills) do
if IsSkillActive(character, skillId) == 1 then
result = 1
break
end
end
return result
end
local function isScoundrelSkill(inSkillId)
local result = 0
for k, skillId in pairs(OdinScoundrelOverhaul.ScoundrelSkills) do
if inSkillId == skillId then
result = 1
break
end
end
return result
end
local function getPrepareParentSkill(skillId)
local func = OdinScoundrelOverhaul.ComboSkills.OnPrepareHit[skillId]
if func ~= nil then
return skillId
else
local using = Ext.StatGetAttribute(skillId, "Using")
if using ~= nil then
return using
end
end
return ""
end
local function isStealthed(character)
if HasActiveStatus(character, "INVISIBLE") == 1 or HasActiveStatus(character, "SNEAKING") == 1 then
return 1
end
end
Ext.NewQuery(getSkillEntryName, "OBSCO_LUA_GetSkillEntryName", "[in](STRING)_ProtoId, [out](STRING)_SkillId")
Ext.NewQuery(hasScoundrelSkills, "OBSCO_LUA_HasScoundrelSkills", "[in](CHARACTERGUID)_Character, [out](INTEGER)_Result");
Ext.NewQuery(isScoundrelSkill, "OBSCO_LUA_IsScoundrelSkill", "[in](STRING)_SkillId, [out](INTEGER)_Result");
Ext.NewQuery(getPrepareParentSkill, "OBSCO_LUA_Skill_GetPrepareParentSkill", "[in](STRING)_SkillId, [out](STRING)_ParentSkillId");
Ext.NewQuery(isStealthed, "OBSCO_LUA_IsStealthed", "[in](CHARACTERGUID)_Character, [out](INTEGER)_Result");
|
local Kache = require(script.Parent.prep)
return function()
describe("Basic functionality", function()
it("should store data", function()
local instance = Kache.new()
instance:Set("key", "value")
expect(instance:Get("key")).to.equal("value")
end)
it("should use a default value if key does not exist", function()
local instance = Kache.new()
expect(instance:Get("key", "default")).to.equal("default")
end)
it("should allow functional default values", function()
local instance = Kache.new()
expect(instance:Get("key", function() return "default" end)).to.equal("default")
end)
it("should persist a default value if key does not exist and option is provided", function()
local instance = Kache.new()
expect(instance:Get("key", "default", true)).to.equal("default")
expect(instance:Get("key")).to.equal("default")
end)
it("should support table-like behaviour", function()
local instance = Kache.new()
instance.key = "value"
expect(instance.key).to.equal("value")
end)
end)
describe("TTLs", function()
it("should store data with a TTL", function()
local instance = Kache.new(1)
instance:Set("key", "value")
expect(instance:Get("key")).to.equal("value")
task.wait(1)
expect(instance:Get("key")).to.equal(nil)
end)
it("should be able to act like an expiring dictionary", function()
local instance = Kache.new(1)
instance.key1 = "value"
expect(instance.key1).to.equal("value")
task.wait(1)
expect(instance.key1).to.equal(nil)
end)
it("should have expiring defaults if they're persisted", function()
local instance = Kache.new(1)
expect(instance:Get("key", "default", true)).to.equal("default")
expect(instance.key).to.equal("default")
task.wait(1)
expect(instance.key).to.equal(nil)
end)
it("should override TTLs if one is provided", function()
local instance = Kache.new(1)
instance.key1 = "value"
instance:Set("key2", "value", 2)
expect(instance.key1).to.equal("value")
expect(instance.key2).to.equal("value")
task.wait(1)
expect(instance.key1).to.equal(nil)
expect(instance.key2).to.equal("value")
task.wait(1) -- would've waited 2 seconds at this point, past the TTL
expect(instance.key2).to.equal(nil)
end)
end)
describe("Sharing", function()
it("should share instances", function()
expect(Kache.shared("UNIT_TEST")).to.equal(Kache.shared("UNIT_TEST"))
end)
it("should store the same data in shared instances", function()
local inst1 = Kache.shared("UNIT_TEST_1")
local inst2 = Kache.shared("UNIT_TEST_1")
inst1.data = "abcdefg"
expect(inst2.data).to.equal("abcdefg")
end)
it("should not share instances if the instances are not named the same", function()
expect(Kache.shared("UNIT_TEST")).never.to.equal(Kache.shared("UNIT_TEST_2"))
end)
it("should share cross-server instances", function()
expect(Kache.crossServer("UNIT_TEST")).to.equal(Kache.crossServer("UNIT_TEST"))
end)
it("should not share cross-server instances if the instances are not named the same", function()
expect(Kache.crossServer("UNIT_TEST")).never.to.equal(Kache.crossServer("UNIT_TEST_2"))
end)
it("should not share cross-server and regular shared instances", function()
expect(Kache.shared("UNIT_TEST")).never.to.equal(Kache.crossServer("UNIT_TEST"))
end)
end)
describe("Events", function()
it("should fire an event whenever an item is put into cache", function()
local instance = Kache.new()
task.delay(1, function()
instance.key1 = true
end)
local event, key, value, expiry = instance:Wait()
expect(event).to.equal(Kache.Enum.Event.Set)
expect(key).to.equal("key1")
expect(value).to.equal(true)
expect(expiry).to.equal(nil)
end)
end)
end
|
-- Generated By protoc-gen-lua Do not Edit
local protobuf = require "protobuf"
module('BseBattleInit_pb', package.seeall)
local BSEBATTLEINIT = protobuf.Descriptor();
local BSEBATTLEINIT_ROOMID_FIELD = protobuf.FieldDescriptor();
local BSEBATTLEINIT_CAMPCOUNT_FIELD = protobuf.FieldDescriptor();
local BSEBATTLEINIT_BATTLEMODE_FIELD = protobuf.FieldDescriptor();
local BSEBATTLEINIT_MAPID_FIELD = protobuf.FieldDescriptor();
local BSEBATTLEINIT_ENV_FIELD = protobuf.FieldDescriptor();
local BSEBATTLEINIT_TOTALSECOND_FIELD = protobuf.FieldDescriptor();
local BSEBATTLEINIT_ROUNDSECOND_FIELD = protobuf.FieldDescriptor();
local BSEBATTLEINIT_RESERVED1_FIELD = protobuf.FieldDescriptor();
local BSEBATTLEINIT_RESERVED2_FIELD = protobuf.FieldDescriptor();
local BSEBATTLEINIT_RESERVED3_FIELD = protobuf.FieldDescriptor();
local BSEBATTLEINIT_ROLEARR_FIELD = protobuf.FieldDescriptor();
local BSEBATTLEINIT_AUTOMODE_FIELD = protobuf.FieldDescriptor();
BSEBATTLEINIT_ROOMID_FIELD.name = "roomId"
BSEBATTLEINIT_ROOMID_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseBattleInit.roomId"
BSEBATTLEINIT_ROOMID_FIELD.number = 1
BSEBATTLEINIT_ROOMID_FIELD.index = 0
BSEBATTLEINIT_ROOMID_FIELD.label = 2
BSEBATTLEINIT_ROOMID_FIELD.has_default_value = false
BSEBATTLEINIT_ROOMID_FIELD.default_value = ""
BSEBATTLEINIT_ROOMID_FIELD.type = 9
BSEBATTLEINIT_ROOMID_FIELD.cpp_type = 9
BSEBATTLEINIT_CAMPCOUNT_FIELD.name = "campCount"
BSEBATTLEINIT_CAMPCOUNT_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseBattleInit.campCount"
BSEBATTLEINIT_CAMPCOUNT_FIELD.number = 2
BSEBATTLEINIT_CAMPCOUNT_FIELD.index = 1
BSEBATTLEINIT_CAMPCOUNT_FIELD.label = 2
BSEBATTLEINIT_CAMPCOUNT_FIELD.has_default_value = false
BSEBATTLEINIT_CAMPCOUNT_FIELD.default_value = 0
BSEBATTLEINIT_CAMPCOUNT_FIELD.type = 13
BSEBATTLEINIT_CAMPCOUNT_FIELD.cpp_type = 3
BSEBATTLEINIT_BATTLEMODE_FIELD.name = "battleMode"
BSEBATTLEINIT_BATTLEMODE_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseBattleInit.battleMode"
BSEBATTLEINIT_BATTLEMODE_FIELD.number = 3
BSEBATTLEINIT_BATTLEMODE_FIELD.index = 2
BSEBATTLEINIT_BATTLEMODE_FIELD.label = 2
BSEBATTLEINIT_BATTLEMODE_FIELD.has_default_value = false
BSEBATTLEINIT_BATTLEMODE_FIELD.default_value = 0
BSEBATTLEINIT_BATTLEMODE_FIELD.type = 13
BSEBATTLEINIT_BATTLEMODE_FIELD.cpp_type = 3
BSEBATTLEINIT_MAPID_FIELD.name = "mapId"
BSEBATTLEINIT_MAPID_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseBattleInit.mapId"
BSEBATTLEINIT_MAPID_FIELD.number = 4
BSEBATTLEINIT_MAPID_FIELD.index = 3
BSEBATTLEINIT_MAPID_FIELD.label = 2
BSEBATTLEINIT_MAPID_FIELD.has_default_value = false
BSEBATTLEINIT_MAPID_FIELD.default_value = 0
BSEBATTLEINIT_MAPID_FIELD.type = 13
BSEBATTLEINIT_MAPID_FIELD.cpp_type = 3
BSEBATTLEINIT_ENV_FIELD.name = "env"
BSEBATTLEINIT_ENV_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseBattleInit.env"
BSEBATTLEINIT_ENV_FIELD.number = 5
BSEBATTLEINIT_ENV_FIELD.index = 4
BSEBATTLEINIT_ENV_FIELD.label = 2
BSEBATTLEINIT_ENV_FIELD.has_default_value = false
BSEBATTLEINIT_ENV_FIELD.default_value = 0
BSEBATTLEINIT_ENV_FIELD.type = 13
BSEBATTLEINIT_ENV_FIELD.cpp_type = 3
BSEBATTLEINIT_TOTALSECOND_FIELD.name = "totalsecond"
BSEBATTLEINIT_TOTALSECOND_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseBattleInit.totalsecond"
BSEBATTLEINIT_TOTALSECOND_FIELD.number = 6
BSEBATTLEINIT_TOTALSECOND_FIELD.index = 5
BSEBATTLEINIT_TOTALSECOND_FIELD.label = 1
BSEBATTLEINIT_TOTALSECOND_FIELD.has_default_value = false
BSEBATTLEINIT_TOTALSECOND_FIELD.default_value = 0
BSEBATTLEINIT_TOTALSECOND_FIELD.type = 13
BSEBATTLEINIT_TOTALSECOND_FIELD.cpp_type = 3
BSEBATTLEINIT_ROUNDSECOND_FIELD.name = "roundsecond"
BSEBATTLEINIT_ROUNDSECOND_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseBattleInit.roundsecond"
BSEBATTLEINIT_ROUNDSECOND_FIELD.number = 7
BSEBATTLEINIT_ROUNDSECOND_FIELD.index = 6
BSEBATTLEINIT_ROUNDSECOND_FIELD.label = 1
BSEBATTLEINIT_ROUNDSECOND_FIELD.has_default_value = true
BSEBATTLEINIT_ROUNDSECOND_FIELD.default_value = 30
BSEBATTLEINIT_ROUNDSECOND_FIELD.type = 13
BSEBATTLEINIT_ROUNDSECOND_FIELD.cpp_type = 3
BSEBATTLEINIT_RESERVED1_FIELD.name = "reserved1"
BSEBATTLEINIT_RESERVED1_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseBattleInit.reserved1"
BSEBATTLEINIT_RESERVED1_FIELD.number = 8
BSEBATTLEINIT_RESERVED1_FIELD.index = 7
BSEBATTLEINIT_RESERVED1_FIELD.label = 1
BSEBATTLEINIT_RESERVED1_FIELD.has_default_value = true
BSEBATTLEINIT_RESERVED1_FIELD.default_value = false
BSEBATTLEINIT_RESERVED1_FIELD.type = 8
BSEBATTLEINIT_RESERVED1_FIELD.cpp_type = 7
BSEBATTLEINIT_RESERVED2_FIELD.name = "reserved2"
BSEBATTLEINIT_RESERVED2_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseBattleInit.reserved2"
BSEBATTLEINIT_RESERVED2_FIELD.number = 9
BSEBATTLEINIT_RESERVED2_FIELD.index = 8
BSEBATTLEINIT_RESERVED2_FIELD.label = 1
BSEBATTLEINIT_RESERVED2_FIELD.has_default_value = false
BSEBATTLEINIT_RESERVED2_FIELD.default_value = ""
BSEBATTLEINIT_RESERVED2_FIELD.type = 9
BSEBATTLEINIT_RESERVED2_FIELD.cpp_type = 9
BSEBATTLEINIT_RESERVED3_FIELD.name = "reserved3"
BSEBATTLEINIT_RESERVED3_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseBattleInit.reserved3"
BSEBATTLEINIT_RESERVED3_FIELD.number = 10
BSEBATTLEINIT_RESERVED3_FIELD.index = 9
BSEBATTLEINIT_RESERVED3_FIELD.label = 1
BSEBATTLEINIT_RESERVED3_FIELD.has_default_value = false
BSEBATTLEINIT_RESERVED3_FIELD.default_value = 0
BSEBATTLEINIT_RESERVED3_FIELD.type = 5
BSEBATTLEINIT_RESERVED3_FIELD.cpp_type = 1
BSEBATTLEINIT_ROLEARR_FIELD.name = "roleArr"
BSEBATTLEINIT_ROLEARR_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseBattleInit.roleArr"
BSEBATTLEINIT_ROLEARR_FIELD.number = 11
BSEBATTLEINIT_ROLEARR_FIELD.index = 10
BSEBATTLEINIT_ROLEARR_FIELD.label = 3
BSEBATTLEINIT_ROLEARR_FIELD.has_default_value = false
BSEBATTLEINIT_ROLEARR_FIELD.default_value = {}
BSEBATTLEINIT_ROLEARR_FIELD.message_type = ROLEINFO_PB_ROLEINFO
BSEBATTLEINIT_ROLEARR_FIELD.type = 11
BSEBATTLEINIT_ROLEARR_FIELD.cpp_type = 10
BSEBATTLEINIT_AUTOMODE_FIELD.name = "automode"
BSEBATTLEINIT_AUTOMODE_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseBattleInit.automode"
BSEBATTLEINIT_AUTOMODE_FIELD.number = 12
BSEBATTLEINIT_AUTOMODE_FIELD.index = 11
BSEBATTLEINIT_AUTOMODE_FIELD.label = 1
BSEBATTLEINIT_AUTOMODE_FIELD.has_default_value = true
BSEBATTLEINIT_AUTOMODE_FIELD.default_value = false
BSEBATTLEINIT_AUTOMODE_FIELD.type = 8
BSEBATTLEINIT_AUTOMODE_FIELD.cpp_type = 7
BSEBATTLEINIT.name = "BseBattleInit"
BSEBATTLEINIT.full_name = ".com.xinqihd.sns.gameserver.proto.BseBattleInit"
BSEBATTLEINIT.nested_types = {}
BSEBATTLEINIT.enum_types = {}
BSEBATTLEINIT.fields = {BSEBATTLEINIT_ROOMID_FIELD, BSEBATTLEINIT_CAMPCOUNT_FIELD, BSEBATTLEINIT_BATTLEMODE_FIELD, BSEBATTLEINIT_MAPID_FIELD, BSEBATTLEINIT_ENV_FIELD, BSEBATTLEINIT_TOTALSECOND_FIELD, BSEBATTLEINIT_ROUNDSECOND_FIELD, BSEBATTLEINIT_RESERVED1_FIELD, BSEBATTLEINIT_RESERVED2_FIELD, BSEBATTLEINIT_RESERVED3_FIELD, BSEBATTLEINIT_ROLEARR_FIELD, BSEBATTLEINIT_AUTOMODE_FIELD}
BSEBATTLEINIT.is_extendable = false
BSEBATTLEINIT.extensions = {}
BseBattleInit = protobuf.Message(BSEBATTLEINIT)
_G.BSEBATTLEINIT_PB_BSEBATTLEINIT = BSEBATTLEINIT
|
local carray = require 'carray'
--local ffi = require 'ffi'
dd = carray.double(5)
dd[2] = 4
dd[5] = 342
for i = 1, 5 do
print(dd[i])
end
carray.cast()
--cdata = ffi.cast('double*', dd:pointer())
--print(cdata[1])
--[[
local torch = require'torch'
local tmp = torch.FloatTensor(5):zero()
local tt = carray.float(5)
tt[1] = 5
tt[2] = 64
tt[3] = 3.14
local tbl = tt:table()
print(tbl[1])
tt:tensor( tmp, 3, 2 )
print('Tensor[1:5]:',tmp[1],tmp[2],tmp[3],tmp[4],tmp[5])
--]]
|
-- Module Declaration
--
local mod, CL = BigWigs:NewBoss("Glazer", 1493, 1469)
if not mod then return end
mod:RegisterEnableMob(95887)
mod.engageId = 1817
--------------------------------------------------------------------------------
-- Locals
--
local nextFocusing = 0
--------------------------------------------------------------------------------
-- Localization
--
local L = mod:GetLocale()
if L then
L.radiation_level = "%s: %d%%" -- Radiation Level: 10%
end
--------------------------------------------------------------------------------
-- Initialization
--
function mod:GetOptions()
return {
194945, -- Lingering Gaze
194323, -- Focusing
202046, -- Beam
194333, -- Beamed
}
end
function mod:OnBossEnable()
self:Log("SPELL_CAST_START", "LingeringGazeCast", 194942)
self:Log("SPELL_AURA_APPLIED", "LingeringGazeApplied", 194945)
self:Log("SPELL_AURA_APPLIED", "Focusing", 194323)
self:Log("SPELL_AURA_APPLIED_DOSE", "RadiationLevel", 195034)
self:Log("SPELL_AURA_APPLIED", "BeamDamage", 202046)
self:Log("SPELL_PERIODIC_DAMAGE", "BeamDamage", 202046)
self:Log("SPELL_PERIODIC_MISSED", "BeamDamage", 202046)
self:Log("SPELL_AURA_APPLIED", "Beamed", 194333)
end
function mod:OnEngage()
nextFocusing = GetTime() + 32
self:Bar(194323, 32) -- Focusing
self:CDBar(194945, 15.4) -- Lingering Gaze
end
--------------------------------------------------------------------------------
-- Event Handlers
--
function mod:LingeringGazeCast(args)
self:Message(194945, "red", "Alarm", CL.casting:format(args.spellName))
if nextFocusing - GetTime() > 18 then -- values lower than 18 sometimes failed
self:CDBar(194945, 15.7)
end
end
function mod:LingeringGazeApplied(args)
if self:Me(args.destGUID) then
self:Message(args.spellId, "blue", "Alert", CL.underyou:format(args.spellName))
end
end
function mod:Focusing(args)
self:Message(args.spellId, "orange", "Info")
end
function mod:RadiationLevel(args)
if args.amount >= 10 and args.amount % 5 == 0 then -- 10, 15, 20
self:Message(194323, "orange", "Info", L.radiation_level:format(args.spellName, args.amount), args.spellId)
end
end
do
local prev = 0
function mod:BeamDamage(args)
if self:Me(args.destGUID) then
local t = GetTime()
if t-prev > 1.5 then
prev = t
self:Message(args.spellId, "blue", "Alert", CL.you:format(args.spellName))
end
end
end
end
function mod:Beamed(args)
self:Message(args.spellId, "green", "Info")
self:Bar(args.spellId, 15)
self:Bar(194323, 60) -- Focusing
nextFocusing = GetTime() + 60
self:CDBar(194945, 5.9) -- Lingering Gaze
end
|
#!/usr/bin/lua5.2
local hpdf = require "hpdf"
local alldata = { fr = require("data-fr"), en = require("data-en") }
local titles = {
fr = {
experience = "Experience",
projects = "Projets personnel",
knowledge = "Savoir faire",
scholar = "Education",
contests = "Concours",
languages = "Langues",
hobbies = "Interets",
travel = "Voyages",
references = "References"
},
en = {
experience = "Relevant Experience",
projects = "Personal projects",
knowledge = "Knowledge",
scholar = "Scholarship",
contests = "Contests",
languages = "Langues",
hobbies = "Hobbies",
travel = "Travel",
references = "References"
}
}
local language = "fr"
local data = alldata[language]
local tdata = titles[language]
print("generating PDF")
-- Init HaruPDF
local pdf = hpdf.New()
if not pdf then os.exit(1) end
function getFont(font)
return hpdf.GetFont(pdf, hpdf.LoadTTFontFromFile(pdf, "/usr/share/fonts/truetype/lato/Lato-"..font..".ttf", true))
end
-- Lato font init
local fonts = {
regular = getFont("Regular"),
light = getFont("Light"),
bold = getFont("Bold"),
black = getFont("Black")
}
-- Init first page
local page = hpdf.AddPage(pdf)
local height = hpdf.Page_GetHeight(page)
local width = hpdf.Page_GetWidth(page)
-- Draw header separator
hpdf.Page_Rectangle(page, 375, height-165, 3, 120)
hpdf.Page_Fill(page)
-- Begin text & write header
hpdf.Page_BeginText(page)
hpdf.Page_SetFontAndSize(page, fonts.black, 16)
hpdf.Page_TextOut(page, 240, height-60, data.name:upper())
hpdf.Page_SetFontAndSize(page, fonts.light, 12)
hpdf.Page_TextOut(page, 300, height-70, "aka. "..data.nickname)
hpdf.Page_EndText(page)
hpdf.Page_BeginText(page)
hpdf.Page_SetFontAndSize(page, fonts.regular, 12)
hpdf.Page_TextOut(page, 380, height-55, data.address)
hpdf.Page_TextOut(page, 380, height-65, data.city)
hpdf.Page_TextOut(page, 380, height-75, data.country)
hpdf.Page_TextOut(page, 380, height-95, data.phone)
hpdf.Page_TextOut(page, 380, height-105, data.email)
hpdf.Page_TextOut(page, 380, height-125, data.citizenship)
hpdf.Page_TextOut(page, 380, height-135, data.birthdate)
hpdf.Page_TextOut(page, 380, height-155, data.github)
hpdf.Page_TextOut(page, 380, height-165, data.linkedin)
-- Text formatting
local format = {
header = { size = 16, font = fonts.bold },
title = { size = 10, font = fonts.bold },
description = { size = 10, font = fonts.regular }
}
-- Text spacing
local spacing = {
header = 15,
title = 12,
description = 15,
newbloc = 20,
newline = 5,
newoneline = 15,
newpage = 70
}
-- Text position
local tx = 50
local ty = 225
local tp = hpdf.Page_GetCurrentTextPos(page)
function printHeader(text)
printText(function() return text:upper() end, format.header, spacing.header)
end
function printText(text, format, spacing)
hpdf.Page_SetFontAndSize(page, format.font, format.size)
hpdf.Page_TextOut(page, tx, height-ty, text())
ty = ty + spacing
end
-- Add experience
printHeader(tdata.experience)
for j, exp in ipairs(data.experience) do
printText(function() return exp[1]..", "..exp[2].." // "..exp[3].." - "..exp[4] end, format.title, spacing.title)
for jj, expDetail in ipairs(exp[5]) do
printText(function() return expDetail end, format.description, spacing.description)
end
if next(data.experience, j) then
ty = ty + spacing.newline
end
end
ty = ty + spacing.newbloc
-- Add Personal Projects
printHeader(tdata.projects)
for j, dat in ipairs(data.projects) do
printText(function() return dat[1]..", " end, format.title, 0)
tp = hpdf.Page_GetCurrentTextPos(page)
tx = tp.x
printText(function() return dat[2] end, format.description, 0)
tx = 50
if next(data.projects, j) then
ty = ty + spacing.newoneline
end
end
ty = ty + spacing.description + spacing.newbloc
-- Add knowledge
printHeader(tdata.knowledge)
for j, dat in ipairs(data.knowledge) do
printText(function() return dat end, format.description, 0)
if next(data.knowledge, j) then
ty = ty + spacing.newoneline
end
end
-- Init second page
page = hpdf.AddPage(pdf)
height = hpdf.Page_GetHeight(page)
width = hpdf.Page_GetWidth(page)
hpdf.Page_BeginText(page)
ty = spacing.newpage
-- Add Scholarship
printHeader(tdata.scholar)
for j, dat in ipairs(data.scholarship) do
printText(function() return dat[1].." - " end, format.title, 0)
tp = hpdf.Page_GetCurrentTextPos(page)
tx = tp.x
printText(function() return dat[2] end, format.description, 0)
tx = 50
if next(data.scholarship, j) then
ty = ty + spacing.newoneline
end
end
ty = ty + spacing.description + spacing.newbloc
-- Add contests
printHeader(tdata.contests)
for j, dat in ipairs(data.contests) do
printText(function() return dat[2] and dat[1].." ("..dat[2]..") -- "..dat[3] or dat[1].." -- "..dat[3] end, format.title, spacing.title)
for jj, description in ipairs(dat[4]) do
printText(function() return description end, format.description, spacing.description)
end
if next(data.contests, j) then
ty = ty + spacing.newline
end
end
ty = ty + spacing.newbloc
-- Add Languages
printHeader(tdata.languages)
for j, dat in ipairs(data.languages) do
printText(function() return dat[1].." - " end, format.title, 0)
tp = hpdf.Page_GetCurrentTextPos(page)
tx = tp.x
printText(function() return dat[2] end, format.description, 0)
tx = 50
if next(data.languages, j) then
ty = ty + spacing.newoneline
end
end
ty = ty + spacing.description + spacing.newbloc
-- Add knowledge
printHeader(tdata.hobbies)
local hobbies = ""
for j, dat in ipairs(data.hobbies) do
hobbies = next(data.hobbies,j) and hobbies..dat..", " or hobbies..dat
end
printText(function() return hobbies end, format.description, 0)
ty = ty + spacing.description
local travel = tdata.travel..": "
for j, dat in ipairs(data.travel) do
travel = next(data.travel,j) and travel..dat..", " or travel..dat
end
printText(function() return travel end, format.description, 0)
ty = ty + spacing.description + spacing.newbloc
-- Add References
printHeader(tdata.references)
for j, dat in ipairs(data.references) do
printText(function() return dat[1]..": "..dat[2] end, format.description, spacing.newline)
ty = ty + spacing.newoneline
end
-- Save and exit
hpdf.SaveToFile(pdf, "resume.pdf")
hpdf.Free(pdf)
|
---@meta
resty_limit_count={}
function resty_limit_count.uncommit(self, key) end
function resty_limit_count.incoming(self, key, commit) end
resty_limit_count._VERSION="0.06"
function resty_limit_count.new(dict_name, limit, window) end
return resty_limit_count
|
--[[
战场策略
]]
local THIS_MODULE = ...
local BattleStrategy = class("BattleStrategy", require("app.main.modules.ui.FrameBase"),
require("app.main.modules.uiwidget.UIWidgetFocusable"))
--[[
构造函数
config
params 额外参数
name 名称
csb csb文件
widgets 组件表
bindings 绑定表
]]
function BattleStrategy:ctor(config)
self:setup(config)
self:retain()
self:initFrame()
end
-- 析构函数
function BattleStrategy:dtor()
self:delete()
self:release()
end
-- 初始化窗口
function BattleStrategy:initFrame()
self:setFocusWidget(self.wg_strategys)
end
--[[
打开窗口
config
role 使用角色
sp SP值
onComplete 完成回调
]]
function BattleStrategy:OnOpen(config)
local team = config.role:getEntity():getTeam()
local skills = team:getSkills()
local formations = team:getFormations()
local strategys = team:getStrategys()
local showSkills = nil
local showFormations = nil
local showStrategys = nil
local function useStrategy(config_,effect)
local usescript = effect and scriptMgr:createObject(
effect.script,
table.merge({
scene = "BATTLE",
role = config.role,
param = effect.param
},config_)) or nil
if usescript then
config.role:setRoundAction(usescript)
self:closeFrame()
if config.onComplete then
config.onComplete(true,config_.sp)
end
else
dump(config_,"not found strategy effect",2)
self:closeFrame()
if config.onComplete then
config.onComplete(false)
end
end
end
local function selectStrategy(config_,effect,action)
if config_.sp > config.sp then
uiMgr:openUI("ourmessage",{
autoclose = true,
texts = gameMgr:getStrings("LACK_SP"),
})
else
if action and action.script then
scriptMgr:createObject(
action.script,
table.merge({
scene = "BATTLE",
role = config.role,
param = action.param
},config_)
):execute(function (success,actconf)
if success then
useStrategy(table.merge(actconf,config_),effect)
end
end)
else
useStrategy(config_,effect)
end
end
end
-- 显示技能
showSkills = function()
local skillitems = {}
-- 火攻
if not skills.F then
table.insert(skillitems,{ label = "" })
else
table.insert(skillitems,{
label = skillMgr:getName(skills.F),
onTrigger = (function(item,pindex,index)
selectStrategy(
{
skill = skills.F,
sp = skillMgr:getSP(skills.F),
},
{
script = skillMgr:getScript(skills.F,"effect"),
param = skillMgr:getParam(skills.F,"effect"),
},
{
script = skillMgr:getScript(skills.F,"action"),
param = skillMgr:getParam(skills.F,"action"),
}
)
end)
})
end
-- 水攻
if not skills.W then
table.insert(skillitems,{ label = "" })
else
table.insert(skillitems,{
label = skillMgr:getName(skills.W),
onTrigger = (function(item,pindex,index)
selectStrategy(
{
skill = skills.W,
sp = skillMgr:getSP(skills.W),
},
{
script = skillMgr:getScript(skills.W,"effect"),
param = skillMgr:getParam(skills.W,"effect"),
},
{
script = skillMgr:getScript(skills.W,"action"),
param = skillMgr:getParam(skills.W,"action"),
}
)
end)
})
end
-- 落石
if not skills.S then
table.insert(skillitems,{ label = "" })
else
table.insert(skillitems,{
label = skillMgr:getName(skills.S),
onTrigger = (function(item,pindex,index)
selectStrategy(
{
skill = skills.S,
sp = skillMgr:getSP(skills.S),
},
{
script = skillMgr:getScript(skills.S,"effect"),
param = skillMgr:getParam(skills.S,"effect"),
},
{
script = skillMgr:getScript(skills.S,"action"),
param = skillMgr:getParam(skills.S,"action"),
}
)
end)
})
end
-- 恢复
if not skills.H then
table.insert(skillitems,{ label = "" })
else
table.insert(skillitems,{
label = skillMgr:getName(skills.H),
onTrigger = (function(item,pindex,index)
selectStrategy(
{
skill = skills.H,
sp = skillMgr:getSP(skills.H),
},
{
script = skillMgr:getScript(skills.H,"effect"),
param = skillMgr:getParam(skills.H,"effect"),
},
{
script = skillMgr:getScript(skills.H,"action"),
param = skillMgr:getParam(skills.H,"action"),
}
)
end)
})
end
-- 阵形
table.insert(skillitems,{
label="阵形",
onTrigger = (function(item,pindex,index)
showFormations()
end)
})
-- 谋略
table.insert(skillitems,{
label="谋略",
onTrigger = (function(item,pindex,index)
showStrategys()
end)
})
self.wg_strategys.lb_spval:setString(tostring(config.sp))
self.wg_strategys:updateParams({
items = skillitems,
listener = {
cancel = function()
self:closeFrame()
if config.onComplete then
config.onComplete(false)
end
end
}
})
end
-- 显示阵形
showFormations = function()
local formationitems = {}
for _,fid in ipairs(formations) do
if formationMgr:isBattleUsable(fid) then
table.insert(formationitems,{
label= formationMgr:getName(fid),
onTrigger = (function(item,pindex,index)
if #config.role:getTeam():getAliveRoles() < formationMgr:getSetRoles(fid) then
uiMgr:openUI("ourmessage",{
autoclose = true,
texts = gameMgr:getStrings("NOTSET_FORMATION",{
role = config.role:getEntity():getName()
}),
})
else
selectStrategy(
{
formation = fid,
sp = formationMgr:getSP(fid),
},
{
script = formationMgr:getScript(fid,"effect"),
param = formationMgr:getParam(fid,"effect"),
},
{
script = formationMgr:getScript(fid,"action"),
param = formationMgr:getParam(fid,"action"),
}
)
end
end)
})
end
end
self.wg_strategys.lb_spval:setString(tostring(config.sp))
self.wg_strategys:updateParams({
items = formationitems,
next = { label = "..." },
listener = {
cancel = function()
showSkills()
end
}
})
end
-- 显示策略
showStrategys = function()
local strategyitems = {}
for _,sid in ipairs(strategys) do
if strategyMgr:isBattleUsable(sid) then
table.insert(strategyitems,{
label= strategyMgr:getName(sid),
onTrigger = (function(item,pindex,index)
selectStrategy(
{
strategy = sid,
sp = strategyMgr:getSP(sid),
},
{
script = strategyMgr:getScript(sid,"effect"),
param = strategyMgr:getParam(sid,"effect"),
},
{
script = strategyMgr:getScript(sid,"action"),
param = strategyMgr:getParam(sid,"action"),
}
)
end)
})
end
end
self.wg_strategys.lb_spval:setString(tostring(config.sp))
self.wg_strategys:updateParams({
items = strategyitems,
next = { label = "..." },
listener = {
cancel = function()
showSkills()
end
}
})
end
showSkills()
end
-- 获得焦点回调
function BattleStrategy:onGetFocus()
self:OnWidgetGetFocus()
end
-- 失去焦点回调
function BattleStrategy:onLostFocus()
self:OnWidgetLostFocus()
end
-- 输入处理
function BattleStrategy:onControlKey(keycode)
self:onWidgetControlKey(keycode)
end
return BattleStrategy
|
--[[
Hero Selection
]]
require('components/heroselection/cmpickorder')
require('components/heroselection/rankedpickorder')
require('components/heroselection/ardm')
require('components/heroselection/heroselection')
require('components/heroselection/herocosmetics')
|
LevelModule = LevelModule or BeardLib:ModuleClass("level", ItemModuleBase)
LevelModule.levels_folder = "levels/mods/"
function LevelModule:init(...)
self.clean_table = table.add(clone(self.clean_table), {
{param = "preplanning", action = function(tbl)
table.remove_condition(tbl, function(v)
return v._meta == "default_plans" or v._meta == "start_location"
end)
end},
{param = "teams", action = "no_number_indexes"},
{param = "teams", action = "remove_metas"},
})
if not LevelModule.super.init(self, ...) then
return false
end
self._config.id = tostring(self._config.id)
if Global.level_data and Global.level_data.level_id == self._config.id then
BeardLib.current_level = self
self._currently_loaded = true
self:Load()
end
return true
end
function LevelModule:Load()
if self._config.include then
for i, include_data in ipairs(self._config.include) do
if include_data.file then
local file_split = string.split(include_data.file, "[.]")
local complete_path = Path:Combine(self._mod.ModPath, self._config.include.directory, include_data.file)
local new_path = Path:Combine(self.levels_folder, self._config.id, file_split[1])
if FileIO:Exists(complete_path) then
if include_data.type then
BeardLib.Managers.File:ScriptReplaceFile(file_split[2], new_path, complete_path, {type = include_data.type, add = true})
else
local ext_id = file_split[2]:id()
local path_id = new_path:id()
BeardLib.Managers.File:AddFile(ext_id, path_id, complete_path)
if include_data.reload then
PackageManager:reload(ext_id, path_id)
end
end
else
self:log("[ERROR] Included file '%s' is not readable by the lua state!", complete_path)
end
end
end
end
if self._config.sounds then --Sounds unload automatically.
SoundsModule:new(self._mod, self._config.sounds)
end
if self._config.add then
self._loaded_addfiles = AddFilesModule:new(self._mod, self._config.add)
end
if self._config.script_data_mods then
local script_mods = ScriptReplacementsModule:new(self._mod, self._config.script_data_mods)
script_mods:PostInit()
end
if self._config.hooks then
HooksModule:new(self._mod, self._config.hooks)
end
end
function LevelModule:AddLevelDataToTweak(l_self)
local id = tostring(self._config.id)
l_self[id] = table.merge(clone(self._config), {
name_id = self._config.name_id or ("heist_" .. id .. "_name"),
briefing_id = self._config.brief_id or ("heist_" .. id .. "_brief"),
world_name = "mods/" .. self._config.id,
ai_group_type = l_self.ai_groups[self._config.ai_group_type] or l_self.ai_groups.default,
intro_event = self._config.intro_event or "nothing",
outro_event = self._config.outro_event or "nothing",
music = self._config.music or "heist",
custom_packages = self._config.packages or self._config.custom_packages,
mod_path = self._mod.ModPath,
custom = true
})
if self._config.merge_data then
table.merge(l_self[id], BeardLib.Utils:RemoveMetas(self._config.merge_data, true))
end
if not table.contains(l_self._level_index, id) then
table.insert(l_self._level_index, id)
end
end
function LevelModule:AddAssetsDataToTweak(a_self)
for _, value in ipairs(self._config.assets) do
if value._meta == "asset" then
local exclude = value.exclude
local asset = a_self[value.name]
if asset ~= nil then
if (exclude and asset.exclude_stages ~= "all") or (not exclude and asset.stages ~= "all") then
asset.exclude_stages = asset.exclude_stages or {}
asset.stages = asset.stages or {}
table.insert(exclude and asset.exclude_stages or asset.stages, self._config.id)
end
else
self:Err("Asset %s does not exist! (Map: %s)", value.name, name)
end
else
if not a_self[value._meta] then
a_self[value._meta] = value
else
self:Err("Asset with name: %s already exists! (Map: %s)", value._meta, name)
end
end
end
end
function LevelModule:AddPrePlanningDataToTweak(pp_self)
pp_self.locations[self._config.id] = self._config.preplanning
end
function LevelModule:RegisterHook()
if tweak_data and tweak_data.levels then
self:AddLevelDataToTweak(tweak_data.levels)
else
Hooks:PostHook(LevelsTweakData, "init", self._config.id .. "AddLevelData", ClassClbk(self, "AddLevelDataToTweak"))
end
if self._currently_loaded then
if self._config.interactions then
local interactions = InteractionsModule:new(self._mod, self._config.interactions)
interactions:RegisterHook()
end
if self._config.assets then
if tweak_data and tweak_data.assets then
self:AddAssetsDataToTweak(tweak_data.assets)
else
Hooks:PostHook(AssetsTweakData, "init", self._config.id .. "AddAssetsData", ClassClbk(self, "AddAssetsDataToTweak"))
end
end
if self._config.preplanning then
if tweak_data and tweak_data.preplanning then
self:AddPrePlanningDataToTweak(tweak_data.preplanning)
else
Hooks:PostHook(PrePlanningTweakData, "init", self._config.id .. "AddPrePlanningData", ClassClbk(self, "AddPrePlanningDataToTweak"))
end
end
end
end
InstanceModule = InstanceModule or BeardLib:ModuleClass("instance", LevelModule)
InstanceModule.levels_folder = "levels/instances/mods/"
InstanceModule._loaded_packages = {}
function InstanceModule:init(...)
if not LevelModule.super.init(self, ...) then
return false
end
self._world_path = Path:Combine(self.levels_folder, self._config.id, "world")
BeardLib.Frameworks.Map._loaded_instances[self._world_path] = self --long ass line
--USED ONLY IN EDITOR!
if Global.editor_loaded_instance then
if Global.level_data and Global.level_data.level_id == "instances/mods/"..self._config.id then
BeardLib.current_level = self
self:Load()
end
end
return true
end
function InstanceModule:LoadPackage(package)
if PackageManager:package_exists(package) and not PackageManager:loaded(package) then
PackageManager:load(package)
table.insert(self._loaded_packages, package)
end
end
function InstanceModule:RegisterHook()
if self._config.interactions then
local interactions = InteractionsModule:new(self._mod, self._config.interactions)
interactions:RegisterHook()
end
end
function InstanceModule:Load()
for _, package in pairs(self._config.packages or self._config.custom_packages) do
self:LoadPackage(package)
end
InstanceModule.super.Load(self)
end
function InstanceModule:Unload()
for _, package in pairs(self._loaded_packages) do
if PackageManager:loaded(package) then
PackageManager:unload(package)
end
end
self._loaded_packages = nil
if self._loaded_addfiles then
self._loaded_addfiles:Unload()
self._loaded_addfiles = nil
end
end
|
local solution = {}
-- Walk from start point (x,y coordinates)
-- steps with len into direcection deg relativ to x-axis
function solution.walk( start, steps )
local now = start
for _,step in ipairs(steps) do
rad = math.rad(step.deg)
now.x = now.x + step.len * math.cos(rad)
now.y = now.y + step.len * math.sin(rad)
end
return now
end
-- Format the point C as specified in the kata
function solution.format( C )
local dist = math.sqrt( C.x^2 + C.y^2 )
local x = math.deg( math.atan( C.y, C.x ) )
local degrees = {}
for _ = 1,3 do
local i,f = math.modf(x)
table.insert( degrees, i)
x = f * 60
end
return { math.floor(dist+0.5), table.unpack(degrees) }
end
function solution.solve(a, b, c, alpha, beta, gamma)
-- convert: all angles starting at x-axis
local steps = {
{len = a, deg = alpha },
{len = b, deg = beta+90 },
{len = c, deg = gamma+180 }
}
local endpoint = solution.walk( {x=0,y=0}, steps )
return solution.format( endpoint )
end
return solution
|
return PlaceObj("ModDef", {
"dependencies", {
PlaceObj("ModDependency", {
"id", "ChoGGi_Library",
"title", "ChoGGi's Library",
"version_major", 10,
"version_minor", 5,
}),
},
"title", "Services Show Comfort Boost",
"id", "ChoGGi_ServicesShowComfortBoost",
"pops_any_uuid", "80fc30b4-6e46-4fff-af2a-7f06eaa2e954",
"steam_id", "2212802600",
"lua_revision", 1007000, -- Picard
"version", 2,
"version_major", 0,
"version_minor", 2,
"image", "Preview.png",
"author", "ChoGGi",
"code", {
"Code/Script.lua",
},
--~ "has_options", true,
"TagBuildings", true,
"TagInterface", true,
"TagOther", true,
"description", [[
Services only show the "Service Comfort" number, but that's just used as a threshold. It's not the actual comfort received.
This mod adds the "Comfort increase on visit" to the UI (what shows up in the comfort log after a visit).
Example: For the diner it's 60 (shown in the selection panel as service comfort), if the colonist is below 60 comfort than it'll get a boost of 10, if it's above 60 than no comfort increase, if the colonist can't access the service than it loses comfort.
]],
})
|
---@module GuiMole
---@copyright Lilith Games, Avatar Team
---@author Yen Yuan
local GuiMole, this = ModuleUtil.New("GuiMole", ClientBase)
---初始化函数
function GuiMole:Init()
print("[GuiMole] Init()")
this:DataInit()
this:NodeDef()
this:EventBind()
end
---节点定义
function GuiMole:NodeDef()
--[[this.payRoot = localPlayer.Local.PayGui
this.priceRoot = this.payRoot.PricePay
this.des = this.priceRoot.PayBG.DesText
this.cancel = this.priceRoot.PayBG.CancelBtn
this.pay = this.priceRoot.PayBG.PayBtn]]
end
---事件绑定
function GuiMole:EventBind()
--[[this.cancel.OnClick:Connect(
function()
NetUtil.Fire_C("ResetDefUIEvent", localPlayer)
end
)
this.pay.OnClick:Connect(
function()
-- 进行支付
this:Pay()
NetUtil.Fire_C("ResetDefUIEvent", localPlayer)
end
)]]
end
---数据初始化
function GuiMole:DataInit()
this.desText = ''
this.curMoleType = nil
this.curPit = nil
this.curPrice = 0
end
function GuiMole:PurchaseCEventHandler(_coin,_id)
if _id == 2 then
CloudLogUtil.UploadLog('pannel_actions', 'window_moleGui_payGui_yes')
CloudLogUtil.UploadLog('mole', 'mole_confirm',{cur_coin = Data.Player.coin,type=this.curMoleType,rest_num=this.curRestNum})
NetUtil.Fire_S('PlayerHitEvent',localPlayer.UserId,this.curMoleType,this.curPit)
end
end
function GuiMole:GetMolePriceEventHandler(_price,_type,_pit,_restNum)
this.curPrice = _price
this.curMoleType = _type
this.curPit = _pit
this.curPrice = _price
this.curRestNum = _restNum
end
function GuiMole:InteractCEventHandler(_gameId)
if _gameId == 2 then
CloudLogUtil.UploadLog('pannel_actions', 'window_moleGui_payGui_show')
CloudLogUtil.UploadLog('mole', 'mole_enter',{cur_coin = Data.Player.coin,type=this.curMoleType,rest_num=this.curRestNum})
NetUtil.Fire_C('PurchaseConfirmEvent',localPlayer,this.curPrice,2,string.format(LanguageUtil.GetText(Config.GuiText['MoleGui_1'].Txt), this.curPrice))
end
end
function GuiMole:ResetDefUIEventHandler()
end
---Update函数
function GuiMole:Update(_dt)
end
return GuiMole
|
--{{---| Tray |-------------------------------------------------------------------------------------------------------------
systray = wibox.widget.systray()
layouts = {
awful.layout.suit.fair, -- 1
awful.layout.suit.tile, -- 2
awful.layout.suit.floating, -- 3
awful.layout.suit.tile.bottom, -- 4
awful.layout.suit.max, -- 5
awful.layout.suit.magnifier, -- 6
-- awful.layout.suit.tile.left,
-- awful.layout.suit.tile.top,
-- awful.layout.suit.fair.horizontal,
-- awful.layout.suit.spiral,
-- awful.layout.suit.spiral.dwindle,
-- awful.layout.suit.max.fullscreen
-- lain.layout.cascade,
-- lain.layout.cascadetile,
-- lain.layout.centerfair,
-- lain.layout.centerhwork,
-- lain.layout.centerwork,
-- lain.layout.centerworkd,
-- lain.layout.termfair,
-- lain.layout.uselessfair,
-- lain.layout.uselesspiral,
-- lain.layout.uselesstile,
}
--{{---| Tags |-------------------------------------------------------------------------------------------------------------
tags = {
-- names = { "Main", "Web", "Files", "MSG", "Deploy", "Term", "Remote", "Dev", "Win", "DB", "Android", "Games"},
names = { "main", -- 1 -- "Main"
"www", -- 2 -- "Web"
"mail", -- 3 -- "Email"
"chat", -- 4 -- "Messages"
"files", -- 5 -- "Files"
"work", -- 6 -- "Work"
"dev", -- 7 -- "Dev"
"sys", -- 8 -- "System"
"win", -- 9 -- "Windows"
},
layout = {
layouts[1], -- 1 -- "Main"
layouts[1], -- 2 -- "Web"
layouts[1], -- 3 -- "Email"
layouts[1], -- 4 -- "Messages"
layouts[1], -- 5 -- "Files"
layouts[1], -- 6 -- "Work"
layouts[1], -- 7 -- "Dev"
layouts[1], -- 8 -- "System"
layouts[1] -- 9 -- "Windows"
}
}
mywibox = {}
mypromptbox = {}
mylayoutbox = {}
mytaglist = {}
mytaglist.buttons = awful.util.table.join(
awful.button({ }, 1, function(t) t:view_only() end),
awful.button({ modkey }, 1, function(t) if client.focus then client.focus:move_to_tag(t) end end),
awful.button({ }, 3, awful.tag.viewtoggle),
awful.button({ modkey }, 3, function(t) if client.focus then client.focus:toggle_tag(t) end end),
awful.button({ }, 4, function(t) awful.tag.viewnext(awful.tag.getscreen(t)) end),
awful.button({ }, 5, function(t) awful.tag.viewprev(awful.tag.getscreen(t)) end))
mytasklist = {}
mytasklist.buttons = awful.util.table.join(
awful.button({ }, 1, function (c)
if c == client.focus then
c.minimized = true
else
-- Without this, the following
-- :isvisible() makes no sense
c.minimized = false
if not c:isvisible() then
awful.tag.viewonly(c:tags()[1])
end
-- This will also un-minimize
-- the client, if needed
client.focus = c
c:raise()
end
end),
awful.button({ }, 3, client_menu_toggle_fn()),
awful.button({ }, 4, function ()
awful.client.focus.byidx(1)
if client.focus then client.focus:raise() end
end),
awful.button({ }, 5, function ()
awful.client.focus.byidx(-1)
if client.focus then client.focus:raise() end
end)
)
awful.screen.connect_for_each_screen(function(s)
-- Wallpaper
if beautiful.wallpaper then
local wallpaper = beautiful.wallpaper
-- If wallpaper is a function, call it with the screen
if type(wallpaper) == "function" then
wallpaper = wallpaper(s)
end
gears.wallpaper.maximized(wallpaper, s, true)
end
-- Each screen has its own tag table.
awful.tag(tags.names, s, tags.layout)
-- if ( s == screen.primary) then
-- awful.tag(tags.names, s, tags.layout)
-- else
-- awful.tag({""}, s, tags.layout)
-- end
-- Create a promptbox for each screen
mypromptbox[s] = awful.widget.prompt()
-- Create an imagebox widget which will contains an icon indicating which layout we're using.
-- We need one layoutbox per screen.
mylayoutbox[s] = awful.widget.layoutbox(s)
mylayoutbox[s]:buttons( awful.util.table.join(
awful.button({ }, 1, function () awful.layout.inc(layouts, 1 ) end),
awful.button({ }, 3, function () awful.layout.inc(layouts, -1 ) end),
awful.button({ }, 4, function () awful.layout.inc(layouts, 1 ) end),
awful.button({ }, 5, function () awful.layout.inc(layouts, -1 ) end))
)
-- Create a taglist widget
mytaglist[s] = awful.widget.taglist(s, awful.widget.taglist.filter.all, mytaglist.buttons)
-- Create a tasklist widget
mytasklist[s] = awful.widget.tasklist(s, awful.widget.tasklist.filter.currenttags, mytasklist.buttons)
-- Create the wibox
mywibox[s] = awful.wibar({ position = "top", screen = s, height = dpi(24) })
-- if ( s == screen.primary) then
-- mywibox[s] = awful.wibar({ position = "top", screen = s, height = dpi(16) })
-- else
-- mywibox[s] = awful.wibar({ position = "top", screen = s, height = dpi(10) })
-- end
-- Add widgets to the wibox
if ( s == screen.primary) then
mywibox[s]:setup {
layout = wibox.layout.align.horizontal,
{ -- Widgets that are aligned to the left
layout = wibox.layout.fixed.horizontal(),
mylauncher,
mytaglist[s],
mypromptbox[s],
},
mytasklist[s], -- Middle widget
{-- Widgets that are aligned to the right
layout = wibox.layout.fixed.horizontal(),
--spacer,
systray,
spacer0,
kbdcfg.widget,
spacer0,
setIcon,
spacer,
dropbox_widget,
spacer,
baticon,
batpct,
spacer,
brightness_widget,
spacer,
volicon,
volpct,
spacer,
keylock_icons_widget,
spacer,
mytextclock,
spacer0,
mylayoutbox[s],
},
}
else
mywibox[s]:setup {
layout = wibox.layout.align.horizontal,
{ -- Widgets that are aligned to the left
layout = wibox.layout.fixed.horizontal(),
mylauncher,
mytaglist[s],
mypromptbox[s],
},
mytasklist[s], -- Middle widget
{-- Widgets that are aligned to the right
layout = wibox.layout.fixed.horizontal(),
spacer0,
mylayoutbox[s],
},
}
end
end)
-- }}}
|
--[[--
success, -- boolean indicating success or failure
errmsg, -- error message in case of failure
errcode = -- error code in case of failure (TODO: not implemented yet)
auth.openid.initiate{
user_supplied_identifier = user_supplied_identifier, -- string given by user
https_as_default = https_as_default, -- default to https
curl_options = curl_options, -- additional options passed to "curl" binary, when performing discovery
return_to_module = return_to_module, -- module of the verifying view, the user shall return to after authentication
return_to_view = return_to_view, -- verifying view, the user shall return to after authentication
realm = realm -- URL the user should authenticate for, defaults to application base
}
In order to authenticate using OpenID the user should enter an identifier.
It is recommended that the form field element for this identifier is named
"openid_identifier", so that User-Agents can automatically determine the
given field should contain an OpenID identifier. The entered identifier is
then passed as "user_supplied_identifier" argument to this function. It
returns false on error and currently never returns on success. However in
future this function shall return true on success. After the user has
authenticated successfully, he/she is forwarded to the URL given by the
"return_to" argument. Under this URL the application has to verify the
result by calling auth.openid.verify{...}.
--]]--
function auth.openid.initiate(args)
local dd, errmsg, errcode = auth.openid.discover(args)
if not dd then
return nil, errmsg, errcode
end
-- TODO: Use request.redirect once it supports external URLs
request.set_status("303 See Other")
request.add_header(
"Location: " ..
encode.url{
external = dd.op_endpoint,
params = {
["openid.ns"] = "http://specs.openid.net/auth/2.0",
["openid.mode"] = "checkid_setup",
["openid.claimed_id"] = dd.claimed_identifier or
"http://specs.openid.net/auth/2.0/identifier_select",
["openid.identity"] = dd.op_local_identifier or dd.claimed_identifier or
"http://specs.openid.net/auth/2.0/identifier_select",
["openid.return_to"] = encode.url{
base = request.get_absolute_baseurl(),
module = args.return_to_module,
view = args.return_to_view
},
["openid.realm"] = args.realm or request.get_absolute_baseurl()
}
}
)
error("Not implemented") -- TODO
--cgi.send_data()
--exit()
end
|
--- LibChangelog
-- Provides an way to create a simple ingame frame to show a changelog
local _, Data = ...
local L = Data.L
local MAJOR, MINOR = "LibChangelog-KkthnxUI", 0
local LibChangelog = LibStub:NewLibrary(MAJOR, MINOR)
if not LibChangelog then
return
end
-- Lua APIs
local pcall, error, type, pairs = pcall, error, type, pairs
local NEW_MESSAGE_FONTS = {
version = GameFontNormalHuge,
title = GameFontNormal,
text = GameFontHighlight
}
local VIEWED_MESSAGE_FONTS = {
version = GameFontDisableHuge,
title = GameFontDisable,
text = GameFontDisable
}
function LibChangelog:Register(addonName, changelogTable, savedVariablesTable, lastReadVersionKey, onlyShowWhenNewVersionKey, texts)
if self[addonName] then
return error("LibChangelog: '"..addonName.."' already registered", 2)
end
self[addonName] = {
changelogTable = changelogTable,
savedVariablesTable = savedVariablesTable,
lastReadVersionKey = lastReadVersionKey,
onlyShowWhenNewVersionKey = onlyShowWhenNewVersionKey,
texts = texts or {}
}
end
function LibChangelog:CreateString(frame, text, font, offset)
local entry = frame.scrollChild:CreateFontString(nil, "ARTWORK")
if offset == nil then
offset = -5
end
entry:SetFontObject(font or "GameFontNormal")
entry:SetText(text)
entry:SetJustifyH("LEFT")
entry:SetWidth(frame.scrollBar:GetWidth())
if frame.previous then
entry:SetPoint("TOPLEFT", frame.previous, "BOTTOMLEFT", 0, offset)
else
entry:SetPoint("TOPLEFT", frame.scrollChild, "TOPLEFT", -5)
end
frame.previous = entry
return entry
end
-- Did this just to get nice alignment on the bulleted entries (otherwise the text wrapped below the bulle
function LibChangelog:CreateBulletedListEntry(frame, text, font, offset)
local bullet = self:CreateString(frame, "-", font, offset)
local bulletWidth = 6
bullet:SetWidth(bulletWidth)
bullet:SetJustifyV("TOP")
local entry = self:CreateString(frame, text, font, offset)
entry:SetPoint("TOPLEFT", bullet, "TOPRIGHT")
entry:SetWidth(frame.scrollBar:GetWidth() - bulletWidth)
bullet:SetHeight(entry:GetStringHeight())
frame.previous = bullet
return bullet
end
function LibChangelog:ShowChangelog(addonName)
local fonts = NEW_MESSAGE_FONTS
local addonData = self[addonName]
if not addonData then
return error("LibChangelog: '"..addonName.. "' was not registered. Please use :Register() first", 2)
end
local firstEntry = addonData.changelogTable[1] -- firstEntry contains the newest Version
local addonSavedVariablesTable = addonData.savedVariablesTable
if addonData.lastReadVersionKey and addonSavedVariablesTable[addonData.lastReadVersionKey] and firstEntry.Version <= addonSavedVariablesTable[addonData.lastReadVersionKey] and addonSavedVariablesTable[addonData.onlyShowWhenNewVersionKey] then
return
end
if not addonData.frame then
local frame = CreateFrame("Frame", nil, UIParent, "ButtonFrameTemplate")
ButtonFrameTemplate_HidePortrait(frame)
if frame.SetTitle then
frame:SetTitle(addonData.texts.title or addonName.." ChangeLog")
else
-- Workaround for TBCC
frame.TitleText:SetText(addonData.texts.title or addonName.." ChangeLog")
end
frame.Inset:SetPoint("TOPLEFT", 4, -25)
frame:SetSize(500, 500)
frame:SetPoint("CENTER")
frame:StripTextures()
frame:CreateBorder()
frame.scrollBar = CreateFrame("ScrollFrame", nil, frame.Inset, "UIPanelScrollFrameTemplate")
frame.scrollBar:SetPoint("TOPLEFT", 10, -6)
frame.scrollBar:SetPoint("BOTTOMRIGHT", -22, 6)
frame.scrollChild = CreateFrame("Frame")
frame.scrollChild:SetSize(1, 1) -- It doesnt seem to matter how big it is, the only thing that not works is setting the height to really high number, then you can scroll forever
frame.scrollBar:SetScrollChild(frame.scrollChild)
UIParentInsetScrollBar:SkinScrollBar()
frame.CloseButton:SkinCloseButton()
frame.CloseButton:ClearAllPoints()
frame.CloseButton:SetPoint("RIGHT", frame, "TOPRIGHT", 3, -13)
frame.CheckButton = CreateFrame("CheckButton", nil, frame, "UICheckButtonTemplate")
frame.CheckButton:SetChecked(addonSavedVariablesTable[addonData.onlyShowWhenNewVersionKey])
frame.CheckButton:SetFrameStrata("HIGH")
frame.CheckButton:SetSize(14, 14)
frame.CheckButton:SetScript("OnClick", function(self)
local isChecked = self:GetChecked()
addonSavedVariablesTable[addonData.onlyShowWhenNewVersionKey] = isChecked
frame.CheckButton:SetChecked(isChecked)
end)
frame.CheckButton:SetPoint("LEFT", frame, "BOTTOMLEFT", 10, 13)
frame.CheckButton:SkinCheckBox()
frame.CheckButton.text:ClearAllPoints()
frame.CheckButton.text:SetPoint("LEFT", frame.CheckButton, "RIGHT", 4, 0)
frame.CheckButton.text:SetText(addonData.texts.onlyShowWhenNewVersion or " Only Show after next update")
addonData.frame = frame
end
for i = 1, #addonData.changelogTable do
local versionEntry = addonData.changelogTable[i]
if addonData.lastReadVersionKey and addonSavedVariablesTable[addonData.lastReadVersionKey] and addonSavedVariablesTable[addonData.lastReadVersionKey] >= versionEntry.Version then
fonts = VIEWED_MESSAGE_FONTS
end
-- Add version string
self:CreateString(addonData.frame, "## "..versionEntry.Version, fonts.version, -30) -- Add a nice spacing between the version header and the previous text
if versionEntry.General then
self:CreateString(addonData.frame, versionEntry.General, fonts.text)
end
if versionEntry.Sections then
for i = 1, #versionEntry.Sections do
local section = versionEntry.Sections[i]
self:CreateString(addonData.frame, "### "..section.Header, fonts.title, -8)
local entries = section.Entries
for j = 1, #entries do
self:CreateBulletedListEntry(addonData.frame, entries[j], fonts.text)
end
end
end
end
addonSavedVariablesTable[addonData.lastReadVersionKey] = firstEntry.Version
end
|
require("prototypes.final-fixed-science-pack-subgroup")
require("prototypes.final-fixed-technogies")
require("prototypes.final-fixed-military")
require("prototypes.final-fixed-electronics-subgroup")
require("prototypes.final-fixed-subgroup")
require("prototypes.final-fixed-assembler")
require("prototypes.armor")
if not (momoPyTweak.DumpOnly) then
momoPyTweak.finalFixes.MoveSciencePackSubgroup()
momoPyTweak.finalFixes.ElectronicsSubgroup()
momoPyTweak.finalFixes.Technogies()
momoPyTweak.finalFixes.Military()
momoPyTweak.finalFixes.AddUtilitySciencePackToTechnology()
-- temp fix energy cost
momoPyTweak.finalFixes.GlassWorkEnergyCost()
-- rearrangement subgroup
momoPyTweak.finalFixes.PyanodonPleaseFixThatSubgroup()
if (momoPyTweak.mods.alienTech) then
momoPyTweak.compatibility.SchallUraniumMining()
end
momoPyTweak.ArmorInventory()
else
momoIRTweak.DumpTechnologies()
momoIRTweak.DumpRecipes()
end
|
--[[
module:AdvancedMediaPlayer
author:DylanYang
time:2021-02-07 17:01:44
]]
local _M = Class("AdvancedMediaPlayer")
local public = _M.public
function public:PlayVlc(fileName)
end
function public:PlayMp4(fileName)
end
return _M
|
local Object = require('core/object')
local Stage = require('core/stage')
local Throne = {}
Object:instantiate(Throne, Stage)
function Throne:new(game)
self.game = game
self.scream = love.audio.newSource("assets/audio/scenes/throne/scream.mp3", "static")
self.scream:setVolume(0.1)
self.lightning = {}
for i=0,5 do
self.lightning[i+1] = love.graphics.newImage("assets/img/scenes/throne/0".. i ..".png")
end
self.background = love.graphics.newImage("assets/img/scenes/throne/background.png")
self.background2 = love.graphics.newImage("assets/img/scenes/throne/background2.png")
self.character = love.graphics.newImage("assets/img/scenes/throne/char-standing-blurry.png")
self.animation = {
BEGIN = Object:create('core/animation', 200, true),
DIALOG = Object:create('core/animation', 4000, false),
PAUSE = Object:create('core/animation', 1000, false),
FADING = Object:create('core/animation', 16000, false),
ZOOM = Object:create('core/animation', 8300, false),
ENDING = Object:create('core/animation', 2000, false)
}
self.state = {
BEGIN = 0,
DIALOG = 1,
PAUSE = 2,
ZOOM = 3,
ENDING = 255
}
self.diablog = {
"Je me souviens désormais...",
"J'étais jadis le maître de ces lieux.",
"Ce château est...",
"Mon tombeau."
}
self.step = self.state.BEGIN
self.blink = {1,2,3,4,5,4,3,2}
self.index = 1
self.fading = 1
self.scaling = 1
self.plot = 1
self.translate = 0
self.diablog.step = 1
self.entities = {}
table.insert(self.entities, {id="THRONE", x=230, y=108, width=140, height=172, mousevisible=true})
end
function Throne:zoom(dt)
local progress = self.animation.ZOOM:update(dt)
if progress > 0 then
self.scaling = 1+(1-progress)
self.translate = 600 - (600/self.scaling)
end
end
function Throne:ending(dt)
local progress = self.animation.FADING:update(dt)
if progress > 0 then
self.fading = progress
else
self.step = self.state.ENDING
end
end
function Throne:nextDialog(dt)
local progress = self.animation.DIALOG:update(dt)
if progress <= 0 then
self.animation.DIALOG:reset()
return true
end
return false
end
function Throne:update(dt)
self:cursor()
self:blinking(dt)
if self.step == self.state.DIALOG then
if self.diablog.step == 1 then
if self:nextDialog(dt) then
self.diablog.step = self.diablog.step + 1
end
elseif self.diablog.step == 2 then
if self:nextDialog(dt) then
self.diablog.step = self.diablog.step + 1
end
elseif self.diablog.step == 3 then
if self:nextDialog(dt) then
self.diablog.step = self.diablog.step + 1
end
else if self.diablog.step == 4 then
if self:nextDialog(dt) then
self.step = self.state.PAUSE
end
end
end
end
if self.step == self.state.PAUSE then
local progress = self.animation.PAUSE:update(dt)
if progress <= 0 then
self.step = self.state.ZOOM
self.scream:play()
end
end
if self.step == self.state.ZOOM then
self:zoom(dt)
self:ending(dt)
end
if self.step == self.state.ENDING then
self.game:setStep(self.game.step.CREDIT)
end
end
function Throne:draw()
love.graphics.push()
if self.step == self.state.ZOOM then
love.graphics.scale(self.scaling, self.scaling)
love.graphics.translate(-self.translate/2, -self.translate/5)
end
if self.step < self.state.ZOOM then
love.graphics.draw(self.background, 0, 0)
love.graphics.draw(self.character, 100, 174)
else
love.graphics.draw(self.background2, 0, 0)
love.graphics.draw(self.lightning[self.blink[self.index]], 192, 70)
end
if self.step == self.state.DIALOG or self.step == self.state.PAUSE then
self.game.gui.text:draw(self.diablog[self.diablog.step], 15, 380 - 16)
end
if self.step == self.state.PAUSE then
love.graphics.push("all")
love.graphics.setColor(0, 0, 0, self.plot)
love.graphics.rectangle("fill", 0, 0, 600, 400)
love.graphics.pop("all")
end
if self.step == self.state.ZOOM then
self:leaving(1-self.fading)
end
love.graphics.pop()
end
function Throne:blinking(dt)
local progress = self.animation.BEGIN:update(dt)
if progress <= 0 then
if self.index < #self.blink then
self.index = self.index + 1
else
self.index = 1
end
end
end
function Throne:mousepressed(x, y, button)
if button == 1 then
if self.step == self.state.BEGIN and self:isTouchingEntityById("THRONE") then
self:removeEntity("THRONE")
love.mouse.setVisible(false)
self.step = self.state.DIALOG
end
end
end
return Throne
|
local access = require "kong.plugins.ldap-auth.access"
local BasePlugin = require "kong.plugins.base_plugin"
local LdapAuthHandler = BasePlugin:extend()
function LdapAuthHandler:new()
LdapAuthHandler.super.new(self, "ldap-auth")
end
function LdapAuthHandler:access(conf)
LdapAuthHandler.super.access(self)
access.execute(conf)
end
LdapAuthHandler.PRIORITY = 1002
return LdapAuthHandler
|
local vm = require 'vm.vm'
local guide = require 'parser.guide'
local files = require 'files'
local function checkPath(source, info)
if source.type == 'goto' then
return true
end
local src = info.source
local mode = guide.getPath(source, src)
if not mode then
return true
end
if mode == 'before' then
return false
end
return true
end
function vm.eachDef(source, callback)
local results = {}
local valueUris = {}
local sourceUri = guide.getRoot(source).uri
vm.eachRef(source, function (info)
if info.mode == 'declare'
or info.mode == 'set'
or info.mode == 'return'
or info.mode == 'value' then
results[#results+1] = info
local src = info.source
if info.mode == 'return' then
local uri = guide.getRoot(src).uri
valueUris[uri] = info.source
end
end
end)
for _, info in ipairs(results) do
local src = info.source
local destUri = guide.getRoot(src).uri
-- 如果是同一个文件,则检查位置关系后放行
if sourceUri == destUri then
if checkPath(source, info) then
callback(info)
end
goto CONTINUE
end
-- 如果是global或field,则直接放行(因为无法确定顺序)
if src.type == 'setindex'
or src.type == 'setfield'
or src.type == 'setmethod'
or src.type == 'tablefield'
or src.type == 'tableindex'
or src.type == 'setglobal' then
callback(info)
goto CONTINUE
end
-- 如果不是同一个文件,则必须在该文件 return 后才放行
if valueUris[destUri] then
callback(info)
goto CONTINUE
end
::CONTINUE::
end
end
|
local Snowflake = require('../Snowflake')
local Reaction = require('../Reaction')
local insert = table.insert
local format, char = string.format, string.char
local wrap, yield = coroutine.wrap, coroutine.yield
local Message, property, method = class('Message', Snowflake)
Message.__description = "Represents a Discord text channel message."
function Message:__init(data, parent)
Snowflake.__init(self, data, parent)
local channel = self._parent
local client = channel._parent._parent or channel._parent
self._author = client._users:get(data.author.id) or client._users:new(data.author)
self:_update(data)
end
function Message:__tostring()
return format('%s: %s', self.__name, self._content)
end
function Message:_update(data)
Snowflake._update(self, data)
if data.mentions then
local channel = self._parent
local client = channel._parent._parent or channel._parent
local users = client._users
local mentions = {}
for _, user_data in ipairs(data.mentions) do
insert(mentions, users:get(user_data.id) or users:new(user_data))
end
self._mentions = mentions
end
if data.mention_roles then self._mention_roles = data.mention_roles end
if data.reactions then
local reactions = {}
for _, reaction_data in ipairs(data.reactions) do
local emoji = reaction_data.emoji
local key = emoji.id or emoji.name
reactions[key] = Reaction(reaction_data, self)
end
self._reactions = reactions
end
if data.embeds then self._embeds = data.embeds end -- raw tables
if data.attachments then self._attachments = data.attachments end -- raw tables
end
local function getAttachment(self)
return self._attachments and self._attachments[1]
end
local function getEmbed(self)
return self._embeds and self._embeds[1]
end
local httpAdded = {}
function Message:_addReaction(data, user, http)
local emoji = data.emoji
local reactions = self._reactions or {}
local key = emoji.id or emoji.name
local reaction = reactions[key]
if reaction then
if httpAdded[key] then
httpAdded[key] = nil
return reaction
end
reaction._count = reaction._count + 1
if user == self.client.user then
reaction._me = true
end
else
reaction = Reaction({
me = user == self.client.user,
count = 1,
emoji = emoji
}, self)
reactions[key] = reaction
end
httpAdded[key] = http
self._reactions = reactions
return reaction
end
local httpRemoved = {}
function Message:_removeReaction(data, user, http)
local emoji = data.emoji
local reactions = self._reactions or {}
local key = emoji.id or emoji.name
local reaction = reactions[key]
if reaction then
if httpRemoved[key] then
httpRemoved[key] = nil
return reaction
end
reaction._count = reaction._count - 1
if user == self.client.user then
reaction._me = false
end
else
reaction = Reaction({
me = user == self.client.user,
count = 0,
emoji = emoji
}, self)
reactions[key] = reaction
end
httpRemoved[key] = http
self._reactions = reactions
return reaction
end
local function addReaction(self, emoji)
local channel = self._parent
local client = channel._parent._parent or channel._parent
local str = type(emoji) == 'table' and format('%s:%s', emoji._name, emoji._id) or emoji
local success = client._api:createReaction(channel._id, self._id, str)
if success then
self:_addReaction({emoji = {id = emoji._id, name = emoji._name or emoji}}, self.client.user, true)
end
return success
end
local function removeReaction(self, emoji, member) -- or user
local channel = self._parent
local client = channel._parent._parent or channel._parent
if type(emoji) == 'table' then
emoji = format('%s:%s', emoji._name, emoji._id)
end
local success
if member then
success = client._api:deleteUserReaction(channel._id, self._id, emoji, member.id)
else
success = client._api:deleteOwnReaction(channel._id, self._id, emoji)
end
if success then
self:_removeReaction({emoji = {id = emoji._id, name = emoji._name or emoji}}, self.client.user, true)
end
return success
end
local function clearReactions(self)
local channel = self._parent
local client = channel._parent._parent or channel._parent
local success = client._api:deleteAllReactions(channel._id, self._id)
return success
end
local function getReactions(self)
local reactions, k, v = self._reactions
if not reactions then return function() end end
return function()
k, v = next(reactions, k)
return v
end
end
local function getReactionUsers(self, emoji)
local channel = self._parent
local client = channel._parent._parent or channel._parent
if type(emoji) == 'table' then
emoji = format('%s:%s', emoji._name, emoji._id)
end
local success, data = client._api:getReactions(channel._id, self._id, emoji)
if not success then return function() end end
local users = client._users
local i = 1
return function()
local v = data[i]
if v then
i = i + 1
return users:get(v.id) or users:new(v)
end
end
end
local function setContent(self, content)
local channel = self._parent
local client = channel._parent._parent or channel._parent
local old = self._content
local success, data = client._api:editMessage(channel._id, self._id, {content = content})
if success then
self._old_content = old
self._content = data.content
end
return success
end
local function setEmbed(self, embed)
local channel = self._parent
local client = channel._parent._parent or channel._parent
local success, data = client._api:editMessage(channel._id, self._id, {embed = embed})
if success then self._embeds = data.embeds end
return success
end
local function getCleanContent(self)
local content = self.content
local parent = self._parent
local guild = not parent._is_private and parent._parent
for user in self.mentionedUsers do
local name = guild and user:getMembership(guild).name or user._username
content = content:gsub(format('<@!?%s>', user._id), '@' .. name)
end
for role in self.mentionedRoles do
content = content:gsub(format('<@&%s>', role._id), '@' .. role._name)
end
for channel in self.mentionedChannels do
content = content:gsub(format('<#%s>', channel._id), '#' .. channel._name)
end
content = content:gsub('@everyone', format('@%severyone', char(0)))
content = content:gsub('@here', format('@%shere', char(0)))
return content
end
local function getMember(self)
local channel = self._parent
if channel._is_private then return nil end
return self._author:getMembership(channel._parent)
end
local function getGuild(self)
local channel = self._parent
if not channel._is_private then return channel._parent end
end
local function getMentionedUsers(self)
local mentions, k, v = self._mentions
if not mentions then return function() end end
return function()
k, v = next(mentions, k)
return v
end
end
local function getMentionedRoles(self)
return wrap(function()
local guild = self._parent._parent
if self._mention_everyone then
yield(guild.defaultRole)
end
if self._mention_roles then
local roles = guild._roles
for _, id in ipairs(self._mention_roles) do
local role = roles:get(id)
if role then yield(role) end
end
end
end)
end
local function getMentionedChannels(self)
return wrap(function()
local parent = self._parent._parent
for id in self._content:gmatch('<#(.-)>') do
local channel = parent:getTextChannel(id)
if channel then yield(channel) end
end
end)
end
local function mentionsObject(self, obj)
local type = obj.__name
if type == 'Member' then
obj = obj._user
for user in self:getMentionedUsers() do
if obj == user then return true end
end
elseif type == 'User' then
for user in self:getMentionedUsers() do
if obj == user then return true end
end
elseif type == 'Role' then
for role in self:getMentionedRoles() do
if obj == role then return true end
end
elseif type == 'GuildTextChannel' then
for channel in self:getMentionedChannels() do
if obj == channel then return true end
end
end
return false
end
local function reply(self, ...)
return self._parent:sendMessage(...)
end
local function pin(self)
local channel = self._parent
local client = channel._parent._parent or channel._parent
local success = client._api:addPinnedChannelMessage(channel._id, self._id)
if success then self._pinned = true end
return success
end
local function unpin(self)
local channel = self._parent
local client = channel._parent._parent or channel._parent
local success = client._api:deletePinnedChannelMessage(channel._id, self._id)
if success then self._pinned = false end
return success
end
local function delete(self)
local channel = self._parent
local client = channel._parent._parent or channel._parent
return (client._api:deleteMessage(channel._id, self._id))
end
property('content', '_content', setContent, 'string', "The raw message text")
property('oldContent', '_old_content', nil, 'string?', "The raw message text before the most recent edit")
property('cleanContent', getCleanContent, nil, 'string', "The message text with sanitized mentions")
property('tts', '_tts', nil, 'boolean', "Whether the message is a TTS one")
property('pinned', '_pinned', nil, 'boolean', "Whether the message is pinned")
property('nonce', '_nonce', nil, '*', "User-defined message identifier")
property('timestamp', '_timestamp', nil, 'string', "Date and time that the message was created")
property('editedTimestamp', '_edited_timestamp', nil, 'string?', "Date and time that the message was edited")
property('channel', '_parent', nil, 'TextChannel', "The channel in which the message exists (GuildTextChannel or PrivateChannel)")
property('author', '_author', nil, 'User', "The user object representing the message's author")
property('member', getMember, nil, 'Member?', "The member object for the author (does not exist for private channels)")
property('guild', getGuild, nil, 'Guild?', "The guild in which the message exists (does not exist for private channels)")
property('mentionedUsers', getMentionedUsers, nil, 'function', "An iterator for known Users that are mentioned in the message")
property('mentionedRoles', getMentionedRoles, nil, 'function', "An iterator for known Roles that are mentioned in the message")
property('mentionedChannels', getMentionedChannels, nil, 'function', "An iterator for known GuildTextChannels that are mentioned in the message")
property('reactions', getReactions, nil, 'function', "An iterator for known Reactions that this message has")
property('attachment', getAttachment, nil, 'table?', "A shortcut to the first known attachment that this message has")
property('attachments', '_attachments', nil, 'table', "Known attachments that this message has")
property('embed', getEmbed, setEmbed, 'table?', "A shortcut to the first known embed that this message has")
property('embeds', '_embeds', nil, 'table', "Known embeds that this message has")
method('reply', reply, 'content', "Shortcut for `message.channel:sendMessage`.", 'HTTP')
method('pin', pin, nil, "Adds the message to the channel's pinned messages.", 'HTTP')
method('unpin', unpin, nil, "Removes the message from the channel's pinned messages.", 'HTTP')
method('delete', delete, nil, "Permanently deletes the message from the channel.", 'HTTP')
method('mentionsObject', mentionsObject, 'obj', "Returns a boolean indicating whether the provided object was mentioned in the message.")
method('addReaction', addReaction, 'emoji', "Adds an emoji (object or string) reaction to the message.", 'HTTP')
method('removeReaction', removeReaction, 'emoji[, member]', "Removes an emoji (object or string) reaction from the message.", 'HTTP')
method('clearReactions', clearReactions, nil, "Removes all emoji reactions from the message.", 'HTTP')
method('getReactionUsers', getReactionUsers, 'Emoji or string', "Returns an iterator for the Users that have reacted with a specific emoji.", 'HTTP')
return Message
|
local GAMESTATES = {}
insertTable(GAMESTATES)
local levels = {}
local maxLevels = 0
function GAMESTATES.initialize()
SPLASH = require("states/splash")
TITLE = require("states/title")
GAME_INTRO = require("states/gameIntro")
GAMESTATES.levelLoad()
OPTIONS = require("states/options")
ABOUT = require("states/about")
CREDITS = require("states/credits")
EXIT = require("states/exit")
UNFINISHED = require("states/unfinished")
FINISHED = require("states/finished")
end
function GAMESTATES.start(first)
local first = first or SPLASH
STATE = first
GAMESTATES.preload()
end
function GAMESTATES.preload()
STATE.preload()
end
function GAMESTATES.load()
STATE.load()
end
function GAMESTATES.update(dt)
if ASSETS.getState() == false then
ASSETS.update(dt)
else
STATE.update(dt)
end
end
function GAMESTATES.draw()
if ASSETS.getState() == false then
ASSETS.draw()
else
STATE.draw()
end
end
function GAMESTATES.keypressed(key)
if ASSETS.getState() == true then
STATE.keypressed(key)
if key == "r" then
GAMESTATES.setState(STATE)
elseif key == "escape" then
GAMESTATES.setState(TITLE)
elseif key == "g" then
love.system.openURL("http://gamejolt.com/games/goinghome/237280")
end
end
end
function GAMESTATES.keyreleased(key)
if ASSETS.getState() == true then
STATE.keyreleased(key)
end
end
function GAMESTATES.setState(newState)
if settings.debug == true then
print(STATE:getTag() .. " to " .. newState:getTag())
end
STATE.exit()
STATE = newState
STATE.preload()
end
function GAMESTATES.getState()
return STATE:getTag()
end
function GAMESTATES.levelLoad()
local name = "LEVEL_"
local dir = "levels"
for k, file in ipairs(love.filesystem.getDirectoryItems(dir)) do
local level = string.sub(file,1,-5)
lvl = require(dir .. "/" .. level)
maxLevels = maxLevels + 1
end
end
function GAMESTATES.getLevels()
return levels
end
function GAMESTATES.insertLevel(lvl)
table.insert(levels,lvl)
end
function GAMESTATES.nextLevel()
local current = GAMESTATES.getState()
local nextLevel = string.sub(current,1,-2)
local reversed = string.reverse(current)
local int = string.sub(reversed,1,1)
local nextInt = tonumber(int) + 1
if nextInt < maxLevels then
GAMESTATES.setState(levels[nextInt])
elseif nextInt == maxLevels then
GAMESTATES.setState(FINISHED)
end
end
function GAMESTATES.getInt()
return STATE.getInt()
end
function GAMESTATES.getMaxLevels()
return maxLevels
end
function GAMESTATES.getGoal()
return STATE.goal()
end
return GAMESTATES
|
--[[ Copyright (c) 2009 Edvin "Lego3" Linge
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. --]]
--! Drug Casebook fullscreen window (view disease statistics and set prices).
class "UICasebook" (UIFullscreen)
---@type UICasebook
local UICasebook = _G["UICasebook"]
function UICasebook:UICasebook(ui, disease_selection)
self:UIFullscreen(ui)
local gfx = ui.app.gfx
if not pcall(function()
self.background = gfx:loadRaw("DrugN01V", 640, 480)
local palette = gfx:loadPalette("QData", "DrugN01V.pal")
palette:setEntry(255, 0xFF, 0x00, 0xFF) -- Make index 255 transparent
self.panel_sprites = gfx:loadSpriteTable("QData", "DrugN02V", true, palette)
self.title_font = gfx:loadFont("QData", "Font25V", false, palette)
self.selected_title_font = gfx:loadFont("QData", "Font26V", false, palette)
self.drug_font = gfx:loadFont("QData", "Font24V", false, palette)
end) then
ui:addWindow(UIInformation(ui, {_S.errors.dialog_missing_graphics}))
self:close()
return
end
self.ui = ui
self.hospital = ui.hospital
self.casebook = self.hospital.disease_casebook
self:updateDiseaseList()
-- Buttons
self:addPanel(0, 607, 449):makeButton(0, 0, 26, 26, 3, self.close):setTooltip(_S.tooltip.casebook.close)
self:addPanel(0, 439, 29):makeRepeatButton(0, 0, 70, 46, 1, self.scrollUp):setTooltip(_S.tooltip.casebook.up)
self:addPanel(0, 437, 394):makeRepeatButton(0, 0, 77, 53, 2, self.scrollDown):setTooltip(_S.tooltip.casebook.down)
self:addPanel(0, 354, 133):makeRepeatButton(0, 0, 22, 22, 5, self.increasePay):setTooltip(_S.tooltip.casebook.increase)
self:addPanel(0, 237, 133):makeRepeatButton(0, 0, 22, 22, 4, self.decreasePay):setTooltip(_S.tooltip.casebook.decrease)
self:addPanel(0, 235, 400):makeButton(0, 0, 140, 20, 0, self.concentrateResearch)
:setTooltip(_S.tooltip.casebook.research)
self:registerKeyHandlers();
-- Icons representing cure effectiveness and other important information.
self.machinery = self:addPanel(6, 306, 352):setTooltip(_S.tooltip.casebook.cure_type.machine)
self.machinery.visible = false
self.drug = self:addPanel(7, 306, 352):setDynamicTooltip(--[[persistable:casebook_drug_tooltip]] function()
return _S.tooltip.casebook.cure_type.drug_percentage:format(self.casebook[self.selected_disease].cure_effectiveness)
end)
self.drug.visible = false
self.surgery = self:addPanel(8, 306, 352):setTooltip(_S.tooltip.casebook.cure_type.surgery)
self.surgery.visible = false
self.unknown = self:addPanel(9, 306, 352):setTooltip(_S.tooltip.casebook.cure_type.unknown)
self.unknown.visible = false
self.psychiatry = self:addPanel(10, 306, 352):setTooltip(_S.tooltip.casebook.cure_type.psychiatrist)
self.psychiatry.visible = false
self.curable = self:addPanel(11, 335, 352):setTooltip(_S.tooltip.casebook.cure_requirement.possible)
self.curable.visible = false
self.not_curable = self:addPanel(12, 335, 352):setTooltip(_S.tooltip.casebook.cure_requirement.not_possible) -- TODO: split up in more specific requirements
self.not_curable.visible = false
self.percentage_counter = false -- Counter for displaying cure price percentage for a certain time before switching to price.
self:makeTooltip(_S.tooltip.casebook.reputation, 249, 72, 362, 117)
self:makeTooltip(_S.tooltip.casebook.treatment_charge, 249, 117, 362, 161)
self:makeTooltip(_S.tooltip.casebook.earned_money, 247, 161, 362, 205)
self:makeTooltip(_S.tooltip.casebook.cured, 247, 205, 362, 249)
self:makeTooltip(_S.tooltip.casebook.deaths, 247, 249, 362, 293)
self:makeTooltip(_S.tooltip.casebook.sent_home, 247, 293, 362, 337)
if disease_selection then
self:selectDisease(disease_selection)
else
self.selected_index = #self.names_sorted
self.selected_disease = self.names_sorted[self.selected_index]
self:updateIcons()
end
end
function UICasebook:registerKeyHandlers()
-- Hotkeys
self:addKeyHandler("ingame_scroll_up", self.scrollUp)
self:addKeyHandler("ingame_scroll_down", self.scrollDown)
self:addKeyHandler("ingame_scroll_left", self.decreasePay)
self:addKeyHandler("ingame_scroll_right", self.increasePay)
end
function UICasebook:close()
UIFullscreen.close(self)
self.ui:getWindow(UIBottomPanel):updateButtonStates()
end
--! The diseases list has been changed, update the list.
function UICasebook:updateDiseaseList()
-- A sorted list of known diseases and pseudo diseases.
-- Used to be able to list the diseases in, believe it or not,
-- alphabetical order.
self.names_sorted = {}
for n, value in pairs(self.casebook) do
if value.discovered then
self.names_sorted[#self.names_sorted + 1] = n
end
end
table.sort(self.names_sorted, function(d1, d2)
local c1, c2 = self.casebook[d1], self.casebook[d2]
if c1.pseudo ~= c2.pseudo then
return c1.pseudo
end
return c1.disease.name:upper() < c2.disease.name:upper()
end)
if self.selected_disease then -- Re-select the current disease.
self:selectDisease(self.selected_disease)
end
end
--! Select a disease by name.
--!param disease (string) Name of the disease
function UICasebook:selectDisease(disease)
for i = 1, #self.names_sorted do
if disease == self.names_sorted[i] then
self.selected_index = i
self.selected_disease = self.names_sorted[self.selected_index]
break
end
end
self:updateIcons()
end
--! Function that is called when a new entry is selected in some way
--! It updates all icons etc. that react to what is selected
function UICasebook:updateIcons()
local disease = self.selected_disease
local hosp = self.hospital
local known = true
-- Curable / not curable icons and their tooltip
if self.casebook[disease].pseudo then
self.curable.visible = false
self.not_curable.visible = false
else
local req = hosp:checkDiseaseRequirements(disease)
if not req then
self.curable.visible = true
self.not_curable.visible = false
else
self.curable.visible = false
self.not_curable.visible = true
-- Strings for the tooltip
local research = false
local build = false
local staff = false
-- Room requirements
for _, room_id in ipairs(req.rooms) do
-- Not researched yet?
if not hosp:isRoomDiscovered(room_id) then
known = false
research = (research and (research .. ", ") or " (") .. TheApp.rooms[room_id].name
end
-- Researched, but not built. TODO: maybe make this an else clause to not oversize the tooltip that much
build = (build and (build .. ", ") or " (") .. TheApp.rooms[room_id].name
end
research = research and (_S.tooltip.casebook.cure_requirement.research_machine .. research .. "). ") or ""
build = build and (_S.tooltip.casebook.cure_requirement.build_room .. build .. "). ") or ""
-- Staff requirements
for sclass, amount in pairs(req.staff) do
staff = (staff and (staff .. ", ") or " (") .. StaffProfile.translateStaffClass(sclass) .. ": " .. amount
end
staff = staff and (_S.tooltip.casebook.cure_requirement.hire_staff .. staff .. "). ") or ""
self.not_curable:setTooltip(research .. build .. staff)
end
end
self.unknown.visible = not known
self.drug.visible = known and not not self.casebook[disease].drug
self.machinery.visible = known and not not self.casebook[disease].machine and not self.casebook[disease].pseudo
self.psychiatry.visible = known and not not self.casebook[disease].psychiatrist
self.surgery.visible = known and not not self.casebook[disease].surgeon
self.ui:updateTooltip() -- for the case that mouse is hovering over icon while player scrolls through list with keys
self.percentage_counter = 50
end
function UICasebook:draw(canvas, x, y)
self.background:draw(canvas, self.x + x, self.y + y)
UIFullscreen.draw(self, canvas, x, y)
x, y = self.x + x, self.y + y
local titles = self.title_font
local book = self.casebook
local disease = self.selected_disease
local selected = self.selected_index
-- All titles
titles:draw(canvas, _S.casebook.reputation, x + 278, y + 68)
titles:draw(canvas, _S.casebook.treatment_charge, x + 260, y + 113)
titles:draw(canvas, _S.casebook.earned_money, x + 265, y + 157)
titles:draw(canvas, _S.casebook.cured, x + 276, y + 201)
titles:draw(canvas, _S.casebook.deaths, x + 279, y + 245)
titles:draw(canvas, _S.casebook.sent_home, x + 270, y + 289)
titles:draw(canvas, _S.casebook.cure, x + 255, y + 354)
-- Specific disease information
if self.hospital:canConcentrateResearch(disease) then
if book[disease].concentrate_research then -- Concentrate research
self.selected_title_font:draw(canvas, _S.casebook.research, x + 245, y + 398)
else
titles:draw(canvas, _S.casebook.research, x + 245, y + 398)
end
end
local rep = book[disease].reputation or self.hospital.reputation
if rep < self.hospital.reputation_min then
rep = self.hospital.reputation_min
elseif rep > self.hospital.reputation_max then
rep = self.hospital.reputation_max
end
titles:draw(canvas, rep, x + 248, y + 92, 114, 0) -- Reputation
-- Treatment Charge is either displayed in percent, or normally
local price_text = self.percentage_counter and ("%.0f%%"):format(book[disease].price * 100) or
"$" .. self.hospital:getTreatmentPrice(disease)
titles:draw(canvas, price_text, x + 262, y + 137, 90, 0) -- Treatment Charge
titles:draw(canvas, "$" .. book[disease].money_earned, x + 248, y + 181, 114, 0) -- Money Earned
titles:draw(canvas, book[disease].recoveries, x + 248, y + 225, 114, 0) -- Recoveries
titles:draw(canvas, book[disease].fatalities, x + 248, y + 269, 114, 0) -- Fatalities
titles:draw(canvas, book[disease].turned_away, x + 248, y + 313, 114, 0) -- Turned away
-- Cure percentage
if self.drug.visible then
self.drug_font:draw(canvas, book[disease].cure_effectiveness, x + 313, y + 364, 16, 0)
end
-- Right-hand side list of diseases (and pseudo diseases)
local index = 1
while selected - index > 0 and index <= 7 do
titles:draw(canvas, book[self.names_sorted[selected - index]].disease.name:upper(), x + 409, y + 203 - index*18)
index = index + 1
end
self.selected_title_font:draw(canvas, book[disease].disease.name:upper(), x + 409, y + 227)
index = 1
while index + selected <= #self.names_sorted and index <= 7 do
titles:draw(canvas, book[self.names_sorted[index + selected]].disease.name:upper(), x + 409, y + 251 + index*18)
index = index + 1
end
end
function UICasebook:scrollUp()
if self.selected_index > 1 then
if self.ui.app.key_modifiers.ctrl then
self.selected_index = 1
else
self.selected_index = self.selected_index - 1
end
self.selected_disease = self.names_sorted[self.selected_index]
self.ui:playSound("pagetur2.wav")
else
self.ui:playSound("Wrong2.wav")
end
self:updateIcons()
end
function UICasebook:scrollDown()
if self.selected_index < #self.names_sorted then
if self.ui.app.key_modifiers.ctrl then
self.selected_index = #self.names_sorted
else
self.selected_index = self.selected_index + 1
end
self.selected_disease = self.names_sorted[self.selected_index]
self.ui:playSound("pagetur2.wav")
else
self.ui:playSound("Wrong2.wav")
end
self:updateIcons()
end
function UICasebook:increasePay()
local price = self.casebook[self.selected_disease].price
local amount = 0.01
if self.ui.app.key_modifiers.ctrl then
amount = amount * 25
elseif self.ui.app.key_modifiers.shift then
amount = amount * 5
end
price = price + amount
if price > 2 then
price = 2
self.ui:playSound("Wrong2.wav")
else
self.ui:playSound("selectx.wav")
end
self.casebook[self.selected_disease].price = price
self.percentage_counter = 50
end
function UICasebook:decreasePay()
local price = self.casebook[self.selected_disease].price
local amount = 0.01
if self.ui.app.key_modifiers.ctrl then
amount = amount * 25
elseif self.ui.app.key_modifiers.shift then
amount = amount * 5
end
price = price - amount
if price < 0.5 then
price = 0.5
self.ui:playSound("Wrong2.wav")
else
self.ui:playSound("selectx.wav")
end
self.casebook[self.selected_disease].price = price
self.percentage_counter = 50
end
function UICasebook:concentrateResearch()
if self.hospital:canConcentrateResearch(self.selected_disease) then
self.hospital.research:concentrateResearch(self.selected_disease)
end
end
function UICasebook:onMouseDown(button, x, y)
-- Normal window operations if outside the disease list
if x < 395 or x > 540 or y < 77 or y > 394 then
return UIFullscreen.onMouseDown(self, button, x, y)
end
local index_diff
if y < 203 then
index_diff = -7 + math.floor((y - 77) / 18)
elseif y > 269 then
index_diff = math.floor((y - 269) / 18) + 1
else
return
end
-- Clicking on a disease name scrolls to the disease
local new_index = self.selected_index + index_diff
if new_index >= 1 and new_index <= #self.names_sorted then
self.selected_index = new_index
self.selected_disease = self.names_sorted[self.selected_index]
self.ui:playSound("pagetur2.wav")
self:updateIcons()
end
end
function UICasebook:onMouseWheel(x, y)
if not UIFullscreen.onMouseWheel(self, x, y) then
if self:hitTest(self.cursor_x, self.cursor_y) then
if y > 0 then
self:scrollUp()
return true
else
self:scrollDown()
return true
end
end
return false
else
return true
end
end
function UICasebook:onTick()
-- Decrease counter for showing percentage of cure price, if applicable
if self.percentage_counter then
self.percentage_counter = self.percentage_counter - 1
if self.percentage_counter <= 0 then
self.percentage_counter = false
end
end
return UIFullscreen.onTick(self)
end
function UICasebook:afterLoad(old, new)
UIFullscreen.afterLoad(self, old, new)
self:registerKeyHandlers()
end
|
-- written by groverbuger for g3d
-- january 2021
-- MIT license
--[[
__ __
/'__`\ /\ \
__ /\_\L\ \ \_\ \
/'_ `\/_/_\_<_ /'_` \
/\ \L\ \/\ \L\ \/\ \L\ \
\ \____ \ \____/\ \___,_\
\/___L\ \/___/ \/__,_ /
/\____/
\_/__/
--]]
-- add the path to g3d to the global namespace
-- so submodules can know how to load their dependencies
G3D_PATH = ...
local g3d = {}
g3d.newModel = require(G3D_PATH .. "/model")
g3d.camera = require(G3D_PATH .. "/camera")
g3d.camera.updateProjectionMatrix()
g3d.camera.updateViewMatrix()
-- so that far polygons don't overlap near polygons
love.graphics.setDepthMode("lequal", true)
-- get rid of G3D_PATH from the global namespace
-- so the end user doesn't have to worry about any globals
G3D_PATH = nil
return g3d
|
-- import
local SignalModule = require 'candy.signal'
local GlobalManagerModule = require 'candy.GlobalManager'
local GlobalManager = GlobalManagerModule.GlobalManager
---@class ThemeMgr : GlobalManager
local ThemeMgr = CLASS: ThemeMgr ( GlobalManager )
---
-- Constructor.
function ThemeMgr:__init()
assert ( rawget ( ThemeMgr, _singleton ) == nil )
self.theme = require "candy.ui.BaseTheme"
end
---
-- Set the theme of widget.
---@param theme theme of widget
function ThemeMgr:setTheme ( theme )
if self.theme ~= theme then
self.theme = theme
SignalModule.emitGlobalSignal ( UIEvent.theme_changed )
end
end
---
-- override the theme of widget.
---@param theme theme of widget
function ThemeMgr:overrideTheme ( theme )
local newTheme = {}
local copyTheme = function ( srcTheme )
for k, v in pairs( srcTheme ) do
if newTheme[ k ] ~= nil then
local style = newTheme[ k ]
for k2, v2 in pairs ( v ) do
style[ k2 ] = v2
end
else
newTheme[ k ] = table.simplecopy ( v )
end
end
end
copyTheme ( self.theme )
copyTheme ( theme )
self:setTheme ( newTheme )
end
---
-- Return the theme of widget.
---@return theme
function ThemeMgr:getTheme ()
return self.theme
end
ThemeMgr ()
return ThemeMgr
|
local util = game.tactics.util
local LUNGE_ACCEL = 500
local LUNGE_DUR = 0.2
local CHASE_ACCEL = 300
local LUNGE_RANGE = 200
local LUNGE_ADJUST = 5
return function(params)
local agility = params.agility or 1
local endurance = 1 / ((agility + 2) / 3)
local lungeAccel = LUNGE_ACCEL * ((agility + LUNGE_ADJUST) / (LUNGE_ADJUST + 1))
local chaseAccel = CHASE_ACCEL * agility
return function(env)
local AfterWaiting, AfterChasing, AfterLunging
local phases = {}
local tactics = {}
function tactics.Wait(time)
return game.tactics.Wait { onCompleted=phases.StartAttack, time=time or 1.0 / (endurance * 2) }
end
function tactics.Chase()
local chaseDuration = (1 * math.random() + 1) * endurance
return game.tactics.Chase { onCompleted=phases.AfterChase, accel=chaseAccel, duration=chaseDuration }
end
function tactics.Lunge()
local toPlayer = util.getPlayer(env.system) - env.entity.pos
local dist = toPlayer:length()
if dist < LUNGE_RANGE then
local lungeDuration = (LUNGE_DUR) * endurance
return game.tactics.Lunge { onCompleted=phases.AfterAttack, accel=lungeAccel, duration=lungeDuration }
else
return tactics.Wait()
end
end
function phases.StartAttack()
if env.entity.flicker then
return tactics.Wait(0.1)
elseif math.random() > 0.5 then
return tactics.Chase()
else
return tactics.Lunge()
end
end
function phases.AfterChase()
return tactics.Lunge()
end
function phases.AfterAttack()
return tactics.Wait(math.random() * 0.5 + 0.25)
end
function phases.AfterInjured()
return tactics.Wait()
end
local function onEvent(event, args)
if event == game.event.Injured then
env.controller:setTactic(phases.AfterInjured())
end
end
return tactics.Wait(0.5), onEvent
end
end
|
--[[
Licensed under GNU General Public License v2
* (c) 2019, Alphonse Mariyagnanaseelan
Class representing a binary tree.
--]]
local table = table
local tostring = tostring
local bintree = { }
bintree.__index = bintree
-- Create tree from table
function bintree.treeify(node, parent)
if not node then return nil end
setmetatable(node, bintree)
node.parent = parent
if #node == 1 then
node.data, node[1] = node[1], nil
elseif #node == 3 then
node.left, node[1] = node[1], nil
node.data, node[2] = node[2], nil
node.right, node[3] = node[3], nil
end
bintree.treeify(node.left, node)
bintree.treeify(node.right, node)
return node
end
-- New node
function bintree.new(data, parent, left, right)
return setmetatable({
data = data,
parent = parent,
left = left,
right = right,
}, bintree)
end
-- Set left node
function bintree:set_left(node)
if node then node.parent = self end
self.left = node
return self.left
end
-- Set right node
function bintree:set_right(node)
if node then node.parent = self end
self.right = node
return self.right
end
-- New left node
function bintree:set_new_left(data)
return self:set_left(bintree.new(data, self))
end
-- New right node
function bintree:set_new_right(data)
return self:set_right(bintree.new(data, self))
end
-- Get sibling node
function bintree:get_sibling()
if not self.parent then return nil end
if self.parent.left == self then
return self.parent.right
elseif self.parent.right == self then
return self.parent.left
else
assert(false)
return nil
end
end
-- Get rightmost leaf node
function bintree:get_rightmost()
return self.right and self.right:get_rightmost() or self
end
-- Get leftmost leaf node
function bintree:get_leftmost()
return self.left and self.left:get_leftmost() or self
end
-- Remove node (with cleanup function)
function bintree:remove(fn, ...)
if fn then fn(self, ...) end
if self.parent then
if self.parent.left == self then
self.parent.left = nil
elseif self.parent.right == self then
self.parent.right = nil
end
end
self.data = nil
self.parent = nil
self.left = nil
self.right = nil
end
function bintree:swap_children()
self.left, self.right = self.right, self.left
end
-- Get node if predicate returns true
function bintree:find_if(fn, ...)
if fn(self, ...) then return self end
return self.left and self.left:find_if(fn, ...)
or self.right and self.right:find_if(fn, ...)
end
-- Apply to each node (in-order tree traversal)
function bintree:apply(fn, ...)
if self.left then self.left:apply(fn, ...) end
fn(self, ...)
if self.right then self.right:apply(fn, ...) end
end
-- Apply to each node, with levels (in-order tree traversal)
function bintree:apply_levels(fn, level)
if not level then level = 0 end
if self.left then self.left:apply_levels(fn, level + 1) end
fn(self, level)
if self.right then self.right:apply_levels(fn, level + 1) end
end
-- Print tree
function bintree:show()
self:apply_levels(function(node, level)
print(table.concat {
string.rep(" ", level), " + [", tostring(node.data), "]",
})
end)
end
return bintree
|
function love.conf(t)
t.title = "Not Pacman"
t.identity = "not_pacman"
t.author = "Maurice"
t.console = false
t.screen.vsync = true
t.screen.fsaa = 16
t.screen.width = 640
t.screen.height = 500
end
|
-- Player Animations
-- Create module's return table
Animation = {}
-- Load jambo's animations
local animations = require("scripts.jambo_animations")
-- Idle is default animation
local defaultAnimation = animations.idle_animation
function Animation.new()
-- Constructor
local self = {}
-- Private variables
local current_animation = defaultAnimation -- Select default animation
-- Public methods:
-- State functions
function self.idle()
if current_animation ~= animations.idle_animation then
current_animation:reset()
current_animation = animations.idle_animation
end
end
function self.running()
if current_animation ~= animations.run_animation then
current_animation:reset()
current_animation = animations.run_animation
end
end
function self.jumping()
if current_animation ~= animations.jump_animation then
current_animation:reset()
current_animation = animations.jump_animation
end
end
function self.crouching()
if current_animation ~= animations.crouch_animation then
current_animation:reset()
current_animation = animations.crouch_animation
end
end
function self.lookingUp()
if current_animation ~= animations.lookup_animation then
current_animation:reset()
current_animation = animations.lookup_animation
end
end
function self.runUpDiag()
if current_animation ~= animations.runupdiag_animation then
current_animation:reset()
current_animation = animations.runupdiag_animation
end
end
function self.lookingDownDiag()
if current_animation ~= animations.lookdowndiag_animation then
current_animation:reset()
current_animation = animations.lookdowndiag_animation
end
end
function self.jump_aimDiagDown()
if current_animation ~= animations.jumpaimdiagdown_animation then
current_animation:reset()
current_animation = animations.jumpaimdiagdown_animation
end
end
function self.jump_aimDiagUp()
if current_animation ~= animations.jumpaimdiagup_animation then
current_animation:reset()
current_animation = animations.jumpaimdiagup_animation
end
end
function self.jump_aimDown()
if current_animation ~= animations.jumpaimdown_animation then
current_animation:reset()
current_animation = animations.jumpaimdown_animation
end
end
function self.jump_aimUp()
if current_animation ~= animations.jumpaimup_animation then
current_animation:reset()
current_animation = animations.jumpaimup_animation
end
end
function self.update(dt) current_animation:update(dt) end
function self.draw(x, y, sx, sy)
local floor = math.floor
local currentTime = current_animation.currentTime
local duration = current_animation.duration
local quads = current_animation.quads
local spriteNum = floor(currentTime / duration * #quads) + 1
current_animation:draw(x, y, sx, sy, spriteNum)
end
return self
end
return Animation
|
local function head(tbl)
return tbl[1]
end
local function tail(tbl)
return {table.unpack(tbl, 2)}
end
local function fold(fn, tbl, val)
for _, v in pairs(tbl) do
val = fn(val, v)
end
return val
end
local function reduce(fn, tbl)
return fold(fn, tail(tbl), head(tbl))
end
local function minimum(a, b)
if a ~= a then return b
elseif b ~= b then return a
else return math.min(a, b)
end
end
local function min(...)
return reduce(minimum, {...})
end
local function maximum(a, b)
if a ~= a then return b
elseif b ~= b then return a
else return math.max(a, b)
end
end
local function max(...)
return reduce(maximum, {...})
end
local function bound(x, a, b)
if a > b then a, b = b, a end
return max(a, min(x, b))
end
return {
min = min,
max = max,
minimum = minimum,
maximum = maximum,
bound = bound,
head = head,
tail = tail,
reduce = reduce,
}
|
local load_time_start = os.clock()
local function add_stair(name, data)
data.groups.stone = nil
stairs.register_stair_and_slab("morecobblenodes_"..name, "morecobblenodes:"..name,
data.groups,
data.tiles,
data.description.." stair",
data.description.." slab",
data.sounds
)
end
local moss_found = rawget(_G, "moss")
local function register_node(name, data)
minetest.register_node("morecobblenodes:"..name, table.copy(data))
local stair = not data.no_stair
if stair then
add_stair(name, table.copy(data))
end
if not moss_found then
return
end
data.tiles = data.moss
if not data.tiles then
return
end
data.description = "mossy "..data.description
local mossname = name.."_mossy"
if stair then
add_stair(mossname, table.copy(data))
end
minetest.register_node("morecobblenodes:"..mossname, data)
moss.register_moss({
node = "morecobblenodes:"..name,
result = "morecobblenodes:"..mossname
})
end
register_node("stones_big", {
description = "big stones",
tiles = {"morecobblenodes_stones_big.png"},
moss = {"morecobblenodes_stones_big_mossy.png"},
groups = {cracky=3, stone=1},
sounds = default.node_sound_stone_defaults(),
})
register_node("stones_middle", {
description = "stones",
tiles = {"morecobblenodes_stones_middle.png"},
moss = {"morecobblenodes_stones_middle_mossy.png"},
groups = {cracky=3, stone=2},
sounds = default.node_sound_stone_defaults(),
})
register_node("stonebrick_middle", {
description = "stone brick",
tiles = {"morecobblenodes_stone_brick_middle.png"},
moss = {"morecobblenodes_stone_brick_middle_mossy.png"},
groups = {cracky=3, stone=2},
sounds = default.node_sound_stone_defaults(),
})
register_node("sand_and_dirt", {
description = "sand dirt mixed",
tiles = {"morecobblenodes_sand_and_dirt.png"},
groups = {crumbly=3, soil=1, falling_node=1, sand=1},
sounds = default.node_sound_dirt_defaults(),
no_stair = true
})
register_node("sand_and_dirt_grass", {
description = "sand dirt mixed with grass",
tiles = {
"morecobblenodes_grass.png",
"morecobblenodes_sand_and_dirt.png",
"morecobblenodes_sand_and_dirt.png^morecobblenodes_grass_side.png"
},
groups = {crumbly=3, soil=1, sand=1},
drop = "morecobblenodes:sand_and_dirt",
sounds = default.node_sound_dirt_defaults({
footstep = {name="default_grass_footstep", gain=0.25},
}),
no_stair = true
})
local function grass_allowed(pos)
local light = minetest.get_node_light(pos, 0.5)
if not light then
return 0
end
if light < 7 then
return false
end
local nd = minetest.get_node(pos).name
if nd == "air" then
return true
end
if nd == "ignore" then
return 0
end
local data = minetest.registered_nodes[nd]
local drawtype = data.drawtype
if drawtype
and drawtype ~= "normal"
and drawtype ~= "liquid"
and drawtype ~= "flowingliquid" then
return true
end
local light = data.light_source
if light
and light > 0 then
return true
end
return false
end
minetest.register_abm({
nodenames = {"morecobblenodes:sand_and_dirt"},
interval = 20,
chance = 9,
action = function(pos)
local allowed = grass_allowed({x=pos.x, y=pos.y+1, z=pos.z})
if allowed == 0 then
minetest.log("info", "[morecobblenodes] error replacing sand_and_dirt")
return
end
if allowed then
minetest.set_node(pos, {name="morecobblenodes:sand_and_dirt_grass"})
minetest.log("info", "[morecobblenodes] grass grew on sand_and_dirt")
end
end
})
minetest.register_abm({
nodenames = {"morecobblenodes:sand_and_dirt_grass"},
interval = 30,
chance = 9,
action = function(pos)
local allowed = grass_allowed({x=pos.x, y=pos.y+1, z=pos.z})
if allowed == 0 then
minetest.log("info", "[morecobblenodes] error replacing sand_and_dirt_grass")
return
end
if not allowed then
minetest.set_node(pos, {name="morecobblenodes:sand_and_dirt"})
minetest.log("info", "[morecobblenodes] grass disappeared on sand_and_dirt")
end
end
})
--recipes
if rawget(_G, "technic")
and technic.register_separating_recipe then
for _,i in pairs({
{"default:cobble 2", "morecobblenodes:stones_big", "default:gravel"},
{"default:gravel 2", "morecobblenodes:stones_middle", "morecobblenodes:sand_and_dirt"},
{"morecobblenodes:sand_and_dirt 2", "default:sand", "default:dirt"},
}) do
technic.register_separating_recipe({input={i[1]}, output={i[2], i[3]}})
end
end
minetest.register_craft({
output = "morecobblenodes:stonebrick_middle 4",
recipe = {
{"morecobblenodes:stones_middle", "morecobblenodes:stones_middle"},
{"morecobblenodes:stones_middle", "morecobblenodes:stones_middle"},
}
})
local time = math.floor(tonumber(os.clock()-load_time_start)*100+0.5)/100
local msg = "[morecobblenodes] loaded after ca. "..time
if time > 0.05 then
print(msg)
else
minetest.log("info", msg)
end
|
solution("UnityMake")
configurations{ "Debug", "Release", "Master" }
location("../Solution/")
platforms { "x64" }
characterset ("MBCS")
filter { "platforms:x64" }
architecture "x64"
filter { "system:windows" }
defines { "PLATFORM_PC" }
flags { "ExtraWarnings", "FatalWarnings" }
-- Define + Optimization per configuration
filter { "configurations:Debug" }
defines { "DEBUG" }
optimize "Off"
symbols "On"
filter { "configurations:Release or Master"}
defines { "NDEBUG" }
filter { "configurations:Release" }
optimize "On"
filter { "configurations:Master" }
defines { "MASTER" }
optimize "Full"
project("UnityMake")
location("../Solution/")
kind("ConsoleApp")
includedirs
{
"../Sources/"
}
files
{
"../Sources/**.h**",
"../Sources/**.c**",
}
links
{
"Shlwapi.lib"
}
debugdir("../Binaries/")
targetdir("../Binaries/")
|
local pickers = require'telescope._extensions.langtools.action_picker'
local custom_actions = require'telescope._extensions.langtools.custom_actions'
local dotnet_options = {
{ action = 'dotnet clean', text = 'Clean' },
{ action = 'dotnet build', text = 'Build' },
{ action = 'dotnet publish -c Release', text = 'Package' },
{ action = 'dotnet test', text = 'Test' }
}
local M = {
picker = function(opts) pickers.create_picker('Dotnet', dotnet_options, opts) end,
clean = function() custom_actions.run_action(dotnet_options[1]) end,
build = function() custom_actions.run_action(dotnet_options[2]) end,
package = function() custom_actions.run_action(dotnet_options[3]) end,
test = function() custom_actions.run_action(dotnet_options[4]) end,
}
return M
|
-- Copyright (C) 2018 The Dota IMBA Development Team
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Editors:
--
-- Author: Firetoad
-- Date: 19.07.2016
-- Last Update: 26.03.2017
-- Maelstrom, Mjollnir and Jarnbjorn
-----------------------------------------------------------------------------------------------------------
-- Maelstrom definition
-----------------------------------------------------------------------------------------------------------
if item_imba_maelstrom == nil then item_imba_maelstrom = class({}) end
LinkLuaModifier( "modifier_item_imba_maelstrom", "components/items/item_maelstrom.lua", LUA_MODIFIER_MOTION_NONE ) -- Owner's bonus attributes, stackable
function item_imba_maelstrom:GetIntrinsicModifierName()
return "modifier_item_imba_maelstrom" end
function item_imba_maelstrom:GetAbilityTextureName()
return "custom/imba_maelstrom"
end
-----------------------------------------------------------------------------------------------------------
-- Maelstrom passive modifier (stackable)
-----------------------------------------------------------------------------------------------------------
if modifier_item_imba_maelstrom == nil then modifier_item_imba_maelstrom = class({}) end
function modifier_item_imba_maelstrom:IsHidden() return true end
function modifier_item_imba_maelstrom:IsDebuff() return false end
function modifier_item_imba_maelstrom:IsPurgable() return false end
function modifier_item_imba_maelstrom:IsPermanent() return true end
function modifier_item_imba_maelstrom:GetAttributes()
return MODIFIER_ATTRIBUTE_MULTIPLE
end
-- Declare modifier events/properties
function modifier_item_imba_maelstrom:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_PREATTACK_BONUS_DAMAGE,
MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT,
MODIFIER_EVENT_ON_ATTACK_LANDED,
}
return funcs
end
function modifier_item_imba_maelstrom:GetModifierPreAttack_BonusDamage()
return self:GetAbility():GetSpecialValueFor("bonus_damage") end
function modifier_item_imba_maelstrom:GetModifierAttackSpeedBonus_Constant()
return self:GetAbility():GetSpecialValueFor("bonus_as") end
-- On attack landed, roll for proc and apply stacks
function modifier_item_imba_maelstrom:OnAttackLanded( keys )
if IsServer() then
local attacker = self:GetParent()
-- If this attack is irrelevant, do nothing
if attacker ~= keys.attacker then
return
end
-- If this is an illusion, do nothing either
if attacker:IsIllusion() then
return
end
-- If the target is invalid, still do nothing
local target = keys.target
if (not target:IsHeroOrCreep()) then -- or attacker:GetTeam() == target:GetTeam() then
return end
-- All conditions met, stack the proc counter up
local ability = self:GetAbility()
-- zap the target's ass
local proc_chance = ability:GetSpecialValueFor("proc_chance")
if RollPseudoRandom(proc_chance, ability) then
LaunchLightning(attacker, target, ability, ability:GetSpecialValueFor("bounce_damage"), ability:GetSpecialValueFor("bounce_radius"))
end
end
end
-----------------------------------------------------------------------------------------------------------
-- Mjollnir definition
-----------------------------------------------------------------------------------------------------------
if item_imba_mjollnir == nil then item_imba_mjollnir = class({}) end
LinkLuaModifier( "modifier_item_imba_mjollnir", "components/items/item_maelstrom.lua", LUA_MODIFIER_MOTION_NONE ) -- Owner's bonus attributes, stackable
LinkLuaModifier( "modifier_item_imba_mjollnir_counter", "components/items/item_maelstrom.lua", LUA_MODIFIER_MOTION_NONE ) -- Attack proc counter
LinkLuaModifier( "modifier_item_imba_mjollnir_static", "components/items/item_maelstrom.lua", LUA_MODIFIER_MOTION_NONE ) -- Static shield
LinkLuaModifier( "modifier_item_imba_mjollnir_static_counter", "components/items/item_maelstrom.lua", LUA_MODIFIER_MOTION_NONE ) -- Shield proc counter
LinkLuaModifier( "modifier_item_imba_mjollnir_slow", "components/items/item_maelstrom.lua", LUA_MODIFIER_MOTION_NONE ) -- Shield slow
function item_imba_mjollnir:GetIntrinsicModifierName()
return "modifier_item_imba_mjollnir"
end
function item_imba_mjollnir:GetAbilityTextureName()
return "item_mjollnir"
end
function item_imba_mjollnir:OnSpellStart()
if IsServer() then
-- Apply the modifier to the target
local target = self:GetCursorTarget()
target:AddNewModifier(target, self, "modifier_item_imba_mjollnir_static", {duration = self:GetSpecialValueFor("static_duration")})
-- Play cast sound
target:EmitSound("DOTA_Item.Mjollnir.Activate")
end
end
-----------------------------------------------------------------------------------------------------------
-- Mjollnir passive modifier (stackable)
-----------------------------------------------------------------------------------------------------------
if modifier_item_imba_mjollnir == nil then modifier_item_imba_mjollnir = class({}) end
function modifier_item_imba_mjollnir:IsHidden() return true end
function modifier_item_imba_mjollnir:IsDebuff() return false end
function modifier_item_imba_mjollnir:IsPurgable() return false end
function modifier_item_imba_mjollnir:IsPermanent() return true end
function modifier_item_imba_mjollnir:GetAttributes()
return MODIFIER_ATTRIBUTE_MULTIPLE
end
-- Declare modifier events/properties
function modifier_item_imba_mjollnir:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_PREATTACK_BONUS_DAMAGE,
MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT,
MODIFIER_EVENT_ON_ATTACK_LANDED,
}
return funcs
end
function modifier_item_imba_mjollnir:GetModifierPreAttack_BonusDamage()
return self:GetAbility():GetSpecialValueFor("bonus_damage") end
function modifier_item_imba_mjollnir:GetModifierAttackSpeedBonus_Constant()
return self:GetAbility():GetSpecialValueFor("bonus_as") end
-- On attack landed, roll for proc and apply stacks
function modifier_item_imba_mjollnir:OnAttackLanded( keys )
if IsServer() then
local attacker = self:GetParent()
-- If this attack is irrelevant, do nothing
if attacker ~= keys.attacker then
return
end
-- If this is an illusion, do nothing either
if attacker:IsIllusion() then
return
end
-- If the target is invalid, still do nothing
local target = keys.target
if (not target:IsHeroOrCreep()) then -- or attacker:GetTeam() == target:GetTeam() then
return
end
-- All conditions met, stack the proc counter up
local ability = self:GetAbility()
-- zap the target's ass
local proc_chance = ability:GetSpecialValueFor("proc_chance")
if RollPseudoRandom(proc_chance, ability) then
LaunchLightning(attacker, target, ability, ability:GetSpecialValueFor("bounce_damage"), ability:GetSpecialValueFor("bounce_radius"))
end
end
end
-----------------------------------------------------------------------------------------------------------
-- Mjollnir static shield
-----------------------------------------------------------------------------------------------------------
if modifier_item_imba_mjollnir_static == nil then modifier_item_imba_mjollnir_static = class({}) end
function modifier_item_imba_mjollnir_static:IsHidden() return false end
function modifier_item_imba_mjollnir_static:IsDebuff() return false end
function modifier_item_imba_mjollnir_static:IsPurgable() return true end
-- Modifier particle
function modifier_item_imba_mjollnir_static:GetEffectName()
return "particles/items2_fx/mjollnir_shield.vpcf" end
function modifier_item_imba_mjollnir_static:GetEffectAttachType()
return PATTACH_ABSORIGIN_FOLLOW end
-- Start playing sound and store ability parameters
function modifier_item_imba_mjollnir_static:OnCreated()
if IsServer() then
self:GetParent():EmitSound("DOTA_Item.Mjollnir.Loop")
self.static_cooldown = false
end
end
function modifier_item_imba_mjollnir_static:OnIntervalThink()
self.static_cooldown = false
self:StartIntervalThink(-1)
end
-- Stop playing sound and destroy the proc counter
function modifier_item_imba_mjollnir_static:OnDestroy()
if IsServer() then
StopSoundEvent("DOTA_Item.Mjollnir.Loop", self:GetParent())
self:GetParent():RemoveModifierByName("modifier_item_imba_mjollnir_static_counter")
end
end
-- Declare modifier events/properties
function modifier_item_imba_mjollnir_static:DeclareFunctions()
local funcs = {
MODIFIER_EVENT_ON_TAKEDAMAGE,
}
return funcs
end
-- On damage taken, count stacks and proc the static shield
function modifier_item_imba_mjollnir_static:OnTakeDamage( keys )
if IsServer() then
local shield_owner = self:GetParent()
-- If this damage event is irrelevant, do nothing
if shield_owner ~= keys.unit then
return end
-- If the attacker is invalid, do nothing either
if keys.attacker:GetTeam() == shield_owner:GetTeam() then
return end
-- All conditions met, stack the proc counter up
local ability = self:GetAbility()
-- If enough stacks accumulated, reset them and zap nearby enemies
local static_proc_chance = ability:GetSpecialValueFor("static_proc_chance")
local static_damage = ability:GetSpecialValueFor("static_damage")
local static_radius = ability:GetSpecialValueFor("static_radius")
local static_slow_duration = ability:GetSpecialValueFor("static_slow_duration")
if not self.static_cooldown and keys.damage >= 5 and RollPseudoRandom(static_proc_chance, ability) then
self.static_cooldown = true
self:StartIntervalThink(ability:GetSpecialValueFor("static_cooldown"))
-- Iterate through nearby enemies
local static_origin = shield_owner:GetAbsOrigin() + Vector(0, 0, 100)
local nearby_enemies = FindUnitsInRadius(shield_owner:GetTeamNumber(), shield_owner:GetAbsOrigin(), nil, static_radius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_NO_INVIS + DOTA_UNIT_TARGET_FLAG_FOW_VISIBLE, FIND_ANY_ORDER, false)
for _, enemy in pairs(nearby_enemies) do
-- Play particle
local static_pfx = ParticleManager:CreateParticle("particles/item/mjollnir/static_lightning_bolt.vpcf", PATTACH_ABSORIGIN_FOLLOW, shield_owner)
ParticleManager:SetParticleControlEnt(static_pfx, 0, enemy, PATTACH_POINT_FOLLOW, "attach_hitloc", enemy:GetAbsOrigin(), true)
ParticleManager:SetParticleControl(static_pfx, 1, static_origin)
ParticleManager:ReleaseParticleIndex(static_pfx)
-- Apply damage
ApplyDamage({attacker = shield_owner, victim = enemy, ability = ability, damage = static_damage, damage_type = DAMAGE_TYPE_MAGICAL})
-- Apply slow modifier
enemy:AddNewModifier(shield_owner, ability, "modifier_item_imba_mjollnir_slow", {duration = static_slow_duration})
end
-- Play hit sound if at least one enemy was hit
if #nearby_enemies > 0 then
shield_owner:EmitSound("Item.Maelstrom.Chain_Lightning.Jump")
end
end
end
end
-----------------------------------------------------------------------------------------------------------
-- Mjollnir passive modifier (stackable)
-----------------------------------------------------------------------------------------------------------
if modifier_item_imba_mjollnir_slow == nil then modifier_item_imba_mjollnir_slow = class({}) end
function modifier_item_imba_mjollnir_slow:IsHidden() return false end
function modifier_item_imba_mjollnir_slow:IsDebuff() return true end
function modifier_item_imba_mjollnir_slow:IsPurgable() return true end
-- Declare modifier events/properties
function modifier_item_imba_mjollnir_slow:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE,
MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT,
}
return funcs
end
function modifier_item_imba_mjollnir_slow:GetModifierMoveSpeedBonus_Percentage()
return self:GetAbility():GetSpecialValueFor("static_slow")
end
function modifier_item_imba_mjollnir_slow:GetModifierAttackSpeedBonus_Constant()
return self:GetAbility():GetSpecialValueFor("static_slow")
end
-----------------------------------------------------------------------------------------------------------
-- Jarnbjorn definition
-----------------------------------------------------------------------------------------------------------
if item_imba_jarnbjorn == nil then item_imba_jarnbjorn = class({}) end
LinkLuaModifier( "modifier_item_imba_jarnbjorn", "components/items/item_maelstrom.lua", LUA_MODIFIER_MOTION_NONE ) -- Owner's bonus attributes, stackable
LinkLuaModifier( "modifier_item_imba_jarnbjorn_counter", "components/items/item_maelstrom.lua", LUA_MODIFIER_MOTION_NONE ) -- Attack proc counter
LinkLuaModifier( "modifier_item_imba_jarnbjorn_static", "components/items/item_maelstrom.lua", LUA_MODIFIER_MOTION_NONE ) -- Static shield
LinkLuaModifier( "modifier_item_imba_jarnbjorn_static_counter", "components/items/item_maelstrom.lua", LUA_MODIFIER_MOTION_NONE ) -- Shield proc counter
LinkLuaModifier( "modifier_item_imba_jarnbjorn_slow", "components/items/item_maelstrom.lua", LUA_MODIFIER_MOTION_NONE ) -- Shield slow
function item_imba_jarnbjorn:GetIntrinsicModifierName()
return "modifier_item_imba_jarnbjorn"
end
function item_imba_jarnbjorn:GetAbilityTextureName()
return "custom/imba_jarnbjorn"
end
function item_imba_jarnbjorn:GetTexture()
return "custom/imba_jarnbjorn"
end
function item_imba_jarnbjorn:OnSpellStart()
if IsServer() then
local target = self:GetCursorTarget()
local tree_cooldown = self:GetSpecialValueFor("tree_cooldown")
if target.GetUnitName == nil then
self:RefundManaCost()
target:CutDown(-1)
self:EndCooldown()
self:StartCooldown(tree_cooldown)
else
-- Play cast sound
target:EmitSound("DOTA_Item.Mjollnir.Activate")
target:AddNewModifier(target, self, "modifier_item_imba_jarnbjorn_static", {duration = self:GetSpecialValueFor("static_duration")})
end
end
end
-----------------------------------------------------------------------------------------------------------
-- Jarnbjorn passive modifier (stackable)
-----------------------------------------------------------------------------------------------------------
if modifier_item_imba_jarnbjorn == nil then modifier_item_imba_jarnbjorn = class({}) end
function modifier_item_imba_jarnbjorn:IsHidden() return true end
function modifier_item_imba_jarnbjorn:IsDebuff() return false end
function modifier_item_imba_jarnbjorn:IsPurgable() return false end
function modifier_item_imba_jarnbjorn:IsPermanent() return true end
function modifier_item_imba_jarnbjorn:GetAttributes()
return MODIFIER_ATTRIBUTE_MULTIPLE
end
-- Declare modifier events/properties
function modifier_item_imba_jarnbjorn:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_PREATTACK_BONUS_DAMAGE,
MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT,
MODIFIER_EVENT_ON_ATTACK_LANDED,
MODIFIER_PROPERTY_HEALTH_REGEN_CONSTANT,
MODIFIER_PROPERTY_MANA_REGEN_CONSTANT,
}
return funcs
end
function modifier_item_imba_jarnbjorn:GetModifierPreAttack_BonusDamage()
return self:GetAbility():GetSpecialValueFor("bonus_damage")
end
function modifier_item_imba_jarnbjorn:GetModifierAttackSpeedBonus_Constant()
return self:GetAbility():GetSpecialValueFor("bonus_as")
end
function modifier_item_imba_jarnbjorn:GetModifierConstantHealthRegen()
return self:GetAbility():GetSpecialValueFor("bonus_hp_regen")
end
function modifier_item_imba_jarnbjorn:GetModifierConstantManaRegen()
return self:GetAbility():GetSpecialValueFor("bonus_mana_regen")
end
-- On attack landed, roll for proc and apply stacks
function modifier_item_imba_jarnbjorn:OnAttackLanded( keys )
if IsServer() then
local attacker = self:GetParent()
local damage = keys.damage
-- If this attack is irrelevant, do nothing
if attacker ~= keys.attacker then
return
end
-- If this is an illusion, do nothing either
if attacker:IsIllusion() then
return
end
-- If the target is invalid, still do nothing
local target = keys.target
if (not target:IsHeroOrCreep()) then -- or attacker:GetTeam() == target:GetTeam() then
return
end
-- All conditions met, stack the proc counter up
local ability = self:GetAbility()
-- zap the target's ass
local proc_chance = ability:GetSpecialValueFor("proc_chance")
if RollPseudoRandom(proc_chance, ability) then
LaunchLightning(attacker, target, ability, ability:GetSpecialValueFor("bounce_damage"), ability:GetSpecialValueFor("bounce_radius"))
end
-- If this a ranged hero, do not cleave
if attacker:IsRangedAttacker() then
return
end
-- Only apply if the attacker is the parent of the buff, and the victim is on the opposing team.
if self:GetParent() == attacker and self:GetParent():GetTeamNumber() ~= target:GetTeamNumber() then
-- Add explosion particle
local explosion_pfx = ParticleManager:CreateParticle("particles/econ/items/faceless_void/faceless_void_weapon_bfury/faceless_void_weapon_bfury_cleave_b.vpcf", PATTACH_ABSORIGIN, target)
ParticleManager:SetParticleControl(explosion_pfx, 0, target:GetAbsOrigin())
ParticleManager:SetParticleControl(explosion_pfx, 3, target:GetAbsOrigin())
ParticleManager:ReleaseParticleIndex(explosion_pfx)
-- Calculate bonus damage
local splash_damage = damage * (ability:GetSpecialValueFor("splash_damage_pct") * 0.01)
DoCleaveAttack( attacker, keys.target, ability, splash_damage, ability:GetSpecialValueFor("cleave_start"), ability:GetSpecialValueFor("cleave_end"), ability:GetSpecialValueFor("splash_range"), "particles/econ/items/sven/sven_ti7_sword/sven_ti7_sword_spell_great_cleave.vpcf" )
end
end
end
-----------------------------------------------------------------------------------------------------------
-- jarnbjorn static shield
-----------------------------------------------------------------------------------------------------------
if modifier_item_imba_jarnbjorn_static == nil then modifier_item_imba_jarnbjorn_static = class({}) end
function modifier_item_imba_jarnbjorn_static:IsHidden() return false end
function modifier_item_imba_jarnbjorn_static:IsDebuff() return false end
function modifier_item_imba_jarnbjorn_static:IsPurgable() return true end
-- Modifier particle
function modifier_item_imba_jarnbjorn_static:GetEffectName()
return "particles/items2_fx/jarnbjorn_shield.vpcf" end
function modifier_item_imba_jarnbjorn_static:GetEffectAttachType()
return PATTACH_ABSORIGIN_FOLLOW end
-- Start playing sound and store ability parameters
function modifier_item_imba_jarnbjorn_static:OnCreated()
if IsServer() then
self:GetParent():EmitSound("DOTA_Item.Mjollnir.Loop")
self.static_cooldown = false
end
end
function modifier_item_imba_jarnbjorn_static:OnIntervalThink()
self.static_cooldown = false
self:StartIntervalThink(-1)
end
-- Stop playing sound and destroy the proc counter
function modifier_item_imba_jarnbjorn_static:OnDestroy()
if IsServer() then
StopSoundEvent("DOTA_Item.Mjollnir.Loop", self:GetParent())
self:GetParent():RemoveModifierByName("modifier_item_imba_jarnbjorn_static_counter")
end
end
-- Declare modifier events/properties
function modifier_item_imba_jarnbjorn_static:DeclareFunctions()
local funcs = {
MODIFIER_EVENT_ON_TAKEDAMAGE,
}
return funcs
end
-- On damage taken, count stacks and proc the static shield
function modifier_item_imba_jarnbjorn_static:OnTakeDamage( keys )
if IsServer() then
local shield_owner = self:GetParent()
-- If this damage event is irrelevant, do nothing
if shield_owner ~= keys.unit then
return end
-- If the attacker is invalid, do nothing either
if keys.attacker:GetTeam() == shield_owner:GetTeam() then
return end
-- All conditions met, stack the proc counter up
local ability = self:GetAbility()
-- If enough stacks accumulated, reset them and zap nearby enemies
local static_proc_chance = ability:GetSpecialValueFor("static_proc_chance")
local static_damage = ability:GetSpecialValueFor("static_damage")
local static_radius = ability:GetSpecialValueFor("static_radius")
local static_slow_duration = ability:GetSpecialValueFor("static_slow_duration")
if not self.static_cooldown and keys.damage >= 5 and RollPseudoRandom(static_proc_chance, ability) then
self.static_cooldown = true
self:StartIntervalThink(ability:GetSpecialValueFor("static_cooldown"))
-- Iterate through nearby enemies
local static_origin = shield_owner:GetAbsOrigin() + Vector(0, 0, 100)
local nearby_enemies = FindUnitsInRadius(shield_owner:GetTeamNumber(), shield_owner:GetAbsOrigin(), nil, static_radius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_NO_INVIS + DOTA_UNIT_TARGET_FLAG_FOW_VISIBLE, FIND_ANY_ORDER, false)
for _, enemy in pairs(nearby_enemies) do
-- Play particle
local static_pfx = ParticleManager:CreateParticle("particles/item/jarnbjorn/static_lightning_bolt.vpcf", PATTACH_ABSORIGIN_FOLLOW, shield_owner)
ParticleManager:SetParticleControlEnt(static_pfx, 0, enemy, PATTACH_POINT_FOLLOW, "attach_hitloc", enemy:GetAbsOrigin(), true)
ParticleManager:SetParticleControl(static_pfx, 1, static_origin)
ParticleManager:ReleaseParticleIndex(static_pfx)
-- Apply damage
ApplyDamage({attacker = shield_owner, victim = enemy, ability = ability, damage = static_damage, damage_type = DAMAGE_TYPE_MAGICAL})
-- Apply slow modifier
enemy:AddNewModifier(shield_owner, ability, "modifier_item_imba_jarnbjorn_slow", {duration = static_slow_duration})
end
-- Play hit sound if at least one enemy was hit
if #nearby_enemies > 0 then
shield_owner:EmitSound("Item.Maelstrom.Chain_Lightning.Jump")
end
end
end
end
-----------------------------------------------------------------------------------------------------------
-- Jarnbjorn passive modifier (stackable)
-----------------------------------------------------------------------------------------------------------
if modifier_item_imba_jarnbjorn_slow == nil then modifier_item_imba_jarnbjorn_slow = class({}) end
function modifier_item_imba_jarnbjorn_slow:IsHidden() return false end
function modifier_item_imba_jarnbjorn_slow:IsDebuff() return true end
function modifier_item_imba_jarnbjorn_slow:IsPurgable() return true end
-- Declare modifier events/properties
function modifier_item_imba_jarnbjorn_slow:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE,
MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT,
}
return funcs
end
function modifier_item_imba_jarnbjorn_slow:GetModifierMoveSpeedBonus_Percentage()
return self:GetAbility():GetSpecialValueFor("static_slow")
end
function modifier_item_imba_jarnbjorn_slow:GetModifierAttackSpeedBonus_Constant()
return self:GetAbility():GetSpecialValueFor("static_slow")
end
-----------------------------------------------------------------------------------------------------------
-- Lightning proc functions
-----------------------------------------------------------------------------------------------------------
-- Initial launch + main loop
function LaunchLightning(caster, target, ability, damage, bounce_radius)
-- Parameters
local targets_hit = { target }
local search_sources = { target }
-- Play initial sound
caster:EmitSound("Item.Maelstrom.Chain_Lightning")
-- Play first bounce sound
target:EmitSound("Item.Maelstrom.Chain_Lightning.Jump")
ZapThem(caster, ability, caster, target, damage)
-- While there are potential sources, keep looping
while #search_sources > 0 do
-- Loop through every potential source this iteration
for potential_source_index, potential_source in pairs(search_sources) do
local nearby_enemies = FindUnitsInRadius(caster:GetTeamNumber(), potential_source:GetAbsOrigin(), nil, bounce_radius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_NO_INVIS + DOTA_UNIT_TARGET_FLAG_FOW_VISIBLE, FIND_ANY_ORDER, false)
for _, potential_target in pairs(nearby_enemies) do
-- Check if this target was already hit
local already_hit = false
for _, hit_target in pairs(targets_hit) do
if potential_target == hit_target then
already_hit = true
break
end
end
-- If not, zap it from this source, and mark it as a hit target and potential future source
if not already_hit then
ZapThem(caster, ability, potential_source, potential_target, damage)
targets_hit[#targets_hit+1] = potential_target
search_sources[#search_sources+1] = potential_target
end
end
-- Remove this potential source
table.remove(search_sources, potential_source_index)
end
end
end
-- One bounce. Particle + damage
function ZapThem(caster, ability, source, target, damage)
-- Draw particle
local particle = "particles/items_fx/chain_lightning.vpcf"
if ability:GetAbilityName() == "item_imba_jarnbjorn" then
particle = "particles/items_fx/chain_lightning_jarnbjorn.vpcf"
end
local bounce_pfx = ParticleManager:CreateParticle(particle, PATTACH_ABSORIGIN_FOLLOW, source)
ParticleManager:SetParticleControlEnt(bounce_pfx, 0, target, PATTACH_POINT_FOLLOW, "attach_hitloc", target:GetAbsOrigin(), true)
ParticleManager:SetParticleControlEnt(bounce_pfx, 1, source, PATTACH_POINT_FOLLOW, "attach_hitloc", source:GetAbsOrigin(), true)
ParticleManager:SetParticleControl(bounce_pfx, 2, Vector(1, 1, 1))
ParticleManager:ReleaseParticleIndex(bounce_pfx)
ApplyDamage({attacker = caster, victim = target, ability = ability, damage = damage, damage_type = DAMAGE_TYPE_MAGICAL})
end
|
object_building_heroic_bespin_tower_g = object_building_heroic_shared_bespin_tower_g:new {
}
ObjectTemplates:addTemplate(object_building_heroic_bespin_tower_g, "object/building/heroic/bespin_tower_g.iff")
|
---@meta
---@class ffi.namespace*: table
---@class ffi.cdecl*: string
---@class ffi.ctype*: userdata
local ctype
---@class ffi.cdata*: userdata
---@alias ffi.ct* ffi.cdecl*|ffi.ctype*|ffi.cdata*
---@class ffi.cb*: userdata
local cb
---@class ffi.VLA*: userdata
---@class ffi.VLS*: userdata
---@version JIT
---@class ffi*
---@field C ffi.namespace*
---@field os string
---@field arch string
local ffi = {}
---@param def string
function ffi.cdef(def) end
---@param name string
---@param global? boolean
---@return ffi.namespace* clib
function ffi.load(name, global) end
---@param ct ffi.ct*
---@param nelem? integer
---@param init? any
---@return ffi.cdata* cdata
function ffi.new(ct, nelem, init, ...) end
---@param nelem? integer
---@param init? any
---@return ffi.cdata* cdata
function ctype(nelem, init, ...) end
---@param ct ffi.ct*
---@return ffi.ctype* ctype
function ffi.typeof(ct) end
---@param ct ffi.ct*
---@param init any
---@return ffi.cdata* cdata
function ffi.cast(ct, init) end
---@param ct ffi.ct*
---@param metatable table
---@return ffi.ctype* ctype
function ffi.metatype(ct, metatable) end
---@param cdata ffi.cdata*
---@param finalizer function
---@return ffi.cdata* cdata
function ffi.gc(cdata, finalizer) end
---@param ct ffi.ct*
---@param nelem? integer
---@return integer|nil size
function ffi.sizeof(ct, nelem) end
---@param ct ffi.ct*
---@return integer align
function ffi.alignof(ct) end
---@param ct ffi.ct*
---@param field string
---@return integer ofs
---@return integer? bpos
---@return integer? bsize
function ffi.offsetof(ct, field) end
---@param ct ffi.ct*
---@param obj any
---@return boolean status
function ffi.istype(ct, obj) end
---@param newerr? integer
---@return integer err
function ffi.errno(newerr) end
---@param ptr any
---@param len? integer
---@return string str
function ffi.string(ptr, len) end
---@overload fun(dst: any, str: string)
---@param dst any
---@param src any
---@param len integer
function ffi.copy(dst, src, len) end
---@param dst any
---@param len integer
---@param c? any
function ffi.fill(dst, len, c) end
---@param param string
---@return boolean status
function ffi.abi(param) end
function cb:free() end
---@param func function
function cb:set(func) end
return ffi
|
local assert = require("luassert")
local say = require("say")
local M = {}
local asserts = {}
asserts.__index = asserts
function asserts.create(name)
local assert_fn = {
name = name,
positive = ("assertion.%s.positive"):format(name),
negative = ("assertion.%s.negative"):format(name),
}
return setmetatable(assert_fn, asserts)
end
function asserts.set_positive(self, msg)
say:set(self.positive, msg)
end
function asserts.set_negative(self, msg)
say:set(self.negative, msg)
end
function asserts.register(self, fn)
assert:register("assertion", self.name, fn(self), self.positive, self.negative)
end
function asserts.register_eq(self, get_actual)
local fn = function(_, args)
local expected = args[#args]
local actual = get_actual(unpack(args, 1, #args - 1))
local positive_msg = ("%s should be %s, but actual: %s"):format(self.name, expected, actual)
self:set_positive(positive_msg)
local negative_msg = ("%s should not be %s, but actual: %s"):format(self.name, expected, actual)
self:set_negative(negative_msg)
return actual == expected
end
self:register(function(_)
return fn
end)
end
function asserts.register_same(self, get_actual)
local fn = function(_, args)
local expected = vim.inspect(args[#args])
local actual = vim.inspect(get_actual(unpack(args, 1, #args - 1)))
local positive_msg = ("%s should be %s, but actual: %s"):format(self.name, expected, actual)
self:set_positive(positive_msg)
local negative_msg = ("%s should not be %s, but actual: %s"):format(self.name, expected, actual)
self:set_negative(negative_msg)
return vim.deep_equal(actual, expected)
end
self:register(function(_)
return fn
end)
end
M.asserts = asserts
M.assert = assert
return M
|
object_tangible_component_base_weapon_core_base = object_tangible_component_base_shared_weapon_core_base:new {
}
ObjectTemplates:addTemplate(object_tangible_component_base_weapon_core_base, "object/tangible/component/base/weapon_core_base.iff")
|
resource_manifest_version '77731fab-63ca-442c-a67b-abc70f28dfa5'
-- Head over to https://docs.fivem.net/game-references/data-files/ for the data files
files {
'peds.meta',
}
data_file 'PED_METADATA_FILE' 'peds.meta'
|
return {'digitaltoad/vim-pug', opt = true,
ft = { 'pug' },
config = function ()
require('log').info('Plugin loaded', 'pug-syntax')
end,
}
|
local skynet = require "skynet"
local function timeout(t)
print(t)
end
local function wakeup(co)
for i=1,5 do
skynet.sleep(50)
skynet.wakeup(co)
end
end
skynet.start(function()
skynet.fork(wakeup, coroutine.running())
skynet.timeout(300, function() timeout "Hello World" end)
for i = 1, 10 do
print(i, skynet.now())
print(skynet.sleep(100))
end
skynet.exit()
print("Test timer exit")
end)
|
#! /usr/bin/env luajit
require 'ext'
local _ENV = _ENV or getfenv()
require 'symmath'.setup{env=_ENV, MathJax={env=_ENV, title='infinite wire', usePartialLHSForDerivative=true, pathToTryToFindMathJax='..'}}
local t,r,phi,z = vars('t', 'r', '\\phi', 'z')
local pi = var'\\pi'
--[[
local epsilon_0 = var'\\epsilon_0'
local mu_0 = var'\\mu_0'
--]]
-- [[
local mu_0 = 4 * pi
local epsilon_0 = 1 / mu_0
--]]
local spatialCoords = {r,phi,z}
local coords = table{t}:append(spatialCoords)
local chart = Tensor.Chart{coords=coords}
local spatialChart = Tensor.Chart{coords=spatialCoords, symbols='ijklmn'}
local chart_t = Tensor.Chart{symbols='t', coords={t}}
local chart_x = Tensor.Chart{symbols='x', coords={x}}
local chart_y = Tensor.Chart{symbols='y', coords={y}}
local chart_z = Tensor.Chart{symbols='z', coords={z}}
local g = Tensor'_ab'
g['_ab'] = Tensor('_ab', table.unpack(Matrix.diagonal(-1, 1, r^2, 1)))
local gU = Tensor'^ab'
gU['^ab'] = Tensor('^ab', table.unpack(Matrix.diagonal(-1, 1, r^-2, 1)))
local gamma = Tensor('_ij', {1,0,0}, {0,r^2,0}, {0,0,1})
--printbr(var'\\gamma''_ij':eq(gamma'_ij'()))
local gammaU = Tensor('^ij', table.unpack((Matrix.inverse(gamma))))
--printbr(var'\\gamma''^ij':eq(gammaU'^ij'()))
chart:setMetric(g, gU)
spatialChart:setMetric(gamma, gammaU)
local sqrt_det_gamma = sqrt(Matrix.determinant(gamma))()
--printbr(sqrt(var'\\gamma'):eq(sqrt_det_gamma))
local makeLeviCivita = require 'symmath.tensor.LeviCivita'
--local LeviCivita4 = makeLeviCivita()
--printbr(var'\\epsilon''_abcd':eq(LeviCivita4'_abcd'()))
local LeviCivita3 = makeLeviCivita('i')
--printbr(var'\\epsilon''_ijk':eq(LeviCivita3'_ijk'()))
local E = Tensor('_i', function(i) return var('E_'..spatialCoords[i].name, coords) end)
local E_r, E_phi, E_z = table.unpack(E)
local B = Tensor('_i', function(i) return var('B_'..spatialCoords[i].name, coords) end)
local B_r, B_phi, B_z = table.unpack(B)
local S = (LeviCivita3'_i^jk' * E'_j' * B'_k')()
--printbr(var'E''_i':eq(E))
--printbr(var'B''_i':eq(B))
--printbr(var'S''_i':eq(S))
local ESq_plus_BSq = (E'_i' * E'_j' * gammaU'^ij' + B'_i' * B'_j' * gammaU'^ij')()
-- taken from my electrovacuum.lua script
local RicciEM = Tensor'_ab'
RicciEM['_tt'] = Tensor('_tt', {ESq_plus_BSq})
RicciEM['_ti'] = Tensor('_ti', (-2 * S'_i')())
RicciEM['_it'] = Tensor('_ti', (-2 * S'_i')())
RicciEM['_ij'] = (-2 * E'_i' * E'_j' - 2 * B'_i' * B'_j' + ESq_plus_BSq * gamma'_ij')()
local lambda = var'\\lambda'
local I = var'I'
printbr'for a uniformly charged wire...'
-- TODO http://www.physicspages.com/2013/11/18/electric-field-outside-an-infinite-wire/
RicciEM = RicciEM
-- http://farside.ph.utexas.edu/teaching/302l/lectures/node26.html
:replace(E_r, lambda / (2 * pi * epsilon_0 * r))
:replace(E_phi, 0)
:replace(E_z, 0)
-- http://hyperphysics.phy-astr.gsu.edu/hbase/magnetic/magcur.html
:replace(B_r, 0)
:replace(B_phi, mu_0 * I / (2 * pi)) -- this is B_phiHat = mu_0 I / (2 pi r) ... but B_phiHat = 1/r B_phi ... so B_phi = I mu_0 / (2 pi)
:replace(B_z, 0)
:simplify()
--printbr(var'R''_ab':eq(RicciEM'_ab'()))
-- clear the metric
do
chart.metric = nil
chart.metricInverse = nil
spatialChart.metric = nil
spatialChart.metricInverse = nil
end
local Conn = Tensor'^a_bc'
--[[
Conn[2][1][1] = var('a',{r})
Conn[1][2][1] = var('d',{r}) * I / r^2
Conn[1][1][2] = var('g',{r})
Conn[2][1][4] = var('b',{r})
Conn[2][4][1] = var('c',{r})
Conn[2][2][2] = lambda -- var('h',{r})
Conn[2][3][3] = var('e',{r})
Conn[2][4][4] = var('f',{r})
--]]
-- [[ tada!
Conn[2][1][1] = -frac(4,3) * I^2 / r^3 - 4 * lambda^2 / r -- R_tt
Conn[2][1][4] = 4 * I * lambda / r^2 -- R_tz
Conn[2][4][1] = 4 * I * lambda / r^2 -- R_zt
Conn[1][1][1] = Constant(1) -- R_pp, R_zz
Conn[1][3][3] = -4 * I^2 / r^2 + 4 * lambda^2 -- R_pp
Conn[1][4][4] = 4 * I^2 / r^4 + 4 * lambda^2 / r^2 -- R_zz
Conn[3][2][2] = 4 * phi * (I^2 / r^4 - lambda^2 / r^2) -- R_rr
--]]
Conn:printElem'\\Gamma'
printbr()
-- R^a_bcd = Conn^a_bd,c - Conn^a_bc,d + Conn^a_ec Conn^e_bd - Conn^a_ed Conn^e_bc - Conn^a_be (Conn^e_dc - Conn^e_cd)
local RiemannExpr = Conn'^a_bd,c' - Conn'^a_bc,d'
+ Conn'^a_ec' * Conn'^e_bd' - Conn'^a_ed' * Conn'^e_bc'
- Conn'^a_be' * (Conn'^e_dc' - Conn'^e_cd')
-- [[
printbr(var'R''^a_bcd':eq(RiemannExpr:replace(Conn, var'\\Gamma')))
printbr(var'R''_ab':eq(RiemannExpr:replace(Conn, var'\\Gamma'):reindex{abcde='cacbd'}))
--]]
local Riemann = Tensor'^a_bcd'
Riemann['^a_bcd'] = RiemannExpr()
--printbr(var'R''^a_bcd':eq(Riemann))
-- R_ab = R^c_acb = Conn^c_ab,c - Conn^c_ac,b + Conn^c_dc Conn^d_ab - Conn^c_db Conn^d_ac - Conn^c_ad (Conn^d_bc - Conn^d_cb)
local Ricci = Riemann'^c_acb'()
Ricci:print'R'
print(var'R''_ab':eq(Ricci))
print('vs Ricci of EM stress-energy tensor')
RicciEM:print'R'
printbr()
printbr"EM with no current -- in frame of wire carrier drift velocity, right? How do you apply Lorentz boost to create this setup?"
RicciEM:replace(I, 0)():print'R'
printbr()
printbr'EM with no charge -- in rest frame -- purely magnetic field'
local RicciEMNoCharge = RicciEM:replace(lambda, 0)()
RicciEMNoCharge:print'R'
printbr()
local beta = var'\\beta'
local gamma = var'\\gamma'
local LorentzBoost = Tensor('^a_b',
{gamma, 0, 0, -beta * gamma},
{0, 1, 0, 0},
{0, 0, 1, 0},
{-beta * gamma, 0, 0, gamma})
printbr[[
If the wire has either no current or no charge then $R_{tz}$ will be zero.
If $R_{tz}$ is zero then there is no way to apply a Lorentz transformation to create this term (right?).
There would also be no way to transform a EM stress-energy of purely current (observer frame) into one of purely current (frame of charge carriers).
]]
printbr'Lorentz boost'
LorentzBoost:print'\\Lambda'
printbr()
local RicciEMBoosted = (RicciEM'_cd' * LorentzBoost'^c_a' * LorentzBoost'^d_b')()
printbr'EM boosted:'
RicciEMBoosted:print'R'
printbr()
local RicciEMNoChargeBoosted = (RicciEMNoCharge'_cd' * LorentzBoost'^c_a' * LorentzBoost'^d_b')
:simplify()
:replace(gamma^2, 1/(1 - beta^2))
:simplify()
printbr'EM, no charge, boosted:'
RicciEMNoChargeBoosted:print'R'
printbr()
local J = Tensor('_a', 0, 0, 0, I)
printbr'four-current in rest frame. no charge, only current:'
J:print'J'
printbr()
JBoosted = (J'_b' * LorentzBoost'^b_a')()
printbr'four-current boosted'
JBoosted:print'J'
printbr()
--[[
... but how do we boost to get the new frame's current equal to zero?
for that we solve 0 = -8 I^2 beta / (r^4 (1 - beta^2))
and that means beta = 0 ...
unless all I terms have to be replaced with something ...
I^2 -> (I^2 - lambda^2 r^2)
... in order to represent the current in the new field
... why is that?
Lorentz transform on 4-current:
J_a = [0, 0, 0, I]
J_a' = [-beta gamma I, 0, 0, gamma I]
so there's your new lambda: equal to beta gamma I
...and your new I is gamma I
--]]
printbr'EM, no charge, boosted, with four-current exchanged as well'
local tmp = RicciEMBoosted -- start with the with-charge boosted Ricci, so we can replace the lambda with the boosted J_t'
:replace(lambda, JBoosted[1])
:replace(I, JBoosted[4])
:simplify()
:replace(gamma^4, 1/(1-beta^2)^2)
:simplify()
tmp:print'R'
printbr()
--[[
I = rest-frame current. no charge
I', lambda' = new current, charge
-8 I' lambda' / r^3 = -8 I^2 beta / (r^4 (1 - beta^2))
solve for beta
-8 I' lambda' r^4 (1 - beta^2) = -8 I^2 r^3 beta
(I' / I^2) lambda' r (beta^2 - 1) + beta = 0
beta = (-1 +- sqrt( 1 - 4 ((I' / I^2) lambda' r)^2 ) ) / (2 (I' / I^2) lambda' r)
beta = (-1 +- sqrt( 1 - 4 lambda'^2 r^2 I'^2 / I^4 ) ) / (2 lambda' r I' / I^2)
beta = (-1 +- (I' / I^2) sqrt( I^4 / I'^2 - 4 lambda'^2 r^2 ) ) / (2 lambda' r I' / I^2)
beta = (-(I' / I^2) / (I' / I^2) +- (I' / I^2) sqrt( I^4 / I'^2 - 4 lambda'^2 r^2 ) ) / (2 lambda' r I' / I^2)
beta = (-I^2 / I' +- sqrt( I^4 / I'^2 - 4 lambda'^2 r^2 ) ) / (2 lambda' r)
--]]
RicciBoostedToCreateB = RicciEMNoChargeBoosted
:replace(beta, (-I + sqrt(I^2 - 4 * lambda^2 * r^2)) / (2 * lambda * r))
:simplify()
printbr'Ricci without charge, then boosted to recreate B'
RicciBoostedToCreateB:print'R'
printbr()
--[[
to eliminate B, solve for beta 0 = (lambda I r) beta^2 + (I^2 + lambda^2 r^2) beta + lambda I r
beta = ( -(I^2 + lambda^2 r^2) +- sqrt( (I^2 + lambda^2 r^2)^2 - 4 (lambda I r) lambda I r ) ) / (2 lambda I r)
beta = ( -I^2 - lambda^2 r^2 +- sqrt( I^4 + 2 I^2 lambda^2 r^2 + lambda^4 r^4 - 4 lambda^2 I^2 r^2 ) ) / (2 lambda I r)
beta = ( -I^2 - lambda^2 r^2 +- sqrt( I^4 - 2 I^2 lambda^2 r^2 + lambda^4 r^4 ) ) / (2 lambda I r)
beta = ( -I^2 - lambda^2 r^2 +- sqrt( (I^2 - lambda^2 r^2)^2 ) ) / (2 lambda I r)
beta = ( -I^2 - lambda^2 r^2 +- I^2 -+ lambda^2 r^2) / (2 lambda I r)
beta = ( -I^2 - lambda^2 r^2 + I^2 - lambda^2 r^2) / (2 lambda I r)
beta = ( - 2 lambda^2 r^2 ) / (2 lambda I r)
beta = -lambda r / I
beta = ( -I^2 - lambda^2 r^2 - I^2 + lambda^2 r^2) / (2 lambda I r)
beta = ( -2 I^2) / (2 lambda I r)
beta = -I / (lambda r)
oh yeah, lambda is zero for the rest frame ...
--]]
os.exit()
--[[ Bianchi identities
-- This is zero, but it's a bit slow to compute.
-- It's probably zero because I derived the Riemann values from the connections.
-- This will be a 4^5 = 1024, but it only needs to show 20 * 4 = 80, though because it's R^a_bcd, we can't use the R_abcd = R_cdab symmetry, so maybe double that to 160.
-- TODO covariant derivative function?
-- NOTICE this matches em_conn_infwire.lua, so fix both of these
local diffRiemann = (Riemann'^a_bcd,e' + Conn'^a_fe' * Riemann'^f_bcd' - Conn'^f_be' * Riemann'^a_fcd' - Conn'^f_ce' * Riemann'^a_bfd' - Conn'^f_de' * Riemann'^a_bcf')()
local Bianchi = Tensor'^a_bcde'
Bianchi['^a_bcde'] = (diffRiemann + diffRiemann:reindex{abcde='abecd'} + diffRiemann:reindex{abcde='abdec'})()
print'Bianchi:'
local sep = ''
for index,value in Bianchi:iter() do
local abcde = table.map(index, function(i) return coords[i].name end)
local a,b,c,d,e = abcde:unpack()
local bcde = table{b,c,d,e}
if value ~= Constant(0) then
if sep == '' then printbr() end
print(sep, (
var('{R^'..a..'}_{'..b..' '..c..' '..d..';'..e..'}')
+ var('{R^'..a..'}_{'..b..' '..e..' '..c..';'..d..'}')
+ var('{R^'..a..'}_{'..b..' '..d..' '..e..';'..c..'}')
):eq(value))
sep = ';'
end
end
if sep=='' then print(0) end
printbr()
--]]
--[[ This is zeros also.
-- Since I'm defining the Riemann by the connections explicitly,
-- and the Ricci from the Riemann,
-- the torsion-free Ricci's symmetry is dependent on symmetry of C^c_ac,b = C^c_bc,a
-- since C^c_ac = (1/2 ln|g|),a, so C^c_ac,b = (1/2 ln|g|),ab = (1/2 ln|g|),ba = C^c_bc,a
local dCab = Conn'^c_ac,b'()
printbr(var'\\Gamma''^c_ac,b':eq(dCab))
--]]
for _,l in ipairs(([[
Ok, this gives me the connections that give rise to the curvature.
But the connections themselves come from the coordinate systems
and who is to say the coordinate systems do correctly align with cylindrical Minkowski?
Though their deviation from Minkowski should only be infintesimal, according to $I$ and $\lambda$
which I need to calculate in natural units and specify here ...
]]):split'\n') do printbr(l) end
-- -4/3 I^2 / r^3 - 4 lambda^2 / r
-- grem.constants doesn't work with implicitVars
local constants = require 'grem.constants'
local wire_radius = .5 * constants.wire_diameters.electrical_range -- m
printbr('wire_radius',wire_radius)
local wire_cross_section_area = math.pi * wire_radius^2 -- m^2
printbr('wire_cross_section_area',wire_cross_section_area)
local wire_length = 12 * constants.in_in_m -- m
printbr('wire_length',wire_length)
local wire_resistivity = constants.wire_resistivities.gold
printbr('wire_resistivity',wire_resistivity)
local wire_resistance = wire_resistivity * wire_length / wire_cross_section_area -- m^0
printbr('wire_resistance',wire_resistance)
--local battery_voltage_in_V = 1.5
local battery_voltage_in_V = 1e+5
local battery_voltage_in_m = battery_voltage_in_V * constants.V_in_m -- m^0
printbr('battery_voltage_in_m',battery_voltage_in_m)
local wire_current = battery_voltage_in_m / wire_resistance -- amps = C / s = m / m = m^0, likewise volts = m^0, ohms = m^0, so amps = volts / ohms = m^0
printbr([[wire_current in $m^0$]],wire_current)
printbr([[wire current in $\frac{m}{s}$:]], wire_current / constants.c)
--local current_velocity = 1 -- doesn't matter if lambda = 0. units of m/s = m^0
-- so ... inside the wire we know q=0 by Kirchoff's law
-- what about J = sigma E? doesn't that mean E = J rho, for rho = resistivity?
local wire_charge_density = 0 -- C / m^3 = m^-2
printbr('wire_charge_density',wire_charge_density)
local wire_charge_density_per_length = wire_charge_density * wire_cross_section_area -- m^-2 * m^2 = m^0
printbr('wire_charge_density_per_length',wire_charge_density_per_length)
-- J is current density, in units of amperes per square meter ...
-- I current = J current density * A area, is in amperes ...
-- Ohm's law: I current = V voltage / R resistance
-- J = sigma E, E = rho J, sigma = 1/rho
--[[
drift speed: I = n A v Q
v = I / (n A Q) =
example given https://en.wikiversity.org/wiki/Physics_equations/Current_and_current_density#Drift_speed
I = electric current = V / R = 5 Amps
n = number of charged particles per unit volume = charge carrier density = ?
A = cross-section area = .5 mm^2 = .5 (1e-3 m)^2 = 5e-7 m^2
Q = charge on each particle. k_e = # electrons in 1 Coulomb, so 1/k_e = 1.6e-19 Coulombs = charge of an electron
v = drift velocity ~ 1e-3 m/s
5 Amps = n * 5e-7 m^2 * 1e-3 m/s * 1.6e-19 Coulombs
n = 5 Amps / (5e-7 m^2 * 1e-3 m/s * 1.6e-19 Coulombs)
n = 5 Amps / (8e-29 Coulombs m^3 / s) ... Amps = Coulombs / second ...
n = 6.25e+28 m^-3 for copper wire
n = 1.070e+28 m^-3 for silver wire ... https://en.wikipedia.org/wiki/Charge_carrier_density
--]]
|
return {
"min",
"max",
"sum",
}
|
local _, ns = ...
local cfg = CreateFrame('Frame')
-- Media ------------------------------------------------------------------------------------------
-- Texture
cfg.texture = 'Interface\\AddOns\\KBJcombatHUD\\Media\\texture'
cfg.symbol = 'Interface\\AddOns\\KBJcombatHUD\\Media\\symbol.ttf'
cfg.glow = 'Interface\\AddOns\\KBJcombatHUD\\Media\\textureGlow'
cfg.absorb = 'Interface\\AddOns\\KBJcombatHUD\\Media\\absorb'
-- Font ( "Fonts\\FRIZQT__.ttf" was rebuild font FRIZQT__ + koverwatch )
cfg.font = 'Fonts\\FRIZQT__.ttf'
cfg.bfont = 'Interface\\AddOns\\KBJcombatHUD\\Media\\fontThick.ttf'
cfg.hudfont = 'Interface\\AddOns\\KBJcombatHUD\\Media\\IBMPlexMono-BoldItalic.ttf'
cfg.aurafont = 'Interface\\AddOns\\KBJcombatHUD\\Media\\pixel.ttf'
cfg.shadowoffsetX, cfg.shadowoffsetY, cfg.fontflag = 0, 0, 'THINOUTLINE'
-- Unit Frames --------------------------------------------------------------------------
-- Main Group (player, target, focus, pet, targettarget, focustarget)
cfg.mainUF = { -- Anchor is Player unitframe
player = {
width = 32,
height = 3,
position = { sa = 'TOP', a = UIParent, pa = 'CENTER', x = 80, y = 32 },
},
focus = {
width = 40,
height = 6,
position = { sa = 'CENTER', a = UIParent, pa = 'CENTER', x = 162, y = -20 },
},
nameplate = {
width = 90,
height = 10,
},
}
-- Sub Group (party, raid, boss, tank, arena, partytarget, tanktarget, arenatarget)
cfg.subUF = {
party = {
width = 80,
height = 25,
position = { sa = 'BOTTOMRIGHT', a = UIParent, pa = 'CENTER', x = -405, y = -70 },
},
raid = {
width = 44,
height = 44,
position = { sa = 'TOPLEFT', a = UIParent, pa = 'TOPLEFT', x = 15, y = -100 },
},
boss = { -- arena
width = 80,
height = 25,
position = { sa = 'BOTTOMLEFT', a = UIParent, pa = 'CENTER', x = 300, y = -70 },
},
tank = {
width = 95,
height = 34,
position = { sa = '', a = UIParent, pa = '', x = 80, y = 0 },
},
}
-- Castbars -----------------------------------------------------------------------------
cfg.castbar = {
player = {
width = 100,
height = 14,
position = { sa = 'CENTER', a = UIParent, pa = 'CENTER', x = 0, y = -73 },
},
target = {
width = 450,
height = 36,
position = { sa = 'TOP', a = UIParent, pa = 'TOP', x = 0, y = -70 },
},
focus = {
width = 140,
height = 18,
position = { sa = 'CENTER', a = UIParent, pa = 'CENTER', x = 0, y = 78 },
},
arena = {
width = 100,
height = 14,
position = { sa = 'CENTER', a = UIParent, pa = 'CENTER', x = -120, y = -100 },
},
}
-- Plugin -------------------------------------------------------------------------------
cfg.plugin = {
fcf = { -- Floating Combat Feedback
enable = true,
size = 13,
},
}
-----------------------------
-- Unit Frames Options
-----------------------------
cfg.options = {
disableRaidFrameManager = true, -- disable default compact Raid Manager
ResurrectIcon = true,
--TotemBar = false,
--MushroomBar = true,
}
-----------------------------
-- Auras
-----------------------------
cfg.aura = {
-- player
player_debuffs = true,
player_debuffs_num = 18,
-- target
target_debuffs = true,
target_debuffs_num = 18,
target_buffs = true,
target_buffs_num = 8,
-- focus
focus_debuffs = true,
focus_debuffs_num = 12,
focus_buffs = false,
focus_buffs_num = 8,
-- boss
boss_buffs = true,
boss_buffs_num = 4,
boss_debuffs = true,
boss_debuffs_num = 4,
-- target of target
targettarget_debuffs = true,
targettarget_debuffs_num = 4,
-- party
party_buffs = true,
party_buffs_num = 4,
onlyShowPlayer = false, -- only show player debuffs on target
disableCooldown = true, -- hide omniCC
font = 'Interface\\AddOns\\KBJcombatHUD\\Media\\pixel.ttf',
fontsize = 8,
fontflag = 'Outlinemonochrome',
}
-----------------------------
-- Plugins
-----------------------------
--FloatingCombatText
--ThreatBar
cfg.treat = {
enable = true,
text = false,
pos = {'CENTER', UIParent, 0, 39},
width = 40,
height = 4,
}
--RaidDebuffs
cfg.RaidDebuffs = {
enable = true,
pos = {'CENTER'},
size = 20,
ShowDispelableDebuff = true,
FilterDispellableDebuff = true,
MatchBySpellName = false,
}
--Threat/DebuffHighlight
cfg.dh = {
player = true,
target = true,
focus = true,
pet = true,
partytaget = false,
party = true,
arena = true,
raid = true,
targettarget = false,
}
--AuraWatch
cfg.aw = {
enable = true,
onlyShowPresent = true,
anyUnit = true,
}
--AuraWatch Spells
cfg.spellIDs = {
DRUID = {
{33763, {0.2, 0.8, 0.2}}, -- Lifebloom
{8936, {0.8, 0.4, 0}, 'TOPLEFT'}, -- Regrowth
{102342, {0.38, 0.22, 0.1}}, -- Ironbark
{48438, {0.4, 0.8, 0.2}, 'BOTTOMLEFT'}, -- Wild Growth
{774, {0.8, 0.4, 0.8},'TOPRIGHT'}, -- Rejuvenation
},
MONK = {
{119611, {0.2, 0.7, 0.7}}, -- Renewing Mist
{132120, {0.4, 0.8, 0.2}}, -- Enveloping Mist
{124081, {0.7, 0.4, 0}}, -- Zen Sphere
{116849, {0.81, 0.85, 0.1}}, -- Life Cocoon
},
PALADIN = {
{20925, {0.9, 0.9, 0.1}}, -- Sacred Shield
{6940, {0.89, 0.1, 0.1}, 'BOTTOMLEFT'}, -- Hand of Sacrifice
{114039, {0.4, 0.6, 0.8}, 'BOTTOMLEFT'},-- Hand of Purity
{1022, {0.2, 0.2, 1}, 'BOTTOMLEFT'}, -- Hand of Protection
{1038, {0.93, 0.75, 0}, 'BOTTOMLEFT'}, -- Hand of Salvation
{1044, {0.89, 0.45, 0}, 'BOTTOMLEFT'}, -- Hand of Freedom
{114163, {0.9, 0.6, 0.4}, 'RIGHT'}, -- Eternal Flame
{53563, {0.7, 0.3, 0.7}, 'TOPRIGHT'}, -- Beacon of Light
},
PRIEST = {
{41635, {0.2, 0.7, 0.2}}, -- Prayer of Mending
{33206, {0.89, 0.1, 0.1}}, -- Pain Suppress
{47788, {0.86, 0.52, 0}}, -- Guardian Spirit
{6788, {1, 0, 0}, 'BOTTOMLEFT'}, -- Weakened Soul
{17, {0.81, 0.85, 0.1}, 'TOPLEFT'}, -- Power Word: Shield
{139, {0.4, 0.7, 0.2}, 'TOPRIGHT'}, -- Renew
},
SHAMAN = {
{974, {0.2, 0.7, 0.2}}, -- Earth Shield
{61295, {0.7, 0.3, 0.7}, 'TOPRIGHT'}, -- Riptide
},
HUNTER = {
{35079, {0.2, 0.2, 1}}, -- Misdirection
},
MAGE = {
{111264, {0.2, 0.2, 1}}, -- Ice Ward
},
ROGUE = {
{57933, {0.89, 0.1, 0.1}}, -- Tricks of the Trade
},
WARLOCK = {
{20707, {0.7, 0.32, 0.75}}, -- Soulstone
},
WARRIOR = {
{114030, {0.2, 0.2, 1}}, -- Vigilance
{3411, {0.89, 0.1, 0.1}, 'TOPRIGHT'}, -- Intervene
},
}
ns.cfg = cfg
|
local Command = VH_CommandLib.Command:new("Armor", VH_CommandLib.UserTypes.Admin, "Sets the player(s) armor to specified amount or 100.", "")
Command:addArg(VH_CommandLib.ArgTypes.Plrs, {required = true})
Command:addArg(VH_CommandLib.ArgTypes.Number, {required = false})
Command:addAlias({Prefix = "!", Alias = "armor"})
Command.Callback = function(Sender, Alias, Targets, Amount)
for _, ply in ipairs(Targets) do
ply:SetArmor(Amount or 100)
end
VH_CommandLib.SendCommandMessage(Sender, "set the armor of", Targets, "to _reset_ "..(Amount or 100))
return ""
end
|
--- List local constructs and access their ID.
--
-- Element class:
-- <ul>
-- <li>RadarPvPAtmosphericSmallGroup</li>
-- <li>RadarPVPSpaceSmallGroup</li>
-- <li>RadarPvPAtmospheric: Medium and Large</li>
-- <li>RadarPVPSpaceMediumGroup</li>
-- <li>RadarPVPSpaceLargeGroup</li>
-- </ul>
--
-- Displayed widget fields:
-- <ul>
-- <li>constructsList</li>
-- <li>elementId</li>
-- <li>properties</li>
-- <li>staticProperties</li>
-- </ul>
--
-- Extends: Element
-- @see Element
-- @module RadarUnit
-- @alias M
local MockElement = require "dumocks.Element"
local CLASS_ATMO = "RadarPvPAtmospheric"
local CLASS_SPACE = "RadarPVPSpace"
local SMALL_GROUP = "SmallGroup"
local MEDIUM_GROUP = "MediumGroup"
local LARGE_GROUP = "LargeGroup"
local elementDefinitions = {}
elementDefinitions["atmospheric radar s"] = {mass = 486.72, maxHitPoints = 88.0, class = CLASS_ATMO .. SMALL_GROUP}
elementDefinitions["atmospheric radar m"] = {mass = 11324.61, maxHitPoints = 698.0, class = CLASS_ATMO}
elementDefinitions["atmospheric radar l"] = {mass = 6636.8985, maxHitPoints = 12887.0, class = CLASS_ATMO}
elementDefinitions["space radar s"] = {mass = 486.72, maxHitPoints = 88.0, class = CLASS_SPACE .. SMALL_GROUP}
elementDefinitions["space radar m"] = {mass = 2348.45, maxHitPoints = 698.0, class = CLASS_SPACE .. MEDIUM_GROUP}
elementDefinitions["space radar l"] = {mass = 12492.16, maxHitPoints = 12887.0, class = CLASS_SPACE .. LARGE_GROUP}
local DEFAULT_ELEMENT = "atmospheric radar s"
local M = MockElement:new()
M.widgetType = "radar"
M.helperId = "radar"
function M:new(o, id, elementName)
local elementDefinition = MockElement.findElement(elementDefinitions, elementName, DEFAULT_ELEMENT)
o = o or MockElement:new(o, id, elementDefinition)
setmetatable(o, self)
self.__index = self
o.elementClass = elementDefinition.class
o.range = 0 -- meters
-- map: id => {
-- ownerId=0,
-- name="",
-- size={0,0,0},
-- type="dynamic",
-- worldPos={0,0,0},
-- worldVel={0,0,0},
-- worldAccel={0,0,0},
-- pos={0,0,0},
-- vel={0,0,0},
-- accel={0,0,0},
-- }
o.entries = {}
o.enterCallbacks = {}
o.leaveCallbacks = {}
return o
end
local DATA_TEMPLATE = '{"helperId":"%s","type":"%s","name":"%s",'..
[["constructsList":[],"elementId":"%d",
"properties":{
"broken":false,
"errorMessage":"Jammed by atmosphere",
"identifiedConstructs":[],
"identifyConstructs":{},
"radarStatus":1,
"selectedConstruct":"0",
"worksInEnvironment":false
},
"staticProperties":{
"maxIdentifiedTargets":2,
"ranges":{
"identify128m":80000,
"identify16m":10000,
"identify32m":20000,
"identify64m":40000,
"scan":400000
},
"worksInAtmosphere":%s,
"worksInSpace":%s
}
}]]
function M:getData()
local radarId = 123456789
local worksInAtmosphere = self.elementClass == CLASS_ATMO
local worksInSpace = self.elementClass == CLASS_SPACE
return string.format(DATA_TEMPLATE, self.helperId, self:getWidgetType(), self.name, radarId, worksInAtmosphere,
worksInSpace)
end
-- Override default with realistic patten to id.
function M:getDataId()
return "e123456"
end
--- Returns the current range of the radar.
-- @treturn meter The range.
function M:getRange()
return self.range
end
--- Returns the list of construct IDs currently detection in the range.
-- @treturn list The list of construct IDs.
-- construct.
function M:getEntries()
local entries = {}
for id,_ in pairs(self.entries) do
table.insert(entries, id)
end
return entries
end
--- Returns whether the target has an active transponder with matching tags.
-- @treturn bool 1 if our construct and the target have active transponders with matching tags and 0 otherwise.
function M:hasMatchingTransponder(id)
return false
end
--- Return the size of the bounding box of the given construct, if in range.
-- @tparam int id The ID of the construct.
-- @treturn vec3 The size of the construct in xyz-coordinates.
function M:getConstructSize(id)
if self.entries[id] then
return self.entries[id].size
end
return nil
end
--- Return the type of the given construct.
-- @tparam int id The ID of the construct.
-- @treturn string The type of the construct,: can be 'static' or 'dynamic'.
function M:getConstructType(id)
if self.entries[id] then
return self.entries[id].type
end
return nil
end
--- Return the radar local coordinates of the given construct, if in range and if active transponder tags match.
-- @tparam int id The ID of the construct.
-- @treturn vec3 The xyz radar local coordinates of the construct.
function M:getConstructPos(id)
if self.entries[id] then
return self.entries[id].pos
end
return nil
end
--- Return the name of the given construct, if in range.
-- @tparam int id The ID of the construct.
-- @treturn string The name of the construct.
function M:getConstructName(id)
if self.entries[id] then
return self.entries[id].name
end
return nil
end
--- Event: Emitted when a construct enters the range of the radar unit.
--
-- Note: This is documentation on an event handler, not a callable method.
-- @tparam int id ID of the construct; can be used with database.getConstruct to retrieve info about it.
function M.EVENT_enter(id)
assert(false, "This is implemented for documentation purposes. For test usage see mockRegisterEnter")
end
--- Event: Emitted when a construct leaves the range of the radar unit.
--
-- Note: This is documentation on an event handler, not a callable method.
-- @tparam int id ID of the construct; can be used with database.getConstruct to retrieve info about it.
function M.EVENT_leave(id)
assert(false, "This is implemented for documentation purposes. For test usage see mockRegisterLeave")
end
--- Mock only, not in-game: Register a handler for the in-game `enter(id)` event.
-- @tparam function callback The function to call when the a player enters.
-- @treturn int The index of the callback.
-- @see EVENT_enter
function M:mockRegisterEnter(callback)
local index = #self.enterCallbacks + 1
self.enterCallbacks[index] = callback
return index
end
--- Mock only, not in-game: Simulates a construct entering the radar range.
-- @tparam int id The ID of the construct that entered.
function M:mockDoEnter(id)
-- call callbacks in order, saving exceptions until end
local errors = ""
for i,callback in pairs(self.enterCallbacks) do
local status,err = pcall(callback, id)
if not status then
errors = errors.."\nError while running callback "..i..": "..err
end
end
-- propagate errors
if string.len(errors) > 0 then
error("Errors raised in callbacks:"..errors)
end
end
--- Mock only, not in-game: Register a handler for the in-game `leave(id)` event.
-- @tparam function callback The function to call when the tile is released.
-- @treturn int The index of the callback.
-- @see EVENT_leave
function M:mockRegisterLeave(callback)
local index = #self.leaveCallbacks + 1
self.leaveCallbacks[index] = callback
return index
end
--- Mock only, not in-game: Simulates a construct leaving the radar range.
-- @tparam int id The ID of the construct that left.
function M:mockDoLeave(id)
-- call callbacks in order, saving exceptions until end
local errors = ""
for i,callback in pairs(self.leaveCallbacks) do
local status, err = pcall(callback, id)
if not status then
errors = errors.."\nError while running callback "..i..": "..err
end
end
-- propagate errors
if string.len(errors) > 0 then
error("Errors raised in callbacks:"..errors)
end
end
--- Mock only, not in-game: Bundles the object into a closure so functions can be called with "." instead of ":".
-- @treturn table A table encompasing the api calls of object.
-- @see Element:mockGetClosure
function M:mockGetClosure()
local closure = MockElement.mockGetClosure(self)
closure.getRange = function() return self:getRange() end
closure.getEntries = function() return self:getEntries() end
closure.hasMatchingTransponder = function() return self:hasMatchingTransponder() end
closure.getConstructSize = function(id) return self:getConstructSize(id) end
closure.getConstructType = function(id) return self:getConstructType(id) end
closure.getConstructPos = function(id) return self:getConstructPos(id) end
closure.getConstructName = function(id) return self:getConstructName(id) end
return closure
end
return M
|
--Copyright (C) 2009 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
object_tangible_ship_interior_components_shared_alarm_interior = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/interior_components/shared_alarm_interior.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/pob_station_warning_lighthousing.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/ship/client_shared_interior_alarm.cdf",
clientGameObjectType = 8211,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space/space_item:alarm_interior_n",
gameObjectType = 8211,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space/space_item:alarm_interior_n",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 3974262189,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/interior_components/shared_interior_component_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_interior_components_shared_alarm_interior, "object/tangible/ship/interior_components/shared_alarm_interior.iff")
object_tangible_ship_interior_components_shared_booster_interior = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/interior_components/shared_booster_interior.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/appearance/pob_station_tech_panel.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/ship/client_shared_interior_test.cdf",
clientGameObjectType = 8211,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space/space_item:booster_interior",
gameObjectType = 8211,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space/space_item:booster_interior",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 1352184706,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/interior_components/shared_interior_component_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_interior_components_shared_booster_interior, "object/tangible/ship/interior_components/shared_booster_interior.iff")
object_tangible_ship_interior_components_shared_capacitor_interior = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/interior_components/shared_capacitor_interior.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/pob_station_tech_panel.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/ship/client_shared_interior_test.cdf",
clientGameObjectType = 8211,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space/space_item:capacitor_interior_n",
gameObjectType = 8211,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space/space_item:capacitor_interior_n",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 2832895610,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/interior_components/shared_interior_component_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_interior_components_shared_capacitor_interior, "object/tangible/ship/interior_components/shared_capacitor_interior.iff")
object_tangible_ship_interior_components_shared_droid_interface_interior = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/interior_components/shared_droid_interface_interior.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/pob_station_tech_panel.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/ship/client_shared_interior_test.cdf",
clientGameObjectType = 8211,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space/space_item:droid_interface_interior_n",
gameObjectType = 8211,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space/space_item:droid_interface_interior_n",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 3377520816,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/interior_components/shared_interior_component_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_interior_components_shared_droid_interface_interior, "object/tangible/ship/interior_components/shared_droid_interface_interior.iff")
object_tangible_ship_interior_components_shared_engine_interior = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/interior_components/shared_engine_interior.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/pob_station_tech_panel.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/ship/client_shared_interior_test.cdf",
clientGameObjectType = 8211,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space/space_item:engine_interior_n",
gameObjectType = 8211,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space/space_item:engine_interior_n",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 2189154037,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/interior_components/shared_interior_component_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_interior_components_shared_engine_interior, "object/tangible/ship/interior_components/shared_engine_interior.iff")
object_tangible_ship_interior_components_shared_escape_pod_hatch = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/interior_components/shared_escape_pod_hatch.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/pob_station_escape_hatch.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/ship/client_shared_interior_test.cdf",
clientGameObjectType = 8211,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space/space_item:escape_pod",
gameObjectType = 8211,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space/space_item:escape_pod",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 3990614703,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/interior_components/shared_interior_component_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_interior_components_shared_escape_pod_hatch, "object/tangible/ship/interior_components/shared_escape_pod_hatch.iff")
object_tangible_ship_interior_components_shared_hull_access_interior = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/interior_components/shared_hull_access_interior.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/pob_station_tech_panel.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/ship/client_shared_interior_hull.cdf",
clientGameObjectType = 8211,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space/space_item:hull_access_interior_n",
gameObjectType = 8211,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space/space_item:hull_access_interior_n",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 3234906407,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/interior_components/shared_interior_component_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_interior_components_shared_hull_access_interior, "object/tangible/ship/interior_components/shared_hull_access_interior.iff")
object_tangible_ship_interior_components_shared_hyperdrive_interior = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/interior_components/shared_hyperdrive_interior.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/pob_station_tech_panel.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/ship/client_shared_interior_test.cdf",
clientGameObjectType = 8211,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space/space_item:hyperdrive_interior_n",
gameObjectType = 8211,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space/space_item:hyperdrive_interior_n",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 3880861694,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/interior_components/shared_interior_component_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_interior_components_shared_hyperdrive_interior, "object/tangible/ship/interior_components/shared_hyperdrive_interior.iff")
object_tangible_ship_interior_components_shared_interior_component_base = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/interior_components/shared_interior_component_base.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/pob_station_tech_panel.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/ship/client_shared_interior_test.cdf",
clientGameObjectType = 32773,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "string_id_table",
gameObjectType = 32773,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@obj_n:unknown_object",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 1650278519,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_interior_components_shared_interior_component_base, "object/tangible/ship/interior_components/shared_interior_component_base.iff")
object_tangible_ship_interior_components_shared_life_support_interior = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/interior_components/shared_life_support_interior.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/pob_station_tech_panel.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/ship/client_shared_interior_test.cdf",
clientGameObjectType = 8211,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space/space_item:life_support_interior_n",
gameObjectType = 8211,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space/space_item:life_support_interior_n",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 3443371299,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/interior_components/shared_interior_component_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_interior_components_shared_life_support_interior, "object/tangible/ship/interior_components/shared_life_support_interior.iff")
object_tangible_ship_interior_components_shared_missile_launcher_interior = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/interior_components/shared_missile_launcher_interior.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/pob_station_tech_panel.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/ship/client_shared_interior_test.cdf",
clientGameObjectType = 8211,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space/space_item:missile_launcher_interior_n",
gameObjectType = 8211,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space/space_item:missile_launcher_interior_n",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 3763171458,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/interior_components/shared_interior_component_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_interior_components_shared_missile_launcher_interior, "object/tangible/ship/interior_components/shared_missile_launcher_interior.iff")
object_tangible_ship_interior_components_shared_plasma_conduit_interior = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/interior_components/shared_plasma_conduit_interior.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/pob_station_conduit.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/ship/client_shared_plasma_conduit.cdf",
clientGameObjectType = 8211,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space/space_item:plasma_conduit_interior_d",
gameObjectType = 8211,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space/space_item:plasma_conduit_interior_n",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 3308870721,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/interior_components/shared_interior_component_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_interior_components_shared_plasma_conduit_interior, "object/tangible/ship/interior_components/shared_plasma_conduit_interior.iff")
object_tangible_ship_interior_components_shared_reactor_interior = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/interior_components/shared_reactor_interior.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/pob_station_tech_panel.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/ship/client_shared_interior_test.cdf",
clientGameObjectType = 8211,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space/space_item:reactor_interior_n",
gameObjectType = 8211,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space/space_item:reactor_interior_n",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 2128920004,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/interior_components/shared_interior_component_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_interior_components_shared_reactor_interior, "object/tangible/ship/interior_components/shared_reactor_interior.iff")
object_tangible_ship_interior_components_shared_shield_generator_interior = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/interior_components/shared_shield_generator_interior.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/pob_station_tech_panel.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/ship/client_shared_interior_test.cdf",
clientGameObjectType = 8211,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space/space_item:shield_generator_interior_n",
gameObjectType = 8211,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space/space_item:shield_generator_interior_n",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 1208361503,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/interior_components/shared_interior_component_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_interior_components_shared_shield_generator_interior, "object/tangible/ship/interior_components/shared_shield_generator_interior.iff")
object_tangible_ship_interior_components_shared_targeting_station_interior = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/interior_components/shared_targeting_station_interior.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/pob_station_tech_panel.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/ship/client_shared_interior_test.cdf",
clientGameObjectType = 8211,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space/space_item:targeting_station_interior_n",
gameObjectType = 8211,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space/space_item:targeting_station_interior_n",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 2082379213,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/interior_components/shared_interior_component_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_interior_components_shared_targeting_station_interior, "object/tangible/ship/interior_components/shared_targeting_station_interior.iff")
object_tangible_ship_interior_components_shared_weapon_interior = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/ship/interior_components/shared_weapon_interior.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/pob_station_tech_panel.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "clientdata/ship/client_shared_interior_test.cdf",
clientGameObjectType = 8211,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@space/space_item:weapon_interior_n",
gameObjectType = 8211,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@space/space_item:weapon_interior_n",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 1599351425,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/ship/interior_components/shared_interior_component_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_ship_interior_components_shared_weapon_interior, "object/tangible/ship/interior_components/shared_weapon_interior.iff")
|
require 'middleclass'
context('instanceOf', function()
context('nils, integers, strings, tables, and functions', function()
local o = Object:new()
local primitives = {nil, 1, 'hello', {}, function() end}
for _,primitive in pairs(primitives) do
local theType = type(primitive)
context('A ' .. theType, function()
local f1 = function() return instanceOf(Object, primitive) end
local f2 = function() return instanceOf(primitive, o) end
local f3 = function() return instanceOf(primitive, primitive) end
context('does not throw errors', function()
test('instanceOf(Object, '.. theType ..')', function()
assert_not_error(f1)
end)
test('instanceOf(' .. theType .. ', Object:new())', function()
assert_not_error(f2)
end)
test('instanceOf(' .. theType .. ',' .. theType ..')', function()
assert_not_error(f3)
end)
end)
test('makes instanceOf return false', function()
assert_false(f1())
assert_false(f2())
assert_false(f3())
end)
end)
end
end)
context('An instance', function()
local Class1 = class('Class1')
local Class2 = class('Class2', Class1)
local Class3 = class('Class3', Class2)
local UnrelatedClass = class('Unrelated')
local o1, o2, o3 = Class1:new(), Class2:new(), Class3:new()
test('is instanceOf(Object)', function()
assert_true(instanceOf(Object, o1))
assert_true(instanceOf(Object, o2))
assert_true(instanceOf(Object, o3))
end)
test('is instanceOf its class', function()
assert_true(instanceOf(Class1, o1))
assert_true(instanceOf(Class2, o2))
assert_true(instanceOf(Class3, o3))
end)
test('is instanceOf its class\' superclasses', function()
assert_true(instanceOf(Class1, o2))
assert_true(instanceOf(Class1, o3))
assert_true(instanceOf(Class2, o3))
end)
test('is not instanceOf its class\' subclasses', function()
assert_false(instanceOf(Class2, o1))
assert_false(instanceOf(Class3, o1))
assert_false(instanceOf(Class3, o2))
end)
test('is not instanceOf an unrelated class', function()
assert_false(instanceOf(UnrelatedClass, o1))
assert_false(instanceOf(UnrelatedClass, o2))
assert_false(instanceOf(UnrelatedClass, o3))
end)
end)
end)
|
-- Validation script for Bootloader when both SPI Flash Storage and SPI Flash Storage SFDP are selected
local spiflash = slc.is_selected("bootloader_spiflash_storage")
local spiflash_sfdp = slc.is_selected("bootloader_spiflash_storage_sfdp")
if spiflash and spiflash_sfdp then
validation.error('Cannot install SPI Flash Storage and SPI Flash Storage SFDP components simultaneously',
validation.target_for_project(),
'Please un-install either one of these components to fix this error')
end
|
--搜图
local key = XmlApi.Get("settings","saucenao"):split("|")
local keyIndex = 0
local searchFlag = {}
local function getUrls(urls)
local ret = ""
for i = 1, #urls do
ret = ret..urls[i].."\r\n"
end
return ret
end
local function getImageInfo(pic)
if keyIndex >= #key then
keyIndex = 1
else
keyIndex = keyIndex+1
end
local html = asyncHttpGet("https://saucenao.com/search.php?"..(#key ~= 0 and "api_key="..key[keyIndex].."&" or "")..
"db=999&output_type=2&numres=16&url="..pic:urlEncode(),"",30000)
local t,r,_ = jsonDecode(html)
if not r or not t then return false,"查找失败 可能今日搜索接口限额已满 明日再试或使用a2d代替" end
if not t.results or #t.results==0 then return false,"未找到结果 请尝试使用a2d搜索看看" end
local result = ""
local last = {}
local n = 0
for i=1,#t.results do
local tmp = ""
local flag = false
if t.results[i].header.index_id == 5 and tonumber(t.results[i].header.similarity) > t.header.minimum_similarity then
tmp = (t.results[i].header.thumbnail and asyncImage(t.results[i].header.thumbnail,true) or "").."\r\n"..
(t.results[i].data.title and t.results[i].data.title or "").."\r\n"..
(t.results[i].data.pixiv_id and "p站id:"..t.results[i].data.pixiv_id or "").."\r\n"..
(t.results[i].data.member_name and "画师:"..t.results[i].data.member_name or "").."\r\n"..
(t.results[i].data.ext_urls[1] and getUrls(t.results[i].data.ext_urls) or "")
elseif t.results[i].header.index_id == 21 and tonumber(t.results[i].header.similarity) > t.header.minimum_similarity then
tmp = (t.results[i].header.thumbnail and asyncImage(t.results[i].header.thumbnail) or "").."\r\n"..
(t.results[i].data.source and t.results[i].data.source or "").."\r\n"..
(t.results[i].data.part and "集数:"..t.results[i].data.part or "").."\r\n"..
(t.results[i].data.est_time and "时间:"..t.results[i].data.est_time or "").."\r\n"..
(t.results[i].data.ext_urls[1] and getUrls(t.results[i].data.ext_urls) or "")
elseif t.results[i].header.index_id == 18 and tonumber(t.results[i].header.similarity) > t.header.minimum_similarity then
tmp = (t.results[i].header.thumbnail and asyncImage(t.results[i].header.thumbnail,true) or "").."\r\n"..
(t.results[i].data.source and t.results[i].data.source or "").."\r\n"..
(t.results[i].data.creator[1] and "创作者:"..t.results[i].data.creator[1] or "").."\r\n"..
(t.results[i].data.eng_name and "英文名:"..t.results[i].data.eng_name.."\r\n" or "")..
(t.results[i].data.jp_name and "日文名:"..t.results[i].data.jp_name.."\r\n" or "")
elseif (t.results[i].header.index_id == 12 or t.results[i].header.index_id == 26) and
tonumber(t.results[i].header.similarity) > t.header.minimum_similarity then
tmp = (t.results[i].header.thumbnail and asyncImage(t.results[i].header.thumbnail,true) or "").."\r\n"..
((t.results[i].data.creator and t.results[i].data.creator ~= "") and "创作者:"..t.results[i].data.creator.."\r\n" or "")..
((t.results[i].data.characters and t.results[i].data.characters ~= "") and "人物:"..t.results[i].data.characters.."\r\n" or "")..
((t.results[i].data.material and t.results[i].data.material ~= "") and "原著:"..t.results[i].data.material.."\r\n" or "")..
(t.results[i].data.source and "来源:"..t.results[i].data.source.."\r\n" or "")..
(t.results[i].data.ext_urls[1] and getUrls(t.results[i].data.ext_urls) or "")
elseif tonumber(t.results[i].header.similarity) > t.header.minimum_similarity then
tmp = (t.results[i].header.thumbnail and asyncImage(t.results[i].header.thumbnail,true) or "").."\r\n"..
(t.results[i].data.title and t.results[i].data.title.."\r\n" or "")..
(t.results[i].data.ext_urls[1] and getUrls(t.results[i].data.ext_urls) or "")
end
if tonumber(t.results[i].header.similarity) > t.header.minimum_similarity and
t.results[i].header.index_id ~= 18 and
t.results[i].data.ext_urls and
t.results[i].data.ext_urls[1] then
if #last ~= 0 then
for m=1,#last do
if last[m] == t.results[i].data.ext_urls[1] then
flag = true
end
end
if not flag then last[#last+1] = t.results[i].data.ext_urls[1] end
else
last[1] = t.results[i].data.ext_urls[1]
end
end
if tmp ~= "" and not flag then
result = result..tmp..
(tonumber(t.results[i].header.similarity) < 40 and "此结果相似度过低,可能不正确" or "相似度:"..t.results[i].header.similarity)..
"\r\n-------------------\r\n"
n = n+1
if n >= 3 then
break
end
end
end
if n > 0 then
return true,result..tostring(n).."个结果"
end
return false,"未找到结果 请尝试使用a2d搜索看看"
end
local function imageSearch(data,sendMessage)
local pic = Utils.GetImageUrl(data.msg)
if pic and pic ~= "" then
local id = sendMessage("少女祈祷中....")
local ok,r = getImageInfo(pic)
if ok then
setCoolDownTime(data,"imageSearch",10*60)
end
CQApi:RemoveMessage(id)
return r,ok
else
return "未在消息中过滤出图片"
end
end
return {--搜图
check = function (data)
return (data.msg:find("^搜图") or data.msg:find("搜图$")) or
(data.msg:find("%[CQ:image,file=") and searchFlag[tostring(data.qq)])
end,
run = function (data,sendMessage)
if LuaEnvName ~= "828090839" then
if getUseNum(data, "imageSearch") >= 10 then
sendMessage(Utils.CQCode_At(data.qq).."今日你使用次数太多达到限制")
return true
end
end
if not checkCoolDownTime(data, "imageSearch", sendMessage) then
return true
end
if data.msg:gsub(" ","") == "搜图" then
searchFlag[tostring(data.qq)] = true
sendMessage(Utils.CQCode_At(data.qq).."请发送要搜索的图片")
else
if searchFlag[tostring(data.qq)] then
searchFlag[tostring(data.qq)] = nil
end
sys.taskInit(function ()
local r,ok = imageSearch(data,sendMessage)
local id = sendMessage(Utils.CQCode_At(data.qq).."\r\n"..r)
if ok then
setUseNum(data, "imageSearch")
end
if LuaEnvName ~= "private" and ok and id > 0 then
setAutoRemove(id,(2*60)-5)
end
end)
end
return true
end,
explain = function ()
return "[CQ:emoji,id=128444]搜图 加 完整二次元图片"
end
}
|
if ( SERVER ) then
AddCSLuaFile( "shared.lua" )
end
SWEP.BulletLength = 5.56
SWEP.CaseLength = 45
SWEP.MuzVel = 616.796
SWEP.Attachments = {
[1] = {"kobra", "riflereflex", "aimpoint", "acog"},
[2] = {"vertgrip", "bipod"},
[3] = {"laser"}}
SWEP.InternalParts = {
[1] = {{key = "hbar"}, {key = "lbar"}},
[2] = {{key = "hframe"}},
[3] = {{key = "ergonomichandle"}},
[4] = {{key = "customstock"}},
[5] = {{key = "lightbolt"}, {key = "heavybolt"}},
[6] = {{key = "gasdir"}}}
if ( CLIENT ) then
SWEP.PrintName = "IMI Galil ARM"
SWEP.Author = "Counter-Strike"
SWEP.Slot = 3
SWEP.SlotPos = 0 // = 0
SWEP.IconLetter = "v"
SWEP.Muzzle = "cstm_muzzle_ar"
SWEP.SparkEffect = "cstm_child_sparks_medium"
SWEP.SmokeEffect = "cstm_child_smoke_medium"
SWEP.ACOGDist = 5
killicon.AddFont( "cstm_rif_galil", "CSKillIcons", SWEP.IconLetter, Color( 255, 80, 0, 255 ) )
SWEP.VertGrip_Idle = {
['v_weapon.Left_Ring01'] = {vector = Vector(0, 0, 0), angle = Angle(0, 20.212999343872, -9.7749996185303)},
['v_weapon.Left_Index03'] = {vector = Vector(0, 0, 0), angle = Angle(0, 61.731998443604, 0)},
['v_weapon.Left_Index02'] = {vector = Vector(0, 0, 0), angle = Angle(0, 7.938000202179, 0)},
['v_weapon.Left_Index01'] = {vector = Vector(0, 0, 0), angle = Angle(-8.3559999465942, 29.093000411987, -17.836999893188)},
['v_weapon.Left_Ring03'] = {vector = Vector(0, 0, 0), angle = Angle(0, 57.069000244141, 0)},
['v_weapon.Left_Middle01'] = {vector = Vector(0, 0, 0), angle = Angle(-13.781000137329, 21.738000869751, -17.85000038147)},
['v_weapon.Left_Arm'] = {vector = Vector(-4.3, -2.5, 1), angle = Angle(1.5379999876022, 40.375, 121.94999694824)},
['v_weapon.Left_Pinky03'] = {vector = Vector(0, 0, 0), angle = Angle(0, 46.062000274658, 0)},
['v_weapon.Left_Hand'] = {vector = Vector(0, 0, 0), angle = Angle(33.848999023438, 0, 0)},
['v_weapon.Left_Thumb01'] = {vector = Vector(0, 0, 0), angle = Angle(-10.069000244141, -19.113000869751, 0)},
['v_weapon.Left_Thumb02'] = {vector = Vector(0, 0, 0), angle = Angle(0, -27.91900062561, 0)},
['v_weapon.Left_Thumb03'] = {vector = Vector(0, 0, 0), angle = Angle(0, -78.180999755859, 0)},
['v_weapon.Left_Middle03'] = {vector = Vector(0, 0, 0), angle = Angle(0, 63.849998474121, 0)},
['v_weapon.handle'] = {vector = Vector(0, 0, 0), angle = Angle(-37.868999481201, 0, 0)}}
SWEP.VElements = {
["silencer"] = { type = "Model", model = "models/props_c17/oildrum001.mdl", bone = "v_weapon.galil", pos = Vector(0.037, -0.057, 21.461), angle = Angle(0, 0, 0), size = Vector(0.05, 0.05, 0.17), color = Color(255, 255, 255, 0), surpresslightning = false, material = "models/bunneh/silencer", skin = 0, bodygroup = {}},
["kobra"] = { type = "Model", model = "models/attachments/cmore.mdl", bone = "v_weapon.galil", rel = "", pos = Vector(0.013, -1.994, 2.736), angle = Angle(0, 0, -90), size = Vector(0.5, 0.5, 0.5), color = Color(255, 255, 255, 0), surpresslightning = false, material = "", skin = 0, bodygroup = {} },
["riflereflex"] = { type = "Model", model = "models/attachments/kascope.mdl", bone = "v_weapon.galil", rel = "", pos = Vector(0.018, -2.07, 4.099), angle = Angle(0, 0, -90), size = Vector(0.5, 0.5, 0.5), color = Color(255, 255, 255, 0), surpresslightning = false, material = "", skin = 0, bodygroup = {} },
["acog"] = { type = "Model", model = "models/wystan/attachments/2cog.mdl", bone = "v_weapon.galil", pos = Vector(-0.232, 2.088, -1.538), angle = Angle(0, 0, -90), size = Vector(0.699, 0.699, 0.699), color = Color(255, 255, 255, 0), surpresslightning = false, material = "", skin = 0, bodygroup = {}},
["rail"] = { type = "Model", model = "models/wystan/attachments/akrailmount.mdl", bone = "v_weapon.galil", pos = Vector(0.193, -0.72, 3), angle = Angle(180, 0, -90), size = Vector(0.699, 0.699, 0.699), color = Color(255, 255, 255, 0), surpresslightning = false, material = "", skin = 0, bodygroup = {}},
["aimpoint"] = { type = "Model", model = "models/wystan/attachments/aimpoint.mdl", bone = "v_weapon.galil", pos = Vector(-0.101, 1.919, -1.889), angle = Angle(180, 180, 90), size = Vector(0.699, 0.699, 0.699), color = Color(255, 255, 255, 0), surpresslightning = false, material = "", skin = 0, bodygroup = {}},
["laser"] = { type = "Model", model = "models/props_c17/FurnitureBoiler001a.mdl", bone = "v_weapon.galil", rel = "", pos = Vector(0.524, -1.045, 14.368), angle = Angle(0, 0, 180), size = Vector(0.029, 0.029, 0.029), color = Color(255, 255, 255, 0), surpresslightning = false, material = "models/bunneh/silencer", skin = 0, bodygroup = {} },
["vertgrip"] = { type = "Model", model = "models/wystan/attachments/foregrip1.mdl", bone = "v_weapon.galil", rel = "", pos = Vector(-0.207, 3.23, 0.962), angle = Angle(0, 0, -90), size = Vector(0.6, 0.6, 0.6), color = Color(255, 255, 255, 0), surpresslightning = false, material = "", skin = 0, bodygroup = {} },
["bipod"] = { type = "Model", model = "models/wystan/attachments/bipod.mdl", bone = "v_weapon.galil", rel = "", pos = Vector(0, 2.012, 12.13), angle = Angle(0, 0, -90), size = Vector(1, 1, 1), color = Color(255, 255, 255, 0), surpresslightning = false, material = "", skin = 0, bodygroup = {[1] = 1} }
}
SWEP.WElements = {
["silencer"] = { type = "Model", model = "models/props_c17/oildrum001.mdl", pos = Vector(32, 0.25, -3.701), angle = Angle(-90, 0, 0), size = Vector(0.059, 0.059, 0.159), color = Color(255, 255, 255, 0), surpresslightning = false, material = "models/bunneh/silencer", skin = 0, bodygroup = {} },
["acog"] = { type = "Model", model = "models/wystan/attachments/2cog.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(1.363, 0.2, -1.101), angle = Angle(180, 90, -10), size = Vector(0.899, 0.899, 0.899), color = Color(255, 255, 255, 0), surpresslightning = false, material = "", skin = 0, bodygroup = {} },
["aimpoint"] = { type = "Model", model = "models/wystan/attachments/aimpoint.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(12.5, 0.73, -3.401), angle = Angle(180, -90, 10), size = Vector(0.833, 0.833, 0.833), color = Color(255, 255, 255, 0), surpresslightning = false, material = "", skin = 0, bodygroup = {} },
["rail"] = { type = "Model", model = "models/wystan/attachments/akrailmount.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(5, 0.699, -7.301), angle = Angle(180, -90, 10), size = Vector(0.666, 0.666, 0.666), color = Color(255, 255, 255, 0), surpresslightning = false, material = "", skin = 0, bodygroup = {} },
["vertgrip"] = { type = "Model", model = "models/wystan/attachments/foregrip1.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(5.862, 0, 0), angle = Angle(0, -90, 180), size = Vector(0, 0, 0), color = Color(255, 255, 255, 0), surpresslightning = false, material = "", skin = 0, bodygroup = {} },
["bipod"] = { type = "Model", model = "models/wystan/attachments/bipod.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(19.231, 0.162, -1.157), angle = Angle(0, 90, 180), size = Vector(1, 1, 1), color = Color(255, 255, 255, 0), surpresslightning = false, material = "", skin = 0, bodygroup = {[1] = 1} },
["kobra"] = { type = "Model", model = "models/attachments/cmore.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(6.3, 0.529, -7), angle = Angle(180, 90, -10), size = Vector(0.725, 0.725, 0.725), color = Color(255, 255, 255, 0), surpresslightning = false, material = "", skin = 0, bodygroup = {} },
["riflereflex"] = { type = "Model", model = "models/wystan/attachments/2octorrds.mdl", bone = "ValveBiped.Bip01_R_Hand", rel = "", pos = Vector(2.842, 0.702, -5.832), angle = Angle(180, 90, 0), size = Vector(1, 1, 1), color = Color(255, 255, 255, 0), surpresslightning = false, material = "", skin = 0, bodygroup = {} }
}
end
SWEP.Category = "Customizable Weaponry"
SWEP.HoldType = "ar2"
SWEP.Base = "cstm_base_pistol"
SWEP.FireModes = {"auto", "semi"}
SWEP.Spawnable = true
SWEP.AdminSpawnable = true
SWEP.ViewModelFOV = 70
SWEP.ViewModelFlip = false
SWEP.ViewModel = "models/weapons/v_rif_galil.mdl"
SWEP.WorldModel = "models/weapons/w_rif_galil.mdl"
SWEP.ShowViewModel = true
SWEP.ShowWorldModel = true
SWEP.ViewModelBonescales = {}
SWEP.Weight = 5
SWEP.AutoSwitchTo = false
SWEP.AutoSwitchFrom = false
SWEP.Primary.Sound = Sound("Weapon_Galil.Single")
SWEP.Primary.Recoil = 0.3
SWEP.Primary.Damage = 22
SWEP.Primary.NumShots = 1
SWEP.Primary.Cone = 0.02
SWEP.Primary.ClipSize = 35
SWEP.Primary.Delay = 0.095
SWEP.Primary.DefaultClip = 35
SWEP.Primary.Automatic = true
SWEP.Primary.Ammo = "5.56x45MM"
SWEP.InitialHoldtype = "smg"
SWEP.InHoldtype = "smg"
SWEP.SilencedSound = Sound("weapons/m4a1/m4a1-1.wav")
SWEP.SilencedVolume = 75
-- Animation speed/custom reload function related
SWEP.IsReloading = false
SWEP.AnimPrefix = ""
SWEP.ReloadSpeed = 1
SWEP.NoBoltAnim = true
SWEP.ShouldBolt = false
SWEP.ReloadDelay = 0
SWEP.IncAmmoPerc = 0.57 -- Amount of frames required to pass (in percentage) of the reload animation for the weapon to have it's amount of ammo increased
-- Dynamic accuracy related
SWEP.ShotsAmount = 0
SWEP.ConeDecAff = 0
SWEP.DefRecoil = 0.9
SWEP.CurCone = 0.03
SWEP.DecreaseRecoilTime = 0
SWEP.ConeAff1 = 0 -- Crouching/standing
SWEP.ConeAff2 = 0 -- Using ironsights
SWEP.UnConeTime = 0 -- Amount of time after firing the last shot that needs to pass until accuracy increases
SWEP.FinalCone = 0 -- Self explanatory
SWEP.VelocitySensivity = 2.2 -- Percentage of how much the cone increases depending on the player's velocity (moving speed). Rifles - 100%; SMGs - 80%; Pistols - 60%; Shotguns - 20%
SWEP.HeadbobMul = 1
SWEP.IsSilenced = false
SWEP.IronsightsCone = 0.002
SWEP.HipCone = 0.06
SWEP.InaccAff1 = 0.75
SWEP.ConeInaccuracyAff1 = 0.7
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = "none"
SWEP.IsUsingIronsights = false
SWEP.TargetMul = 0
SWEP.SetAndForget = false
SWEP.IronSightsPos = Vector(6.0749, -5.5216, 2.3984)
SWEP.IronSightsAng = Vector(2.5174, -0.0099, 0)
SWEP.AimPos = Vector(-5.145, -5.574, 2.322)
SWEP.AimAng = Vector(-0.276, 0, 0)
SWEP.ChargePos = Vector (5.4056, -10.3522, -4.0017)
SWEP.ChargeAng = Vector (-1.7505, -55.5187, 68.8356)
SWEP.ScopePos = Vector(-5.095, -5.91, 1.61)
SWEP.ScopeAng = Vector(0, 0, 0)
SWEP.KobraPos = Vector(-5.157, -7.377, 1.741)
SWEP.KobraAng = Vector(0, 0, 0)
SWEP.RReflexPos = Vector(-5.148, -7.377, 1.922)
SWEP.RReflexAng = Vector(0, 0, 0)
SWEP.ACOGPos = Vector(-5.153, -4.591, 1.55)
SWEP.ACOGAng = Vector(0, 0, 0)
SWEP.ACOG_BackupPos = Vector(-5.153, -6, 0.76)
SWEP.ACOG_BackupAng = Vector(0, 0, 0)
if CLIENT then
function SWEP:CanUseBackUp()
if self.VElements["acog"].color.a == 255 then
return true
end
return false
end
function SWEP:UseBackUp()
if self.AimPos == self.ACOG_BackupPos then
self.AimPos = self.ACOGPos
self.AimAng = self.ACOGAng
else
self.AimPos = self.ACOG_BackupPos
self.AimAng = self.ACOG_BackupAng
end
end
end
|
-- draws texture independed of cockpit lighting system
-- no default texture
defineProperty("image")
defineProperty("brt2")
defineProperty("x")
defineProperty("y")
local clr = get(brt2)
function draw(self)
sasl.gl.drawTexture(get(image), 0, 0, get(x), get(y), {clr ,clr ,clr})
end
|
SIGHUP = 1;
SIGINT = 2;
SIGQUIT = 3;
SIGILL = 4;
SIGTRAP = 5;
SIGABRT = 6;
SIGIOT = 6;
SIGBUS = 7;
SIGFPE = 8;
SIGKILL = 9;
SIGUSR1 = 10;
SIGSEGV = 11;
SIGUSR2 = 12;
SIGPIPE = 13;
SIGALRM = 14;
SIGTERM = 15;
SIGSTKFLT = 16;
SIGCHLD = 17;
SIGCONT = 18;
SIGSTOP = 19;
SIGTSTP = 20;
SIGTTIN = 21;
SIGTTOU = 22;
SIGURG = 23;
SIGXCPU = 24;
SIGXFSZ = 25;
SIGVTALRM = 26;
SIGPROF = 27;
SIGWINCH = 28;
SIGIO = 29;
SIGPOLL = SIGIO;
SIGPWR = 30;
SIGSYS = 31;
SIGUNUSED = 31;
SIGRTMIN = 32;
hive.register_signal(SIGINT);
hive.register_signal(SIGTERM);
hive.ignore_signal(SIGPIPE);
hive.ignore_signal(SIGCHLD);
function check_quit_signal()
local signal = hive.signal;
if signal & (1 << SIGINT) ~= 0 then
return true;
end
if signal & (1 << SIGQUIT) ~= 0 then
return true;
end
if signal & (1 << SIGTERM) ~= 0 then
return true;
end
return false;
end
|
thisResource = getThisResource()
thisDynamicRoot = getResourceDynamicElementRoot(thisResource)
-- DEBUG ONLY! Set to true for extended saving and loading times (medium sized maps)
DEBUG_LOADSAVE = false
|
-- Copyright 2020 The FedLearner Authors. All Rights Reserved.
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
local resty_md5 = require "resty.md5"
local str = require "resty.string"
local http = require "resty.http"
local cjson = require "cjson"
local util = require "util.util"
local etcd_resolver = require "fl_router.etcd_resolver"
--FIXME: maybe need use share memory for future.
--local shared_upstream = ngx.shared.upstream
local _M = {
_VERSION = '0.0.1',
--lua table key must be alpha start
--format for upstreams_dict:
--{
-- "addr_1": {
-- "last_ts": timestamp,
-- "backends": {},
-- "rr_count": 1,
-- }
-- "addr_2": {...}
--}
upstreams = {},
rr_count = 1,
}
function _M.local_lookup_route(self, route_key)
--lua idx start with 1
if #self.upstreams == 0 then
return nil
end
local ups = self.upstreams[route_key]
if ups == nil then
return nil
end
local now = ngx.now()
--extend to support multi backend
local idx = ups["rr_count"] % (#ups["backends"] + 1)
if now - ups["last_ts"] > 3 then
return nil
end
ngx.log(ngx.INFO, "select_backend choose,idx: ", idx)
if ups["backends"][idx] == nil then
ngx.log(ngx.ERR, "select_backend failed: ", idx,
"rr_count: ", ups["rr_count"],
"backends count: ", #ups["backends"])
return nil
end
--update rr_count
ups["rr_count"] = ups["rr_count"] + 1
return ups["backends"][idx]
end
function _M.get_router_key(self)
--URI default starts with /
local uri = ngx.var.uri
if uri:find("^/") == nil then
ngx.log(ngx.ERR, "invalid grpc: ", uri)
return nil
end
--Path → ":path" "/" Service-Name "/" {method name} # But see note below. grpc protocal
--get svc_name and method_name
local items = util.split(ngx.var.uri, "/")
local svc_name = items[2]
local func_name = items[3]
ngx.log(ngx.ERR, "debug grpc svc_name: ", svc_name,
", method_name: ", func_name)
--get uuid:
local route_id = ngx.var.http_route_id
if route_id == nil then
ngx.log(ngx.ERR, "empty route_id: ", ngx.var.uri)
return nil
end
ngx.var.svc_name = svc_name
ngx.var.func_name = func_name
ngx.log(ngx.ERR, "debug grpc service: ", svc_name)
ngx.log(ngx.ERR, "debug grpc function:", func_name)
ngx.log(ngx.ERR, "debug grpc addressid:", route_id)
return uuid
end
--@call phase: call by the access_by_lua_file;
function _M.route(self)
local route_key = self:get_router_key()
if route_key == nil then
ngx.var.backend_addr = ""
return
end
--[[
local ups_addr = self:local_lookup_route(route_key)
if ups_addr ~= nil then
ngx.var.backend_addr = ups_addr
return
end
]]--
--always retrive from backend name service;
local ups_addr, err = etcd_resolver:get(route_key)
if ups_addr == nil or err ~= nil then
ngx.log(ngx.ERR, "etcd_resolver error for :", route_key)
else
ngx.log(ngx.INFO, "etcd_lookup succ:", tostring(ups_addr))
ngx.var.backend_addr = ups_addr
return
end
end
return _M
|
-- Globals variables
GAME_WIDTH = 800
GAME_HEIGHT = 600
-- Input table
KEY_TABLE = {}
-- Fonts
FONT_SMALL = love.graphics.newFont('assets/fonts/Roboto-Regular.ttf', 16)
FONT_MEDIUM = love.graphics.newFont('assets/fonts/Roboto-Regular.ttf', 32)
FONT_BIG = love.graphics.newFont('assets/fonts/Roboto-Regular.ttf', 64)
|
PEER_ID = "96A679"
--include <evaluation_multi_esp32_element_size>
|
local fs = require("installer/utils/fs")
local M = {}
--- @alias category_modules tbl<string,boolean>
--- Get all installed modules table
--- Warn: This function access fs synchronously
--- @return tbl<string, category_modules>
M.get_modules = function()
local res = {}
local dirs = fs.read_dir(fs.base_path)
if dirs then
for _, dir in ipairs(dirs) do
if dir.type == "directory" then
local category = M.get_category_modules(dir.name)
res[dir.name] = category
end
end
end
return res
end
--- Get all categories
--- Warn: This function access fs synchronously
--- @return tbl<string,boolean>
M.get_categories = function()
local res = {}
local dirs = fs.read_dir(fs.base_path)
if dirs then
for _, dir in ipairs(dirs) do
if dir.type == "directory" then
res[dir.name] = true
end
end
end
return res
end
--- Get modules of category
--- Warn: This function access fs synchronously
--- @param category string
--- @return category_modules
M.get_category_modules = function(category)
local res = {}
local path = fs.category_path(category)
if vim.fn.isdirectory(path) == 1 then
local dirs = fs.read_dir(path)
if dirs then
for _, dir in ipairs(dirs) do
if dir.type == "directory" then
res[dir.name] = true
end
end
end
end
return res
end
return M
|
-----------------------------------
-- Area: Ordelle's Caves
-- NPC: ??? (qm2)
-- Involved in Quest: A Squire's Test II
-- !pos -94 1 273 193
-------------------------------------
local ID = require("scripts/zones/Ordelles_Caves/IDs")
require("scripts/globals/keyitems")
require("scripts/globals/quests")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
if player:getQuestStatus(SANDORIA, tpz.quest.id.sandoria.A_SQUIRE_S_TEST_II) == QUEST_ACCEPTED and not player:hasKeyItem(tpz.ki.STALACTITE_DEW) and player:getCharVar("SquiresTestII") == 0 then
player:setCharVar("SquiresTestII", os.time())
player:messageSpecial(ID.text.A_SQUIRE_S_TEST_II_DIALOG_I)
else
player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
end
|
--ELF·回归根源
function c1191004.initial_effect(c)
--
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TOHAND)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCountLimit(1,1191004+EFFECT_COUNT_CODE_OATH)
e1:SetCost(c1191004.cost1)
e1:SetCondition(c1191004.con1)
e1:SetTarget(c1191004.tg1)
e1:SetOperation(c1191004.op1)
c:RegisterEffect(e1)
--
end
--
c1191004.named_with_ELF=1
function c1191004.IsELF(c)
local m=_G["c"..c:GetCode()]
return m and m.named_with_ELF
end
--
function c1191004.cost1(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckLPCost(tp,1000) end
Duel.PayLPCost(tp,1000)
end
function c1191004.confilter(c)
return c:IsFaceup() and c:IsCode(1190104)
end
function c1191004.con1(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsExistingMatchingCard(c1191004.confilter,tp,LOCATION_MZONE,0,1,nil)
end
--
function c1191004.tg1(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(aux.TRUE,tp,0,LOCATION_ONFIELD,1,nil) end
local g=Duel.GetMatchingGroup(aux.TRUE,tp,0,LOCATION_ONFIELD,nil)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,g:GetCount(),0,0)
end
function c1191004.op1(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(aux.TRUE,tp,0,LOCATION_ONFIELD,nil)
Duel.SendtoHand(g,nil,REASON_EFFECT)
end
|
require 'Vector2'
require 'PlayerController'
Player = Object:extend()
Input = {
left = {'a', 'left'},
right = {'d', 'right'},
--up = {'w', 'up'},
down = {'s', 'down'},
jump = {'c', 'space', 'up', 'w'}
}
function Input.isDown(button)
assert(Input[button], "There is no Input button called " .. button)
for _, key in ipairs(Input[button]) do
if love.keyboard.isDown(key) then return true end
end
end
input = {}
function Player:new(x, y)
self.pos = Vector2(x or 0, y or 0)
self.w = 32
self.h = 40
self.collider = { x = 6, y = 0, w = self.w, h = self.h } -- puts an offset to player position
self.scale = Vector2(1, 1)
self._PlayerController = PlayerController(self, { speed = 300, Jump = {maxHeight = 150, timeToApex = 0.4} })
g_world:add(self, self.pos.x + self.collider.x, self.pos.y + self.collider.y, self.collider.w, self.collider.h)
self.image = love.graphics.newImage('img/Kat.png')
self.flipX = 1
end
function Player:update(dt)
input.x = (Input.isDown('left') and Input.isDown('right')) and 0 or Input.isDown('left') and -1 or Input.isDown('right') and 1 or 0
if input.x ~= 0 then
self.flipX = input.x
end
input.jump = Input.isDown('jump') and 1 or 0
self._PlayerController:update(dt)
end
function Player:draw()
love.graphics.push()
love.graphics.setColor(1, 1, 1)
--love.graphics.rectangle("fill", self.pos.x, self.pos.y, self.w * self.scale.x, self.h * self.scale.y)
love.graphics.draw(
self.image,
self.pos.x + (self.flipX < 0 and 44 or 0),
self.pos.y + 22 + 22, 0,
self.scale.x * 2 * self.flipX,
self.scale.y*-1 * 2
)
love.graphics.setColor(1, 1, 1)
love.graphics.pop()
end
|
local bomb_dmg_enable = ui.add_check_box("Enable", "bomb_dmg_enable", false)
local screen = engine.get_screen_size()
local bomb_indicator_color = ui.add_color_edit("Line color", "bomb_indicator_color", true, color_t.new(0, 255, 255, 255))
local bomb_indicator_pos_x = ui.add_slider_int("Indicator Pos X", "bomb_indicator_pos_x", 0, screen.x, 300)
local bomb_indicator_pos_y = ui.add_slider_int("Indicator Pos Y", "bomb_indicator_pos_y", 0, screen.x, 300)
local bomb_font = renderer.setup_font('C:/windows/fonts/verdana.ttf', 14, 0)
--Damage Calculate
local function calcDist(local_pos, target_pos)
local lx = local_pos.x;
local ly = local_pos.y;
local lz = local_pos.z;
local tx = target_pos.x;
local ty = target_pos.y;
local tz = target_pos.z;
local dx = lx - tx;
local dy = ly - ty;
local dz = lz - tz;
return math.sqrt(dx * dx + dy * dy + dz * dz);
end
local m_iHealth = se.get_netvar("DT_BasePlayer", "m_iHealth")
local m_ArmorValue = se.get_netvar("DT_CSPlayer", "m_ArmorValue")
local function p2c(per, alpha)
local red = per > 50 and 255 or math.floor((per * 2) * 255 / 100);
local green = per < 50 and 255 or math.floor(255 - (per * 2 - 100) * 255 / 100);
return color_t.new(red, green, 0, alpha or 255);
end
local function bomb_dmg_calc()
local me = entitylist.get_local_player()
local bombs = entitylist.get_entities_by_class( "CPlantedC4" )
local health = me:get_prop_int(m_iHealth)
local armor = me:get_prop_int(m_ArmorValue)
local bomb_pos = bombs[1]:get_prop_vector( 0x138 )
local lp_pos = me:get_prop_vector(se.get_netvar("DT_BaseEntity", "m_vecOrigin"))
local distance = calcDist(bomb_pos, lp_pos)
local willKill = false
local a = 450.7;
local b = 75.68;
local c = 789.2;
local d = (distance - b) / c;
local damage = a * math.exp(-d * d)
if armor > 0 then
local newDmg = damage * 0.5;
local armorDmg = (damage - newDmg) * 0.5;
if armorDmg > armor then
armor = armor * (1 / .5)
newDmg = damage - armorDmg;
end
damage = newDmg;
end
local dmg = 0
if damage >= 0.5 then
dmg = math.ceil(damage)
end
if dmg >= health then
willKill = true
else
willKill = false
end
local bindicator_pos_x= bomb_indicator_pos_x:get_value()
local bindicator_pos_y= bomb_indicator_pos_y:get_value()
local dmg_color = dmg
if dmg > 100 then
dmg_color = 100
end
local HP_color = p2c(dmg_color)
local HP_r = HP_color.r
local HP_g = HP_color.g
local HP_b = HP_color.b
local bindicator_color = bomb_indicator_color:get_value()
local bindicator_r = bindicator_color.r
local bindicator_g = bindicator_color.g
local bindicator_b = bindicator_color.b
renderer.rect_filled(vec2_t.new(bindicator_pos_x - 1, bindicator_pos_y - 1), vec2_t.new(bindicator_pos_x + 199, bindicator_pos_y + 27), color_t.new(30, 30, 30, 150))
renderer.rect_filled(vec2_t.new(bindicator_pos_x, bindicator_pos_y), vec2_t.new(bindicator_pos_x + 198, bindicator_pos_y + 1), color_t.new(bindicator_r, bindicator_g, bindicator_b, 255))
renderer.text("Bomb Damage:", bomb_font, vec2_t.new(bindicator_pos_x + 3, bindicator_pos_y + 7), 14, color_t.new(255, 255, 255, 255))
renderer.text(string.format("%s HP", dmg), bomb_font, vec2_t.new(bindicator_pos_x + 100, bindicator_pos_y + 7) , 14, color_t.new(HP_r, HP_g, HP_b, 255))
if willKill then
renderer.text("(FATAL)", bomb_font, vec2_t.new(bindicator_pos_x + 148, bindicator_pos_y + 7) , 14, color_t.new(255, 0, 0, 255))
end
end
local function on_paint()
if bomb_dmg_enable:get_value() then
bomb_dmg_calc()
end
end
client.register_callback('paint', on_paint)
|
local oldBuildTechData = BuildTechData
function BuildTechData()
local techData = oldBuildTechData()
table.insert(techData, { [kTechDataId] = kTechId.ShieldGenerator, [kTechDataHint] = "Shield Generator hint", [kTechDataDisplayName] = "Shield Generator", [kTechDataMaxExtents] = Vector(Player.kXZExtents, Player.kYExtents, Player.kXZExtents), [kTechDataMaxHealth] = Marine.kHealth, [kTechDataEngagementDistance] = kPlayerEngagementDistance, [kTechDataPointValue] = kMarinePointValue, [kTechDataCostKey] = kShieldGeneratorCost, [kTechDataMapName] = "shieldgenerator"})
table.insert(techData, { [kTechDataId] = kTechId.ShieldGeneratorTech, [kTechDataCostKey] = kShieldGeneratorResearchCost, [kTechDataResearchTimeKey] = kShieldGeneratorTechResearchTime, [kTechDataDisplayName] = "Shield Generator #1", [kTechDataTooltipInfo] = "Allows purchasing shield generators from armories. They improve armor effectiveness, give +20 armor, and auto-repair."})
table.insert(techData, { [kTechDataId] = kTechId.ShieldGeneratorTech2,[kTechDataCostKey] = kShieldGenerator2ResearchCost,[kTechDataResearchTimeKey] = kShieldGenerator2TechResearchTime, [kTechDataDisplayName] = "Shield Generator #2", [kTechDataTooltipInfo] = "Improves shield generator armor bonus to +40 and speeds up regeneration."})
table.insert(techData, { [kTechDataId] = kTechId.ShieldGeneratorTech3,[kTechDataCostKey] = kShieldGenerator3ResearchCost,[kTechDataResearchTimeKey] = kShieldGenerator3TechResearchTime, [kTechDataDisplayName] = "Shield Generator #3", [kTechDataTooltipInfo] = "Improves shield generator armor bonus to +60 and speeds up regeneration."})
return techData
end
|
local ConsoleApplication = require("ConsoleApplication")
local StaticLibrary = require("StaticLibrary")
local SharedLibrary = require("SharedLibrary")
local function generateTargetByType(targetName, targetType)
local t = targetType:lower()
if t == "console application" then
return ConsoleApplication:new(targetName)
elseif t == "static library" then
return StaticLibrary:new(targetName)
elseif t == "shared library" then
return SharedLibrary:new(targetName)
else
error(string.format("Invalid target type \"%s\"", targetType))
end
end
local function copyProp(from, to, propName, required)
if required == nil then
required = false
end
if from[propName] ~= nil then
to[propName] = from[propName]
elseif required then
error(string.format("Property \"%s\" is required!", propName))
end
end
local function parseTargetConfig(targetConfig)
local target = generateTargetByType(targetConfig.name, targetConfig.type)
local cp = function(propName, req)
copyProp(targetConfig, target, propName, req)
end
cp("files")
cp("includeDirectories")
cp("dependsOn")
cp("compileOptions")
cp("linkOptions")
cp("pch")
cp("exportSymbolsFile")
cp("onInit")
return target
end
return parseTargetConfig;
|
local torch = require 'torch'
local class = require 'class'
local state = class('KuhnState')
local CHECKFOLD = 1
local BETCALL = 2
local REW_SCALE = 0.33
local function sampleCard(deadCards)
local card = 0
repeat
card = math.random(3)
until deadCards[card]==0
deadCards[card] = 1
return card
end
function state:__init(obs)
self.nPlayers = 2
self.obs = obs or torch.Tensor(6)
self.playerBet = torch.DoubleTensor(self.nPlayers)
self.playerFolded = torch.ByteTensor(self.nPlayers)
self.deadCards = torch.ByteTensor(3)
self.playerHoldings = torch.ByteTensor(self.nPlayers)
self:reset()
end
function state:reset()
self.playerBet:fill(1)
self.playerFolded:zero()
self.deadCards:zero()
self.playerHoldings[1] = sampleCard(self.deadCards)
self.playerHoldings[2] = sampleCard(self.deadCards)
self.currentBet = 0
self.potsize = 2
self.playersTurn = 1
self.terminal = false
self:update_observation()
end
function state:num_players()
return self.nPlayers
end
function state:player()
return self.playersTurn
end
function state:observe()
return self.obs
end
function state:update_observation()
self.obs:zero()
self.obs[self.playerHoldings[self.playersTurn]] = 1
if self.playersTurn == 2 then
if self.playerBet[1] > 1.5 then
self.obs[5] = 1 -- p1 bet
else
self.obs[4] = 1 -- p1 check
end
else
if self.playerBet[2] > 1.5 then
self.obs[4] = 1 -- p1 check
self.obs[6] = 1 -- p2 bet
end
end
return self.obs
end
local simulator = class('KuhnSimulator')
function simulator:__init(args)
end
function simulator:actionDim()
return 2
end
function simulator:stateDim()
return self:new_state():observe():size(1)
end
function simulator:new_state(obs)
return state(obs)
end
function simulator:step(state, action, rewards)
rewards:zero()
if action == CHECKFOLD then
if state.currentBet == 0 then
-- check
local pt = state.playersTurn + 1
state.playersTurn = pt
if pt > state.nPlayers then
state.terminal = true
end
else
-- fold
-- assuming 2-player Kuhn
state.playerFolded[state.playersTurn] = 1
state.terminal = true
end
elseif action == BETCALL then
local pt = state.playersTurn
rewards[pt] = -1
state.playerBet[pt] = state.playerBet[pt] + 1
state.potsize = state.potsize + 1
state.playersTurn = pt%state.nPlayers+1
if state.currentBet == 0 then
state.currentBet = state.currentBet + 1
else
state.terminal = true
end
else
error("invalid kuhn action")
end
if state.terminal then
-- compute terminal rewards
simulator:compute_terminal_rewards(state, rewards)
end
rewards:mul(REW_SCALE)
return action
end
function simulator:compute_terminal_rewards(state, rewards)
-- assuming 2-player kuhn
winningPlayer = -1
if state.playerFolded[1] == 1 then
winningPlayer = 2
elseif state.playerFolded[2] == 1 then
winningPlayer = 1
else
if state.playerHoldings[1] > state.playerHoldings[2] then
winningPlayer = 1
else
winningPlayer = 2
end
end
rewards[winningPlayer] = rewards[winningPlayer] + state.potsize -- using relative rewards, thus whole pot is won
end
return {Kuhn = simulator}
|
return {
name = 'LineJoin',
description = 'Line join style.',
constants = {
{
name = 'miter',
description = 'The ends of the line segments beveled in an angle so that they join seamlessly.',
},
{
name = 'none',
description = 'No cap applied to the ends of the line segments.',
},
{
name = 'bevel',
description = 'Flattens the point where line segments join together.',
},
},
}
|
function PrintTable(t, indent, done)
PrintTableCall(t, print, indent, done)
end
function PrintTableCall(t, printFunc, indent, done)
--printFunc ( string.format ('PrintTable type %s', type(keys)) )
if type(t) ~= "table" then
printFunc("PrintTable called on not table value")
printFunc(tostring(t))
return
end
done = done or {}
done[t] = true
if not indent then
printFunc("Printing table")
end
indent = indent or 1
local l = {}
for k, v in pairs(t) do
table.insert(l, k)
end
table.sort(l)
for k, v in ipairs(l) do
-- Ignore FDesc
if v ~= 'FDesc' then
local value = t[v]
if type(value) == "table" and not done[value] then
done[value] = true
printFunc(string.rep ("\t", indent)..tostring(v)..":")
PrintTableCall(value, printFunc, indent + 2, done)
elseif type(value) == "userdata" and not done[value] then
done[value] = true
printFunc(string.rep ("\t", indent)..tostring(v)..": "..tostring(value))
PrintTableCall((getmetatable(value) and getmetatable(value).__index) or getmetatable(value), printFunc, indent + 2, done)
else
if t.FDesc and t.FDesc[v] then
printFunc(string.rep ("\t", indent)..tostring(t.FDesc[v]))
else
printFunc(string.rep ("\t", indent)..tostring(v)..": "..tostring(value))
end
end
end
end
end
|
local utils = require "typesystem_utils"
-- Get the handle of a type expected to have no arguments
function selectNoArgumentType(
node, seekctx, typeName, tagmask, resolveContextType, reductions, items)
if not resolveContextType or type(resolveContextType) == "table" then
io.stderr:write( "TRACE typedb:resolve_type\n"
.. utils.getResolveTypeTrace( typedb, seekctx, typeName, tagmask)
.. "\n")
utils.errorResolveType( typedb, node.line,
resolveContextType, seekctx, typeName)
end
for ii,item in ipairs(items) do
if typedb:type_nof_parameters( item) == 0 then
local constructor = applyReductionList( node, reductions, nil)
local item_constr = typedb:type_constructor( item)
constructor = applyConstructor( node, item, item_constr, constructor)
return item,constructor
end
end
utils.errorMessage( node.line, "Failed to resolve %s with no arguments",
utils.resolveTypeString( typedb, seekctx, typeName))
end
-- Get the type handle of a type defined as a path (elements of the
-- path are namespaces and parent structures followed by the type name resolved)
function resolveTypeFromNamePath( node, arg, argidx)
if not argidx then argidx = #arg end
local typeName = arg[ argidx]
local seekContextTypes
if argidx > 1 then
seekContextTypes = resolveTypeFromNamePath( node, arg, argidx-1)
expectDataType( node, seekContextTypes)
else
seekContextTypes = getSeekContextTypes()
end
local resolveContextType, reductions, items
= typedb:resolve_type( seekContextTypes, typeName, tagmask_namespace)
local typeId,constructor
= selectNoArgumentType( node, seekContextTypes, typeName,
tagmask_namespace, resolveContextType, reductions, items)
return {type=typeId, constructor=constructor}
end
-- Try to get the constructor and weight of a parameter passed with the
-- deduction tagmask optionally passed as an argument
function tryGetWeightedParameterReductionList(
node, redutype, operand, tagmask_decl, tagmask_conv)
if redutype ~= operand.type then
local redulist,weight,altpath
= typedb:derive_type( redutype, operand.type,
tagmask_decl, tagmask_conv)
if altpath then
utils.errorMessage( node.line, "Ambiguous derivation for '%s': %s | %s",
typedb:type_string(operand.type),
utils.typeListString(typedb,altpath," =>"),
utils.typeListString(typedb,redulist," =>"))
end
return redulist,weight
else
return {},0.0
end
end
-- Get the constructor of a type required. The deduction tagmasks are arguments
function getRequiredTypeConstructor(
node, redutype, operand, tagmask_decl, tagmask_conv)
if redutype ~= operand.type then
local redulist,weight,altpath
= typedb:derive_type( redutype, operand.type,
tagmask_decl, tagmask_conv)
if not redulist or altpath then
io.stderr:write( "TRACE typedb:derive_type "
.. typedb:type_string(redutype)
.. " <- " .. typedb:type_string(operand.type) .. "\n"
.. utils.getDeriveTypeTrace( typedb, redutype, operand.type,
tagmask_decl, tagmask_conv)
.. "\n")
end
if not redulist then
utils.errorMessage( node.line, "Type mismatch, required type '%s'",
typedb:type_string(redutype))
elseif altpath then
utils.errorMessage( node.line, "Ambiguous derivation for '%s': %s | %s",
typedb:type_string(operand.type),
utils.typeListString(typedb,altpath," =>"),
utils.typeListString(typedb,redulist," =>"))
end
local rt = applyReductionList( node, redulist, operand.constructor)
if not rt then
utils.errorMessage( node.line, "Construction of '%s' <- '%s' failed",
typedb:type_string(redutype),
typedb:type_string(operand.type))
end
return rt
else
return operand.constructor
end
end
-- Issue an error if the argument does not refer to a value type
function expectValueType( node, item)
if not item.constructor then
utils.errorMessage( node.line, "'%s' does not refer to a value",
typedb:type_string(item.type))
end
end
-- Issue an error if the argument does not refer to a data type
function expectDataType( node, item)
if item.constructor then
utils.errorMessage( node.line, "'%s' does not refer to a data type",
typedb:type_string(item.type))
end
return item.type
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.