content
stringlengths 5
1.05M
|
|---|
local get_digit = (function()
local numbers = {
[0] = { 1, 2, 3, 5, 6, 7 },
[1] = { 3, 6 },
[2] = { 1, 3, 4, 5, 7 },
[3] = { 1, 3, 4, 6, 7 },
[4] = { 2, 3, 4, 6 },
[5] = { 1, 2, 4, 6, 7 },
[6] = { 1, 2, 4, 5, 6, 7 },
[7] = { 1, 3, 6 },
[8] = { 1, 2, 3, 4, 5, 6, 7 },
[9] = { 1, 2, 3, 4, 6, 7 },
}
local bitmasks = {}
for n, t in pairs(numbers) do
local m = 0
for i = 1, #t do
m = m | (1 << t[i])
end
bitmasks[m] = n
end
return function(m)
return bitmasks[m]
end
end)()
local function permutate(arr, mem, m, cb)
if #mem == #arr then
cb(mem)
return
end
for i = 1, #arr do
if m & (1 << i) == 0 then
table.insert(mem, arr[i])
permutate(arr, mem, m | (1 << i), cb)
table.remove(mem)
end
end
end
local function string_to_number(s, key)
local x = 0
for c in s:gmatch '%w' do
x = x | (1 << key[c])
end
return get_digit(x)
end
local keys = { 'a', 'b', 'c', 'd', 'e', 'f', 'g' }
local function solve(digits)
local key
local function check_permutation(p)
local rev = {}
for k, v in ipairs(p) do
rev[v] = k
end
for j = 1, #digits do
if string_to_number(digits[j], rev) == nil then
return
end
end
key = rev
end
permutate(keys, {}, 0, check_permutation)
return key
end
local sum = 0
for line in io.lines() do
local digits = {}
for word in line:gmatch '%w+' do
table.insert(digits, word)
end
local key = solve(digits)
local n = 0
for i = #digits - 3, #digits do
local d = string_to_number(digits[i], key) * 10 ^ (#digits - i)
n = n + d
end
sum = sum + n
end
print(sum)
|
--/run dofile("interface/addons/DungeonLoots/lua/worldmap.lua")
local me = DL.worldmap
local lastmapID = GetCurrentWorldMapID()
function me.Show(instance, npc)
if instance then
WorldMapFrame:Show()
if npc then
if DL.tbls.instance[instance] then
for i=1,#DL.tbls.instance[instance].boss do
if DL.tbls.instance[instance].boss[i].id == npc then
WorldMapFrame_SetWorldMapID(DL.tbls.instance[instance].boss[i].pos.map or instance)
return
end
end
WorldMapFrame_SetWorldMapID(instance)
end
else
if DL.tbls.instance[instance] then
WorldMapFrame_SetWorldMapID(DL.tbls.instance[instance].zone)
end
end
end
end
function me.ShowInDL(map, boss)
DL.ui.listtype = 0 -- instancelist
if boss then
DL.ui.listid = 2 -- items
else
DL.ui.listid = 1 -- bosses
end
DL.ui.instanceid = map
DL.ui.bossid = boss
if DL_main_frame:IsVisible() then
DL.ui.FilterList()
else
DL_main_frame:Show()
end
DL.ui.SetChangerText()
end
function me.OnClick(this, key)
if key == "LBUTTON" then
if this.vars.zone then
if DL.tbls.instance[this.vars.zone] then
if IsAltKeyDown() then
me.ShowInDL(this.vars.map_id, this.vars.main or this.vars.id)
else
if DL.tbls.instance[this.vars.zone].boss[1].pos.map then
WorldMapFrame_SetWorldMapID(DL.tbls.instance[this.vars.zone].boss[1].pos.map)
return
end
end
end
WorldMapFrame_SetWorldMapID(this.vars.zone)
elseif this.vars.id then
if IsAltKeyDown() then
if IsCtrlKeyDown() then
GC_OpenWebRadio("http://www.rom-welten.de/database/view.php?id="..this.vars.id)
return
end
me.ShowInDL(this.vars.map_id, this.vars.main or this.vars.id)
elseif IsShiftKeyDown() then
DL_PreviewFrame:Show()
DL_PreviewFrameModel:SetModel(this.vars.id)
end
end
else -- RBUTTON
if this.vars.zone then -- Instanceportal
DL_WorldMap_Instance_Dropdown.vars = this.vars
ToggleDropDownMenu( DL_WorldMap_Instance_Dropdown, 1, nil, "cursor", 1 ,1 )
elseif this.vars.id then -- Bosspos
DL_WorldMap_Boss_Dropdown.vars = this.vars
ToggleDropDownMenu( DL_WorldMap_Boss_Dropdown, 1, nil, "cursor", 1 ,1 )
end
end
end
function me.OnEnter(this)
if not this.vars then
return
end
GameTooltip:SetOwner(WorldMapViewFrame, "ANCHOR_BOTTOMRIGHT")
GameTooltip:ClearAllAnchors()
GameTooltip:SetAnchor("BOTTOMRIGHT", "BOTTOMRIGHT", WorldMapViewFrame, 0, 0)
GameTooltip:Show();
local txt,tbl = "", {}
if this.vars.zone then
txt,tbl = DL.helper.GetInstanceTooltip(this.vars.zone)
if me.tp.instance[this.vars.zone] then -- teleport tooltip
table.insert(tbl,"<SEP>")
table.insert(tbl,TEXT("_glossary_00803"))
for i=1,#me.tp.instance[this.vars.zone] do
table.insert(tbl,me.tp.instance[this.vars.zone][i].note)
end
end
elseif this.vars.id then
txt,tbl = DL.helper.GetBossMapTooltip(this.vars)
if me.tp.instance[this.vars.id] then -- teleport tooltip
table.insert(tbl,"<SEP>")
table.insert(tbl,TEXT("_glossary_00803"))
for i=1,#me.tp.instance[this.vars.id] do
table.insert(tbl,me.tp.instance[this.vars.id][i].note)
end
end
end
GameTooltip:SetText(txt);
for i=1,#tbl do
if tbl[i] == "<SEP>" then
GameTooltip:AddSeparator()
else
GameTooltip:AddLine(tbl[i])
end
end
end
function me.GetPOISByMap(MapID, map_id2)
local tbl = {}
if DL.tbls.zone[MapID] and not map_id2 then
for zid,pos in pairs(DL.tbls.zone[MapID]) do
if type(pos) =="table" then
if DL_Settings.DLInstanceEnabled then
table.insert(tbl,{zone=zid,pos={x=pos.x,y=pos.y},instance = true})
if pos.val then
local t2 = me.GetPOISByMap(zid, MapID)
for i=1,#t2 do
table.insert(tbl,t2[i])
end
end
end
else
local t2 = me.GetPOISByMap(zid, MapID)
for i=1,#t2 do
table.insert(tbl,t2[i])
end
end
end
end
if DL.tbls.instance[MapID] and DL_Settings.DLBossesEnabled then
local bosses = DL.tbls.instance[MapID].boss
local minus = 0
for i=1,#bosses do
if bosses[i].nocount then
minus = minus +1
end
if bosses[i].pos and (not bosses[i].pos.map or (bosses[i].pos.map and map_id2 and bosses[i].pos.map==map_id2)) then
table.insert(tbl,{
id=bosses[i].id,
pos = bosses[i].pos,
loot = bosses[i].loot,
box = bosses[i].box,
worldboss = bosses[i].worldboss,
note = bosses[i].note,
visible = bosses[i].visible,
num=i-minus,
map_id = MapID,
}
)
if bosses[i].id2 then
for j=1,#bosses[i].id2 do
table.insert(tbl,{
id=bosses[i].id2[j].id,
pos = bosses[i].id2[j].pos,
loot = bosses[i].id2[j].loot,
worldboss = bosses[i].id2[j].worldboss,
box = bosses[i].id2[j].box,
visible = bosses[i].id2[j].visible,
num=i-minus,
main = bosses[i].id,
map_id = MapID,
}
)
end
end
end
end
end
return tbl
end
function me.DrawPOIS(MapID)
if not MapID then
MapID = GetCurrentWorldMapID()
end
lastmapID = MapID
if DL_Settings.DLWorldmapEnabled then
local tbl = me.GetPOISByMap(MapID)
for i=1,30 do
if tbl[i] and tbl[i].pos and tbl[i].pos.x and tbl[i].pos.y then -- Instance entrance
_G["DungeonLoot_WM_POI_Tex"..i]:ClearAllAnchors()
local xx,yy=WorldMapViewFrame:GetSize()
_G["DungeonLoot_WM_POI_Tex"..i]:SetAnchor("CENTER","TOPLEFT","WorldMapViewFrame",xx*tbl[i].pos.x,yy*tbl[i].pos.y)
if tbl[i].zone then
_G["DungeonLoot_WM_POI_Tex"..i].vars = tbl[i]
me.SetTexture(i,true,nil,nil,true)
elseif tbl[i].id then -- Boss
_G["DungeonLoot_WM_POI_Tex"..i].vars = tbl[i]
me.SetTexture(i,false,tbl[i].loot,tbl[i].box,tbl[i].visible,tbl[i].worldboss)
end
if me.tp.instance[tbl[i].zone] or me.tp.instance[tbl[i].id] then
_G["DungeonLoot_WM_POI_Tex"..i.."Teleport"]:Show()
else
_G["DungeonLoot_WM_POI_Tex"..i.."Teleport"]:Hide()
end
_G["DungeonLoot_WM_POI_Tex"..i]:Show()
else
_G["DungeonLoot_WM_POI_Tex"..i].vars = nil
_G["DungeonLoot_WM_POI_Tex"..i]:Hide()
end
end
else
for i=1,30 do
_G["DungeonLoot_WM_POI_Tex"..i].vars = nil
_G["DungeonLoot_WM_POI_Tex"..i]:Hide()
end
end
end
function me.SetTexture(id,instance,loot,box,visible, worldboss)
if not(id>30 or id <=0 or type(id)~="number") then
local frame = _G["DungeonLoot_WM_POI_Tex"..id]
if visible then
frame:Show()
else
frame:Hide()
end
if instance then
_G[frame:GetName().."Tex"]:SetFile("interface/addons/DungeonLoots/images/ini.tga")
else
if loot then
if box then
if worldboss then
_G[frame:GetName().."Tex"]:SetFile("interface/addons/DungeonLoots/images/kiste.tga")
else
_G[frame:GetName().."Tex"]:SetFile("interface/addons/DungeonLoots/images/kiste.tga")
end
else
if worldboss then
_G[frame:GetName().."Tex"]:SetFile("interface/targetframe/targetframe-bossicon.tga")
else
_G[frame:GetName().."Tex"]:SetFile("interface/addons/DungeonLoots/images/boss2.tga")
end
end
else
if worldboss then
_G[frame:GetName().."Tex"]:SetFile("interface/targetframe/targetframe-bossicon.tga")
else
_G[frame:GetName().."Tex"]:SetFile("interface/addons/DungeonLoots/images/boss1.tga")
end
end
end
end
end
-- /run local aa = WorldMapFrame_SetWorldMapID WorldMapFrame_SetWorldMapID=function(id) aa(id) print(id) end
local DL_WorldMapFrame_SetWorldMapID = WorldMapFrame_SetWorldMapID
function WorldMapFrame_SetWorldMapID( MapID )
DL_WorldMapFrame_SetWorldMapID( MapID )
if DL.tbls.zoneoverride[MapID] then
MapID = DL.tbls.zoneoverride[MapID]
end
me.DrawPOIS(MapID)
end
function me.Init()
me.WoWMap()
DL_WorldMap_Setting_DropdownButton:SetText(DL.lang.WorldmapButton or "")
if yGather_WorldmapButton then
DL_WorldMap_Setting_DropdownButton:ClearAllAnchors()
DL_WorldMap_Setting_DropdownButton:SetAnchor("LEFT","RIGHT","yGather_WorldmapButton",20,0)
end
UIDropDownMenu_Initialize(DL_WorldMap_Instance_Dropdown, me.InstanceDropdown);
UIDropDownMenu_Initialize(DL_WorldMap_Boss_Dropdown, me.Bossdropdown);
UIDropDownMenu_Initialize(DL_WorldMap_Setting_Dropdown, me.SettingDropdown);
me.CollectTransport()
end
function me.CheckDistance(x1,y1,x2,y2)
local x = x1-x2
local y = y1-y2
local dist = math.sqrt((x*x)+(y*y))
if dist < 4 then
return true
end
end
function me.CollectTransport()
me.tp = {instance={}, porter={}}
for i=1,49 do
local IconType,Note,ZoneID,X,Y,Z,Name,file=TB_GetTeleportInfo(i);
if ZoneID < 10000 then
ZoneID = ZoneID % 1000
end
if ZoneID==0 then
else
local zone = DL.tbls.zone[ZoneID]
if zone then --instance check
for instance, pos in pairs(zone) do
if type(pos)== "table" then
local x,y = string.match(Name, "(%d+%.%d),(%d+%.%d)")
if x and y then
if me.CheckDistance(x,y,pos.x*100,pos.y*100) then
me.tp.porter[i]=true
if not me.tp.instance[instance] then
me.tp.instance[instance] = {}
end
table.insert(me.tp.instance[instance],
{tpid = i, zone=ZoneID, name = Name, note= Note}
)
end
end
end
end
end
local zone = DL.tbls.instance[ZoneID]
if zone then
local boss = zone.boss
for z=1,#boss do
local pos = boss[z].pos
if pos then
local x,y = string.match(Name, "(%d%d.%d),(%d%d.%d)")
if x and y then
if me.CheckDistance(x,y,pos.x*100,pos.y*100) then
me.tp.porter[i]=true
if not me.tp.instance[boss[z].id] then
me.tp.instance[boss[z].id] = {}
end
table.insert(me.tp.instance[boss[z].id],
{tpid = i, zone=ZoneID, name = Name, note= Note}
)
end
end
end
end
end
if DL.tbls.translate_table[ZoneID] then
for zid, val in pairs(DL.tbls.translate_table[ZoneID]) do
local x1 = val[1]
local x2 = val[3]
local y1 = val[2]
local y2 = val[4]
local x,y = nil, nil
if x1-x2~=0 then
x=math.abs((1-(X-x2)/(x1-x2))*100)
end
if y1-y2~=0 then
y=math.abs((1-(Z-y2)/(y1-y2))*100)
end
local zone = DL.tbls.zone[zid]
if zone then --instance check
for instance, pos in pairs(zone) do
if type(pos)== "table" then
if x and y then
if me.CheckDistance(x,y,pos.x*100,pos.y*100) then
--me.tp.porter[i]=true -- don't hide these pois
if not me.tp.instance[instance] then
me.tp.instance[instance] = {}
end
table.insert(me.tp.instance[instance],
{tpid = i, zone=zid, name = Name, note= Note}
)
end
end
end
end
end
local zone = DL.tbls.instance[zid]
if zone then
local boss = zone.boss
for z=1,#boss do
local pos = boss[z].pos
if pos then
if x and y then
if me.CheckDistance(x,y,pos.x*100,pos.y*100) then
--me.tp.porter[i]=true -- don't hide these pois
if not me.tp.instance[boss[z].id] then
me.tp.instance[boss[z].id] = {}
end
table.insert(me.tp.instance[boss[z].id],
{tpid = i, zone=zid, name = Name, note= Note}
)
end
end
end
end
end
end
end
end
end
end
function me.Bossdropdown()
local vars = DL_WorldMap_Boss_Dropdown.vars
if not vars then return end
local menuitem = {};
if UIDROPDOWNMENU_MENU_LEVEL == 1 then
menuitem.notCheckable = 1;
menuitem.text = TEXT("Sys"..vars.id.."_name")
menuitem.isTitle = 1
UIDropDownMenu_AddButton(menuitem, UIDROPDOWNMENU_MENU_LEVEL);
menuitem = {}
--------------------------- ShowInDL ---------------------------
menuitem.text = DL.lang.ShowInDL
menuitem.func = function()
me.ShowInDL(vars.map_id, vars.main or vars.id)
end
UIDropDownMenu_AddButton(menuitem,UIDROPDOWNMENU_MENU_LEVEL)
--------------------------- RomWelten ---------------------------
menuitem.text = DL.lang.ShowInDB
menuitem.func = function()
GC_OpenWebRadio("http://www.rom-welten.de/database/view.php?id="..vars.id)
end
UIDropDownMenu_AddButton(menuitem,UIDROPDOWNMENU_MENU_LEVEL)
--------------------------- Preview ---------------------------
menuitem.text = TEXT("FST_PREVIEW")
menuitem.func = function()
DL_PreviewFrame:Show()
DL_PreviewFrameModel:SetModel(vars.id)
end
UIDropDownMenu_AddButton(menuitem,UIDROPDOWNMENU_MENU_LEVEL)
--------------------------- Teleport ---------------------------
menuitem = {}
menuitem.hasArrow = 1
if vars.id and me.tp.instance[vars.id] and #me.tp.instance[vars.id]>0 then
for i=1, #me.tp.instance[vars.id] do
menuitem.text = me.tp.instance[vars.id][i].note --del port
menuitem.value = i
UIDropDownMenu_AddButton(menuitem, UIDROPDOWNMENU_MENU_LEVEL)
end
end
elseif UIDROPDOWNMENU_MENU_LEVEL == 2 then -- tp
menuitem.notCheckable = 1;
menuitem.text = me.tp.instance[vars.id][UIDROPDOWNMENU_MENU_VALUE].name
menuitem.isTitle = 1
UIDropDownMenu_AddButton(menuitem, UIDROPDOWNMENU_MENU_LEVEL);
local tp_id = me.tp.instance[vars.id][UIDROPDOWNMENU_MENU_VALUE].tpid
menuitem = {}
menuitem.text = TEXT("TB_EDITNOTE_TIP")
menuitem.func = function ()
TeleportBook.select = tp_id
TB_EditNote_OnClick(nil)
end
UIDropDownMenu_AddButton( menuitem, UIDROPDOWNMENU_MENU_LEVEL )
menuitem = {}
menuitem.text = TEXT("TB_DELETE_TIP")
menuitem.hasArrow = 1
menuitem.value = tp_id
UIDropDownMenu_AddButton( menuitem, UIDROPDOWNMENU_MENU_LEVEL )
local _, transport,portal,passageway=TB_GetTeleportItem()
menuitem = {}
menuitem.text = TEXT("TB_TELEPORT_TYPE1")
menuitem.tooltipTitle = string.format(TB_TELEPORT_TIP,TB_GetItemName(2))
menuitem.disabled = 1
if transport then menuitem.disabled = nil end
menuitem.func = function ()
TB_Teleport(0, tp_id)
HideUIPanel( WorldMapFrame )
end
UIDropDownMenu_AddButton( menuitem, UIDROPDOWNMENU_MENU_LEVEL )
menuitem.text = TEXT("TB_TELEPORT_TYPE2")
menuitem.tooltipTitle = string.format(TB_TELEPORT_TIP,TB_GetItemName(3))
menuitem.disabled = 1
if portal then menuitem.disabled = nil end
menuitem.func = function ()
TB_Teleport(1, tp_id)
HideUIPanel( WorldMapFrame )
end
UIDropDownMenu_AddButton( menuitem, UIDROPDOWNMENU_MENU_LEVEL )
menuitem.text = TEXT("TB_TELEPORT_TYPE3")
menuitem.tooltipTitle = string.format(TB_TELEPORT_TIP,TB_GetItemName(4))
menuitem.disabled = 1
if passageway then menuitem.disabled = nil end
menuitem.func = function ()
TB_Teleport(2, tp_id)
HideUIPanel( WorldMapFrame )
end
UIDropDownMenu_AddButton( menuitem, UIDROPDOWNMENU_MENU_LEVEL )
elseif UIDROPDOWNMENU_MENU_LEVEL == 3 then -- delete
menuitem = {}
menuitem.text = TEXT("TB_DELETE_TIP")
menuitem.func = function ()
TB_DeleteTeleport(UIDROPDOWNMENU_MENU_VALUE)
ToggleDropDownMenu(DL_WorldMap_Instance_Dropdown)
end
UIDropDownMenu_AddButton( menuitem, UIDROPDOWNMENU_MENU_LEVEL )
end
end
function me.InstanceDropdown()
local menuitem = {};
local vars = DL_WorldMap_Instance_Dropdown.vars
if not vars then return end
if UIDROPDOWNMENU_MENU_LEVEL == 1 then
menuitem.notCheckable = 1;
menuitem.text = GetZoneLocalName(vars.zone or 1)
menuitem.isTitle = 1
UIDropDownMenu_AddButton(menuitem, UIDROPDOWNMENU_MENU_LEVEL);
menuitem = {}
--------------------------- ChangeMap ---------------------------
menuitem.text = TEXT("UI_WORLDMAP_SELECT_MAP") -- ChangeMap
menuitem.func = function()
if DL.tbls.instance[vars.zone] and DL.tbls.instance[vars.zone].boss[1].pos.map then
WorldMapFrame_SetWorldMapID(DL.tbls.instance[vars.zone].boss[1].pos.map)
return
end
WorldMapFrame_SetWorldMapID(vars.zone)
end
UIDropDownMenu_AddButton(menuitem,UIDROPDOWNMENU_MENU_LEVEL)
--------------------------- ShowInDL ---------------------------
if not DL.tbls.instance[vars.zone or 0] then
menuitem.disabled = 1
end
menuitem.text = DL.lang.ShowInDL
menuitem.func = function()
me.ShowInDL(vars.zone, nil)
end
UIDropDownMenu_AddButton(menuitem,UIDROPDOWNMENU_MENU_LEVEL)
--------------------------- Teleport ---------------------------
menuitem = {}
menuitem.hasArrow = 1
local pos = vars.pos
if vars.zone and me.tp.instance[vars.zone] and #me.tp.instance[vars.zone]>0 then
for i=1, #me.tp.instance[vars.zone] do
menuitem.text = me.tp.instance[vars.zone][i].note --del port
menuitem.value = i
UIDropDownMenu_AddButton(menuitem, UIDROPDOWNMENU_MENU_LEVEL)
end
end
elseif UIDROPDOWNMENU_MENU_LEVEL == 2 then -- tp
menuitem.notCheckable = 1;
menuitem.text = me.tp.instance[vars.zone][UIDROPDOWNMENU_MENU_VALUE].name
menuitem.isTitle = 1
UIDropDownMenu_AddButton(menuitem, UIDROPDOWNMENU_MENU_LEVEL);
local tp_id = me.tp.instance[vars.zone][UIDROPDOWNMENU_MENU_VALUE].tpid
menuitem = {}
menuitem.text = TEXT("TB_EDITNOTE_TIP")
menuitem.func = function ()
TeleportBook.select = tp_id
TB_EditNote_OnClick(nil)
end
UIDropDownMenu_AddButton( menuitem, UIDROPDOWNMENU_MENU_LEVEL )
menuitem = {}
menuitem.text = TEXT("TB_DELETE_TIP")
menuitem.hasArrow = 1
menuitem.value = tp_id
UIDropDownMenu_AddButton( menuitem, UIDROPDOWNMENU_MENU_LEVEL )
local _, transport,portal,passageway=TB_GetTeleportItem()
menuitem = {}
menuitem.text = TEXT("TB_TELEPORT_TYPE1")
menuitem.tooltipTitle = string.format(TB_TELEPORT_TIP,TB_GetItemName(2))
menuitem.disabled = 1
if transport then menuitem.disabled = nil end
menuitem.func = function ()
TB_Teleport(0, tp_id)
HideUIPanel( WorldMapFrame )
end
UIDropDownMenu_AddButton( menuitem, UIDROPDOWNMENU_MENU_LEVEL )
menuitem.text = TEXT("TB_TELEPORT_TYPE2")
menuitem.tooltipTitle = string.format(TB_TELEPORT_TIP,TB_GetItemName(3))
menuitem.disabled = 1
if portal then menuitem.disabled = nil end
menuitem.func = function ()
TB_Teleport(1, tp_id)
HideUIPanel( WorldMapFrame )
end
UIDropDownMenu_AddButton( menuitem, UIDROPDOWNMENU_MENU_LEVEL )
menuitem.text = TEXT("TB_TELEPORT_TYPE3")
menuitem.tooltipTitle = string.format(TB_TELEPORT_TIP,TB_GetItemName(4))
menuitem.disabled = 1
if passageway then menuitem.disabled = nil end
menuitem.func = function ()
TB_Teleport(2, tp_id)
HideUIPanel( WorldMapFrame )
end
UIDropDownMenu_AddButton( menuitem, UIDROPDOWNMENU_MENU_LEVEL )
elseif UIDROPDOWNMENU_MENU_LEVEL == 3 then -- delete
menuitem = {}
menuitem.text = TEXT("TB_DELETE_TIP")
menuitem.func = function ()
TB_DeleteTeleport(UIDROPDOWNMENU_MENU_VALUE)
ToggleDropDownMenu(DL_WorldMap_Instance_Dropdown)
end
UIDropDownMenu_AddButton( menuitem, UIDROPDOWNMENU_MENU_LEVEL )
end
end
function me.SettingDropdown()
local menuitem = {};
if UIDROPDOWNMENU_MENU_LEVEL == 1 then
menuitem.notCheckable = 1;
menuitem.text = DL.lang.WorldmapButton
menuitem.isTitle = 1
UIDropDownMenu_AddButton(menuitem, UIDROPDOWNMENU_MENU_LEVEL);
menuitem = {}
menuitem.keepShownOnClick = 1;
menuitem.text = DL.lang.HideWoWMapZone
menuitem.checked = DL_Settings.WoWMapInstanceDisabled
menuitem.func = function()
DL_Settings.WoWMapInstanceDisabled=not DL_Settings.WoWMapInstanceDisabled
end
UIDropDownMenu_AddButton(menuitem, UIDROPDOWNMENU_MENU_LEVEL);
menuitem = {};
menuitem.keepShownOnClick = 1;
menuitem.text = DL.lang.HideWoWMapTeleport
menuitem.checked = DL_Settings.WoWMapTPPOIDisabled
menuitem.func = function()
DL_Settings.WoWMapTPPOIDisabled=not DL_Settings.WoWMapTPPOIDisabled
WoWMapPOI.CollectTransportPOIs()
WorldMapFrame_SetWorldMapID(lastmapID)
end
UIDropDownMenu_AddButton(menuitem, UIDROPDOWNMENU_MENU_LEVEL);
menuitem = {};
menuitem.keepShownOnClick = 1;
menuitem.text = DL.lang.UseDLPoi
menuitem.checked = DL_Settings.DLWorldmapEnabled
menuitem.func = function()
DL_Settings.DLWorldmapEnabled=not DL_Settings.DLWorldmapEnabled
if DL_Settings.DLWorldmapEnabled then
DropDownList1Button5:Enable()
DropDownList1Button6:Enable()
else
DropDownList1Button5:Disable()
DropDownList1Button6:Disable()
end
me.DrawPOIS(lastmapID)
end
UIDropDownMenu_AddButton(menuitem, UIDROPDOWNMENU_MENU_LEVEL);
menuitem = {};
menuitem.keepShownOnClick = 1;
menuitem.text = DL.lang.UseDLInstancePoi
if not DL_Settings.DLWorldmapEnabled then
menuitem.disabled = 1
end
menuitem.checked = DL_Settings.DLInstanceEnabled
menuitem.func = function()
DL_Settings.DLInstanceEnabled=not DL_Settings.DLInstanceEnabled
me.DrawPOIS(lastmapID)
end
UIDropDownMenu_AddButton(menuitem, UIDROPDOWNMENU_MENU_LEVEL);
menuitem = {};
menuitem.keepShownOnClick = 1;
menuitem.text = DL.lang.UseDLBossPoi
if not DL_Settings.DLWorldmapEnabled then
menuitem.disabled = 1
end
menuitem.checked = DL_Settings.DLBossesEnabled
menuitem.func = function()
DL_Settings.DLBossesEnabled=not DL_Settings.DLBossesEnabled
me.DrawPOIS(lastmapID)
end
UIDropDownMenu_AddButton(menuitem, UIDROPDOWNMENU_MENU_LEVEL);
end
end
function me.CollectTransportPOIs()
assert(WoWMap and WoWMap.Data and WoWMap.Data.POIs) -- call it only if WoWMap-POI is loaded
me.CollectTransport()
for i, poi_cat in pairs(WoWMap.Data.POIs) do
if poi_cat.maps then
for map_id ,tbl in pairs(poi_cat.maps) do
local tbl_len = #tbl
for j=1, tbl_len do
for a,b in pairs(tbl[tbl_len-j+1]) do
if a=="TBNr" then
if me.tp.porter[b] then
table.remove(WoWMap.Data.POIs[i].maps[map_id], tbl_len-j+1)
end
end
end
end
end
end
end
end
function me.WoWMap()
--WoWMap workaround
if WoWMap and WoWMap.Data then
local version= tonumber(string.match(WoWMap.Data.Version,"v(%d+).+"))
if version >=4 then
local DungeonLoot_WorldMapFrame_OnUpdate = WorldMapFrame_OnUpdate
function WorldMapFrame_OnUpdate(elapsedTime)
DungeonLoot_WorldMapFrame_OnUpdate(elapsedTime)
if DL_Settings.WoWMapInstanceDisabled then
if WoWMap.Data.ZoneID then
local zid = WoWMap.Data.ZoneID
if DL.tbls.zone[zid] then
for a,b in pairs(DL.tbls.zone[zid]) do
if type(b)=="boolean" and b==true then
WoWMapHighlight:Hide()
end
end
elseif DL.tbls.instance[zid] and WoWMap.GetCurrentMapID()==DL.tbls.instance[zid].zone then
WoWMapHighlight:Hide()
end
if DL.tbls.zoneoverride[WoWMap.GetCurrentMapID()] then
zid = DL.tbls.zoneoverride[WoWMap.GetCurrentMapID()]
if DL.tbls.instance[zid] and WoWMap.GetCurrentMapID()==DL.tbls.instance[zid].zone then
WoWMapHighlight:Hide()
end
end
end
end
end
if WoWMapPOI then
local ori_CollectTransportPOIs = WoWMapPOI.CollectTransportPOIs
function WoWMapPOI.CollectTransportPOIs()
ori_CollectTransportPOIs()
if DL_Settings.WoWMapTPPOIDisabled then
me.CollectTransportPOIs()
end
end
end
end
end
end
DL.worldmap = me
|
local util = require 'lua_util'
context("Lua util - callback_from_string", function()
local cases = {
{'return function', 'return function(a, b) return a + b end'},
{'function', 'function(a, b) return a + b end'},
{'plain ops', 'local c = select(1, ...)\nreturn c + select(2, ...)'},
}
local fail_cases = {
nil,
'',
'return function(a, b) ( end',
'function(a, b) ( end',
'return a + b'
}
for _,c in ipairs(cases) do
test('Success case: ' .. c[1], function()
local ret,f = util.callback_from_string(c[2])
assert_true(ret, f)
assert_equal(f(2, 2), 4)
end)
end
for i,c in ipairs(fail_cases) do
test('Failure case: ' .. tostring(i), function()
local ret,f = util.callback_from_string(c)
assert_false(ret)
end)
end
end)
context("Lua util - str_endswith", function()
local ending = {
{'a', 'a'},
{'ab', 'b'},
{'ab', 'ab'},
{'abc', 'bc'},
{'any', ''},
}
local not_ending = {
{'a', 'b'},
{'', 'a'},
{'ab', 'a'},
{'ab', 'ba'},
{'ab', 'lab'},
{'abc', 'ab'},
{'abcd', 'bc'},
{'a', 'A'},
{'aB', 'b'},
}
for _, c in ipairs(ending) do
test(string.format('True case: str_endswith("%s", "%s")', c[1], c[2]), function()
assert_true(util.str_endswith(c[1], c[2]))
end)
end
for _, c in ipairs(not_ending) do
test(string.format('False case: str_endswith("%s", "%s")', c[1], c[2]), function()
assert_false(util.str_endswith(c[1], c[2]))
end)
end
end)
|
-- import
local Config = require "candy.Config"
--------------------------------------------------------------------------------
-- MOAI SDK
--------------------------------------------------------------------------------
-- Setting the FPS
MOAISim.setStep ( 1 / 60 )
-- Setting of the operation of the Loop.
MOAISim.clearLoopFlags ()
MOAISim.setCpuBudget ( 2 )
MOAISim.setLoopFlags ( MOAISim.SIM_LOOP_ALLOW_BOOST )
MOAISim.setLoopFlags ( MOAISim.SIM_LOOP_ALLOW_SPIN + MOAISim.SIM_LOOP_ALLOW_BOOST )
-- Sets the boost threshold
-- MOAISim.setBoostThreshold ( 0 )
MOAISim.setLongDelayThreshold ( 10 )
MOAISim.setBoostThreshold ( 2 )
MOAISim.setStepMultiplier ( 1 )
--------------------------------------------------------------------------------
-- Flower
--------------------------------------------------------------------------------
-- Resources setting
-- candy.Resources.addResourceDirectory ( "assets" )
-- Set the window size
-- if candy.isDesktop () then
-- local brand = MOAIEnvironment.osBrand
-- if brand == 'Windows' then
-- candy.setDefaultWindowSize ( "desktop1920x1080", true, false ) -- windows
-- else
-- candy.setDefaultWindowSize ( "desktop2560x1440", true, true ) -- *nix system
-- end
-- end
-- Set the window title
Config.WINDOW_TITLE = "Game" .. ' - ' .. MOAIEnvironment.osBrand
-- Ver
Config.VERSION = "0.1"
-- Config.WINDOW_WIDTH = 320
-- Config.WINDOW_HEIGHT = 480
-- default y behavior; set to true to have y=0 be the bottom of the screen
Config.VIEWPORT_YFLIP = false
-- Optional table of arguments for setBlendMode on new images.
-- Empty table gives default behavior.
Config.BLEND_MODE = nil
-- High quality rendering of Label
-- When enabled, it may take a long time to display the label.
Config.LABEL_HIGH_QUALITY_ENABLED = true
-- Set the default font
Config.FONT_NAME = "fonts/VL-PGothic.ttf"
-- Set the default font charcodes
-- Optimized by setting the loadable string in advance.
Config.FONT_CHARCODES = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 .,:;!?()&/-"
-- Default font points
-- Config.FONT_POINTS = 24
-- Set the default font filter
Config.FONT_FILTER = MOAITexture.GL_LINEAR
-- Config.FONT_FILTER = MOAITexture.GL_NEAREST
-- Set the texture filter of default
Config.TEXTURE_DEFAULT_FILTER = MOAITexture.GL_LINEAR
-- Config.TEXTURE_DEFAULT_FILTER = MOAITexture.GL_NEAREST
-- Setting of the behavior of the InputMgr
-- Whether to fire a touch event on the desktop environment
Config.TOUCH_EVENT_ENABLED = true
-- Whether to fire a mouse event on the desktop environment
Config.MOUSE_EVENT_ENABLED = true
--------------------------------------------------------------------------------
-- Logger
--------------------------------------------------------------------------------
-- info log
-- candy.Logger.LOG_LEVELS.INFO = true
-- warn log
-- candy.Logger.LOG_LEVELS.WARN = true
-- error log
-- candy.Logger.LOG_LEVELS.ERROR = true
-- debug log
-- candy.Logger.LOG_LEVELS.DEBUG = true
-- trace log
-- candy.Logger.LOG_LEVELS.TRACE = true
_G.CANDY_LOG_LEVEL = 'status'
_G.MOAI_LOG_LEVEL = 'status'
--------------------------------------------------------------------------------
-- Debugging
--------------------------------------------------------------------------------
-- Show bounds of MOAIProp
-- flower.DebugUtils.showDebugLines()
-- Start performance log
-- flower.DebugUtils.startPerformanceLog()
return Config
|
object_mobile_nova_orion_employee_05 = object_mobile_shared_nova_orion_employee_05:new {
}
ObjectTemplates:addTemplate(object_mobile_nova_orion_employee_05, "object/mobile/nova_orion_employee_05.iff")
|
local _, nMainbar = ...
nMainbarMouseoverMixin = {}
function nMainbarMouseoverMixin:OnLoad()
self.bar = self:GetParent()
end
function nMainbarMouseoverMixin:OnShow()
if ( not self:IsMouseOver() ) then
self.bar:SetAlpha(self.minAlpha)
end
end
function nMainbarMouseoverMixin:OnEnter()
self.bar:SetAlpha(self.maxAlpha)
end
function nMainbarMouseoverMixin:OnLeave()
self.bar:SetAlpha(self.minAlpha)
end
function nMainbarMouseoverMixin:SetupBar(buttonName, maxButtons, minAlpha, maxAlpha)
self.buttonName = buttonName
self.maxButtons = maxButtons
self.minAlpha = minAlpha or 0
self.maxAlpha = maxAlpha or 1
self.bar:SetAlpha(self.minAlpha)
self:SetPoint("TOPLEFT", _G[self.buttonName..1], -5, 5)
self:SetPoint("BOTTOMRIGHT", _G[self.buttonName..self.maxButtons], 5, -5)
self:SetupButtons()
hooksecurefunc("ValidateActionBarTransition", function()
if ( self.bar:IsShown() ) then
if ( not self:IsMouseOver() ) then
self.bar:SetAlpha(self.minAlpha)
end
end
end)
end
function nMainbarMouseoverMixin:SetupButtons()
for i = 1, self.maxButtons do
local button = _G[self.buttonName..i]
if ( button ) then
button:HookScript("OnEnter", function()
self.bar:SetAlpha(self.maxAlpha)
end)
button:HookScript("OnLeave", function()
if ( not self:IsMouseOver() ) then
self.bar:SetAlpha(self.minAlpha)
end
end)
end
end
end
|
-- UDVDevice.lua
local libudev = require("libudev_ffi")
local UDVListIterator = require("UDVListIterator")
local libc = require("libc")
local UDVDevice = {}
setmetatable(UDVDevice, {
__call = function(self, ...)
return UDVDevice:new(...)
end,
})
local UDVDevice_mt = {
__index = UDVDevice;
}
function UDVDevice.init(self, handle)
--local ctxt = UDVContext(libudev.udev_device_get_udev(handle))
--print("UDVDevice.init: ", handle)
local obj = {
Handle = handle;
DevPath = libc.safeffistring(libudev.udev_device_get_devpath(handle));
Subsystem = libc.safeffistring(libudev.udev_device_get_subsystem(handle));
DevType = libc.safeffistring(libudev.udev_device_get_devtype(handle));
SysPath = libc.safeffistring(libudev.udev_device_get_syspath(handle));
SysName = libc.safeffistring(libudev.udev_device_get_sysname(handle));
SysNum = libc.safeffistring(libudev.udev_device_get_sysnum(handle));
DevNode = libc.safeffistring(libudev.udev_device_get_devnode(handle));
Driver = libc.safeffistring(libudev.udev_device_get_driver(handle));
Action = libc.safeffistring(libudev.udev_device_get_action(handle));
IsInitialized = libudev.udev_device_get_is_initialized(handle)==1;
}
obj.Name = obj.SysPath;
setmetatable(obj, UDVDevice_mt)
return obj;
end
function UDVDevice.new(self, ctxt, syspath)
local dev = libudev.udev_device_new_from_syspath(ctxt, syspath)
if dev == nil then
return nil;
end
return self:init(dev)
end
function UDVDevice.newFromHandle(self, device_handle)
return self:init(device_handle);
end
function UDVDevice.action(self)
return libc.safeffistring(libudev.udev_device_get_action(self.Handle));
end
-- iterate over all the properties of the device
function UDVDevice.properties(self)
local listEntry = libudev.udev_device_get_properties_list_entry(self.Handle);
return UDVListIterator, listEntry, listEntry;
end
-- retrieve the value of a single property
function UDVDevice.getProperty(self, name)
name = name:lower()
for _, prop in self:properties() do
if name == prop.Name:lower() then
return prop.Value;
end
end
return nil;
end
-- iterate over all the tags for the device
-- tags are nothing more than the 'TAGS' property broken out
-- into a convenient API
function UDVDevice.tags(self)
local listEntry = libudev.udev_device_get_tags_list_entry(self.Handle);
return UDVListIterator, listEntry, listEntry;
end
return UDVDevice
|
slot0 = class("NewYearShrinePage", import("...base.BaseActivityPage"))
slot0.MAX_COUNT = 7
slot0.OnInit = function (slot0)
slot0.progressTpl = slot0:findTF("ProgressTpl")
slot0.progressTplContainer = slot0:findTF("ProgressList")
slot0.progressUIItemList = UIItemList.New(slot0.progressTplContainer, slot0.progressTpl)
slot0.countText = slot0:findTF("CountText")
slot1 = slot0:findTF("Award")
slot0.lockTF = slot0:findTF("Unlock", slot1)
slot0.getBtn = slot0:findTF("Achieve", slot1)
slot0.gotTag = slot0:findTF("Got", slot1)
slot0.goBtn = slot0:findTF("GoBtn")
end
slot0.OnDataSetting = function (slot0)
slot0.isAchieved = slot0.activity.data1
slot0.playCount = slot0.activity.data2
slot0.startTimestamp = slot0.activity.data3
slot0.dayFromStart = pg.TimeMgr.GetInstance():DiffDay(slot0.startTimestamp, pg.TimeMgr.GetInstance():GetServerTime()) + 1
slot0.curDay = math.clamp(slot0.dayFromStart, 1, slot0.MAX_COUNT)
slot0.storyIDTable = {}
if slot0.activity:getConfig("config_client").story then
for slot5, slot6 in ipairs(slot1) do
if slot6[1] then
slot0.storyIDTable[slot5] = slot7
end
end
end
end
slot0.OnFirstFlush = function (slot0)
setText(slot0.countText, slot1)
slot0.progressUIItemList:make(function (slot0, slot1, slot2)
if slot0 == UIItemList.EventUpdate then
slot3 = slot0:findTF("Achieve", slot2)
slot4 = slot0:findTF("Unlock", slot2)
setActive(slot0:findTF("Lock", slot2), slot1 + 1 > slot0.curDay)
if slot1 <= slot0.curDay then
setActive(slot3, slot1 <= slot1)
setActive(slot4, slot1 < slot1)
else
setActive(slot3, false)
setActive(slot4, true)
end
end
end)
slot0.progressUIItemList.align(slot2, slot0.MAX_COUNT)
onButton(slot0, slot0.getBtn, function ()
if slot1.MAX_COUNT <= slot0.curDay and slot1.MAX_COUNT <= slot0.playCount and slot0.isAchieved <= 0 then
slot0:emit(ActivityMediator.EVENT_OPERATION, {
cmd = 1,
activity_id = slot0.activity.id
})
end
end, SFX_PANEL)
onButton(slot0, slot0.goBtn, function ()
pg.m02:sendNotification(GAME.GO_MINI_GAME, 20, {
callback = function ()
SCENE.SetSceneInfo(slot0, SCENE.NEWYEAR_BACKHILL)
getProxy(ContextProxy):PushContext2Prev(Context.New())
end
})
end, SFX_PANEL)
slot2 = {}
slot3 = pg.NewStoryMgr.GetInstance()
slot4 = math.clamp(slot0.playCount, 0, slot0.MAX_COUNT)
for slot8 = 1, slot0.MAX_COUNT, 1 do
if slot0.storyIDTable[slot8] and slot8 <= slot0.curDay and slot8 <= slot4 then
table.insert(slot2, function (slot0)
slot0:Play(slot0.Play, slot0)
end)
end
end
seriesAsync(slot2, function ()
print("play story done,count:", #slot0)
end)
end
slot0.OnUpdateFlush = function (slot0)
setActive(slot0.gotTag, slot0.isAchieved > 0)
if slot0.MAX_COUNT <= slot0.curDay and slot0.MAX_COUNT <= slot0.playCount and slot0.isAchieved <= 0 then
setActive(slot0.lockTF, false)
setActive(slot0.getBtn, true)
triggerButton(slot0.getBtn)
elseif slot0.isAchieved > 0 then
setActive(slot0.lockTF, false)
setActive(slot0.getBtn, true)
else
setActive(slot0.lockTF, true)
setActive(slot0.getBtn, false)
end
end
slot0.OnDestroy = function (slot0)
return
end
slot0.IsTip = function ()
if getProxy(ActivityProxy):getActivityById(pg.activity_const.NEWYEAR_SHRINE_PAGE_ID.act_id) and not slot0:isEnd() then
return math.clamp(slot0.data2, 0, slot0.MAX_COUNT) < math.clamp(slot1, 1, slot0.MAX_COUNT)
end
end
return slot0
|
function plugindef()
-- This function and the 'finaleplugin' namespace
-- are both reserved for the plug-in definition.
finaleplugin.Author = "Jacob Winkler"
finaleplugin.Copyright = "2022"
finaleplugin.Version = ".1"
finaleplugin.Date = "1/30/2022"
return "Run Script", "Run Script", "Opens and executes a Lua script"
end
function run_script()
local script_name = open_script()
-- Will eventually add additional logic for previously opened scripts...
dofile(script_name)
end
function open_script()
local ui = finenv.UI()
local run = finale.FCFileOpenDialog(ui)
local str = finale.FCString()
--
run:Execute()
run:GetFileName(str)
return str.LuaString
end
run_script()
|
local Observer = require("reactivex.observer")
local ReplaySubject = require("reactivex.subjects.replaysubject")
local Subscription = require("reactivex.subscription")
local Observable = require("reactivex.observable")
local Observer = require("reactivex.observer")
local Subscription = require("reactivex.subscription")
describe('ReplaySubject', function()
describe('create', function()
it('returns a ReplaySubject', function()
expect(ReplaySubject.create()).to.be.an(ReplaySubject)
end)
it('sets an appropriate buffer size if it is specified', function()
local subject = ReplaySubject.create(2)
local observer = Observer.create()
local onNext = spy(observer, '_onNext')
subject:onNext(1)
subject:onNext(2)
subject:onNext(3)
subject:subscribe(observer)
expect(onNext).to.equal({{2}, {3}})
end)
it('keeps an infinite buffer if no buffer size is specified', function()
local subject = ReplaySubject.create()
local observer = Observer.create()
local onNext = spy(observer, '_onNext')
subject:onNext(1)
subject:onNext(2)
subject:onNext(3)
subject:subscribe(observer)
expect(onNext).to.equal({{1}, {2}, {3}})
end)
end)
describe('subscribe', function()
it('returns a Subscription', function()
local subject = ReplaySubject.create()
local observer = Observer.create()
expect(subject:subscribe(observer)).to.be.an(Subscription)
end)
it('accepts 3 functions as arguments', function()
local onNext, onCompleted = spy(), spy()
local subject = ReplaySubject.create()
subject:subscribe(onNext, nil, onCompleted)
subject:onNext(5)
subject:onCompleted()
expect(onNext).to.equal({{5}})
expect(#onCompleted).to.equal(1)
end)
it('calls onNext with the current buffer', function()
local subject = ReplaySubject.create(2)
local observer = Observer.create()
local onNext = spy(observer, '_onNext')
subject:onNext(1)
subject:onNext(2)
subject:onNext(3)
subject:subscribe(observer)
expect(onNext).to.equal({{2}, {3}})
end)
end)
describe('onNext', function()
it('pushes values to all subscribers', function()
local observers = {}
local spies = {}
for i = 1, 2 do
observers[i] = Observer.create()
spies[i] = spy(observers[i], '_onNext')
end
local subject = ReplaySubject.create()
subject:subscribe(observers[1])
subject:subscribe(observers[2])
subject:onNext(1)
subject:onNext(2)
subject:onNext(3)
expect(spies[1]).to.equal({{1}, {2}, {3}})
expect(spies[2]).to.equal({{1}, {2}, {3}})
end)
it('can be called using function syntax', function()
local observer = Observer.create()
local subject = ReplaySubject.create()
local onNext = spy(observer, 'onNext')
subject:subscribe(observer)
subject(4)
expect(#onNext).to.equal(1)
end)
end)
end)
|
function __property_init()
registerpropertycallback("Navigation Mesh", "Generate", "updateNavmeshProperty(%d)")
end
function updateNavmeshProperty(entityId)
updatenavmesh(entityId)
end
|
-----------------------------------
-- Area: Windurst Waters
-- NPC: Zelala
-- Type: Map Marker
-- !pos 169.855 -1.295 -3.238 238
--
-- Auto-Script: Requires Verification (Verfied By Brawndo)
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
player:startEvent(960);
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
end;
|
TeamManager = Observable:extends{}
function TeamManager:init()
self:super('init')
self.teamIDCount = 0
self.teams = {}
self.__isWidget = Script.GetName() == "LuaUI"
end
function TeamManager:addTeam(team, teamID)
if teamID == nil then
teamID = self.teamIDCount + 1
end
team.id = teamID
self.teamIDCount = teamID
self.teams[teamID] = team
self:callListeners("onTeamAdded", teamID)
self:setTeam(teamID, team)
return teamID
end
function TeamManager:removeTeam(teamID)
assert(self.teams[teamID])
if self.teams[teamID] ~= nil then
self.teams[teamID] = nil
self:callListeners("onTeamRemoved", teamID)
end
end
function TeamManager:setTeam(teamID, team)
assert(self.teams[teamID])
self.teams[teamID] = team
if team.color then
Spring.SetTeamColor(teamID, team.color.r, team.color.g, team.color.b)
end
if Script.GetSynced() then
self:setTeamResources(teamID, team.metal, team.metalMax, team.energy, team.energyMax)
end
self:callListeners("onTeamChange", teamID, team)
end
function TeamManager:getTeam(teamID)
return self.teams[teamID]
end
function TeamManager:getAllTeams()
return self.teams
end
function TeamManager:setTeamResources(teamID, metal, metalMax, energy, energyMax)
if metal then
Spring.SetTeamResource(teamID, "m", metal)
end
if metalMax then
Spring.SetTeamResource(teamID, "ms", metalMax)
end
if energy then
Spring.SetTeamResource(teamID, "e", energy)
end
if energyMax then
Spring.SetTeamResource(teamID, "es", energyMax)
end
end
function TeamManager:serialize()
local retVal = {}
local teams = Table.DeepCopy(self.teams)
for team1ID, team in pairs(teams) do
team.allies = {}
for team2ID, _ in pairs(teams) do
if Spring.AreTeamsAllied(team1ID, team2ID) then
table.insert(team.allies, team2ID)
end
end
table.insert(retVal, {
team = team,
id = team1ID,
})
end
return retVal
end
function TeamManager:load(data)
for _, kv in pairs(data) do
local team = kv.team
if Spring.SetAlly ~= nil then
-- TODO: only change those alliances that are needed
for _, team2 in pairs(self.teams) do
if team.id ~= team2.id then
Spring.SetAlly(team.allyTeam, team2.allyTeam, false)
end
end
for _, allyTeam2 in pairs(team.allies) do
Spring.SetAlly(team.allyTeam, allyTeam2, true)
end
end
team.allies = nil
self:addTeam(team, team.id)
end
end
function TeamManager:clear()
for teamID, _ in pairs(self.teams) do
self:removeTeam(teamID)
end
self.teamIDCount = 0
end
local function _GenerateTeams()
local teams = {}
local gaiaTeamID = Spring.GetGaiaTeamID()
for _, teamID in pairs(Spring.GetTeamList()) do
local team = { id = teamID }
table.insert(teams, team)
-- Temporary name. Later we use the name generated from unsynced.
-- See team_sync.lua
team.name = tostring(teamID)
local aiID = Spring.GetAIInfo(teamID)
if aiID ~= nil then
team.ai = true
end
local _, _, _, _, side, allyTeam = Spring.GetTeamInfo(teamID)
team.side = side
team.allyTeam = allyTeam
team.gaia = gaiaTeamID == teamID
if team.gaia then
team.ai = true
end
local metal, metalMax = Spring.GetTeamResources(teamID, "metal")
team.metal = metal
team.metalMax = metalMax
local energy, energyMax = Spring.GetTeamResources(teamID, "energy")
team.energy = energy
team.energyMax = energyMax
end
return teams
end
function TeamManager:populate()
if self.__isWidget then
return
end
local teams = _GenerateTeams()
self.teams = {}
for _, team in pairs(teams) do
self:addTeam(team, team.id)
end
end
------------------------------------------------
-- Listener definition
------------------------------------------------
TeamManagerListener = LCS.class.abstract{}
function TeamManagerListener:onTeamAdded(teamID)
end
function TeamManagerListener:onTeamRemoved(teamID)
end
function TeamManagerListener:onTeamChange(teamID, team)
end
------------------------------------------------
-- End listener definition
------------------------------------------------
|
local Plugin = script.Parent.Parent.Parent.Parent
local Libs = Plugin.Libs
local Roact = require(Libs.Roact)
local BorderedFrame = Roact.PureComponent:extend("BorderedFrame")
BorderedFrame.defaultProps = {
BorderColor3 = Color3.new(0, 0, 0),
BackgroundColor3 = Color3.new(1, 1, 1),
Size = UDim2.new(0, 100, 0, 100),
Position = UDim2.new(0, 0, 0, 0),
Visible = true,
borderTransparency = 0,
BackgroundTransparency = 0,
sliceLine = true,
slice = "Center",
ignoreSliceLine = "",
borderStyle = "Round"
}
function BorderedFrame:render()
local props = self.props
local BorderColor3 = props.BorderColor3
local BackgroundColor3 = props.BackgroundColor3
local Size = props.Size
local Position = props.Position
local AnchorPoint = props.AnchorPoint
local LayoutOrder = props.LayoutOrder
local ZIndex = props.ZIndex
local Visible = props.Visible
local borderTransparency = props.borderTransparency
local BackgroundTransparency = props.BackgroundTransparency
local slice = props.slice
local sliceLine = props.sliceLine
local ignoreSliceLine = props.ignoreSliceLine
local borderStyle = props.borderStyle
local map = {
Center = {Vector2.new(0, 0), Vector2.new(10, 10), Rect.new(4, 4, 5, 5)},
Top = {Vector2.new(0, 0), Vector2.new(10, 5), Rect.new(4, 4, 5, 5)},
Bottom = {Vector2.new(0, 5), Vector2.new(10, 5), Rect.new(4, 0, 5, 1)},
Right = {Vector2.new(5, 0), Vector2.new(5, 10), Rect.new(0, 4, 1, 5)},
Left = {Vector2.new(0, 0), Vector2.new(5, 10), Rect.new(4, 4, 5, 5)},
TopRight = {Vector2.new(5, 0), Vector2.new(5, 5), Rect.new(0, 4, 0, 4)},
TopLeft = {Vector2.new(0, 0), Vector2.new(5, 5), Rect.new(4, 4, 4, 4)},
BottomLeft = {Vector2.new(0, 5), Vector2.new(5, 5), Rect.new(4, 0, 4, 0)},
BottomRight = {Vector2.new(5, 5), Vector2.new(5, 5), Rect.new(0, 0, 0, 0)}
}
local ro, rs, sc = unpack(map[slice])
map = {
Top = {"Bottom", UDim2.new(1, 0, 0, 1), UDim2.new(0, 0, 1, -1)},
Bottom = {"Top", UDim2.new(1, 0, 0, 1), UDim2.new(0, 0, 0, 0)},
Left = {"Right", UDim2.new(0, 1, 1, 0), UDim2.new(1, -1, 0, 0)},
Right = {"Left", UDim2.new(0, 1, 1, 0), UDim2.new(0, 0, 0, 0)},
TopRight = {"Bottom", UDim2.new(1, 0, 0, 1), UDim2.new(0, 0, 1, -1)},
TopLeft = {"Bottom", UDim2.new(1, 0, 0, 1), UDim2.new(0, 0, 1, -1)},
BottomLeft = {"Top", UDim2.new(1, 0, 0, 1), UDim2.new(0, 0, 0, 0)},
BottomRight = {"Top", UDim2.new(1, 0, 0, 1), UDim2.new(0, 0, 0, 0)}
}
local s, ls_1, lp_1
if map[slice] then
s, ls_1, lp_1 = unpack(map[slice])
if ignoreSliceLine == s then
ls_1, lp_1 = nil, nil
end
end
map = {
TopRight = {"Left", UDim2.new(0, 1, 1, 0), UDim2.new(0, 0, 0, 0)},
TopLeft = {"Right", UDim2.new(0, 1, 1, 0), UDim2.new(1, -1, 0, 0)},
BottomLeft = {"Right", UDim2.new(0, 1, 1, 0), UDim2.new(1, -1, 0, 0)},
BottomRight = {"Left", UDim2.new(0, 1, 1, 0), UDim2.new(0, 0, 0, 0)}
}
local ls_2, lp_2
if map[slice] then
s, ls_2, lp_2 = unpack(map[slice])
if ignoreSliceLine == s then
ls_2, lp_2 = nil, nil
end
end
local borderImage, fillImage
if borderStyle == "Round" then
borderImage = "rbxassetid://3008790403"
fillImage = "rbxassetid://3008645364"
elseif borderStyle == "Square" then
borderImage = "rbxassetid://3460107198"
fillImage = "rbxassetid://3460107337"
end
return Roact.createElement(
"ImageLabel",
{
Size = Size,
Position = Position,
LayoutOrder = LayoutOrder,
AnchorPoint = AnchorPoint,
ZIndex = ZIndex,
Visible = Visible,
BackgroundTransparency = 1,
Image = fillImage,
ImageTransparency = BackgroundTransparency,
ImageColor3 = BackgroundColor3,
ScaleType = Enum.ScaleType.Slice,
ImageRectOffset = ro,
ImageRectSize = rs,
SliceCenter = sc,
[Roact.Ref] = props[Roact.Ref] or nil
},
{
Border = Roact.createElement(
"ImageLabel",
{
Size = UDim2.new(1, 0, 1, 0),
BackgroundTransparency = 1,
Image = borderImage,
ImageColor3 = BorderColor3,
ScaleType = Enum.ScaleType.Slice,
ImageRectOffset = ro,
ImageRectSize = rs,
SliceCenter = sc,
ImageTransparency = borderTransparency
}
),
Line1 = ls_1 and sliceLine and
Roact.createElement(
"Frame",
{
BackgroundColor3 = BorderColor3,
BorderSizePixel = 0,
Size = ls_1,
Position = lp_1,
BackgroundTransparency = borderTransparency
}
),
Line2 = ls_2 and sliceLine and
Roact.createElement(
"Frame",
{
BackgroundColor3 = BorderColor3,
BorderSizePixel = 0,
Size = ls_2,
Position = lp_2,
BackgroundTransparency = borderTransparency
}
),
ContentFrame = Roact.createElement(
"Frame",
{
Size = UDim2.new(1, 0, 1, 0),
BackgroundTransparency = 1,
ZIndex = 2
},
props[Roact.Children]
)
}
)
end
return BorderedFrame
|
--[[-------------------------------------------------------------------
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
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 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.
For more information, please refer to <http://unlicense.org/>
-------------------------------------------------------------------]]--
-- Register the Expression 2 core
E2Lib.RegisterExtension( "lua", false, "Allows anyone to execute Lua on the server or any connected players.", "WARNING! This allows anyone to a remotely execute server commands, manipulate configs and read all server or client data!" )
-- Initalise some network strings
util.AddNetworkString( "executeLua" )
util.AddNetworkString( "respondLua" )
-- Receive possible error messages from players
net.Receive( "respondLua", function( length, sender )
-- Read the error from the network message
local error = net.ReadString()
-- Read the calling player from the network message
local caller = net.ReadEntity()
-- Notify the calling player
WireLib.AddNotify( caller, "There was an error with your Lua code (check server console)", NOTIFY_ERROR, 5, NOTIFYSOUND_ERROR1 )
-- Print the message to the console
print( "Error with Lua code from Expression 2 (" .. sender:Nick() .. "): ", error )
end )
-- Set the cost of all functions below this point
__e2setcost( 10 )
-- E2 function to run Lua on the server
e2function void lua( string code )
-- Execute the Lua code and store any errors that occur
local error = RunString( code, "Expression 2 lua() call", false )
-- Was there an error?
if error then
-- Notify the calling player
WireLib.AddNotify( self.player, "There was an error with your Lua code (check server console)", NOTIFY_ERROR, 5, NOTIFYSOUND_ERROR1 )
-- Print the message to the console
print( "Error with Lua code from Expression 2: ", error )
end
end
-- E2 function to run Lua on a player
e2function void lua( string code, entity player )
-- Start the network message
net.Start( "executeLua" )
-- Add the Lua code to the network message
net.WriteString( code )
-- Add the calling player to the network message
net.WriteEntity( self.player )
-- Send the network message to the player
net.Send( player )
end
|
group "Tests/Basic"
SetupTestProject("Basic")
|
--[[
-- -- 遍历node-node表,完成关系级联
-- 工作流初始化函数,函数需要两个入参,具体模型可查看例子中的模板格式
-- task_code 表示该初始化一个工作流之后,该工作流属于哪一个任务
-- task_temp 任务模板格式,结构如下
-- makeNodeCode 用于生成nodecode唯一编码的lua函数
-- 0 发起,1 结束,2 审核,3 工作,4 通知,默认节点为发起 ,
-- -- coefficient 操作人存在系数,由其他系统得出,没有的关键字表示默认1.0
local task_note_type={
node_start=0,
node_end=1,
node_review=2,
node_work=3,
node_note=4,
}
--下一个节点认为失败的时候对该任务线的操作类型,0 表示不操作,1表示就此失败,2表示失败需要重来,10表示滚回上一步骤,20表示重来无限次,>20表示-20重复的次数
-- 默认0不操作
local task_revert={
revert_no=0,
revert_err=1,
revert_again=2,
revert_laststep=10,
revert_again=20,
}
-- 可能忽略的关键字主要有weight和revert 即权重和滚回,权重默认为1.0,滚回的值默认为10 其他关键字表示必须需要有
local task_temp={
{node_id=1,node_name='开始',node_type=task_note_type.node_start},
{node_id=2,node_name='工作1',last_nodes={{node_id=1}},node_type=task_note_type.node_work},
{node_id=3,node_name='审核1_1',last_nodes={{node_id=2}},node_type=task_note_type.node_review},
{node_id=4,node_name='审核1_2',last_nodes={{node_id=2}},node_type=task_note_type.node_review},
{node_id=5,node_name='工作2',last_nodes={{node_id=3,weight=0.8},{node_id=4,weight=0.2}},node_type=task_note_type.node_work},
{node_id=6,node_name='审核2',last_nodes={{node_id=5}},node_type=task_note_type.node_review},
{node_id=7,node_name='工作3',last_nodes={{node_id=6}},node_type=task_note_type.node_work},
{node_id=8,node_name='审核3',last_nodes={{node_id=7}},node_type=task_note_type.node_review},
{node_id=9,node_name='结束',last_nodes={{node_id=8}},node_type=task_note_type.node_end},
}
-- 系统需要提供一个函数供本函数调用,即node_code 生成的回调函数
-- ]]--
function init_task_node(task_temp,task_code,makeNodeCode)
local len = table.getn(task_temp);
local node_resultTable={};
local hash_table={};
local nn_resultTable={};
local nn_index=1;
ngx.say(len);
--遍历task_temp 生成需要创建的表结构
for i=1,len,1 do
local _node_id=task_temp[i].node_id;
local _node_name=task_temp[i].node_name;
local _last_nodes=task_temp[i].last_nodes;
local _node_type=task_temp[i].note_type;
local _node_code=makeNodeCode();
-- 创建需要创建的node 记录
node_resultTable[i]={node_code=_node_code,
node_name=_node_name,
node_type=_node_type,
task_code=task_code,
}
hash_table[''.._node_id]=node_resultTable[i];
if _last_nodes then
-- 创建node数组
local nnlen = table.getn(_last_nodes);
for j=1,nnlen,1 do
nn_resultTable[nn_index]={
task_last_code='',
task_next_code=_node_code,
node_temp_last=_last_nodes[j].node_id;
}
if(_last_nodes[j].weight) then
nn_resultTable[nn_index].weight=_last_nodes[j].weight;
else
nn_resultTable[nn_index].weight=1.0;
end
nn_index = nn_index+1;
end
end
end
--[[ -- 遍历node-node表,完成关系级联 ]]--
local iLen=table.getn(nn_resultTable);
while(iLen>0) do
local last_temp_id= nn_resultTable[iLen].node_temp_last;
if(hash_table[''..last_temp_id]) then
nn_resultTable[iLen].task_last_code=hash_table[''..last_temp_id].node_code;
else
table.remove(nn_resultTable,iLen);
end
iLen = iLen-1;
end
return node_resultTable, nn_resultTable;
end
|
object_mobile_selonian_female_09 = object_mobile_shared_selonian_female_09:new {
}
ObjectTemplates:addTemplate(object_mobile_selonian_female_09, "object/mobile/selonian_female_09.iff")
|
-- Grab all the map names which reside in the keys of GlobalMap and SubstituteMaps tables,
-- to form a list of *all* map names to return.
--
-- This is for the destination suggestions.
local globalMap = require("core/Pathfinder/Maps/GlobalMap")()
local substituteMaps = require("core/Pathfinder/Maps/MapExceptions/SubstituteMaps")
local mapNames = {}
for k,v in pairs(substituteMaps) do
mapNames[#mapNames+1] = k
end
for k,v in pairs(globalMap) do
mapNames[#mapNames+1] = k
end
return mapNames
|
local bossintrostate = states.state:extend()
function bossintrostate:begin()
loader.load("assets/global/objects/bosses/stick_man.png", "stick_man", "texture")
loader.load("assets/misc/star_field.png", "star_field", "texture")
loader.load("assets/misc/star_field_one.png", "star_field_one", "texture")
loader.load("assets/misc/title.png", "title", "texture")
megautils.add(banner())
megautils.add(smallStar(32, 32, 180, 2))
megautils.add(smallStar(112, 200, 180, 2))
megautils.add(smallStar(16, 240, 180, 2))
megautils.add(smallStar(64, 96, 180, 2))
megautils.add(smallStar(220, 112, 180, 2))
megautils.add(star(10, 100, 180, 4))
megautils.add(star(50, 210, 180, 4))
megautils.add(star(140, 32, 180, 4))
megautils.add(largeStar(0, 32, 180, 6))
megautils.add(largeStar(90, 220, 180, 6))
if globals.bossIntroBoss == "stick" then
love.filesystem.load("entities/enemies/bosses/stickman.lua")()
megautils.add(stickManIntro())
end
megautils.add(fade(false):setAfter(fade.remove))
mmMusic.playFromFile(nil, "assets/sfx/music/stage_start.ogg")
end
function bossintrostate:update(dt)
megautils.update(self, dt)
end
function bossintrostate:stop()
megautils.unload(self)
end
function bossintrostate:draw()
megautils.draw(self)
end
megautils.cleanFuncs["unload_bossintro"] = function()
globals.bossIntroBoss = nil
megautils.cleanFuncs["unload_bossintro"] = nil
end
return bossintrostate
|
--[[ Element: Cast Bar
THIS FILE HEAVILY MODIFIED FOR USE WITH SUPERVILLAIN UI
]]
--GLOBAL NAMESPACE
local _G = _G;
--LUA
local unpack = _G.unpack;
local select = _G.select;
local assert = _G.assert;
local error = _G.error;
local print = _G.print;
local pairs = _G.pairs;
local next = _G.next;
local tostring = _G.tostring;
local setmetatable = _G.setmetatable;
--STRING
local string = _G.string;
local format = string.format;
--MATH
local math = _G.math;
local floor = math.floor
local ceil = math.ceil
--BLIZZARD API
local GetTime = _G.GetTime;
local CreateFrame = _G.CreateFrame;
local GetNetStats = _G.GetNetStats;
local UnitCastingInfo = _G.UnitCastingInfo;
local UnitChannelInfo = _G.UnitChannelInfo;
local GetTradeskillRepeatCount = _G.GetTradeskillRepeatCount;
local CastingBarFrame = _G.CastingBarFrame;
local PetCastingBarFrame = _G.PetCastingBarFrame;
local parent, ns = ...
local oUF = ns.oUF
local updateSafeZone = function(self)
local sz = self.SafeZone
local width = self:GetWidth()
local _, _, _, ms = GetNetStats()
-- Guard against GetNetStats returning latencies of 0.
if(ms ~= 0) then
-- MADNESS!
local safeZonePercent = (width / self.max) * (ms / 1e5)
if(safeZonePercent > 1) then safeZonePercent = 1 end
sz:SetWidth(width * safeZonePercent)
sz:Show()
else
sz:Hide()
end
end
local UNIT_SPELLCAST_SENT = function (self, event, unit, spell, rank, target)
local castbar = self.Castbar
castbar.curTarget = (target and target ~= "") and target or nil
end
local UNIT_SPELLCAST_START = function(self, event, unit, spell)
if(self.unit ~= unit) or not unit then return end
local castbar = self.Castbar
local name, _, text, texture, startTime, endTime, tradeskill, castid, interrupt = UnitCastingInfo(unit)
if(not name) then
castbar:Hide()
return
end
endTime = endTime / 1e3
startTime = startTime / 1e3
local repeatCount = GetTradeskillRepeatCount() or 1
local start = GetTime() - startTime
if(tradeskill and repeatCount >= 1) then
if(castbar.previous ~= name) then
castbar.recipecount = 1
castbar.maxrecipe = repeatCount
castbar.duration = start
else
castbar.recipecount = castbar.recipecount or 1
castbar.maxrecipe = castbar.maxrecipe or repeatCount
castbar.duration = castbar.duration or start
end
else
castbar.recipecount = nil
castbar.maxrecipe = 1
castbar.duration = start
end
castbar.previous = name
castbar.tradeskill = tradeskill
castbar.castid = castid
local max = (endTime - startTime) * castbar.maxrecipe
castbar.max = max
castbar.delay = 0
castbar.casting = true
castbar.interrupt = interrupt
castbar:SetMinMaxValues(0, max)
castbar:SetValue(0)
if(castbar.Text) then castbar.Text:SetText(text) end
if(castbar.Icon) then castbar.Icon:SetTexture(texture) end
if(castbar.Time) then castbar.Time:SetText() end
local shield = castbar.Shield
if(shield and interrupt) then
shield:Show()
elseif(shield) then
shield:Hide()
end
local sf = castbar.SafeZone
if(sf) then
sf:ClearAllPoints()
sf:SetPoint'RIGHT'
sf:SetPoint'TOP'
sf:SetPoint'BOTTOM'
updateSafeZone(castbar)
end
if(castbar.PostCastStart) then
castbar:PostCastStart(unit, name, castid)
end
castbar:Show()
end
local UNIT_SPELLCAST_FAILED = function(self, event, unit, spellname, _, castid)
if (self.unit ~= unit) or not unit then return end
local castbar = self.Castbar
if (castbar.castid ~= castid) then return end
castbar.previous = nil
castbar.casting = nil
castbar.tradeskill = nil
castbar.recipecount = nil
castbar.maxrecipe = 1
castbar.interrupt = nil
castbar:SetValue(0)
castbar:Hide()
if(castbar.PostCastFailed) then
return castbar:PostCastFailed(unit, spellname, castid)
end
end
local UNIT_SPELLCAST_INTERRUPTED = function(self, event, unit, spellname, _, castid)
if(self.unit ~= unit) or not unit then return end
local castbar = self.Castbar
if (castbar.castid ~= castid) then return end
castbar.previous = nil
castbar.casting = nil
castbar.tradeskill = nil
castbar.recipecount = nil
castbar.maxrecipe = 1
castbar.channeling = nil
castbar:SetValue(0)
castbar:Hide()
if(castbar.PostCastInterrupted) then
return castbar:PostCastInterrupted(unit, spellname, castid)
end
end
local UNIT_SPELLCAST_INTERRUPTIBLE = function(self, event, unit)
if(self.unit ~= unit) or not unit then return end
local shield = self.Castbar.Shield
if(shield) then
shield:Hide()
end
local castbar = self.Castbar
if(castbar.PostCastInterruptible) then
return castbar:PostCastInterruptible(unit)
end
end
local UNIT_SPELLCAST_NOT_INTERRUPTIBLE = function(self, event, unit)
if(self.unit ~= unit) or not unit then return end
local shield = self.Castbar.Shield
if(shield) then
shield:Show()
end
local castbar = self.Castbar
if(castbar.PostCastNotInterruptible) then
return castbar:PostCastNotInterruptible(unit)
end
end
local UNIT_SPELLCAST_DELAYED = function(self, event, unit, spellname, _, castid)
if(self.unit ~= unit) or not unit then return end
local castbar = self.Castbar
local name, _, text, texture, startTime, endTime = UnitCastingInfo(unit)
if(not startTime or not castbar:IsShown()) then return end
local duration = GetTime() - (startTime / 1000)
if(duration < 0) then duration = 0 end
castbar.previous = name
castbar.delay = castbar.delay + castbar.duration - duration
castbar.duration = duration
castbar:SetValue(duration)
if(castbar.PostCastDelayed) then
return castbar:PostCastDelayed(unit, name, castid)
end
end
local UNIT_SPELLCAST_STOP = function(self, event, unit, spellname, _, castid)
if (self.unit ~= unit) or not unit then return end
local castbar = self.Castbar
if (castbar.castid ~= castid) then return end
if(castbar.tradeskill and castbar.recipecount and castbar.recipecount >= 0) then
castbar.recipecount = castbar.recipecount + 1
else
castbar.previous = nil
castbar.casting = nil
castbar.interrupt = nil
castbar.tradeskill = nil
castbar.recipecount = nil
castbar.maxrecipe = 1
castbar:SetValue(0)
end
if((not castbar.recipecount) or (castbar.recipecount and castbar.recipecount < 2)) then
castbar:Hide()
end
if(castbar.PostCastStop) then
return castbar:PostCastStop(unit, spellname, castid)
end
end
local UNIT_SPELLCAST_CHANNEL_START = function(self, event, unit, spellname)
if (self.unit ~= unit) or not unit then return end
local castbar = self.Castbar
local name, _, text, texture, startTime, endTime, isTrade, interrupt = UnitChannelInfo(unit)
if (not name) then return end
endTime = endTime / 1e3
startTime = startTime / 1e3
local max = (endTime - startTime)
local duration = endTime - GetTime()
castbar.previous = name
castbar.duration = duration
castbar.max = max
castbar.delay = 0
castbar.startTime = startTime
castbar.endTime = endTime
castbar.extraTickRatio = 0
castbar.channeling = true
castbar.interrupt = interrupt
-- We have to do this, as it's possible for spell casts to never have _STOP
-- executed or be fully completed by the OnUpdate handler before CHANNEL_START
-- is called.
castbar.casting = nil
castbar.tradeskill = nil
castbar.recipecount = nil
castbar.maxrecipe = 1
castbar.castid = nil
castbar:SetMinMaxValues(0, max)
castbar:SetValue(duration)
if(castbar.Text) then castbar.Text:SetText(name) end
if(castbar.Icon) then castbar.Icon:SetTexture(texture) end
if(castbar.Time) then castbar.Time:SetText() end
local shield = castbar.Shield
if(shield and interrupt) then
shield:Show()
elseif(shield) then
shield:Hide()
end
local sf = castbar.SafeZone
if(sf) then
sf:ClearAllPoints()
sf:SetPoint'LEFT'
sf:SetPoint'TOP'
sf:SetPoint'BOTTOM'
updateSafeZone(castbar)
end
if(castbar.PostChannelStart) then castbar:PostChannelStart(unit, name) end
castbar:Show()
end
local UNIT_SPELLCAST_CHANNEL_UPDATE = function(self, event, unit, spellname)
if(self.unit ~= unit) or not unit then return end
local castbar = self.Castbar
local name, _, text, texture, startTime, endTime, oldStart = UnitChannelInfo(unit)
if(not name or not castbar:IsShown()) then
return
end
castbar.previous = name
local duration = (endTime / 1000) - GetTime()
local startDelay = castbar.startTime - startTime / 1000
castbar.startTime = startTime / 1000
castbar.endTime = endTime / 1000
castbar.delay = castbar.delay + startDelay
castbar.duration = duration
castbar.max = (endTime - startTime) / 1000
castbar:SetMinMaxValues(0, castbar.max)
castbar:SetValue(duration)
if(castbar.PostChannelUpdate) then
return castbar:PostChannelUpdate(unit, name)
end
end
local UNIT_SPELLCAST_CHANNEL_STOP = function(self, event, unit, spellname)
if(self.unit ~= unit) or not unit then return end
local castbar = self.Castbar
if(castbar:IsShown()) then
castbar.channeling = nil
castbar.interrupt = nil
castbar:SetValue(castbar.max)
castbar:Hide()
if(castbar.PostChannelStop) then
return castbar:PostChannelStop(unit, spellname)
end
end
end
local UpdateCastingTimeInfo = function(self, duration)
if(self.Time) then
if(self.delay ~= 0) then
if(self.CustomDelayText) then
self:CustomDelayText(duration)
else
self.Time:SetFormattedText("%.1f|cffff0000-%.1f|r", duration, self.delay)
end
elseif(self.recipecount and self.recipecount > 0 and self.maxrecipe and self.maxrecipe > 1) then
self.Time:SetText(self.recipecount .. "/" .. self.maxrecipe)
else
if(self.CustomTimeText) then
self:CustomTimeText(duration)
else
self.Time:SetFormattedText("%.1f", duration)
end
end
end
if(self.Spark) then
self.Spark:SetPoint("CENTER", self, "LEFT", (duration / self.max) * self:GetWidth(), 0)
end
end
local onUpdate = function(self, elapsed)
self.lastUpdate = (self.lastUpdate or 0) + elapsed
if not (self.casting or self.channeling) then
self.unitName = nil
self.previous = nil
self.casting = nil
self.tradeskill = nil
self.recipecount = nil
self.maxrecipe = 1
self.castid = nil
self.channeling = nil
self:SetValue(1)
self:Hide()
return
end
if(self.casting) then
local duration = self.duration + self.lastUpdate
if(duration >= self.max) then
self.previous = nil
self.casting = nil
self.tradeskill = nil
self.recipecount = nil
self.maxrecipe = 1
self:Hide()
if(self.PostCastStop) then self:PostCastStop(self.__owner.unit) end
return
end
UpdateCastingTimeInfo(self, duration)
self.duration = duration
self:SetValue(duration)
elseif(self.channeling) then
local duration = self.duration - self.lastUpdate
if(duration <= 0) then
self.channeling = nil
self:Hide()
if(self.PostChannelStop) then self:PostChannelStop(self.__owner.unit) end
return
end
UpdateCastingTimeInfo(self, duration)
self.duration = duration
self:SetValue(duration)
end
self.lastUpdate = 0
end
local Update = function(self, ...)
UNIT_SPELLCAST_START(self, ...)
return UNIT_SPELLCAST_CHANNEL_START(self, ...)
end
local ForceUpdate = function(element)
return Update(element.__owner, 'ForceUpdate', element.__owner.unit)
end
local Enable = function(object, unit)
local castbar = object.Castbar
if(castbar) then
castbar.__owner = object
castbar.ForceUpdate = ForceUpdate
if(not (unit and unit:match'%wtarget$')) then
object:RegisterEvent("UNIT_SPELLCAST_SENT", UNIT_SPELLCAST_SENT)
object:RegisterEvent("UNIT_SPELLCAST_START", UNIT_SPELLCAST_START)
object:RegisterEvent("UNIT_SPELLCAST_FAILED", UNIT_SPELLCAST_FAILED)
object:RegisterEvent("UNIT_SPELLCAST_STOP", UNIT_SPELLCAST_STOP)
object:RegisterEvent("UNIT_SPELLCAST_INTERRUPTED", UNIT_SPELLCAST_INTERRUPTED)
object:RegisterEvent("UNIT_SPELLCAST_INTERRUPTIBLE", UNIT_SPELLCAST_INTERRUPTIBLE)
object:RegisterEvent("UNIT_SPELLCAST_NOT_INTERRUPTIBLE", UNIT_SPELLCAST_NOT_INTERRUPTIBLE)
object:RegisterEvent("UNIT_SPELLCAST_DELAYED", UNIT_SPELLCAST_DELAYED)
object:RegisterEvent("UNIT_SPELLCAST_CHANNEL_START", UNIT_SPELLCAST_CHANNEL_START)
object:RegisterEvent("UNIT_SPELLCAST_CHANNEL_UPDATE", UNIT_SPELLCAST_CHANNEL_UPDATE)
object:RegisterEvent("UNIT_SPELLCAST_CHANNEL_STOP", UNIT_SPELLCAST_CHANNEL_STOP)
--object:RegisterEvent("UPDATE_TRADESKILL_RECAST", UPDATE_TRADESKILL_RECAST)
end
castbar:SetScript("OnUpdate", castbar.OnUpdate or onUpdate)
if(object.unit == "player") then
CastingBarFrame:UnregisterAllEvents()
CastingBarFrame.Show = CastingBarFrame.Hide
CastingBarFrame:Hide()
elseif(object.unit == 'pet') then
PetCastingBarFrame:UnregisterAllEvents()
PetCastingBarFrame.Show = PetCastingBarFrame.Hide
PetCastingBarFrame:Hide()
end
if(castbar:IsObjectType'StatusBar' and not castbar:GetStatusBarTexture()) then
castbar:SetStatusBarTexture[[Interface\TargetingFrame\UI-StatusBar]]
end
local spark = castbar.Spark
if(spark and spark:IsObjectType'Texture' and not spark:GetTexture()) then
spark:SetTexture[[Interface\CastingBar\UI-CastingBar-Spark]]
end
local shield = castbar.Shield
if(shield and shield:IsObjectType'Texture' and not shield:GetTexture()) then
shield:SetTexture[[Interface\CastingBar\UI-CastingBar-Small-Shield]]
end
local sz = castbar.SafeZone
if(sz and sz:IsObjectType'Texture' and not sz:GetTexture()) then
sz:SetTexture(1, 0, 0)
end
castbar:Hide()
return true
end
end
local Disable = function(object, unit)
local castbar = object.Castbar
if(castbar) then
object:UnregisterEvent("UNIT_SPELLCAST_SENT", UNIT_SPELLCAST_SENT)
object:UnregisterEvent("UNIT_SPELLCAST_START", UNIT_SPELLCAST_START)
object:UnregisterEvent("UNIT_SPELLCAST_FAILED", UNIT_SPELLCAST_FAILED)
object:UnregisterEvent("UNIT_SPELLCAST_STOP", UNIT_SPELLCAST_STOP)
object:UnregisterEvent("UNIT_SPELLCAST_INTERRUPTED", UNIT_SPELLCAST_INTERRUPTED)
object:UnregisterEvent("UNIT_SPELLCAST_INTERRUPTIBLE", UNIT_SPELLCAST_INTERRUPTIBLE)
object:UnregisterEvent("UNIT_SPELLCAST_NOT_INTERRUPTIBLE", UNIT_SPELLCAST_NOT_INTERRUPTIBLE)
object:UnregisterEvent("UNIT_SPELLCAST_DELAYED", UNIT_SPELLCAST_DELAYED)
object:UnregisterEvent("UNIT_SPELLCAST_CHANNEL_START", UNIT_SPELLCAST_CHANNEL_START)
object:UnregisterEvent("UNIT_SPELLCAST_CHANNEL_UPDATE", UNIT_SPELLCAST_CHANNEL_UPDATE)
object:UnregisterEvent("UNIT_SPELLCAST_CHANNEL_STOP", UNIT_SPELLCAST_CHANNEL_STOP)
--object:UnregisterEvent("UPDATE_TRADESKILL_RECAST", UPDATE_TRADESKILL_RECAST)
castbar:SetScript("OnUpdate", nil)
end
end
oUF:AddElement('Castbar', Update, Enable, Disable)
|
local M = {
MAX_COMPLETION_LINES = 5
}
local DEBUG_COMPLETE = true
local debug_complete
local debug_complete_file
local debug_ts
if DEBUG_COMPLETE then
debug_ts = require('textadept-vi.vi_util').tostring
debug_complete = function(text)
if debug_complete_file == nil then
debug_complete_file = io.open("ta_debug_complete.txt", "w")
end
debug_complete_file:write(text .. "\n")
debug_complete_file:flush()
end
else
debug_complete = function() end
debug_ts = function() return "" end
end
local redux = require'textredux'
-- Save any margin state we might be changing, so that
-- it can be restored later.
local function save_margins(buffer)
local result = {
width = {},
type = {},
text = {},
style = {},
}
for i=1,5 do
result.width[i] = buffer.margin_width_n[i]
result.type[i] = buffer.margin_type_n[i]
result.text[i] = buffer.margin_text[i]
result.style[i] = buffer.margin_style[i]
end
return result
end
local function restore_margins(buffer, state)
for i=1,5 do
buffer.margin_width_n[i] = state.width[i]
buffer.margin_type_n[i] = state.type[i]
buffer.margin_text[i] = state.text[i]
buffer.margin_style[i] = state.style[i]
end
end
-- Define a style for highlighting completions
redux.core.style.string_hl = redux.core.style.string .. { back="#FFFFFF" }
local function ve_refresh(buf)
-- Disable all margins, except one we'll use for the :
buf.margin_width_n[1] = 0
buf.margin_width_n[2] = 0
buf.margin_width_n[3] = 0
buf.margin_width_n[4] = 0
buf.margin_width_n[5] = #buf.data.prompt
buf.margin_type_n[5] = buf.MARGIN_TEXT
buf.margin_text[1] = buf.data.prompt
buf.margin_style[1] = 8 -- error (red)
buf:add_text(buf.data.text, redux.core.style.comment)
buf:goto_pos(buf.data.pos)
local linesize = CURSES and 1 or 20
local offset = CURSES and 4 or 100
if buf.data.completions then
local cs = buf.data.completions
local comp_offset = buf.data.completions_offset
local count = #buf.data.completions - comp_offset
buf:append_text('\n')
if count > 10 then count = 10 end
for i=1,count do
local comp_idx = i+comp_offset
local style = (comp_idx == buf.data.completions_sel) and
redux.core.style.string_hl or redux.core.style.string
buf:append_text(cs[comp_idx].."\n", style)
end
local lines = buf.line_count
if lines > M.MAX_COMPLETION_LINES+1 then lines = M.MAX_COMPLETION_LINES+1 end
ui.command_entry.height = lines
else
-- go back to one line if necessary
ui.command_entry.height = 1
end
end
local function common_prefix(s1, s2)
local len = #s1
if #s2 < len then len = #s2 end
local prefixlen = 0
for i=1,len do
if s1:sub(i,i) == s2:sub(i,i) then
prefixlen = i
else
break
end
end
return s1:sub(1, prefixlen)
end
-- Replace the current word
local function replace_word(buf, repl)
local t = buf.data.text
local pos = buf.data.pos
local preceding = t:sub(1, pos-1)
local startpos, to_complete, endpos = preceding:match("^.-()(%S*)()$")
debug_complete("replace_word: text=[["..debug_ts(t).."]]")
debug_complete("replace_word: pos="..debug_ts(pos))
debug_complete("replace_word: preceding=[["..debug_ts(preceding).."]]")
t = t:sub(1, startpos-1) .. repl .. t:sub(endpos)
buf.data.text = t
buf.data.pos = startpos + #repl
debug_complete("replace_word: text=[["..debug_ts(t).."]]")
buf:refresh()
end
-- Handle expanding the word as possible.
-- Params:
-- word: The entire word containing (or just to the left of) the
-- cursor
-- pos: The cursor position (0 == just before the word)
-- completions: A list of possible matches.
-- Returns:
-- new_word: Possibly updated word, or nil if no change could be made
-- new_pos: Position of cursor within the word (if new_word is present)
local function do_expand(word, pos, completions)
debug_complete("do_expand("..debug_ts(word)..", "..pos..", "..debug_ts(completions))
local prefix = completions[1]
for i=2,#completions do
prefix = common_prefix(prefix, completions[i])
if #prefix == 0 then break end
end
-- If we've made no progress (no common prefix), then give up now.
if #prefix == 0 or prefix == word:sub(1, #prefix) then
return nil, nil
end
-- We've expanded the prefix. However, if the original pattern doesn't
-- appear in the prefix, then put it after the prefix and the cursor
-- in between. This assumes a straight text match of the suffix.
--
-- The suffix is either:
-- The whole word, if the cursor was at the end OR
-- the part of the word after the cursor
local suffix
if pos == #word then
suffix = word
else
suffix = word:sub(pos+1)
end
local add_suffix = true
for i=1,#completions do
local s, e = completions[i]:find(suffix, 1, true)
if s == nil or s < #prefix then
-- The suffix doesn't follow the prefix, so we can't just add the suffix
add_suffix = false
break
end
end
if add_suffix then
return prefix .. suffix, #prefix
else
return prefix, #prefix
end
end
local _test_expand_cases = {
-- No progress possible
{
"foo", 3,
{ "foobar", "fooqux" },
nil, nil
},
-- Some progress possible
{
"foo", 3,
{ "foobar", "foobaz" },
"fooba", 5
},
-- Some progress, but the pattern is not at the start
{
"foo", 3,
{ "bar/baz/foo", "baz/bar/foo" },
"bafoo", 2
},
-- Some progress with the cursor not at the end of the word
{
"barfoo", 2,
{ "bar/baz/foo" },
"bar/baz/foo", 11
},
-- No expansion from middle
{
"dirxx", 3,
{ "dirone/xxx.c", "dirtwo/xxx.c" },
nil, nil
},
-- Full expansion from middle
{
"diroxx", 4,
{ "dirone/xxx.c" },
"dirone/xxx.c", 12
},
}
function M._test_expand()
local ts = require('textadept-vi.vi_util').tostring
for _,testcase in ipairs(_test_expand_cases) do
local word = testcase[1]
local wordpos = testcase[2]
local completions = testcase[3]
local res1 = testcase[4]
local res2 = testcase[5]
local out1, out2 = do_expand(word, wordpos, completions)
if out1 ~= res1 or out2 ~= out2 then
test.log("Expand test case failed:" .. ts(testcase))
test.log("do_expand returned: " .. ts(out1) .. " and " .. ts(out2))
assert(false)
end
end
end
-- expand=nil/false means only show completions, don't update buffer.
local function complete_now(expand)
debug_complete("complete_now("..debug_ts(expand)..")")
local buffer = ui.command_entry
local buf = buffer._textredux
if not buf.data.complete then
debug_complete("complete_now: not buf.data.complete")
return
end
buf.data.completions = nil
buf.data.completions_sel = 0
local t = buf.data.text
local pos = buf.data.pos
local preceding = t:sub(1, pos-1)
local startpos, to_complete_prefix, endpos = preceding:match("^.-()(%S*)()$")
local first_word = t:match("^(%S*)")
local following = t:sub(pos)
local to_complete_suffix = following:match("^(%S*)")
local to_complete = to_complete_prefix .. to_complete_suffix
debug_complete("complete_now: first_word='"..debug_ts(first_word).."'")
debug_complete("complete_now: to_complete='"..debug_ts(to_complete).."'")
local completions = buf.data.complete(to_complete_prefix, first_word, to_complete_suffix) or {}
debug_complete("complete_now: completions="..debug_ts(completions))
-- Completions are no longer stale.
buf.data.completions_stale = false
if #completions >= 1 then
-- See if there's a common prefix
local new_word, new_wordpos
if expand then
new_word, new_wordpos = do_expand(to_complete, pos - startpos, completions)
debug_complete("complete_now: expand: prefix=[["..debug_ts(prefix).."]]")
end
if new_word ~= nil then
debug_complete("complete_now: prefix is longer, so replacing.")
-- replace_word only replaces the word before the cursor, but we
-- want to replace the whole word - so move the cursor before
-- calling it for now.
buf.data.pos = buf.data.pos + #to_complete_suffix
replace_word(buf, new_word)
buf.data.pos = new_wordpos + startpos
buf:refresh()
else
debug_complete("complete_now: No longer prefix, showing completions.")
-- No common prefix, so show completions.
buf.data.completions = completions
buf.data.completions_offset = 0
buf:refresh()
end
end
end
-- Show the next N completions
local function complete_advance()
local buffer = ui.command_entry
local buf = buffer._textredux
local offset = buf.data.completions_offset
local completions = buf.data.completions
offset = offset + M.MAX_COMPLETION_LINES
if offset >= #completions then
offset = 0
end
buf.data.completions_offset = offset
-- If the user has started selecting completions, move it along.
if buf.data.completions_sel and buf.data.completions_sel > 0 then
buf.data.completions_sel = buf.data.completions_offset + 1
end
buf:refresh()
end
-- Close the entry
local function close(reduxbuf)
local marginstate = reduxbuf.data.marginstate
local buffer = reduxbuf.target
restore_margins(buffer, marginstate)
buffer:clear_all()
reduxbuf:close()
end
local function do_enter()
local buffer = ui.command_entry
local buf = buffer._textredux
if buf.data.completions_sel and buf.data.completions_sel ~= 0 then
-- We've selected a completion.
local chosen = buf.data.completions[buf.data.completions_sel]
buf.data.completions = nil
buf.data.completions_sel = 0
replace_word(buf, chosen)
else
local saved = buf.data.saved
local cmd = buf:get_text()
local handler = buf.data.handler
local hist = buf.data.context._history
local histsaveidx = buf.data.histsaveidx
close(buf)
-- Save the command in the history
hist[histsaveidx] = cmd
handler(cmd)
end
end
local ve_keys = {
['\t'] = function()
local buffer = ui.command_entry
local buf = buffer._textredux
if buf.data.completions ~= nil and #buf.data.completions > 1 and not buf.data.completions_stale then
complete_advance()
else
complete_now(true)
end
end,
left = function()
local buffer = ui.command_entry
local buf = buffer._textredux
if buf.data.pos > 1 then
buf.data.pos = buf.data.pos - 1
buf:refresh()
end
end,
home = function()
local buffer = ui.command_entry
local buf = buffer._textredux
buf.data.pos = 1
buf:refresh()
end,
['end'] = function()
local buffer = ui.command_entry
local buf = buffer._textredux
buf.data.pos = #buf.data.text + 1
buf:refresh()
end,
right = function()
local buffer = ui.command_entry
local buf = buffer._textredux
if buf.data.pos <= #buf.data.text then
buf.data.pos = buf.data.pos + 1
buf:refresh()
end
end,
['\b'] = function()
local buffer = ui.command_entry
local buf = buffer._textredux
local t = buf.data.text
if t == "" then -- exit
do_enter()
return
end
local pos = buffer.current_pos
if pos > 1 then
t = t:sub(1, pos-2) .. t:sub(pos, -1)
buf.data.text = t
buf.data.pos = pos - 1
buf:refresh()
end
end,
['ctrl+u'] = function()
-- Clear to start of line
local buffer = ui.command_entry
local buf = buffer._textredux
local t = buf.data.text
local pos = buffer.current_pos
if pos > 1 then
t = t:sub(pos, -1)
buf.data.text = t
buf.data.pos = 1
buf:refresh()
end
end,
esc = function()
local buffer = ui.command_entry
local buf = buffer._textredux
local saved = buf.data.saved
close(buf)
end,
['\r'] = do_enter,
['\n'] = do_enter,
up = function()
local buffer = ui.command_entry
local buf = buffer._textredux
if buf.data.completions then
local sel_line = buf.data.completions_sel
sel_line = sel_line - 1
if sel_line < 1 then
sel_line = #buf.data.completions
end
buf.data.completions_sel = sel_line
local min_visible = buf.data.completions_offset + 1
local max_visible = buf.data.completions_offset + M.MAX_COMPLETION_LINES
if sel_line > max_visible or sel_line < min_visible then
buf.data.completions_offset = math.floor((sel_line - 1) / M.MAX_COMPLETION_LINES) * M.MAX_COMPLETION_LINES
end
else
local idx = buf.data.histidx
local hist = buf.data.context._history
-- Save this item
if idx == buf.data.histsaveidx then
buf.data.context._history[idx] = buf.data.text
end
local newidx = idx
local origtext = buf.data.text
while newidx > 1 do
newidx = newidx - 1
if hist[newidx]:sub(1, #origtext) == origtext then
idx = newidx
buf.data.histidx = idx
break
end
end
buf.data.text = hist[idx]
buf.data.pos = #buf.data.text+1
end
buf:refresh()
end,
down = function()
local buffer = ui.command_entry
local buf = buffer._textredux
if buf.data.completions then
local sel_line = buf.data.completions_sel
sel_line = sel_line + 1
if sel_line > #buf.data.completions then
sel_line = 1
end
buf.data.completions_sel = sel_line
local min_visible = buf.data.completions_offset + 1
local max_visible = buf.data.completions_offset + M.MAX_COMPLETION_LINES
if sel_line > max_visible or sel_line < min_visible then
buf.data.completions_offset = math.floor((sel_line - 1) / M.MAX_COMPLETION_LINES) * M.MAX_COMPLETION_LINES
end
else
local idx = buf.data.histidx
local hist = buf.data.context._history
if idx < buf.data.histsaveidx then
idx = idx + 1
buf.data.histidx = idx
buf.data.text = hist[idx]
buf.data.pos = #buf.data.text+1
end
end
buf:refresh()
end
}
local function set_key(k)
ve_keys[k] = function()
local buffer = ui.command_entry
local buf = buffer._textredux
local t = buf.data.text
local pos = buffer.current_pos
t = t:sub(1, pos-1) .. k .. t:sub(pos, -1)
buf.data.text = t
buf.data.pos = pos + 1
if buf.data.completions then
complete_now()
-- We should retry completion on tab even if we have saved the completions,
-- but we can continue using them if just typing extra characters.
buf.data.completions_stale = true
end
buf:refresh()
end
end
local function set_key_range(first, last)
local i = string.byte(first)
while i <= string.byte(last) do
set_key(string.char(i))
i = i + 1
end
end
-- Set all ASCII printable keys to just insert.
set_key_range(' ', '\x7e')
local function do_start(context)
local buf = redux.core.buffer.new('entry')
buf.on_refresh = ve_refresh
for k,v in pairs(ve_keys) do
buf.keys[k] = v
end
buf.data = {
prompt=context._prompt,
text = '',
pos=1,
handler=context._handler,
complete=context._complete,
context=context,
histidx=#context._history+1,
histsaveidx=#context._history+1,
}
buf.data.marginstate = save_margins(ui.command_entry)
buf:attach_to_command_entry()
ui.command_entry.height = 1
end
-- Create a new entry context
function M.new(prompt, handler, complete)
local result = {
_prompt=prompt,
_handler=handler,
_complete=complete,
_history={},
start = do_start,
}
return result
end
return M
|
--- Python-style list class. <p>
-- Based on original code by Nick Trout.
-- <p>
-- <b>Please Note</b>: methods that change the list will return the list.
-- This is to allow for method chaining, but please note that <tt>ls = ls:sort()</tt>
-- does not mean that a new copy of the list is made. In-place (mutable) methods
-- are marked as returning 'the list' in this documentation.
-- <p>
-- See the Guide for further <a href="../../index.html#list">discussion</a>
-- <p>
-- See <a href="http://www.python.org/doc/current/tut/tut.html">http://www.python.org/doc/current/tut/tut.html</a>, section 5.1
-- <p>
-- <b>Note</b>: The comments before some of the functions are from the Python docs
-- and contain Python code.
-- <p>
-- Written for Lua version 4.0 <br />
-- Redone for Lua 5.1, Steve Donovan.
-- @class module
-- @name pl.List
-- @pragma nostrip
local tinsert,tremove,concat,tsort = table.insert,table.remove,table.concat,table.sort
local setmetatable, getmetatable,type,tostring,assert,string,next = setmetatable,getmetatable,type,tostring,assert,string,next
local write = io.write
local tablex = require 'pl.tablex'
local filter,imap,imap2,reduce,transform,tremovevalues = tablex.filter,tablex.imap,tablex.imap2,tablex.reduce,tablex.transform,tablex.removevalues
local tablex = tablex
local tsub = tablex.sub
local utils = require 'pl.utils'
local function_arg = utils.function_arg
local is_type = utils.is_type
local split = utils.split
local assert_arg = utils.assert_arg
local normalize_slice = tablex._normalize_slice
--[[
module ('pl.List',utils._module)
]]
local Multimap = utils.stdmt.MultiMap
-- metatable for our list objects
local List = utils.stdmt.List
List.__index = List
List._class = List
local iter
-- we give the metatable its own metatable so that we can call it like a function!
setmetatable(List,{
__call = function (tbl,arg)
return List.new(arg)
end,
})
local function makelist (t,obj)
local klass = List
if obj then
klass = getmetatable(obj)
end
return setmetatable(t,klass)
end
local function is_list(t)
return getmetatable(t) == List
end
local function simple_table(t)
return type(t) == 'table' and not is_list(t) and #t > 0
end
function List:_init (src)
if src then
for v in iter(src) do
tinsert(self,v)
end
end
end
--- Create a new list. Can optionally pass a table;
-- passing another instance of List will cause a copy to be created
-- we pass anything which isn't a simple table to iterate() to work out
-- an appropriate iterator @see List.iterate
-- @param t An optional list-like table
-- @return a new List
-- @usage ls = List(); ls = List {1,2,3,4}
function List.new(t)
local ls
if not simple_table(t) then
ls = {}
List._init(ls,t)
else
ls = t
end
makelist(ls)
return ls
end
function List:clone()
local ls = makelist({},self)
List._init(ls,self)
return ls
end
function List.default_map_with(T)
return function(self,name)
local f = T[name]
if f then
return function(self,...)
return self:map(f,...)
end
else
error("method not found: "..name,2)
end
end
end
---Add an item to the end of the list.
-- @param i An item
-- @return the list
function List:append(i)
tinsert(self,i)
return self
end
List.push = tinsert
--- Extend the list by appending all the items in the given list.
-- equivalent to 'a[len(a):] = L'.
-- @param L Another List
-- @return the list
function List:extend(L)
assert_arg(1,L,'table')
for i = 1,#L do tinsert(self,L[i]) end
return self
end
--- Insert an item at a given position. i is the index of the
-- element before which to insert.
-- @param i index of element before whichh to insert
-- @param x A data item
-- @return the list
function List:insert(i, x)
assert_arg(1,i,'number')
tinsert(self,i,x)
return self
end
--- Insert an item at the begining of the list.
-- @param x a data item
-- @return the list
function List:put (x)
return self:insert(1,x)
end
--- Remove an element given its index.
-- (equivalent of Python's del s[i])
-- @param i the index
-- @return the list
function List:remove (i)
assert_arg(1,i,'number')
tremove(self,i)
return self
end
--- Remove the first item from the list whose value is given.
-- (This is called 'remove' in Python; renamed to avoid confusion
-- with table.remove)
-- Return nil if there is no such item.
-- @param x A data value
-- @return the list
function List:remove_value(x)
for i=1,#self do
if self[i]==x then tremove(self,i) return self end
end
return self
end
--- Remove the item at the given position in the list, and return it.
-- If no index is specified, a:pop() returns the last item in the list.
-- The item is also removed from the list.
-- @param i An index
-- @return the item
function List:pop(i)
if not i then i = #self end
assert_arg(1,i,'number')
return tremove(self,i)
end
List.get = List.pop
--- Return the index in the list of the first item whose value is given.
-- Return nil if there is no such item.
-- @class function
-- @name List:index
-- @param x A data value
-- @param idx where to start search (default 1)
-- @return the index, or nil if not found.
local tfind = tablex.find
List.index = tfind
--- does this list contain the value?.
-- @param x A data value
-- @return true or false
function List:contains(x)
return tfind(self,x) and true or false
end
--- Return the number of times value appears in the list.
-- @param x A data value
-- @return number of times x appears
function List:count(x)
local cnt=0
for i=1,#self do
if self[i]==x then cnt=cnt+1 end
end
return cnt
end
--- Sort the items of the list, in place.
-- @param cmp an optional comparison function; '<' is used if not given.
-- @return the list
function List:sort(cmp)
tsort(self,cmp)
return self
end
--- Reverse the elements of the list, in place.
-- @return the list
function List:reverse()
local t = self
local n = #t
local n2 = n/2
for i = 1,n2 do
local k = n-i+1
t[i],t[k] = t[k],t[i]
end
return self
end
--- Emulate list slicing. like 'list[first:last]' in Python.
-- If first or last are negative then they are relative to the end of the list
-- eg. slice(-2) gives last 2 entries in a list, and
-- slice(-4,-2) gives from -4th to -2nd
-- @param first An index
-- @param last An index
-- @return a new List
function List:slice(first,last)
return tsub(self,first,last)
end
--- empty the list.
-- @return the list
function List:clear()
for i=1,#self do tremove(self,i) end
return self
end
local eps = 1.0e-10
--- Emulate Python's range(x) function.
-- Include it in List table for tidiness
-- @param start A number
-- @param finish A number greater than start; if zero, then 0..start-1
-- @param incr an optional increment (may be less than 1)
-- @usage List.range(0,3) == List {0,1,2,3}
function List.range(start,finish,incr)
if not finish then
start = 0
finish = finish - 1
end
if incr then
if not utils.is_integer(incr) then finish = finish + eps end
else
incr = 1
end
assert_arg(1,start,'number')
assert_arg(2,finish,'number')
local t = List.new()
for i=start,finish,incr do tinsert(t,i) end
return t
end
--- list:len() is the same as #list.
function List:len()
return #self
end
-- Extended operations --
--- Remove a subrange of elements.
-- equivalent to 'del s[i1:i2]' in Python.
-- @param i1 start of range
-- @param i2 end of range
-- @return the list
function List:chop(i1,i2)
return tremovevalues(self,i1,i2)
end
--- Insert a sublist into a list
-- equivalent to 's[idx:idx] = list' in Python
-- @param idx index
-- @param list list to insert
-- @return the list
-- @usage l = List{10,20}; l:splice(2,{21,22}); assert(l == List{10,21,22,20})
function List:splice(idx,list)
assert_arg(1,idx,'number')
idx = idx - 1
local i = 1
for v in iter(list) do
tinsert(self,i+idx,v)
i = i + 1
end
return self
end
--- general slice assignment s[i1:i2] = seq.
-- @param i1 start index
-- @param i2 end index
-- @param seq a list
-- @return the list
function List:slice_assign(i1,i2,seq)
assert_arg(1,i1,'number')
assert_arg(1,i2,'number')
i1,i2 = normalize_slice(self,i1,i2)
if i2 >= i1 then self:chop(i1,i2) end
self:splice(i1,seq)
return self
end
--- concatenation operator.
-- @param L another List
-- @return a new list consisting of the list with the elements of the new list appended
function List:__concat(L)
assert_arg(1,L,'table')
local ls = self:clone()
ls:extend(L)
return ls
end
--- equality operator ==. True iff all elements of two lists are equal.
-- @param L another List
-- @return true or false
function List:__eq(L)
if #self ~= #L then return false end
for i = 1,#self do
if self[i] ~= L[i] then return false end
end
return true
end
--- join the elements of a list using a delimiter. <br>
-- This method uses tostring on all elements.
-- @param delim a delimiter string, can be empty.
-- @return a string
function List:join (delim)
delim = delim or ''
assert_arg(1,delim,'string')
return concat(imap(tostring,self),delim)
end
--- join a list of strings. <br>
-- Uses table.concat directly.
-- @class function
-- @name List:concat
-- @param delim a delimiter
-- @return a string
List.concat = concat
local function tostring_q(val)
local s = tostring(val)
if type(val) == 'string' then
s = '"'..s..'"'
end
return s
end
--- how our list should be rendered as a string. Uses join().
-- @see List:join
function List:__tostring()
return '{'..self:join(',',tostring_q)..'}'
end
--[[
-- NOTE: this works, but is unreliable. If you leave the loop before finishing,
-- then the iterator is not reset.
--- can iterate over a list directly.
-- @usage for v in ls do print(v) end
function List:__call()
if not self.key then self.key = 1 end
local value = self[self.key]
self.key = self.key + 1
if not value then self.key = nil end
return value
end
--]]
--[[
function List.__call(t,v,i)
i = (i or 0) + 1
v = t[i]
if v then return i, v end
end
--]]
--- call the function for each element of the list.
-- @param fun a function or callable object
-- @param ... optional values to pass to function
function List:foreach (fun,...)
local t = self
fun = function_arg(1,fun)
for i = 1,#t do
fun(t[i],...)
end
end
--- create a list of all elements which match a function.
-- @param fun a boolean function
-- @param arg optional argument to be passed as second argument of the predicate
-- @return a new filtered list.
function List:filter (fun,arg)
return makelist(filter(self,fun,arg),self)
end
--- split a string using a delimiter.
-- @param s the string
-- @param delim the delimiter (default spaces)
-- @return a List of strings
-- @see pl.utils.split
function List.split (s,delim)
assert_arg(1,s,'string')
return makelist(split(s,delim))
end
--- apply a function to all elements.
-- Any extra arguments will be passed to the function
-- @param fun a function of at least one argument
-- @param ... arbitrary extra arguments.
-- @return a new list: {f(x) for x in self}
-- @see pl.tablex.imap
function List:map (fun,...)
return makelist(imap(fun,self,...),self)
end
--- apply a function to all elements, in-place.
-- Any extra arguments are passed to the function.
-- @param fun A function that takes at least one argument
-- @param ... arbitrary extra arguments.
function List:transform (fun,...)
transform(fun,self,...)
end
--- apply a function to elements of two lists.
-- Any extra arguments will be passed to the function
-- @param fun a function of at least two arguments
-- @param ls another list
-- @param ... arbitrary extra arguments.
-- @return a new list: {f(x,y) for x in self, for x in arg1}
-- @see pl.tablex.imap2
function List:map2 (fun,ls,...)
return makelist(imap2(fun,self,ls,...),self)
end
--- apply a named method to all elements.
-- Any extra arguments will be passed to the method.
-- @param name name of method
-- @param ... extra arguments
-- @return a new list of the results
-- @see pl.seq.mapmethod
function List:mapm (name,...)
local res = {}
local t = self
for i = 1,#t do
local val = t[i]
local fn = val[name]
if not fn then error(type(val).." does not have method "..name,2) end
res[i] = fn(val,...)
end
return makelist(res,self)
end
--- 'reduce' a list using a binary function.
-- @param fun a function of two arguments
-- @return result of the function
-- @see pl.tablex.reduce
function List:reduce (fun)
return reduce(fun,self)
end
--- partition a list using a classifier function.
-- The function may return nil, but this will be converted to the string key '<nil>'.
-- @param fun a function of at least one argument
-- @param ... will also be passed to the function
-- @return a table where the keys are the returned values, and the values are Lists
-- of values where the function returned that key. It is given the type of Multimap.
-- @see pl.MultiMap
function List:partition (fun,...)
fun = function_arg(1,fun)
local res = {}
for i = 1,#self do
local val = self[i]
local klass = fun(val,...)
if klass == nil then klass = '<nil>' end
if not res[klass] then res[klass] = List() end
res[klass]:append(val)
end
return setmetatable(res,Multimap)
end
--- return an iterator over all values.
function List:iter ()
return iter(self)
end
--- Create an iterator over a seqence.
-- This captures the Python concept of 'sequence'.
-- For tables, iterates over all values with integer indices.
-- @param seq a sequence; a string (over characters), a table, a file object (over lines) or an iterator function
-- @usage for x in iterate {1,10,22,55} do io.write(x,',') end ==> 1,10,22,55
-- @usage for ch in iterate 'help' do do io.write(ch,' ') end ==> h e l p
function List.iterate(seq)
if type(seq) == 'string' then
local idx = 0
local n = #seq
local sub = string.sub
return function ()
idx = idx + 1
if idx > n then return nil
else
return sub(seq,idx,idx)
end
end
elseif type(seq) == 'table' then
local idx = 0
local n = #seq
return function()
idx = idx + 1
if idx > n then return nil
else
return seq[idx]
end
end
elseif type(seq) == 'function' then
return seq
elseif type(seq) == 'userdata' and io.type(seq) == 'file' then
return seq:lines()
end
end
iter = List.iterate
return List
|
Task.Wait() -- Wait a tick for players to connect
local player = Game.GetLocalPlayer()
_G.timer = 60
_G.finish = 0
function Tick()
Task.Wait(1)
if _G.timer > 0
then _G.timer = _G.timer -1
end
if _G.timer == 0
then _G.finish = 1
end
UI.PrintToScreen(tostring (_G.timer))
end
|
local ScrappingMachineUI =
{
Name = "ScrappingMachineUI",
Type = "System",
Namespace = "C_ScrappingMachineUI",
Functions =
{
{
Name = "CloseScrappingMachine",
Type = "Function",
},
{
Name = "DropPendingScrapItemFromCursor",
Type = "Function",
Arguments =
{
{ Name = "index", Type = "number", Nilable = false },
},
},
{
Name = "GetCurrentPendingScrapItemLocationByIndex",
Type = "Function",
Arguments =
{
{ Name = "index", Type = "number", Nilable = false },
},
Returns =
{
{ Name = "itemLoc", Type = "table", Mixin = "ItemLocationMixin", Nilable = false },
},
},
{
Name = "GetScrapSpellID",
Type = "Function",
Returns =
{
{ Name = "spellID", Type = "number", Nilable = false },
},
},
{
Name = "GetScrappingMachineName",
Type = "Function",
Returns =
{
{ Name = "name", Type = "string", Nilable = false },
},
},
{
Name = "HasScrappableItems",
Type = "Function",
Returns =
{
{ Name = "hasScrappableItems", Type = "bool", Nilable = false },
},
},
{
Name = "RemoveAllScrapItems",
Type = "Function",
},
{
Name = "RemoveCurrentScrappingItem",
Type = "Function",
},
{
Name = "RemoveItemToScrap",
Type = "Function",
Arguments =
{
{ Name = "index", Type = "number", Nilable = false },
},
},
{
Name = "ScrapItems",
Type = "Function",
},
{
Name = "SetScrappingMachine",
Type = "Function",
Arguments =
{
{ Name = "gameObject", Type = "string", Nilable = false },
},
},
{
Name = "ValidateScrappingList",
Type = "Function",
},
},
Events =
{
{
Name = "ScrappingMachineClose",
Type = "Event",
LiteralName = "SCRAPPING_MACHINE_CLOSE",
},
{
Name = "ScrappingMachineItemRemovedOrCancelled",
Type = "Event",
LiteralName = "SCRAPPING_MACHINE_ITEM_REMOVED_OR_CANCELLED",
Payload =
{
{ Name = "index", Type = "number", Nilable = false },
},
},
{
Name = "ScrappingMachinePendingItemChanged",
Type = "Event",
LiteralName = "SCRAPPING_MACHINE_PENDING_ITEM_CHANGED",
},
{
Name = "ScrappingMachineScrappingFinished",
Type = "Event",
LiteralName = "SCRAPPING_MACHINE_SCRAPPING_FINISHED",
},
{
Name = "ScrappingMachineShow",
Type = "Event",
LiteralName = "SCRAPPING_MACHINE_SHOW",
},
},
Tables =
{
},
};
APIDocumentation:AddDocumentationTable(ScrappingMachineUI);
|
local Player = game:GetService("Players").LocalPlayer
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")
local ECS = ReplicatedStorage:WaitForChild("ecs-client")
-- Loading in all our systems (i would make a sys-loader for this!)
local camerasystem = require(ECS.systems.camerasystem)
local keybindsystem = require(ECS.systems.keybindsystem)
-- Loading in all our components (again i would make a comp-loader for this!)
local playerComponent = require(ECS.components.player)
local keybindComponent = require(ECS.components.keybinds)
local stateComponent = require(ECS.components.state)
local entity = require(ECS.entity)
-- Creating our PlayerEntity
local PlayerEntity = entity.new()
-- Here we are adding the player component to the player entity
-- the player component stores information about the player
PlayerEntity:AddComponent(playerComponent.new(Player))
-- Here we are adding a stateful-component to the player entity
PlayerEntity:AddComponent(stateComponent.new())
-- Here we are binding creating keybinds
PlayerEntity:AddComponent(keybindComponent.new(Enum.KeyCode.E, function()
-- we can simply query our player state since by using PlayerEntity:get('state')
-- and change the state
local state = PlayerEntity:GetComponent("state")
state.inCamMode = not state.inCamMode
end))
-- Loading our keybinds into the keybind system to avoid any weird behaviours
keybindsystem:Load(PlayerEntity)
-- Here we are updating our player entity every frame for smooth camera movement
RunService.RenderStepped:Connect(function(step)
camerasystem:Update(step, PlayerEntity)
end)
|
package.path = "../src/?.lua;src/?.lua;" .. package.path
pcall(require, "luarocks.require")
local redis = require 'redis'
local params = {
host = '127.0.0.1',
port = 6379,
}
local client = redis.connect(params)
client:select(15) -- for testing purposes
local replies = client:pipeline(function(p)
p:ping()
p:flushdb()
p:exists('counter')
p:incrby('counter', 10)
p:incrby('counter', 30)
p:exists('counter')
p:get('counter')
p:mset({ foo = 'bar', hoge = 'piyo'})
p:del('foo', 'hoge')
p:mget('does_not_exist', 'counter')
p:info()
end)
for _, reply in pairs(replies) do
print('*', reply)
end
|
local st = GS.new()
local base = (...):gsub('%.', '/') .. '/'
local duration_show_splash = 1 -- in seconds
local color_fg = {255,255,255}
local color_bg = {0,0,0}
local cell_width = 23
local cell_height = 23
local cell_spacing = 3
local callbacks = {}
function callbacks.after(f) callbacks.after = f end
-- ANIMATION
-- 1 -> draw square, 0 -> blank
local sequence, board = {}, {
{1,0,1,0,1,1,0,1,0,0,1,1,0},
{1,0,1,0,1,0,0,1,0,0,1,0,1},
{0,1,0,0,1,0,0,1,1,0,1,1,0},
}
-- GRAPHICS
local offset = {
x = (love.graphics.getWidth() - #board[1] * (cell_spacing + cell_width)) / 2,
y = (love.graphics.getHeight() - #board * (cell_spacing + cell_height)) / 2,
}
local haze = {
sx = love.graphics.getWidth() / Image.haze:getWidth(),
sy = love.graphics.getHeight() / Image.haze:getHeight(),
}
-- SOUND
local woosh
local woosh_length = 1.3
local tick = {}
for k = 1,10 do
local len = 0.06 + math.random() * .2
local attack, release = 0.1 * len, 0.9 * len
local freq = 300 + (math.random() * .5 + .5) * 50
tick[k] = love.sound.newSoundData(len * 44100, 44100, 16, 1)
for i = 0,len*44100 do
local t = i / 44100
local sample = math.sin(t * freq * math.pi * 2)
local env = t < attack and (t/attack)^4 or (1 - (t-attack)/(release-attack))^4
sample = sample * env * .2
tick[k]:setSample(i, sample)
end
end
local t = 0
function st:enter()
woosh = nil
sequence = {i = 1, t = 0}
for i = 1,#board do
for k = 1,#board[i] do
sequence[#sequence+1] = {y = i, x = k}
if board[i][k] == 0 then
sequence[#sequence+1] = {t = 1, y = i, x = k}
end
board[i][k] = {a = 0, da = 0}
end
end
-- randomize animation
for i = 1,#sequence do
local k = math.random(i,#sequence)
sequence[i], sequence[k] = sequence[k], sequence[i]
sequence[i].dt = 1 / #sequence
end
t = 0
love.graphics.setBackgroundColor(color_bg)
end
function st:draw()
for i = 1,#board do
local y = offset.y + (i-1) * (cell_height + cell_spacing)
for k = 1,#board[1] do
if board[i][k].a ~= 0 then
color_fg[4] = board[i][k].a
love.graphics.setColor(color_fg)
local x = offset.x + (k-1) * (cell_width + cell_spacing)
love.graphics.rectangle('fill', x,y, cell_width, cell_height)
end
end
end
if t >= duration_show_splash then
love.graphics.setColor(color_bg)
love.graphics.draw(Image.haze, love.graphics.getWidth(),0,0, -haze.sx * math.sqrt(s) * 2, haze.sy * math.sqrt(s) * 5)
end
end
function st:update(dt)
dt = math.min(dt, 1 / 25)
if sequence[sequence.i] then
-- vrld in - update sequence
if sequence.t >= sequence[sequence.i].dt then
local s = sequence[sequence.i]
if board[s.y][s.x].da == 0 then
board[s.y][s.x].da = 1
else
board[s.y][s.x].da = -board[s.y][s.x].da
end
local src = love.audio.newSource(tick[math.random(#tick)])
src:play()
sequence.t = sequence.t - sequence[sequence.i].dt
sequence.i = sequence.i + 1
end
sequence.t = sequence.t + dt
else
-- show vrld
t = t + dt
end
if t >= duration_show_splash then
if not woosh then
woosh = Sound.static.woosh:play()
elseif woosh:isStopped() then
GS.transition(State.menu)
return
end
s = (t-duration_show_splash) / woosh_length
color_bg[4] = math.min(math.sqrt(s) * 2 * 255, 255)
end
-- update board alpha
for i = 1,#board do
for k = 1,#board[i] do
local cell = board[i][k]
cell.a = math.max(math.min(cell.a + 15 * cell.da * dt * 255, 255), 0)
end
end
end
function st:keypressed()
if t < duration_show_splash then
sequence.i = {}
t = duration_show_splash
end
end
return st
|
function love.conf(t)
t.window.width = 1024
t.window.height = 700
t.modules.joystick = false
t.modules.physics = false
end
|
local tag = "spawn_log"
local c, w, g = Color(0, 255, 255), Color(255, 255, 255), Color(192, 192, 192)
local function Log(event, ply, ...)
MsgC(c, "[", event, "] ")
Msg(ply, " ")
MsgC(...)
Msg("\n")
end
local prev
local function NoVectorDecimals(vec)
vec = vec:gsub("(%d+).%d*", "%1")
return vec
end
local function LogProp(ply, model, ent)
if prev == "duplicator" then return end
local pos = NoVectorDecimals(tostring(ent:GetPos()))
Log("SPAWN prop", ply, w, ent:GetModel(), g, " (" .. tostring(ent) .. " @ " .. pos .. ")")
end
local function LogEffect(ply, model, ent)
local pos = NoVectorDecimals(tostring(ent:GetPos()))
Log("SPAWN effect", ply, w, ent:GetModel(), g, " (" .. tostring(ent) .. " @ " .. pos .. ")")
end
local function LogSENT(ply, ent)
local pos = NoVectorDecimals(tostring(ent:GetPos()))
Log("SPAWN sent", ply, w, ent.PrintName or ent:GetClass(), g, " (" .. tostring(ent) .. " @ " .. pos .. ")")
end
local function LogVehicle(ply, ent)
Log("SPAWN vehicle", ply, w, ent.VehicleTable.Name, g, " (" .. tostring(ent) .. ")")
end
local ignoreTools = {
paint = true,
inflator = true,
}
local function LogTool(ply, trace, tool)
if ignoreTools[tool] then return end
local pos = NoVectorDecimals(tostring(trace.HitPos))
Log("TOOL", ply, w, tool, g, " " .. tostring(trace.Entity) .. " @ " .. pos)
prev = tool
timer.Simple(0, function() prev = nil end)
end
hook.Add("PlayerSpawnedProp", tag, LogProp)
hook.Add("PlayerSpawnedEffect", tag, LogEffect)
hook.Add("PlayerSpawnedSENT", tag, LogSENT)
hook.Add("PlayerSpawnedVehicle", tag, LogVehicle)
hook.Add("CanTool", tag, LogTool)
|
---@class TelescopeBookmarksState
---@field os_name string
---@field os_homedir string
---@class TelescopeBookmarksConfig
---@field full_path boolean
---@field selected_browser string
---@field url_open_command string
---@field url_open_plugin string
---@field firefox_profile_name string
---@class Bookmark
---@field name string
---@field path string
---@field url string
|
local say = require("say")
local assert = require("luassert")
local util = require("luassert.util")
local function in_range(state, arguments)
if arguments[3] < arguments[1] then return false end
if arguments[3] > arguments[2] then return false end
return true
end
say:set("assertion.in_range.positive", "Expected between %s and %s \nbut was %s")
say:set("assertion.in_range.negative", "Expected outside %s and %s \nnbut was %s")
assert:register("assertion", "in_range", in_range, "assertion.in_range.positive", "assertion.in_range.negative")
local function color_is_normal(state, arguments)
if not type(arguments[1]) == "table" or #arguments ~= 1 then
return false
end
for _, channel in ipairs({"r", "g", "b"}) do
if not arguments[1][channel] then return false end
assert.in_range(0, 1, arguments[1][channel])
end
return true
end
say:set("assertion.color_is_normal.positive", "%s is not a valid color")
say:set("assertion.color_is_normal.negative", "%s is a valid color")
assert:register("assertion", "color_is_normal", color_is_normal, "assertion.color_is_normal.positive", "assertion.color_is_normal.negative")
local function contains_same(state, arguments)
assert.is_table(arguments[2])
local found = false
for _, value in pairs(arguments[2]) do
if util.deepcompare(value, arguments[1]) then
return true
end
end
return false
end
say:set("assertion.contains_same.positive", "Expected same as %s \nbut found no instances in %s")
say:set("assertion.contains_same.negative", "Expected nothing like %s \nbut found one in %s")
assert:register("assertion", "contains_same", contains_same, "assertion.contains_same.positive", "assertion.contains_same.negative")
|
local obj = {}
obj.__index = obj
-- Metadata
obj.name = "Citrix Viewer Spoon"
obj.version = "1.0"
obj.author = "Bruno Navert"
obj.license = "MIT"
obj.homepage = "https://github.com/brunon/CitrixViewer.spoon"
-- PID of Citrix Viewer app
obj.citrixPid = nil
obj.callbackFunction = nil
local function citrixStarted(pid)
obj.citrixPid = pid
if (obj.callbackFunction ~= nil) then obj.callbackFunction("citrixStarted") end
end
local function citrixStopped()
obj.citrixPid = nil
if (obj.callbackFunction ~= nil) then obj.callbackFunction("citrixStopped") end
end
local citrixAppWatcher = function(name, event, application)
local isCitrixPid = (application ~= nil) and (application:pid() == obj.citrixPid)
-- Citrix shut down
if isCitrixPid and (event == hs.application.watcher.terminated)
then
citrixStopped()
elseif (name == 'Citrix Viewer') and (obj.citrixPid == nil)
then
citrixStarted(application:pid())
end
end
obj.citrixWatcher = hs.application.watcher.new(citrixAppWatcher)
function obj:start()
citrixApp = hs.application.find('Citrix Viewer')
if (citrixApp ~= nil) then
citrixStarted(citrixApp:pid())
end
obj.citrixWatcher:start()
end
function obj:stop()
obj.citrixWatcher:stop()
end
--- CitrixViewer:setStatusCallback(func)
--- Method
--- Registers a function to be called whenever Citrix Viewer starts / stops
---
--- Parameters:
--- * func - A function in the form "function(event)" where "event" is a string describing the state change event
function obj:setStatusCallback(func)
hs.printf("callback=%s",func)
obj.callbackFunction = func
end
return obj
|
data:extend{
{
type = "item-subgroup",
name = "waste",
group = "intermediate-products",
order = "dc"
}
,
{
type = "item-subgroup",
name = "raw-materials",
group = "insane-materials",
order = "ff"
}
,
{
type = "item-subgroup",
name = "insane-parts",
group = "insane-materials",
order = "ff"
}
,
{
type = "item-subgroup",
name = "insane-science",
group = "insane-materials",
order = "ffff"
}
,
{
type = "item-subgroup",
name = "iron",
group = "insane-ores",
order = "b"
}
,
{
type = "item-subgroup",
name = "insane-basic-iron",
group = "insane-ores",
order = "a"
}
,
{
type = "item-subgroup",
name = "zirconium",
group = "insane-ores",
order = "c"
}
,
{
name = "filtration",
type = "recipe-category",
}
,
{
name = "distiling",
type = "recipe-category",
}
,
{
name = "washing",
type = "recipe-category",
}
,
{
name = "blast-furnace",
type = "recipe-category",
}
,
{
name = "metal-casting",
type = "recipe-category",
}
,
{
name = "liquid-metal-furnace",
type = "recipe-category",
}
,
{
type = "item-subgroup",
name = "copper",
group = "insane-ores",
order = "d"
}
,
{
type = "item-subgroup",
name = "insane-mores",
group = "insane-ores",
order = "dc"
}
,
{
name = "froth-floatation",
type = "recipe-category",
}
,
{
name = "melting",
type = "recipe-category",
}
,
{
name = "anode-furnace",
type = "recipe-category",
}
,
{
name = "machines",
type = "item-group",
icon = "__InsaneIndustries__/graphics/icons/TODO.png",
icon_size = 64,
}
,
{
name = "insane-materials",
type = "item-group",
icon = "__InsaneIndustries__/graphics/icons/materials.png",
icon_size = 64,
order = "ff"
}
,
{
name = "insane-ores",
type = "item-group",
icon = "__InsaneIndustries__/graphics/icons/pure-iron-ore.png",
icon_size = 64,
order = "fa"
}
,
{
name = "insane-nuclear",
type = "item-group",
icon = "__InsaneIndustries__/graphics/icons/thorium-plate.png",
icon_size = 64,
order = "bf"
}
,
{
name = "insane-nfuel",
type = "item-subgroup",
group = "insane-nuclear",
}
,
{
name = "insane-nparts",
type = "item-subgroup",
group = "insane-nuclear",
}
,
{
name = "insane-nmaterials",
type = "item-subgroup",
group = "insane-nuclear",
}
,
{
name = "copper-processing",
type = "item-subgroup",
group = "machines",
}
,
{
name = "iron-processing",
type = "item-subgroup",
group = "machines",
}
,
{
name = "generel-processing",
type = "item-subgroup",
group = "machines",
}
,
{
name = "metallurgy",
type = "item-subgroup",
group = "machines",
}
,
{
name = "electrolysis",
type="recipe-category"
}
}
|
Locales['de'] = {
['shop'] = 'geschäft',
['shops'] = 'geschäfte',
['press_menu'] = 'drücke ~INPUT_CONTEXT~ um auf das Geschäft zuzugreifen.',
['bought'] = 'you just bought ~y~%sx~s~ ~b~%s~s~ for ~r~$%s~s~',
['not_enough'] = 'du ~r~hast nicht~s~ genug geld: %s',
['player_cannot_hold'] = 'you do ~r~not~s~ have enough ~y~free space~s~ in your inventory!',
['shop_confirm'] = 'buy %sx %s for $%s?',
['no'] = 'no',
['yes'] = 'yes',
}
|
class("CancelCommonFlagCommand", pm.SimpleCommand).execute = function (slot0, slot1)
pg.ConnectionMgr.GetInstance():Send(11021, {
flag_id = slot1:getBody().flagID
}, 11022, function (slot0)
if getProxy(PlayerProxy) then
slot2 = slot1:getData()
slot2:CancelCommonFlag(slot0)
slot1:updatePlayer(slot2)
end
end)
end
return class("CancelCommonFlagCommand", pm.SimpleCommand)
|
local skynet = require "skynet"
local cluster = require "cluster"
skynet.start(function ()
-- body
--cluster.open "db1"
local sdb = cluster.query("db","sdb")
local mysqldb = cluster.query("db1","mysqldb")
print("......sdb= ",sdb)
print("......mysqldb",mysqldb)
local proxy = cluster.proxy("db",sdb)
local mysqlproxy = cluster.proxy("db", mysqldb)
--local res = skynet.call(mysqlproxy, "lua", "query")
local res = cluster.call("db",mysqlproxy,"query")
for k,v in pairs(res) do
for i,j in pairs(v) do
print(i,j)
end
end
print(skynet.call(proxy,"lua","GET","a"))
print(skynet.call(proxy,"lua","GET","b"))
print('proxy...cluster...'..cluster.call("db",proxy,"GET","a"))
print('proxy...cluster...'..cluster.call("db",proxy,"GET","b"))
--print(cluster.call("db",sdb,"GET","a"))
--local tkx = cluster.snax("db","tkxserver")
--print('.....'..tkx.req.hello "hello cluster")
end)
|
local user_dao = require("core.dao.admin_user_dao")
local decode_base64 = ngx.decode_base64
local resty_sha256 = require("resty.sha256")
local str = require("resty.string")
local pwd_secret ="e5wkxfu73z2rc3tydn6613mmviicbbpq"
local string_gsub = string.gsub
local _M ={}
local function encode(s)
local sha256 = resty_sha256:new()
sha256:update(s)
local digest = sha256:final()
return str.to_hex(digest)
end
local function split(str, delimiter)
local result = {}
if not str or not delimiter then
return result
end
for match in (str..delimiter):gmatch("(.-)"..delimiter) do
if match then
table.insert(result, match)
end
end
return result
end
local function parseHeader(authorization)
local data = split(decode_base64(authorization), ":")
return data[1], data[2]
end
function _M:get_login_username(authorization)
local username = parseHeader(authorization);
return username
end
function _M:sha_password(pwd)
return encode(pwd.."#"..pwd_secret)
end
function _M:check_password(store,authorization)
local username,password = parseHeader(authorization)
if not username or not password then
return false
end
-- 把username 放入ngx ctx 中,在记录操作日志时使用
ngx.ctx.username = username
local sha_password = encode(password.."#"..pwd_secret)
ngx.log(ngx.INFO,"sha_password===:",sha_password)
local user = user_dao.load_user_by_user_pwd(store,username,sha_password)
if user and #user>0 then
return true,user.is_admin
else
return false
end
end
function _M:get_encoded_credential(origin)
local result = string_gsub(origin, "^ *[B|b]asic *", "")
result = string_gsub(result, "( *)$", "")
return result
end
return _M
|
local _,L = ...
if GetLocale()=="esMX" then
end
|
-- coding: utf-8
--[[
-- PLEASE DO "NOT" EDIT THIS FILE!
-- This file is generated by script.
--
-- If you want to apply corrections visit:
-- http://rom.curseforge.com/addons/charplan/localization/
--]]
Charplan.L =
{
}
Charplan.L.STAT_SHORTS =
{
}
Charplan.L.STAT_NAMES =
{
}
|
local JSON = require('JSON')
local parser = clink.arg.new_parser
local la5_args_cache = {}
local cwd = clink.get_cwd()
function JSON:assert () end -- luacheck: no unused args
local function register_parser(la5_parser)
local artisan_parser = parser({ 'artisan'..la5_parser })
la5_parser:disable_file_matching()
artisan_parser:disable_file_matching()
clink.arg.register_parser('la5', la5_parser)
clink.arg.register_parser('php', artisan_parser)
end
local function is_la5_project()
local artisan_file = io.open(clink.get_cwd()..'/artisan', 'r')
if artisan_file ~= nil then
artisan_file:close()
return true
end
return false
end
local function parse_la5_args(word) -- luacheck: no unused args
if not is_la5_project() then return end
if #la5_args_cache > 0 and cwd == clink.get_cwd() then return la5_args_cache end
local args_list = io.popen('php artisan list --format=json')
if args_list == nil then return end
local args_json = args_list:read('*a')
args_list:close()
if not args_json:gmatch('[{}%[%]]') then return end
while args_json:sub(1, 1) ~= '{' do
args_json = args_json:sub(2)
end
local commands_table = JSON:decode(args_json)
if commands_table == nil then return end
la5_args_cache = {}
cwd = clink.get_cwd()
for _, command in pairs(commands_table.commands) do
table.insert(la5_args_cache, command.name)
local arguments = {}
for _, argument in pairs(command.definition.arguments) do
table.insert(arguments, argument.name)
end
local options = {}
for _, option in pairs(command.definition.options) do
table.insert(options, option.name)
if option.shortcut:len() > 0 then
table.insert(options, option.shortcut)
end
end
local args_opts_parser = parser()
if #arguments > 0 and command.name ~= 'help' and command.name ~= 'list' then
args_opts_parser:set_arguments(arguments)
end
args_opts_parser:set_flags(options)
args_opts_parser:disable_file_matching()
register_parser( parser({ command.name..args_opts_parser }) )
end
local namespace_list = {}
for _, namespace in pairs(commands_table.namespaces) do
table.insert(namespace_list, namespace.id)
end
register_parser( parser({
'list'..parser({ namespace_list }):disable_file_matching(),
'help'..parser({ la5_args_cache }):disable_file_matching()
}) )
return la5_args_cache
end
register_parser( parser({ parse_la5_args }) )
|
local view = require("models/cameraModel")
local geometry = {}
geometry.panel = 300
geometry.hexres = 64
geometry.center = {}
function geometry.setSize(newSize)
geometry.hexres = newSize
end
function geometry.recountDimensions()
geometry.itemsFitX=math.floor(width/geometry.hexres/2)
geometry.itemsFitY=math.floor(height/geometry.hexres/2)
geometry.center[1]=math.floor((width-geometry.panel)/2)
geometry.center[2]=math.floor(height/2)
end
function geometry.hex(x,y,mode)
--draw a hexagon at x,y coordinates
local mode = mode or 'line'
local vertices={x+geometry.hexres*0.5, y+geometry.hexres*math.sqrt(3)/2, x+geometry.hexres, y, x+geometry.hexres*0.5,
y-geometry.hexres*math.sqrt(3)/2, x-geometry.hexres*0.5, y-geometry.hexres*math.sqrt(3)/2, x-geometry.hexres, y, x-geometry.hexres*0.5, y+geometry.hexres*math.sqrt(3)/2}
for i=1,6 do
vertices[2*i]=vertices[2*i]-view.y
vertices[2*i-1]=vertices[2*i-1]-view.x
end
for i=1,12 do
vertices[i]=vertices[i]*view.scale
end
for i=1,6 do
vertices[2*i]=vertices[2*i]+geometry.center[2]
vertices[2*i-1]=vertices[2*i-1]+geometry.center[1]
end
love.graphics.polygon(mode, vertices)
end
function geometry.hexfill(x,y)
--draw a filled hexagon
geometry.hex(x,y,'fill')
end
function geometry.hexcoord(x,y)
--convert cartesian coordinates into hexagonal
return x/math.sqrt(3)-y,-x/math.sqrt(3)-y
end
function geometry.hextarget(x,y)
--get index of a hexagon by hexagonal coordinates
if x>=geometry.hexres*math.sqrt(3)/2 then
xint=math.floor(x/(geometry.hexres*math.sqrt(3))+0.5)
elseif x<=-geometry.hexres*math.sqrt(3)/2 then
xint=math.ceil(x/(geometry.hexres*math.sqrt(3))-0.5)
else
xint=0
end
if y>=geometry.hexres*math.sqrt(3)/2 then
yint=math.floor(y/(geometry.hexres*math.sqrt(3))+0.5)
elseif y<=-geometry.hexres*math.sqrt(3)/2 then
yint=math.ceil(y/(geometry.hexres*math.sqrt(3))-0.5)
else
yint=0
end
return xint,yint
end
return geometry
|
local util = require'util'
local function handler(self, source, destination, args, domain)
local query = util.urlEncode(args:gsub(' ', '_'))
domain = domain or 'en'
util.simplehttp(
string.format('https://%s.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&redirects=1&titles=%s', domain, query),
function(js, url, response)
local data = util.json.decode(js)
local _, entry = next(data.query.pages)
if not entry or not entry.extract then
say('Missing entry')
else
-- Sometimes text is very long, let's try to snip some
local text = entry.extract
text = text:match('(.-)\n') or text
say(text)
end
end
)
end
return {
PRIVMSG = {
['^%pwikipedia (.*)$'] = handler,
['^%pwp (.*)$'] = handler,
['^%p([a-z][a-z])wp (.*)$'] = function(self, source, destination, code, arg)
handler(self, source, destination, arg, code)
end
},
}
|
vim.o.background = "light"
vim.g.modus_cursorline_intense = 1
vim.g.modus_green_strings = 1
vim.g.modus_termtrans_enable = 1
vim.g.modus_yellow_comments = 1
|
--[[
HOW TO MAKE YOUR BOT
Thank you for choosing egg bot to startup and make your bot. Before you begin, I will explain how this bot is orginized so you
can begin adding all the fun stuff you want! As a note, I highly encorage to chamge as much as you want, don't feel that you are limited by what I offer.
You can add/modify as much as you want so it suits your own needs
========================
==== BOT'S WORKFLOW ====
========================
The bot is divided into two parts: commands and features
COMMANDS:
The bot has an easy to use system for managing all the commands. A command is a function that does 'something' when the command is called. This bot is
presented so commands are the promary usage for the bot. There are a lot of neat helper functions so the process of making a command is easy, streamlined,
flexible, and fast!
FEATURES:
Features is for everything else that is not a command. Here you can do more complex things, such as, banning certain words, making greeting messages, or
even logging data (message edits, message deletions, channel creation, etc). The point is, anything that you want the bot to do that isn't acommand is a feature
====================================
==== WHATS IN THIS INSTALLATION ====
====================================
/commands
Here is a list of all the command files. Only lua files should go here. All command files are automatically loaded
/features
Here is a list of all the feature files. Only lua files should go here. All feature files are automatically loaded
/files
This is a folder in which you can drop in whatever you want. Use it to store user data, images, libraries, etc.
Startup.bat
This bat file is a shorcut for starting up the bot. Open it with notepad to change the main.lua directory or the name of the window title
main.lua
The file you are looking right now! This is the glue that makes all the other files work.
/files/luaextensions.lua
Built-in file that includes a massive collection of helper functions. The whole artitechture of this bot relies on this file
/files/token.lua
Built-in file to store all your important tokens and passwords. Store sensitive information here instead of other files to avoid 'accidentally' sharing it. Technically optional
/files/perserver.json
Built-in file JSON file used for the purpose to store unique data for every server. Technically optional
==============================
==== ANATOMY OF A COMMAND ====
==============================
This is how you should define each command file. Take a look at the ones included to get a feel for how a command file works!
local command = {}
command.name = "" -- The display name for the command
command.info = "" -- A quick tip about the command that will be shown in the built-in help command. Try keeping it a sentence long
command.desc = "" -- This is what will be shown in the built-in help command. Be as detailed as possible! Any use of '{prefix}' will be automatically subbed in for the actual prefix
command.trigger = {"", ""} -- This is a list of strings. A trigger is what a user needs to use to call a command. Note that 'name' and 'trigger' are not the same thing
command.onCommand = function(message) -- This function will be called when the command is triggered by the user. Only one parameter is passed and it is the message object
command.icon = "" -- You can optionally add an image URL that will be used on the built-in help command
command[EVENT_HANDLE] = function(...) -- You can optionally use any of the event handlers below to use for your commands
command.hidden = bool -- You can optionally marked as a command as hidden. What this means is that it will not show up on the built-in help command
return command
==============================
==== ANATOMY OF A FEATURE ====
==============================
This is how you should define each feature file. Take a look at the ones included to get a feel how a feature file works!
local feature = {}
feature.name = "" -- The display name for the feature
feature.desc = "" -- This is what will be shown in the built-in help command. Be as detailed as possible!
feature.onCommandType = "" -- Can be "ignore", "override", or "both".
What this is for is to provide a solution to conflics for when a command and feature are triggered at the same time
"ignore": If a feature and command are both triggered, do command only, ignore feature
"override": If a feature and command are both triggered, ignore the command, do feature only
"both": If a feature and command are both triggered, do both
feature.onMessage = function(message) return success -- This function will be called when a message is sent. The calling behavior changes depending on 'onCommandType. If returned true, the system will assume the feature is 'successful' in the sense that a message was sent
feature[EVENT_HANDLE] = function(...) -- You can optionally use any of the event handlers below to use for your commands
return feature
=============================
==== ADDING MORE HANDLES ====
=============================
Right now, the only handles are: ready, guildCreate, memberJoin, memberLeave. You can add more if needed.
List of all events: https://github.com/SinisterRectus/Discordia/wiki/Events
Take a look at how memberJoin and memberLeave are set up in the bottom of this file so you can add your own!
======================
==== SO WHAT NOW? ====
======================
Make your bot! I hope you have been convinced to use my little framework to begin making fun commands to your bot!
If you are feeling bored and have nothing to do, feel free to share with me (author) your own creations you have made with this.
My discord username is SetaYoshi, I am in the discordia server if you need me
You can also DM me if you need help, feedback, suggestions, or yell at me if you have complaints
~ SetaYoshi
]]
local ext = require('files/luaextensions.lua') -- Load all helpful extensions
local discordia = require('discordia')
local client = discordia.Client()
local prefix = "!" -- Default prefix. The bot will use this prefix in DMs and when joining a server
local token = require("files/token").DISCORD
-- Store the client so commands have access to it
Misc.discordia = discordia
Misc.class = Misc.discordia.class
Misc.type = Misc.class.type
Misc.client = client
Misc.defaultPrefix = prefix
local fs = require("fs")
local perserver = Misc.loadJson("perserver.json")
-- Ensures that the guildID has proper perserver data, if not then default it
local function perserverCheck(guildID)
perserver[guildID] = perserver[guildID] or {}
local t = perserver[guildID]
t.prefix = t.prefix or prefix
t.commander = t.commander or {}
t.tags = t.tags or {}
end
-- Table of commands
Misc.commands = {}
Misc.commandsMAP = {}
local commands = Misc.commands
local commandsMAP = Misc.commandsMAP
local commandFileList = fs.readdirSync("libs/commands/")
-- Table of features
Misc.features = {}
local features = Misc.features
local featureFileList = fs.readdirSync("libs/features/")
-- Load in and organize all commands
for k, v in ipairs(commandFileList) do
local module = require("commands/"..v)
-- commands is a list of commands
table.insert(commands, module)
-- commandsMAP is mapped by the triggers, for easy access
for _, v in ipairs(module.trigger) do
if commandsMAP[v] then p("!! Multiple commands have the same trigger: ["..v.."]") end
commandsMAP[v] = module
end
end
-- Load in and organize all features
for k, v in ipairs(featureFileList) do
local module = require("features/"..v)
-- features is a list of features
table.insert(features, module)
end
-- This function is used when needing to call a handle to all commands
local commandCache = {}
local function commandHandler(eventName, ...)
if commandCache[eventName] then
for k, v in ipairs(commandCache[eventName]) do
v[eventName](...)
end
else
for k, v in ipairs(commands) do
local f = v[eventName]
if f then
f(...)
table.insert(commandCache[eventName])
end
end
end
end
-- This function is used when needing to call a handle to all commands
local featureCache = {}
local function featureHandler(eventName, ...)
if featureCache[eventName] then
for k, v in ipairs(featureCache[eventName]) do
v[eventName](...)
end
else
for k, v in ipairs(features) do
local f = v[eventName]
if f then
f(...)
table.insert(featureCache[eventName])
end
end
end
end
-- One to control them all (handlers)
local function botHandler(eventName, ...)
commandHandler(eventName, ...)
featureHandler(eventName, ...)
end
-- Emitted after all shards and guilds are fully loaded.
client:on('ready', function()
botHandler("ready")
-- Pring a message to verify the bot is up and running!
p(string.format('Logged in as %s', client.user.username))
-- Set the defaults to every server, just in case
for k in pairs(client.guilds) do
perserverCheck(k)
end
Misc.saveJson("perserver.json")
end)
-- Emitted when a text channel message is created.
client:on('messageCreate', function(message)
-- ignore its own messages
if message.author == client.user then return end
-- Get the server's currrent prefix
local prefix = Misc.getPrefix(message)
local isCommand = string.startswith(message.content, prefix)
-- Run any of the bot's features before checking commands
for k, v in ipairs(features) do
if v.onCommandType ~= "ignore" or (not isCommand) then
local f = v.onMessage
local event = {}
if f then f(message, event) end
if event.success and v.onCommandType == "override" then
return
elseif event.success then
break
end
end
end
-- If the message does not start with the prefix, then ignore the message at this point
if not isCommand then return end
-- Get the command name and command object
local triggerName = Misc.getTriggerLC(message)
local command = commandsMAP[triggerName]
if command then
-- Activate the command if found/exists!
command.onCommand(message)
else
-- Otherwise, inform the user they had an incorrect command
Misc.replyEmbed(message, {title = "Error", text = "Command not found!\nCheck your spelling.", footer = "Use "..Misc.getPrefix(message).."help to see a list of commands"})
end
end)
-- Emitted when a guild is created from the perspective of the current user, usually after the client user joins a new one
client:on('guildCreate', function(guild)
botHandler("guildCreate", guild)
-- Set the defaults of the server
perserverCheck(guild.id)
Misc.saveJson("perserver.json")
end)
-- Emitted when a new user joins a guild.
client:on('memberJoin', function(member)
botHandler("memberJoin", member)
end)
-- Emitted when a user leaves a guild.
client:on('memberLeave', function(member)
botHandler("memberLeave", member)
end)
client:run("Bot "..token)
|
object_static_worldbuilding_building_echo_base_rec_sign = object_static_worldbuilding_building_shared_echo_base_rec_sign:new {
}
ObjectTemplates:addTemplate(object_static_worldbuilding_building_echo_base_rec_sign, "object/static/worldbuilding/building/echo_base_rec_sign.iff")
|
function Sulfuron_FireBolt(Unit, event, miscunit, misc)
Unit:FullCastSpellOnTarget(23331, Unit:GetClosestPlayer())
end
function Sulfuron_FireShield(Unit, event, miscunit, misc)
Unit:FullCastSpellOnTarget(24573, Unit:GetClosestPlayer())
end
function Sulfuron_Charge(Unit, event, miscunit, misc)
Unit:FullCastSpellOnTarget(36058, Unit:GetClosestPlayer())
end
function Sulfuron(Unit, Event, Miscunit, Misc)
Unit:RegisterEvent("Sulfuron_FireBolt", 9000, 0)
Unit:RegisterEvent("Sulfuron_FireShield", 13000, 0)
Unit:RegisterEvent("Sulfuron_Charge", 21000, 0)
Unit:SendChatMessage(12, 0, "You shall be consumed by flame!")
end
function Sulfuron_OnDied(Unit, Event)
Unit:SendChatMessage(12, 0, "S-s-o-o... cold.")
end
RegisterUnitEvent(20909, 1, "Sulfuron")
RegisterUnitEvent(20909, 4, "Sulfuron_OnDied")
|
local _, C = unpack(select(2, ...))
local BAR_FADER = {
fadeInAlpha = 1,
fadeInDuration = 0.2,
fadeOutAlpha = 0,
fadeOutDelay = 0,
fadeOutDuration = 0.2,
}
C.Bars = {
BarMargin = 6,
BarPadding = 0,
Bar1 = {
size = 34,
fader = nil
},
Bar2 = {
size = 34,
fader = nil
},
Bar3 = {
size = 34,
fader = nil
},
Bar4 = {
size = 34,
fader = BAR_FADER
},
Bar5 = {
size = 34,
fader = BAR_FADER
},
BarExtra = {
size = 52,
fader = nil
},
BarVehicle = {
size = 34,
fader = nil
},
BarPet = {
size = 30,
fader = nil
},
BarStance = {
size = 30,
fader = nil
},
}
|
-- -------------------------------------------------------------------------- --
-- 在输入法改变时进行提示
hs.keycodes.inputSourceChanged(function()
local currentSourceID = hs.keycodes.currentSourceID()
-- 如果当前 SourceID 和上一 SourceID 相同,不进行提示
if currentSourceID == lastSourceID then
return
end
-- 提示当前输入法
if (currentSourceID == "com.apple.keylayout.ABC") then
sourcePrompt = "ABC"
elseif (currentSourceID == "com.apple.inputmethod.SCIM.Shuangpin") then
sourcePrompt = "双拼"
elseif (currentSourceID == "com.apple.inputmethod.SCIM.ITABC") then
sourcePrompt = "拼音"
end
lastSourceID = currentSourceID
hs.alert.show(sourcePrompt, 0.8)
end)
|
object_tangible_loot_generic_deed_shared_generic_deed = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/loot/generic_deed/shared_generic_deed.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_loot_generic_deed_shared_generic_deed, "object/tangible/loot/generic_deed/shared_generic_deed.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_loot_generic_deed_shared_house_generic = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/loot/generic_deed/shared_house_generic.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_loot_generic_deed_shared_house_generic, "object/tangible/loot/generic_deed/shared_house_generic.iff")
------------------------------------------------------------------------------------------------------------------------------------
object_tangible_loot_generic_deed_shared_vehicle_generic = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/loot/generic_deed/shared_vehicle_generic.iff"
}
ObjectTemplates:addClientTemplate(object_tangible_loot_generic_deed_shared_vehicle_generic, "object/tangible/loot/generic_deed/shared_vehicle_generic.iff")
------------------------------------------------------------------------------------------------------------------------------------
|
-- MIT https://github.com/kikito/ansicolors.lua/blob/master/ansicolors.lua
local a={reset=0,bright=1,dim=2,underline=4,blink=5,reverse=7,hidden=8,black=30,red=31,green=32,yellow=33,blue=34,magenta=35,cyan=36,white=37,blackbg=40,redbg=41,greenbg=42,yellowbg=43,bluebg=44,magentabg=45,cyanbg=46,whitebg=47}local b=string.char(27)..'[%dm'local function c(d)return b:format(d)end;local function e(f)local g={}local d;for h in f:gmatch("%w+")do d=a[h]assert(d,"Unknown key: "..h)table.insert(g,c(d))end;return table.concat(g)end;local function i(f)f=string.gsub(f,"(%%{(.-)})",function(j,f)return e(f)end)return f end;local function ansicolors(f)f=tostring(f or'')return i('%{reset}'..f..'%{reset}')end
local fs = require("fs")
local json = require("json")
local timer = require("timer")
local http = require("coro-http")
local log = ""
local function Log(str)
print(ansicolors(str))
log = log .. str:gsub("(%%{(.-)})", "") .."\n"
end
local function WriteLog()
local data = log:sub(1, #log - 1) -- remove last \n
fs.writeFileSync("console.log", data)
end
local function Round(num, idp)
local mult = 10 ^ (idp or 0)
return math.floor(num * mult + 0.5) / mult
end
local function FormatTime(seconds, format)
if seconds == nil then return string.format(format or "%s:%s", "00", "00") end
local hours = math.floor(seconds / 3600)
local minutes = math.floor((seconds / 60) % 60)
seconds = Round(seconds % 60)
if minutes < 10 then minutes = "0".. minutes end
if seconds < 10 then seconds = "0".. seconds end
if hours < 1 then
return string.format(format or "%s:%s", minutes, seconds)
end
if hours < 10 then hours = "0".. hours end
return string.format(format or "%s:%s:%s", hours, minutes, seconds)
end
fs.mkdirSync("addons")
local downloaded = 0
local function Download(addon, cback)
Log(" - Downloading %{bright yellow}#".. addon.index .." %{reset yellow}".. addon.title .." %{bright}(".. addon.id ..")...")
local download_start_time = os.time()
local succ, res, response = pcall(http.request, "POST", "https://node05.steamworkshopdownloader.io/prod/api/download/request", {
{"Content-Type", "application/json"}
}, '{"publishedFileId":'.. addon.id ..', "collectionId":null, "hidden":false, "downloadFormat":"'.. (args[2] or "gmaextract") ..'", "autodownload":true}')
if succ then
if res.code == 200 then
local uuid = (json.decode(response) or {}).uuid
if uuid then
local i, timer_id = 0
timer_id = timer.setInterval(2000, function()
coroutine.wrap(function()
--i = i + 1
local succ, res, response = pcall(http.request, "POST", "https://node05.steamworkshopdownloader.io/prod/api/download/status", {
{"Content-Type", "application/json"}
}, '{"uuids": ["'.. uuid ..'"]}')
if succ == false then
Log(" - %{red}Error!%{reset} It looks like the server has down.")
timer.clearInterval(timer_id)
return cback()
end
local data = (json.decode(response) or {})[uuid]
if not data then
Log(" - %{red}Error!%{reset} Got no data from the server! It looks like the server has down.\n".. response)
timer.clearInterval(timer_id)
return cback()
end
if data.status == "prepared" then
Log(" - %{yellow}".. addon.title .." %{reset}is %{green}ready%{reset}! Downloading...")
timer.clearInterval(timer_id)
local succ, res, response = pcall(http.request, "GET", "https://".. data.storageNode .."/prod//storage/".. data.storagePath .."?uuid=".. uuid)
if succ then
if res.code == 200 then
Log(" - Download %{green}finished %{reset}in %{bright yellow}".. FormatTime(os.time() - download_start_time) .." %{reset}second(s)!")
fs.writeFileSync("addons/".. addon.id ..".zip", response)
downloaded = downloaded + 1
else
Log("- %{red}Error!%{reset} Node: %{bright yellow}".. data.storageNode .." %{reset}is down!\nResponse: ".. response .."\nResponse-code: ".. res.code)
end
else
Log("- %{red}Error!%{reset} Node: %{bright yellow}".. data.storageNode .." %{reset}is down!")
end
cback()
elseif data.status == "error" then
Log("- %{red}Error!%{reset} Status: ".. data.progressText)
timer.clearInterval(timer_id)
cback()
--elseif i == 60 then
-- Log(" - %{red}Error!%{reset} The file was prepared for more than a two minutes! It looks like the server has down.\n".. response)
-- timer.clearInterval(timer_id)
-- cback()
else
Log(" - w8 for the server job done...\nprogress: ".. data.progress .."% status: ".. data.status)
end
end)()
end)
else
Log(" - %{red}Error!%{reset} Cant get uuid!\nResponse:".. response)
cback()
end
else
Log(" - %{red}Error!%{reset} Game is not available or server is down!\nResponse: ".. response .."\nResponse-code: ".. res.code)
cback()
end
else
Log(" - %{red}Error!%{reset} Cant connect to the server!")
cback()
end
end
if not fs.existsSync("addons.json") then return Log(" - %{red}Error!%{reset} addons.json not found! Use this scraper to get your addons list:\n%{blue}https://gist.github.com/BrynM/c1b49804e53d7c406143a9ae40ed65ad") end
local addons = json.decode(fs.readFileSync("addons.json"))
local len, i, start_time = #addons, 0, os.time()
local function Main()
i = i + 1
if i > len then
Log(" - %{green}Done!%{reset} ".. downloaded .." of ".. len .." addons succfullied downloaded!")
WriteLog()
return
end
local addon = addons[i]
addon.index = i
addon.id = addon.link:match("[&?]id=([^&]*)")
if fs.existsSync("addons/".. addon.id ..".zip") then
downloaded = downloaded + 1
Main()
else
Download(addon, function()
Log(" - total elapsed time: ".. FormatTime(os.time() - start_time))
Log(" - w8 for 5 seconds to not hit the rate limits")
timer.setTimeout(5000, coroutine.wrap(Main))
end)
end
end
Log(" - Addons count %{bright yellow} ".. len)
coroutine.wrap(Main)()
|
file_player_group_list = io.open ("packages/"..GetPackageName().."/Data/player_group_list.json" ,"r+")
file_player_white_list = io.open ("packages/"..GetPackageName().."/Data/player_white_list.json" ,"r+")
file_player_ban = io.open ("packages/"..GetPackageName().."/Data/player_ban.json" ,"r+")
AddEvent("OnPackageStart", function()
DATA_PLAYER_GROUP = json_decode(file_player_group_list:read("*a"))
DATA_PLAYER_WHITE_LIST = json_decode(file_player_white_list:read("*a"))
DATA_PLAYER_BAN = json_decode(file_player_ban:read("*a"))
MessagePrint(2, "Data Generate")
end)
AddEvent("OnPackageStop", function()
UPDATE_ALL_DATA()
end)
function UPDATE_ALL_DATA()
UPDATE_WHITE_LIST()
UPDATE_GROUP_LIST()
UPDATE_BAN_LIST()
end
function UPDATE_WHITE_LIST()
clear("packages/"..GetPackageName().."/Data/player_white_list.json")
file_player_white_list = io.open ("packages/"..GetPackageName().."/Data/player_white_list.json" ,"r+")
file_player_white_list:write(json_encode(DATA_PLAYER_WHITE_LIST)):close()
MessagePrint(2, "Update white list !")
end
function UPDATE_GROUP_LIST()
clear("packages/"..GetPackageName().."/Data/player_group_list.json")
file_player_group_list = io.open ("packages/"..GetPackageName().."/Data/player_group_list.json" ,"r+")
file_player_group_list:write(json_encode(DATA_PLAYER_GROUP)):close()
MessagePrint(2, "Update Group list !")
end
function UPDATE_BAN_LIST()
clear("packages/"..GetPackageName().."/Data/player_ban.json")
file_player_ban = io.open ("packages/"..GetPackageName().."/Data/player_ban.json" ,"r+")
file_player_ban:write(json_encode(DATA_PLAYER_BAN)):close()
MessagePrint(2, "Update ban list !")
end
function clear(filename)
local fp = io.open( filename, "r" )
if fp == nil then return nil end
content = {}
i = 1;
for line in fp:lines() do
if i < 1 or i >= 1 + 1 then
content[#content+1] = line
end
i = i + 1
end
fp:close()
fp = io.open( filename, "w+" )
for i = 1, #content do
fp:write( string.format( "%s\n", content[i] ) )
end
fp:close()
end
|
ys = ys or {}
slot1 = ys.Battle.BattleConst.UnitType
ys.Battle.BattleCannonBulletFactory = singletonClass("BattleCannonBulletFactory", ys.Battle.BattleBulletFactory)
ys.Battle.BattleCannonBulletFactory.__name = "BattleCannonBulletFactory"
ys.Battle.BattleCannonBulletFactory.Ctor = function (slot0)
slot0.super.Ctor(slot0)
end
ys.Battle.BattleCannonBulletFactory.MakeBullet = function (slot0)
return slot0.Battle.BattleCannonBullet.New()
end
slot3 = Quaternion.Euler(-90, 0, 0)
ys.Battle.BattleCannonBulletFactory.onBulletHitFunc = function (slot0, slot1, slot2)
slot3 = slot0.GetDataProxy()
slot5 = slot0:GetBulletData().GetTemplate(slot4)
slot6 = nil
if slot2 == slot1.AIRCRAFT_UNIT or slot2 == slot1.AIRFIGHTER_UNIT then
slot6 = slot0.GetSceneMediator():GetAircraft(slot1)
elseif slot2 == slot1.PLAYER_UNIT then
slot6 = slot0.GetSceneMediator():GetCharacter(slot1)
elseif slot2 == slot1.ENEMY_UNIT then
slot6 = slot0.GetSceneMediator():GetCharacter(slot1)
end
if not slot6 then
return
end
slot8, slot9 = slot3:HandleDamage(slot4, slot7)
slot10 = nil
if slot6:GetGO() then
if slot8 then
slot11, slot12 = slot0.GetFXPool():GetFX(slot0:GetMissFXID())
slot13 = slot6:GetUnitData():GetBoxSize()
if math.random(0, 1) == 0 then
slot14 = -1
end
pg.EffectMgr.GetInstance():PlayBattleEffect(slot11, Vector3(slot15, 0, slot13.z * slot14):Add(slot6:GetPosition()).Add(slot16, slot12), true)
slot2.Battle.PlayBattleSFX(slot5.miss_sfx)
else
slot2.Battle.PlayBattleSFX(slot5.hit_sfx)
slot0:GetPosition() - slot6:GetPosition().x = slot0.GetPosition() - slot6.GetPosition().x * slot7:GetDirection()
slot0.GetPosition() - slot6.GetPosition().y = math.cos(math.deg2Rad * slot3 * slot6:GetTf().localRotation.eulerAngles.x) * slot0.GetPosition() - slot6.GetPosition().z
slot0.GetPosition() - slot6.GetPosition().z = 0
slot6:AddFX(slot0:GetFXID()).transform.localPosition:Add((slot0.GetPosition() - slot6.GetPosition()) / slot6:GetInitScale())
slot6.AddFX(slot0.GetFXID()).transform.localPosition = slot6.AddFX(slot0.GetFXID()).transform.localPosition
end
end
if slot10 and slot7:GetIFF() == slot3:GetFoeCode() then
slot10.transform.localRotation = Vector3(slot10.transform.localRotation.x, 180, slot10.transform.localRotation.z)
end
if slot4:GetPierceCount() <= 0 then
slot3:RemoveBulletUnit(slot4:GetUniqueID())
end
end
ys.Battle.BattleCannonBulletFactory.onBulletMissFunc = function (slot0)
slot1 = slot0:GetBulletData()
slot7, slot9 = slot0.GetFXPool():GetFX(slot0:GetMissFXID())
pg.EffectMgr.GetInstance():PlayBattleEffect(slot3, slot4:Add(slot0:GetPosition()), true)
slot1.Battle.PlayBattleSFX(slot1:GetTemplate().miss_sfx)
end
ys.Battle.BattleCannonBulletFactory.MakeModel = function (slot0, slot1, slot2, slot3, slot4)
slot5 = slot0:GetDataProxy()
slot6 = slot1:GetBulletData()
if not slot0:GetBulletPool():InstBullet(slot1:GetModleID(), function (slot0)
slot0:AddModel(slot0)
end) then
slot1.AddTempModel(slot1, slot0:GetTempGOPool():GetObject())
end
slot1:SetSpawn(slot2)
slot1:SetFXFunc(slot0.onBulletHitFunc, slot0.onBulletMissFunc)
slot0:GetSceneMediator():AddBullet(slot1)
end
return
|
--[[
Play a menu allowing the caller to accept, listen to, or re-record a
greeting.
]]
-- The name of the recorded greeting.
greeting = args(1)
-- Mailbox info.
mailbox = storage("login_settings", "mailbox_number")
mailbox_directory = profile.mailboxes_dir .. "/" .. mailbox
return
{
{
action = "play_phrase",
phrase = "greeting_options",
repetitions = profile.menu_repetitions,
wait = profile.menu_replay_wait,
keys = {
["1"] = "accept_greeting " .. greeting,
["2"] = "listen_to_greeting " .. greeting,
["3"] = "record_greeting " .. greeting,
},
},
{
action = "call_sequence",
sequence = "exit",
},
}
|
--[[
Small implementation of a JSON file reader.
]]
_libs = _libs or {}
_libs.json = true
_libs.tablehelper = _libs.tablehelper or require 'tablehelper'
_libs.stringhelper = _libs.stringhelper or require 'stringhelper'
local files = require 'filehelper'
_libs.filehelper = _libs.filehelper or (files ~= nil)
json = {}
-- Define singleton JSON characters that can delimit strings.
json.singletons = '{}[],:'
-- Takes a filename and tries to parse the JSON in it, after a validity check.
function json.read(file)
if type(file) == 'string' then
file = files.new(file)
end
if not file:exists() then
return json.error('File not found: \''..file.path..'\'')
end
return json.parse(file:read())
end
-- Returns nil as the parsed table and an additional error message with an optional line number.
function json.error(message, line)
if line == nil then
return nil, 'JSON error: '..message
end
return nil, 'JSON error, line '..line..': '..message
end
-- Returns a Lua value based on a string.
-- Recognizes all valid atomic JSON values: booleans, numbers, strings and null.
-- Object and error groupings will be eliminated during the classifying process.
-- If stripquotes is set to true, quote characters delimiting strings will be stripped.
function json.make_val(str, stripquotes)
stripquotes = true and (stripquotes ~= false)
str = str:trim()
if str == '' then
return nil
elseif str == 'true' then
return true
elseif str == 'false' then
return false
elseif str == 'null' then
return nil
elseif stripquotes and (str:enclosed('\'') or str:enclosed('"')) then
return str:slice(2, -2)
end
str = str:gsub('\\x([%w%d][%w%d])', string.char..tonumber-{16})
return tonumber(str) or str
end
-- Parsing function. Gets a string representation of a JSON object and outputs a Lua table or an error message.
function json.parse(content)
return json.classify(json.tokenize(content))
end
-- Tokenizer. Reads a string and returns an array of lines, each line with a number of valid JSON tokens. Valid tokens include:
-- * \w+ Keys or values
-- * : Key indexer
-- * , Value separator
-- * \{\} Dictionary start/end
-- * \[\] List start/end
function json.tokenize(content)
-- Tokenizer. Reads the string by characters and finds word boundaries, returning an array of tokens to be interpreted.
local current = nil
local tokens = T{T{}}
local quote = nil
local comment = false
local line = 1
for c in content:it() do
-- Only useful for a line count, to produce more accurate debug messages.
if c == "\n" then
line = line + 1
comment = false
tokens:append(T{})
end
-- If the quote character is set, don't parse but syntax, but instead just append to the string until the same quote character is encountered.
if quote ~= nil then
current = current..c
-- If the quote character is found, append the parsed string and reset the parsing values.
if quote == c then
tokens[line]:append(json.make_val(current))
current = nil
quote = nil
end
elseif not comment then
-- If the character is a singleton character, append the previous token and this one, reset the parsing values.
if json.singletons:contains(c) then
if current ~= nil then
tokens[line]:append(json.make_val(current))
current = nil
end
tokens[line]:append(c)
-- If a quote character is found, start a quoting session, see alternative condition.
elseif c == '"' or c == '\'' and current == nil then
quote = c
current = c
-- Otherwise, just append
elseif not c:match('%s') or current ~= nil then
-- Ignore comments. Not JSON conformant.
if c == '/' and current ~= nil and current:last() == '/' then
current = current:slice(1, -2)
comment = true
else
current = current or ''
current = current..c
end
end
end
end
return tokens
end
--
function json.classify(tokens)
-- Scopes and their domains:
-- * 'object': Object scope, delimited by '{' and '}' as well as global scope
-- * 'array': Array scope, delimited by '[' and ']'
local scopes = T{'object'}
-- Possible modes and triggers:
-- * 'new': After an opening brace, bracket, comma or at the start, expecting a new element
-- * 'key': After reading a key
-- * 'colon': After reading a colon
-- * 'value': After reading or having scoped a value (either an object, or an array for the latter)
local modes = T{'new'}
local parsed = T{T{}}
local keys = T{}
-- Classifier. Iterates through the tokens and assigns meaning to them. Determines scoping and creates objects and arrays.
for line, array in pairs(tokens) do
for pos, token in pairs(array) do
if token == '{' then
if modes:last() == 'colon' or modes:last() == 'new' and scopes:last() == 'array' then
parsed:append(T{})
scopes:append('object')
modes:append('new')
else
return json.error('Unexpected token \'{\'.', line)
end
elseif token == '}' then
if modes:last() == 'value' or modes:last() == 'new' then
modes:remove()
scopes:remove()
if modes:last() == 'colon' then
parsed:last(2)[keys:remove()] = parsed:remove()
elseif modes:last() == 'new' and scopes:last() == 'array' then
parsed:last():append(parsed:remove())
else
return json.error('Unexpected token \'}\'.', line)
end
modes[#modes] = 'value'
else
return json.error('Unexpected token \'}\'.', line)
end
elseif token == '[' then
if modes:last() == 'colon' or modes:last() == 'new' and scopes:last() == 'array' then
parsed:append(T{})
scopes:append('array')
modes:append('new')
else
return json.error('Unexpected token \'{\'.', line)
end
elseif token == ']' then
if modes:last() == 'value' or modes:last() == 'new' then
modes:remove()
scopes:remove()
if modes:last() == 'colon' then
parsed[#parsed-1][keys:remove()] = parsed:remove()
elseif modes:last() == 'new' and scopes:last() == 'array' then
parsed:last():append(parsed:remove())
else
return json.error('Unexpected token \'}\'.', line)
end
modes[#modes] = 'value'
else
return json.error('Unexpected token \'}\'.', line)
end
elseif token == ':' then
if modes:last() == 'key' then
modes[#modes] = 'colon'
else
return json.error('Unexpected token \':\'.', line)
end
elseif token == ',' then
if modes:last() == 'value' then
modes[#modes] = 'new'
else
return json.error('Unexpected token \',\'.', line)
end
elseif type(token):isin({'string', 'number'}) and modes:last() == 'new' and scopes:last() == 'object' then
keys:append(token)
modes[#modes] = 'key'
elseif type(token):isin({'boolean', 'number', 'string', 'null'}) then
if modes:last() == 'colon' then
parsed:last()[keys:remove()] = token
modes[#modes] = 'value'
elseif modes:last() == 'new' then
if scopes:last() == 'array' then
parsed:last():append(token)
modes[#modes] = 'value'
else
return json.error('Unexpected token \''..token..'\'.', line)
end
else
return json.error('Unexpected token \''..token..'\'.', line)
end
else
return json.error('Unkown token parsed. You should never see this. Token type: '..type(token), line)
end
end
end
if parsed:isempty() then
return json.error('No JSON found.')
end
if #parsed > 1 then
return json.error('Invalid nesting, missing closing tags.')
end
return parsed:remove()
end
return json
|
local event = require("__flib__.event")
local migration = require("__flib__.migration")
-- the migrations table - this will probably go into its own file
local migrations = {
-- each function will be run when upgrading from a version older than it
-- for example, if we were upgraing from 1.0.3 to 1.1.0, the last two functions would run, but not the first
["1.0.3"] = function()
-- logic specific to changes made in 1.0.3
end,
["1.0.4"] = function()
-- logic specific to changes made in 1.0.4
end,
["1.1.0"] = function()
-- logic specific to changes made in 1.1.0
end,
}
event.on_configuration_changed(function(e)
-- `on_config_changed` will check the event data and apply any migrations in the migrations table that need to be
if migration.on_config_changed(e, migrations) then
-- if the result is true, perform "generic migrations", i.e. refreshing a GUI with the latest item prototypes
-- this chunk will run on every call *except* for right after `on_init`, where the other chunk will run instead
end
-- if the result is false, that means that this mod was just added, so migrations shouldn't be performed
-- if you have code that absolutely must run despite this, put it here
end)
|
force(tonumber("5") + 1, 7) -- EXPECT SOURCE_CHANGE 1:16 "6"
|
-- commandline script that cleans a PATH variable by removing duplicates.
-- this belongs to 'setlua.bat' in case it is ran multiple times.
-- call as: "lua setlua_clean.lua <env-var-name>"
-- NOTE: this code must be able to run on ALL Lua versions
local var = assert(arg[1], "Name of environment variable to clean was not specified on the command line")
local path_value = os.getenv(var)
if path_value then
local entries = {}
local s,e
s = 1
e = path_value:find(";", s)
while s do
local entry = path_value:sub(s, (e or 0))
s = e
if s then s = s + 1 end
if not entries[entry] then
entries[entry] = true
entries[#entries+1] = entry
end
e = path_value:find(";", s)
end
print(table.concat(entries))
end
|
-- __ __
-- __ _____ ______ __/ /_ _______ _____ ____/ /_____ ____
-- / // / _ \/ __/ // / / // /___/ |/|/ / _ \/ __/ '_/ -_) __/
-- \_,_/_//_/_/ \_,_/_/\_, / |__,__/\___/_/ /_/\_\\__/_/
-- /___/
--
-- Name: unruly-worker
-- License: Unlicense
-- Maintainer: Duncan Marsh (slugbyte@slugbyte.com)
-- Repository: https://github.com/slugbyte/unruly-worker
--- create a key mapper that does nothing when trying
--- to map something to itself
--- @param mode string
--- @param noremap boolean
local create_map = function(mode, noremap)
--- a mapper that (mode, noremap)
-- @param lhs string
-- @param rhs string
return function(lhs, rhs)
if lhs == rhs then
return
end
vim.api.nvim_set_keymap(mode, lhs, rhs, {noremap = noremap})
end
end
-- noremap
local map = create_map('', true)
local nmap = create_map('n', true)
local imap = create_map('i', true)
local cmap = create_map('c', true)
local vmap = create_map('v', true)
-- remap
local remap_vmap = create_map('v', false)
local remap_map = create_map('', false)
local map_undisputed = function()
map('a', 'a')
map('A', 'A')
map('b', '%')
map('B', '"')
map('c', 'c')
map('C', 'C')
map('d', 'd')
map('D', 'D')
map('e', 'k')
map('E', 'e')
map('<C-w>e', '<C-w>k')
map('f', 'n')
map('F', 'N')
map('g', 'g')
map('G', 'G')
map('h', ';')
map('H', ',')
map('i', 'i')
map('I', 'I')
map('j', '\\')
map('J', '\\')
map('k', 'y')
map('K', 'Y')
map('l', 'o')
map('L', 'O')
map('m', "'")
map('M', 'm')
map('n', 'j')
map('N', 'J')
map('o', 'l')
map('O', '$')
map('<C-w>o', '<C-w>l')
map('<C-w>n', '<C-w>j')
map('p', 'p')
map('P', 'P')
map('q', 'q')
map('Q', '@')
map('r', 'r')
map('R', 'R')
map('s', 's')
map('S', 'S')
map('t', 'f')
map('T', 'F')
map('u', 'u')
map('U', '<c-r>')
map('v', 'v')
map('V', 'V')
map('w', 'w')
map('W', 'b')
map('x', 'x')
map('X', 'X')
map('y', 'h')
map('Y', '^')
map('<C-w>y', '<C-w>h')
map('z', 'z')
map('Z', 'Z')
map(':', ':')
map("'", ':')
map('"', '\\')
map('`', '\\')
map(',', '.')
map('.', '&')
map('/', '/')
map('?', '?')
map('@', 'zt')
map('#', 'zz')
map('$', 'zb')
map('~', '~')
map('%', '\\')
map('^', '\\')
map('&', '\\')
map('*', '\\')
map('-', '\\')
map('_', '\\')
map('+', '\\')
map('=', '\\')
map('|', '\\')
map(';', '\\')
map('(', '(')
map(')', ')')
map('[', '[')
map(']', ']')
map('>', '>')
map('<', '<')
nmap('<C-Down>', ':m .+1<CR>==')
nmap('<C-Up>', ':m .-2<CR>==')
imap('<C-Down>', ':m .+1<CR>==gi')
imap('<C-Up>', ':m .-2<CR>==gi')
vmap('<C-Down>', ":m '>+1<CR>gv=gv")
vmap('<C-Up>', ":m '<-2<CR>gv=gv")
cmap('<C-a>', '<home>')
cmap('<C-e>', '<end>')
map('ge', 'gk')
map('gn', 'gj')
end
--- add lsp specific mappings if enable is true
--- @param enable boolean
local map_lsp = function(enable)
if enable then
map('-', ':lua vim.diagnostic.goto_prev()<CR>')
map('_', ':lua vim.diagnostic.goto_next()<CR>')
map(';', ':lua vim.lsp.buf.hover()<CR>')
map('<c-f>', ':lua vim.lsp.buf.formatting()<CR>')
map('<c-a>', ':lua vim.lsp.buf.code_action()<CR>')
map('<c-r>', ':lua vim.lsp.buf.rename()<CR>')
map('<c-d>', ':split<CR>:lua vim.lsp.buf.definition()<CR>')
end
end
--- c will toggle comment if enable is true
--- @param enable boolean
local map_comment = function(enable)
if enable then
remap_map('c', 'gcc')
remap_map('C', 'gcip')
remap_vmap('c', 'gc')
remap_vmap('C', 'gc')
end
end
--- s will visual select if enable is true
--- @param enable boolean
local map_select = function(enable)
if enable then
map('s', 'viw')
map('S', 'vip')
end
end
--- e and n will navigate visualy if enable is true
--- @param enable boolean
local map_visual_navigate = function(enable)
if enable then
map('e', 'gk')
map('n', 'gj')
end
end
--- y and o will wrap lines if enable is true
--- @param enable boolean
local map_wrap_navigate = function(enable)
if enable then
vim.cmd('set ww+=<,>')
map('y', '<left>')
map('o', '<right>')
end
end
--- ' is equivalent to : if enable is true
--- @param enable boolean
local map_quote_command = function(enable)
if enable then
map("'", ':')
end
end
--- <C-(y,n,e,o)> nave windows if enable is true
--- @param enable boolean
local map_easy_window_navigate = function(enable)
if enable then
map('<c-n>', '<c-w>j')
map('<c-e>', '<c-w>k')
map('<c-y>', '<c-w>h')
map('<c-o>', '<c-w>l')
end
end
--- configure and map unruly worker keymap
--- @param config table
local function setup(config)
if vim.g.unruly_worker then
return
end
vim.g.unruly_worker = true
local context = {
enable_lsp_map = true,
enable_select_map = true,
enable_quote_command = true,
enable_easy_window_navigate = true,
enable_comment_map = false,
enable_wrap_navigate = false,
enable_visual_navigate = false,
}
if config then
context = vim.tbl_extend("force", context, config)
end
vim.g.unruly_worker_context = context
map_undisputed()
map_lsp(context.enable_lsp_map)
map_select(context.enable_select_map)
map_comment(context.enable_comment_map)
map_wrap_navigate(context.enable_wrap_navigate)
map_quote_command(context.enable_quote_command)
map_visual_navigate(context.enable_visual_navigate)
map_easy_window_navigate(context.enable_easy_window_navigate)
end
return {
setup = setup,
}
|
ENT.Base = "dronesrewrite_base"
ENT.Type = "anim"
//ENT.PrintName = "DF 'Defender'"
ENT.PrintName = "Defender"
ENT.Spawnable = true
ENT.AdminSpawnable = true
ENT.Category = "Drones Rewrite"
ENT.UNIT = "DF"
ENT.Weight = 350
ENT.Model = "models/dronesrewrite/defender/defender.mdl"
ENT.FirstPersonCam_pos = Vector(34, 0, 3)
ENT.RenderCam = false
ENT.ExplosionForce = 16
ENT.ExplosionAngForce = 1.7
ENT.DoExplosionEffect = "stinger_explode_drr"
ENT.HackValue = 3
ENT.Alignment = 0 --1.6
ENT.AlignmentRoll = 0.7
ENT.AlignmentPitch = 1.6
ENT.NoiseCoefficient = 0.4
ENT.AngOffset = 3
ENT.Speed = 7800
ENT.UpSpeed = 40000
ENT.RotateSpeed = 6
ENT.PitchOffset = 0.4
ENT.AllowYawRestrictions = true
ENT.YawMin = -60
ENT.YawMax = 60
ENT.PitchMin = -30
ENT.PitchMax = 50
ENT.KeysFuncs = DRONES_REWRITE.DefaultKeys()
ENT.Fuel = 120
ENT.MaxFuel = 120
ENT.HealthAmount = 110
ENT.DefaultHealth = 110
ENT.Sounds = {
PropellerSound = {
Name = "npc/manhack/mh_engine_loop1.wav",
Pitch = 120,
Level = 71,
Volume = 0.65
},
ExplosionSound = {
Name = "ambient/explosions/explode_7.wav",
Level = 85
}
}
ENT.Propellers = {
Damage = 1,
Health = 50,
HitRange = 18,
Scale = 0.9,
Model = "models/dronesrewrite/propellers/propeller2_4.mdl",
Info = {
Vector(-0.2, 48, 10),
Vector(-0.2, -48, 10),
Vector(-24.5, 0, 10)
}
}
ENT.Attachments = {
["Blaster"] = {
Pos = Vector(6, 13, -5)
},
["Shield"] = {
Pos = Vector(6, -13, -5)
}
}
ENT.Weapons = {
["Electric Blaster"] = {
Name = "Electric Blaster",
Attachment = "Blaster"
},
["Shield"] = {
Name = "Shield",
Attachment = "Shield"
}
}
ENT.Modules = DRONES_REWRITE.GetBaseModules()
|
local rex = require "rex_posix"
local _M = {}
local lexemes = {
{
type = "operator",
pattern = "[+-/*=^÷−%]"
},
{
type = "symbol",
pattern = "[a-zA-Z]+[a-zA-Z0-9]*"
},
{
type = "number",
pattern = "([0-9]+|[0-9]+\\.[0-9]*)"
},
{
type = "parenthesis",
pattern = "[()]"
},
{
type = "separator",
pattern = ","
},
{
type = "space",
pattern = "[[:space:]]",
-- We sort of don’t care about keeping track of spaces.
fake = true
}
}
function _M.lex(input)
local output = {}
local inputIndex = 1
while #input > 0 do
local matched
local i = 1
while i <= #lexemes and not matched do
local lexeme = lexemes[i]
local match = rex.match(input, "^" .. lexeme.pattern)
if match and match ~= "" then
input = input:sub(#match + 1, #input)
inputIndex = inputIndex + #match
if not lexeme.fake then
output[#output+1] = {
type = lexeme.type,
value = match
}
--print(
-- string.format("%10s", lexeme.type),
-- inputIndex, "'"..match.."'", "-", input)
end
matched = true
end
i = i + 1
end
if not matched then
io.stderr:write("<lexer.lex> Unexpected characters or smthing.\n")
return {
type = "error",
value = "unexpected character(s)",
at = inputIndex,
}
end
end
return output
end
setmetatable(_M, {
__call = function(self, ...)
return _M.lex(...)
end
})
return _M
|
-- Plugin: neokeys
-- Author: q9w
-- License: BSD 3-Clause License
-- Source: https://github.com/q9w/neokeys
local function setup()
local opts = {
nowait = true, noremap = true, silent = true
}
-- Set leader
vim.api.nvim_set_keymap('n', '<Space>', '<NOP>', opts)
vim.g.mapleader = ' '
-- telescope
vim.api.nvim_set_keymap('n', '<Leader><Space>', ':Telescope oldfiles<CR>', opts)
-- copy all
vim.api.nvim_set_keymap('n', '<Leader>a', ':%+y<CR>', opts)
-- back to buffer
vim.api.nvim_set_keymap('n', '<Leader>b', '<cmd>:BufferLinePick<CR>', opts)
-- commend
-- vim.api.nvim_set_keymap('n', '<Leader>c', '<Plug>kommentary_line_default', opts)
-- dashboard
vim.api.nvim_set_keymap('n', '<Leader>d', ':Dashboard<CR>', opts)
-- explorer
vim.api.nvim_set_keymap('n', '<Leader>e', '<cmd>NvimTreeToggle<CR>', opts)
-- no hl
vim.api.nvim_set_keymap('n', '<Leader>h', ':set hlsearch!<CR>', opts)
-- quit
vim.api.nvim_set_keymap('', '<Leader>q', '<cmd>qa<CR>', opts)
-- write
vim.api.nvim_set_keymap('', '<Leader>w', '<cmd>w<CR>', opts)
-- buffer keys
vim.api.nvim_set_keymap('', 'bb', "<cmd>:e #<cr>", opts)
vim.api.nvim_set_keymap('', 'bd', "<cmd>:bd<CR>", opts)
vim.api.nvim_set_keymap('', 'be', "<cmd>:BufferLineSortByExtension<CR>", opts)
vim.api.nvim_set_keymap('', 'bf', "<cmd>:BufferLineSortByDirectory<CR>", opts)
vim.api.nvim_set_keymap('', 'bh', "<cmd>:BufferLineMovePrev<CR>", opts)
vim.api.nvim_set_keymap('', 'bj', "<cmd>:BufferLinePick<CR>", opts)
vim.api.nvim_set_keymap('', 'bk', "<cmd>:BufferLinePick<CR>", opts)
vim.api.nvim_set_keymap('', 'bl', "<cmd>:BufferLineMoveNext<CR>", opts)
vim.api.nvim_set_keymap('', 'bn', "<cmd>:BufferLineCycleNext<CR>", opts)
vim.api.nvim_set_keymap('', 'bp', "<cmd>:BufferLineCyclePrev<CR>", opts)
-- e keys
vim.api.nvim_set_keymap('', 'ee', "<cmd>NvimTreeToggle<cr>", opts)
-- floaterm keys
vim.api.nvim_set_keymap('', 'wf', ":FloatermFirst<CR>", opts)
vim.api.nvim_set_keymap('t', 'wf', "<C-\\><C-n>:FloatermFirst<CR>", opts)
vim.api.nvim_set_keymap('', 'wn', ":FloatermNext<CR>", opts)
vim.api.nvim_set_keymap('t', 'wn', "<C-\\><C-n>:FloatermNext<CR>", opts)
vim.api.nvim_set_keymap('', 'wo', ":FloatermNew<CR>", opts)
vim.api.nvim_set_keymap('t', 'wo', "<C-\\><C-n>:FloatermNew<CR>", opts)
vim.api.nvim_set_keymap('', 'wp', ":FloatermPrev<CR>", opts)
vim.api.nvim_set_keymap('t', 'wp', "<C-\\><C-n>:FloatermPrev<CR>", opts)
vim.api.nvim_set_keymap('', 'wt', ":FloatermToggle<CR>", opts)
vim.api.nvim_set_keymap('t', 'wt', "<C-\\><C-n>:FloatermToggle<CR>", opts)
vim.api.nvim_set_keymap('', 'wx', ":FloatermKill<CR>", opts)
vim.api.nvim_set_keymap('t', 'wx', "<C-\\><C-n>:FloatermKill<CR>", opts)
vim.api.nvim_set_keymap('', 'wz', ":FloatermLast<CR>", opts)
vim.api.nvim_set_keymap('t', 'wz', "<C-\\><C-n>:FloatermLast<CR>", opts)
--lightspeed keys
vim.api.nvim_set_keymap('n', ';', '<Plug>Lightspeed_s<enter>', {})
vim.api.nvim_set_keymap('n', ',', '<Plug>Lightspeed_S<enter>', {})
-- neohop keys
vim.api.nvim_set_keymap('', 'h', "<cmd>lua require'hop'.hint_words()<cr>", opts)
--[[ vim.api.nvim_set_keymap('', 's', "<cmd>lua require'hop'.hint_char2()<cr>", opts)
vim.api.nvim_set_keymap('', 'S', "<cmd>lua require'hop'.hint_char1()<cr>", opts) ]]
vim.api.nvim_set_keymap('', 'l', "<cmd>lua require'hop'.hint_lines()<cr>", opts)
-- jump keys
vim.api.nvim_set_keymap('n', 'ja', "<cmd>:AnyJump<CR>", opts)
vim.api.nvim_set_keymap('x', 'ja', "<cmd>:AnyJumpVisual<CR>", opts)
vim.api.nvim_set_keymap('', 'jb', "<cmd>:AnyJumpBack<CR>", opts)
vim.api.nvim_set_keymap('', 'jl', "<cmd>:AnyJumpLastResults<CR>", opts)
-- Snap keys
vim.api.nvim_set_keymap('', 'sb', "<cmd>SnapBuffers<cr>", opts)
vim.api.nvim_set_keymap('', 'sf', "<cmd>SnapFiles<cr>", opts)
vim.api.nvim_set_keymap('', 'sg', "<cmd>SnapGrep<cr>", opts)
vim.api.nvim_set_keymap('', 'so', "<cmd>SnapOldFiles<cr>", opts)
vim.api.nvim_set_keymap('', 'ss', "<cmd>SnapGrepSelectedWord<cr>", opts)
vim.api.nvim_set_keymap('', 'sp', "<cmd>Spectre<cr>", opts)
-- Telescope keys
vim.api.nvim_set_keymap('', 'eb', "<cmd>Telescope current_buffer_fuzzy_find<cr>", opts)
vim.api.nvim_set_keymap('', 'ec', "<cmd>Telescope colorscheme<cr>", opts)
vim.api.nvim_set_keymap('', 'ed', "<cmd>Telescope lsp_document_diagnostics<cr>", opts)
vim.api.nvim_set_keymap('', 'ef', "<cmd>Telescope find_files<cr>", opts)
vim.api.nvim_set_keymap('', 'eg', "<cmd>Telescope live_grep<cr>", opts)
vim.api.nvim_set_keymap('', 'eh', "<cmd>Telescope command_history<cr>", opts)
vim.api.nvim_set_keymap('', 'em', "<cmd>Telescope marks<cr>", opts)
vim.api.nvim_set_keymap('', 'eo', "<cmd>Telescope oldfiles<cr>", opts)
vim.api.nvim_set_keymap('', 'ep', "<cmd>Telescope man_pages<cr>", opts)
vim.api.nvim_set_keymap('', 'er', "<cmd>Telescope registers<cr>", opts)
vim.api.nvim_set_keymap('', 'eR', "<cmd>lua require('spectre').open()<CR>", opts)
vim.api.nvim_set_keymap('', 'ew', "<cmd>Telescope lsp_workspace_diagnostics<cr>", opts)
-- window keys
vim.api.nvim_set_keymap('', 'ww', "<C-W>p", opts)
vim.api.nvim_set_keymap('', 'wh', "<C-W>h", opts)
vim.api.nvim_set_keymap('', 'wl', "<C-W>l", opts)
vim.api.nvim_set_keymap('', 'wj', "<C-W>j", opts)
vim.api.nvim_set_keymap('', 'wk', "<C-W>k", opts)
vim.api.nvim_set_keymap('', 'ws', "<C-W>s", opts)
vim.api.nvim_set_keymap('', 'wv', "<C-W>v", opts)
vim.api.nvim_set_keymap('', 'wc', "<C-W>c", opts)
vim.api.nvim_set_keymap('', 'wb', "<C-W>5<", opts)
vim.api.nvim_set_keymap('', 'we', "<C-W>5>", opts)
vim.api.nvim_set_keymap('', 'wu', ":resize +5<CR>", opts)
vim.api.nvim_set_keymap('', 'wd', ":resize -5<CR>", opts)
vim.api.nvim_set_keymap('', 'wi', "<C-W>=", opts)
-- x keys
vim.api.nvim_set_keymap('', 'x', "<NOP>", opts)
vim.api.nvim_set_keymap('', 'xx', "<Delete>", opts)
vim.api.nvim_set_keymap('', 'xr', "<C-r>", opts)
vim.api.nvim_set_keymap('!', 'xr', "<C-r>", opts)
vim.api.nvim_set_keymap('', 'xo', "<C-o>", opts)
vim.api.nvim_set_keymap('', 'xi', "<C-i>", opts)
vim.api.nvim_set_keymap('', 'xf', "<C-f>", opts)
vim.api.nvim_set_keymap('', 'xb', "<C-b>", opts)
vim.api.nvim_set_keymap('i', 'xp', '<ESC>"+pa', opts)
-- zen keys
vim.api.nvim_set_keymap('', 'zy', ":Goyo<CR>", opts)
vim.api.nvim_set_keymap('', 'zz', "<cmd>lua require'zen-mode'.toggle()<cr>", opts)
-- special keys
vim.api.nvim_set_keymap('!', 'jk', "<ESC>", opts)
vim.api.nvim_set_keymap('', 'jk', "<ESC>", opts)
vim.api.nvim_set_keymap('', 'H', "^", opts)
vim.api.nvim_set_keymap('', 'L', "$", opts)
vim.api.nvim_set_keymap('!', ';a', "<ESC>A", opts)
vim.api.nvim_set_keymap('', 'xh', "<LEFT>", opts)
vim.api.nvim_set_keymap('', 'xl', "<RIGHT>", opts)
vim.api.nvim_set_keymap('!', 'xh', "<LEFT>", opts)
vim.api.nvim_set_keymap('!', 'xl', "<RIGHT>", opts)
vim.api.nvim_set_keymap('', 'U', "<C-r>", opts)
vim.api.nvim_set_keymap('', 'wq', "ZZ", opts)
end
return {
setup = setup
}
|
--------------------------------------------------------------------
CLASS: ParticleSystem ()
:MODEL {
Field 'config' :asset( 'particle_.+' ) :getset( 'Config' );
Field 'inheritTransform' :boolean();
}
function ParticleSystem:__init( config )
self._system = false
-- self:setConfig( config )
self.emitters = {}
self.inheritTransform = false
end
function ParticleSystem:onAttach( entity )
if self._system then
if self.inheritTransform then
entity:_attachProp( self._system )
else
entity:_insertPropToLayer( self._system )
end
end
end
function ParticleSystem:onStart()
self:start()
end
function ParticleSystem:onDetach( entity )
self:stop()
for em in pairs( self.emitters ) do
em:stop()
end
end
function ParticleSystem:getConfig()
return self.configPath
end
function ParticleSystem:setConfig( configPath )
self.configPath = configPath
local config = mock.loadAsset( configPath )
self:setConfigData( config )
end
function ParticleSystem:setConfigData( config )
if self.config then
self:stop()
end
self.config = config
if config then
self._system = config:requestSystem()
if self._entity then
self._entity:_attachProp( self._system )
end
end
end
--------------------------------------------------------------------
function ParticleSystem:start()
if self._system then
return self._system:start()
end
end
function ParticleSystem:stop()
local sys = self._system
if sys then
sys:stop()
self._entity:_detachProp( sys )
self.config:_pushToPool( sys )
self._system = false
end
end
--------------------------------------------------------------------
function ParticleSystem:addEmitter( emitterName, start )
local config = self.config
if not config then
_error('particle has no config loaded')
return nil
end
--check dead emitter
local toRemove = {}
local emitters = self.emitters
for em in pairs( emitters ) do
if em:isDone() then
toRemove[ em ] = true
end
end
for em in pairs(toRemove) do
emitters[ em ] = nil
end
local em = emitterName and config:buildEmitter( emitterName )
if not em then
if emitterName then
_warn( 'particle has no emitter named', emitterName )
end
em = MOAIParticleTimedEmitter.new()
end
self._entity:_attachTransform( em )
em:setSystem( self._system )
self.emitters[ em ] = true
if start~= false then
em:forceUpdate()
em:start()
end
--TODO: attach as new component?
return em
end
function ParticleSystem:clearEmitters()
for em in pairs( self.emitters ) do
em:stop()
end
self.emitters = {}
end
function ParticleSystem:addForceToAll( force )
end
function ParticleSystem:addForceToState( stateName, force )
end
--------------------------------------------------------------------
mock.registerComponent( 'ParticleSystem', ParticleSystem )
|
--[[
ScatWave implementation of Scattering Network
Written by Edouard Oyallon
Team DATA ENS
Copyright 2015
]]
require 'torch'
scatwave = {} -- define the global ScatNet table
scatwave.network_2d_bfs = require 'scatwave.network_2d_bfs'
scatwave.network_2d_bfs_o = require 'scatwave.network_2d_bfs_o'
require 'scatwave.op_fft2d'
require 'scatwave.op_ifft2d'
require 'scatwave.op_down2d'
require 'scatwave.op_lp2dg'
require 'scatwave.op_modulus'
require 'scatwave.op_conv2d_infft'
require 'scatwave.op_subdc'
require 'scatwave.op_hist'
require 'scatwave.op_histsig0'
require 'scatwave.op_sigmoid0'
return scatwave
|
object_mobile_smuggler_fence_diala = object_mobile_shared_smuggler_fence_diala:new {
}
ObjectTemplates:addTemplate(object_mobile_smuggler_fence_diala, "object/mobile/smuggler_fence_diala.iff")
|
--
-- Created by IntelliJ IDEA. Copyright (C) 2017 Hanks
-- User: hanks
-- Date: 2017/5/26
-- A news app
--
require "import"
import "android.widget.*"
import "android.content.*"
import "android.view.View"
import "android.support.v4.view.ViewPager"
import "android.support.design.widget.TabLayout"
import "androlua.adapter.LuaFragmentPageAdapter"
local uihelper = require "uihelper"
local JSON = require "cjson"
local log = require "log"
local fragmentNews = require "163news/fragment_news"
-- create view table
local layout = {
LinearLayout,
layout_width = "fill",
layout_height = "fill",
orientation = "vertical",
statusBarColor = "#FF3333",
{
TabLayout,
id = "tab",
layout_width = "fill",
layout_height = "48dp",
background = "#FF3333",
},
{
FrameLayout,
layout_width = "fill",
layout_height = "fill",
{
ViewPager,
id = "viewPager",
layout_width = "fill",
layout_height = "fill",
},
{
View,
layout_width = "fill",
layout_height = "3dp",
background = "@drawable/shadow_line_top",
}
}
}
local data = {
titles = {},
fragments = {},
}
table.insert(data.fragments, fragmentNews.newInstance('BA8J7DG9wangning'))
table.insert(data.titles, '推荐')
table.insert(data.fragments, fragmentNews.newInstance('BBM54PGAwangning'))
table.insert(data.titles, '新闻')
table.insert(data.fragments, fragmentNews.newInstance('BD29LPUBwangning'))
table.insert(data.titles, '国内')
table.insert(data.fragments, fragmentNews.newInstance('BD29MJTVwangning'))
table.insert(data.titles, '国际')
table.insert(data.fragments, fragmentNews.newInstance('BA8D4A3Rwangning'))
table.insert(data.titles, '科技')
table.insert(data.fragments, fragmentNews.newInstance('BAI6I0O5wangning'))
table.insert(data.titles, '手机')
table.insert(data.fragments, fragmentNews.newInstance('BAI67OGGwangning'))
table.insert(data.titles, '军事')
table.insert(data.fragments, fragmentNews.newInstance('BA8E6OEOwangning'))
table.insert(data.titles, '体育')
table.insert(data.fragments, fragmentNews.newInstance('BCR1UC1Qwangning'))
table.insert(data.titles, '社会')
table.insert(data.fragments, fragmentNews.newInstance('BA10TA81wangning'))
table.insert(data.titles, '娱乐')
table.insert(data.fragments, fragmentNews.newInstance('BA8FF5PRwangning'))
table.insert(data.titles, '教育')
table.insert(data.fragments, fragmentNews.newInstance('BAI6RHDKwangning'))
table.insert(data.titles, '图片')
local adapter = LuaFragmentPageAdapter(activity.getSupportFragmentManager(),
luajava.createProxy("androlua.adapter.LuaFragmentPageAdapter$AdapterCreator", {
getCount = function() return #data.fragments end,
getItem = function(position)
position = position + 1
return data.fragments[position]
end,
getPageTitle = function(position)
position = position + 1
return data.titles[position]
end
}))
local function unicode_to_utf8(convertStr)
local t = {}
for a in string.gmatch(convertStr, '\\u([0-9a-z][0-9a-z][0-9a-z][0-9a-z])') do
if #a == 4 then
local n = tonumber(a, 16)
assert(n, "String decoding failed: bad Unicode escape " .. a)
local x
if n < 0x80 then
x = string.char(n % 0x80)
elseif n < 0x800 then
-- [110x xxxx] [10xx xxxx]
x = string.char(0xC0 + (math.floor(n / 64) % 0x20), 0x80 + (n % 0x40))
else
-- [1110 xxxx] [10xx xxxx] [10xx xxxx]
x = string.char(0xE0 + (math.floor(n / 4096) % 0x10), 0x80 + (math.floor(n / 64) % 0x40), 0x80 + (n % 0x40))
end
convertStr = string.gsub(convertStr, '\\u' .. a, x)
end
end
return convertStr
end
function onCreate(savedInstanceState)
activity.setContentView(loadlayout(layout))
viewPager.setAdapter(adapter)
viewPager.setOffscreenPageLimit(#data.fragments)
viewPager.setCurrentItem(0)
tab.setSelectedTabIndicatorColor(0xffffffff)
tab.setTabTextColors(0x88ffffff, 0xffffffff)
tab.setTabMode(TabLayout.MODE_SCROLLABLE)
tab.setTabGravity(TabLayout.GRAVITY_CENTER)
tab.setupWithViewPager(viewPager)
end
|
--- Item
-- @classmod Item
local Item = {
_class = "Item"
}
setmetatable(Item, {__index = require("stdlib/data/data")})
function Item:_get(item, item_type)
return self:get(item, item_type)
end
Item:set_caller(Item._get)
Item._mt = {
type = "item",
__index = Item,
__call = Item._get,
__tostring = Item.tostring
}
return Item
|
local lpeg = require('lpeg')
-- example CSV grammar from http://www.inf.puc-rio.br/~roberto/lpeg/#CSV
local csv_field = '"' * lpeg.Cs(((lpeg.P(1) - '"') + lpeg.P'""' / '"')^0) * '"' +
lpeg.C((1 - lpeg.S',\n"')^0)
local csv_record = csv_field * (',' * csv_field)^0 * (lpeg.P'\n' + -1)
local headers
function process_record(tag, timestamp, record)
if not headers then
headers = { lpeg.match(csv_record, record.log) }
-- return -1 to drop the header
return -1, timestamp, record
end
local data = {}
local fields = { lpeg.match(csv_record, record.log) }
for index, header in ipairs(headers) do
data[header] = fields[index]
end
-- return "2" to leave timestamp intact
return 2, 0, data
end
|
class("SelectFleetCommanderCommand", pm.SimpleCommand).execute = function (slot0, slot1)
slot2 = slot1:getBody()
slot5 = slot2.commanderId
slot6 = slot2.callback
slot7 = getProxy(FleetProxy):getFleetById(slot3)
slot9 = slot7:getCommanders()
if not slot7:getCommanderByPos(slot4) or slot8.id ~= slot5 then
slot10 = getProxy(CommanderProxy):getCommanderById(slot5)
for slot14, slot15 in pairs(slot9) do
if slot15.groupId == slot10.groupId and slot14 ~= slot4 and slot5 ~= slot15.id then
pg.TipsMgr.GetInstance():ShowTips(i18n("commander_can_not_select_same_group"))
return
end
end
end
function slot10(slot0)
for slot5, slot6 in ipairs(slot1) do
if slot6.fleetId ~= slot0 and slot6.commanderId == slot0 then
return true, slot6
end
end
return false
end
function slot11(slot0)
if (slot0 == 2 and 1) or 2[] and slot2.id == slot0 then
return true, slot1
end
return false
end
slot12 = {}
slot13 = true
slot14, slot15 = slot10(slot5)
if slot14 then
table.insert(slot12, function (slot0)
pg.MsgboxMgr.GetInstance():ShowMsgBox({
content = i18n("comander_repalce_tip", Fleet.DEFAULT_NAME[slot0.fleetId], (slot0.pos == 1 and i18n("commander_main_pos")) or i18n("commander_assistant_pos")),
onYes = function ()
pg.m02:sendNotification(GAME.COOMMANDER_EQUIP_TO_FLEET, {
commanderId = 0,
fleetId = slot0.fleetId,
pos = slot0.pos,
callback = pg.m02
})
end,
onNo = function ()
slot0 = false
slot1()
end
})
end)
end
slot16, slot17 = slot11(slot5)
if slot16 then
table.insert(slot12, function (slot0)
pg.m02:sendNotification(GAME.COOMMANDER_EQUIP_TO_FLEET, {
commanderId = 0,
fleetId = slot0,
pos = pg.m02.sendNotification,
callback = slot0
})
end)
end
table.insert(slot12, function (slot0)
if slot0 then
pg.m02:sendNotification(GAME.COOMMANDER_EQUIP_TO_FLEET, {
fleetId = slot1,
pos = slot2,
commanderId = slot3,
callback = function (slot0)
slot0()
end
})
else
slot0()
end
end)
seriesAsync(slot12, slot6)
end
return class("SelectFleetCommanderCommand", pm.SimpleCommand)
|
--[[
Use the source, Luke!
Copyright (C) 2014-2021 Gary V. Vaughan
]]
local _ENV = require 'std.normalize' {
'luke._base',
'luke.configure',
'luke.environment',
'luke.platforms',
'std.functional',
'type.context-manager',
}
local function has_anykey(t, keylist)
return any(map(keylist, function(k)
return t[k] ~= nil
end))
end
local function isconfig(x)
return istable(x) and has_anykey(x, configure)
end
local function collect_configs(luke, modulename, configs)
configs = configs or {}
for k, v in next, luke do
if isconfig(v) then
append(configs, {t=luke, k=k, module=modulename})
elseif istable(v) then
if k == 'modules' or k == 'external_dependencies' then
for name, rules in next, v do
collect_configs(rules, name, configs)
end
else
collect_configs(v, modulename, configs)
end
end
end
return configs
end
local function deepcopy(t)
return mapvalues(t, function(v)
return case(type(v), {
['table'] = function() return deepcopy(v) end,
v,
})
end)
end
local weighting = setmetatable(copy(configure), {
__call = function(self, config)
local t = config.t[config.k]
for i = 1, len(self) do
if t[self[i]] ~= nil then
return i
end
end
end
})
local function config_cmp(a, b)
return weighting(a) < weighting(b)
end
local function fill_templates(env, src, dest)
with(File(dest, 'w'), function(cm)
for line in lines(src) do
cm:write(expand(env, line) .. '\n')
end
end)
return dest
end
local function rewrite_template_files(L, env, source)
return case(source, {
['(.+)%.in'] = function(r)
L.write('creating ' .. r .. '\n')
return fill_templates(env, r .. '.in', r)
end,
source,
})
end
local function collect_variables(luke, variables)
for k, v in next, luke do
if k == 'external_dependencies' then
map(keys(v), function(name)
local rootdir = concat{'$', name, '_DIR'}
variables[name .. '_DIR'] = '/usr'
variables[name .. '_BINDIR'] = rootdir .. '/bin'
variables[name .. '_INCDIR'] = rootdir .. '/include'
variables[name .. '_LIBDIR'] = rootdir .. '/lib'
end)
elseif istable(v) then
collect_variables(v, variables)
end
end
return variables
end
local function normalize_configs(config)
return cond({
[not istable(config)] = config,
}, {
[not isconfig(config)] = function()
return mapvalues(config, normalize_configs)
end,
}, {
[true] = function()
local keymap = {
include = 'includes',
prog = 'progs',
library = 'libraries',
}
return foldkeys(keymap, config, function(a, b)
local r = istable(a) and copy(a) or {a}
b = istable(b) and b or {b}
return reduce(b, r, function(v)
append(r, v)
end)
end)
end,
})
end
local function normalize_rules(rules)
return case(type(rules), {
['nil'] = nop,
['string'] = function()
return {sources={rules}}
end,
['table'] = function()
if len(rules) > 0 then
return {sources=rules}
elseif isstring(rules.sources) then
return merge({sources = {rules.sources}}, normalize_configs(rules))
end
return normalize_configs(rules)
end,
function(v)
fatal("unsupported rule type '%s'", v)
end,
})
end
local function unwrap_external_dependencies(luke)
if istable(luke.external_dependencies) then
for prefix, config in next, luke.external_dependencies do
-- `config={}` for unsupported, `config={library=''}` for no library required
if istable(config) and next(config) and config.library ~= '' then
luke.incdirs = append(luke.incdirs or {}, format('$%s_INCDIR', prefix))
luke.libdirs = append(luke.libdirs or {}, format('$%s_LIBDIR', prefix))
luke.libraries = append(luke.libraries or {}, config.library)
end
end
luke.external_dependencies = nil
end
return luke
end
return {
loadluke = function(filename)
local content, err = slurp(File(filename))
if content == nil then
return nil, err
end
local r = {}
local chunk, err = loadstring(content, filename, r)
if chunk == nil then
return nil, "Error loading file: " .. err
end
local ok, err = pcall(chunk)
if not ok then
return nil, "Error running file: " .. err
end
r = filter_platforms(r)
r.external_dependencies = normalize_configs(r.external_dependencies)
r.ldocs = normalize_rules(r.ldocs)
r.modules = mapvalues(r.modules, normalize_rules)
return r
end,
collect_variables = function(luke)
return collect_variables(luke, {})
end,
run_configs = function(L, env, luke)
local r = deepcopy(luke)
local all_configs = collect_configs(r)
sort(all_configs, config_cmp)
map(all_configs, function(config)
config.t[config.k] = configure(L, env, config.t[config.k], config.module)
end)
return unwrap_external_dependencies(r)
end,
run_templates = function(L, env, luke)
local r = copy(luke)
local rewrite = bind(rewrite_template_files, {L, env})
r.modules = mapvalues(r.modules, function(rules)
rules.sources = map(rules.sources, rewrite)
end)
if r.ldocs then
r.ldocs.sources = map(r.ldocs.sources, rewrite)
end
return r
end,
}
|
local name = "car_road_master"
local definition = ...
definition.description = "Road Master car"
definition.inventory_image = "inv_car_brown.png"
definition.wield_image = "inv_car_brown.png"
definition.textures = {"road_master.png"}
vehicle_mash.register_vehicle("vehicle_mash:"..name, definition)
|
-- !!!!!!!!!!!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!!!!!!!!!!
-- This file is automaticly generated. Don't edit manualy!
-- !!!!!!!!!!!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!!!!!!!!!!
---@class C_BlackMarketInfo
C_BlackMarketInfo = {}
|
local broadsock_client
local broadsock_server
local mock = require "deftest.mock"
local mock_factory = require "test.mock_factory"
return function()
describe("broadsock client and server", function()
local function create_callbacks()
local callbacks = {}
function callbacks.on_custom_message() end
function callbacks.on_connected() end
function callbacks.on_disconnect() end
mock.mock(callbacks)
return callbacks
end
local function nop() end
before(function()
package.loaded["broadsock.client.broadsock"] = nil
package.loaded["broadsock.server.broadsock"] = nil
broadsock_client = require "broadsock.client.broadsock"
broadsock_server = require "broadsock.server.broadsock"
--mock_socket.mock()
mock_factory.mock()
end)
after(function()
--mock_socket.unmock()
mock_factory.unmock()
broadsock_server.stop()
end)
it("should connect clients and let them know of each other", function()
local ok, err = broadsock_server.start(5000)
assert(ok and not err)
local callbacks1 = create_callbacks()
local client1, err = broadsock_client.create("127.0.0.1", 5000, callbacks1.on_custom_message, callbacks1.on_connected, callbacks1.on_disconnect)
assert(client1 and not err)
local callbacks2 = create_callbacks()
local client2, err = broadsock_client.create("127.0.0.1", 5000, callbacks2.on_custom_message, callbacks2.on_connected, callbacks2.on_disconnect)
assert(client2 and not err)
-- handle the client1 and client2 connections
broadsock_server.update() -- handle client1 connect
assert(broadsock_server.client_count() == 1)
broadsock_server.update() -- handle client2 connect
assert(broadsock_server.client_count() == 2)
-- update the first client
-- it will receive a CONNECT_SELF and a CONNECT_OTHER
client1.update()
assert(callbacks1.on_connected.calls == 1)
assert(client1.client_count() == 2)
-- update the second client
-- it will receive a CONNECT_SELF but no CONNECT_OTHER since when
-- the first client was created and connected the server didn't
-- know of any other clients and could thus not send a CONNECT_OTHER
-- message
client2.update()
assert(callbacks2.on_connected.calls == 1)
assert(client2.client_count() == 1)
end)
it("should send game object positions to other clients", function()
local ok, err = broadsock_server.start(5000)
assert(ok and not err)
local callbacks1 = create_callbacks()
local client1, err = broadsock_client.create("127.0.0.1", 5000, callbacks1.on_custom_message, callbacks1.on_connected, callbacks1.on_disconnect)
assert(client1 and not err)
local callbacks2 = create_callbacks()
local client2, err = broadsock_client.create("127.0.0.1", 5000, callbacks2.on_custom_message, callbacks2.on_connected, callbacks2.on_disconnect)
assert(client2 and not err)
client1.register_factory("/factories#type1", "type1")
client2.register_factory("/factories#type1", "type1")
local id1 = factory.create("/factories#type1", vmath.vector3(100, 100, 0))
client1.register_gameobject(id1, "type1")
local id2 = factory.create("/factories#type1", vmath.vector3(200, 200, 0))
client2.register_gameobject(id2, "type1")
broadsock_server.update() -- handle client1 connect
broadsock_server.update() -- handle client2 connect
client1.update() -- connected, send position of go
client2.update() -- connected, send position of go
broadsock_server.update() -- receive positions, send to others
client1.update() -- receive other go
client2.update() -- receive other go
assert(#mock_factory.ids == 4)
end)
end)
end
|
local IHud = require("api.gui.hud.IHud")
local IInput = require("api.gui.IInput")
local InputHandler = require("api.gui.InputHandler")
local WidgetContainer = require("api.gui.WidgetContainer")
local MainHud = class.class("MainHud", IHud)
MainHud:delegate("input", IInput)
function MainHud:init()
self.input = InputHandler:new()
self.widgets = WidgetContainer:new()
end
function MainHud:default_z_order()
return 100000 -- Gui.LAYER_Z_ORDER_HUD
end
function MainHud:reset()
end
function MainHud:on_theme_switched()
end
function MainHud:relayout(x, y, width, height)
self.width = width or self.width
self.height = height or self.height
self.x = x or self.x
self.y = y or self.y
self.widgets:relayout(self.x, self.y, self.width, self.height)
end
function MainHud:refresh(player)
if player == nil then
return
end
self.widgets:refresh(player)
end
function MainHud:draw(draw_x, draw_y)
self.widgets:draw(draw_x, draw_y)
end
function MainHud:update(dt)
self.widgets:update(dt)
if self.widgets.updated and self.x then
self.widgets:relayout(self.x, self.y, self.width, self.height)
self.widgets.updated = false
end
end
return MainHud
|
local function ChangeUser(msg)
local text = msg.content_.text_
if ChatType == 'sp' or ChatType == 'gp' then
if text then
tdcli_function({ID = "GetUser",user_id_ = msg.sender_user_id_},function(arg,result)
if result.id_ then
local Rio = DevRio:get("RaumoTeam:User"..result.id_)
if not result.username_ then
if Rio then
Dev_Rio(msg.chat_id_, msg.id_, 1, "حذف معرفه خمطو بسرعه، 😹💔 \nهذا معرفه @"..Rio.."", 1, 'html')
DevRio:del("RaumoTeam:User"..result.id_)
end
end
if result.username_ then
if Rio and Rio ~= result.username_ then
local Rio_text = {
'معرفك الجديد عشره بربع محد ياخذه😹💔',
"هاها غيرت معرفك نشروك بقناة فضايح😹💔💭",
"معرفك الجديد حلو منين خامطه؟!🤤♥️",
"معرفك القديم @"..result.username_.." ضمه بقناة لاينبعص، 😹♥️",
}
Rios = math.random(#Rio_text)
Dev_Rio(msg.chat_id_, msg.id_, 1, Rio_text[Rios], 1, 'html')
end
DevRio:set("RaumoTeam:User"..result.id_, result.username_)
end
end
end,nil)
end
end
end
return {
Raumo = ChangeUser
}
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_anim" )
ENT.PrintName = "TV: Label"
ENT.Author = "raubana"
ENT.Information = ""
ENT.Category = "Tunnel Vision"
ENT.Editable = true
ENT.Spawnable = true
ENT.AdminOnly = true
ENT.RenderGroup = RENDERGROUP_OPAQUE
function ENT:SetupDataTables()
self:NetworkVar( "Bool", 0, "Editable", { KeyName = "editable", Edit = { type = "Boolean" } } )
self:NetworkVar( "Bool", 1, "Pickupable", { KeyName = "pickupable", Edit = { type = "Boolean" } } )
self:NetworkVar( "String", 0, "Message", { KeyName = "message", Edit = { type = "String" } } )
end
|
---------------------------------------------------------------------------------------------------
-- Proposal: SDL 0180 Broaden Choice Uniqueness
--
-- Description:
-- Mobile shall be able to send a CreateInteractionChoiceSet RPC where two choices within the
-- choice set have identical menuName values.
---------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local runner = require('user_modules/script_runner')
local common = require('test_scripts/Smoke/commonSmoke')
--[[ Test Configuration ]]
runner.testSettings.isSelfIncluded = false
--[[ Local Variables ]]
local cics1Params = {
interactionChoiceSetID = 499,
choiceSet = {
{
choiceID = 42,
menuName = "menuName"
},
{
choiceID = 43,
menuName = "menuName"
}
}
}
local cics2Params = {
interactionChoiceSetID = 500,
choiceSet = {
{
choiceID = 44,
menuName = "menuName"
},
{
choiceID = 45,
menuName = "unique"
}
}
}
local cics3Params = {
interactionChoiceSetID = 501,
choiceSet = {
{
choiceID = 46,
menuName = "menuName"
},
{
choiceID = 47,
menuName = "unique"
}
}
}
local performInteractionParams = {
initialText = "StartPerformInteraction",
interactionMode = "MANUAL_ONLY",
interactionChoiceSetIDList = { 500, 501 }
}
local performInteraction2Params = {
initialText = "StartPerformInteraction",
interactionMode = "MANUAL_ONLY",
interactionChoiceSetIDList = { 499, 500, 501 }
}
--[[ Local Functions ]]
local function createInteractionChoiceSet(pParams)
local cid = common.getMobileSession():SendRPC("CreateInteractionChoiceSet", pParams)
common.getMobileSession():ExpectResponse(cid, { success = true, resultCode = "SUCCESS" })
end
local function performInteraction(pParams)
local cid = common.getMobileSession():SendRPC("PerformInteraction", pParams)
common.getHMIConnection():ExpectRequest("UI.PerformInteraction")
:Do(function(_, data)
common.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", {})
end)
common.getHMIConnection():ExpectRequest("VR.PerformInteraction")
:Do(function(_, data)
common.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", {})
end)
common.getMobileSession():ExpectResponse(cid, { success = true, resultCode = "SUCCESS" })
end
--[[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", common.preconditions)
runner.Step("Update Preloaded PT", common.updatePreloadedPT)
runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start)
runner.Step("Register App", common.registerApp)
runner.Step("Activate App", common.activateApp)
runner.Title("Test")
runner.Step("CreateInteractionChoiceSet1 with dupe menuNames", createInteractionChoiceSet, { cics1Params })
runner.Step("CreateInteractionChoiceSet2 with (menuName, unique)", createInteractionChoiceSet, { cics2Params })
runner.Step("CreateInteractionChoiceSet3 again with (menuName, unique)", createInteractionChoiceSet, { cics3Params })
runner.Step("PerformInteraction with choice set 2 and 3", performInteraction, { performInteractionParams })
runner.Step("PerformInteraction with all choice sets", performInteraction, { performInteraction2Params })
runner.Title("Postconditions")
runner.Step("Stop SDL", common.postconditions)
|
local code_action_cache = {}
local ctx
local function preview(action)
local res = {}
local syntax
local function render_preview(lines, hl_syn)
vim.fn['clap#preview#show_lines'](lines, hl_syn, -1)
vim.fn['clap#preview#highlight_header']()
end
if action.edit ~= nil and action.edit.changes ~= nil then
for file, x in pairs(action.edit.changes) do
syntax = vim.fn['clap#ext#into_filetype'](tostring(file))
table.insert(res,tostring(file))
for _, line in ipairs(x) do
table.insert(res,line.newText)
end
end
end
if action.command ~= nil then
print('action.command ~= nil\n', vim.inspect(action.command))
-- todo?
end
if #res ~= 0 then render_preview(res, syntax or 'txt') end
end
local function get_index(input)
return tonumber(string.match(input, "^(%d*)"))
end
local function on_move_impl()
local curline = vim.api.nvim_call_dict_function('g:clap.display' , 'getcurline', {})
local index = get_index(curline)
preview(code_action_cache[index])
end
local function codeaction_sink(selected)
local index = get_index(selected)
local action = code_action_cache[index]
if action.edit then
vim.lsp.util.apply_workspace_edit(action.edit)
end
if action.command then
local command = type(action.command) == 'table' and action.command or action
local fn = vim.lsp.commands[command.command]
if fn then
fn(command, ctx)
else
vim.lsp.buf.execute_command(action.command)
end
end
end
-- codeAction event callback handler
-- use customSelectionHandler for defining custom way to handle selection
local code_action_handler = function(_, actions, ctx_l, _, _)
ctx = ctx_l
if actions == nil or vim.tbl_isempty(actions) then
print("No code actions available")
return
end
local data = {}
for i, action in ipairs (actions) do
code_action_cache[i] = action
local title = action.title:gsub('\r\n', '\\r\\n')
title = title:gsub('\n','\\n')
title = title:gsub(string.char(0),'')
data[i] = i .. ': ' .. title
end
local provider = {
source = data,
sink = codeaction_sink,
on_move = on_move_impl,
on_enter = on_move_impl,
-- syntax = 'clap-lsp-symbol'
}
vim.fn['clap#run'](provider)
vim.api.nvim_input('<ESC>')
end
return {
code_action_handler = code_action_handler,
}
|
object_draft_schematic_furniture_furniture_chair_jedi_dark_s01 = object_draft_schematic_furniture_shared_furniture_chair_jedi_dark_s01:new {
}
ObjectTemplates:addTemplate(object_draft_schematic_furniture_furniture_chair_jedi_dark_s01, "object/draft_schematic/furniture/furniture_chair_jedi_dark_s01.iff")
|
-- Created by Elfansoer
--[[
Ability checklist (erase if done/checked):
- Scepter Upgrade
- Break behavior
- Linken/Reflect behavior
- Spell Immune/Invulnerable/Invisible behavior
- Illusion behavior
- Stolen behavior
]]
--------------------------------------------------------------------------------
modifier_hoodwink_acorn_shot_lua_thinker = class({})
--------------------------------------------------------------------------------
-- Classifications
--------------------------------------------------------------------------------
-- Initializations
function modifier_hoodwink_acorn_shot_lua_thinker:OnCreated( kv )
self.caster = self:GetCaster()
self.parent = self:GetParent()
self.ability = self:GetAbility()
-- references
self.projectile_name = "particles/units/heroes/hero_hoodwink/hoodwink_acorn_shot_tracking.vpcf"
self.projectile_speed = self:GetAbility():GetSpecialValueFor( "projectile_speed" )
self.bounces = self:GetAbility():GetSpecialValueFor( "bounce_count" )+1
self.damage = self:GetAbility():GetSpecialValueFor( "bonus_damage" )
self.delay = self:GetAbility():GetSpecialValueFor( "bounce_delay" )
self.range = self:GetAbility():GetSpecialValueFor( "bounce_range" )
if not IsServer() then return end
-- ability properties
self.abilityDamageType = self:GetAbility():GetAbilityDamageType()
self.abilityTargetTeam = self:GetAbility():GetAbilityTargetTeam()
self.abilityTargetType = self:GetAbility():GetAbilityTargetType()
self.abilityTargetFlags = self:GetAbility():GetAbilityTargetFlags()
-- precache projectile
self.info = {
-- Target = self.target,
-- Source = self.parent,
Ability = self.ability,
EffectName = self.projectile_name,
iMoveSpeed = self.projectile_speed,
bDodgeable = true, -- Optional
iSourceAttachment = DOTA_PROJECTILE_ATTACHMENT_HITLOCATION,
bVisibleToEnemies = true, -- Optional
bProvidesVision = true, -- Optional
iVisionRadius = 400, -- Optional
iVisionTeamNumber = self.caster:GetTeamNumber(), -- Optional
ExtraData = {
thinker = self.parent:entindex()
}
}
-- Start bounce in next frame
self:StartIntervalThink( 0 )
end
function modifier_hoodwink_acorn_shot_lua_thinker:OnRefresh( kv )
end
function modifier_hoodwink_acorn_shot_lua_thinker:OnRemoved()
end
function modifier_hoodwink_acorn_shot_lua_thinker:OnDestroy()
if not IsServer() then return end
UTIL_Remove( self:GetParent() )
end
--------------------------------------------------------------------------------
-- Interval Effects
function modifier_hoodwink_acorn_shot_lua_thinker:OnIntervalThink()
self.bounces = self.bounces-1
if self.bounces<0 then
self:Destroy()
return
end
self:StartIntervalThink(-1)
local first = 0
if not self.first then
self.first = true
first = 1
self.info.iMoveSpeed = self.projectile_speed
else
self.source = self.target
-- Find enemies
local enemies = FindUnitsInRadius(
self.caster:GetTeamNumber(), -- int, your team number
self.target:GetOrigin(), -- point, center point
nil, -- handle, cacheUnit. (not known)
self.range, -- float, radius. or use FIND_UNITS_EVERYWHERE
DOTA_UNIT_TARGET_TEAM_ENEMY, -- int, team filter
DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, -- int, type filter
DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES, -- int, flag filter
0, -- int, order filter
false -- bool, can grow cache
)
if #enemies<1 then
self:Destroy()
return
end
local next_target
for _,enemy in pairs(enemies) do
if enemy~=self.target then
next_target = enemy
break
end
end
if not next_target then
self:Destroy()
return
end
self.target = next_target
self.info.iMoveSpeed = self.caster:GetProjectileSpeed()
end
-- launch projectile
self.info.Source = self.source
self.info.Target = self.target
self.info.ExtraData.first = first
ProjectileManager:CreateTrackingProjectile( self.info )
-- play effects
local sound_cast = "Hero_Hoodwink.AcornShot.Bounce"
EmitSoundOn( sound_cast, self.source )
end
--------------------------------------------------------------------------------
-- Helper
function modifier_hoodwink_acorn_shot_lua_thinker:Bounce()
self:StartIntervalThink( self.delay )
end
|
--[[
Title: Wallet
Author(s): big
Date: 2019.01.23
place: Foshan
Desc:
use the lib:
------------------------------------------------------------
local Wallet = NPL.load("(gl)Mod/WorldShare/database/Wallet.lua")
------------------------------------------------------------
]]
local Utils = NPL.load("(gl)Mod/WorldShare/helper/Utils.lua")
local Store = NPL.load("(gl)Mod/WorldShare/store/Store.lua")
local Wallet = NPL.export()
-- TODO: Move to general class
function Wallet:GetAllData()
local playerController = Store:Getter("user/GetPlayerController")
if not playerController then
playerController = GameLogic.GetPlayerController()
local SetPlayerController = Store:Action("user/SetPlayerController")
SetPlayerController(playerController)
end
local wallet = playerController:LoadLocalData("wallet", nil, true)
if type(wallet) ~= "table" then
return {}
end
return wallet
end
function Wallet:GetData(key)
local allData = self:GetAllData()
if type(allData) ~= 'table' then
return false
end
return allData[key]
end
function Wallet:SetData(key, value)
local allData = self:GetAllData()
local playerController = Store:Getter("user/GetPlayerController")
if not allData or not playerController then
return false
end
allData[key] = value
playerController:SaveLocalData("wallet", allData, true)
end
function Wallet:GetUserPassword()
return self:GetData('password')
end
function Wallet:SetUserPassword(password)
self:SetData('password', password)
end
function Wallet:GetUserBalance()
return self:GetData('balance') or 0
end
function Wallet:SetUserBalance(coins)
if not coins then
return false
end
self:SetData('balance', coins)
end
function Wallet:GetPlayerBalance()
return self:GetData('playerBalance') or 0
end
function Wallet:SetPlayerBalance(coins)
if not coins then
return false
end
self:SetData('playerBalance', coins)
end
|
-----------------------------------
-- Area: Western Adoulin
-- NPC: Shipilolo
-- Type: Standard NPC and Quest NPC
-- Involved with Quests: 'A Certain Substitute Patrolman'
-- 'Fertile Ground'
-- 'The Old Man and the Harpoon'
-- 'Wayward Waypoints'
-- !pos 84 0 -60 256
-----------------------------------
require("scripts/globals/missions")
require("scripts/globals/quests")
require("scripts/globals/keyitems")
local ID = require("scripts/zones/Western_Adoulin/IDs")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
local TOMATH = player:getQuestStatus(ADOULIN, tpz.quest.id.adoulin.THE_OLD_MAN_AND_THE_HARPOON)
local Fertile_Ground = player:getQuestStatus(ADOULIN, tpz.quest.id.adoulin.FERTILE_GROUND)
local Wayward_Waypoints = player:getQuestStatus(ADOULIN, tpz.quest.id.adoulin.WAYWARD_WAYPOINTS)
Wayward_Waypoints = (Wayward_Waypoints == QUEST_ACCEPTED) and (player:getCharVar("WW_Need_Shipilolo") > 0)
local ACSP = player:getQuestStatus(ADOULIN, tpz.quest.id.adoulin.A_CERTAIN_SUBSTITUTE_PATROLMAN)
local SOA_Mission = player:getCurrentMission(SOA)
if (SOA_Mission >= tpz.mission.id.soa.LIFE_ON_THE_FRONTIER) then
if ((TOMATH == QUEST_ACCEPTED) and player:hasKeyItem(tpz.ki.BROKEN_HARPOON)) then
-- Progresses Quest: 'The Old Man and the Harpoon'
player:startEvent(2543)
elseif ((Fertile_Ground == QUEST_ACCEPTED) and (not player:hasKeyItem(tpz.ki.BOTTLE_OF_FERTILIZER_X))) then
-- Progresses Quest: 'Fertile Ground'
player:startEvent(2850)
elseif (Wayward_Waypoints and (not player:hasKeyItem(tpz.ki.WAYPOINT_RECALIBRATION_KIT))) then
-- Progresses Quest: 'Wayward Waypoints'
player:startEvent(79)
elseif ((ACSP == QUEST_ACCEPTED) and (player:getCharVar("ACSP_NPCs_Visited") == 5)) then
-- Progresses Quest: 'A Certain Substitute Patrolman'
player:startEvent(2557)
else
-- Standard dialogue
player:startEvent(535)
end
else
-- Dialogue prior to joining colonization effort
player:startEvent(526)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if (csid == 2543) then
-- Progresses Quest: 'The Old Man and the Harpoon'
player:delKeyItem(tpz.ki.BROKEN_HARPOON)
player:addKeyItem(tpz.ki.EXTRAVAGANT_HARPOON)
player:messageSpecial(ID.text.KEYITEM_OBTAINED, tpz.ki.EXTRAVAGANT_HARPOON)
elseif (csid == 2850) then
-- Progresses Quest: 'Fertile Ground'
player:addKeyItem(tpz.ki.BOTTLE_OF_FERTILIZER_X)
elseif (csid == 79) then
player:addKeyItem(tpz.ki.WAYPOINT_RECALIBRATION_KIT)
player:setCharVar("WW_Need_Shipilolo", 0)
elseif (csid == 2557) then
-- Progresses Quest: 'A Certain Substitute Patrolman'
player:setCharVar("ACSP_NPCs_Visited", 6)
end
end
|
local luaunit = require("luaunit")
local luacs = require("luacs")
TestParser = {}
function parse(selectors_group)
local events = {}
local listener = {}
listener.on_start_selectors_group = function(self)
table.insert(events, "start_selectors_group")
end
listener.on_end_selectors_group = function(self)
table.insert(events, "end_selectors_group")
end
listener.on_start_selector = function(self)
table.insert(events, "start_selector")
end
listener.on_end_selector = function(self)
table.insert(events, "end_selector")
end
listener.on_start_simple_selector_sequence = function(self)
table.insert(events, "start_simple_selector_sequence")
end
listener.on_end_simple_selector_sequence = function(self)
table.insert(events, "end_simple_selector_sequence")
end
listener.on_type_selector = function(self, namespace_prefix, element_name)
table.insert(events, {
event = "type_selector",
namespace_prefix = namespace_prefix,
element_name = element_name,
})
end
listener.on_universal = function(self, namespace_prefix)
table.insert(events, {
event = "universal",
namespace_prefix = namespace_prefix,
})
end
listener.on_hash = function(self, name)
table.insert(events, {
event = "hash",
name = name,
})
end
listener.on_class = function(self, name)
table.insert(events, {
event = "class",
name = name,
})
end
listener.on_attribute = function(self, namespace_prefix, name, operator, value)
table.insert(events, {
event = "attribute",
namespace_prefix = namespace_prefix,
name = name,
operator = operator,
value = value,
})
end
listener.on_pseudo_element = function(self, name)
table.insert(events, {
event = "pseudo_element",
name = name,
})
end
listener.on_pseudo_class = function(self, name)
table.insert(events, {
event = "pseudo_class",
name = name,
})
end
listener.on_functional_pseudo = function(self, name, expression)
table.insert(events, {
event = "functional_pseudo",
name = name,
expression = expression,
})
end
listener.on_start_negation = function(self)
table.insert(events, "start_negation")
end
listener.on_end_negation = function(self)
table.insert(events, "end_negation")
end
listener.on_combinator = function(self, combinator)
table.insert(events, {
event = "combinator",
combinator = combinator,
})
end
local parser = luacs.Parser.new(selectors_group, listener)
parser:parse()
return events
end
local function assert_parse_error(css_selector_groups, expected_message)
local success, actual_message = pcall(parse, css_selector_groups)
luaunit.failIf(success,
"Must be fail to parse: <" .. css_selector_groups .. ">")
luaunit.assertEquals(actual_message:gsub("^.+:%d+: ", ""),
expected_message)
end
function TestParser.test_error_no_selector()
assert_parse_error("1 2 3",
"Failed to parse CSS selectors group: " ..
"must have at least one selector: " ..
"<|@|1 2 3>")
end
function TestParser.test_error_no_selector()
assert_parse_error("ul, ",
"Failed to parse CSS selectors group: " ..
"must have selector after ',': " ..
"<ul, |@|>")
end
function TestParser.test_error_garbage()
assert_parse_error("ul 1 2 3",
"Failed to parse CSS selectors group: " ..
"there is garbage after selectors group: " ..
"<ul |@|1 2 3>")
end
function TestParser.test_selectors_group()
luaunit.assertEquals(parse("ul, ol"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "ul",
},
"end_simple_selector_sequence",
"end_selector",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "ol",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_selector_combinator_plus()
luaunit.assertEquals(parse("body + p"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "body"
},
"end_simple_selector_sequence",
{
event = "combinator",
combinator = "+",
},
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "p"
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_selector_combinator_greater()
luaunit.assertEquals(parse("body > p"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "body"
},
"end_simple_selector_sequence",
{
event = "combinator",
combinator = ">",
},
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "p"
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_selector_combinator_tilde()
luaunit.assertEquals(parse("body ~ p"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "body"
},
"end_simple_selector_sequence",
{
event = "combinator",
combinator = "~",
},
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "p"
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_selector_combinator_whitespace()
luaunit.assertEquals(parse("body p"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "body"
},
"end_simple_selector_sequence",
{
event = "combinator",
combinator = " ",
},
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "p"
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector()
luaunit.assertEquals(parse("html"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "html",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_namespace_prefix_star()
luaunit.assertEquals(parse("*|html"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = "*",
element_name = "html",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_namespace_prefix_name()
luaunit.assertEquals(parse("xhtml|html"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = "xhtml",
element_name = "html",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_namespace_prefix_none()
luaunit.assertEquals(parse("|html"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = "",
element_name = "html",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_hash()
luaunit.assertEquals(parse("p#content"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "p",
},
{
event = "hash",
name = "content",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_class()
luaunit.assertEquals(parse("p.content"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "p",
},
{
event = "class",
name = "content",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_class_non_ascii()
luaunit.assertEquals(parse("p.cクラス"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "p",
},
{
event = "class",
name = "cクラス",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_class_escape_backslash()
luaunit.assertEquals(parse("p.\\\\backslash"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "p",
},
{
event = "class",
name = "\\backslash",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_class_unicode_with_space()
luaunit.assertEquals(parse("p.\\3042 A"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "p",
},
{
event = "class",
name = "あA",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_class_unicode_without_space()
luaunit.assertEquals(parse("p.\\003042A"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "p",
},
{
event = "class",
name = "あA",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_attribute()
luaunit.assertEquals(parse("p[ id ]"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "p",
},
{
event = "attribute",
namespace_prefix = nil,
name = "id",
operator = nil,
value = nil,
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_attribute_namespace_prefix()
luaunit.assertEquals(parse("p[ xml|lang ]"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "p",
},
{
event = "attribute",
namespace_prefix = "xml",
name = "lang",
operator = nil,
value = nil,
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_attribute_string_backslash_newline()
luaunit.assertEquals(parse("a[title=\"a\\\nb\"]"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "a",
},
{
event = "attribute",
namespace_prefix = nil,
name = "title",
operator = "=",
value = "ab",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_attribute_string_non_ascii()
luaunit.assertEquals(parse("a[title=\"タイトル\"]"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "a",
},
{
event = "attribute",
namespace_prefix = nil,
name = "title",
operator = "=",
value = "タイトル",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_attribute_string_escape_backslash()
luaunit.assertEquals(parse("a[title=\"\\\\backslash\"]"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "a",
},
{
event = "attribute",
namespace_prefix = nil,
name = "title",
operator = "=",
value = "\\backslash",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_attribute_string_unicode_with_space()
luaunit.assertEquals(parse("a[title=\"\\3042 A\"]"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "a",
},
{
event = "attribute",
namespace_prefix = nil,
name = "title",
operator = "=",
value = "あA",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_attribute_string_unicode_without_space()
luaunit.assertEquals(parse("a[title=\"\\003042A\"]"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "a",
},
{
event = "attribute",
namespace_prefix = nil,
name = "title",
operator = "=",
value = "あA",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_attribute_prefix_match()
luaunit.assertEquals(parse("a[href ^= \"https://\"]"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "a",
},
{
event = "attribute",
namespace_prefix = nil,
name = "href",
operator = "^=",
value = "https://",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_attribute_suffix_match()
luaunit.assertEquals(parse("a[href $= html]"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "a",
},
{
event = "attribute",
namespace_prefix = nil,
name = "href",
operator = "$=",
value = "html",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_attribute_substring_match()
luaunit.assertEquals(parse("a[href *= secret]"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "a",
},
{
event = "attribute",
namespace_prefix = nil,
name = "href",
operator = "*=",
value = "secret",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_attribute_equal()
luaunit.assertEquals(parse("a[id = content]"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "a",
},
{
event = "attribute",
namespace_prefix = nil,
name = "id",
operator = "=",
value = "content",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_attribute_includes()
luaunit.assertEquals(parse("a[class ~= menu]"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "a",
},
{
event = "attribute",
namespace_prefix = nil,
name = "class",
operator = "~=",
value = "menu",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_attribute_dash_match()
luaunit.assertEquals(parse("a[lang |= ja]"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "a",
},
{
event = "attribute",
namespace_prefix = nil,
name = "lang",
operator = "|=",
value = "ja",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_attribute_dash_match_no_whitespace()
luaunit.assertEquals(parse("a[lang|=ja]"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "a",
},
{
event = "attribute",
namespace_prefix = nil,
name = "lang",
operator = "|=",
value = "ja",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_pseudo_element()
luaunit.assertEquals(parse("p::before"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "p",
},
{
event = "pseudo_element",
name = "before",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_pseudo_class()
luaunit.assertEquals(parse("a:visited"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "a",
},
{
event = "pseudo_class",
name = "visited",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_functional_pseudo_plus()
luaunit.assertEquals(parse("p:nth-child(+1)"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "p",
},
{
event = "functional_pseudo",
name = "nth-child",
expression = {
{"plus"},
{"number", 1},
},
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_functional_pseudo_minus()
luaunit.assertEquals(parse("p:nth-child(-1)"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "p",
},
{
event = "functional_pseudo",
name = "nth-child",
expression = {
{"minus"},
{"number", 1},
},
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_functional_pseudo_dimension()
luaunit.assertEquals(parse("p:nth-child(2n)"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "p",
},
{
event = "functional_pseudo",
name = "nth-child",
expression = {
{"dimension", "2n"},
},
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_functional_pseudo_number()
luaunit.assertEquals(parse("p:nth-child(1)"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "p",
},
{
event = "functional_pseudo",
name = "nth-child",
expression = {
{"number", 1},
},
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_functional_pseudo_string_double_quote()
-- TODO: Invalid nth-child
luaunit.assertEquals(parse("p:nth-child(\"a\")"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "p",
},
{
event = "functional_pseudo",
name = "nth-child",
expression = {
{"string", "a"},
},
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_functional_pseudo_string_single_quote()
-- TODO: Invalid nth-child
luaunit.assertEquals(parse("p:nth-child('a')"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "p",
},
{
event = "functional_pseudo",
name = "nth-child",
expression = {
{"string", "a"},
},
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_functional_pseudo_ident()
luaunit.assertEquals(parse("p:lang(ja)"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "p",
},
{
event = "functional_pseudo",
name = "lang",
expression = {
{"name", "ja"},
},
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_negation_type_selector()
luaunit.assertEquals(parse("p:not( span )"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "p",
},
"start_negation",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "span",
},
"end_negation",
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_negation_universal()
luaunit.assertEquals(parse("p:not( * )"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "p",
},
"start_negation",
{
event = "universal",
namespace_prefix = nil,
},
"end_negation",
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_negation_hash()
luaunit.assertEquals(parse("p:not( #content )"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "p",
},
"start_negation",
{
event = "hash",
name = "content",
},
"end_negation",
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_negation_class()
luaunit.assertEquals(parse("p:not( .content )"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "p",
},
"start_negation",
{
event = "class",
name = "content",
},
"end_negation",
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_negation_attribute()
luaunit.assertEquals(parse("p:not( [|class] )"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "p"
},
"start_negation",
{
event = "attribute",
namespace_prefix = "",
name = "class",
operator = nil,
value = nil,
},
"end_negation",
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_type_selector_negation_pseudo()
luaunit.assertEquals(parse("p:not( :checked )"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "p"
},
"start_negation",
{
event = "pseudo_class",
name = "checked",
},
"end_negation",
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_universal()
luaunit.assertEquals(parse("*"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "universal",
namespace_prefix = nil,
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_universal_namespace_prefix_star()
luaunit.assertEquals(parse("*|*"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "universal",
namespace_prefix = "*",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_universal_namespace_prefix_name()
luaunit.assertEquals(parse("xhtml|*"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "universal",
namespace_prefix = "xhtml",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_universal_namespace_prefix_none()
luaunit.assertEquals(parse("|*"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "universal",
namespace_prefix = "",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_universal_hash()
luaunit.assertEquals(parse("*#content"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "universal",
namespace_prefix = nil,
},
{
event = "hash",
name = "content",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_universal_class()
luaunit.assertEquals(parse("*.content"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "universal",
namespace_prefix = nil,
},
{
event = "class",
name = "content",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_universal_attribute()
luaunit.assertEquals(parse("*[id]"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "universal",
namespace_prefix = nil,
},
{
event = "attribute",
namespace_prefix = nil,
name = "id",
operator = nil,
value = nil,
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_universal_attribute_namespace_prefix()
luaunit.assertEquals(parse("*[xml|lang]"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "universal",
namespace_prefix = nil,
},
{
event = "attribute",
namespace_prefix = "xml",
name = "lang",
operator = nil,
value = nil,
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_universal_pseudo_element()
luaunit.assertEquals(parse("*::before"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "universal",
namespace_prefix = nil,
},
{
event = "pseudo_element",
name = "before",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_universal_pseudo_class()
luaunit.assertEquals(parse("*:visited"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "universal",
namespace_prefix = nil,
},
{
event = "pseudo_class",
name = "visited",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_universal_functional_pseudo_plus()
luaunit.assertEquals(parse("*:nth-child(+1)"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "universal",
namespace_prefix = nil,
},
{
event = "functional_pseudo",
name = "nth-child",
expression = {
{"plus"},
{"number", 1},
},
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_universal_functional_pseudo_minus()
luaunit.assertEquals(parse("*:nth-child(-1)"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "universal",
namespace_prefix = nil,
},
{
event = "functional_pseudo",
name = "nth-child",
expression = {
{"minus"},
{"number", 1},
},
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_universal_functional_pseudo_dimension()
luaunit.assertEquals(parse("*:nth-child(2n)"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "universal",
namespace_prefix = nil,
},
{
event = "functional_pseudo",
name = "nth-child",
expression = {
{"dimension", "2n"},
},
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_universal_functional_pseudo_number()
luaunit.assertEquals(parse("*:nth-child(1)"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "universal",
namespace_prefix = nil,
},
{
event = "functional_pseudo",
name = "nth-child",
expression = {
{"number", 1},
},
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_universal_functional_pseudo_string_double_quote()
-- TODO: Invalid nth-child
luaunit.assertEquals(parse("*:nth-child(\"a\")"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "universal",
namespace_prefix = nil,
},
{
event = "functional_pseudo",
name = "nth-child",
expression = {
{"string", "a"},
},
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_universal_functional_pseudo_string_single_quote()
-- TODO: Invalid nth-child
luaunit.assertEquals(parse("*:nth-child('a')"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "universal",
namespace_prefix = nil,
},
{
event = "functional_pseudo",
name = "nth-child",
expression = {
{"string", "a"},
},
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_universal_functional_pseudo_ident()
luaunit.assertEquals(parse("*:lang(ja)"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "universal",
namespace_prefix = nil,
},
{
event = "functional_pseudo",
name = "lang",
expression = {
{"name", "ja"},
},
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_universal_negation_type_selector()
luaunit.assertEquals(parse("*:not( span )"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "universal",
namespace_prefix = nil,
},
"start_negation",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "span",
},
"end_negation",
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_universal_negation_universal()
luaunit.assertEquals(parse("*:not( * )"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "universal",
namespace_prefix = nil,
},
"start_negation",
{
event = "universal",
namespace_prefix = nil,
},
"end_negation",
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_universal_negation_hash()
luaunit.assertEquals(parse("*:not( #content )"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "universal",
namespace_prefix = nil,
},
"start_negation",
{
event = "hash",
name = "content",
},
"end_negation",
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_universal_negation_class()
luaunit.assertEquals(parse("*:not( .content )"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "universal",
namespace_prefix = nil,
},
"start_negation",
{
event = "class",
name = "content",
},
"end_negation",
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_universal_negation_attribute()
luaunit.assertEquals(parse("*:not( [|class] )"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "universal",
namespace_prefix = nil,
},
"start_negation",
{
event = "attribute",
namespace_prefix = "",
name = "class",
operator = nil,
value = nil,
},
"end_negation",
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_universal_negation_pseudo()
luaunit.assertEquals(parse("*:not( :checked )"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "universal",
namespace_prefix = nil,
},
"start_negation",
{
event = "pseudo_class",
name = "checked",
},
"end_negation",
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_universal_attribute_prefix_match()
luaunit.assertEquals(parse("*[href ^= \"https://\"]"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "universal",
namespace_prefix = nil,
},
{
event = "attribute",
namespace_prefix = nil,
name = "href",
operator = "^=",
value = "https://",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_universal_attribute_suffix_match()
luaunit.assertEquals(parse("*[href $= html]"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "universal",
namespace_prefix = nil,
},
{
event = "attribute",
namespace_prefix = nil,
name = "href",
operator = "$=",
value = "html",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_universal_attribute_substring_match()
luaunit.assertEquals(parse("*[href *= secret]"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "universal",
namespace_prefix = nil,
},
{
event = "attribute",
namespace_prefix = nil,
name = "href",
operator = "*=",
value = "secret",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_universal_attribute_equal()
luaunit.assertEquals(parse("*[id = content]"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "universal",
namespace_prefix = nil,
},
{
event = "attribute",
namespace_prefix = nil,
name = "id",
operator = "=",
value = "content",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_universal_attribute_includes()
luaunit.assertEquals(parse("*[class ~= menu]"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "universal",
namespace_prefix = nil,
},
{
event = "attribute",
namespace_prefix = nil,
name = "class",
operator = "~=",
value = "menu",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_universal_attribute_dash_match()
luaunit.assertEquals(parse("*[lang |= ja]"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "universal",
namespace_prefix = nil,
},
{
event = "attribute",
namespace_prefix = nil,
name = "lang",
operator = "|=",
value = "ja",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_comment_c_style_selectors_group()
luaunit.assertEquals(parse("ul, /* ol, */ dl"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "ul",
},
"end_simple_selector_sequence",
"end_selector",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "dl",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
function TestParser.test_comment_sgml_style_selectors_group()
luaunit.assertEquals(parse("ul, <!-- ol, --> dl"),
{
"start_selectors_group",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "ul",
},
"end_simple_selector_sequence",
"end_selector",
"start_selector",
"start_simple_selector_sequence",
{
event = "type_selector",
namespace_prefix = nil,
element_name = "dl",
},
"end_simple_selector_sequence",
"end_selector",
"end_selectors_group",
}
)
end
|
local Flame = Class('Flame', Skill)
Flame.static.image = love.graphics.newImage('assets/sprites/Projectiles/hd_flame_0.png')
Flame.static.grid = Anim8.newGrid(64, 64, Flame.static.image:getDimensions())
Flame.static.particle_image = love.graphics.newImage('assets/sprites/flare/corona.png')
function Flame:initialize(x, y, dir)
Skill.initialize(self, 25, x, y, dir, 500)
self.image = Flame.static.image
self.animation = Anim8.newAnimation(Flame.static.grid(1, 1), 0.1)
if dir == -1 then
self.animation:flipH()
end
self.offset_x = -32
self.offset_y = -16
self.sound_name = 'sounds-explosion_flame'
self.blend_mode = 'add'
self.particles_count = 450
self.particles_timer = 1.5
self.particles = love.graphics.newParticleSystem(Flame.static.particle_image, self.particles_count)
self.particles:setParticleLifetime(0.5, self.particles_timer)
self.particles:setSpread(1 * self.dir)
self.particles:setLinearAcceleration(-600, -400, 600, 800)
self.particles:setSpeed(100)
self.particles:setColors(238, 75, 150, 255,
127, 12, 170, 255,
216, 74, 238, 255,
255, 0, 0, 255,
255, 250, 206, 255)
Signal.emit('sounds-shoot_flame')
end
return Flame
|
local parser = require("parser")
local _dump = require("pl.pretty").dump
describe("parser", function ()
context("very basics", function ()
it("should parse a fact", function ()
parser.parse("(p (a) (b (c))).")
end)
it("should parse a rule", function ()
parser.parse("(:RULE (p (X)) (X)).")
end)
it("should parse the examples", function ()
local x = parser.parse("(p (f (c))).")
--_dump(x)
local y = parser.parse("(:RULE (g (X)) (p1 (Y)) (p2 (Z1) (Z2))).")
--_dump(y)
end)
end)
context("fact parsing", function ()
it("should parse a zero-argument constant fact", function ()
local parse = parser.parse("(x).")
assert_equal(0, #parse.rules)
assert_equal(1, #parse.facts)
local f = parse.facts[1]
assert_equal("x", f.functor)
assert_equal(0, #f.args)
end)
it("should not parse a zero-argument variable fact", function ()
local parse = parser.parse("(X).")
assert_equal(nil, parse)
end)
it("should parse facts with 1 arguments", function ()
local parse = parser.parse("(x (y)).")
assert_equal(0, #parse.rules)
assert_equal(1, #parse.facts)
local f = parse.facts[1]
assert_equal("x", f.functor)
assert_equal(1, #f.args)
f = f.args[1]
assert_equal("constant", f.type)
assert_equal("y", f.value)
end)
it("should parse facts with 2 arguments", function ()
local parse = parser.parse("(x (y) (z)).")
assert_equal(0, #parse.rules)
assert_equal(1, #parse.facts)
local f = parse.facts[1]
assert_equal("x", f.functor)
assert_equal(2, #f.args)
f = parse.facts[1].args[1]
assert_equal("constant", f.type)
assert_equal("y", f.value)
f = parse.facts[1].args[2]
assert_equal("constant", f.type)
assert_equal("z", f.value)
end)
it("should parse facts with 1 nested arguments", function ()
local parse = parser.parse("(x (y (z))).")
assert_equal(0, #parse.rules)
assert_equal(1, #parse.facts)
local f = parse.facts[1]
assert_equal("x", f.functor)
assert_equal(1, #f.args)
f = f.args[1]
assert_equal("functor", f.type)
assert_equal("y", f.functor)
assert_equal(1, #f.args)
f = f.args[1]
assert_equal("constant", f.type)
assert_equal("z", f.value)
end)
end)
context("rule parsing", function ()
it("should NOT parse a rule with no body", function ()
-- TODO
end)
it("should NOT parse a rule with a variable as a predicate symbol", function ()
-- TODO
end)
it("should parse a rule with a zero-argument head", function ()
local parse = parser.parse("(:RULE (q) (p)).")
assert_equal(1, #parse.rules)
assert_equal(0, #parse.facts)
local r = parse.rules[1]
local pred = r.predicate
assert_equal("constant", r.predicate.type)
assert_equal("q", r.predicate.value)
assert_equal(1, #r.body)
assert_equal("constant", r.body[1].type)
assert_equal("p", r.body[1].value)
end)
it("should parse a rule with a one-variable-argument head", function ()
local parse = parser.parse("(:RULE (q (X)) (p (X))).")
assert_equal(1, #parse.rules)
assert_equal(0, #parse.facts)
local r = parse.rules[1]
local pred = r.predicate
assert_equal("functor", pred.type)
assert_equal("q", pred.functor)
assert_equal(1, #pred.args)
assert_equal("variable", pred.args[1].type)
assert_equal("X", pred.args[1].value)
assert_equal(1, #r.body)
local f = r.body[1]
assert_equal("functor", f.type)
assert_equal("p", f.functor)
assert_equal(1, #f.args)
assert_equal("variable", f.args[1].type)
assert_equal("X", f.args[1].value)
end)
end)
context("parse tree methods", function ()
it("should compare two separate constants as the same", function ()
local a = parser.parse("(d (x)).")
local b = parser.parse("(c (x)).")
assert_equal(a.facts[1].args[1], b.facts[1].args[1])
end)
it("should compare two separate variables as the same", function ()
local a = parser.parse("(:RULE (q (A)) (p)).")
local b = parser.parse("(:RULE (a (B) (A)) (b)).")
assert_equal(a.rules[1].predicate.args[1],
b.rules[1].predicate.args[2])
end)
it("should comparse two separate functors as the same", function ()
local a = parser.parse("(d (x (z))).")
local b = parser.parse("(c (x (z))).")
assert_equal(a.facts[1].args[1], b.facts[1].args[1])
end)
end)
context("mixed rules and facts", function ()
-- TODO
end)
end)
|
-- Generated By protoc-gen-lua Do not Edit
local protobuf = require "protobuf/protobuf"
module('atlasdata_pb')
ATLASDATA = protobuf.Descriptor();
local ATLASDATA_GROUPID_FIELD = protobuf.FieldDescriptor();
local ATLASDATA_FINISHID_FIELD = protobuf.FieldDescriptor();
ATLASDATA_GROUPID_FIELD.name = "groupid"
ATLASDATA_GROUPID_FIELD.full_name = ".KKSG.atlasdata.groupid"
ATLASDATA_GROUPID_FIELD.number = 1
ATLASDATA_GROUPID_FIELD.index = 0
ATLASDATA_GROUPID_FIELD.label = 1
ATLASDATA_GROUPID_FIELD.has_default_value = false
ATLASDATA_GROUPID_FIELD.default_value = 0
ATLASDATA_GROUPID_FIELD.type = 13
ATLASDATA_GROUPID_FIELD.cpp_type = 3
ATLASDATA_FINISHID_FIELD.name = "finishid"
ATLASDATA_FINISHID_FIELD.full_name = ".KKSG.atlasdata.finishid"
ATLASDATA_FINISHID_FIELD.number = 2
ATLASDATA_FINISHID_FIELD.index = 1
ATLASDATA_FINISHID_FIELD.label = 1
ATLASDATA_FINISHID_FIELD.has_default_value = false
ATLASDATA_FINISHID_FIELD.default_value = 0
ATLASDATA_FINISHID_FIELD.type = 13
ATLASDATA_FINISHID_FIELD.cpp_type = 3
ATLASDATA.name = "atlasdata"
ATLASDATA.full_name = ".KKSG.atlasdata"
ATLASDATA.nested_types = {}
ATLASDATA.enum_types = {}
ATLASDATA.fields = {ATLASDATA_GROUPID_FIELD, ATLASDATA_FINISHID_FIELD}
ATLASDATA.is_extendable = false
ATLASDATA.extensions = {}
atlasdata = protobuf.Message(ATLASDATA)
|
-- Greatest subsequential sum finding algorithms implementation
-- See: http://en.wikipedia.org/wiki/Maximum_subarray_problem
-- Computes the largest sub-sequential sum using kadanes algorithm
-- s : a given sequence
-- returns : the sum of the largest subsequence found
-- returns : the starting index of the largest subsequence found
-- returns : the final index of the largest subsequence found
local function kadanes(s)
local n = #s
if n< 1 then return 0 end
local max_ending_here, max_so_far = s[1], s[1]
local begin, begin_tmp, last = 1, 1, 1
for i = 2, n do
if max_ending_here < 0 then
max_ending_here = s[i]
begin_tmp = i
else
max_ending_here = max_ending_here + s[i]
end
if max_ending_here >= max_so_far then
max_so_far = max_ending_here
begin = begin_tmp
last = i
end
end
return max_so_far, begin, last
end
-- Computes the largest sub-sequential sum using a brute-force algorithm
-- s : a given sequence
-- returns : the sum of the largest subsequence found
-- returns : the starting index of the largest subsequence found
-- returns : the final index of the largest subsequence found
local function gss_brute_force(s)
local st, ed = 1
local sum , max = s[st], s[st]
for i = 1, #s do
for j = i, #s do
sum = 0
for k = i, j do sum = sum + s[k] end
if sum > max then
st, ed = i, j
max = sum
end
end
end
return max, st, ed==nil and st or ed
end
-- Computes the largest sub-sequential sum by computing sub-sums
-- s : a given sequence
-- returns : the sum of the largest subsequence found
-- returns : the starting index of the largest subsequence found
-- returns : the final index of the largest subsequence found
local function gss_subsums(s)
local st, ed = 1
local sum , max = s[st], s[st]
for i = 1, #s do
sum = 0
for j = i, #s do
sum = sum + s[j]
if sum > max then
st, ed = i, j
max = sum
end
end
end
return max, st, ed==nil and st or ed
end
-- Computes the largest sub-sequential sum with dynamic programming
-- s : a given sequence
-- returns : the sum of the largest subsequence found
-- returns : the starting index of the largest subsequence found
-- returns : the final index of the largest subsequence found
local function gss_dynamic(a)
local s, t = {}, {}
s[1], t[1] = a[1], 1
local max = s[1]
local st, ed = 1, 1
for i = 2, #a do
if s[i-1] > 0 then
s[i] = s[i-1] + a[i]
t[i] = t[i-1]
else
s[i] = a[i]
t[i] = i
end
if s[i] > max then
st, ed = t[i], i
max = s[i]
end
end
return max, st, ed
end
return {
kadanes = kadanes,
brute_force = gss_brute_force,
subsums = gss_subsums,
dynamic = gss_dynamic,
}
|
local GameScene = class("GameScene", cc.load("mvc").ViewBase)
local protoTypes = require("ProtoTypes")
local packetHelper = require "PacketHelper"
local CommonLayer = require("CommonLayer")
local Constants = require("Constants")
local UIHelper = require("UIHelper")
function GameScene:onCreate()
UIHelper.createSceneBg(self)
self.comLayer = CommonLayer.create(self, 0)
self.comLayer.is_offline = true
self.comLayer:addTo(self, 1)
self.comLayer:setPosition(cc.p(0, 0))
local config = packetHelper.load_config("protos/yuncheng.cfg")
self.hallInterface = packetHelper.createObject(config.Interface, config)
self.config = config
config.SeatOrder = true
self:initAgentList()
end
function GameScene:initAgentList()
if self.agent_list then
return
end
local AIPlayer = require "AIPlayer"
local players = AIPlayer.shufflePlayers()
local agent_list = {}
local count = 3
for i = 1, count do
local handler = nil
local p = players[i]
if p.FUniqueID == "uid100" then
handler = self.comLayer
else
p.client_fd = -math.random(1, 1000)
end
local BotPlayer = require "YunCheng_BotPlayer"
p.agent = BotPlayer.create(self, p.FUniqueID, handler)
if handler then
self.comLayer.agent = p.agent
end
p.agent.is_offline = true
self.hallInterface:addPlayer(p)
table.insert(agent_list, p.agent)
end
self.agent_list = agent_list
end
function GameScene:onEnter_()
Constants.startScheduler(self, self.tickFrame, 0.1)
end
function GameScene:onExit_()
Constants.stopScheduler(self)
for _, agent in ipairs(self.agent_list) do
agent:remove_all_long_func()
end
end
function GameScene:tickFrame(dt)
xpcall (function ()
self.hallInterface:tick(dt)
for i, agent in ipairs(self.agent_list) do
agent:tickFrame(dt)
end
end, __G__TRACKBACK__)
for _, agent in ipairs(self.agent_list) do
agent:check_long_func()
end
end
--------------------------------------------
---! @addtogroup CommonLayerDelegate
function GameScene:command_handler (user, packet)
local args = packetHelper:decodeMsg("CGGame.ProtoInfo", packet)
if args.mainType == protoTypes.CGGAME_PROTO_TYPE_SUBMIT_GAMEDATA then
self.hallInterface:handleGameData(user, args)
else
print ("unknown data type ", args.mainType)
end
end
---! @endgroup CommonLayerDelegate
return GameScene
|
--[[
@author Sebastian "CrosRoad95" Jura <sebajura1234@gmail.com>
@copyright 2011-2021 Sebastian Jura <sebajura1234@gmail.com>
@license MIT
]]--
local jobs={
["tuner-sf"]={
code="tuner-sf",
desc="-",
desc2="Praca Tunera",
positionMarker={-2272.03, -159.40, 35.32},
text="* Nie jesteś zatrudniony(a) jako tuner w tym warsztacie.",
cuboid={-2301.8146972656, -180.19532775879, 34.492546081543, 31.5, 64.3, 10},
maxEmployees=2,
},
}
for i,v in pairs(jobs) do
local marker=createMarker(v.positionMarker[1], v.positionMarker[2], v.positionMarker[3]-0.90, "cylinder", 1.2, 78, 255, 0, 155)
setElementDimension(marker, v.positionMarker[5] or 0)
setElementInterior(marker, v.positionMarker[4] or 0)
setElementData(marker,"m:duty",v.code or 0)
local cs= createColCuboid(v.cuboid[1],v.cuboid[2],v.cuboid[3],v.cuboid[4],v.cuboid[5],v.cuboid[6])
setElementData(cs,"m:duty",v.code)
addEventHandler ( "onColShapeLeave", cs, function(el,md)
if getElementData(el,"player:duty") == getElementData(source,"m:duty") then
setElementData(el,"player:duty",false)
outputChatBox("* Zakończyłeś(aś) prace.", el)
local skin=getElementData(el,"player:skin")
setElementModel(el,skin)
end
end)
local t=createElement("text")
setElementDimension(t, v.positionMarker[5] or 0)
setElementInterior(t, v.positionMarker[4] or 0)
setElementData(t,"name",v.desc.."\n"..v.desc2)
setElementPosition(t,v.positionMarker[1],v.positionMarker[2],v.positionMarker[3])
end
addEventHandler("onMarkerHit", resourceRoot, function(el,md)
if getElementType(el)~="player" then return end
local duty=getElementData(source,"m:duty")
if not duty then return end
local uid=getElementData(el,"player:uid")
if not getPlayerJob(el,duty) then
outputChatBox(jobs[duty].text, el, 255, 0, 0)
return
end
if not getElementData(el,"player:duty") then
if jobs[duty].getEmployees then
if getEmployees(duty) >= jobs[duty].maxEmployees then
outputChatBox("* W tej pracy pracuje już maksymalna ilość osób ("..jobs[duty].maxEmployees..")", el, 255, 0, 0)
return
end
end
if jobs[duty].weapon then giveWeapon(el,jobs[duty].weapon,1000) end
setElementData(el,"player:duty",duty)
outputChatBox("* Rozpocząłeś(aś) pracę.", el)
exports["pystories-db"]:dbSet("UPDATE ogrpg_jobs SET actived=NOW() WHERE code=? and uid=?",duty,uid)
else
if getElementData(el,"player:duty") ~= getElementData(source,"m:duty") then outputChatBox("* Idź i zwolnij się z frakcji !",el) return end
if jobs[duty].weapon then takeWeapon(el,jobs[duty].weapon) end
setElementData(el,"player:duty",false)
outputChatBox("* Zakończyłeś(aś) prace.", el)
local skin=getElementData(el,"player:skin")
setElementModel(el,skin)
end
end)
|
local _2afile_2a = "fnl/conjure/remote/transport/bencode/init.fnl"
local _2amodule_name_2a = "conjure.remote.transport.bencode"
local _2amodule_2a
do
package.loaded[_2amodule_name_2a] = {}
_2amodule_2a = package.loaded[_2amodule_name_2a]
end
local _2amodule_locals_2a
do
_2amodule_2a["aniseed/locals"] = {}
_2amodule_locals_2a = (_2amodule_2a)["aniseed/locals"]
end
local autoload = (require("conjure.aniseed.autoload")).autoload
local a, impl = autoload("conjure.aniseed.core"), autoload("conjure.remote.transport.bencode.impl")
do end (_2amodule_locals_2a)["a"] = a
_2amodule_locals_2a["impl"] = impl
local function new()
return {data = ""}
end
_2amodule_2a["new"] = new
local function decode_all(bs, part)
local progress = 1
local end_3f = false
local s = (bs.data .. part)
local acc = {}
while ((progress < a.count(s)) and not end_3f) do
local msg, consumed = impl.decode(s, progress)
if a["nil?"](msg) then
end_3f = true
else
table.insert(acc, msg)
progress = consumed
end
end
a.assoc(bs, "data", string.sub(s, progress))
return acc
end
_2amodule_2a["decode-all"] = decode_all
local function encode(...)
return impl.encode(...)
end
_2amodule_2a["encode"] = encode
return _2amodule_2a
|
local api = vim.api
api.nvim_set_keymap('n', '<Leader>ln', '<Cmd>lua require("jonz94.line-number").toggle()<CR>', { noremap = true })
|
hp = 3000
attack = 520
defense = 300
speed = 100
mdefense = 350
luck = 75
strength = ELEMENT_NONE
weakness = ELEMENT_NONE
function initId(id)
myId = id
end
function start()
preloadSpellSFX("MachineGun")
end
function get_action(step)
return COMBAT_CASTING, "MachineGun", 1, getRandomPlayer()
end
function die()
end
|
--- Simple file operations.
--
-- This module provides actions to handle simple filesystem operations.
--
-- @module file
-- @author Chad Phillips
-- @copyright 2011-2015 Chad Phillips
--- The filesystem handler (default).
--
-- The default handler for the file module. This handles file operations on
-- the local filesystem.
--
-- @handler filesystem
-- @usage
-- {
-- action = "create_directory",
-- handler = "filesystem",
-- -- other params...
-- }
--- Creates a directory.
--
-- This action creates a directory on the filesystem in the specified location.
--
-- @action create_directory
-- @string action
-- create_directory
-- @string directory
-- The directory to create, including the path. Provide either the full path
-- or a relative path from the FreeSWITCH 'base_dir' global variable.
-- @string handler
-- The handler to use, see [handlers](#Handlers). If not specified, defaults
-- to the default handler for the module.
-- @usage
-- {
-- action = "create_directory",
-- directory = "/tmp/mynewdir",
-- }
--- Delete a file.
--
-- This action deletes a file from a location on the filesystem.
--
-- @action delete_file
-- @string action
-- delete_file
-- @string file
-- The file to delete, including the path. Provide either the full path or a
-- relative path from the FreeSWITCH 'base_dir' global variable.
-- @string handler
-- The handler to use, see [handlers](#Handlers). If not specified, defaults
-- to the default handler for the module.
-- @usage
-- {
-- action = "delete_file",
-- file = "/tmp/afile.txt",
-- }
--- Determines if a file exists in the filesystem.
--
-- This action determines if a file exists on the filesystem. This only checks
-- for basic existence -- the file must be readable by the FreeSWITCH user.
--
-- The action will store the result of its check in the 'file' storage area, key
-- 'file_exists': 'true' if the file exists, 'false' otherwise.
--
-- @action file_exists
-- @string action
-- file_exists
-- @string file
-- The file to check, including the path. Provide either the full path or a
-- relative path from the FreeSWITCH 'base_dir' global variable.
-- @string if_false
-- (Optional) The sequence to call if the file does not exist.
-- @string if_true
-- (Optional) The sequence to call if the file exists.
-- @string handler
-- The handler to use, see [handlers](#Handlers). If not specified, defaults
-- to the default handler for the module.
-- @usage
-- {
-- action = "file_exists",
-- file = "/tmp/afile.txt",
-- if_false = "do_this",
-- if_true = "do_that",
-- }
--- Checks a file's size.
--
-- This action checks the size of a file. The result is stored in the 'file'
-- storage area, key 'size'.
--
-- @action file_size
-- @string action
-- file_size
-- @string file
-- The file to check, including the path. Provide either the full path or a
-- relative path from the FreeSWITCH 'base_dir' global variable.
-- @string handler
-- The handler to use, see [handlers](#Handlers). If not specified, defaults
-- to the default handler for the module.
-- @usage
-- {
-- action = "file_size",
-- file = "/tmp/afile.txt",
-- }
--- Move a file from one location to another.
--
-- This action moves a file from one location on the filesystem to another.
--
-- @action move_file
-- @string action
-- move_file
-- @bool binary
-- (Optional) Boolean, only neccesary for copying files. Set to true if the
-- source file is binary (sound files are typically binary). Default is
-- false.
-- @bool copy
-- (Optional) To copy the file to the destination instead of moving it, set
-- this to true. Default is false.
-- @string destination
-- The new destination of the file, including the path. Provide either the
-- full path or a relative path from the FreeSWITCH 'base_dir' global variable.
-- @string source
-- The file to move, including the path. Provide either the full path or a
-- relative path from the FreeSWITCH 'base_dir' global variable.
-- @string handler
-- The handler to use, see [handlers](#Handlers). If not specified, defaults
-- to the default handler for the module.
-- @usage
-- {
-- action = "move_file",
-- binary = false,
-- copy = false,
-- destination = "storage/mymovedfile.txt",
-- source = "/tmp/originalfile.txt",
-- }
--- Removes a directory.
--
-- This action removes a directory from the filesystem in the specified
-- location.
--
-- @action remove_directory
-- @string action
-- remove_directory
-- @string directory
-- The directory to remove, including the path. Provide either the full path
-- or a relative path from the FreeSWITCH 'base_dir' global variable.
-- @string handler
-- The handler to use, see [handlers](#Handlers). If not specified, defaults
-- to the default handler for the module.
-- @usage
-- {
-- action = "remove_directory",
-- directory = "/tmp/somedir",
-- }
local core = require "jester.core"
local _M = {}
--[[
Appends the freeswitch base_dir if a relative path is passed.
]]
local function get_filepath(file)
-- Look for leading slash to indicate full path.
if file:sub(1, 1) ~= "/" then
file = core.conf.base_dir .. "/" .. file
end
return file
end
--[[
Create a directory.
]]
function _M.create_directory(action)
local directory = action.directory
if directory then
local success, file_error
require "lfs"
local path = get_filepath(directory)
-- Look for existing directory.
success, file_error = lfs.attributes(path, "mode")
if success then
core.log.debug("Directory '%s' already exists, skipping creation.", path)
else
-- Create new directory.
success, file_error = lfs.mkdir(path)
if success then
core.log.debug("Created directory '%s'", path)
else
core.log.debug("Failed to create directory '%s'!: %s", path, file_error)
end
end
else
core.log.debug("Cannot create directory, no 'path' parameter defined!")
end
end
--[[
Remove a directory.
]]
function _M.remove_directory(action)
local directory = action.directory
if directory then
local success, file_error
require "lfs"
local path = get_filepath(directory)
-- Look for existing directory.
success, file_error = lfs.attributes(path, "mode")
if success then
-- Remove directory.
success, file_error = lfs.rmdir(path)
if success then
core.log.debug("Deleted directory '%s'", path)
else
core.log.debug("Failed to delete directory '%s'!: %s", path, file_error)
end
else
core.log.debug("Directory '%s' does not exist, skipping removal.", path)
end
else
core.log.debug("Cannot delete directory, no 'path' parameter defined!")
end
end
--[[
Move or copy a file.
]]
function _M.move_file(action)
local operation = action.copy and "copy" or "move"
local binary = action.binary and "b" or ""
if action.source and action.destination then
local success, file_error
local source_file = get_filepath(action.source)
local destination_file = get_filepath(action.destination)
-- Move.
if operation == "move" then
success, file_error = os.rename(source_file, destination_file)
-- Copy.
else
-- There is no copy function for files in Lua, so open the original,
-- read it, and write the new one.
local source, file_error = io.open(source_file, "r" .. binary)
if source then
local destination, file_error = io.open(destination_file, "w" .. binary)
if destination then
success = destination:write(source:read("*all"))
destination:close()
end
source:close()
end
end
if success then
core.log.debug("Successful file %s from '%s' to '%s'", operation, source_file, destination_file)
else
core.log.debug("Failed file %s from '%s' to '%s'!: %s", operation, source_file, destination_file, file_error)
end
else
core.log.debug("Cannot perform file %s, missing parameter! Source: %s, Destination: %s", operation, tostring(action.source), tostring(action.destination))
end
end
--[[
Delete a file.
]]
function _M.delete_file(action)
if action.file then
local file = get_filepath(action.file)
local success, file_error = os.remove(file)
if success then
core.log.debug("Deleted file '%s'", file)
else
core.log.debug("Failed to delete file '%s'!: %s", file, file_error)
end
else
core.log.debug("Cannot delete file, no 'file' parameter defined!")
end
end
--[[
Check for file existence.
]]
function _M.file_exists(action)
local result, file
if action.file then
require "lfs"
file = get_filepath(action.file)
-- If we can pull the file attributes, then the file exists.
local success, file_error = lfs.attributes(file, "mode")
if success then
result = "true"
else
result = "false"
end
else
result = ""
end
-- Store the result of the check.
core.set_storage("file", "file_exists", result)
if result == "false" then
core.log.debug("File '%s' does not exist", file)
-- Run false sequence if specified.
if action.if_false then
core.queue_sequence(action.if_false)
end
elseif result == "true" then
core.log.debug("File '%s' exists", file)
-- Run true sequence if specified.
if action.if_true then
core.queue_sequence(action.if_true)
end
else
core.log.debug("Cannot check file, no 'file' parameter defined!")
end
end
--[[
Returns a file's size.
]]
function _M.file_size(action)
local file, size
if action.file then
require "lfs"
file = get_filepath(action.file)
size = lfs.attributes(file, "size")
end
-- Store the result of the check.
core.set_storage("file", "size", size)
end
return _M
|
local t = require("ds18b20")
local pin = 3 -- gpio0 = 3, gpio2 = 4
local function readout(temps)
if t.sens then
print("Total number of DS18B20 sensors: ".. #t.sens)
for i, s in ipairs(t.sens) do
print(string.format(" sensor #%d address: %s%s", i,
('%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X'):format(s:byte(1,8)),
s:byte(9) == 1 and " (parasite)" or ""))
end
end
for addr, temp in pairs(temps) do
print(string.format("Sensor %s: %s °C", ('%02X:%02X:%02X:%02X:%02X:%02X:%02X:%02X'):format(addr:byte(1,8)), temp))
end
-- Module can be released when it is no longer needed
--t = nil
--package.loaded["ds18b20"]=nil
end
do
t:enable_debug()
file.remove("ds18b20_save.lc") -- remove saved addresses
print("=============================================", node.heap())
print("first call, no addresses in flash, search is performed")
t:read_temp(readout, pin, t.C)
tmr.create():alarm(2000, tmr.ALARM_SINGLE, function()
print("=============================================", node.heap())
print("second readout, no new search, found addresses are used")
t:read_temp(readout, pin)
tmr.create():alarm(2000, tmr.ALARM_SINGLE, function()
print("=============================================", node.heap())
print("force search again")
t:read_temp(readout, pin, nil, true)
tmr.create():alarm(2000, tmr.ALARM_SINGLE, function()
print("=============================================", node.heap())
print("save search results")
t:read_temp(readout, pin, nil, false, true)
tmr.create():alarm(2000, tmr.ALARM_SINGLE, function()
print("=============================================", node.heap())
print("use saved addresses")
t.sens={}
t:read_temp(readout, pin)
end)
end)
end)
end)
end
|
local moon = require("moon")
local cluster = require("moon.cluster")
local M = {}
function M.call(name, cmd, ...)
local config = config.get_service(name)
if config then
local data = { cluster.call(string.format( "server_%d", config.sid),name,cmd, ...) }
return table.unpack(data)
else
error("server.call: can not service ",name)
end
return nil
end
--注册全局的server
moon.exports.server = M
|
---
-- @module log
--
local _COPYRIGHT = "Copyright (C) 2013-2016 Alexey Melnichuk";
local _VERSION = "0.1.7-dev"
local table = require "table"
local string = require "string"
local date = require "date"
local destroy_list = {}
local loggers_list = setmetatable({},{__mode = 'k'})
local emptyfn = function() end
local LOG_LVL = {
EMERG = 1;
ALERT = 2;
FATAL = 3;
ERROR = 4;
WARNING = 5;
NOTICE = 6;
INFO = 7;
DEBUG = 8;
TRACE = 9;
}
local writer_names = {}
local LOG_LVL_NAMES = {}
for k,v in pairs(LOG_LVL) do
LOG_LVL_NAMES[v] = k
writer_names[v] = k:lower()
end
local LOG_LVL_COUNT = #LOG_LVL_NAMES
local function lvl2number(lvl)
if type(lvl) == 'number' then return lvl end
if type(lvl) == 'string' then
lvl = lvl:upper()
local n
if lvl == 'NONE' then n = 0 else n = LOG_LVL[ lvl ] end
if not n then return nil, "unknown log level: '" .. lvl .. "'" end
return n
end
return nil, 'unsupported log leve type: ' .. type(lvl)
end
local Log = {}
Log._COPYRIGHT = _COPYRIGHT
Log._NAME = "log"
Log._VERSION = _VERSION
Log._LICENSE = "MIT"
Log.LVL = LOG_LVL
Log.LVL_NAMES = LOG_LVL_NAMES
Log.lvl2number = lvl2number
function Log.new(max_lvl, writer, formatter, logformat)
if max_lvl and type(max_lvl) ~= 'number' and type(max_lvl) ~= 'string' then
max_lvl, writer, formatter, logformat = nil, max_lvl, writer, formatter
end
max_lvl = assert(lvl2number ( max_lvl or LOG_LVL.INFO ) )
if not writer then
writer = require"log.writer.stdout".new()
end
if not formatter then
formatter = require"log.formatter.default".new()
end
if not logformat then
logformat = require"log.logformat.default".new()
end
local write = function (lvl, ... )
local now = date()
writer( logformat, formatter(...), lvl, now )
end;
local dump = function(lvl, fn, ...)
local now = date()
writer( logformat, (fn(...) or ''), lvl, now )
end
local logger = {}
function logger.writer() return writer end
function logger.formatter() return formatter end
function logger.format() return logformat end
function logger.lvl() return max_lvl end
function logger.set_writer(value)
assert(value)
writer, value = value, writer
return value
end
function logger.set_formatter(value)
assert(value)
formatter, value = value, formatter
return value
end
function logger.set_format(value)
assert(value)
logformat, value = value, logformat
return value
end
function logger.log(lvl, ...)
local err lvl, err = lvl2number(lvl)
if not lvl then return nil, err end
return write(lvl, ...)
end
function logger.dump(lvl, ...)
local err lvl, err = lvl2number(lvl)
if not lvl then return nil, err end
return dump(lvl, ...)
end
function logger.set_lvl(lvl)
local err lvl, err = lvl2number(lvl)
if not lvl then return nil, err end
max_lvl = lvl
for i = 1, max_lvl do logger[ writer_names[i] ] = function(...) write(i, ...) end end
for i = 1, max_lvl do logger[ writer_names[i] .. '_dump'] = function(...) dump(i, ...) end end
for i = max_lvl+1, LOG_LVL_COUNT do logger[ writer_names[i] ] = emptyfn end
for i = max_lvl+1, LOG_LVL_COUNT do logger[ writer_names[i] .. '_dump'] = emptyfn end
return true
end
assert(logger.set_lvl(max_lvl))
loggers_list[logger] = true;
return logger
end
function Log.add_cleanup(fn)
assert(type(fn)=='function')
for k,v in ipairs(destroy_list) do
if v == fn then return end
end
table.insert(destroy_list, 1, fn)
return fn
end
function Log.remove_cleanup(fn)
for k,v in ipairs(destroy_list) do
if v == fn then
table.remove(destroy_list, k)
break
end
end
end
function Log.close()
for k,fn in ipairs(destroy_list) do pcall(fn) end
for logger in pairs(loggers_list) do
logger.fotal = emptyfn;
logger.error = emptyfn;
logger.warning = emptyfn;
logger.info = emptyfn;
logger.notice = emptyfn;
logger.debug = emptyfn;
logger.closed = true;
loggers_list[logger] = nil
end
destroy_list = {}
end
return Log
|
require 'common'
require 'event_single'
require 'event_battle'
require 'event_misc'
require 'event_gen'
require 'event_extra'
|
local package = {
Name = "API",
Description = "Reveals specific API methods to remote",
Author = "7kayoh",
Class = "Plugin",
Category = "Server",
Target = {}
}
local allowedRequests = {
"getAdminLevel",
"getAdminStatusWithUserId",
"checkUserAdmin",
}
local dLog = nil
function package.Target.remoteTask(player, requestType, ...)
dLog("Info", player.Name .. " is currently calling API method " .. requestType)
return package.API[requestType](...)
end
function package.Target:Init()
dLog = require(package.Core.dLog)
package.API.addRemoteTask("Function", function(player, requestType)
return package.API.checkUserAdmin(player) and table.find(allowedRequests, requestType) ~= nil
end, package.Target.remoteTask)
end
return package
|
--[[
Credit to einsteinK.
Credit to Stravant for LBI.
Credit to the creators of all the other modules used in this.
Sceleratis was here and decided modify some things.
einsteinK was here again to fix a bug in LBI for if-statements
--]]
local waitDeps = {
'FiOne';
'LuaK';
'LuaP';
'LuaU';
'LuaX';
'LuaY';
'LuaZ';
}
for i,v in pairs(waitDeps) do script:WaitForChild(v) end
local luaX = require(script.LuaX)
local luaY = require(script.LuaY)
local luaZ = require(script.LuaZ)
local luaU = require(script.LuaU)
local fiOne = require(script.FiOne)
luaX:init()
local LuaState = {}
getfenv().script = nil
return function(str,env)
local f,writer,buff,name
local env = env or getfenv(2)
local name = (env.script and env.script:GetFullName())
local ran,error = pcall(function()
local zio = luaZ:init(luaZ:make_getS(str), nil)
if not zio then return error() end
local func = luaY:parser(LuaState, zio, nil, name or "::Adonis::Loadstring::")
writer, buff = luaU:make_setS()
luaU:dump(LuaState, func, writer, buff)
f = fiOne(buff.data, env)
end)
if ran then
return f,buff.data
else
return nil,error
end
end
|
-- clock.lua (based on pdfclock.c)
RADIUS=200
MARGIN=20
p:begin_page(2 * (RADIUS + MARGIN), 2 * (RADIUS + MARGIN))
p:translate(RADIUS + MARGIN, RADIUS + MARGIN)
p:setcolor("both", "rgb", 0, 0, 1)
p:save()
-- minute strokes
p:setlinewidth(2)
for alpha = 0,360-6,6 do
p:rotate(6)
p:moveto(RADIUS, 0)
p:lineto(RADIUS-MARGIN/3, 0)
p:stroke()
end
p:restore()
p:save()
-- 5 minute strokes
p:setlinewidth(3)
for alpha = 0,360-30,30 do
p:rotate(30)
p:moveto(RADIUS, 0)
p:lineto(RADIUS-MARGIN, 0)
p:stroke()
end
p:restore()
_,_,hour,min,sec=string.find(os.date"%H:%M:%S","(%d+):(%d+):(%d+)")
-- draw hour hand
p:save()
p:rotate(-((min/60) + hour - 3) * 30)
p:moveto(-RADIUS/10, -RADIUS/20)
p:lineto(RADIUS/2, 0)
p:lineto(-RADIUS/10, RADIUS/20)
p:closepath()
p:fill()
p:restore()
-- draw minute hand
p:save()
p:rotate(-((sec/60) + min - 15) * 6)
p:moveto(-RADIUS/10, -RADIUS/20)
p:lineto(RADIUS * 0.8, 0)
p:lineto(-RADIUS/10, RADIUS/20)
p:closepath()
p:fill()
p:restore()
-- draw second hand
p:setcolor("both", "rgb", 1, 0, 0)
p:setlinewidth(2)
p:save()
p:rotate(-((sec - 15) * 6))
p:moveto(-RADIUS/5, 0)
p:lineto(RADIUS, 0)
p:stroke()
p:restore()
-- draw little circle at center
p:circle(0, 0, RADIUS/30)
p:fill()
p:end_page()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.