commit
stringlengths 40
40
| old_file
stringlengths 6
181
| new_file
stringlengths 6
181
| old_contents
stringlengths 448
7.17k
| new_contents
stringlengths 449
7.17k
| subject
stringlengths 0
450
| message
stringlengths 6
4.92k
| lang
stringclasses 1
value | license
stringclasses 12
values | repos
stringlengths 9
33.9k
|
|---|---|---|---|---|---|---|---|---|---|
6ebcfd9e798db6ea4e2a716fa4c9f972a2fa71ea
|
frontend/ui/elements/font_settings.lua
|
frontend/ui/elements/font_settings.lua
|
local Device = require("device")
local logger = require("logger")
local util = require("util")
local _ = require("gettext")
--[[ Font settings for systems with multiple font dirs ]]--
local LINUX_FONT_PATH = "share/fonts"
local MACOS_FONT_PATH = "Library/fonts"
local function getDir(isUser)
local home = Device.home_dir
if isUser and not home then return end
if Device:isAndroid() then
if isUser then
return home .. "/fonts;" .. home .. "/koreader/fonts"
else
return "/system/fonts"
end
elseif Device:isPocketBook() then
if isUser then
return "/mnt/ext1/system/fonts"
else
return "/ebrmain/adobefonts;/ebrmain/fonts"
end
elseif Device:isRemarkable() then
return isUser and string.format("%s/.local/%s", home, LINUX_FONT_PATH)
or string.format("/usr/%s", LINUX_FONT_PATH)
elseif Device:isDesktop() or Device:isEmulator() then
if jit.os == "OSX" then
return isUser and string.format("%s/%s", home, MACOS_FONT_PATH)
or string.format("/%s", MACOS_FONT_PATH)
else
return isUser and string.format("%s/.local/%s", home, LINUX_FONT_PATH)
or string.format("/usr/%s", LINUX_FONT_PATH)
end
end
end
local function openFontDir()
if not Device:canOpenLink() then return end
local user_dir = getDir(true)
local openable = util.pathExists(user_dir)
if not openable and user_dir then
logger.info("Font path not found, making one in ", user_dir)
openable = util.makePath(user_dir)
end
if not openable then
logger.warn("Unable to create the folder ", user_dir)
return
end
Device:openLink(user_dir)
end
local function usesSystemFonts()
return G_reader_settings:isTrue("system_fonts")
end
local FontSettings = {}
function FontSettings:getPath()
local user, system = getDir(true), getDir()
if usesSystemFonts() then
if user and system then
return user .. ";" .. system
elseif system then
return system
end
end
return user
end
function FontSettings:getSystemFontMenuItems()
local t = {{
text = _("Enable system fonts"),
checked_func = usesSystemFonts,
callback = function()
G_reader_settings:saveSetting("system_fonts", not usesSystemFonts())
local UIManager = require("ui/uimanager")
local InfoMessage = require("ui/widget/infomessage")
UIManager:show(InfoMessage:new{
text = _("This will take effect on next restart.")
})
end,
}}
if Device:isDesktop() or Device:isEmulator() then table.insert(t, 2, {
text = _("Open fonts folder"),
keep_menu_open = true,
callback = openFontDir,
})
end
return t
end
return FontSettings
|
local Device = require("device")
local logger = require("logger")
local util = require("util")
local _ = require("gettext")
--[[ Font settings for systems with multiple font dirs ]]--
local function getDir(isUser)
local home = Device.home_dir
local XDG_DATA_HOME = os.getenv("XDG_DATA_HOME")
local LINUX_FONT_PATH = XDG_DATA_HOME and XDG_DATA_HOME .. "/fonts"
or home .. "/.local/share/fonts"
local LINUX_SYS_FONT_PATH = "/usr/share/fonts"
local MACOS_FONT_PATH = "Library/fonts"
if isUser and not home then return end
if Device:isAndroid() then
return isUser and home .. "/fonts;" .. home .. "/koreader/fonts"
or "/system/fonts"
elseif Device:isPocketBook() then
return isUser and "/mnt/ext1/system/fonts"
or "/ebrmain/adobefonts;/ebrmain/fonts"
elseif Device:isRemarkable() then
return isUser and LINUX_FONT_PATH
or LINUX_SYS_FONT_PATH
elseif Device:isDesktop() or Device:isEmulator() then
if jit.os == "OSX" then
return isUser and home .. "/" .. MACOS_FONT_PATH
or "/" .. MACOS_FONT_PATH
else
return isUser and LINUX_FONT_PATH
or LINUX_SYS_FONT_PATH
end
end
end
local function openFontDir()
if not Device:canOpenLink() then return end
local user_dir = getDir(true)
local openable = util.pathExists(user_dir)
if not openable and user_dir then
logger.info("Font path not found, making one in ", user_dir)
openable = util.makePath(user_dir)
end
if not openable then
logger.warn("Unable to create the folder ", user_dir)
return
end
Device:openLink(user_dir)
end
local function usesSystemFonts()
return G_reader_settings:isTrue("system_fonts")
end
local FontSettings = {}
function FontSettings:getPath()
local user, system = getDir(true), getDir()
if usesSystemFonts() then
if user and system then
return user .. ";" .. system
elseif system then
return system
end
end
return user
end
function FontSettings:getSystemFontMenuItems()
local t = {{
text = _("Enable system fonts"),
checked_func = usesSystemFonts,
callback = function()
G_reader_settings:saveSetting("system_fonts", not usesSystemFonts())
local UIManager = require("ui/uimanager")
local InfoMessage = require("ui/widget/infomessage")
UIManager:show(InfoMessage:new{
text = _("This will take effect on next restart.")
})
end,
}}
if Device:isDesktop() or Device:isEmulator() then table.insert(t, 2, {
text = _("Open fonts folder"),
keep_menu_open = true,
callback = openFontDir,
})
end
return t
end
return FontSettings
|
[fix, desktop] Use XDG_DATA_HOME to search for fonts (#8521)
|
[fix, desktop] Use XDG_DATA_HOME to search for fonts (#8521)
Same as <https://github.com/koreader/koreader/pull/8507>.
|
Lua
|
agpl-3.0
|
NiLuJe/koreader,koreader/koreader,NiLuJe/koreader,poire-z/koreader,poire-z/koreader,Frenzie/koreader,koreader/koreader,Frenzie/koreader
|
c8138daae317febd4f84c1cda00c79b4a95be04f
|
game/scripts/vscripts/modules/teams/teams.lua
|
game/scripts/vscripts/modules/teams/teams.lua
|
Teams = Teams or class({})
Teams.Data = Teams.Data or {
[DOTA_TEAM_GOODGUYS] = {
color = {0, 128, 0},
name = "#DOTA_GoodGuys",
name2 = "#DOTA_GoodGuys_2",
playerColors = {
{51, 117, 255},
{102, 255, 191},
{191, 0, 191},
{243, 240, 11},
{255, 107, 0},
{130, 129, 178}
}
},
[DOTA_TEAM_BADGUYS] = {
color = {255, 0, 0},
name = "#DOTA_BadGuys",
name2 = "#DOTA_BadGuys_2",
playerColors = {
{254, 134, 194},
{161, 180, 71},
{101, 217, 247},
{0, 131, 33},
{164, 105, 0},
{204, 139, 85}
}
},
[DOTA_TEAM_CUSTOM_1] = {
color = {197, 77, 168},
name = "#DOTA_Custom1",
name2 = "#DOTA_Custom1_2",
playerColors = {
{178, 121, 90},
{147, 255, 120},
{255, 91, 0},
{26, 20, 204}
}
},
[DOTA_TEAM_CUSTOM_2] = {
color = {255, 108, 0},
name = "#DOTA_Custom2",
name2 = "#DOTA_Custom2_2",
playerColors = {
{71, 204, 131},
{255, 255, 255},
{255, 241, 96},
{195, 86, 255}
}
},
[DOTA_TEAM_CUSTOM_3] = {
color = {52, 85, 255},
name = "#DOTA_Custom3",
name2 = "#DOTA_Custom3_2",
},
[DOTA_TEAM_CUSTOM_4] = {
color = {101, 212, 19},
name = "#DOTA_Custom4",
name2 = "#DOTA_Custom4_2",
},
[DOTA_TEAM_CUSTOM_5] = {
color = {129, 83, 54},
name = "#DOTA_Custom5",
name2 = "#DOTA_Custom5_2",
},
[DOTA_TEAM_CUSTOM_6] = {
color = {27, 192, 216},
name = "#DOTA_Custom6",
name2 = "#DOTA_Custom6_2",
},
[DOTA_TEAM_CUSTOM_7] = {
color = {199, 228, 13},
name = "#DOTA_Custom7",
name2 = "#DOTA_Custom7_2",
},
[DOTA_TEAM_CUSTOM_8] = {
color = {140, 42, 244},
name = "#DOTA_Custom8",
name2 = "#DOTA_Custom8_2",
},
}
Events:Register("activate", function ()
local gameMode = GameRules:GetGameModeEntity()
gameMode:SetTowerBackdoorProtectionEnabled(false)
PlayerTables:CreateTable("teams", {}, AllPlayersInterval)
local mapinfo = LoadKeyValues("addoninfo.txt")[GetMapName()]
local num = math.floor(mapinfo.MaxPlayers / mapinfo.TeamCount)
local count = 0
for team, data in pairsByKeys(Teams.Data) do
local playerCount = count < mapinfo.TeamCount and num or 0
GameRules:SetCustomGameTeamMaxPlayers(team, playerCount)
count = count + 1
Teams.Data[team].count = playerCount
Teams.Data[team].enabled = playerCount > 0
if Options:IsEquals("CustomTeamColors") then
SetTeamCustomHealthbarColor(team, data.color[1], data.color[2], data.color[3])
end
end
end)
Events:Register("AllPlayersLoaded", function ()
local playerId = 0
for team, data in pairsByKeys(Teams.Data) do
for i = 1, data.count do
PlayerResource:SetCustomTeamAssignment(playerId, team)
playerId = playerId + 1
if not PlayerResource:IsValidPlayerID(playerId) then return end
end
end
end)
function Teams:PostInitialize()
for team, data in pairsByKeys(Teams.Data) do
if data.enabled then
Teams:RecalculateKillWeight(team)
end
local playerCounter = 0
for _,playerId in ipairs(Teams:GetPlayerIDs(team, true, true)) do
playerCounter = playerCounter + 1
local color = data.playerColors[playerCounter]
PLAYER_DATA[playerId].Color = color
PlayerResource:SetCustomPlayerColor(playerId, color[1], color[2], color[3])
end
end
end
function Teams:GetScore(team)
return Teams.Data[team].score or 0
end
function Teams:GetColor(team)
return Teams.Data[team].color
end
function Teams:IsEnabled(team)
return Teams.Data[team] and Teams.Data[team].enabled
end
function Teams:GetTeamKillWeight(team)
return Teams.Data[team].kill_weight or 1
end
function Teams:GetDesiredPlayerCount(team)
return Teams.Data[team].count or 0
end
function Teams:GetTotalDesiredPlayerCount()
local count = 0
for _, data in pairs(Teams.Data) do
count = count + data.count
end
return count
end
function Teams:GetName(team, bSecond)
return bSecond and Teams.Data[team].name2 or Teams.Data[team].name
end
function Teams:ModifyScore(team, value)
local new = Teams:GetScore(team) + value
new = math.min(new, Options:GetValue("KillLimit"))
Teams.Data[team].score = new
PlayerTables:SetTableValue("teams", team, table.deepcopy(Teams.Data[team]))
if new >= Options:GetValue("KillLimit") then
GameMode:OnKillGoalReached(team)
end
end
function Teams:SetTeamKillWeight(team, value)
Teams.Data[team].kill_weight = value
PlayerTables:SetTableValue("teams", team, table.deepcopy(Teams.Data[team]))
end
function Teams:GetPlayerIDs(team, bNotAbandoned, bAbandoned)
local ids = {}
for i = 0, DOTA_MAX_TEAM_PLAYERS - 1 do
local isAbandoned = PlayerResource:IsPlayerAbandoned(i)
if PlayerResource:IsValidPlayerID(i) and PlayerResource:GetTeam(i) == team and ((bNotAbandoned and not isAbandoned) or (bAbandoned and isAbandoned)) then
table.insert(ids, i)
end
end
return ids
end
function Teams:RecalculateKillWeight(team)
if not Teams:IsEnabled(team) then return end
local remaining = GetTeamPlayerCount(team)
local value = remaining == 0 and 0 or 1
if value == 1 and Options:GetValue("DynamicKillWeight") then
local desired = Teams:GetDesiredPlayerCount(team)
local missing = desired - remaining
value = math.max(missing, 1)
end
Teams:SetTeamKillWeight(team, value)
end
|
Teams = Teams or class({})
Teams.Data = Teams.Data or {
[DOTA_TEAM_GOODGUYS] = {
color = {0, 128, 0},
name = "#DOTA_GoodGuys",
name2 = "#DOTA_GoodGuys_2",
playerColors = {
{51, 117, 255},
{102, 255, 191},
{191, 0, 191},
{243, 240, 11},
{255, 107, 0},
{130, 129, 178}
}
},
[DOTA_TEAM_BADGUYS] = {
color = {255, 0, 0},
name = "#DOTA_BadGuys",
name2 = "#DOTA_BadGuys_2",
playerColors = {
{254, 134, 194},
{161, 180, 71},
{101, 217, 247},
{0, 131, 33},
{164, 105, 0},
{204, 139, 85}
}
},
[DOTA_TEAM_CUSTOM_1] = {
color = {197, 77, 168},
name = "#DOTA_Custom1",
name2 = "#DOTA_Custom1_2",
playerColors = {
{178, 121, 90},
{147, 255, 120},
{255, 91, 0},
{26, 20, 204}
}
},
[DOTA_TEAM_CUSTOM_2] = {
color = {255, 108, 0},
name = "#DOTA_Custom2",
name2 = "#DOTA_Custom2_2",
playerColors = {
{71, 204, 131},
{255, 255, 255},
{255, 241, 96},
{195, 86, 255}
}
},
[DOTA_TEAM_CUSTOM_3] = {
color = {52, 85, 255},
name = "#DOTA_Custom3",
name2 = "#DOTA_Custom3_2",
},
[DOTA_TEAM_CUSTOM_4] = {
color = {101, 212, 19},
name = "#DOTA_Custom4",
name2 = "#DOTA_Custom4_2",
},
[DOTA_TEAM_CUSTOM_5] = {
color = {129, 83, 54},
name = "#DOTA_Custom5",
name2 = "#DOTA_Custom5_2",
},
[DOTA_TEAM_CUSTOM_6] = {
color = {27, 192, 216},
name = "#DOTA_Custom6",
name2 = "#DOTA_Custom6_2",
},
[DOTA_TEAM_CUSTOM_7] = {
color = {199, 228, 13},
name = "#DOTA_Custom7",
name2 = "#DOTA_Custom7_2",
},
[DOTA_TEAM_CUSTOM_8] = {
color = {140, 42, 244},
name = "#DOTA_Custom8",
name2 = "#DOTA_Custom8_2",
},
}
Events:Register("activate", function ()
local gameMode = GameRules:GetGameModeEntity()
gameMode:SetTowerBackdoorProtectionEnabled(false)
PlayerTables:CreateTable("teams", {}, AllPlayersInterval)
local mapinfo = LoadKeyValues("addoninfo.txt")[GetMapName()]
local num = math.floor(mapinfo.MaxPlayers / mapinfo.TeamCount)
local count = 0
for team, data in pairsByKeys(Teams.Data) do
local playerCount = count < mapinfo.TeamCount and num or 0
GameRules:SetCustomGameTeamMaxPlayers(team, playerCount)
count = count + 1
Teams.Data[team].count = playerCount
Teams.Data[team].enabled = playerCount > 0
if Options:IsEquals("CustomTeamColors") then
SetTeamCustomHealthbarColor(team, data.color[1], data.color[2], data.color[3])
end
end
end)
function Teams:PostInitialize()
for team, data in pairsByKeys(Teams.Data) do
if data.enabled then
Teams:RecalculateKillWeight(team)
end
local playerCounter = 0
for _,playerId in ipairs(Teams:GetPlayerIDs(team, true, true)) do
playerCounter = playerCounter + 1
local color = data.playerColors[playerCounter]
PLAYER_DATA[playerId].Color = color
PlayerResource:SetCustomPlayerColor(playerId, color[1], color[2], color[3])
end
end
end
function Teams:GetScore(team)
return Teams.Data[team].score or 0
end
function Teams:GetColor(team)
return Teams.Data[team].color
end
function Teams:IsEnabled(team)
return Teams.Data[team] and Teams.Data[team].enabled
end
function Teams:GetTeamKillWeight(team)
return Teams.Data[team].kill_weight or 1
end
function Teams:GetDesiredPlayerCount(team)
return Teams.Data[team].count or 0
end
function Teams:GetTotalDesiredPlayerCount()
local count = 0
for _, data in pairs(Teams.Data) do
count = count + data.count
end
return count
end
function Teams:GetName(team, bSecond)
return bSecond and Teams.Data[team].name2 or Teams.Data[team].name
end
function Teams:ModifyScore(team, value)
local new = Teams:GetScore(team) + value
new = math.min(new, Options:GetValue("KillLimit"))
Teams.Data[team].score = new
PlayerTables:SetTableValue("teams", team, table.deepcopy(Teams.Data[team]))
if new >= Options:GetValue("KillLimit") then
GameMode:OnKillGoalReached(team)
end
end
function Teams:SetTeamKillWeight(team, value)
Teams.Data[team].kill_weight = value
PlayerTables:SetTableValue("teams", team, table.deepcopy(Teams.Data[team]))
end
function Teams:GetPlayerIDs(team, bNotAbandoned, bAbandoned)
local ids = {}
for i = 0, DOTA_MAX_TEAM_PLAYERS - 1 do
local isAbandoned = PlayerResource:IsPlayerAbandoned(i)
if PlayerResource:IsValidPlayerID(i) and PlayerResource:GetTeam(i) == team and ((bNotAbandoned and not isAbandoned) or (bAbandoned and isAbandoned)) then
table.insert(ids, i)
end
end
return ids
end
function Teams:RecalculateKillWeight(team)
if not Teams:IsEnabled(team) then return end
local remaining = GetTeamPlayerCount(team)
local value = remaining == 0 and 0 or 1
if value == 1 and Options:GetValue("DynamicKillWeight") then
local desired = Teams:GetDesiredPlayerCount(team)
local missing = desired - remaining
value = math.max(missing, 1)
end
Teams:SetTeamKillWeight(team, value)
end
|
Revert "fix(teams): players in unranked modes don't get team"
|
Revert "fix(teams): players in unranked modes don't get team"
This reverts commit e219400ca783249e80d7926450bbf40bf2769dc0.
|
Lua
|
mit
|
ark120202/aabs
|
4c0c6e635e87d907e7aacc188953e309cb1ceebf
|
modules/game_viplist/viplist.lua
|
modules/game_viplist/viplist.lua
|
vipWindow = nil
vipButton = nil
addVipWindow = nil
function init()
connect(g_game, { onGameEnd = clear,
onAddVip = onAddVip,
onVipStateChange = onVipStateChange })
g_keyboard.bindKeyDown('Ctrl+P', toggle)
vipButton = TopMenu.addRightGameToggleButton('vipListButton', tr('VIP list') .. ' (Ctrl+P)', 'viplist.png', toggle)
vipButton:setOn(true)
vipWindow = g_ui.loadUI('viplist.otui', modules.game_interface.getRightPanel())
refresh()
vipWindow:setup()
end
function terminate()
g_keyboard.unbindKeyDown('Ctrl+P')
disconnect(g_game, { onGameEnd = clear,
onAddVip = onAddVip,
onVipStateChange = onVipStateChange })
vipWindow:destroy()
vipButton:destroy()
end
function refresh()
clear()
for id,vip in pairs(g_game.getVips()) do
onAddVip(id, unpack(vip))
end
vipWindow:setContentMinimumHeight(38)
--vipWindow:setContentMaximumHeight(256)
end
function clear()
local vipList = vipWindow:getChildById('contentsPanel')
vipList:destroyChildren()
end
function toggle()
if vipButton:isOn() then
vipWindow:close()
vipButton:setOn(false)
else
vipWindow:open()
vipButton:setOn(true)
end
end
function onMiniWindowClose()
vipButton:setOn(false)
end
function createAddWindow()
addVipWindow = g_ui.displayUI('addvip.otui')
end
function destroyAddWindow()
addVipWindow:destroy()
addVipWindow = nil
end
function addVip()
g_game.addVip(addVipWindow:getChildById('name'):getText())
destroyAddWindow()
end
function onAddVip(id, name, state)
local vipList = vipWindow:getChildById('contentsPanel')
local label = g_ui.createWidget('VipListLabel')
label.onMousePress = onVipListLabelMousePress
label:setId('vip' .. id)
label:setText(name)
if state == VipState.Online then
label:setColor('#00ff00')
elseif state == VipState.Pending then
label:setColor('#ffca38')
else
label:setColor('#ff0000')
end
label.vipState = state
label:setPhantom(false)
connect(label, { onDoubleClick = function () g_game.openPrivateChannel(label:getText()) return true end } )
local nameLower = name:lower()
local childrenCount = vipList:getChildCount()
for i=1,childrenCount do
local child = vipList:getChildByIndex(i)
if state == VipState.Online and not child.vipState == VipState.Online then
vipList:insertChild(i, label)
return
end
if (not state == VipState.Online and not child.vipState == VipState.Online)
or (state == VipState.Online and child.vipState == VipState.Online) then
local childText = child:getText():lower()
local length = math.min(childText:len(), nameLower:len())
for j=1,length do
if nameLower:byte(j) < childText:byte(j) then
vipList:insertChild(i, label)
return
elseif nameLower:byte(j) > childText:byte(j) then
break
end
end
end
end
vipList:insertChild(childrenCount+1, label)
end
function onVipStateChange(id, state)
local vipList = vipWindow:getChildById('contentsPanel')
local label = vipList:getChildById('vip' .. id)
local text = label:getText()
label:destroy()
onAddVip(id, text, state)
end
function onVipListMousePress(widget, mousePos, mouseButton)
if mouseButton ~= MouseRightButton then return end
local vipList = vipWindow:getChildById('contentsPanel')
local menu = g_ui.createWidget('PopupMenu')
menu:addOption(tr('Add new VIP'), function() createAddWindow() end)
menu:display(mousePos)
return true
end
function onVipListLabelMousePress(widget, mousePos, mouseButton)
if mouseButton ~= MouseRightButton then return end
local vipList = vipWindow:getChildById('contentsPanel')
local menu = g_ui.createWidget('PopupMenu')
menu:addOption(tr('Add new VIP'), function() createAddWindow() end)
menu:addOption(tr('Remove %s', widget:getText()), function() if widget then g_game.removeVip(widget:getId():sub(4)) vipList:removeChild(widget) end end)
menu:addSeparator()
menu:addOption(tr('Copy Name'), function() g_window.setClipboardText(widget:getText()) end)
menu:display(mousePos)
return true
end
|
vipWindow = nil
vipButton = nil
addVipWindow = nil
function init()
connect(g_game, { onGameEnd = clear,
onAddVip = onAddVip,
onVipStateChange = onVipStateChange })
g_keyboard.bindKeyDown('Ctrl+P', toggle)
vipButton = TopMenu.addRightGameToggleButton('vipListButton', tr('VIP list') .. ' (Ctrl+P)', 'viplist.png', toggle)
vipButton:setOn(true)
vipWindow = g_ui.loadUI('viplist.otui', modules.game_interface.getRightPanel())
refresh()
vipWindow:setup()
end
function terminate()
g_keyboard.unbindKeyDown('Ctrl+P')
disconnect(g_game, { onGameEnd = clear,
onAddVip = onAddVip,
onVipStateChange = onVipStateChange })
vipWindow:destroy()
vipButton:destroy()
end
function refresh()
clear()
for id,vip in pairs(g_game.getVips()) do
onAddVip(id, unpack(vip))
end
vipWindow:setContentMinimumHeight(38)
--vipWindow:setContentMaximumHeight(256)
end
function clear()
local vipList = vipWindow:getChildById('contentsPanel')
vipList:destroyChildren()
end
function toggle()
if vipButton:isOn() then
vipWindow:close()
vipButton:setOn(false)
else
vipWindow:open()
vipButton:setOn(true)
end
end
function onMiniWindowClose()
vipButton:setOn(false)
end
function createAddWindow()
addVipWindow = g_ui.displayUI('addvip.otui')
end
function destroyAddWindow()
addVipWindow:destroy()
addVipWindow = nil
end
function addVip()
g_game.addVip(addVipWindow:getChildById('name'):getText())
destroyAddWindow()
end
function onAddVip(id, name, state)
local vipList = vipWindow:getChildById('contentsPanel')
local label = g_ui.createWidget('VipListLabel')
label.onMousePress = onVipListLabelMousePress
label:setId('vip' .. id)
label:setText(name)
if state == VipState.Online then
label:setColor('#00ff00')
elseif state == VipState.Pending then
label:setColor('#ffca38')
else
label:setColor('#ff0000')
end
label.vipState = state
label:setPhantom(false)
connect(label, { onDoubleClick = function () g_game.openPrivateChannel(label:getText()) return true end } )
local nameLower = name:lower()
local childrenCount = vipList:getChildCount()
for i=1,childrenCount do
local child = vipList:getChildByIndex(i)
if state == VipState.Online and child.vipState ~= VipState.Online then
vipList:insertChild(i, label)
return
end
if (state ~= VipState.Online and child.vipState ~= VipState.Online)
or (state == VipState.Online and child.vipState == VipState.Online) then
local childText = child:getText():lower()
local length = math.min(childText:len(), nameLower:len())
for j=1,length do
if nameLower:byte(j) < childText:byte(j) then
vipList:insertChild(i, label)
return
elseif nameLower:byte(j) > childText:byte(j) then
break
elseif j == nameLower:len() then -- We are at the end of nameLower, and its shorter than childText, thus insert before
vipList:insertChild(i, label)
end
end
end
end
vipList:insertChild(childrenCount+1, label)
end
function onVipStateChange(id, state)
local vipList = vipWindow:getChildById('contentsPanel')
local label = vipList:getChildById('vip' .. id)
local text = label:getText()
label:destroy()
onAddVip(id, text, state)
end
function onVipListMousePress(widget, mousePos, mouseButton)
if mouseButton ~= MouseRightButton then return end
local vipList = vipWindow:getChildById('contentsPanel')
local menu = g_ui.createWidget('PopupMenu')
menu:addOption(tr('Add new VIP'), function() createAddWindow() end)
menu:display(mousePos)
return true
end
function onVipListLabelMousePress(widget, mousePos, mouseButton)
if mouseButton ~= MouseRightButton then return end
local vipList = vipWindow:getChildById('contentsPanel')
local menu = g_ui.createWidget('PopupMenu')
menu:addOption(tr('Add new VIP'), function() createAddWindow() end)
menu:addOption(tr('Remove %s', widget:getText()), function() if widget then g_game.removeVip(widget:getId():sub(4)) vipList:removeChild(widget) end end)
menu:addSeparator()
menu:addOption(tr('Copy Name'), function() g_window.setClipboardText(widget:getText()) end)
menu:display(mousePos)
return true
end
|
Fix Vip List sorting
|
Fix Vip List sorting
Fixes Vip list sorting issues for both alphabetical sorting and
online/offline sorting. Fixes Issue #169
Tested in 8.61
|
Lua
|
mit
|
dreamsxin/otclient,gpedro/otclient,Cavitt/otclient_mapgen,dreamsxin/otclient,EvilHero90/otclient,kwketh/otclient,gpedro/otclient,Cavitt/otclient_mapgen,Radseq/otclient,kwketh/otclient,dreamsxin/otclient,gpedro/otclient,EvilHero90/otclient,Radseq/otclient
|
c376d34e4fba71855eb2184170b27117b9f49135
|
regress/0-fnmatch.lua
|
regress/0-fnmatch.lua
|
#!/bin/sh
_=[[
. "${0%/*}/regress.sh"
exec runlua -r5.2 "$0" "$@"
]]
local unix = require"unix"
local regress = require"regress".export".*"
local function files_fnmatch(rootdir, patt)
return coroutine.wrap(function ()
local dir = assert(unix.opendir(rootdir))
for name, type in dir:files("name", "type") do
type = type or assert(unix.fstatat(dir, name, 0, "type"))
local _, matched = assert(unix.fnmatch(patt, name))
if matched and unix.S_ISREG(type) then
coroutine.yield(name)
end
end
end)
end
local function files_shfind(rootdir, patt)
local function quote(s)
return string.format("'%s'", s:gsub("'", "'\"'\"'"))
end
return coroutine.wrap(function ()
local fh = io.popen(string.format("cd %s && find . -maxdepth 1 -name %s -type f", quote(rootdir), quote(patt)), "r")
for ln in fh:lines() do
local name = ln:match("([^/]+)$")
if name then
coroutine.yield(name)
end
end
end)
end
local function files_fold(t, iter)
for name in iter do
t[#t + 1] = name
end
table.sort(t)
return t
end
local list_fnmatch = files_fold({}, files_fnmatch("/etc", "*s*"))
local list_shfind = files_fold({}, files_shfind("/etc", "*s*"))
for i=1,math.max(#list_fnmatch, #list_shfind) do
local a, b = list_fnmatch[i], list_shfind[i]
if a ~= b then
panic("discrepency between fnmatch(3) and find(1) (%s ~= %s)", tostring(a), tostring(b))
end
end
say"OK"
|
#!/bin/sh
_=[[
. "${0%/*}/regress.sh"
exec runlua -r5.2 "$0" "$@"
]]
local unix = require"unix"
local regress = require"regress".export".*"
local function files_fnmatch(rootdir, patt)
return coroutine.wrap(function ()
local dir = assert(unix.opendir(rootdir))
for name, type in dir:files("name", "type") do
type = type or assert(unix.fstatat(dir, name, unix.AT_SYMLINK_NOFOLLOW, "mode"))
local _, matched = assert(unix.fnmatch(patt, name))
if matched and unix.S_ISREG(type) then
coroutine.yield(name)
end
end
end)
end
local function files_shfind(rootdir, patt)
local function quote(s)
return string.format("'%s'", s:gsub("'", "'\"'\"'"))
end
return coroutine.wrap(function ()
local fh = io.popen(string.format("cd %s && find . -name . -o -type d -prune -o \\( -name %s -type f \\) -print 2>/dev/null", quote(rootdir), quote(patt)), "r")
for ln in fh:lines() do
local name = ln:match("([^/]+)$")
if name and name ~= "." then
coroutine.yield(name)
end
end
end)
end
local function files_fold(t, iter)
for name in iter do
t[#t + 1] = name
end
table.sort(t)
return t
end
local list_fnmatch = files_fold({}, files_fnmatch("/etc", "*s*"))
local list_shfind = files_fold({}, files_shfind("/etc", "*s*"))
for i=1,math.max(#list_fnmatch, #list_shfind) do
local a, b = list_fnmatch[i], list_shfind[i]
if a ~= b then
panic("discrepency between fnmatch(3) and find(1) (%s ~= %s)", tostring(a), tostring(b))
end
end
say"OK"
|
fix 0-fnmatch on solaris, which doesn't support a type field for readdir, nor -maxdepth for find utility
|
fix 0-fnmatch on solaris, which doesn't support a type field for readdir, nor -maxdepth for find utility
|
Lua
|
mit
|
Redfoxmoon3/lunix,Redfoxmoon3/lunix,wahern/lunix,wahern/lunix
|
e2eba69269d737da61ca7ea6cb988ad2b742757b
|
neovim/ftplugin/python.lua
|
neovim/ftplugin/python.lua
|
-- Configure auto formatting using isort and black.
-- Adapted from stylua-nvim:
-- https://github.com/ckipp01/stylua-nvim/blob/main/lua/stylua-nvim.lua
local function buf_get_full_text(bufnr)
local text = table.concat(vim.api.nvim_buf_get_lines(bufnr, 0, -1, true), "\n")
if vim.api.nvim_buf_get_option(bufnr, "eol") then
text = text .. "\n"
end
return text
end
local function format_buffer()
local isort_command = "isort --stdout --quiet - 2>/dev/null"
local black_command = "black --quiet - 2>/dev/null"
local bufnr = vim.fn.bufnr("%")
local input = buf_get_full_text(bufnr)
local output = input
for _, command in pairs({ isort_command, black_command }) do
output = vim.fn.system(command, output)
if vim.fn.empty(output) ~= 0 then
-- TODO: warn user about errors?
return
end
end
if output ~= input then
-- Save current view. We restore this on `BufWritePost` (see below).
-- Idea taken from https://github.com/nvim-treesitter/nvim-treesitter/issues/1424#issuecomment-909181939
vim.cmd("mkview")
local new_lines = vim.fn.split(output, "\n")
vim.api.nvim_buf_set_lines(0, 0, -1, false, new_lines)
vim.opt.foldmethod = vim.opt.foldmethod
end
end
local group = vim.api.nvim_create_augroup("python_format", { clear = true })
vim.api.nvim_create_autocmd({ "BufWritePre" }, {
group = group,
pattern = "*.py",
callback = format_buffer,
})
vim.api.nvim_create_autocmd({ "BufWritePost" }, {
group = group,
pattern = "*.py",
callback = function()
vim.cmd("edit")
vim.cmd("loadview")
end,
})
|
-- Configure auto formatting using isort and black.
-- Adapted from stylua-nvim:
-- https://github.com/ckipp01/stylua-nvim/blob/main/lua/stylua-nvim.lua
local function buf_get_full_text(bufnr)
local text = table.concat(vim.api.nvim_buf_get_lines(bufnr, 0, -1, true), "\n")
if vim.api.nvim_buf_get_option(bufnr, "eol") then
text = text .. "\n"
end
return text
end
local function format_buffer()
local isort_command = "isort --stdout --quiet - 2>/dev/null"
local black_command = "black --quiet - 2>/dev/null"
local bufnr = vim.fn.bufnr("%")
local input = buf_get_full_text(bufnr)
local output = input
for _, command in pairs({ isort_command, black_command }) do
output = vim.fn.system(command, output)
if vim.fn.empty(output) ~= 0 then
-- TODO: warn user about errors?
return
end
end
vim.cmd("mkview")
if output ~= input then
-- Save current view. We restore this on `BufWritePost` (see below).
-- Idea taken from https://github.com/nvim-treesitter/nvim-treesitter/issues/1424#issuecomment-909181939
local new_lines = vim.fn.split(output, "\n")
vim.api.nvim_buf_set_lines(0, 0, -1, false, new_lines)
vim.opt.foldmethod = vim.opt.foldmethod
end
end
local group = vim.api.nvim_create_augroup("python_format", { clear = true })
vim.api.nvim_create_autocmd({ "BufWritePre" }, {
group = group,
pattern = "*.py",
callback = format_buffer,
})
vim.api.nvim_create_autocmd({ "BufWritePost" }, {
group = group,
pattern = "*.py",
callback = function()
vim.cmd("edit")
vim.cmd("loadview")
end,
})
|
Fix Python format on save when no changes
|
Fix Python format on save when no changes
|
Lua
|
mit
|
epwalsh/dotfiles,epwalsh/dotfiles
|
adcb1bc4935043424989e9367e95825af9e1941e
|
AceGUI-3.0/widgets/AceGUIContainer-ScrollFrame.lua
|
AceGUI-3.0/widgets/AceGUIContainer-ScrollFrame.lua
|
--[[-----------------------------------------------------------------------------
ScrollFrame Container
Plain container that scrolls its content and doesn't grow in height.
-------------------------------------------------------------------------------]]
local Type, Version = "ScrollFrame", 22
local AceGUI = LibStub and LibStub("AceGUI-3.0", true)
if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end
-- Lua APIs
local pairs, assert, type = pairs, assert, type
local min, max, floor, abs = math.min, math.max, math.floor, math.abs
-- WoW APIs
local CreateFrame, UIParent = CreateFrame, UIParent
--[[-----------------------------------------------------------------------------
Support functions
-------------------------------------------------------------------------------]]
local function FixScrollOnUpdate(frame)
frame:SetScript("OnUpdate", nil)
frame.obj:FixScroll()
end
--[[-----------------------------------------------------------------------------
Scripts
-------------------------------------------------------------------------------]]
local function ScrollFrame_OnMouseWheel(frame, value)
frame.obj:MoveScroll(value)
end
local function ScrollFrame_OnSizeChanged(frame)
frame:SetScript("OnUpdate", FixScrollOnUpdate)
end
local function ScrollBar_OnScrollValueChanged(frame, value)
frame.obj:SetScroll(value)
end
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
["OnAcquire"] = function(self)
self:SetScroll(0)
self:FixScroll()
end,
["OnRelease"] = function(self)
self.status = nil
for k in pairs(self.localstatus) do
self.localstatus[k] = nil
end
self.scrollframe:SetPoint("BOTTOMRIGHT")
self.scrollbar:Hide()
self.scrollBarShown = nil
self.content.height, self.content.width = nil, nil
end,
["SetScroll"] = function(self, value)
local status = self.status or self.localstatus
local viewheight = self.scrollframe:GetHeight()
local height = self.content:GetHeight()
local offset
if viewheight > height then
offset = 0
else
offset = floor((height - viewheight) / 1000.0 * value)
end
self.content:ClearAllPoints()
self.content:SetPoint("TOPLEFT", 0, offset)
self.content:SetPoint("TOPRIGHT", 0, offset)
status.offset = offset
status.scrollvalue = value
end,
["MoveScroll"] = function(self, value)
local status = self.status or self.localstatus
local height, viewheight = self.scrollframe:GetHeight(), self.content:GetHeight()
if self.scrollBarShown then
local diff = height - viewheight
local delta = 1
if value < 0 then
delta = -1
end
self.scrollbar:SetValue(min(max(status.scrollvalue + delta*(1000/(diff/45)),0), 1000))
end
end,
["FixScroll"] = function(self)
if self.updateLock then return end
self.updateLock = true
local status = self.status or self.localstatus
local height, viewheight = self.scrollframe:GetHeight(), self.content:GetHeight()
local offset = status.offset or 0
local curvalue = self.scrollbar:GetValue()
-- Give us a margin of error of 2 pixels to stop some conditions that i would blame on floating point inaccuracys
-- No-one is going to miss 2 pixels at the bottom of the frame, anyhow!
if viewheight < height + 2 then
if self.scrollBarShown then
self.scrollBarShown = nil
self.scrollbar:Hide()
self.scrollbar:SetValue(0)
self.scrollframe:SetPoint("BOTTOMRIGHT")
self:DoLayout()
end
else
if not self.scrollBarShown then
self.scrollBarShown = true
self.scrollbar:Show()
self.scrollframe:SetPoint("BOTTOMRIGHT", -20, 0)
self:DoLayout()
end
local value = (offset / (viewheight - height) * 1000)
if value > 1000 then value = 1000 end
self.scrollbar:SetValue(value)
self:SetScroll(value)
if value < 1000 then
self.content:ClearAllPoints()
self.content:SetPoint("TOPLEFT", 0, offset)
self.content:SetPoint("TOPRIGHT", 0, offset)
status.offset = offset
end
end
self.updateLock = nil
end,
["LayoutFinished"] = function(self, width, height)
self.content:SetHeight(height or 0 + 20)
self.scrollframe:SetScript("OnUpdate", FixScrollOnUpdate)
end,
["SetStatusTable"] = function(self, status)
assert(type(status) == "table")
self.status = status
if not status.scrollvalue then
status.scrollvalue = 0
end
end,
["OnWidthSet"] = function(self, width)
local content = self.content
content.width = width
end,
["OnHeightSet"] = function(self, height)
local content = self.content
content.height = height
end
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local function Constructor()
local frame = CreateFrame("Frame", nil, UIParent)
local num = AceGUI:GetNextWidgetNum(Type)
local scrollframe = CreateFrame("ScrollFrame", nil, frame)
scrollframe:SetPoint("TOPLEFT")
scrollframe:SetPoint("BOTTOMRIGHT")
scrollframe:EnableMouseWheel(true)
scrollframe:SetScript("OnMouseWheel", ScrollFrame_OnMouseWheel)
scrollframe:SetScript("OnSizeChanged", ScrollFrame_OnSizeChanged)
local scrollbar = CreateFrame("Slider", ("AceConfigDialogScrollFrame%dScrollBar"):format(num), scrollframe, "UIPanelScrollBarTemplate")
scrollbar:SetPoint("TOPLEFT", scrollframe, "TOPRIGHT", 4, -16)
scrollbar:SetPoint("BOTTOMLEFT", scrollframe, "BOTTOMRIGHT", 4, 16)
scrollbar:SetMinMaxValues(0, 1000)
scrollbar:SetValueStep(1)
scrollbar:SetValue(0)
scrollbar:SetWidth(16)
scrollbar:Hide()
-- set the script as the last step, so it doesn't fire yet
scrollbar:SetScript("OnValueChanged", ScrollBar_OnScrollValueChanged)
local scrollbg = scrollbar:CreateTexture(nil, "BACKGROUND")
scrollbg:SetAllPoints(scrollbar)
scrollbg:SetTexture(0, 0, 0, 0.4)
--Container Support
local content = CreateFrame("Frame", nil, scrollframe)
content:SetPoint("TOPLEFT")
content:SetPoint("TOPRIGHT")
content:SetHeight(400)
scrollframe:SetScrollChild(content)
local widget = {
localstatus = { scrollvalue = 0 },
scrollframe = scrollframe,
scrollbar = scrollbar,
content = content,
frame = frame,
type = Type
}
for method, func in pairs(methods) do
widget[method] = func
end
scrollframe.obj, scrollbar.obj = widget, widget
return AceGUI:RegisterAsContainer(widget)
end
AceGUI:RegisterWidgetType(Type, Constructor, Version)
|
--[[-----------------------------------------------------------------------------
ScrollFrame Container
Plain container that scrolls its content and doesn't grow in height.
-------------------------------------------------------------------------------]]
local Type, Version = "ScrollFrame", 22
local AceGUI = LibStub and LibStub("AceGUI-3.0", true)
if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end
-- Lua APIs
local pairs, assert, type = pairs, assert, type
local min, max, floor, abs = math.min, math.max, math.floor, math.abs
-- WoW APIs
local CreateFrame, UIParent = CreateFrame, UIParent
--[[-----------------------------------------------------------------------------
Support functions
-------------------------------------------------------------------------------]]
local function FixScrollOnUpdate(frame)
frame:SetScript("OnUpdate", nil)
frame.obj:FixScroll()
end
--[[-----------------------------------------------------------------------------
Scripts
-------------------------------------------------------------------------------]]
local function ScrollFrame_OnMouseWheel(frame, value)
frame.obj:MoveScroll(value)
end
local function ScrollFrame_OnSizeChanged(frame)
frame:SetScript("OnUpdate", FixScrollOnUpdate)
end
local function ScrollBar_OnScrollValueChanged(frame, value)
frame.obj:SetScroll(value)
end
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
["OnAcquire"] = function(self)
self:SetScroll(0)
self.scrollframe:SetScript("OnUpdate", FixScrollOnUpdate)
end,
["OnRelease"] = function(self)
self.status = nil
for k in pairs(self.localstatus) do
self.localstatus[k] = nil
end
self.scrollframe:SetPoint("BOTTOMRIGHT")
self.scrollbar:Hide()
self.scrollBarShown = nil
self.content.height, self.content.width = nil, nil
end,
["SetScroll"] = function(self, value)
local status = self.status or self.localstatus
local viewheight = self.scrollframe:GetHeight()
local height = self.content:GetHeight()
local offset
if viewheight > height then
offset = 0
else
offset = floor((height - viewheight) / 1000.0 * value)
end
self.content:ClearAllPoints()
self.content:SetPoint("TOPLEFT", 0, offset)
self.content:SetPoint("TOPRIGHT", 0, offset)
status.offset = offset
status.scrollvalue = value
end,
["MoveScroll"] = function(self, value)
local status = self.status or self.localstatus
local height, viewheight = self.scrollframe:GetHeight(), self.content:GetHeight()
if self.scrollBarShown then
local diff = height - viewheight
local delta = 1
if value < 0 then
delta = -1
end
self.scrollbar:SetValue(min(max(status.scrollvalue + delta*(1000/(diff/45)),0), 1000))
end
end,
["FixScroll"] = function(self)
if self.updateLock then return end
self.updateLock = true
local status = self.status or self.localstatus
local height, viewheight = self.scrollframe:GetHeight(), self.content:GetHeight()
local offset = status.offset or 0
local curvalue = self.scrollbar:GetValue()
-- Give us a margin of error of 2 pixels to stop some conditions that i would blame on floating point inaccuracys
-- No-one is going to miss 2 pixels at the bottom of the frame, anyhow!
if viewheight < height + 2 then
if self.scrollBarShown then
self.scrollBarShown = nil
self.scrollbar:Hide()
self.scrollbar:SetValue(0)
self.scrollframe:SetPoint("BOTTOMRIGHT")
self:DoLayout()
end
else
if not self.scrollBarShown then
self.scrollBarShown = true
self.scrollbar:Show()
self.scrollframe:SetPoint("BOTTOMRIGHT", -20, 0)
self:DoLayout()
end
local value = (offset / (viewheight - height) * 1000)
if value > 1000 then value = 1000 end
self.scrollbar:SetValue(value)
self:SetScroll(value)
if value < 1000 then
self.content:ClearAllPoints()
self.content:SetPoint("TOPLEFT", 0, offset)
self.content:SetPoint("TOPRIGHT", 0, offset)
status.offset = offset
end
end
self.updateLock = nil
end,
["LayoutFinished"] = function(self, width, height)
self.content:SetHeight(height or 0 + 20)
self.scrollframe:SetScript("OnUpdate", FixScrollOnUpdate)
end,
["SetStatusTable"] = function(self, status)
assert(type(status) == "table")
self.status = status
if not status.scrollvalue then
status.scrollvalue = 0
end
end,
["OnWidthSet"] = function(self, width)
local content = self.content
content.width = width
end,
["OnHeightSet"] = function(self, height)
local content = self.content
content.height = height
end
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local function Constructor()
local frame = CreateFrame("Frame", nil, UIParent)
local num = AceGUI:GetNextWidgetNum(Type)
local scrollframe = CreateFrame("ScrollFrame", nil, frame)
scrollframe:SetPoint("TOPLEFT")
scrollframe:SetPoint("BOTTOMRIGHT")
scrollframe:EnableMouseWheel(true)
scrollframe:SetScript("OnMouseWheel", ScrollFrame_OnMouseWheel)
scrollframe:SetScript("OnSizeChanged", ScrollFrame_OnSizeChanged)
local scrollbar = CreateFrame("Slider", ("AceConfigDialogScrollFrame%dScrollBar"):format(num), scrollframe, "UIPanelScrollBarTemplate")
scrollbar:SetPoint("TOPLEFT", scrollframe, "TOPRIGHT", 4, -16)
scrollbar:SetPoint("BOTTOMLEFT", scrollframe, "BOTTOMRIGHT", 4, 16)
scrollbar:SetMinMaxValues(0, 1000)
scrollbar:SetValueStep(1)
scrollbar:SetValue(0)
scrollbar:SetWidth(16)
scrollbar:Hide()
-- set the script as the last step, so it doesn't fire yet
scrollbar:SetScript("OnValueChanged", ScrollBar_OnScrollValueChanged)
local scrollbg = scrollbar:CreateTexture(nil, "BACKGROUND")
scrollbg:SetAllPoints(scrollbar)
scrollbg:SetTexture(0, 0, 0, 0.4)
--Container Support
local content = CreateFrame("Frame", nil, scrollframe)
content:SetPoint("TOPLEFT")
content:SetPoint("TOPRIGHT")
content:SetHeight(400)
scrollframe:SetScrollChild(content)
local widget = {
localstatus = { scrollvalue = 0 },
scrollframe = scrollframe,
scrollbar = scrollbar,
content = content,
frame = frame,
type = Type
}
for method, func in pairs(methods) do
widget[method] = func
end
scrollframe.obj, scrollbar.obj = widget, widget
return AceGUI:RegisterAsContainer(widget)
end
AceGUI:RegisterWidgetType(Type, Constructor, Version)
|
AceGUI-3.0: Schedule a FixScroll instead of running it immediately to resolve a load-time layout issue
|
AceGUI-3.0: Schedule a FixScroll instead of running it immediately to resolve a load-time layout issue
git-svn-id: e768786be8df873dac9515156656ebbdc6d77160@1058 5debad98-a965-4143-8383-f471b3509dcf
|
Lua
|
bsd-3-clause
|
sarahgerweck/Ace3
|
0374d8bf1038849efa504afaab9d129e8e3cc0b9
|
Bilinear.lua
|
Bilinear.lua
|
local Bilinear, parent = torch.class('nn.Bilinear', 'nn.Module')
local function isint(x) return type(x) == 'number' and x == math.floor(x) end
function Bilinear:__assertInput(input)
assert(input and type(input) == 'table' and #input == 2,
'input should be a table containing two data Tensors')
assert(input[1]:nDimension() == 2 and input[2]:nDimension() == 2,
'input Tensors should be two-dimensional')
assert(input[1]:size(1) == input[2]:size(1),
'input Tensors should have the same number of rows (instances)')
assert(input[1]:size(2) == self.weight:size(2),
'dimensionality of first input is erroneous')
assert(input[2]:size(2) == self.weight:size(3),
'dimensionality of second input is erroneous')
end
function Bilinear:__assertInputGradOutput(input, gradOutput)
assert(input[1]:size(1) == gradOutput:size(1),
'number of rows in gradOutput does not match input')
assert(gradOutput:size(2) == self.weight:size(1),
'number of columns in gradOutput does not output size of layer')
end
function Bilinear:__init(inputSize1, inputSize2, outputSize, bias)
-- assertions:
assert(self and inputSize1 and inputSize2 and outputSize,
'should specify inputSize1 and inputSize2 and outputSize')
assert(isint(inputSize1) and isint(inputSize2) and isint(outputSize),
'inputSize1 and inputSize2 and outputSize should be integer numbers')
assert(inputSize1 > 0 and inputSize2 > 0 and outputSize > 0,
'inputSize1 and inputSize2 and outputSize should be positive numbers')
-- set up model:
parent.__init(self)
local bias = ((bias == nil) and true) or bias
self.weight = torch.Tensor(outputSize, inputSize1, inputSize2)
self.gradWeight = torch.Tensor(outputSize, inputSize1, inputSize2)
if bias then
self.bias = torch.Tensor(outputSize)
self.gradBias = torch.Tensor(outputSize)
end
self.gradInput = {torch.Tensor(), torch.Tensor()}
self:reset()
end
function Bilinear:reset(stdv)
assert(self)
if stdv then
assert(stdv and type(stdv) == 'number' and stdv > 0,
'standard deviation should be a positive number')
stdv = stdv * math.sqrt(3)
else
stdv = 1 / math.sqrt(self.weight:size(2))
end
self.weight:uniform(-stdv, stdv)
if self.bias then self.bias:uniform(-stdv, stdv) end
return self
end
function Bilinear:updateOutput(input)
assert(self)
self:__assertInput(input)
-- set up buffer:
self.buff2 = self.buff2 or input[1].new()
self.buff2:resizeAs(input[2])
-- compute output scores:
self.output:resize(input[1]:size(1), self.weight:size(1))
for k = 1,self.weight:size(1) do
torch.mm(self.buff2, input[1], self.weight[k])
self.buff2:cmul(input[2])
torch.sum(self.output:narrow(2, k, 1), self.buff2, 2)
end
if self.bias then
self.output:add(
self.bias:reshape(1, self.bias:nElement()):expandAs(self.output)
)
end
return self.output
end
function Bilinear:updateGradInput(input, gradOutput)
assert(self)
if self.gradInput then
self:__assertInputGradOutput(input, gradOutput)
if #self.gradInput == 0 then
for i = 1, 2 do self.gradInput[i] = input[1].new() end end
-- compute d output / d input:
self.gradInput[1]:resizeAs(input[1]):fill(0)
self.gradInput[2]:resizeAs(input[2]):fill(0)
-- do first slice of weight tensor (k = 1)
self.gradInput[1]:mm(input[2], self.weight[1]:t())
self.gradInput[1]:cmul(gradOutput:narrow(2,1,1):expand(self.gradInput[1]:size(1),
self.gradInput[1]:size(2)))
self.gradInput[2]:addmm(1, input[1], self.weight[1])
self.gradInput[2]:cmul(gradOutput:narrow(2,1,1):expand(self.gradInput[2]:size(1),
self.gradInput[2]:size(2)))
-- do remaining slices of weight tensor
if self.weight:size(1) > 1 then
self.buff1 = self.buff1 or input[1].new()
self.buff1:resizeAs(input[1])
for k = 2, self.weight:size(1) do
self.buff1:mm(input[2], self.weight[k]:t())
self.buff1:cmul(gradOutput:narrow(2,k,1):expand(self.gradInput[1]:size(1),
self.gradInput[1]:size(2)))
self.gradInput[1]:add(self.buff1)
self.buff2:mm(input[1], self.weight[k])
self.buff2:cmul(gradOutput:narrow(2,k,1):expand(self.gradInput[2]:size(1),
self.gradInput[2]:size(2)))
self.gradInput[2]:add(self.buff2)
end
end
return self.gradInput
end
end
function Bilinear:accGradParameters(input, gradOutput, scale)
local scale = scale or 1
self:__assertInputGradOutput(input, gradOutput)
assert(scale and type(scale) == 'number' and scale >= 0)
-- make sure we have buffer:
self.buff1 = self.buff1 or input[1].new()
self.buff1:resizeAs(input[1])
-- accumulate parameter gradients:
for k = 1,self.weight:size(1) do
torch.cmul(
self.buff1, input[1], gradOutput:narrow(2, k, 1):expandAs(input[1])
)
self.gradWeight[k]:addmm(self.buff1:t(), input[2])
end
if self.bias then self.gradBias:add(scale, gradOutput:sum(1)) end
end
-- we do not need to accumulate parameters when sharing:
Bilinear.sharedAccUpdateGradParameters = Bilinear.accUpdateGradParameters
function Bilinear:__tostring__()
return torch.type(self) ..
string.format(
'(%dx%d -> %d) %s',
self.weight:size(2), self.weight:size(3), self.weight:size(1),
(self.bias == nil and ' without bias' or '')
)
end
function Bilinear:clearState()
if self.buff2 then self.buff2:set() end
if self.buff1 then self.buff1:set() end
return parent.clearState(self)
end
|
local Bilinear, parent = torch.class('nn.Bilinear', 'nn.Module')
local function isint(x) return type(x) == 'number' and x == math.floor(x) end
function Bilinear:__assertInput(input)
assert(input and type(input) == 'table' and #input == 2,
'input should be a table containing two data Tensors')
assert(input[1]:nDimension() == 2 and input[2]:nDimension() == 2,
'input Tensors should be two-dimensional')
assert(input[1]:size(1) == input[2]:size(1),
'input Tensors should have the same number of rows (instances)')
assert(input[1]:size(2) == self.weight:size(2),
'dimensionality of first input is erroneous')
assert(input[2]:size(2) == self.weight:size(3),
'dimensionality of second input is erroneous')
end
function Bilinear:__assertInputGradOutput(input, gradOutput)
assert(input[1]:size(1) == gradOutput:size(1),
'number of rows in gradOutput does not match input')
assert(gradOutput:size(2) == self.weight:size(1),
'number of columns in gradOutput does not output size of layer')
end
function Bilinear:__init(inputSize1, inputSize2, outputSize, bias)
-- assertions:
assert(self and inputSize1 and inputSize2 and outputSize,
'should specify inputSize1 and inputSize2 and outputSize')
assert(isint(inputSize1) and isint(inputSize2) and isint(outputSize),
'inputSize1 and inputSize2 and outputSize should be integer numbers')
assert(inputSize1 > 0 and inputSize2 > 0 and outputSize > 0,
'inputSize1 and inputSize2 and outputSize should be positive numbers')
-- set up model:
parent.__init(self)
local bias = ((bias == nil) and true) or bias
self.weight = torch.Tensor(outputSize, inputSize1, inputSize2)
self.gradWeight = torch.Tensor(outputSize, inputSize1, inputSize2)
if bias then
self.bias = torch.Tensor(outputSize)
self.gradBias = torch.Tensor(outputSize)
end
self.gradInput = {torch.Tensor(), torch.Tensor()}
self:reset()
end
function Bilinear:reset(stdv)
assert(self)
if stdv then
assert(stdv and type(stdv) == 'number' and stdv > 0,
'standard deviation should be a positive number')
stdv = stdv * math.sqrt(3)
else
stdv = 1 / math.sqrt(self.weight:size(2))
end
self.weight:uniform(-stdv, stdv)
if self.bias then self.bias:uniform(-stdv, stdv) end
return self
end
function Bilinear:updateOutput(input)
assert(self)
self:__assertInput(input)
-- set up buffer:
self.buff2 = self.buff2 or input[1].new()
self.buff2:resizeAs(input[2])
-- compute output scores:
self.output:resize(input[1]:size(1), self.weight:size(1))
for k = 1,self.weight:size(1) do
torch.mm(self.buff2, input[1], self.weight[k])
self.buff2:cmul(input[2])
torch.sum(self.output:narrow(2, k, 1), self.buff2, 2)
end
if self.bias then
self.output:add(
self.bias:reshape(1, self.bias:nElement()):expandAs(self.output)
)
end
return self.output
end
function Bilinear:updateGradInput(input, gradOutput)
assert(self)
if self.gradInput then
self:__assertInputGradOutput(input, gradOutput)
if #self.gradInput == 0 then
for i = 1, 2 do self.gradInput[i] = input[1].new() end
end
-- compute d output / d input:
self.gradInput[1]:resizeAs(input[1]):fill(0)
self.gradInput[2]:resizeAs(input[2]):fill(0)
-- do first slice of weight tensor (k = 1)
self.gradInput[1]:mm(input[2], self.weight[1]:t())
self.gradInput[1]:cmul(gradOutput:narrow(2,1,1):expand(self.gradInput[1]:size(1),
self.gradInput[1]:size(2)))
self.gradInput[2]:addmm(1, input[1], self.weight[1])
self.gradInput[2]:cmul(gradOutput:narrow(2,1,1):expand(self.gradInput[2]:size(1),
self.gradInput[2]:size(2)))
-- do remaining slices of weight tensor
if self.weight:size(1) > 1 then
self.buff1 = self.buff1 or input[1].new()
self.buff1:resizeAs(input[1])
for k = 2, self.weight:size(1) do
self.buff1:mm(input[2], self.weight[k]:t())
self.buff1:cmul(gradOutput:narrow(2,k,1):expand(self.gradInput[1]:size(1),
self.gradInput[1]:size(2)))
self.gradInput[1]:add(self.buff1)
self.buff2:mm(input[1], self.weight[k])
self.buff2:cmul(gradOutput:narrow(2,k,1):expand(self.gradInput[2]:size(1),
self.gradInput[2]:size(2)))
self.gradInput[2]:add(self.buff2)
end
end
return self.gradInput
end
end
function Bilinear:accGradParameters(input, gradOutput, scale)
local scale = scale or 1
self:__assertInputGradOutput(input, gradOutput)
assert(scale and type(scale) == 'number' and scale >= 0)
-- make sure we have buffer:
self.buff1 = self.buff1 or input[1].new()
self.buff1:resizeAs(input[1])
-- accumulate parameter gradients:
for k = 1,self.weight:size(1) do
torch.cmul(
self.buff1, input[1], gradOutput:narrow(2, k, 1):expandAs(input[1])
)
self.gradWeight[k]:addmm(self.buff1:t(), input[2])
end
if self.bias then self.gradBias:add(scale, gradOutput:sum(1)) end
end
-- we do not need to accumulate parameters when sharing:
Bilinear.sharedAccUpdateGradParameters = Bilinear.accUpdateGradParameters
function Bilinear:__tostring__()
return torch.type(self) ..
string.format(
'(%dx%d -> %d) %s',
self.weight:size(2), self.weight:size(3), self.weight:size(1),
(self.bias == nil and ' without bias' or '')
)
end
function Bilinear:clearState()
if self.buff2 then self.buff2:set() end
if self.buff1 then self.buff1:set() end
return parent.clearState(self)
end
|
Fix unclosed if statement.
|
Fix unclosed if statement.
|
Lua
|
bsd-3-clause
|
sagarwaghmare69/nn,joeyhng/nn,eriche2016/nn,apaszke/nn,nicholas-leonard/nn,colesbury/nn
|
84039ae1be911cc0424a5262706cc48f4ec2a380
|
src/websocket/server_ev.lua
|
src/websocket/server_ev.lua
|
local socket = require'socket'
local tools = require'websocket.tools'
local frame = require'websocket.frame'
local handshake = require'websocket.handshake'
local tconcat = table.concat
local tinsert = table.insert
local ev
local loop
local clients = {}
local client = function(sock,protocol)
assert(sock)
sock:setoption('tcp-nodelay',true)
local fd = sock:getfd()
local message_io
local close_timer
local async_send = require'websocket.ev_common'.async_send(sock,loop)
local self = {}
self.state = 'OPEN'
local user_on_error
local on_error = function(s,err)
clients[protocol][self] = nil
if user_on_error then
user_on_error(self,err)
else
print('Websocket server error',err)
end
end
local user_on_close
local on_close = function(was_clean,code,reason)
clients[protocol][self] = nil
if close_timer then
close_timer:stop(loop)
close_timer = nil
end
message_io:stop(loop)
self.state = 'CLOSED'
if user_on_close then
user_on_close(self,was_clean,code,reason or '')
end
sock:shutdown()
sock:close()
end
local handle_sock_err = function(err)
if err == 'closed' then
if self.state ~= 'CLOSED' then
on_close(false,1006,'')
end
else
on_error(err)
end
end
local user_on_message
local on_message = function(message,opcode)
if opcode == frame.TEXT or opcode == frame.BINARY then
if user_on_message then
user_on_message(self,message,opcode)
end
elseif opcode == frame.CLOSE then
if self.state ~= 'CLOSING' then
self.state = 'CLOSING'
local code,reason = frame.decode_close(message)
local encoded = frame.encode_close(code)
encoded = frame.encode(encoded,frame.CLOSE)
async_send(encoded,
function()
on_close(true,code or 1006,reason)
end,handle_sock_err)
else
on_close(true,code or 1006,reason)
end
end
end
self.send = function(_,message,opcode)
local encoded = frame.encode(message,opcode or frame.TEXT)
async_send(encoded)
end
message_io = require'websocket.ev_common'.message_io(
sock,loop,
on_message,
handle_sock_err)
self.on_close = function(_,on_close_arg)
user_on_close = on_close_arg
end
self.on_error = function(_,on_error_arg)
user_on_error = on_error_arg
end
self.on_message = function(_,on_message_arg)
user_on_message = on_message_arg
on_message = on_message_arg
end
self.broadcast = function(_,...)
for client in pairs(clients[protocol]) do
if client.state == 'OPEN' then
client:send(...)
end
end
end
self.close = function(_,code,reason,timeout)
clients[protocol][self] = nil
if self.state == 'OPEN' then
self.state = 'CLOSING'
assert(message_io)
timeout = timeout or 3
local encoded = frame.encode_close(code or 1000,reason or '')
encoded = frame.encode(encoded,frame.CLOSE)
async_send(encoded)
close_timer = ev.Timer.new(function()
close_timer = nil
on_close(false,1006,'timeout')
end,timeout)
close_timer:start(loop)
end
end
return self
end
local listen = function(opts)
assert(opts and (opts.protocols or opts.default))
ev = require'ev'
loop = opts.loop or ev.Loop.default
local on_error = function(s,err) print(err) end
local protocols = {}
if opts.protocols then
for protocol in pairs(opts.protocols) do
clients[protocol] = {}
tinsert(protocols,protocol)
end
end
local self = {}
local listener,err = socket.bind(opts.interface or '*',opts.port or 80)
assert(listener,err)
listener:settimeout(0)
local listen_io = ev.IO.new(
function()
local client_sock = listener:accept()
client_sock:settimeout(0)
assert(client_sock)
local request = {}
ev.IO.new(
function(loop,read_io)
repeat
local line,err,part = client_sock:receive('*l')
if line then
if last then
line = last..line
last = nil
end
request[#request+1] = line
elseif err ~= 'timeout' then
on_error(self,'Websocket Handshake failed due to socket err:'..err)
read_io:stop(loop)
return
else
last = part
return
end
until line == ''
read_io:stop(loop)
local upgrade_request = tconcat(request,'\r\n')
local response,protocol = handshake.accept_upgrade(upgrade_request,protocols)
if not response then
print('Handshake failed, Request:')
print(upgrade_request)
client_sock:close()
return
end
local index
ev.IO.new(
function(loop,write_io)
local len = #response
local sent,err = client_sock:send(response,index)
if not sent then
write_io:stop(loop)
print('Websocket client closed while handshake',err)
elseif sent == len then
write_io:stop(loop)
if protocol and opts.protocols[protocol] then
local new_client = client(client_sock,protocol)
clients[protocol][new_client] = true
opts.protocols[protocol](new_client)
elseif opts.default then
local new_client = client(client_sock)
opts.default(new_client)
else
print('Unsupported protocol:',protocol or '"null"')
end
else
assert(sent < len)
index = sent
end
end,client_sock:getfd(),ev.WRITE):start(loop)
end,client_sock:getfd(),ev.READ):start(loop)
end,listener:getfd(),ev.READ)
self.close = function(keep_clients)
listen_io:stop(loop)
listener:close()
listener = nil
if not keep_clients then
for protocol,clients in pairs(clients) do
for client in pairs(clients) do
client:close()
end
end
end
end
listen_io:start(loop)
return self
end
return {
listen = listen
}
|
local socket = require'socket'
local tools = require'websocket.tools'
local frame = require'websocket.frame'
local handshake = require'websocket.handshake'
local tconcat = table.concat
local tinsert = table.insert
local ev
local loop
local clients = {}
local client = function(sock,protocol)
assert(sock)
sock:setoption('tcp-nodelay',true)
local fd = sock:getfd()
local message_io
local close_timer
local async_send = require'websocket.ev_common'.async_send(sock,loop)
local self = {}
self.state = 'OPEN'
local user_on_error
local on_error = function(s,err)
clients[protocol][self] = nil
if user_on_error then
user_on_error(self,err)
else
print('Websocket server error',err)
end
end
local user_on_close
local on_close = function(was_clean,code,reason)
clients[protocol][self] = nil
if close_timer then
close_timer:stop(loop)
close_timer = nil
end
message_io:stop(loop)
self.state = 'CLOSED'
if user_on_close then
user_on_close(self,was_clean,code,reason or '')
end
sock:shutdown()
sock:close()
end
local handle_sock_err = function(err)
if err == 'closed' then
if self.state ~= 'CLOSED' then
on_close(false,1006,'')
end
else
on_error(err)
end
end
local user_on_message
local on_message = function(message,opcode)
if opcode == frame.TEXT or opcode == frame.BINARY then
if user_on_message then
user_on_message(self,message,opcode)
end
elseif opcode == frame.CLOSE then
if self.state ~= 'CLOSING' then
self.state = 'CLOSING'
local code,reason = frame.decode_close(message)
local encoded = frame.encode_close(code)
encoded = frame.encode(encoded,frame.CLOSE)
async_send(encoded,
function()
on_close(true,code or 1006,reason)
end,handle_sock_err)
else
on_close(true,code or 1006,reason)
end
end
end
self.send = function(_,message,opcode)
local encoded = frame.encode(message,opcode or frame.TEXT)
async_send(encoded)
end
message_io = require'websocket.ev_common'.message_io(
sock,loop,
on_message,
handle_sock_err)
self.on_close = function(_,on_close_arg)
user_on_close = on_close_arg
end
self.on_error = function(_,on_error_arg)
user_on_error = on_error_arg
end
self.on_message = function(_,on_message_arg)
user_on_message = on_message_arg
end
self.broadcast = function(_,...)
for client in pairs(clients[protocol]) do
if client.state == 'OPEN' then
client:send(...)
end
end
end
self.close = function(_,code,reason,timeout)
clients[protocol][self] = nil
if self.state == 'OPEN' then
self.state = 'CLOSING'
assert(message_io)
timeout = timeout or 3
local encoded = frame.encode_close(code or 1000,reason or '')
encoded = frame.encode(encoded,frame.CLOSE)
async_send(encoded)
close_timer = ev.Timer.new(function()
close_timer = nil
on_close(false,1006,'timeout')
end,timeout)
close_timer:start(loop)
end
end
return self
end
local listen = function(opts)
assert(opts and (opts.protocols or opts.default))
ev = require'ev'
loop = opts.loop or ev.Loop.default
local on_error = function(s,err) print(err) end
local protocols = {}
if opts.protocols then
for protocol in pairs(opts.protocols) do
clients[protocol] = {}
tinsert(protocols,protocol)
end
end
local self = {}
local listener,err = socket.bind(opts.interface or '*',opts.port or 80)
assert(listener,err)
listener:settimeout(0)
local listen_io = ev.IO.new(
function()
local client_sock = listener:accept()
client_sock:settimeout(0)
assert(client_sock)
local request = {}
ev.IO.new(
function(loop,read_io)
repeat
local line,err,part = client_sock:receive('*l')
if line then
if last then
line = last..line
last = nil
end
request[#request+1] = line
elseif err ~= 'timeout' then
on_error(self,'Websocket Handshake failed due to socket err:'..err)
read_io:stop(loop)
return
else
last = part
return
end
until line == ''
read_io:stop(loop)
local upgrade_request = tconcat(request,'\r\n')
local response,protocol = handshake.accept_upgrade(upgrade_request,protocols)
if not response then
print('Handshake failed, Request:')
print(upgrade_request)
client_sock:close()
return
end
local index
ev.IO.new(
function(loop,write_io)
local len = #response
local sent,err = client_sock:send(response,index)
if not sent then
write_io:stop(loop)
print('Websocket client closed while handshake',err)
elseif sent == len then
write_io:stop(loop)
if protocol and opts.protocols[protocol] then
local new_client = client(client_sock,protocol)
clients[protocol][new_client] = true
opts.protocols[protocol](new_client)
elseif opts.default then
local new_client = client(client_sock)
opts.default(new_client)
else
print('Unsupported protocol:',protocol or '"null"')
end
else
assert(sent < len)
index = sent
end
end,client_sock:getfd(),ev.WRITE):start(loop)
end,client_sock:getfd(),ev.READ):start(loop)
end,listener:getfd(),ev.READ)
self.close = function(keep_clients)
listen_io:stop(loop)
listener:close()
listener = nil
if not keep_clients then
for protocol,clients in pairs(clients) do
for client in pairs(clients) do
client:close()
end
end
end
end
listen_io:start(loop)
return self
end
return {
listen = listen
}
|
fix overwrite private on_message
|
fix overwrite private on_message
|
Lua
|
mit
|
lipp/lua-websockets,lipp/lua-websockets,KSDaemon/lua-websockets,OptimusLime/lua-websockets,enginix/lua-websockets,OptimusLime/lua-websockets,lipp/lua-websockets,OptimusLime/lua-websockets,enginix/lua-websockets,KSDaemon/lua-websockets,KSDaemon/lua-websockets,enginix/lua-websockets
|
623e14c7ffa7e265da117fd96554caf589969a15
|
plugins/mod_tls.lua
|
plugins/mod_tls.lua
|
-- Prosody IM v0.2
-- Copyright (C) 2008 Matthew Wild
-- Copyright (C) 2008 Waqas Hussain
--
-- This program is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
--
local st = require "util.stanza";
--local sessions = sessions;
local t_insert = table.insert;
local log = require "util.logger".init("mod_starttls");
local xmlns_starttls ='urn:ietf:params:xml:ns:xmpp-tls';
module:add_handler("c2s_unauthed", "starttls", xmlns_starttls,
function (session, stanza)
if session.conn.starttls then
session.send(st.stanza("proceed", { xmlns = xmlns_starttls }));
-- FIXME: I'm commenting the below, not sure why it was necessary
-- sessions[session.conn] = nil;
session:reset_stream();
session.conn.starttls();
session.log("info", "TLS negotiation started...");
else
-- FIXME: What reply?
session.log("warn", "Attempt to start TLS, but TLS is not available on this connection");
end
end);
local starttls_attr = { xmlns = xmlns_starttls };
module:add_event_hook("stream-features",
function (session, features)
if session.conn.starttls then
features:tag("starttls", starttls_attr):up();
end
end);
|
-- Prosody IM v0.2
-- Copyright (C) 2008 Matthew Wild
-- Copyright (C) 2008 Waqas Hussain
--
-- This program is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
--
local st = require "util.stanza";
--local sessions = sessions;
local t_insert = table.insert;
local log = require "util.logger".init("mod_starttls");
local xmlns_starttls ='urn:ietf:params:xml:ns:xmpp-tls';
module:add_handler("c2s_unauthed", "starttls", xmlns_starttls,
function (session, stanza)
if session.conn.starttls then
session.send(st.stanza("proceed", { xmlns = xmlns_starttls }));
session:reset_stream();
session.conn.starttls();
session.log("info", "TLS negotiation started...");
else
-- FIXME: What reply?
session.log("warn", "Attempt to start TLS, but TLS is not available on this connection");
end
end);
local starttls_attr = { xmlns = xmlns_starttls };
module:add_event_hook("stream-features",
function (session, features)
if session.conn.starttls then
features:tag("starttls", starttls_attr):up();
end
end);
|
Remove a FIXME from mod_tls
|
Remove a FIXME from mod_tls
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
7f0ceff0741aa1fccdd60523d4d3788cfdae43a8
|
modules/self-test/test_runner.lua
|
modules/self-test/test_runner.lua
|
---
-- self-test/test_runner.lua
--
-- Execute unit tests and test suites.
--
-- Author Jason Perkins
-- Copyright (c) 2008-2016 Jason Perkins and the Premake project.
---
local p = premake
local m = p.modules.self_test
local _ = {}
function m.runTest(test)
local scopedTestCall
if test.testFunction then
scopedTestCall = _.runTest
elseif test.suite then
scopedTestCall = _.runTestSuite
else
scopedTestCall = _.runAllTests
end
return scopedTestCall(test)
end
function _.runAllTests()
local passed = 0
local failed = 0
local suites = m.getSuites()
for suiteName, suite in pairs(suites) do
if not m.isSuppressed(suiteName) then
local test = {}
test.suiteName = suiteName
test.suite = suite
local suitePassed, suiteFailed = _.runTestSuite(test)
passed = passed + suitePassed
failed = failed + suiteFailed
end
end
return passed, failed
end
function _.runTestSuite(test)
local passed = 0
local failed = 0
for testName, testFunction in pairs(test.suite) do
test.testName = testName
test.testFunction = testFunction
if m.isValid(test) and not m.isSuppressed(test.suiteName .. "." .. test.testName) then
if _.runTest(test) then
passed = passed + 1
else
failed = failed + 1
end
end
end
return passed, failed
end
function _.runTest(test)
local hooks = _.installTestingHooks()
_TESTS_DIR = test.suite._TESTS_DIR
_SCRIPT_DIR = test.suite._SCRIPT_DIR
local ok, err = _.setupTest(test)
if ok then
ok, err = _.executeTest(test)
end
local tok, terr = _.teardownTest(test)
ok = ok and tok
err = err or terr
if not ok then
m.print(string.format("%s.%s: %s", test.suiteName, test.testName, err))
end
_.removeTestingHooks(hooks)
return ok, err
end
function _.installTestingHooks()
local hooks = {}
hooks.action = _ACTION
hooks.options = _OPTIONS
hooks.os = _OS
hooks.io_open = io.open
hooks.io_output = io.output
hooks.os_writefile_ifnotequal = os.writefile_ifnotequal
hooks.p_utf8 = p.utf8
hooks.print = print
local mt = getmetatable(io.stderr)
_.builtin_write = mt.write
mt.write = _.stub_stderr_write
_OPTIONS = {}
setmetatable(_OPTIONS, getmetatable(hooks.options))
io.open = _.stub_io_open
io.output = _.stub_io_output
os.writefile_ifnotequal = _.stub_os_writefile_ifnotequal
print = _.stub_print
p.utf8 = _.stub_utf8
stderr_capture = nil
p.clearWarnings()
p.eol("\n")
p.escaper(nil)
p.indent("\t")
p.api.reset()
m.stderr_capture = nil
m.value_openedfilename = nil
m.value_openedfilemode = nil
m.value_closedfile = false
return hooks
end
function _.removeTestingHooks(hooks)
_ACTION = hooks.action
_OPTIONS = hooks.options
_OS = hooks.os
io.open = hooks.io_open
io.output = hooks.io_output
os.writefile_ifnotequal = hooks.os_writefile_ifnotequal
p.utf8 = hooks.p_utf8
print = hooks.print
local mt = getmetatable(io.stderr)
mt.write = _.builtin_write
end
function _.setupTest(test)
if type(test.suite.setup) == "function" then
return xpcall(test.suite.setup, _.errorHandler)
else
return true
end
end
function _.executeTest(test)
local result, err
p.capture(function()
result, err = xpcall(test.testFunction, _.errorHandler)
end)
return result, err
end
function _.teardownTest(test)
if type(test.suite.teardown) == "function" then
return xpcall(test.suite.teardown, _.errorHandler)
else
return true
end
end
function _.errorHandler(err)
local msg = err
-- if the error doesn't include a stack trace, add one
if not msg:find("stack traceback:", 1, true) then
msg = debug.traceback(err, 2)
end
-- trim of the trailing context of the originating xpcall
local i = msg:find("[C]: in function 'xpcall'", 1, true)
if i then
msg = msg:sub(1, i - 3)
end
-- if the resulting stack trace is only one level deep, ignore it
local n = select(2, msg:gsub('\n', '\n'))
if n == 2 then
msg = msg:sub(1, msg:find('\n', 1, true) - 1)
end
return msg
end
function _.stub_io_open(fname, mode)
m.value_openedfilename = fname
m.value_openedfilemode = mode
return {
close = function()
m.value_closedfile = true
end
}
end
function _.stub_io_output(f)
end
function _.stub_os_writefile_ifnotequal(content, fname)
m.value_openedfilename = fname
m.value_closedfile = true
return 0
end
function _.stub_print(s)
end
function _.stub_stderr_write(...)
if select(1, ...) == io.stderr then
m.stderr_capture = (m.stderr_capture or "") .. select(2, ...)
else
return _.builtin_write(...)
end
end
function _.stub_utf8()
end
|
---
-- self-test/test_runner.lua
--
-- Execute unit tests and test suites.
--
-- Author Jason Perkins
-- Copyright (c) 2008-2016 Jason Perkins and the Premake project.
---
local p = premake
local m = p.modules.self_test
local _ = {}
function m.runTest(test)
local scopedTestCall
if test.testFunction then
scopedTestCall = _.runTest
elseif test.suite then
scopedTestCall = _.runTestSuite
else
scopedTestCall = _.runAllTests
end
return scopedTestCall(test)
end
function _.runAllTests()
local passed = 0
local failed = 0
local suites = m.getSuites()
for suiteName, suite in pairs(suites) do
if not m.isSuppressed(suiteName) then
local test = {}
test.suiteName = suiteName
test.suite = suite
local suitePassed, suiteFailed = _.runTestSuite(test)
passed = passed + suitePassed
failed = failed + suiteFailed
end
end
return passed, failed
end
function _.runTestSuite(test)
local passed = 0
local failed = 0
for testName, testFunction in pairs(test.suite) do
test.testName = testName
test.testFunction = testFunction
if m.isValid(test) and not m.isSuppressed(test.suiteName .. "." .. test.testName) then
if _.runTest(test) then
passed = passed + 1
else
failed = failed + 1
end
end
end
return passed, failed
end
function _.runTest(test)
local hooks = _.installTestingHooks()
_TESTS_DIR = test.suite._TESTS_DIR
_SCRIPT_DIR = test.suite._SCRIPT_DIR
local ok, err = _.setupTest(test)
if ok then
ok, err = _.executeTest(test)
end
local tok, terr = _.teardownTest(test)
ok = ok and tok
err = err or terr
_.removeTestingHooks(hooks)
if ok then
return 1, 0
else
m.print(string.format("%s.%s: %s", test.suiteName, test.testName, err))
return 0, 1
end
end
function _.installTestingHooks()
local hooks = {}
hooks.action = _ACTION
hooks.options = _OPTIONS
hooks.os = _OS
hooks.io_open = io.open
hooks.io_output = io.output
hooks.os_writefile_ifnotequal = os.writefile_ifnotequal
hooks.p_utf8 = p.utf8
hooks.print = print
local mt = getmetatable(io.stderr)
_.builtin_write = mt.write
mt.write = _.stub_stderr_write
_OPTIONS = {}
setmetatable(_OPTIONS, getmetatable(hooks.options))
io.open = _.stub_io_open
io.output = _.stub_io_output
os.writefile_ifnotequal = _.stub_os_writefile_ifnotequal
print = _.stub_print
p.utf8 = _.stub_utf8
stderr_capture = nil
p.clearWarnings()
p.eol("\n")
p.escaper(nil)
p.indent("\t")
p.api.reset()
m.stderr_capture = nil
m.value_openedfilename = nil
m.value_openedfilemode = nil
m.value_closedfile = false
return hooks
end
function _.removeTestingHooks(hooks)
_ACTION = hooks.action
_OPTIONS = hooks.options
_OS = hooks.os
io.open = hooks.io_open
io.output = hooks.io_output
os.writefile_ifnotequal = hooks.os_writefile_ifnotequal
p.utf8 = hooks.p_utf8
print = hooks.print
local mt = getmetatable(io.stderr)
mt.write = _.builtin_write
end
function _.setupTest(test)
if type(test.suite.setup) == "function" then
return xpcall(test.suite.setup, _.errorHandler)
else
return true
end
end
function _.executeTest(test)
local result, err
p.capture(function()
result, err = xpcall(test.testFunction, _.errorHandler)
end)
return result, err
end
function _.teardownTest(test)
if type(test.suite.teardown) == "function" then
return xpcall(test.suite.teardown, _.errorHandler)
else
return true
end
end
function _.errorHandler(err)
local msg = err
-- if the error doesn't include a stack trace, add one
if not msg:find("stack traceback:", 1, true) then
msg = debug.traceback(err, 2)
end
-- trim of the trailing context of the originating xpcall
local i = msg:find("[C]: in function 'xpcall'", 1, true)
if i then
msg = msg:sub(1, i - 3)
end
-- if the resulting stack trace is only one level deep, ignore it
local n = select(2, msg:gsub('\n', '\n'))
if n == 2 then
msg = msg:sub(1, msg:find('\n', 1, true) - 1)
end
return msg
end
function _.stub_io_open(fname, mode)
m.value_openedfilename = fname
m.value_openedfilemode = mode
return {
close = function()
m.value_closedfile = true
end
}
end
function _.stub_io_output(f)
end
function _.stub_os_writefile_ifnotequal(content, fname)
m.value_openedfilename = fname
m.value_closedfile = true
return 0
end
function _.stub_print(s)
end
function _.stub_stderr_write(...)
if select(1, ...) == io.stderr then
m.stderr_capture = (m.stderr_capture or "") .. select(2, ...)
else
return _.builtin_write(...)
end
end
function _.stub_utf8()
end
|
Fix crashing bug when `--test-only` argument is used to select a single ttest
|
Fix crashing bug when `--test-only` argument is used to select a single ttest
|
Lua
|
bsd-3-clause
|
premake/premake-core,LORgames/premake-core,jstewart-amd/premake-core,premake/premake-core,aleksijuvani/premake-core,soundsrc/premake-core,lizh06/premake-core,xriss/premake-core,Blizzard/premake-core,mendsley/premake-core,bravnsgaard/premake-core,resetnow/premake-core,TurkeyMan/premake-core,soundsrc/premake-core,soundsrc/premake-core,starkos/premake-core,sleepingwit/premake-core,dcourtois/premake-core,TurkeyMan/premake-core,Blizzard/premake-core,CodeAnxiety/premake-core,noresources/premake-core,premake/premake-core,resetnow/premake-core,tvandijck/premake-core,xriss/premake-core,starkos/premake-core,mandersan/premake-core,TurkeyMan/premake-core,xriss/premake-core,starkos/premake-core,starkos/premake-core,dcourtois/premake-core,TurkeyMan/premake-core,sleepingwit/premake-core,Zefiros-Software/premake-core,noresources/premake-core,LORgames/premake-core,Blizzard/premake-core,noresources/premake-core,TurkeyMan/premake-core,resetnow/premake-core,mandersan/premake-core,lizh06/premake-core,noresources/premake-core,jstewart-amd/premake-core,Zefiros-Software/premake-core,resetnow/premake-core,CodeAnxiety/premake-core,jstewart-amd/premake-core,tvandijck/premake-core,dcourtois/premake-core,lizh06/premake-core,premake/premake-core,starkos/premake-core,starkos/premake-core,aleksijuvani/premake-core,mendsley/premake-core,Zefiros-Software/premake-core,lizh06/premake-core,dcourtois/premake-core,jstewart-amd/premake-core,CodeAnxiety/premake-core,starkos/premake-core,Zefiros-Software/premake-core,mendsley/premake-core,premake/premake-core,sleepingwit/premake-core,xriss/premake-core,noresources/premake-core,CodeAnxiety/premake-core,noresources/premake-core,resetnow/premake-core,sleepingwit/premake-core,aleksijuvani/premake-core,bravnsgaard/premake-core,tvandijck/premake-core,mandersan/premake-core,aleksijuvani/premake-core,soundsrc/premake-core,LORgames/premake-core,bravnsgaard/premake-core,xriss/premake-core,Blizzard/premake-core,dcourtois/premake-core,tvandijck/premake-core,jstewart-amd/premake-core,dcourtois/premake-core,soundsrc/premake-core,mendsley/premake-core,aleksijuvani/premake-core,bravnsgaard/premake-core,premake/premake-core,sleepingwit/premake-core,tvandijck/premake-core,bravnsgaard/premake-core,LORgames/premake-core,Blizzard/premake-core,LORgames/premake-core,Zefiros-Software/premake-core,dcourtois/premake-core,noresources/premake-core,mendsley/premake-core,mandersan/premake-core,CodeAnxiety/premake-core,Blizzard/premake-core,mandersan/premake-core,premake/premake-core
|
ee3942c2f5aeca2f7feb5fe1e566cdbb642e1b69
|
sslobby/gamemode/minigames/deathmatch/init.lua
|
sslobby/gamemode/minigames/deathmatch/init.lua
|
MINIGAME.Time = 60
MINIGAME.Weapons = {"weapon_crowbar", "weapon_frag", "weapon_smg1", "weapon_pistol", "weapon_shotgun"}
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:Start()
print(self.Name .. " has started.")
self.BaseClass.Start(self)
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:Finish(timeLimit)
self.BaseClass.Finish(self, timeLimit)
print(self.Name .. " has finished.")
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:HasRequirements(players, teams)
return teams > 1
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:PlayerLoadout(player)
for k, weapon in pairs(self.Weapons) do
player:Give(weapon)
end
player:GiveAmmo(2, "grenade")
player:GiveAmmo(500, "smg1")
player:GiveAmmo(500, "pistol")
player:GiveAmmo(1, "SMG1_Grenade")
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:DoPlayerDeath(victim, inflictor, dmginfo)
timer.Simple(0, function()
self:RemovePlayer(victim)
local won = self:AnnounceWin()
if (won) then
self:Finish()
end
end)
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:PlayerShouldTakeDamage(player, attacker)
if (player:Team() == attacker:Team()) then
return false
end
end
|
MINIGAME.Time = 60
MINIGAME.Weapons = {"weapon_crowbar", "weapon_frag", "weapon_smg1", "weapon_pistol", "weapon_shotgun"}
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:Start()
print(self.Name .. " has started.")
self.BaseClass.Start(self)
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:Finish(timeLimit)
self.BaseClass.Finish(self, timeLimit)
print(self.Name .. " has finished.")
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:HasRequirements(players, teams)
return teams > 1
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:PlayerLoadout(player)
for k, weapon in pairs(self.Weapons) do
player:Give(weapon)
end
player:GiveAmmo(2, "grenade")
player:GiveAmmo(500, "smg1")
player:GiveAmmo(500, "pistol")
player:GiveAmmo(1, "SMG1_Grenade")
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:DoPlayerDeath(victim, inflictor, dmginfo)
timer.Simple(0, function()
self:RemovePlayer(victim)
local won = self:AnnounceWin()
if (won) then
self:Finish()
end
end)
end
---------------------------------------------------------
--
---------------------------------------------------------
function MINIGAME:PlayerShouldTakeDamage(player, attacker)
if (player.Team and attacker.Team and player:Team() == attacker:Team()) then
return false
end
end
|
Fixed an error with take damage (entities not both being players)
|
Fixed an error with take damage (entities not both being players)
|
Lua
|
bsd-3-clause
|
T3hArco/skeyler-gamemodes
|
a8a201ca77256b52930a424f7ac66f997db2dc5e
|
lua/entities/gmod_wire_grabber.lua
|
lua/entities/gmod_wire_grabber.lua
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Grabber"
ENT.RenderGroup = RENDERGROUP_BOTH
ENT.WireDebugName = "Grabber"
function ENT:SetupDataTables()
self:NetworkVar( "Float", 0, "BeamLength" )
end
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Inputs = Wire_CreateInputs(self, { "Grab","Strength (The strength of the weld. The weld will break if enough force is applied. Setting to zero makes the weld unbreakable.)","Range" })
self.Outputs = Wire_CreateOutputs(self, {"Holding", "Grabbed Entity [ENTITY]"})
self.WeldStrength = 0
self.Weld = nil
self.WeldEntity = nil
self.ExtraProp = nil
self.ExtraPropWeld = nil
self:GetPhysicsObject():SetMass(10)
self:Setup(100, true)
end
function ENT:OnRemove()
if self.Weld then
self:ResetGrab()
end
Wire_Remove(self)
end
function ENT:Setup(Range, Gravity)
if Range then self:SetBeamLength(Range) end
self.Gravity = Gravity
end
function ENT:LinkEnt( prop )
if not IsValid(prop) then return false, "Not a valid entity!" end
self.ExtraProp = prop
WireLib.SendMarks(self, {prop})
return true
end
function ENT:UnlinkEnt()
if IsValid(self.ExtraPropWeld) then
self.ExtraPropWeld:Remove()
self.ExtraPropWeld = nil
end
self.ExtraProp = nil
WireLib.SendMarks(self, {})
return true
end
function ENT:ResetGrab()
if IsValid(self.Weld) then
self.Weld:Remove()
if IsValid(self.WeldEntity) and IsValid(self.WeldEntity:GetPhysicsObject()) and self.Gravity then
self.WeldEntity:GetPhysicsObject():EnableGravity(true)
end
end
if IsValid(self.ExtraPropWeld) then
self.ExtraPropWeld:Remove()
end
self.Weld = nil
self.WeldEntity = nil
self.ExtraPropWeld = nil
self:SetColor(Color(255, 255, 255, self:GetColor().a))
Wire_TriggerOutput(self, "Holding", 0)
Wire_TriggerOutput(self, "Grabbed Entity", self.WeldEntity)
end
function ENT:CanGrab(trace)
if not trace.Entity or not isentity(trace.Entity) then return false end
if (not trace.Entity:IsValid() and not trace.Entity:IsWorld()) or trace.Entity:IsPlayer() then return false end
-- If there's no physics object then we can't constraint it!
if not util.IsValidPhysicsObject(trace.Entity, trace.PhysicsBone) then return false end
if not gamemode.Call( "CanTool", self:GetPlayer(), trace, "weld" ) then return false end
return true
end
function ENT:TriggerInput(iname, value)
if iname == "Grab" then
if value ~= 0 and self.Weld == nil then
local vStart = self:GetPos()
local vForward = self:GetUp()
local filter = ents.FindByClass( "gmod_wire_spawner" ) -- for prop spawning contraptions that grab spawned props
table.insert( filter, self )
local trace = util.TraceLine {
start = vStart,
endpos = vStart + (vForward * self:GetBeamLength()),
filter = filter
}
if not self:CanGrab(trace) then return end
-- Weld them!
local const = constraint.Weld(self, trace.Entity, 0, 0, self.WeldStrength)
if const then
const.Type = "" --prevents the duplicator from making this weld
end
local const2
--Msg("+Weld1\n")
if self.ExtraProp then
if self.ExtraProp:IsValid() then
const2 = constraint.Weld(self.ExtraProp, trace.Entity, 0, 0, self.WeldStrength)
if const2 then
const2.Type = "" --prevents the duplicator from making this weld
end
--Msg("+Weld2\n")
end
end
if self.Gravity then
trace.Entity:GetPhysicsObject():EnableGravity(false)
end
self.WeldEntity = trace.Entity
self.Weld = const
self.ExtraPropWeld = const2
self:SetColor(Color(255, 0, 0, self:GetColor().a))
Wire_TriggerOutput(self, "Holding", 1)
Wire_TriggerOutput(self, "Grabbed Entity", self.WeldEntity)
elseif value == 0 then
if self.Weld ~= nil or self.ExtraPropWeld ~= nil then
self:ResetGrab()
end
end
elseif iname == "Strength" then
self.WeldStrength = math.max(value,0)
elseif iname == "Range" then
self:SetBeamLength(math.Clamp(value,0,32000))
end
end
--duplicator support (TAD2020)
function ENT:BuildDupeInfo()
local info = BaseClass.BuildDupeInfo(self) or {}
if self.WeldEntity and self.WeldEntity:IsValid() then
info.WeldEntity = self.WeldEntity:EntIndex()
end
if self.ExtraProp and self.ExtraProp:IsValid() then
info.ExtraProp = self.ExtraProp:EntIndex()
end
return info
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
self.WeldEntity = GetEntByID(info.WeldEntity)
self.ExtraProp = GetEntByID(info.ExtraProp)
if self.WeldEntity and self.Inputs.Grab.Value ~= 0 then
if not self.Weld and self.trace~=nil then
self.Weld = constraint.Weld(self, self.trace, 0, 0, self.WeldStrength)
self.Weld.Type = "" --prevents the duplicator from making this weld
end
if IsValid(self.ExtraProp) then
self.ExtraPropWeld = constraint.Weld(self.ExtraProp, self.WeldEntity, 0, 0, self.WeldStrength)
self.ExtraPropWeld.Type = "" --prevents the duplicator from making this weld
end
if self.Gravity then
self.WeldEntity:GetPhysicsObject():EnableGravity(false)
end
if self.Weld then
self:SetColor(Color(255, 0, 0, self:GetColor().a))
Wire_TriggerOutput(self, "Holding", 1)
Wire_TriggerOutput(self, "Grabbed Entity", self.WeldEntity)
else
self:ResetGrab()
end
end
end
duplicator.RegisterEntityClass("gmod_wire_grabber", WireLib.MakeWireEnt, "Data", "Range", "Gravity")
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Grabber"
ENT.RenderGroup = RENDERGROUP_BOTH
ENT.WireDebugName = "Grabber"
function ENT:SetupDataTables()
self:NetworkVar( "Float", 0, "BeamLength" )
end
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Inputs = Wire_CreateInputs(self, { "Grab","Strength (The strength of the weld. The weld will break if enough force is applied. Setting to zero makes the weld unbreakable.)","Range" })
self.Outputs = Wire_CreateOutputs(self, {"Holding", "Grabbed Entity [ENTITY]"})
self.WeldStrength = 0
self.Weld = nil
self.WeldEntity = nil
self.EntHadGravity = true
self.ExtraProp = nil
self.ExtraPropWeld = nil
self:GetPhysicsObject():SetMass(10)
self:Setup(100, true)
end
function ENT:OnRemove()
if self.Weld then
self:ResetGrab()
end
Wire_Remove(self)
end
function ENT:Setup(Range, Gravity)
if Range then self:SetBeamLength(Range) end
self.Gravity = Gravity
end
function ENT:LinkEnt( prop )
if not IsValid(prop) then return false, "Not a valid entity!" end
self.ExtraProp = prop
WireLib.SendMarks(self, {prop})
return true
end
function ENT:UnlinkEnt()
if IsValid(self.ExtraPropWeld) then
self.ExtraPropWeld:Remove()
self.ExtraPropWeld = nil
end
self.ExtraProp = nil
WireLib.SendMarks(self, {})
return true
end
function ENT:ResetGrab()
if IsValid(self.Weld) then
self.Weld:Remove()
if self.EntHadGravity and IsValid(self.WeldEntity) and IsValid(self.WeldEntity:GetPhysicsObject()) and self.Gravity then
self.WeldEntity:GetPhysicsObject():EnableGravity(true)
end
end
if IsValid(self.ExtraPropWeld) then
self.ExtraPropWeld:Remove()
end
self.Weld = nil
self.WeldEntity = nil
self.ExtraPropWeld = nil
self:SetColor(Color(255, 255, 255, self:GetColor().a))
Wire_TriggerOutput(self, "Holding", 0)
Wire_TriggerOutput(self, "Grabbed Entity", self.WeldEntity)
end
function ENT:CanGrab(trace)
if not trace.Entity or not isentity(trace.Entity) then return false end
if (not trace.Entity:IsValid() and not trace.Entity:IsWorld()) or trace.Entity:IsPlayer() then return false end
-- If there's no physics object then we can't constraint it!
if not util.IsValidPhysicsObject(trace.Entity, trace.PhysicsBone) then return false end
if not gamemode.Call( "CanTool", self:GetPlayer(), trace, "weld" ) then return false end
return true
end
function ENT:TriggerInput(iname, value)
if iname == "Grab" then
if value ~= 0 and self.Weld == nil then
local vStart = self:GetPos()
local vForward = self:GetUp()
local filter = ents.FindByClass( "gmod_wire_spawner" ) -- for prop spawning contraptions that grab spawned props
table.insert( filter, self )
local trace = util.TraceLine {
start = vStart,
endpos = vStart + (vForward * self:GetBeamLength()),
filter = filter
}
if not self:CanGrab(trace) then return end
-- Weld them!
local const = constraint.Weld(self, trace.Entity, 0, 0, self.WeldStrength)
if const then
const.Type = "" --prevents the duplicator from making this weld
end
local const2
--Msg("+Weld1\n")
if self.ExtraProp then
if self.ExtraProp:IsValid() then
const2 = constraint.Weld(self.ExtraProp, trace.Entity, 0, 0, self.WeldStrength)
if const2 then
const2.Type = "" --prevents the duplicator from making this weld
end
--Msg("+Weld2\n")
end
end
if self.Gravity then
trace.Entity:GetPhysicsObject():EnableGravity(false)
end
self.WeldEntity = trace.Entity
self.Weld = const
self.ExtraPropWeld = const2
self.EntHadGravity = trace.Entity:GetPhysicsObject():IsGravityEnabled()
self:SetColor(Color(255, 0, 0, self:GetColor().a))
Wire_TriggerOutput(self, "Holding", 1)
Wire_TriggerOutput(self, "Grabbed Entity", self.WeldEntity)
elseif value == 0 then
if self.Weld ~= nil or self.ExtraPropWeld ~= nil then
self:ResetGrab()
end
end
elseif iname == "Strength" then
self.WeldStrength = math.max(value,0)
elseif iname == "Range" then
self:SetBeamLength(math.Clamp(value,0,32000))
end
end
--duplicator support (TAD2020)
function ENT:BuildDupeInfo()
local info = BaseClass.BuildDupeInfo(self) or {}
if self.WeldEntity and self.WeldEntity:IsValid() then
info.WeldEntity = self.WeldEntity:EntIndex()
end
if self.ExtraProp and self.ExtraProp:IsValid() then
info.ExtraProp = self.ExtraProp:EntIndex()
end
return info
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
self.WeldEntity = GetEntByID(info.WeldEntity)
self.ExtraProp = GetEntByID(info.ExtraProp)
if self.WeldEntity and self.Inputs.Grab.Value ~= 0 then
if not self.Weld and self.trace~=nil then
self.Weld = constraint.Weld(self, self.trace, 0, 0, self.WeldStrength)
self.Weld.Type = "" --prevents the duplicator from making this weld
end
if IsValid(self.ExtraProp) then
self.ExtraPropWeld = constraint.Weld(self.ExtraProp, self.WeldEntity, 0, 0, self.WeldStrength)
self.ExtraPropWeld.Type = "" --prevents the duplicator from making this weld
end
if self.Gravity then
self.WeldEntity:GetPhysicsObject():EnableGravity(false)
end
if self.Weld then
self:SetColor(Color(255, 0, 0, self:GetColor().a))
Wire_TriggerOutput(self, "Holding", 1)
Wire_TriggerOutput(self, "Grabbed Entity", self.WeldEntity)
else
self:ResetGrab()
end
end
end
duplicator.RegisterEntityClass("gmod_wire_grabber", WireLib.MakeWireEnt, "Data", "Range", "Gravity")
|
Fix grabber re-enabling gravity for props (#2251)
|
Fix grabber re-enabling gravity for props (#2251)
Fixes #2245
|
Lua
|
apache-2.0
|
dvdvideo1234/wire,wiremod/wire,Grocel/wire
|
2798c5a48d0c1a1faf19cc24933aa8f1202f7cf8
|
profiles/car.lua
|
profiles/car.lua
|
-- Begin of globals
bollards_whitelist = { [""] = true, ["cattle_grid"] = true, ["border_control"] = true, ["toll_booth"] = true, ["no"] = true, ["sally_port"] = true, ["gate"] = true}
access_tag_whitelist = { ["yes"] = true, ["motorcar"] = true, ["motor_vehicle"] = true, ["vehicle"] = true, ["permissive"] = true, ["designated"] = true }
access_tag_blacklist = { ["no"] = true, ["private"] = true, ["agricultural"] = true, ["forestery"] = true }
access_tag_restricted = { ["destination"] = true, ["delivery"] = true }
access_tags = { "motorcar", "motor_vehicle", "vehicle" }
service_tag_restricted = { ["parking_aisle"] = true }
ignore_in_grid = { ["ferry"] = true, ["pier"] = true }
speed_profile = {
["motorway"] = 90,
["motorway_link"] = 75,
["trunk"] = 85,
["trunk_link"] = 70,
["primary"] = 65,
["primary_link"] = 60,
["secondary"] = 55,
["secondary_link"] = 50,
["tertiary"] = 40,
["tertiary_link"] = 30,
["unclassified"] = 25,
["residential"] = 25,
["living_street"] = 10,
["service"] = 15,
-- ["track"] = 5,
["ferry"] = 5,
["pier"] = 5,
["default"] = 50
}
take_minimum_of_speeds = true
obey_oneway = true
obey_bollards = true
use_restrictions = true
ignore_areas = true -- future feature
traffic_signal_penalty = 2
u_turn_penalty = 20
-- End of globals
function node_function (node)
local barrier = node.tags:Find ("barrier")
local access = node.tags:Find ("access")
local traffic_signal = node.tags:Find("highway")
--flag node if it carries a traffic light
if traffic_signal == "traffic_signals" then
node.traffic_light = true;
end
if access_tag_blacklist[barrier] then
node.bollard = true;
end
if "" ~= barrier then
if obey_bollards then
--flag node as unpassable if it black listed as unpassable
node.bollard = true;
end
--reverse the previous flag if there is an access tag specifying entrance
if node.bollard and bollards_whitelist[barrier] and access_tag_whitelist[barrier] then
node.bollard = false;
return 1
end
-- Check if our vehicle types are allowd to pass the barrier
for i,v in ipairs(access_tags) do
local mode_value = node.tags:Find(v)
if nil ~= mode_value and "yes" == mode_value then
node.bollard = false
return
end
end
else
-- Check if our vehicle types are forbidden to pass the node
for i,v in ipairs(access_tags) do
local mode_value = node.tags:Find(v)
if nil ~= mode_value and "no" == mode_value then
node.bollard = true
return 1
end
end
end
return 1
end
function way_function (way, numberOfNodesInWay)
-- A way must have two nodes or more
if(numberOfNodesInWay < 2) then
return 0;
end
-- First, get the properties of each way that we come across
local highway = way.tags:Find("highway")
local name = way.tags:Find("name")
local ref = way.tags:Find("ref")
local junction = way.tags:Find("junction")
local route = way.tags:Find("route")
local maxspeed = parseMaxspeed(way.tags:Find ( "maxspeed") )
local man_made = way.tags:Find("man_made")
local barrier = way.tags:Find("barrier")
local oneway = way.tags:Find("oneway")
local cycleway = way.tags:Find("cycleway")
local duration = way.tags:Find("duration")
local service = way.tags:Find("service")
local area = way.tags:Find("area")
local access = way.tags:Find("access")
-- Second parse the way according to these properties
if ignore_areas and ("yes" == area) then
return 0
end
-- Check if we are allowed to access the way
if access_tag_blacklist[access] ~=nil and access_tag_blacklist[access] then
return 0;
end
-- Check if our vehicle types are forbidden
for i,v in ipairs(access_tags) do
local mode_value = way.tags:Find(v)
if nil ~= mode_value and "no" == mode_value then
return 0;
end
end
-- Set the name that will be used for instructions
if "" ~= ref then
way.name = ref
elseif "" ~= name then
way.name = name
end
if "roundabout" == junction then
way.roundabout = true;
end
-- Handling ferries and piers
if (speed_profile[route] ~= nil and speed_profile[route] > 0) or
(speed_profile[man_made] ~= nil and speed_profile[man_made] > 0)
then
if durationIsValid(duration) then
way.speed = math.max( parseDuration(duration) / math.max(1, numberOfNodesInWay-1) );
way.is_duration_set = true;
end
way.direction = Way.bidirectional;
if speed_profile[route] ~= nil then
highway = route;
elseif speed_profile[man_made] ~= nil then
highway = man_made;
end
if not way.is_duration_set then
way.speed = speed_profile[highway]
end
end
-- Set the avg speed on the way if it is accessible by road class
if (speed_profile[highway] ~= nil and way.speed == -1 ) then
if (0 < maxspeed and not take_minimum_of_speeds) or (maxspeed == 0) then
maxspeed = math.huge
end
way.speed = math.min(speed_profile[highway], maxspeed)
end
-- Set the avg speed on ways that are marked accessible
if access_tag_whitelist[access] and way.speed == -1 then
if (0 < maxspeed and not take_minimum_of_speeds) or maxspeed == 0 then
maxspeed = math.huge
end
way.speed = math.min(speed_profile["default"], maxspeed)
end
-- Set access restriction flag if access is allowed under certain restrictions only
if access ~= "" and access_tag_restricted[access] then
way.is_access_restricted = true
end
-- Set access restriction flag if service is allowed under certain restrictions only
if service ~= "" and service_tag_restricted[service] then
way.is_access_restricted = true
end
-- Set direction according to tags on way
if obey_oneway then
if oneway == "no" or oneway == "0" or oneway == "false" then
way.direction = Way.bidirectional
elseif oneway == "-1" then
way.direction = Way.opposite
elseif oneway == "yes" or oneway == "1" or oneway == "true" or junction == "roundabout" or highway == "motorway_link" or highway == "motorway" then
way.direction = Way.oneway
else
way.direction = Way.bidirectional
end
else
way.direction = Way.bidirectional
end
-- Override general direction settings of there is a specific one for our mode of travel
if ignore_in_grid[highway] ~= nil and ignore_in_grid[highway] then
way.ignore_in_grid = true
end
way.type = 1
return 1
end
|
-- Begin of globals
barrier_whitelist = { ["cattle_grid"] = true, ["border_control"] = true, ["toll_booth"] = true, ["no"] = true, ["sally_port"] = true, ["gate"] = true}
access_tag_whitelist = { ["yes"] = true, ["motorcar"] = true, ["motor_vehicle"] = true, ["vehicle"] = true, ["permissive"] = true, ["designated"] = true }
access_tag_blacklist = { ["no"] = true, ["private"] = true, ["agricultural"] = true, ["forestery"] = true }
access_tag_restricted = { ["destination"] = true, ["delivery"] = true }
access_tags = { "motorcar", "motor_vehicle", "vehicle" }
service_tag_restricted = { ["parking_aisle"] = true }
ignore_in_grid = { ["ferry"] = true, ["pier"] = true }
speed_profile = {
["motorway"] = 90,
["motorway_link"] = 75,
["trunk"] = 85,
["trunk_link"] = 70,
["primary"] = 65,
["primary_link"] = 60,
["secondary"] = 55,
["secondary_link"] = 50,
["tertiary"] = 40,
["tertiary_link"] = 30,
["unclassified"] = 25,
["residential"] = 25,
["living_street"] = 10,
["service"] = 15,
-- ["track"] = 5,
["ferry"] = 5,
["pier"] = 5,
["default"] = 50
}
take_minimum_of_speeds = true
obey_oneway = true
obey_bollards = true
use_restrictions = true
ignore_areas = true -- future feature
traffic_signal_penalty = 2
u_turn_penalty = 20
-- End of globals
function node_function (node)
local barrier = node.tags:Find ("barrier")
local access = node.tags:Find ("access")
local traffic_signal = node.tags:Find("highway")
--flag node if it carries a traffic light
if traffic_signal == "traffic_signals" then
node.traffic_light = true;
end
if "" ~= barrier and obey_bollards then
node.bollard = true; -- flag as unpassable and then check
if "yes" == access then
node.bollard = false;
return
end
--reverse the previous flag if there is an access tag specifying entrance
if node.bollard and (barrier_whitelist[barrier] or access_tag_whitelist[access]) then
node.bollard = false;
return
end
end
end
function way_function (way, numberOfNodesInWay)
-- A way must have two nodes or more
if(numberOfNodesInWay < 2) then
return 0;
end
-- First, get the properties of each way that we come across
local highway = way.tags:Find("highway")
local name = way.tags:Find("name")
local ref = way.tags:Find("ref")
local junction = way.tags:Find("junction")
local route = way.tags:Find("route")
local maxspeed = parseMaxspeed(way.tags:Find ( "maxspeed") )
local man_made = way.tags:Find("man_made")
local barrier = way.tags:Find("barrier")
local oneway = way.tags:Find("oneway")
local cycleway = way.tags:Find("cycleway")
local duration = way.tags:Find("duration")
local service = way.tags:Find("service")
local area = way.tags:Find("area")
local access = way.tags:Find("access")
-- Second parse the way according to these properties
if ignore_areas and ("yes" == area) then
return 0
end
-- Check if we are allowed to access the way
if access_tag_blacklist[access] ~=nil and access_tag_blacklist[access] then
return 0;
end
-- Check if our vehicle types are forbidden
for i,v in ipairs(access_tags) do
local mode_value = way.tags:Find(v)
if nil ~= mode_value and "no" == mode_value then
return 0;
end
end
-- Set the name that will be used for instructions
if "" ~= ref then
way.name = ref
elseif "" ~= name then
way.name = name
end
if "roundabout" == junction then
way.roundabout = true;
end
-- Handling ferries and piers
if (speed_profile[route] ~= nil and speed_profile[route] > 0) or
(speed_profile[man_made] ~= nil and speed_profile[man_made] > 0)
then
if durationIsValid(duration) then
way.speed = math.max( parseDuration(duration) / math.max(1, numberOfNodesInWay-1) );
way.is_duration_set = true;
end
way.direction = Way.bidirectional;
if speed_profile[route] ~= nil then
highway = route;
elseif speed_profile[man_made] ~= nil then
highway = man_made;
end
if not way.is_duration_set then
way.speed = speed_profile[highway]
end
end
-- Set the avg speed on the way if it is accessible by road class
if (speed_profile[highway] ~= nil and way.speed == -1 ) then
if (0 < maxspeed and not take_minimum_of_speeds) or (maxspeed == 0) then
maxspeed = math.huge
end
way.speed = math.min(speed_profile[highway], maxspeed)
end
-- Set the avg speed on ways that are marked accessible
if access_tag_whitelist[access] and way.speed == -1 then
if (0 < maxspeed and not take_minimum_of_speeds) or maxspeed == 0 then
maxspeed = math.huge
end
way.speed = math.min(speed_profile["default"], maxspeed)
end
-- Set access restriction flag if access is allowed under certain restrictions only
if access ~= "" and access_tag_restricted[access] then
way.is_access_restricted = true
end
-- Set access restriction flag if service is allowed under certain restrictions only
if service ~= "" and service_tag_restricted[service] then
way.is_access_restricted = true
end
-- Set direction according to tags on way
if obey_oneway then
if oneway == "no" or oneway == "0" or oneway == "false" then
way.direction = Way.bidirectional
elseif oneway == "-1" then
way.direction = Way.opposite
elseif oneway == "yes" or oneway == "1" or oneway == "true" or junction == "roundabout" or highway == "motorway_link" or highway == "motorway" then
way.direction = Way.oneway
else
way.direction = Way.bidirectional
end
else
way.direction = Way.bidirectional
end
-- Override general direction settings of there is a specific one for our mode of travel
if ignore_in_grid[highway] ~= nil and ignore_in_grid[highway] then
way.ignore_in_grid = true
end
way.type = 1
return 1
end
|
Fixes issue #461 and cucumber tests
|
Fixes issue #461 and cucumber tests
|
Lua
|
bsd-2-clause
|
felixguendling/osrm-backend,neilbu/osrm-backend,yuryleb/osrm-backend,bjtaylor1/osrm-backend,neilbu/osrm-backend,bjtaylor1/Project-OSRM-Old,ibikecph/osrm-backend,bjtaylor1/osrm-backend,raymond0/osrm-backend,beemogmbh/osrm-backend,Conggge/osrm-backend,chaupow/osrm-backend,alex85k/Project-OSRM,antoinegiret/osrm-backend,agruss/osrm-backend,raymond0/osrm-backend,stevevance/Project-OSRM,nagyistoce/osrm-backend,prembasumatary/osrm-backend,ammeurer/osrm-backend,keesklopt/matrix,ammeurer/osrm-backend,frodrigo/osrm-backend,oxidase/osrm-backend,Project-OSRM/osrm-backend,raymond0/osrm-backend,ramyaragupathy/osrm-backend,neilbu/osrm-backend,deniskoronchik/osrm-backend,keesklopt/matrix,Conggge/osrm-backend,bitsteller/osrm-backend,arnekaiser/osrm-backend,duizendnegen/osrm-backend,yuryleb/osrm-backend,bjtaylor1/osrm-backend,Conggge/osrm-backend,bjtaylor1/osrm-backend,skyborla/osrm-backend,Tristramg/osrm-backend,frodrigo/osrm-backend,atsuyim/osrm-backend,deniskoronchik/osrm-backend,KnockSoftware/osrm-backend,jpizarrom/osrm-backend,Carsten64/OSRM-aux-git,keesklopt/matrix,neilbu/osrm-backend,antoinegiret/osrm-geovelo,skyborla/osrm-backend,KnockSoftware/osrm-backend,Project-OSRM/osrm-backend,duizendnegen/osrm-backend,chaupow/osrm-backend,hydrays/osrm-backend,beemogmbh/osrm-backend,skyborla/osrm-backend,Carsten64/OSRM-aux-git,keesklopt/matrix,oxidase/osrm-backend,ammeurer/osrm-backend,jpizarrom/osrm-backend,chaupow/osrm-backend,ibikecph/osrm-backend,Tristramg/osrm-backend,atsuyim/osrm-backend,felixguendling/osrm-backend,arnekaiser/osrm-backend,frodrigo/osrm-backend,duizendnegen/osrm-backend,antoinegiret/osrm-geovelo,stevevance/Project-OSRM,felixguendling/osrm-backend,tkhaxton/osrm-backend,yuryleb/osrm-backend,Carsten64/OSRM-aux-git,bitsteller/osrm-backend,ammeurer/osrm-backend,arnekaiser/osrm-backend,stevevance/Project-OSRM,antoinegiret/osrm-backend,Project-OSRM/osrm-backend,nagyistoce/osrm-backend,Tristramg/osrm-backend,agruss/osrm-backend,bjtaylor1/Project-OSRM-Old,frodrigo/osrm-backend,stevevance/Project-OSRM,KnockSoftware/osrm-backend,beemogmbh/osrm-backend,atsuyim/osrm-backend,hydrays/osrm-backend,beemogmbh/osrm-backend,ibikecph/osrm-backend,Carsten64/OSRM-aux-git,tkhaxton/osrm-backend,hydrays/osrm-backend,Project-OSRM/osrm-backend,KnockSoftware/osrm-backend,arnekaiser/osrm-backend,ammeurer/osrm-backend,hydrays/osrm-backend,yuryleb/osrm-backend,ammeurer/osrm-backend,Conggge/osrm-backend,ramyaragupathy/osrm-backend,jpizarrom/osrm-backend,ramyaragupathy/osrm-backend,alex85k/Project-OSRM,agruss/osrm-backend,ammeurer/osrm-backend,prembasumatary/osrm-backend,bjtaylor1/Project-OSRM-Old,deniskoronchik/osrm-backend,duizendnegen/osrm-backend,tkhaxton/osrm-backend,bitsteller/osrm-backend,nagyistoce/osrm-backend,alex85k/Project-OSRM,bjtaylor1/Project-OSRM-Old,raymond0/osrm-backend,oxidase/osrm-backend,oxidase/osrm-backend,deniskoronchik/osrm-backend,antoinegiret/osrm-geovelo,prembasumatary/osrm-backend,antoinegiret/osrm-backend
|
f6204fbd359838a8b89d1490482160cf0017b0d0
|
overlay/sdk/hi-linux/rules.lua
|
overlay/sdk/hi-linux/rules.lua
|
-- HiSilicon Linux SDK
package { 'make', 'host',
source = 'make-3.81.tar.bz2'
}
package { 'hi-kernel' }
package { 'hi-sdk', 'target',
{ 'tools' },
{ 'prepare',
{ 'hi-kernel', 'unpack' }
},
{ 'hiboot' },
{ 'linux' },
{ 'rootfs' },
{ 'common' },
{ 'msp' },
{ 'component' }
}
package { 'cmake-modules' }
package { 'libuv', 'target' }
package { 'ffmpeg', 'target' }
package { 'hi-utils', 'target',
{ 'build',
{ 'cmake-modules', 'unpack' },
{ 'hi-sdk', 'install_component', 'target' }
}
}
package { 'karaoke-player', 'target',
{ 'build',
{ 'cmake-modules', 'unpack' },
{ 'ffmpeg', 'install', 'target' },
{ 'hi-sdk', 'install_component', 'target' },
{ 'libuv', 'install', 'target' },
}
}
|
-- HiSilicon Linux SDK
package { 'make', 'host',
source = 'make-3.81.tar.bz2'
}
package { 'hi-kernel' }
package { 'hi-sdk', 'target',
{ 'tools' },
{ 'prepare',
{ 'hi-kernel', 'unpack' }
},
{ 'hiboot' },
{ 'linux' },
{ 'rootfs' },
{ 'common' },
{ 'msp' },
{ 'component' }
}
package { 'cmake-modules' }
package { 'libuv', 'target' }
package { 'ffmpeg', 'target' }
package { 'hi-utils', 'target',
{ 'build',
{ 'cmake-modules', 'unpack' },
{ 'hi-sdk', 'component', 'target' }
}
}
package { 'karaoke-player', 'target',
{ 'build',
{ 'cmake-modules', 'unpack' },
{ 'ffmpeg', 'install', 'target' },
{ 'hi-sdk', 'component', 'target' },
{ 'libuv', 'install', 'target' },
}
}
|
Fix hi-sdk target dependencies
|
Fix hi-sdk target dependencies
|
Lua
|
mit
|
bazurbat/jagen
|
affcb2cbc5174641cc9896a0231c5970937f7090
|
gamemode/zombies/class_default.lua
|
gamemode/zombies/class_default.lua
|
NPC.Class = ""
NPC.Name = ""
NPC.Description = ""
NPC.Icon = ""
NPC.Flag = 0
NPC.Cost = 0
NPC.PopCost = 0
NPC.SortIndex = 0
NPC.Hidden = true
NPC.Health = 0
NPC.Model = {}
if SERVER then
NPC.SpawnFlags = SF_NPC_LONG_RANGE + SF_NPC_FADE_CORPSE + SF_NPC_ALWAYSTHINK + SF_NPC_NO_PLAYER_PUSHAWAY
NPC.Capabilities = nil
NPC.Friends = {"npc_zombie", "npc_poisonzombie", "npc_burnzombie", "npc_dragzombie"}
end
function NPC:OnSpawned(npc)
npc:SetBloodColor(BLOOD_COLOR_RED)
npc:SetKeyValue("wakeradius", 32768)
npc:SetKeyValue("wakesquad", 1)
npc:SetNPCState(NPC_STATE_ALERT)
if self.Capabilities then
npc:CapabilitiesClear()
npc:CapabilitiesAdd(self.Capabilities)
end
if self.Health and self.Health ~= 0 then
npc:SetHealth(self.Health)
end
end
function NPC:OnScaledDamage(npc, hitgroup, dmginfo)
end
function NPC:OnTakeDamage(npc, attacker, inflictor, dmginfo)
local damage = dmginfo:GetDamage()
if npc:Health() <= damage then
dmginfo:SetDamageType(bit.bor(dmginfo:GetDamageType(), DMG_REMOVENORAGDOLL))
end
local atkowner = attacker:GetOwner()
if IsValid(attacker) and attacker:GetClass() == "env_fire" and IsValid(atkowner) and atkowner:GetClass() == "npc_burnzombie" then
dmginfo:SetDamageType(DMG_GENERIC)
dmginfo:SetDamage(0)
dmginfo:ScaleDamage(0)
return true
end
if not IsValid(npc:GetEnemy()) and IsValid(attacker) then
npc:ForceGotoEnemy(attacker, attacker:GetPos())
for k, v in pairs(ents.FindByClass("npc_*")) do
if IsValid(v) and v:IsNPC() and not IsValid(v:GetEnemy()) then
npc:ForceGotoEnemy(v, attacker:GetPos())
end
end
end
end
function NPC:OnKilled(npc, attacker, inflictor)
local owner = npc:GetOwner()
if IsValid(owner) and owner:IsPlayer() then
local popCost = self.PopCost
local population = GAMEMODE:GetCurZombiePop()
popCost = popCost or 1
GAMEMODE:TakeCurZombiePop(popCost)
end
net.Start("zm_spawnclientragdoll")
net.WriteEntity(npc)
net.Broadcast()
if IsValid(attacker) and attacker:IsPlayer() then
attacker:AddFrags(1)
end
end
function NPC:Think(npc)
--[[
if not IsValid(npc) then return end
local isDead = npc:Health() <= 0 or npc:IsCurrentSchedule(SCHED_DIE)
if isDead then
return
end
local strafing = npc:IsCurrentSchedule(SCHED_RUN_RANDOM)
if strafing then
return
end
local currentActivity = npc:GetActivity()
local reloading = npc:IsCurrentSchedule(SCHED_RELOAD) or npc:IsCurrentSchedule(SCHED_HIDE_AND_RELOAD) or currentActivity == ACT_RELOAD
if reloading then
return
end
local getLineOfFire = npc:IsCurrentSchedule(SCHED_ESTABLISH_LINE_OF_FIRE)
if getLineOfFire then
return
end
local chasingEnemy = npc:IsCurrentSchedule(SCHED_CHASE_ENEMY)
if chasingEnemy then
return
end
local fallingBack = npc:IsCurrentSchedule(SCHED_RUN_FROM_ENEMY_FALLBACK)
if fallingBack then
return
end
local specialAttack = npc:IsCurrentSchedule(SCHED_RANGE_ATTACK2) or npc:IsCurrentSchedule(SCHED_MELEE_ATTACK1) or npc:IsCurrentSchedule(SCHED_MELEE_ATTACK2) or npc:IsCurrentSchedule(SCHED_SPECIAL_ATTACK1) or npc:IsCurrentSchedule(SCHED_SPECIAL_ATTACK2)
if specialAttack then
return
end
local forcedRunning = npc:IsCurrentSchedule(SCHED_FORCED_GO_RUN)
if forcedRunning and not IsValid(npc:GetEnemy()) then
return
end
npc:Fire("Wake")
if IsValid(npc:GetEnemy()) then
npc:RefreshEnemyMemory()
npc:SetNPCState(NPC_STATE_COMBAT)
npc:Fire("SetReadinessHigh")
else
npc:Fire("SetReadinessLow")
local state = npc:GetNPCState()
local patrolling = npc:IsCurrentSchedule(SCHED_PATROL_WALK)
if state == NPC_STATE_IDLE and not patrolling then
npc:SetSchedule(SCHED_PATROL_WALK)
return
end
end
--]]
local meleeAttacking = npc:GetActivity() == ACT_MELEE_ATTACK1
if IsValid(npc:GetEnemy()) then
local enemyDistance = npc:GetPos():Distance(npc:GetEnemy():GetPos())
local chasingEnemy = npc:IsCurrentSchedule(SCHED_CHASE_ENEMY)
if enemyDistance <= 75 then
if not meleeAttacking then
npc:RefreshEnemyMemory()
npc:SetSchedule(SCHED_MELEE_ATTACK1)
end
elseif not chasingEnemy then
npc:SetSchedule(SCHED_CHASE_ENEMY)
end
end
end
|
NPC.Class = ""
NPC.Name = ""
NPC.Description = ""
NPC.Icon = ""
NPC.Flag = 0
NPC.Cost = 0
NPC.PopCost = 0
NPC.SortIndex = 0
NPC.Hidden = true
NPC.Health = 0
NPC.Model = {}
if SERVER then
NPC.SpawnFlags = SF_NPC_LONG_RANGE + SF_NPC_FADE_CORPSE + SF_NPC_ALWAYSTHINK + SF_NPC_NO_PLAYER_PUSHAWAY
NPC.Capabilities = nil
NPC.Friends = {"npc_zombie", "npc_poisonzombie", "npc_burnzombie", "npc_dragzombie"}
end
function NPC:OnSpawned(npc)
npc:SetBloodColor(BLOOD_COLOR_RED)
npc:SetKeyValue("wakeradius", 32768)
npc:SetKeyValue("wakesquad", 1)
npc:SetNPCState(NPC_STATE_ALERT)
if self.Capabilities then
npc:CapabilitiesClear()
npc:CapabilitiesAdd(self.Capabilities)
end
if self.Health and self.Health ~= 0 then
npc:SetHealth(self.Health)
end
end
function NPC:OnScaledDamage(npc, hitgroup, dmginfo)
end
function NPC:OnTakeDamage(npc, attacker, inflictor, dmginfo)
local damage = dmginfo:GetDamage()
if npc:Health() <= damage then
dmginfo:SetDamageType(bit.bor(dmginfo:GetDamageType(), DMG_REMOVENORAGDOLL))
end
if IsValid(attacker) then
local atkowner = attacker:GetOwner()
if IsValid(attacker) and attacker:GetClass() == "env_fire" and IsValid(atkowner) and atkowner:GetClass() == "npc_burnzombie" then
dmginfo:SetDamageType(DMG_GENERIC)
dmginfo:SetDamage(0)
dmginfo:ScaleDamage(0)
return true
end
if not IsValid(npc:GetEnemy()) then
npc:ForceGotoEnemy(attacker, attacker:GetPos())
for k, v in pairs(ents.FindByClass("npc_*")) do
if IsValid(v) and v:IsNPC() and not IsValid(v:GetEnemy()) then
npc:ForceGotoEnemy(v, attacker:GetPos())
end
end
end
end
end
function NPC:OnKilled(npc, attacker, inflictor)
local owner = npc:GetOwner()
if IsValid(owner) and owner:IsPlayer() then
local popCost = self.PopCost
local population = GAMEMODE:GetCurZombiePop()
popCost = popCost or 1
GAMEMODE:TakeCurZombiePop(popCost)
end
net.Start("zm_spawnclientragdoll")
net.WriteEntity(npc)
net.Broadcast()
if IsValid(attacker) and attacker:IsPlayer() then
attacker:AddFrags(1)
end
end
function NPC:Think(npc)
--[[
if not IsValid(npc) then return end
local isDead = npc:Health() <= 0 or npc:IsCurrentSchedule(SCHED_DIE)
if isDead then
return
end
local strafing = npc:IsCurrentSchedule(SCHED_RUN_RANDOM)
if strafing then
return
end
local currentActivity = npc:GetActivity()
local reloading = npc:IsCurrentSchedule(SCHED_RELOAD) or npc:IsCurrentSchedule(SCHED_HIDE_AND_RELOAD) or currentActivity == ACT_RELOAD
if reloading then
return
end
local getLineOfFire = npc:IsCurrentSchedule(SCHED_ESTABLISH_LINE_OF_FIRE)
if getLineOfFire then
return
end
local chasingEnemy = npc:IsCurrentSchedule(SCHED_CHASE_ENEMY)
if chasingEnemy then
return
end
local fallingBack = npc:IsCurrentSchedule(SCHED_RUN_FROM_ENEMY_FALLBACK)
if fallingBack then
return
end
local specialAttack = npc:IsCurrentSchedule(SCHED_RANGE_ATTACK2) or npc:IsCurrentSchedule(SCHED_MELEE_ATTACK1) or npc:IsCurrentSchedule(SCHED_MELEE_ATTACK2) or npc:IsCurrentSchedule(SCHED_SPECIAL_ATTACK1) or npc:IsCurrentSchedule(SCHED_SPECIAL_ATTACK2)
if specialAttack then
return
end
local forcedRunning = npc:IsCurrentSchedule(SCHED_FORCED_GO_RUN)
if forcedRunning and not IsValid(npc:GetEnemy()) then
return
end
npc:Fire("Wake")
if IsValid(npc:GetEnemy()) then
npc:RefreshEnemyMemory()
npc:SetNPCState(NPC_STATE_COMBAT)
npc:Fire("SetReadinessHigh")
else
npc:Fire("SetReadinessLow")
local state = npc:GetNPCState()
local patrolling = npc:IsCurrentSchedule(SCHED_PATROL_WALK)
if state == NPC_STATE_IDLE and not patrolling then
npc:SetSchedule(SCHED_PATROL_WALK)
return
end
end
--]]
local meleeAttacking = npc:GetActivity() == ACT_MELEE_ATTACK1
if IsValid(npc:GetEnemy()) then
local enemyDistance = npc:GetPos():Distance(npc:GetEnemy():GetPos())
local chasingEnemy = npc:IsCurrentSchedule(SCHED_CHASE_ENEMY)
if enemyDistance <= 75 then
if not meleeAttacking then
npc:RefreshEnemyMemory()
npc:SetSchedule(SCHED_MELEE_ATTACK1)
end
elseif not chasingEnemy then
npc:SetSchedule(SCHED_CHASE_ENEMY)
end
end
end
|
Fixed nil error in NPC:OnTakeDamage
|
Fixed nil error in NPC:OnTakeDamage
|
Lua
|
apache-2.0
|
ForrestMarkX/glua-ZombieMaster
|
3aa6964e198ab9d6a3373b9c25be0bada7204c3a
|
scripts/tundra/environment.lua
|
scripts/tundra/environment.lua
|
module(..., package.seeall)
local util = require 'tundra.util'
local path = require 'tundra.path'
local depgraph = require 'tundra.depgraph'
local nenv = require 'tundra.environment.native'
local os = require 'os'
local global_setup = {}
--[==[
The environment is a holder for variables and their associated values. Values
are always kept as tables, even if there is only a single value.
FOO = { a b c }
e:interpolate("$(FOO)") -> "a b c"
e:interpolate("$(FOO:j, )") -> "a, b, c"
e:interpolate("$(FOO:p-I)") -> "-Ia -Ib -Ic"
Missing keys trigger errors unless a default value is specified.
]==]--
local envclass = {}
function envclass:create(parent, assignments, obj)
obj = obj or {}
setmetatable(obj, self)
self.__index = self
obj.vars = {}
obj.parent = parent
obj.lookup = { obj.vars }
obj.memos = {}
obj.memo_keys = {}
obj.external_vars = parent and util.clone_table(parent.external_vars) or nil
-- assign initial bindings
if assignments then
obj:set_many(assignments)
end
return obj
end
function envclass:clone(assignments)
return envclass:create(self, assignments)
end
function envclass:register_implicit_make_fn(ext, fn, docstring)
if type(ext) ~= "string" then
errorf("extension must be a string")
end
if type(fn) ~= "function" then
errorf("fn must be a function")
end
if not ext:match("^%.") then
ext = "." .. ext -- we want the dot in the extension
end
if not self._implicit_exts then
self._implicit_exts = {}
end
self._implicit_exts[ext] = {
Function = fn,
Doc = docstring or "",
}
end
function envclass:get_implicit_make_fn(filename)
local ext = path.get_extension(filename)
local chain = self
while chain do
local t = chain._implicit_exts
if t then
local v = t[ext]
if v then return v.Function end
end
chain = chain.parent
end
return nil
end
function envclass:has_key(key)
return self.vars[key] and true or false
end
function envclass:get_vars()
return self.vars
end
function envclass:set_many(table)
for k, v in pairs(table) do
self:set(k, v)
end
end
function envclass:append(key, value)
if type(value) ~= "string" then
error("environment append: " .. util.tostring(value) .. " is not a string", 2)
end
self:invalidate_memos(key)
local t = self:get_list(key, 1)
local result
if type(t) == "table" then
result = util.clone_array(t)
table.insert(result, value)
else
result = { value }
end
self.vars[key] = result
end
function envclass:replace(key, value)
if type(value) == "string" then
value = { value }
end
assert(type(value) == "table")
self:invalidate_memos(key)
self.vars[key] = value
end
function envclass:invalidate_memos(key)
local name_tab = self.memo_keys[key]
if name_tab then
for name, _ in pairs(name_tab) do
self.memos[name] = nil
end
end
end
function envclass:set_default(key, value)
if not self:has_key(key) then
self:set(key, value)
end
end
function envclass:set(key, value)
self:invalidate_memos(key)
assert(key:len() > 0, "key must not be empty")
assert(type(key) == "string", "key must be a string")
if type(value) == "string" then
if value:len() > 0 then
self.vars[key] = { value }
else
-- let empty strings make empty tables
self.vars[key] = {}
end
elseif type(value) == "table" then
-- FIXME: should filter out empty values
for _, v in ipairs(value) do
if not type(v) == "string" then
error("key " .. key .. "'s table value contains non-string value " .. tostring(v))
end
end
self.vars[key] = util.clone_array(value)
else
error("key " .. key .. "'s value is neither table nor string: " .. tostring(value))
end
end
function envclass:get_id()
return self.id
end
function envclass:get(key, default)
local v = self.vars[key]
if v then
return table.concat(v, " ")
elseif self.parent then
return self.parent:get(key, default)
elseif default then
return default
else
error(string.format("key '%s' not present in environment", key))
end
end
function envclass:get_list(key, default)
local v = self.vars[key]
if v then
return v -- FIXME: this should be immutable from the outside
elseif self.parent then
return self.parent:get_list(key, default)
elseif default then
return default
elseif not key then
error("nil key is not allowed")
else
error(string.format("key '%s' not present in environment", key))
end
end
function envclass:get_parent()
return self.parent
end
function envclass:interpolate(str, vars)
local n = nenv.interpolate(str, function (var)
local v = vars and vars[var] or nil
if v then
if type(v) ~= "table" then
v = { v }
end
return v
end
local chain = self
while chain do
v = chain.vars[var]
if v then
return v
end
chain = chain.parent
end
printf("Env lookup failed for %q. Available keys:", var)
local chain = self
while chain do
local keys = util.table_keys(chain.vars)
table.sort(keys)
for _, k in ipairs(keys) do
printf(" %s", k)
end
chain = chain.parent
end
return nil
end)
return n
end
function create(parent, assignments, obj)
return envclass:create(parent, assignments, obj)
end
function envclass:record_memo_var(key, name)
local tab = self.memo_keys[key]
if not tab then
tab = {}
self.memo_keys[key] = tab
end
tab[name] = true
end
function envclass:memoize(key, name, fn)
local memo = self.memos[name]
if not memo then
self:record_memo_var(key, name)
memo = fn()
self.memos[name] = memo
end
return memo
end
function envclass:get_external_env_var(key)
local chain = self
while chain do
local t = self.external_vars
if t then
local v = t[key]
if v then return v end
end
chain = chain.parent
end
return os.getenv(key)
end
function envclass:set_external_env_var(key, value)
local t = self.external_vars
if not t then
t = {}
self.external_vars = t
end
t[key] = value
end
function envclass:add_setup_function(fn)
local t = self.setup_funcs
if not t then
t = {}
self.setup_funcs = t
end
t[#t + 1] = fn
end
function envclass:run_setup_functions()
for _, func in ipairs(global_setup) do
func(self)
end
t = self.setup_funcs
local chain = self
while chain do
for _, func in util.nil_ipairs(chain.setup_funcs) do
func(self)
end
chain = chain.parent
end
end
function add_global_setup(fn)
global_setup[#global_setup + 1] = fn
end
function is_environment(datum)
return getmetatable(datum) == envclass
end
|
module(..., package.seeall)
local util = require 'tundra.util'
local path = require 'tundra.path'
local depgraph = require 'tundra.depgraph'
local nenv = require 'tundra.environment.native'
local os = require 'os'
local global_setup = {}
--[==[
The environment is a holder for variables and their associated values. Values
are always kept as tables, even if there is only a single value.
FOO = { a b c }
e:interpolate("$(FOO)") -> "a b c"
e:interpolate("$(FOO:j, )") -> "a, b, c"
e:interpolate("$(FOO:p-I)") -> "-Ia -Ib -Ic"
Missing keys trigger errors unless a default value is specified.
]==]--
local envclass = {}
function envclass:create(parent, assignments, obj)
obj = obj or {}
setmetatable(obj, self)
self.__index = self
obj.vars = {}
obj.parent = parent
obj.lookup = { obj.vars }
obj.memos = {}
obj.memo_keys = {}
obj.external_vars = parent and util.clone_table(parent.external_vars) or nil
-- assign initial bindings
if assignments then
obj:set_many(assignments)
end
return obj
end
function envclass:clone(assignments)
return envclass:create(self, assignments)
end
function envclass:register_implicit_make_fn(ext, fn, docstring)
if type(ext) ~= "string" then
errorf("extension must be a string")
end
if type(fn) ~= "function" then
errorf("fn must be a function")
end
if not ext:match("^%.") then
ext = "." .. ext -- we want the dot in the extension
end
if not self._implicit_exts then
self._implicit_exts = {}
end
self._implicit_exts[ext] = {
Function = fn,
Doc = docstring or "",
}
end
function envclass:get_implicit_make_fn(filename)
local ext = path.get_extension(filename)
local chain = self
while chain do
local t = chain._implicit_exts
if t then
local v = t[ext]
if v then return v.Function end
end
chain = chain.parent
end
return nil
end
function envclass:has_key(key)
local chain = self
while chain do
if chain.vars[key] then
return true
end
chain = chain.parent
end
return false
end
function envclass:get_vars()
return self.vars
end
function envclass:set_many(table)
for k, v in pairs(table) do
self:set(k, v)
end
end
function envclass:append(key, value)
if type(value) ~= "string" then
error("environment append: " .. util.tostring(value) .. " is not a string", 2)
end
self:invalidate_memos(key)
local t = self:get_list(key, 1)
local result
if type(t) == "table" then
result = util.clone_array(t)
table.insert(result, value)
else
result = { value }
end
self.vars[key] = result
end
function envclass:replace(key, value)
if type(value) == "string" then
value = { value }
end
assert(type(value) == "table")
self:invalidate_memos(key)
self.vars[key] = value
end
function envclass:invalidate_memos(key)
local name_tab = self.memo_keys[key]
if name_tab then
for name, _ in pairs(name_tab) do
self.memos[name] = nil
end
end
end
function envclass:set_default(key, value)
if not self:has_key(key) then
self:set(key, value)
end
end
function envclass:set(key, value)
self:invalidate_memos(key)
assert(key:len() > 0, "key must not be empty")
assert(type(key) == "string", "key must be a string")
if type(value) == "string" then
if value:len() > 0 then
self.vars[key] = { value }
else
-- let empty strings make empty tables
self.vars[key] = {}
end
elseif type(value) == "table" then
-- FIXME: should filter out empty values
for _, v in ipairs(value) do
if not type(v) == "string" then
error("key " .. key .. "'s table value contains non-string value " .. tostring(v))
end
end
self.vars[key] = util.clone_array(value)
else
error("key " .. key .. "'s value is neither table nor string: " .. tostring(value))
end
end
function envclass:get_id()
return self.id
end
function envclass:get(key, default)
local v = self.vars[key]
if v then
return table.concat(v, " ")
elseif self.parent then
return self.parent:get(key, default)
elseif default then
return default
else
error(string.format("key '%s' not present in environment", key))
end
end
function envclass:get_list(key, default)
local v = self.vars[key]
if v then
return v -- FIXME: this should be immutable from the outside
elseif self.parent then
return self.parent:get_list(key, default)
elseif default then
return default
elseif not key then
error("nil key is not allowed")
else
error(string.format("key '%s' not present in environment", key))
end
end
function envclass:get_parent()
return self.parent
end
function envclass:interpolate(str, vars)
local n = nenv.interpolate(str, function (var)
local v = vars and vars[var] or nil
if v then
if type(v) ~= "table" then
v = { v }
end
return v
end
local chain = self
while chain do
v = chain.vars[var]
if v then
return v
end
chain = chain.parent
end
printf("Env lookup failed for %q. Available keys:", var)
local chain = self
while chain do
local keys = util.table_keys(chain.vars)
table.sort(keys)
for _, k in ipairs(keys) do
printf(" %s", k)
end
chain = chain.parent
end
return nil
end)
return n
end
function create(parent, assignments, obj)
return envclass:create(parent, assignments, obj)
end
function envclass:record_memo_var(key, name)
local tab = self.memo_keys[key]
if not tab then
tab = {}
self.memo_keys[key] = tab
end
tab[name] = true
end
function envclass:memoize(key, name, fn)
local memo = self.memos[name]
if not memo then
self:record_memo_var(key, name)
memo = fn()
self.memos[name] = memo
end
return memo
end
function envclass:get_external_env_var(key)
local chain = self
while chain do
local t = self.external_vars
if t then
local v = t[key]
if v then return v end
end
chain = chain.parent
end
return os.getenv(key)
end
function envclass:set_external_env_var(key, value)
local t = self.external_vars
if not t then
t = {}
self.external_vars = t
end
t[key] = value
end
function envclass:add_setup_function(fn)
local t = self.setup_funcs
if not t then
t = {}
self.setup_funcs = t
end
t[#t + 1] = fn
end
function envclass:run_setup_functions()
for _, func in ipairs(global_setup) do
func(self)
end
t = self.setup_funcs
local chain = self
while chain do
for _, func in util.nil_ipairs(chain.setup_funcs) do
func(self)
end
chain = chain.parent
end
end
function add_global_setup(fn)
global_setup[#global_setup + 1] = fn
end
function is_environment(datum)
return getmetatable(datum) == envclass
end
|
Fixed env:has_key() didn't take parent into account
|
Fixed env:has_key() didn't take parent into account
|
Lua
|
mit
|
deplinenoise/tundra,bmharper/tundra,deplinenoise/tundra,bmharper/tundra,bmharper/tundra,bmharper/tundra,deplinenoise/tundra
|
490bb163f506a5779c4c8c2d0cc4a2330bc62f19
|
mod_muc_intercom/mod_muc_intercom.lua
|
mod_muc_intercom/mod_muc_intercom.lua
|
-- Relay messages between rooms
-- By Kim Alvefur <zash@zash.se>
local host_session = prosody.hosts[module.host];
local st_msg = require "util.stanza".message;
local jid = require "util.jid";
function check_message(data)
local origin, stanza = data.origin, data.stanza;
local muc_rooms = host_session.muc and host_session.muc.rooms;
if not muc_rooms then return; end
local this_room = muc_rooms[stanza.attr.to];
if not this_room then return; end -- no such room
local from_room_jid = this_room._jid_nick[stanza.attr.from];
if not from_room_jid then return; end -- no such nick
local from_room, from_host, from_nick = jid.split(from_room_jid);
local body = stanza:get_child("body");
body = body and body:get_text(); -- I feel like I want to do `or ""` there :/
local target_room, message = body:match("^@([^:]+):(.*)");
if not target_room or not message then return; end
if target_room == from_room then return; end -- don't route to itself
module:log("debug", "target room is %s", target_room);
local bare_room = jid.join(target_room, from_host);
if not muc_rooms[bare_room] then return; end -- TODO send a error
module:log("info", "message from %s in %s to %s", from_nick, from_room, target_room);
local sender = jid.join(target_room, module.host, from_room .. "/" .. from_nick);
local forward_stanza = st_msg({from = sender, to = bare_room, type = "groupchat"}, message);
module:log("debug", "broadcasting message to target room");
muc_rooms[bare_room]:broadcast_message(forward_stanza);
end
module:hook("message/bare", check_message);
|
-- Relay messages between rooms
-- By Kim Alvefur <zash@zash.se>
local host_session = prosody.hosts[module.host];
local st_msg = require "util.stanza".message;
local jid = require "util.jid";
function check_message(data)
local origin, stanza = data.origin, data.stanza;
local muc_rooms = host_session.muc and host_session.muc.rooms;
if not muc_rooms then return; end
local this_room = muc_rooms[stanza.attr.to];
if not this_room then return; end -- no such room
local from_room_jid = this_room._jid_nick[stanza.attr.from];
if not from_room_jid then return; end -- no such nick
local from_room, from_host, from_nick = jid.split(from_room_jid);
local body = stanza:get_child("body");
if not body then return; end -- No body, like topic changes
body = body and body:get_text(); -- I feel like I want to do `or ""` there :/
local target_room, message = body:match("^@([^:]+):(.*)");
if not target_room or not message then return; end
if target_room == from_room then return; end -- don't route to itself
module:log("debug", "target room is %s", target_room);
local bare_room = jid.join(target_room, from_host);
if not muc_rooms[bare_room] then return; end -- TODO send a error
module:log("info", "message from %s in %s to %s", from_nick, from_room, target_room);
local sender = jid.join(target_room, module.host, from_room .. "/" .. from_nick);
local forward_stanza = st_msg({from = sender, to = bare_room, type = "groupchat"}, message);
module:log("debug", "broadcasting message to target room");
muc_rooms[bare_room]:broadcast_message(forward_stanza);
end
module:hook("message/bare", check_message);
|
mod_muc_intercom: Fix traceback on topic changes
|
mod_muc_intercom: Fix traceback on topic changes
|
Lua
|
mit
|
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
|
5b98493ffc58dda356f953b934007f13477a254f
|
cnnmrf.lua
|
cnnmrf.lua
|
-- -*- coding: utf-8 -*-
require 'torch'
require 'paths'
paths.dofile('mylib/helper.lua')
-----------------------------------------
-- Parameters
-----------------------------------------
cmd = torch.CmdLine()
cmd:option('-content_name', 'potrait1', "The content image located in folder 'data/content'")
cmd:option('-style_name', 'picasso', "The style image located in folder 'data/style'")
cmd:option('-ini_method', 'image', "Initial method, set to 'image' to use the content image as the initialization; set to 'random' to use random noise.")
cmd:option('-type', 'transfer', 'transfer|syn')
cmd:option('-max_size',384, "Maximum size of the image. Larger image needs more time and memory.")
cmd:option('-backend','cudnn', "Use cudnn' for CUDA-enabled GPUs or 'clnn' for OpenCL.")
cmd:option('-mode','speed', "Try 'speed' if you have a GPU with more than 4GB memory, and try 'memory' otherwise. The 'speed' mode is significantly faster (especially for synthesizing high resolutions) at the cost of higher GPU memory. ")
cmd:option('-num_res',3, "Number of resolutions. Notice the lowest resolution image should be larger than the patch size otherwise it won't synthesize.")
cmd:option('-num_iter',{100, 100, 100}, "Number of iterations for each resolution.")
cmd:option('-mrf_layers',{12, 21}, "The layers for MRF constraint. Usualy layer 21 alone already gives decent results. Including layer 12 may improve the results but at significantly more computational cost.")
cmd:option('-mrf_weight',{1e-4, 1e-4}, "Weight for each MRF layer. Higher weights leads to more style faithful results.")
cmd:option('-mrf_patch_size',{3, 3}, "The patch size for MRF constraint. This value is defined seperately for each MRF layer.")
cmd:option('-target_num_rotation',0, 'To matching objects of different poses. This value is shared by all MRF layers. The total number of rotational copies is "2 * mrf_num_rotation + 1"')
cmd:option('-target_num_scale',0, 'To matching objects of different scales. This value is shared by all MRF layers. The total number of scaled copies is "2 * mrf_num_scale + 1"')
cmd:option('-target_sample_stride',{2, 2}, "Stride to sample mrf on style image. This value is defined seperately for each MRF layer.")
cmd:option('-mrf_confidence_threshold',{0, 0}, "Threshold for filtering out bad matching. Default value 0 means we keep all matchings. This value is defined seperately for all layers.")
cmd:option('-source_sample_stride',{2, 2}, "Stride to sample mrf on synthesis image. This value is defined seperately for each MRF layer. This settings is relevant only for syn setting.")
cmd:option('-content_layers',{21}, "The layers for content constraint")
cmd:option('-content_weight',2e1, "The weight for content constraint. Increasing this value will make the result more content faithful. Decreasing the value will make the method more style faithful. Notice this value should be increase (for example, doubled) if layer 12 is included for MRF constraint.")
cmd:option('-tv_weight',1e-3, "TV smoothness weight")
cmd:option('-scaler', 2, "Relative expansion from example to result. This settings is relevant only for syn setting.")
cmd:option('-gpu_chunck_size_1',256, "Size of chunks to split feature maps along the channel dimension. This is to save memory when normalizing the matching score in mrf layers. Use large value if you have large gpu memory. As reference we use 256 for Titan X, and 32 for Geforce GT750M 2G.")
cmd:option('-gpu_chunck_size_2',16, "Size of chuncks to split feature maps along the y dimension. This is to save memory when normalizing the matching score in mrf layers. Use large value if you have large gpu memory. As reference we use 16 for Titan X, and 2 for Geforce GT750M 2G.")
-- fixed parameters
cmd:option('-target_step_rotation', math.pi/24)
cmd:option('-target_step_scale', 1.05)
cmd:option('-output_folder', 'data/result/trans/MRF/')
cmd:option('-proto_file', 'data/models/VGG_ILSVRC_19_layers_deploy.prototxt')
cmd:option('-model_file', 'data/models/VGG_ILSVRC_19_layers.caffemodel')
cmd:option('-gpu', 0, 'Zero-indexed ID of the GPU to use')
cmd:option('-nCorrection', 25)
cmd:option('-print_iter', 10)
cmd:option('-save_iter', 10)
params = cmd:parse(arg)
local wrapper = nil
if params.type == 'transfer' then
wrapper = require 'transfer_CNNMRF_wrapper'
else
wrapper = require 'syn_CNNMRF_wrapper'
end
wrapper.main(params)
|
-- -*- coding: utf-8 -*-
require 'torch'
require 'paths'
paths.dofile('mylib/helper.lua')
--adapted from http://lua-users.org/wiki/SplitJoin
function split(str, pat, cast_to_func)
local t = {} -- NOTE: use {n = 0} in Lua-5.0
local fpat = "(.-)" .. pat
local last_end = 1
local s, e, cap = str:find(fpat, 1)
while s do
if s ~= 1 or cap ~= "" then
table.insert(t, cast_to_func(cap))
end
last_end = e+1
s, e, cap = str:find(fpat, last_end)
end
if last_end <= #str then
cap = str:sub(last_end)
table.insert(t, cast_to_func(cap))
end
return t
end
-----------------------------------------
-- Parameters
-----------------------------------------
cmd = torch.CmdLine()
cmd:text('Below are all options with their default values in [].')
cmd:text()
cmd:text('Basic options: ')
cmd:option('-content_name', 'potrait1', "The content image located in folder 'data/content'")
cmd:option('-style_name', 'picasso', "The style image located in folder 'data/style'")
cmd:option('-ini_method', 'image', "Initial method, set to 'image' to use the content image as the initialization; set to 'random' to use random noise.")
cmd:option('-type', 'transfer', 'Use Guided Synthesis (transfer) or Un-guided Synthesis (syn)')
cmd:option('-max_size',384, "Maximum size of the image. Larger image needs more time and memory.")
cmd:option('-backend','cudnn', "Use cudnn' for CUDA-enabled GPUs or 'clnn' for OpenCL.")
cmd:option('-mode','speed', "Try 'speed' if you have a GPU with more than 4GB memory, and try 'memory' otherwise. The 'speed' mode is significantly faster (especially for synthesizing high resolutions) at the cost of higher GPU memory. ")
cmd:option('-num_res',3, "Number of resolutions. Notice the lowest resolution image should be larger than the patch size otherwise it won't synthesize.")
cmd:option('-num_iter','100,100,100', "Number of iterations for each resolution. You can use comma-separated values.")
cmd:text()
cmd:text('Advanced options: ')
cmd:option('-mrf_layers','12,21', "The layers for MRF constraint. Usually layer 21 alone already gives decent results. Including layer 12 may improve the results but at significantly more computational cost. You can use comma-separated values.")
cmd:option('-mrf_weight','1e-4,1e-4', "Weight for each MRF layer. Higher weights leads to more style faithful results. You can use comma-separated values.")
cmd:option('-mrf_patch_size', '3,3', "The patch size for MRF constraint. This value is defined seperately for each MRF layer. You can use comma-separated values.")
cmd:option('-target_num_rotation',0, 'To matching objects of different poses. This value is shared by all MRF layers. The total number of rotational copies is "2 * mrf_num_rotation + 1"')
cmd:option('-target_num_scale',0, 'To matching objects of different scales. This value is shared by all MRF layers. The total number of scaled copies is "2 * mrf_num_scale + 1"')
cmd:option('-target_sample_stride','2,2', "Stride to sample mrf on style image. This value is defined seperately for each MRF layer. You can use comma-separated values.")
cmd:option('-mrf_confidence_threshold','0,0', "Threshold for filtering out bad matching. Default value 0 means we keep all matchings. This value is defined seperately for all layers. You can use comma-separated values.")
cmd:option('-source_sample_stride','2,2', "Stride to sample mrf on synthesis image. This value is defined seperately for each MRF layer. This settings is relevant only for syn setting. You can use comma-separated values.")
cmd:option('-content_layers','21', "The layers for content constraint. You can use comma-separated values.")
cmd:option('-content_weight',2e1, "The weight for content constraint. Increasing this value will make the result more content faithful. Decreasing the value will make the method more style faithful. Notice this value should be increase (for example, doubled) if layer 12 is included for MRF constraint.")
cmd:option('-tv_weight',1e-3, "TV smoothness weight")
cmd:option('-scaler', 2, "Relative expansion from example to result. This settings is relevant only for syn setting.")
cmd:option('-gpu_chunck_size_1',256, "Size of chunks to split feature maps along the channel dimension. This is to save memory when normalizing the matching score in mrf layers. Use large value if you have large gpu memory. As reference we use 256 for Titan X, and 32 for Geforce GT750M 2G.")
cmd:option('-gpu_chunck_size_2',16, "Size of chuncks to split feature maps along the y dimension. This is to save memory when normalizing the matching score in mrf layers. Use large value if you have large gpu memory. As reference we use 16 for Titan X, and 2 for Geforce GT750M 2G.")
-- fixed parameters
cmd:option('-target_step_rotation', math.pi/24)
cmd:option('-target_step_scale', 1.05)
cmd:option('-output_folder', 'data/result/trans/MRF/')
cmd:option('-proto_file', 'data/models/VGG_ILSVRC_19_layers_deploy.prototxt')
cmd:option('-model_file', 'data/models/VGG_ILSVRC_19_layers.caffemodel')
cmd:option('-gpu', 0, 'Zero-indexed ID of the GPU to use')
cmd:option('-nCorrection', 25)
cmd:option('-print_iter', 10)
cmd:option('-save_iter', 10)
params = cmd:parse(arg)
for _,par in pairs({'mrf_layers', 'mrf_weight', 'num_iter', 'mrf_patch_size', 'target_sample_stride', 'mrf_confidence_threshold', 'source_sample_stride', 'content_layers'}) do
params[par] = split(params[par], ',', tonumber)
end
local wrapper = nil
if params.type == 'transfer' then
wrapper = require 'transfer_CNNMRF_wrapper'
else
wrapper = require 'syn_CNNMRF_wrapper'
end
wrapper.main(params)
|
fixed multi-valued options
|
fixed multi-valued options
|
Lua
|
mit
|
chuanli11/CNNMRF
|
77e1d3810aa0a5315f2f78b18308bce25a2e0816
|
Extensions/subsets_and_batches.lua
|
Extensions/subsets_and_batches.lua
|
local params = {...}
local Dataframe = params[1]
local argcheck = require "argcheck"
local doc = require "argcheck.doc"
doc[[
## Subsets and batches
The core idea behind loading batches and is that you split your dataset using the
`create_subsets` function where you can also choose the sampler that you want. The
sampler will decide how `get_batch` retrieves a Batchframe object. The Batchframe
is a sub_class to Dataframe with the major difference being the `to_tensor` functionality
that has here been extended so that you can load data and labels from the same dataset.
If you want to run the batch loader in parallel you need to keep the sampling in
the main thread and do the `to_tensor` conversion in the threads. This as the offset
for the sampler is hidden inside the samplers local environement and the main thread
has no way of knowing that you've sampled the next 30 cases in the data in a subthread.
]]
Dataframe.create_subsets = argcheck{
doc = [[
<a name="Dataframe.create_subsets">
### Dataframe.create_subsets(@ARGP)
Initializes the metadata needed for batch loading:
- Subsets e.g. for training, validating, and testing
- Samplers associated with the above
The metadata is stored under `self.subsets.*`.
_Note_: This function must be called prior to load_batch as it needs the
information for loading correct rows.
@ARGT
_Return value_: self
]],
{name='self', type='Dataframe'},
{name='subsets', type='Df_Dict',
doc=[[ The default data subsets are:
{['train'] = 0.7,
['validate'] = 0.2,
['test'] = 0.1}]],
default=false},
{name='samplers', type='Df_Dict|string',
doc=[[The samplers to use together with the subsets. Defaults to permutation
for the train set while the validate and test have a linear. If you provide a
string identifying the sampler it will be used by all the subsets.]],
default=false},
call=function(self, subsets, samplers)
if (not subsets) then
subsets = {['train'] = 0.7,
['validate'] = 0.2,
['test'] = 0.1}
else
subsets = subsets.data
end
-- Check data_type for inconcistencies
local total = 0
for v,p in pairs(subsets) do
assert(type(v) == 'string', "The data types keys should be strings")
assert(type(p) == 'number', "The data types values should be numbers")
total = total + p
end
-- Normalize the data to proportions
if (math.abs(total - 1) > 1e-4) then
print("Warning: You have provided a total ~= 1 (".. total .. ")")
for v,p in pairs(subsets) do
subsets[v] = subsets[v]/total
end
end
-- Initiate samplers
if (not samplers) then
samplers = {}
if (subsets['train'] ~= nil) then
samplers.train = 'permutation'
end
for _,type in ipairs({'validate', 'test'}) do
if (subsets[type] ~= nil) then
samplers[type] = 'linear'
end
end
for type,_ in pairs(subsets) do
if (samplers[type] ~= nil) then
samplers[type] = 'permutation'
end
end
else
samplers = samplers.data
-- Add samplers that are missing in the sampler input
for type,_ in pairs(subsets) do
if (samplers[type] ~= nil) then
if (type == 'validate' or
type == 'test') then
samplers[type] = 'linear'
else
samplers[type] = 'permutation'
end
end
end
end
self.subsets = {
subset_splits = subsets,
samplers = samplers
}
return self:reset_subsets()
end}
Dataframe.reset_subsets = argcheck{
doc = [[
<a name="Dataframe.reset_subsets">
### Dataframe.reset_subsets(@ARGP)
Clears the previous subsets and creates new ones according to saved information
in the `self.subsets.subset_splits` and `subsets.subsets.samplers` created by
the `create_subsets` function.
@ARGT
_Return value_: self
]],
{name='self', type='Dataframe'},
call=function(self)
assert(self.subsets ~= nil and
self.subsets.subset_splits ~= nil and
self.subsets.samplers ~= nil,
"You haven't initiated your subsets correctly. Please call create_subsets() before the reset_subsets()")
local offset = 0
local i = 0
local n_subsets = table.exact_length(self.subsets.subset_splits)
local permuations = torch.randperm(self:size(1))
self.subsets.sub_objs = {}
for name, proportion in pairs(self.subsets.subset_splits) do
i = i + 1
if (i == n_subsets) then
-- Use the remainder (should be correct as the create_subsets takes care of normalizing)
self.subsets.sub_objs[name] =
Df_Subset(Df_Array(permuations[{{offset + 1, self:size(1)}}]),
self.subsets.samplers[name],
self)
offset = self:size(1)
else
local no_to_select = self.subsets.subset_splits[name] * self:size(1)
-- Clean the number just to make sure we have a valid number
-- and that the number is an integer
no_to_select = math.min(1, math.floor(no_to_select))
self.subsets.sub_objs[name] =
Df_Subset(Df_Array(permuations[{{offset + 1, offset + no_to_select}}]),
self.subsets.samplers[name],
self)
offset = offset + no_to_select
end
end
return self
end}
Dataframe.has_subset = argcheck{
doc = [[
<a name="Dataframe.has_subset">
### Dataframe.has_subset(@ARGP)
Checks if subset used in batch loading is available
@ARGT
_Return value_: boolean
]],
{name="self", type="Dataframe"},
{name='subset', type='string', doc='Type of subset to check for'},
call = function(self, subset)
return(self.batch ~= nil and
self.batch.sub_objs ~= nil and
self.batch.sub_objs[subset] ~= nil)
end}
Dataframe.get_subset = argcheck{
doc = [[
<a name="Dataframe.get_subset">
### Dataframe.get_subset(@ARGP)
Returns the entire subset as either a Df_Subset, Dataframe or Batchframe
@ARGT
_Return value_: Df_Subset, Dataframe or Batchframe
]],
{name="self", type="Dataframe"},
{name='subset', type='string', doc='Type of data to load'},
{name='return_type', type='string',
doc=[[Choose the type of return object that you're interested in.
Return a Batchframe with a different `to_tensor` functionality that allows
loading data, label tensors simultaneously]], default="Df_Subset"},
call = function(self, subset, return_type)
assert(self:has_subset(subset), "There is no subset named " .. subset)
local sub_obj = self.subsets.sub_objs[subset]
if (return_type == "Df_Subset") then
return sub_obj
end
if (return_type == "Dataframe") then
return self:
_create_subset{index_items = Df_Array[sub_obj:get_column('indexes')],
as_batchframe = false}
end
if (return_type == "Batchframe") then
return self:
_create_subset{index_items = Df_Array[sub_obj:get_column('indexes')],
as_batchframe = false}
end
error("Invalid return type: " .. return_type)
end}
|
local params = {...}
local Dataframe = params[1]
local argcheck = require "argcheck"
local doc = require "argcheck.doc"
doc[[
## Subsets and batches
The core idea behind loading batches and is that you split your dataset using the
`create_subsets` function where you can also choose the sampler that you want. The
sampler will decide how `get_batch` retrieves a Batchframe object. The Batchframe
is a sub_class to Dataframe with the major difference being the `to_tensor` functionality
that has here been extended so that you can load data and labels from the same dataset.
If you want to run the batch loader in parallel you need to keep the sampling in
the main thread and do the `to_tensor` conversion in the threads. This as the offset
for the sampler is hidden inside the samplers local environement and the main thread
has no way of knowing that you've sampled the next 30 cases in the data in a subthread.
]]
Dataframe.create_subsets = argcheck{
doc = [[
<a name="Dataframe.create_subsets">
### Dataframe.create_subsets(@ARGP)
Initializes the metadata needed for batch loading:
- Subsets e.g. for training, validating, and testing
- Samplers associated with the above
The metadata is stored under `self.subsets.*`.
_Note_: This function must be called prior to load_batch as it needs the
information for loading correct rows.
@ARGT
_Return value_: self
]],
{name='self', type='Dataframe'},
{name='subsets', type='Df_Dict',
doc=[[ The default data subsets are:
{['train'] = 0.7,
['validate'] = 0.2,
['test'] = 0.1}]],
default=false},
{name='samplers', type='Df_Dict|string',
doc=[[The samplers to use together with the subsets. Defaults to permutation
for the train set while the validate and test have a linear. If you provide a
string identifying the sampler it will be used by all the subsets.]],
default=false},
call=function(self, subsets, samplers)
if (not subsets) then
subsets = {['train'] = 0.7,
['validate'] = 0.2,
['test'] = 0.1}
else
subsets = subsets.data
end
-- Check data_type for inconcistencies
local total = 0
for v,p in pairs(subsets) do
assert(type(v) == 'string', "The data types keys should be strings")
assert(type(p) == 'number', "The data types values should be numbers")
total = total + p
end
-- Normalize the data to proportions
if (math.abs(total - 1) > 1e-4) then
print("Warning: You have provided a total ~= 1 (".. total .. ")")
for v,p in pairs(subsets) do
subsets[v] = subsets[v]/total
end
end
-- Initiate samplers
if (not samplers) then
samplers = {}
if (subsets['train'] ~= nil) then
samplers.train = 'permutation'
end
for _,type in ipairs({'validate', 'test'}) do
if (subsets[type] ~= nil) then
samplers[type] = 'linear'
end
end
for type,_ in pairs(subsets) do
if (samplers[type] == nil) then
samplers[type] = 'permutation'
end
end
else
samplers = samplers.data
-- Add samplers that are missing in the sampler input
for type,_ in pairs(subsets) do
if (samplers[type] ~= nil) then
if (type == 'validate' or
type == 'test') then
samplers[type] = 'linear'
else
samplers[type] = 'permutation'
end
end
end
end
self.subsets = {
subset_splits = subsets,
samplers = samplers
}
return self:reset_subsets()
end}
Dataframe.reset_subsets = argcheck{
doc = [[
<a name="Dataframe.reset_subsets">
### Dataframe.reset_subsets(@ARGP)
Clears the previous subsets and creates new ones according to saved information
in the `self.subsets.subset_splits` and `subsets.subsets.samplers` created by
the `create_subsets` function.
@ARGT
_Return value_: self
]],
{name='self', type='Dataframe'},
call=function(self)
assert(self.subsets ~= nil and
self.subsets.subset_splits ~= nil and
self.subsets.samplers ~= nil,
"You haven't initiated your subsets correctly. Please call create_subsets() before the reset_subsets()")
local offset = 0
local i = 0
local n_subsets = table.exact_length(self.subsets.subset_splits)
local permuations = torch.randperm(self:size(1))
self.subsets.sub_objs = {}
for name, proportion in pairs(self.subsets.subset_splits) do
i = i + 1
if (i == n_subsets) then
-- Use the remainder (should be correct as the create_subsets takes care of normalizing)
self.subsets.sub_objs[name] =
Df_Subset(Df_Array(permuations[{{offset + 1, self:size(1)}}]),
self.subsets.samplers[name],
self)
offset = self:size(1)
else
local no_to_select = self.subsets.subset_splits[name] * self:size(1)
-- Clean the number just to make sure we have a valid number
-- and that the number is an integer
no_to_select = math.max(1, math.floor(no_to_select))
self.subsets.sub_objs[name] =
Df_Subset(Df_Array(permuations[{{offset + 1, offset + no_to_select}}]),
self.subsets.samplers[name],
self)
offset = offset + no_to_select
end
end
return self
end}
Dataframe.has_subset = argcheck{
doc = [[
<a name="Dataframe.has_subset">
### Dataframe.has_subset(@ARGP)
Checks if subset used in batch loading is available
@ARGT
_Return value_: boolean
]],
{name="self", type="Dataframe"},
{name='subset', type='string', doc='Type of subset to check for'},
call = function(self, subset)
return(self.subsets ~= nil and
self.subsets.sub_objs ~= nil and
self.subsets.sub_objs[subset] ~= nil)
end}
Dataframe.get_subset = argcheck{
doc = [[
<a name="Dataframe.get_subset">
### Dataframe.get_subset(@ARGP)
Returns the entire subset as either a Df_Subset, Dataframe or Batchframe
@ARGT
_Return value_: Df_Subset, Dataframe or Batchframe
]],
{name="self", type="Dataframe"},
{name='subset', type='string', doc='Type of data to load'},
{name='return_type', type='string',
doc=[[Choose the type of return object that you're interested in.
Return a Batchframe with a different `to_tensor` functionality that allows
loading data, label tensors simultaneously]], default="Df_Subset"},
call = function(self, subset, return_type)
assert(self:has_subset(subset),
("There is no subset named '%s' among the subsets: %s"):
format(subset, table.get_key_string(self.subsets.sub_objs)))
local sub_obj = self.subsets.sub_objs[subset]
if (return_type == "Df_Subset") then
return sub_obj
end
if (return_type == "Dataframe") then
return self:
_create_subset{index_items = Df_Array[sub_obj:get_column('indexes')],
as_batchframe = false}
end
if (return_type == "Batchframe") then
return self:
_create_subset{index_items = Df_Array[sub_obj:get_column('indexes')],
as_batchframe = false}
end
error("Invalid return type: " .. return_type)
end}
|
Logical and naming mistakes fixed
|
Logical and naming mistakes fixed
|
Lua
|
mit
|
AlexMili/torch-dataframe
|
9e887a32d3fced6e45ca3a86bbac1cb58755e84b
|
lua/entities/gmod_wire_grabber.lua
|
lua/entities/gmod_wire_grabber.lua
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Grabber"
ENT.RenderGroup = RENDERGROUP_BOTH
ENT.WireDebugName = "Grabber"
function ENT:SetupDataTables()
self:NetworkVar( "Float", 0, "BeamLength" )
end
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Inputs = Wire_CreateInputs(self, { "Grab","Strength" })
self.Outputs = Wire_CreateOutputs(self, {"Holding", "Grabbed Entity [ENTITY]"})
self.WeldStrength = 0
self.Weld = nil
self.WeldEntity = nil
self.ExtraProp = nil
self.ExtraPropWeld = nil
self:GetPhysicsObject():SetMass(10)
self:Setup(100, true)
end
function ENT:OnRemove()
if self.Weld then
self:ResetGrab()
end
Wire_Remove(self)
end
function ENT:Setup(Range, Gravity)
if Range then self:SetBeamLength(Range) end
self.Gravity = Gravity
end
function ENT:LinkEnt( prop )
if not IsValid(prop) then return false, "Not a valid entity!" end
self.ExtraProp = prop
WireLib.SendMarks(self, {prop})
return true
end
function ENT:UnlinkEnt()
if IsValid(self.ExtraPropWeld) then
self.ExtraPropWeld:Remove()
self.ExtraPropWeld = nil
end
self.ExtraProp = nil
WireLib.SendMarks(self, {})
return true
end
function ENT:ResetGrab()
if IsValid(self.Weld) then
self.Weld:Remove()
if IsValid(self.WeldEntity) and IsValid(self.WeldEntity:GetPhysicsObject()) and self.Gravity then
self.WeldEntity:GetPhysicsObject():EnableGravity(true)
end
end
if IsValid(self.ExtraPropWeld) then
self.ExtraPropWeld:Remove()
end
self.Weld = nil
self.WeldEntity = nil
self.ExtraPropWeld = nil
self:SetColor(Color(255, 255, 255, self:GetColor().a))
Wire_TriggerOutput(self, "Holding", 0)
Wire_TriggerOutput(self, "Grabbed Entity", self.WeldEntity)
end
function ENT:CanGrab(trace)
if not trace.Entity or not isentity(trace.Entity) then return false end
if (not trace.Entity:IsValid() and not trace.Entity:IsWorld()) or trace.Entity:IsPlayer() then return false end
-- If there's no physics object then we can't constraint it!
if not util.IsValidPhysicsObject(trace.Entity, trace.PhysicsBone) then return false end
if not gamemode.Call( "CanTool", self:GetPlayer(), trace, "weld" ) then return false end
return true
end
function ENT:TriggerInput(iname, value)
if iname == "Grab" then
if value ~= 0 and self.Weld == nil then
local vStart = self:GetPos()
local vForward = self:GetUp()
local filter = ents.FindByClass( "gmod_wire_spawner" ) -- for prop spawning contraptions that grab spawned props
table.insert( filter, self )
local trace = util.TraceLine {
start = vStart,
endpos = vStart + (vForward * self:GetBeamLength()),
filter = filter
}
if not self:CanGrab(trace) then return end
-- Weld them!
local const = constraint.Weld(self, trace.Entity, 0, 0, self.WeldStrength)
if const then
const.Type = "" --prevents the duplicator from making this weld
end
local const2
--Msg("+Weld1\n")
if self.ExtraProp then
if self.ExtraProp:IsValid() then
const2 = constraint.Weld(self.ExtraProp, trace.Entity, 0, 0, self.WeldStrength)
if const2 then
const2.Type = "" --prevents the duplicator from making this weld
end
--Msg("+Weld2\n")
end
end
if self.Gravity then
trace.Entity:GetPhysicsObject():EnableGravity(false)
end
self.WeldEntity = trace.Entity
self.Weld = const
self.ExtraPropWeld = const2
self:SetColor(Color(255, 0, 0, self:GetColor().a))
Wire_TriggerOutput(self, "Holding", 1)
Wire_TriggerOutput(self, "Grabbed Entity", self.WeldEntity)
elseif value == 0 then
if self.Weld ~= nil or self.ExtraPropWeld ~= nil then
self:ResetGrab()
end
end
elseif iname == "Strength" then
self.WeldStrength = math.max(value,0)
end
end
--duplicator support (TAD2020)
function ENT:BuildDupeInfo()
local info = self.BaseClass.BuildDupeInfo(self) or {}
if self.WeldEntity and self.WeldEntity:IsValid() then
info.WeldEntity = self.WeldEntity:EntIndex()
end
if self.ExtraProp and self.ExtraProp:IsValid() then
info.ExtraProp = self.ExtraProp:EntIndex()
end
return info
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
self.WeldEntity = GetEntByID(info.WeldEntity)
self.ExtraProp = GetEntByID(info.ExtraProp)
if self.WeldEntity and self.Inputs.Grab.Value ~= 0 then
if not self.Weld and self.trace~=nil then
self.Weld = constraint.Weld(self, self.trace, 0, 0, self.WeldStrength)
self.Weld.Type = "" --prevents the duplicator from making this weld
end
if IsValid(self.ExtraProp) then
self.ExtraPropWeld = constraint.Weld(self.ExtraProp, self.WeldEntity, 0, 0, self.WeldStrength)
self.ExtraPropWeld.Type = "" --prevents the duplicator from making this weld
end
if self.Gravity then
self.WeldEntity:GetPhysicsObject():EnableGravity(false)
end
if self.Weld then
self:SetColor(Color(255, 0, 0, self:GetColor().a))
Wire_TriggerOutput(self, "Holding", 1)
Wire_TriggerOutput(self, "Grabbed Entity", self.WeldEntity)
else
self:ResetGrab()
end
end
end
duplicator.RegisterEntityClass("gmod_wire_grabber", WireLib.MakeWireEnt, "Data", "Range", "Gravity")
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Grabber"
ENT.RenderGroup = RENDERGROUP_BOTH
ENT.WireDebugName = "Grabber"
function ENT:SetupDataTables()
self:NetworkVar( "Float", 0, "BeamLength" )
end
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Inputs = Wire_CreateInputs(self, { "Grab","Strength","Range" })
self.Outputs = Wire_CreateOutputs(self, {"Holding", "Grabbed Entity [ENTITY]"})
self.WeldStrength = 0
self.Weld = nil
self.WeldEntity = nil
self.ExtraProp = nil
self.ExtraPropWeld = nil
self:GetPhysicsObject():SetMass(10)
self:Setup(100, true)
end
function ENT:OnRemove()
if self.Weld then
self:ResetGrab()
end
Wire_Remove(self)
end
function ENT:Setup(Range, Gravity)
if Range then self:SetBeamLength(Range) end
self.Gravity = Gravity
end
function ENT:LinkEnt( prop )
if not IsValid(prop) then return false, "Not a valid entity!" end
self.ExtraProp = prop
WireLib.SendMarks(self, {prop})
return true
end
function ENT:UnlinkEnt()
if IsValid(self.ExtraPropWeld) then
self.ExtraPropWeld:Remove()
self.ExtraPropWeld = nil
end
self.ExtraProp = nil
WireLib.SendMarks(self, {})
return true
end
function ENT:ResetGrab()
if IsValid(self.Weld) then
self.Weld:Remove()
if IsValid(self.WeldEntity) and IsValid(self.WeldEntity:GetPhysicsObject()) and self.Gravity then
self.WeldEntity:GetPhysicsObject():EnableGravity(true)
end
end
if IsValid(self.ExtraPropWeld) then
self.ExtraPropWeld:Remove()
end
self.Weld = nil
self.WeldEntity = nil
self.ExtraPropWeld = nil
self:SetColor(Color(255, 255, 255, self:GetColor().a))
Wire_TriggerOutput(self, "Holding", 0)
Wire_TriggerOutput(self, "Grabbed Entity", self.WeldEntity)
end
function ENT:CanGrab(trace)
if not trace.Entity or not isentity(trace.Entity) then return false end
if (not trace.Entity:IsValid() and not trace.Entity:IsWorld()) or trace.Entity:IsPlayer() then return false end
-- If there's no physics object then we can't constraint it!
if not util.IsValidPhysicsObject(trace.Entity, trace.PhysicsBone) then return false end
if not gamemode.Call( "CanTool", self:GetPlayer(), trace, "weld" ) then return false end
return true
end
function ENT:TriggerInput(iname, value)
if iname == "Grab" then
if value ~= 0 and self.Weld == nil then
local vStart = self:GetPos()
local vForward = self:GetUp()
local filter = ents.FindByClass( "gmod_wire_spawner" ) -- for prop spawning contraptions that grab spawned props
table.insert( filter, self )
local trace = util.TraceLine {
start = vStart,
endpos = vStart + (vForward * self:GetBeamLength()),
filter = filter
}
if not self:CanGrab(trace) then return end
-- Weld them!
local const = constraint.Weld(self, trace.Entity, 0, 0, self.WeldStrength)
if const then
const.Type = "" --prevents the duplicator from making this weld
end
local const2
--Msg("+Weld1\n")
if self.ExtraProp then
if self.ExtraProp:IsValid() then
const2 = constraint.Weld(self.ExtraProp, trace.Entity, 0, 0, self.WeldStrength)
if const2 then
const2.Type = "" --prevents the duplicator from making this weld
end
--Msg("+Weld2\n")
end
end
if self.Gravity then
trace.Entity:GetPhysicsObject():EnableGravity(false)
end
self.WeldEntity = trace.Entity
self.Weld = const
self.ExtraPropWeld = const2
self:SetColor(Color(255, 0, 0, self:GetColor().a))
Wire_TriggerOutput(self, "Holding", 1)
Wire_TriggerOutput(self, "Grabbed Entity", self.WeldEntity)
elseif value == 0 then
if self.Weld ~= nil or self.ExtraPropWeld ~= nil then
self:ResetGrab()
end
end
elseif iname == "Strength" then
self.WeldStrength = math.max(value,0)
elseif iname == "Range" then
self:SetBeamLength(math.Clamp(value,0,32000))
self:ResetGrab() -- reset grab on change
end
end
--duplicator support (TAD2020)
function ENT:BuildDupeInfo()
local info = self.BaseClass.BuildDupeInfo(self) or {}
if self.WeldEntity and self.WeldEntity:IsValid() then
info.WeldEntity = self.WeldEntity:EntIndex()
end
if self.ExtraProp and self.ExtraProp:IsValid() then
info.ExtraProp = self.ExtraProp:EntIndex()
end
return info
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
self.WeldEntity = GetEntByID(info.WeldEntity)
self.ExtraProp = GetEntByID(info.ExtraProp)
if self.WeldEntity and self.Inputs.Grab.Value ~= 0 then
if not self.Weld and self.trace~=nil then
self.Weld = constraint.Weld(self, self.trace, 0, 0, self.WeldStrength)
self.Weld.Type = "" --prevents the duplicator from making this weld
end
if IsValid(self.ExtraProp) then
self.ExtraPropWeld = constraint.Weld(self.ExtraProp, self.WeldEntity, 0, 0, self.WeldStrength)
self.ExtraPropWeld.Type = "" --prevents the duplicator from making this weld
end
if self.Gravity then
self.WeldEntity:GetPhysicsObject():EnableGravity(false)
end
if self.Weld then
self:SetColor(Color(255, 0, 0, self:GetColor().a))
Wire_TriggerOutput(self, "Holding", 1)
Wire_TriggerOutput(self, "Grabbed Entity", self.WeldEntity)
else
self:ResetGrab()
end
end
end
duplicator.RegisterEntityClass("gmod_wire_grabber", WireLib.MakeWireEnt, "Data", "Range", "Gravity")
|
Add Range input for grabber
|
Add Range input for grabber
Basically same as for transferer and cd ray. But also reset grabber on change beam (for prevent possible "bugs").
|
Lua
|
apache-2.0
|
wiremod/wire,garrysmodlua/wire,sammyt291/wire,thegrb93/wire,dvdvideo1234/wire,Grocel/wire,NezzKryptic/Wire
|
0b1ad27c7ac762e804ad3ccc7631f9d6dcea6bbc
|
plugins/lua/user_modules/algo/crc32.lua
|
plugins/lua/user_modules/algo/crc32.lua
|
algo = algo or {};
function algo.CRC32(stuff)
local Polynomial = 0xEDB88320;
local lookup = {};
for i = 0, 0xFF do
local crc = i;
for j = 0, 7 do
crc = (crc >> 1) ~ ((crc & 1) * Polynomial);
end
lookup[i] = crc;
end
local function dw(x) return x & 0xFFFFFFFF; end
local poly = 0xEDB88320;
local crc = dw(~0);
for i = 1, stuff:len() do
crc = (crc >> 8) ~ lookup[((crc & 0xFF) ~ stuff:sub(i,i):byte())];
end
return dw(~crc);
end
|
algo = algo or {};
local Polynomial = 0xEDB88320;
local lookup = {};
for i = 0, 0xFF do
local crc = i;
for j = 0, 7 do
crc = (crc >> 1) ~ ((crc & 1) * Polynomial);
end
lookup[i] = crc;
end
local function dw(x) return x & 0xFFFFFFFF; end
function algo.CRC32(stuff)
stuff = tostring(stuff);
local crc = dw(~0);
for i = 1, stuff:len() do
crc = (crc >> 8) ~ lookup[((crc & 0xFF) ~ stuff:sub(i,i):byte())];
end
return dw(~crc);
end
|
Algorithm fixes
|
Algorithm fixes
|
Lua
|
cc0-1.0
|
SwadicalRag/hash.js,meepdarknessmeep/hash.js
|
20392d6d3e632562b910609e7afdc6a9cfa143b7
|
packages/nn/LookupTable.lua
|
packages/nn/LookupTable.lua
|
local LookupTable, parent = torch.class('nn.LookupTable', 'nn.Module')
LookupTable.__version = 2
function LookupTable:__init(nIndex, ...)
parent.__init(self)
if select('#', ...) == 1 and type(select(1, ...)) ~= "number" then
local size = select(1, ...)
self.size = torch.LongStorage(#size + 1)
for i=1,#size do
self.size[i+1] = size[i]
end
else
self.size = torch.LongStorage(select('#', ...)+1)
for i=1,select('#',...) do
self.size[i+1] = select(i, ...)
end
end
self.size[1] = nIndex
self.weight = torch.Tensor(self.size)
self.gradWeight = torch.Tensor(self.size)
self.currentInputs = {}
self:reset()
end
function LookupTable:reset(stdv)
stdv = stdv or 1
self.weight:apply(function()
return random.normal(0, stdv)
end)
end
function LookupTable:forward(input)
local nIndex = input:size(1)
self.size[1] = nIndex
self.output:resize(self.size)
for i=1,nIndex do
self.output:select(1, i):copy(self.weight:select(1, input[i]))
end
return self.output
end
function LookupTable:zeroGradParameters()
for i=1,#self.currentInputs do
self.gradWeight:select(1, currentInput[i]):zero()
self.currentInputs[i] = nil
end
end
function LookupTable:accGradParameters(input, gradOutput, scale)
table.insert(self.currentInputs, input.new(input:size()):copy(input))
self.gradWeight:select(1, currentInput[i]):add(scale, gradOutput:select(1, i))
end
function LookupTable:accUpdateGradParameters(input, gradOutput, lr)
self.weight:select(1, currentInput[i]):add(-lr, gradOutput:select(1, i))
end
function LookupTable:updateParameters(learningRate)
for i=1,#self.currentInputs do
local currentInput = self.currentInputs[i]
local currentGradWeight = self.currentGradWeights[i]
for i=1,currentInput:size(1) do
self.weight:select(1, currentInput[i]):add(-learningRate, self.gradWeight:select(1, currentInput[i]))
end
end
end
|
local LookupTable, parent = torch.class('nn.LookupTable', 'nn.Module')
LookupTable.__version = 2
function LookupTable:__init(nIndex, ...)
parent.__init(self)
if select('#', ...) == 1 and type(select(1, ...)) ~= "number" then
local size = select(1, ...)
self.size = torch.LongStorage(#size + 1)
for i=1,#size do
self.size[i+1] = size[i]
end
else
self.size = torch.LongStorage(select('#', ...)+1)
for i=1,select('#',...) do
self.size[i+1] = select(i, ...)
end
end
self.size[1] = nIndex
self.weight = torch.Tensor(self.size)
self.gradWeight = torch.Tensor(self.size)
self.currentInputs = {}
self:reset()
end
function LookupTable:reset(stdv)
stdv = stdv or 1
self.weight:apply(function()
return random.normal(0, stdv)
end)
end
function LookupTable:forward(input)
local nIndex = input:size(1)
self.size[1] = nIndex
self.output:resize(self.size)
for i=1,nIndex do
self.output:select(1, i):copy(self.weight:select(1, input[i]))
end
return self.output
end
function LookupTable:zeroGradParameters()
for i=1,#self.currentInputs do
self.gradWeight:select(1, currentInput[i]):zero()
self.currentInputs[i] = nil
end
end
function LookupTable:accGradParameters(input, gradOutput, scale)
table.insert(self.currentInputs, input.new(input:size()):copy(input))
for i=1,input:size(1) do
self.gradWeight:select(1, input[i]):add(scale, gradOutput:select(1, i))
end
end
function LookupTable:accUpdateGradParameters(input, gradOutput, lr)
for i=1,input:size(1) do
self.weight:select(1, input[i]):add(-lr, gradOutput:select(1, i))
end
end
function LookupTable:updateParameters(learningRate)
for i=1,#self.currentInputs do
local currentInput = self.currentInputs[i]
local currentGradWeight = self.currentGradWeights[i]
for i=1,currentInput:size(1) do
self.weight:select(1, currentInput[i]):add(-learningRate, self.gradWeight:select(1, currentInput[i]))
end
end
end
|
bug corrections in LookupTable
|
bug corrections in LookupTable
|
Lua
|
bsd-3-clause
|
soumith/TH,soumith/TH,soumith/TH,soumith/TH
|
053dafd8be1cd0a90712dd5522b0062a6f8a336f
|
src_trunk/resources/realism-system/c_weapons_back.lua
|
src_trunk/resources/realism-system/c_weapons_back.lua
|
weapons = { }
function weaponSwitch(prevSlot, newSlot)
local weapon = getPedWeapon(source, prevSlot)
local newWeapon = getPedWeapon(source, newSlot)
if (weapons[source] == nil) then
weapons[source] = { }
end
if (weapon == 30 or weapon == 31) and (isPedInVehicle(source)==false) then
if (weapons[source][1] == nil or weapons[source][2] ~= weapon or weapons[source][3] ~= isPedDucked(source)) then -- Model never created
weapons[source][1] = createModel(source, weapon)
weapons[source][2] = weapon
weapons[source][3] = isPedDucked(source)
else
local object = weapons[source][1]
destroyElement(object)
weapons[source] = nil
end
elseif weapons[source] and weapons[source][1] and ( newWeapon == 30 or newWeapon == 31 or getPedTotalAmmo(source, 5) == 0 ) then
local object = weapons[source][1]
destroyElement(object)
weapons[source] = nil
end
end
addEventHandler("onClientPlayerWeaponSwitch", getRootElement(), weaponSwitch)
function playerEntersVehicle(player)
if (weapons[player]) then
local object = weapons[player][1]
destroyElement(object)
end
end
addEventHandler("onClientVehicleEnter", getRootElement(), playerEntersVehicle)
function playerExitsVehicle(player)
if (weapons[player]) then
local weapon = weapons[player][2]
weapons[player][1] = createModel(player, weapon)
weapons[player][3] = isPedDucked(player)
end
end
addEventHandler("onClientVehicleExit", getRootElement(), playerExitsVehicle)
function createModel(player, weapon)
local bx, by, bz = getPedBonePosition(player, 3)
local x, y, z = getElementPosition(player)
local r = getPedRotation(player)
crouched = isPedDucked(player)
local ox, oy, oz = bx-x-0.13, by-y-0.25, bz-z+0.25
if (crouched) then
oz = -0.025
end
local objectID = 355
if (weapon==31) then
objectID = 356
elseif (weapon==30) then
objectID = 355
end
local currobject = getElementData(source, "weaponback.object")
if (isElement(currobject)) then
destroyElement(currobject)
end
local object = createObject(objectID, x, y, z)
attachElements(object, player, ox, oy, oz, 0, 60, 0)
return object
end
|
weapons = { }
function weaponSwitch(prevSlot, newSlot)
local weapon = getPedWeapon(source, prevSlot)
local newWeapon = getPedWeapon(source, newSlot)
if (weapons[source] == nil) then
weapons[source] = { }
end
if (weapon == 30 or weapon == 31) and (isPedInVehicle(source)==false) then
if (weapons[source][1] == nil or weapons[source][2] ~= weapon or weapons[source][3] ~= isPedDucked(source)) then -- Model never created
weapons[source][1] = createModel(source, weapon)
weapons[source][2] = weapon
weapons[source][3] = isPedDucked(source)
else
local object = weapons[source][1]
destroyElement(object)
weapons[source] = nil
end
elseif weapons[source] and weapons[source][1] and ( newWeapon == 30 or newWeapon == 31 or getPedTotalAmmo(source, 5) == 0 ) then
local object = weapons[source][1]
destroyElement(object)
weapons[source] = nil
end
end
addEventHandler("onClientPlayerWeaponSwitch", getRootElement(), weaponSwitch)
function playerEntersVehicle(player)
if (weapons[player]) then
local object = weapons[player][1]
destroyElement(object)
end
end
addEventHandler("onClientVehicleEnter", getRootElement(), playerEntersVehicle)
function playerExitsVehicle(player)
if (weapons[player]) and getPedTotalAmmo(player, 5) > 0 then
local weapon = weapons[player][2]
weapons[player][1] = createModel(player, weapon)
weapons[player][3] = isPedDucked(player)
end
end
addEventHandler("onClientVehicleExit", getRootElement(), playerExitsVehicle)
function createModel(player, weapon)
local bx, by, bz = getPedBonePosition(player, 3)
local x, y, z = getElementPosition(player)
local r = getPedRotation(player)
crouched = isPedDucked(player)
local ox, oy, oz = bx-x-0.13, by-y-0.25, bz-z+0.25
if (crouched) then
oz = -0.025
end
local objectID = 355
if (weapon==31) then
objectID = 356
elseif (weapon==30) then
objectID = 355
end
local currobject = getElementData(source, "weaponback.object")
if (isElement(currobject)) then
destroyElement(currobject)
end
local object = createObject(objectID, x, y, z)
attachElements(object, player, ox, oy, oz, 0, 60, 0)
return object
end
|
fixed an issue with weapons showing weapons you don't have
|
fixed an issue with weapons showing weapons you don't have
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1925 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
dbac3687ecf660ec0cb33915eea63ef560a31db5
|
modules/lua/init.lua
|
modules/lua/init.lua
|
-- Copyright 2007-2011 Mitchell mitchell<att>caladbolg.net. See LICENSE.
---
-- The lua module.
-- It provides utilities for editing Lua code.
-- User tags are loaded from _USERHOME/modules/lua/tags and user apis are loaded
-- from _USERHOME/modules/lua/api.
module('_m.lua', package.seeall)
-- Markdown:
-- ## Key Commands
--
-- + `Alt+L, M`: Open this module for editing.
-- + `Alt+L, G`: Goto file being 'require'd on the current line.
-- + `Shift+Return`: Try to autocomplete an `if`, `for`, etc. statement with
-- `end`.
-- + `.`: When to the right of a known symbol, show an autocompletion list of
-- fields and functions.
-- + `:`: When to the right of a known symbol, show an autocompletion list of
-- functions only.
-- + `Ctrl+I`: (Windows and Linux) Autocomplete symbol.
-- + `Ctrl+Esc`: (Mac OSX) Autocomplete symbol.
-- + `Ctrl+H`: Show documentation for the selected symbol or the symbol under
-- the caret.
--
-- ## Fields
--
-- * `sense`: The Lua [Adeptsense](_m.textadept.adeptsense.html).
local m_editing, m_run = _m.textadept.editing, _m.textadept.run
-- Comment string tables use lexer names.
m_editing.comment_string.lua = '--'
-- Compile and Run command tables use file extensions.
m_run.run_command.lua = 'lua %(filename)'
m_run.error_detail.lua = {
pattern = '^lua: (.-):(%d+): (.+)$',
filename = 1, line = 2, message = 3
}
---
-- Sets default buffer properties for Lua files.
function set_buffer_properties()
end
-- Adeptsense.
sense = _m.textadept.adeptsense.new('lua')
sense.syntax.class_definition = 'module%s*%(?%s*[\'"]([%w_%.]+)'
sense.syntax.symbol_chars = '[%w_%.:]'
sense.syntax.type_declarations = {}
sense.syntax.type_assignments = {
['^[\'"]'] = 'string', -- foo = 'bar' or foo = "bar"
['^([%w_%.]+)%s*$'] = '%1', -- foo = _m.textadept.adeptsense
['^(_m%.textadept%.adeptsense)%.new'] = '%1',
['require%s*%(?%s*(["\'])([%w_%.]+)%1%)?'] = '%2',
['^io%.p?open%s*%b()%s*$'] = 'file'
}
sense.api_files = { _HOME..'/modules/lua/api' }
sense:add_trigger('.')
sense:add_trigger(':', false, true)
-- script/update_doc generates a fake set of ctags used for autocompletion.
sense.ctags_kinds = {
f = 'functions',
F = 'fields',
m = 'classes',
t = 'fields',
}
sense:load_ctags(_HOME..'/modules/lua/tags', true)
-- Strips '_G' from symbols since it's implied.
function sense:get_class(symbol)
return self.super.get_class(self, symbol:gsub('_G%.?', ''))
end
-- Shows an autocompletion list for the symbol behind the caret.
-- If the symbol contains a ':', only display functions. Otherwise, display
-- both functions and fields.
function sense:complete(only_fields, only_functions)
local line, pos = buffer:get_cur_line()
local symbol = line:sub(1, pos):match(self.syntax.symbol_chars..'*$')
return self.super.complete(self, false, symbol:find(':'))
end
-- Load user tags and apidoc.
if lfs.attributes(_USERHOME..'/modules/lua/tags') then
sense:load_ctags(_USERHOME..'/modules/lua/tags')
end
if lfs.attributes(_USERHOME..'/modules/lua/api') then
sense.api_files[#sense.api_files + 1] = _USERHOME..'/modules/lua/api'
end
-- Commands.
---
-- Patterns for auto 'end' completion for control structures.
-- @class table
-- @name control_structure_patterns
-- @see try_to_autocomplete_end
local control_structure_patterns = {
'^%s*for', '^%s*function', '^%s*if', '^%s*repeat', '^%s*while',
'function%s*%b()%s*$', '^%s*local%s*function'
}
---
-- Tries to autocomplete Lua's 'end' keyword for control structures like 'if',
-- 'while', 'for', etc.
-- @see control_structure_patterns
function try_to_autocomplete_end()
local buffer = buffer
local line_num = buffer:line_from_position(buffer.current_pos)
local line = buffer:get_line(line_num)
local line_indentation = buffer.line_indentation
for _, patt in ipairs(control_structure_patterns) do
if line:find(patt) then
local indent = line_indentation[line_num]
buffer:begin_undo_action()
buffer:new_line()
buffer:new_line()
buffer:add_text(patt:find('repeat') and 'until' or 'end')
line_indentation[line_num + 1] = indent + buffer.indent
buffer:line_up()
buffer:line_end()
buffer:end_undo_action()
return true
end
end
return false
end
---
-- Determines the Lua file being 'require'd, searches through package.path for
-- that file, and opens it in Textadept.
function goto_required()
local line = buffer:get_cur_line()
local patterns = { 'require%s*(%b())', 'require%s*(([\'"])[^%2]+%2)' }
local file
for _, patt in ipairs(patterns) do
file = line:match(patt)
if file then break end
end
if not file then return end
file = file:sub(2, -2):gsub('%.', '/')
for path in package.path:gmatch('[^;]+') do
path = path:gsub('?', file)
if lfs.attributes(path) then
io.open_file(path:iconv('UTF-8', _CHARSET))
break
end
end
end
events.connect(events.FILE_AFTER_SAVE,
function() -- show syntax errors as annotations
if buffer:get_lexer() == 'lua' then
local buffer = buffer
buffer:annotation_clear_all()
local text = buffer:get_text()
text = text:gsub('^#![^\n]+', '') -- ignore shebang line
local _, err = loadstring(text)
if err then
local line, msg = err:match('^.-:(%d+):%s*(.+)$')
if line then
buffer.annotation_visible = 2
buffer:annotation_set_text(line - 1, msg)
buffer.annotation_style[line - 1] = 8 -- error style number
buffer:goto_line(line - 1)
end
end
end
end)
---
-- Container for Lua-specific key commands.
-- @class table
-- @name _G.keys.lua
keys.lua = {
al = {
m = { io.open_file,
(_HOME..'/modules/lua/init.lua'):iconv('UTF-8', _CHARSET) },
g = { goto_required },
},
['s\n'] = { try_to_autocomplete_end },
[not OSX and 'ci' or 'cesc'] = { sense.complete, sense },
ch = { sense.show_apidoc, sense },
}
-- Snippets.
if type(snippets) == 'table' then
---
-- Container for Lua-specific snippets.
-- @class table
-- @name _G.snippets.lua
snippets.lua = {
l = "local %1(expr)%2( = %3(value))",
p = "print(%0)",
f = "function %1(name)(%2(args))\n\t%0\nend",
['for'] = "for i = %1(1), %2(10)%3(, -1) do\n\t%0\nend",
fori = "for %1(i), %2(val) in ipairs(%3(table)) do\n\t%0\nend",
forp = "for %1(k), %2(v) in pairs(%3(table)) do\n\t%0\nend",
}
end
|
-- Copyright 2007-2011 Mitchell mitchell<att>caladbolg.net. See LICENSE.
---
-- The lua module.
-- It provides utilities for editing Lua code.
-- User tags are loaded from _USERHOME/modules/lua/tags and user apis are loaded
-- from _USERHOME/modules/lua/api.
module('_m.lua', package.seeall)
-- Markdown:
-- ## Key Commands
--
-- + `Alt+L, M`: Open this module for editing.
-- + `Alt+L, G`: Goto file being 'require'd on the current line.
-- + `Shift+Return`: Try to autocomplete an `if`, `for`, etc. statement with
-- `end`.
-- + `.`: When to the right of a known symbol, show an autocompletion list of
-- fields and functions.
-- + `:`: When to the right of a known symbol, show an autocompletion list of
-- functions only.
-- + `Ctrl+I`: (Windows and Linux) Autocomplete symbol.
-- + `Ctrl+Esc`: (Mac OSX) Autocomplete symbol.
-- + `Ctrl+H`: Show documentation for the selected symbol or the symbol under
-- the caret.
--
-- ## Fields
--
-- * `sense`: The Lua [Adeptsense](_m.textadept.adeptsense.html).
local m_editing, m_run = _m.textadept.editing, _m.textadept.run
-- Comment string tables use lexer names.
m_editing.comment_string.lua = '--'
-- Compile and Run command tables use file extensions.
m_run.run_command.lua = 'lua %(filename)'
m_run.error_detail.lua = {
pattern = '^lua: (.-):(%d+): (.+)$',
filename = 1, line = 2, message = 3
}
---
-- Sets default buffer properties for Lua files.
function set_buffer_properties()
end
-- Adeptsense.
sense = _m.textadept.adeptsense.new('lua')
sense.syntax.class_definition = 'module%s*%(?%s*[\'"]([%w_%.]+)'
sense.syntax.symbol_chars = '[%w_%.:]'
sense.syntax.type_declarations = {}
sense.syntax.type_assignments = {
['^[\'"]'] = 'string', -- foo = 'bar' or foo = "bar"
['^([%w_%.]+)%s*$'] = '%1', -- foo = _m.textadept.adeptsense
['^(_m%.textadept%.adeptsense)%.new'] = '%1',
['require%s*%(?%s*(["\'])([%w_%.]+)%1%)?'] = '%2',
['^io%.p?open%s*%b()%s*$'] = 'file'
}
sense.api_files = { _HOME..'/modules/lua/api' }
sense:add_trigger('.')
sense:add_trigger(':', false, true)
-- script/update_doc generates a fake set of ctags used for autocompletion.
sense.ctags_kinds = {
f = 'functions',
F = 'fields',
m = 'classes',
t = 'fields',
}
sense:load_ctags(_HOME..'/modules/lua/tags', true)
-- Strips '_G' from symbols since it's implied.
function sense:get_class(symbol)
if symbol:find('^_G') then
symbol = symbol:gsub('_G%.?', '')
if symbol == '' then return '' end
end
return self.super.get_class(self, symbol)
end
-- Shows an autocompletion list for the symbol behind the caret.
-- If the symbol contains a ':', only display functions. Otherwise, display
-- both functions and fields.
function sense:complete(only_fields, only_functions)
local line, pos = buffer:get_cur_line()
local symbol = line:sub(1, pos):match(self.syntax.symbol_chars..'*$')
return self.super.complete(self, false, symbol:find(':'))
end
-- Load user tags and apidoc.
if lfs.attributes(_USERHOME..'/modules/lua/tags') then
sense:load_ctags(_USERHOME..'/modules/lua/tags')
end
if lfs.attributes(_USERHOME..'/modules/lua/api') then
sense.api_files[#sense.api_files + 1] = _USERHOME..'/modules/lua/api'
end
-- Commands.
---
-- Patterns for auto 'end' completion for control structures.
-- @class table
-- @name control_structure_patterns
-- @see try_to_autocomplete_end
local control_structure_patterns = {
'^%s*for', '^%s*function', '^%s*if', '^%s*repeat', '^%s*while',
'function%s*%b()%s*$', '^%s*local%s*function'
}
---
-- Tries to autocomplete Lua's 'end' keyword for control structures like 'if',
-- 'while', 'for', etc.
-- @see control_structure_patterns
function try_to_autocomplete_end()
local buffer = buffer
local line_num = buffer:line_from_position(buffer.current_pos)
local line = buffer:get_line(line_num)
local line_indentation = buffer.line_indentation
for _, patt in ipairs(control_structure_patterns) do
if line:find(patt) then
local indent = line_indentation[line_num]
buffer:begin_undo_action()
buffer:new_line()
buffer:new_line()
buffer:add_text(patt:find('repeat') and 'until' or 'end')
line_indentation[line_num + 1] = indent + buffer.indent
buffer:line_up()
buffer:line_end()
buffer:end_undo_action()
return true
end
end
return false
end
---
-- Determines the Lua file being 'require'd, searches through package.path for
-- that file, and opens it in Textadept.
function goto_required()
local line = buffer:get_cur_line()
local patterns = { 'require%s*(%b())', 'require%s*(([\'"])[^%2]+%2)' }
local file
for _, patt in ipairs(patterns) do
file = line:match(patt)
if file then break end
end
if not file then return end
file = file:sub(2, -2):gsub('%.', '/')
for path in package.path:gmatch('[^;]+') do
path = path:gsub('?', file)
if lfs.attributes(path) then
io.open_file(path:iconv('UTF-8', _CHARSET))
break
end
end
end
events.connect(events.FILE_AFTER_SAVE,
function() -- show syntax errors as annotations
if buffer:get_lexer() == 'lua' then
local buffer = buffer
buffer:annotation_clear_all()
local text = buffer:get_text()
text = text:gsub('^#![^\n]+', '') -- ignore shebang line
local _, err = loadstring(text)
if err then
local line, msg = err:match('^.-:(%d+):%s*(.+)$')
if line then
buffer.annotation_visible = 2
buffer:annotation_set_text(line - 1, msg)
buffer.annotation_style[line - 1] = 8 -- error style number
buffer:goto_line(line - 1)
end
end
end
end)
---
-- Container for Lua-specific key commands.
-- @class table
-- @name _G.keys.lua
keys.lua = {
al = {
m = { io.open_file,
(_HOME..'/modules/lua/init.lua'):iconv('UTF-8', _CHARSET) },
g = { goto_required },
},
['s\n'] = { try_to_autocomplete_end },
[not OSX and 'ci' or 'cesc'] = { sense.complete, sense },
ch = { sense.show_apidoc, sense },
}
-- Snippets.
if type(snippets) == 'table' then
---
-- Container for Lua-specific snippets.
-- @class table
-- @name _G.snippets.lua
snippets.lua = {
l = "local %1(expr)%2( = %3(value))",
p = "print(%0)",
f = "function %1(name)(%2(args))\n\t%0\nend",
['for'] = "for i = %1(1), %2(10)%3(, -1) do\n\t%0\nend",
fori = "for %1(i), %2(val) in ipairs(%3(table)) do\n\t%0\nend",
forp = "for %1(k), %2(v) in pairs(%3(table)) do\n\t%0\nend",
}
end
|
Fixed bug introduced by stripping '_G' in Lua Adeptsense; modules/lua/init.lua
|
Fixed bug introduced by stripping '_G' in Lua Adeptsense; modules/lua/init.lua
|
Lua
|
mit
|
jozadaquebatista/textadept,jozadaquebatista/textadept
|
6eeac33ad126152ea9c6e1985b670676d8e5b49e
|
frontend/ui/widget/filechooser.lua
|
frontend/ui/widget/filechooser.lua
|
local lfs = require("libs/libkoreader-lfs")
local UIManager = require("ui/uimanager")
local Menu = require("ui/widget/menu")
local Screen = require("device").screen
local Device = require("device")
local util = require("ffi/util")
local _ = require("gettext")
local ffi = require("ffi")
ffi.cdef[[
int strcoll (const char *str1, const char *str2);
]]
-- string sort function respecting LC_COLLATE
local function strcoll(str1, str2)
return ffi.C.strcoll(str1, str2) < 0
end
local FileChooser = Menu:extend{
no_title = true,
path = lfs.currentdir(),
parent = nil,
show_hidden = nil,
filter = function(filename) return true end,
exclude_dirs = {"%.sdr$"},
strcoll = strcoll,
collate = "strcoll", -- or collate = "access",
reverse_collate = false,
path_items = {}, -- store last browsed location(item index) for each path
}
function FileChooser:init()
self.width = Screen:getWidth()
-- common dir filter
self.dir_filter = function(dirname)
for _, pattern in ipairs(self.exclude_dirs) do
if dirname:match(pattern) then return end
end
return true
end
-- circumvent string collating in Kobo devices. See issue koreader/koreader#686
if Device:isKobo() then
self.strcoll = function(a, b) return a < b end
end
self.item_table = self:genItemTableFromPath(self.path)
Menu.init(self) -- call parent's init()
end
function FileChooser:genItemTableFromPath(path)
local dirs = {}
local files = {}
-- lfs.dir directory without permission will give error
local ok, iter, dir_obj = pcall(lfs.dir, self.path)
if ok then
for f in iter, dir_obj do
if self.show_hidden or not string.match(f, "^%.[^.]") then
local filename = self.path.."/"..f
local attributes = lfs.attributes(filename)
if attributes ~= nil then
if attributes.mode == "directory" and f ~= "." and f~=".." then
if self.dir_filter(filename) then
table.insert(dirs, {name = f, attr = attributes})
end
elseif attributes.mode == "file" then
if self.file_filter(filename) then
table.insert(files, {name = f, attr = attributes})
end
end
end
end
end
end
local sorting = nil
local reverse = self.reverse_collate
if self.collate == "strcoll" then
if DALPHA_SORT_CASE_INSENSITIVE then
sorting = function(a, b)
return self.strcoll(string.lower(a.name), string.lower(b.name)) == not reverse
end
else
sorting = function(a, b)
return self.strcoll(a.name, b.name) == not reverse
end
end
elseif self.collate == "access" then
sorting = function(a, b)
if reverse then
return a.attr.access < b.attr.access
else
return a.attr.access > b.attr.access
end
end
end
table.sort(dirs, sorting)
if path ~= "/" then table.insert(dirs, 1, {name = ".."}) end
table.sort(files, sorting)
local item_table = {}
for i, dir in ipairs(dirs) do
local subdir_path = self.path.."/"..dir.name
local items = 0
ok, iter, dir_obj = pcall(lfs.dir, subdir_path)
if ok then
for f in iter, dir_obj do
items = items + 1
end
-- exclude "." and ".."
items = items - 2
end
local istr = util.template(
items == 0 and _("0 items")
or items == 1 and _("1 item")
or _("%1 items"), items)
table.insert(item_table, {
text = dir.name.."/",
mandatory = istr,
path = subdir_path
})
end
for _, file in ipairs(files) do
local full_path = self.path.."/"..file.name
local file_size = lfs.attributes(full_path, "size") or 0
local sstr
if file_size > 1024*1024 then
sstr = string.format("%4.1f MB", file_size/1024/1024)
elseif file_size > 1024 then
sstr = string.format("%4.1f KB", file_size/1024)
else
sstr = string.format("%d B", file_size)
end
table.insert(item_table, {
text = file.name,
mandatory = sstr,
path = full_path
})
end
-- lfs.dir iterated node string may be encoded with some weird codepage on Windows
-- we need to encode them to utf-8
if ffi.os == "Windows" then
for k, v in pairs(item_table) do
if v.text then
v.text = util.multiByteToUTF8(v.text) or ""
end
end
end
return item_table
end
function FileChooser:updateItems(select_number)
Menu.updateItems(self, select_number) -- call parent's updateItems()
self.path_items[self.path] = (self.page - 1) * self.perpage + (select_number or 1)
end
function FileChooser:refreshPath()
self:swithItemTable(nil, self:genItemTableFromPath(self.path), self.path_items[self.path])
end
function FileChooser:changeToPath(path)
path = util.realpath(path)
self.path = path
self:refreshPath()
end
function FileChooser:toggleHiddenFiles()
self.show_hidden = not self.show_hidden
self:refreshPath()
end
function FileChooser:setCollate(collate)
self.collate = collate
self:refreshPath()
end
function FileChooser:toggleReverseCollate()
self.reverse_collate = not self.reverse_collate
self:refreshPath()
end
function FileChooser:onMenuSelect(item)
-- parent directory of dir without permission get nil mode
-- we need to change to parent path in this case
if lfs.attributes(item.path, "mode") == "file" then
self:onFileSelect(item.path)
else
self:changeToPath(item.path)
end
return true
end
function FileChooser:onMenuHold(item)
self:onFileHold(item.path)
return true
end
function FileChooser:onFileSelect(file)
UIManager:close(self)
return true
end
function FileChooser:onFileHold(file)
return true
end
return FileChooser
|
local lfs = require("libs/libkoreader-lfs")
local UIManager = require("ui/uimanager")
local Menu = require("ui/widget/menu")
local Screen = require("device").screen
local Device = require("device")
local util = require("ffi/util")
local _ = require("gettext")
local ffi = require("ffi")
ffi.cdef[[
int strcoll (const char *str1, const char *str2);
]]
-- string sort function respecting LC_COLLATE
local function strcoll(str1, str2)
return ffi.C.strcoll(str1, str2) < 0
end
local FileChooser = Menu:extend{
no_title = true,
path = lfs.currentdir(),
parent = nil,
show_hidden = nil,
filter = function(filename) return true end,
exclude_dirs = {"%.sdr$"},
strcoll = strcoll,
collate = "strcoll", -- or collate = "access",
reverse_collate = false,
path_items = {}, -- store last browsed location(item index) for each path
}
function FileChooser:init()
self.width = Screen:getWidth()
-- common dir filter
self.dir_filter = function(dirname)
for _, pattern in ipairs(self.exclude_dirs) do
if dirname:match(pattern) then return end
end
return true
end
self.list = function(path, dirs, files)
-- lfs.dir directory without permission will give error
local ok, iter, dir_obj = pcall(lfs.dir, path)
if ok then
for f in iter, dir_obj do
if self.show_hidden or not string.match(f, "^%.[^.]") then
local filename = path.."/"..f
local attributes = lfs.attributes(filename)
if attributes ~= nil then
if attributes.mode == "directory" and f ~= "." and f~=".." then
if self.dir_filter(filename) then
table.insert(dirs, {name = f, attr = attributes})
end
elseif attributes.mode == "file" then
if self.file_filter == nil or self.file_filter(filename) then
table.insert(files, {name = f, attr = attributes})
end
end
end
end
end
end
end
-- circumvent string collating in Kobo devices. See issue koreader/koreader#686
if Device:isKobo() then
self.strcoll = function(a, b) return a < b end
end
self.item_table = self:genItemTableFromPath(self.path)
Menu.init(self) -- call parent's init()
end
function FileChooser:genItemTableFromPath(path)
local dirs = {}
local files = {}
self.list(path, dirs, files)
local sorting = nil
local reverse = self.reverse_collate
if self.collate == "strcoll" then
if DALPHA_SORT_CASE_INSENSITIVE then
sorting = function(a, b)
return self.strcoll(string.lower(a.name), string.lower(b.name)) == not reverse
end
else
sorting = function(a, b)
return self.strcoll(a.name, b.name) == not reverse
end
end
elseif self.collate == "access" then
sorting = function(a, b)
if reverse then
return a.attr.access < b.attr.access
else
return a.attr.access > b.attr.access
end
end
end
table.sort(dirs, sorting)
if path ~= "/" then table.insert(dirs, 1, {name = ".."}) end
table.sort(files, sorting)
local item_table = {}
for i, dir in ipairs(dirs) do
local dirs = {}
local files = {}
local subdir_path = self.path.."/"..dir.name
self.list(subdir_path, dirs, files)
local items = #dirs + #files
local istr = util.template(
items == 1 and _("1 item")
or _("%1 items"), items)
table.insert(item_table, {
text = dir.name.."/",
mandatory = istr,
path = subdir_path
})
end
for _, file in ipairs(files) do
local full_path = self.path.."/"..file.name
local file_size = lfs.attributes(full_path, "size") or 0
local sstr
if file_size > 1024*1024 then
sstr = string.format("%4.1f MB", file_size/1024/1024)
elseif file_size > 1024 then
sstr = string.format("%4.1f KB", file_size/1024)
else
sstr = string.format("%d B", file_size)
end
table.insert(item_table, {
text = file.name,
mandatory = sstr,
path = full_path
})
end
-- lfs.dir iterated node string may be encoded with some weird codepage on Windows
-- we need to encode them to utf-8
if ffi.os == "Windows" then
for k, v in pairs(item_table) do
if v.text then
v.text = util.multiByteToUTF8(v.text) or ""
end
end
end
return item_table
end
function FileChooser:updateItems(select_number)
Menu.updateItems(self, select_number) -- call parent's updateItems()
self.path_items[self.path] = (self.page - 1) * self.perpage + (select_number or 1)
end
function FileChooser:refreshPath()
self:swithItemTable(nil, self:genItemTableFromPath(self.path), self.path_items[self.path])
end
function FileChooser:changeToPath(path)
path = util.realpath(path)
self.path = path
self:refreshPath()
end
function FileChooser:toggleHiddenFiles()
self.show_hidden = not self.show_hidden
self:refreshPath()
end
function FileChooser:setCollate(collate)
self.collate = collate
self:refreshPath()
end
function FileChooser:toggleReverseCollate()
self.reverse_collate = not self.reverse_collate
self:refreshPath()
end
function FileChooser:onMenuSelect(item)
-- parent directory of dir without permission get nil mode
-- we need to change to parent path in this case
if lfs.attributes(item.path, "mode") == "file" then
self:onFileSelect(item.path)
else
self:changeToPath(item.path)
end
return true
end
function FileChooser:onMenuHold(item)
self:onFileHold(item.path)
return true
end
function FileChooser:onFileSelect(file)
UIManager:close(self)
return true
end
function FileChooser:onFileHold(file)
return true
end
return FileChooser
|
*.sdr folders are not excluded in folder item count Bug #1966
|
*.sdr folders are not excluded in folder item count
Bug #1966
|
Lua
|
agpl-3.0
|
pazos/koreader,NickSavage/koreader,Frenzie/koreader,frankyifei/koreader,chihyang/koreader,Frenzie/koreader,NiLuJe/koreader,koreader/koreader,NiLuJe/koreader,mwoz123/koreader,poire-z/koreader,Markismus/koreader,houqp/koreader,koreader/koreader,lgeek/koreader,poire-z/koreader,mihailim/koreader,apletnev/koreader,robert00s/koreader,Hzj-jie/koreader
|
29e80b6cb7a07336f48992d2464e9d4c92ded22c
|
spec/log_spec.lua
|
spec/log_spec.lua
|
local log = require 'lua-lsp.log'
describe("log.fmt", function()
it("handles %_", function()
assert.equal("strong",
log.fmt("%_", "strong"))
assert.equal("nil",
log.fmt("%_", nil))
local t1, t2 = {}, {}
assert.equal(tostring(t1) .. " " .. tostring(t2),
log.fmt("%_ %_", t1, t2))
end)
it("handles %t", function()
assert.equal('{ "a", "b", "c" }',
log.fmt("%t", {"a", "b", "c"}))
assert.equal('{ 1,\n <metatable> = {}\n} { 2 }',
log.fmt("%t %t", setmetatable({1}, {}), {2}))
end)
it("handles numeric args", function()
assert.equal("12 nil",
log.fmt("%2$d %1$_", nil, 12))
local t = {"okay"}
assert.equal('{ "okay" } '..tostring(t),
log.fmt("%1$t %1$_", t))
end)
it("handles functions", function()
assert.equal("12 nil",
log.fmt(function()
return "%2$d %1$_", nil, 12
end))
end)
end)
describe("log levels", function()
it("can disable logging", function()
log.setTraceLevel("off")
log.file = {write = function() end}
io.write = log.file.write
stub(log.file, "write")
log("a")
log.debug("b")
log.info("c")
log.warning("d")
log.error("e")
assert.stub(log.file.write).was_not.called()
end)
it("can only print important messages", function()
log.setTraceLevel("messages")
log.file = {write = function() end}
io.write = log.file.write
stub(log.file, "write")
log("a")
assert.stub(log.file.write).was_not.called()
log.debug("b")
assert.stub(log.file.write).was_not.called()
log.info("c")
assert.stub(log.file.write).was.called()
log.file.write:clear()
log.warning("d")
assert.stub(log.file.write).was.called()
log.file.write:clear()
log.error("e")
assert.stub(log.file.write).was.called()
log.file.write:clear()
end)
it("can print all messages", function()
log.setTraceLevel("verbose")
log.file = {write = function() end}
io.write = log.file.write
stub(log.file, "write")
log("a")
log.debug("b")
log.info("c")
log.warning("d")
log.error("e")
assert.stub(log.file.write).was.called(5)
end)
end)
|
-- luacheck: ignore 122
local log = require 'lua-lsp.log'
describe("log.fmt", function()
it("handles %_", function()
assert.equal("strong",
log.fmt("%_", "strong"))
assert.equal("nil",
log.fmt("%_", nil))
local t1, t2 = {}, {}
assert.equal(tostring(t1) .. " " .. tostring(t2),
log.fmt("%_ %_", t1, t2))
end)
it("handles %t", function()
assert.equal('{ "a", "b", "c" }',
log.fmt("%t", {"a", "b", "c"}))
assert.equal('{ 1,\n <metatable> = {}\n} { 2 }',
log.fmt("%t %t", setmetatable({1}, {}), {2}))
end)
it("handles numeric args", function()
assert.equal("12 nil",
log.fmt("%2$d %1$_", nil, 12))
local t = {"okay"}
assert.equal('{ "okay" } '..tostring(t),
log.fmt("%1$t %1$_", t))
end)
it("handles functions #atm", function()
assert.equal("12 nil",
log.fmt(function()
return "%2$d %1$_", nil, 12
end))
end)
end)
describe("log levels", function()
it("can disable logging", function()
log.setTraceLevel("off")
log.file = {write = function() end}
-- luacheck: ignore 122
io.write = log.file.write
stub(log.file, "write")
log("a")
log.debug("b")
log.info("c")
log.warning("d")
log.error("e")
assert.stub(log.file.write).was_not.called()
end)
it("can only print important messages", function()
log.setTraceLevel("messages")
log.file = {write = function() end}
io.write = log.file.write
stub(log.file, "write")
log("a")
assert.stub(log.file.write).was_not.called()
log.debug("b")
assert.stub(log.file.write).was_not.called()
log.info("c")
assert.stub(log.file.write).was.called()
log.file.write:clear()
log.warning("d")
assert.stub(log.file.write).was.called()
log.file.write:clear()
log.error("e")
assert.stub(log.file.write).was.called()
log.file.write:clear()
end)
it("can print all messages", function()
log.setTraceLevel("verbose")
log.file = {write = function() end}
io.write = log.file.write
stub(log.file, "write")
log("a")
log.debug("b")
log.info("c")
log.warning("d")
log.error("e")
assert.stub(log.file.write).was.called(5)
end)
end)
|
Fix luacheck warnings
|
Fix luacheck warnings
|
Lua
|
mit
|
Alloyed/lua-lsp
|
b5861464c0e1afb0fbee62c308a7b21ab6d662df
|
lua/entities/gmod_wire_forcer.lua
|
lua/entities/gmod_wire_forcer.lua
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Forcer"
ENT.RenderGroup = RENDERGROUP_BOTH
ENT.WireDebugName = "Forcer"
function ENT:SetupDataTables()
self:NetworkVar( "Float", 0, "BeamLength" )
self:NetworkVar( "Bool", 0, "ShowBeam" )
self:NetworkVar( "Bool", 1, "BeamHighlight" )
end
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Force = 0
self.OffsetForce = 0
self.Velocity = 0
self.Inputs = WireLib.CreateInputs( self, { "Force", "OffsetForce", "Velocity", "Length" } )
self:Setup(0, 100, true, false)
end
function ENT:Setup( Force, Length, ShowBeam, Reaction )
self.ForceMul = Force or 1
self.Reaction = Reaction or false
if Length then self:SetBeamLength(Length) end
if ShowBeam ~= nil then self:SetShowBeam(ShowBeam) end
self:ShowOutput()
end
function ENT:TriggerInput( name, value )
if (name == "Force") then
self.Force = value
self:SetBeamHighlight(value != 0)
self:ShowOutput()
elseif (name == "OffsetForce") then
self.OffsetForce = value
self:SetBeamHighlight(value != 0)
self:ShowOutput()
elseif (name == "Velocity") then
self.Velocity = math.Clamp(value,-100000,100000)
self:SetBeamHighlight(value != 0)
self:ShowOutput()
elseif (name == "Length") then
self:SetBeamLength(math.Round(value))
self:ShowOutput()
end
end
local check = WireLib.checkForce
function ENT:Think()
if self.Force == 0 and self.OffsetForce == 0 and self.Velocity == 0 then return end
local Forward = self:GetUp()
local BeamOrigin = self:GetPos() + Forward * self:OBBMaxs().z
local trace = util.TraceLine {
start = BeamOrigin,
endpos = BeamOrigin + self:GetBeamLength() * Forward,
filter = self
}
if not IsValid(trace.Entity) then return end
if not gamemode.Call( "GravGunPunt", self:GetPlayer(), trace.Entity ) then return end
if trace.Entity:GetMoveType() == MOVETYPE_VPHYSICS then
local phys = trace.Entity:GetPhysicsObject()
if not IsValid(phys) then return end
if self.Force ~= 0 and check(Forward * self.Force * self.ForceMul) then phys:ApplyForceCenter( Forward * self.Force * self.ForceMul ) end
if self.OffsetForce ~= 0 and check(Forward * self.OffsetForce * self.ForceMul) then phys:ApplyForceOffset( Forward * self.OffsetForce * self.ForceMul, trace.HitPos ) end
if self.Velocity ~= 0 then phys:SetVelocityInstantaneous( Forward * self.Velocity ) end
else
if self.Velocity ~= 0 then trace.Entity:SetVelocity( Forward * self.Velocity ) end
end
if self.Reaction and IsValid(self:GetPhysicsObject()) and (self.Force + self.OffsetForce ~= 0) and check(Forward * -(self.Force + self.OffsetForce) * self.ForceMul) then
self:GetPhysicsObject():ApplyForceCenter( Forward * -(self.Force + self.OffsetForce) * self.ForceMul )
end
self:NextThink( CurTime() )
return true
end
function ENT:ShowOutput()
self:SetOverlayText(
"Center Force = "..math.Round(self.ForceMul * self.Force)..
"\nOffset Force = "..math.Round(self.ForceMul * self.OffsetForce)..
"\nVelocity = "..math.Round(self.Velocity)..
"\nLength = " .. math.Round(self:GetBeamLength())
)
end
function ENT:BuildDupeInfo()
local info = self.BaseClass.BuildDupeInfo(self) or {}
info.ForceMul = self.ForceMul
info.Reaction = self.Reaction
return info
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
self:Setup( info.ForceMul, info.Length, info.ShowBeam, info.Reaction )
self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
end
--Moves old "A" input to new "Force" input for older saves
WireLib.AddInputAlias( "A", "Force" )
duplicator.RegisterEntityClass("gmod_wire_forcer", WireLib.MakeWireEnt, "Data", "Force", "Length", "ShowBeam", "Reaction")
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Forcer"
ENT.RenderGroup = RENDERGROUP_BOTH
ENT.WireDebugName = "Forcer"
function ENT:SetupDataTables()
self:NetworkVar( "Float", 0, "BeamLength" )
self:NetworkVar( "Bool", 0, "ShowBeam" )
self:NetworkVar( "Bool", 1, "BeamHighlight" )
end
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Force = 0
self.OffsetForce = 0
self.Velocity = 0
self.Inputs = WireLib.CreateInputs( self, { "Force", "OffsetForce", "Velocity", "Length" } )
self:Setup(0, 100, true, false)
end
function ENT:Setup( Force, Length, ShowBeam, Reaction )
self.ForceMul = Force or 1
self.Reaction = Reaction or false
if Length then self:SetBeamLength(Length) end
if ShowBeam ~= nil then self:SetShowBeam(ShowBeam) end
self:ShowOutput()
end
function ENT:TriggerInput( name, value )
if (name == "Force") then
self.Force = value
self:SetBeamHighlight(value != 0)
self:ShowOutput()
elseif (name == "OffsetForce") then
self.OffsetForce = value
self:SetBeamHighlight(value != 0)
self:ShowOutput()
elseif (name == "Velocity") then
self.Velocity = math.Clamp(value,-100000,100000)
self:SetBeamHighlight(value != 0)
self:ShowOutput()
elseif (name == "Length") then
self:SetBeamLength(math.Round(value))
self:ShowOutput()
end
end
local check = WireLib.checkForce
function ENT:Think()
if self.Force == 0 and self.OffsetForce == 0 and self.Velocity == 0 then return end
local Forward = self:GetUp()
local BeamOrigin = self:GetPos() + Forward * self:OBBMaxs().z
local trace = util.TraceLine {
start = BeamOrigin,
endpos = BeamOrigin + self:GetBeamLength() * Forward,
filter = self
}
if not IsValid(trace.Entity) then return end
if IsValid(self:GetPlayer()) and not gamemode.Call( "GravGunPunt", self:GetPlayer(), trace.Entity ) then return end
if trace.Entity:GetMoveType() == MOVETYPE_VPHYSICS then
local phys = trace.Entity:GetPhysicsObject()
if not IsValid(phys) then return end
if self.Force ~= 0 and check(Forward * self.Force * self.ForceMul) then phys:ApplyForceCenter( Forward * self.Force * self.ForceMul ) end
if self.OffsetForce ~= 0 and check(Forward * self.OffsetForce * self.ForceMul) then phys:ApplyForceOffset( Forward * self.OffsetForce * self.ForceMul, trace.HitPos ) end
if self.Velocity ~= 0 then phys:SetVelocityInstantaneous( Forward * self.Velocity ) end
else
if self.Velocity ~= 0 then trace.Entity:SetVelocity( Forward * self.Velocity ) end
end
if self.Reaction and IsValid(self:GetPhysicsObject()) and (self.Force + self.OffsetForce ~= 0) and check(Forward * -(self.Force + self.OffsetForce) * self.ForceMul) then
self:GetPhysicsObject():ApplyForceCenter( Forward * -(self.Force + self.OffsetForce) * self.ForceMul )
end
self:NextThink( CurTime() )
return true
end
function ENT:ShowOutput()
self:SetOverlayText(
"Center Force = "..math.Round(self.ForceMul * self.Force)..
"\nOffset Force = "..math.Round(self.ForceMul * self.OffsetForce)..
"\nVelocity = "..math.Round(self.Velocity)..
"\nLength = " .. math.Round(self:GetBeamLength())
)
end
function ENT:BuildDupeInfo()
local info = self.BaseClass.BuildDupeInfo(self) or {}
info.ForceMul = self.ForceMul
info.Reaction = self.Reaction
return info
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
self:Setup( info.ForceMul, info.Length, info.ShowBeam, info.Reaction )
self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
end
--Moves old "A" input to new "Force" input for older saves
WireLib.AddInputAlias( "A", "Force" )
duplicator.RegisterEntityClass("gmod_wire_forcer", WireLib.MakeWireEnt, "Data", "Force", "Length", "ShowBeam", "Reaction")
|
Fix GravGunPunt hook calling without a player (#1298)
|
Fix GravGunPunt hook calling without a player (#1298)
Fix invalid hook call
|
Lua
|
apache-2.0
|
NezzKryptic/Wire,wiremod/wire,garrysmodlua/wire,sammyt291/wire,Grocel/wire,bigdogmat/wire,dvdvideo1234/wire,thegrb93/wire
|
555315b38814983dfaa32da41dbeec3c27b04d0b
|
mod_host_guard/mod_host_guard.lua
|
mod_host_guard/mod_host_guard.lua
|
-- (C) 2011, Marco Cirillo (LW.Org)
-- Block or restrict by blacklist remote access to local components or hosts.
module:set_global()
local guard_blockall = module:get_option_set("host_guard_blockall", {})
local guard_ball_wl = module:get_option_set("host_guard_blockall_exceptions", {})
local guard_protect = module:get_option_set("host_guard_selective", {})
local guard_block_bl = module:get_option_set("host_guard_blacklist", {})
local s2smanager = require "core.s2smanager"
local config = require "core.configmanager"
local nameprep = require "util.encodings".stringprep.nameprep
local _make_connect = s2smanager.make_connect
function s2smanager.make_connect(session, connect_host, connect_port)
if not session.s2sValidation then
if guard_blockall:contains(session.from_host) and not guard_ball_wl:contains(session.to_host) or
guard_block_bl:contains(session.to_host) and guard_protect:contains(session.from_host) then
module:log("error", "remote service %s attempted to access restricted host %s", session.to_host, session.from_host)
s2smanager.destroy_session(session, "You're not authorized, good bye.")
return false;
end
end
return _make_connect(session, connect_host, connect_port)
end
local _stream_opened = s2smanager.streamopened
function s2smanager.streamopened(session, attr)
local host = attr.to and nameprep(attr.to)
local from = attr.from and nameprep(attr.from)
if not from then
session.s2sValidation = false
else
session.s2sValidation = true
end
if guard_blockall:contains(host) and not guard_ball_wl:contains(from) or
guard_block_bl:contains(from) and guard_protect:contains(host) then
module:log("error", "remote service %s attempted to access restricted host %s", from, host)
session:close({condition = "policy-violation", text = "You're not authorized, good bye."})
return false;
end
_stream_opened(session, attr)
end
local function sdr_hook (event)
local origin, stanza = event.origin, event.stanza
if origin.type == "s2sin" or origin.type == "s2sin_unauthed" then
if guard_blockall:contains(stanza.attr.to) and not guard_ball_wl:contains(stanza.attr.from) or
guard_block_bl:contains(stanza.attr.from) and guard_protect:contains(stanza.attr.to) then
module:log("error", "remote service %s attempted to access restricted host %s", stanza.attr.from, stanza.attr.to)
origin:close({condition = "policy-violation", text = "You're not authorized, good bye."})
return false
end
end
return nil
end
local function handle_activation (host)
if guard_blockall:contains(host) or guard_protect:contains(host) then
if hosts[host] and hosts[host].events then
hosts[host].events.add_handler("stanza/jabber:server:dialback:result", sdr_hook, 100)
module:log ("debug", "adding host protection for: "..host)
end
end
end
local function handle_deactivation (host)
if guard_blockall:contains(host) or guard_protect:contains(host) then
if hosts[host] and hosts[host].events then
hosts[host].events.remove_handler("stanza/jabber:server:dialback:result", sdr_hook)
module:log ("debug", "removing host protection for: "..host)
end
end
end
local function reload()
module:log ("debug", "server configuration reloaded, rehashing plugin tables...")
guard_blockall = module:get_option_set("host_guard_blockall", {})
guard_ball_wl = module:get_option_set("host_guard_blockall_exceptions", {})
guard_protect = module:get_option_set("host_guard_components", {})
guard_block_bl = module:get_option_set("host_guard_blacklist", {})
end
local function setup()
module:log ("debug", "initializing host guard module...")
module:hook ("component-activated", handle_activation)
module:hook ("component-deactivated", handle_deactivation)
module:hook ("config-reloaded", reload)
for n,table in pairs(hosts) do
if table.type == "component" then
if guard_blockall:contains(n) or guard_protect:contains(n) then
hosts[n].events.remove_handler("stanza/jabber:server:dialback:result", sdr_hook)
handle_activation(n)
end
end
end
end
if prosody.start_time then
setup()
else
module:hook ("server-started", setup)
end
|
-- (C) 2011, Marco Cirillo (LW.Org)
-- Block or restrict by blacklist remote access to local components or hosts.
module:set_global()
local guard_blockall = module:get_option_set("host_guard_blockall", {})
local guard_ball_wl = module:get_option_set("host_guard_blockall_exceptions", {})
local guard_protect = module:get_option_set("host_guard_selective", {})
local guard_block_bl = module:get_option_set("host_guard_blacklist", {})
local s2smanager = require "core.s2smanager"
local config = require "core.configmanager"
local nameprep = require "util.encodings".stringprep.nameprep
local _make_connect = s2smanager.make_connect
function s2smanager.make_connect(session, connect_host, connect_port)
if not session.s2sValidation then
if guard_blockall:contains(session.from_host) and not guard_ball_wl:contains(session.to_host) or
guard_block_bl:contains(session.to_host) and guard_protect:contains(session.from_host) then
module:log("error", "remote service %s attempted to access restricted host %s", session.to_host, session.from_host)
s2smanager.destroy_session(session, "You're not authorized, good bye.")
return false;
end
end
return _make_connect(session, connect_host, connect_port)
end
local _stream_opened = s2smanager.streamopened
function s2smanager.streamopened(session, attr)
local host = attr.to and nameprep(attr.to)
local from = attr.from and nameprep(attr.from)
if not from then
session.s2sValidation = false
else
session.s2sValidation = true
end
if guard_blockall:contains(host) and not guard_ball_wl:contains(from) or
guard_block_bl:contains(from) and guard_protect:contains(host) then
module:log("error", "remote service %s attempted to access restricted host %s", from, host)
session:close({condition = "policy-violation", text = "You're not authorized, good bye."})
return false;
end
_stream_opened(session, attr)
end
local function sdr_hook (event)
local origin, stanza = event.origin, event.stanza
if origin.type == "s2sin" or origin.type == "s2sin_unauthed" then
if guard_blockall:contains(stanza.attr.to) and not guard_ball_wl:contains(stanza.attr.from) or
guard_block_bl:contains(stanza.attr.from) and guard_protect:contains(stanza.attr.to) then
module:log("error", "remote service %s attempted to access restricted host %s", stanza.attr.from, stanza.attr.to)
origin:close({condition = "policy-violation", text = "You're not authorized, good bye."})
return false
end
end
return nil
end
local function handle_activation (host)
if guard_blockall:contains(host) or guard_protect:contains(host) then
if hosts[host] and hosts[host].events then
hosts[host].events.add_handler("stanza/jabber:server:dialback:result", sdr_hook, 100)
module:log ("debug", "adding host protection for: "..host)
end
end
end
local function handle_deactivation (host)
if guard_blockall:contains(host) or guard_protect:contains(host) then
if hosts[host] and hosts[host].events then
hosts[host].events.remove_handler("stanza/jabber:server:dialback:result", sdr_hook)
module:log ("debug", "removing host protection for: "..host)
end
end
end
local function init_hosts()
for n,table in pairs(hosts) do
hosts[n].events.remove_handler("stanza/jabber:server:dialback:result", sdr_hook)
if guard_blockall:contains(n) or guard_protect:contains(n) then handle_activation(n) end
end
end
local function reload()
module:log ("debug", "server configuration reloaded, rehashing plugin tables...")
guard_blockall = module:get_option_set("host_guard_blockall", {})
guard_ball_wl = module:get_option_set("host_guard_blockall_exceptions", {})
guard_protect = module:get_option_set("host_guard_selective", {})
guard_block_bl = module:get_option_set("host_guard_blacklist", {})
init_hosts()
end
local function setup()
module:log ("debug", "initializing host guard module...")
module:hook ("host-activated", handle_activation)
module:hook ("host-deactivated", handle_deactivation)
module:hook ("config-reloaded", reload)
init_hosts()
end
if prosody.start_time then
setup()
else
module:hook ("server-started", setup)
end
|
mod_host_guard: fixed plugin, minor code refactor.
|
mod_host_guard: fixed plugin, minor code refactor.
|
Lua
|
mit
|
heysion/prosody-modules,syntafin/prosody-modules,cryptotoad/prosody-modules,apung/prosody-modules,either1/prosody-modules,mardraze/prosody-modules,vfedoroff/prosody-modules,BurmistrovJ/prosody-modules,jkprg/prosody-modules,mmusial/prosody-modules,cryptotoad/prosody-modules,apung/prosody-modules,NSAKEY/prosody-modules,brahmi2/prosody-modules,BurmistrovJ/prosody-modules,jkprg/prosody-modules,drdownload/prosody-modules,joewalker/prosody-modules,heysion/prosody-modules,NSAKEY/prosody-modules,mmusial/prosody-modules,mmusial/prosody-modules,guilhem/prosody-modules,crunchuser/prosody-modules,guilhem/prosody-modules,stephen322/prosody-modules,NSAKEY/prosody-modules,crunchuser/prosody-modules,iamliqiang/prosody-modules,iamliqiang/prosody-modules,obelisk21/prosody-modules,syntafin/prosody-modules,1st8/prosody-modules,joewalker/prosody-modules,crunchuser/prosody-modules,vince06fr/prosody-modules,prosody-modules/import,softer/prosody-modules,vfedoroff/prosody-modules,1st8/prosody-modules,dhotson/prosody-modules,Craige/prosody-modules,olax/prosody-modules,olax/prosody-modules,either1/prosody-modules,asdofindia/prosody-modules,drdownload/prosody-modules,BurmistrovJ/prosody-modules,obelisk21/prosody-modules,vince06fr/prosody-modules,cryptotoad/prosody-modules,softer/prosody-modules,mardraze/prosody-modules,1st8/prosody-modules,amenophis1er/prosody-modules,mmusial/prosody-modules,stephen322/prosody-modules,NSAKEY/prosody-modules,asdofindia/prosody-modules,heysion/prosody-modules,jkprg/prosody-modules,guilhem/prosody-modules,amenophis1er/prosody-modules,stephen322/prosody-modules,dhotson/prosody-modules,iamliqiang/prosody-modules,joewalker/prosody-modules,LanceJenkinZA/prosody-modules,iamliqiang/prosody-modules,prosody-modules/import,olax/prosody-modules,Craige/prosody-modules,drdownload/prosody-modules,obelisk21/prosody-modules,jkprg/prosody-modules,Craige/prosody-modules,BurmistrovJ/prosody-modules,syntafin/prosody-modules,brahmi2/prosody-modules,obelisk21/prosody-modules,asdofindia/prosody-modules,Craige/prosody-modules,apung/prosody-modules,LanceJenkinZA/prosody-modules,guilhem/prosody-modules,vince06fr/prosody-modules,softer/prosody-modules,amenophis1er/prosody-modules,vince06fr/prosody-modules,cryptotoad/prosody-modules,mmusial/prosody-modules,joewalker/prosody-modules,drdownload/prosody-modules,apung/prosody-modules,asdofindia/prosody-modules,LanceJenkinZA/prosody-modules,BurmistrovJ/prosody-modules,1st8/prosody-modules,amenophis1er/prosody-modules,mardraze/prosody-modules,prosody-modules/import,olax/prosody-modules,brahmi2/prosody-modules,vfedoroff/prosody-modules,dhotson/prosody-modules,prosody-modules/import,softer/prosody-modules,cryptotoad/prosody-modules,softer/prosody-modules,either1/prosody-modules,jkprg/prosody-modules,syntafin/prosody-modules,stephen322/prosody-modules,guilhem/prosody-modules,joewalker/prosody-modules,syntafin/prosody-modules,brahmi2/prosody-modules,crunchuser/prosody-modules,either1/prosody-modules,vince06fr/prosody-modules,dhotson/prosody-modules,mardraze/prosody-modules,1st8/prosody-modules,asdofindia/prosody-modules,mardraze/prosody-modules,brahmi2/prosody-modules,obelisk21/prosody-modules,Craige/prosody-modules,vfedoroff/prosody-modules,NSAKEY/prosody-modules,vfedoroff/prosody-modules,crunchuser/prosody-modules,olax/prosody-modules,either1/prosody-modules,amenophis1er/prosody-modules,drdownload/prosody-modules,prosody-modules/import,LanceJenkinZA/prosody-modules,iamliqiang/prosody-modules,LanceJenkinZA/prosody-modules,heysion/prosody-modules,stephen322/prosody-modules,apung/prosody-modules,heysion/prosody-modules,dhotson/prosody-modules
|
dbf4fbb3e7f2c61b41fccea01c1263b1511b110b
|
game/scripts/vscripts/modules/custom_abilities/ability_shop.lua
|
game/scripts/vscripts/modules/custom_abilities/ability_shop.lua
|
function CustomAbilities:PostAbilityShopData()
CustomGameEventManager:RegisterListener("ability_shop_buy", function(_, data)
CustomAbilities:OnAbilityBuy(data.PlayerID, data.ability)
end)
CustomGameEventManager:RegisterListener("ability_shop_sell", Dynamic_Wrap(CustomAbilities, "OnAbilitySell"))
CustomGameEventManager:RegisterListener("ability_shop_downgrade", Dynamic_Wrap(CustomAbilities, "OnAbilityDowngrade"))
PlayerTables:CreateTable("ability_shop_data", CustomAbilities.ClientData, AllPlayersInterval)
end
function CustomAbilities:GetAbilityListInfo(abilityname)
return CustomAbilities.AbilityInfo[abilityname]
end
function CustomAbilities:OnAbilityBuy(PlayerID, abilityname)
local hero = PlayerResource:GetSelectedHeroEntity(PlayerID)
local abilityInfo = CustomAbilities:GetAbilityListInfo(abilityname)
if not abilityInfo then
return
end
local cost = abilityInfo.cost
local banned_with = abilityInfo.banned_with
for _,v in ipairs(banned_with) do
if hero:HasAbility(v) then
return
end
end
if hero and cost and hero:GetAbilityPoints() >= cost then
local function Buy()
if IsValidEntity(hero) and hero:GetAbilityPoints() >= cost then
local abilityh = hero:FindAbilityByName(abilityname)
if abilityh and not abilityh:IsHidden() then
if abilityh:GetLevel() < abilityh:GetMaxLevel() then
hero:SetAbilityPoints(hero:GetAbilityPoints() - cost)
abilityh:SetLevel(abilityh:GetLevel() + 1)
end
elseif hero:HasAbility("ability_empty") then
if abilityh and abilityh:IsHidden() then
RemoveAbilityWithModifiers(hero, abilityh)
end
hero:SetAbilityPoints(hero:GetAbilityPoints() - cost)
hero:RemoveAbility("ability_empty")
GameMode:PrecacheUnitQueueed(abilityInfo.hero)
local a, linked = hero:AddNewAbility(abilityname)
a:SetLevel(1)
if linked then
for _,v in ipairs(linked) do
if v:GetAbilityName() == "phoenix_launch_fire_spirit" then
v:SetLevel(1)
end
end
end
hero:CalculateStatBonus()
CustomGameEventManager:Send_ServerToPlayer(PlayerResource:GetPlayer(PlayerID), "dota_ability_changed", {})
end
end
end
if hero:HasAbility(abilityname) then
Buy()
else
PrecacheItemByNameAsync(abilityname, Buy)
end
end
end
function CustomAbilities:OnAbilitySell(data)
local hero = PlayerResource:GetSelectedHeroEntity(data.PlayerID)
local listDataInfo = CustomAbilities:GetAbilityListInfo(data.ability)
if hero and hero:HasAbility(data.ability) and not hero:IsChanneling() and listDataInfo then
local cost = listDataInfo.cost
local abilityh = hero:FindAbilityByName(data.ability)
local gold = CustomAbilities:CalculateDowngradeCost(data.ability, cost) * abilityh:GetLevel()
if Gold:GetGold(data.PlayerID) >= gold and not abilityh:IsHidden() then
Gold:RemoveGold(data.PlayerID, gold)
hero:SetAbilityPoints(hero:GetAbilityPoints() + cost*abilityh:GetLevel())
RemoveAbilityWithModifiers(hero, abilityh)
local link = LINKED_ABILITIES[data.ability]
if link then
for _,v in ipairs(link) do
hero:RemoveAbility(v)
end
end
if data.ability == "puck_illusory_orb" then
local etherealJaunt = hero:FindAbilityByName("puck_ethereal_jaunt")
if etherealJaunt then etherealJaunt:SetActivated(false) end
end
hero:AddAbility("ability_empty")
end
end
CustomGameEventManager:Send_ServerToPlayer(PlayerResource:GetPlayer(data.PlayerID), "dota_ability_changed", {})
end
function CustomAbilities:OnAbilityDowngrade(data)
local hero = PlayerResource:GetSelectedHeroEntity(data.PlayerID)
local listDataInfo = CustomAbilities:GetAbilityListInfo(data.ability)
if hero and hero:HasAbility(data.ability) and listDataInfo then
local cost = listDataInfo.cost
local abilityh = hero:FindAbilityByName(data.ability)
if abilityh:GetLevel() <= 1 then
CustomAbilities:OnAbilitySell(data)
else
local gold = CustomAbilities:CalculateDowngradeCost(data.ability, cost)
if Gold:GetGold(data.PlayerID) >= gold and not abilityh:IsHidden() then
Gold:RemoveGold(data.PlayerID, gold)
abilityh:SetLevel(abilityh:GetLevel() - 1)
hero:SetAbilityPoints(hero:GetAbilityPoints() + cost)
end
end
end
CustomGameEventManager:Send_ServerToPlayer(PlayerResource:GetPlayer(data.PlayerID), "dota_ability_changed", {})
end
function CustomAbilities:CalculateDowngradeCost(abilityname, upgradecost)
return (upgradecost*60) + (upgradecost*10*GetDOTATimeInMinutesFull())
end
|
function CustomAbilities:PostAbilityShopData()
CustomGameEventManager:RegisterListener("ability_shop_buy", function(_, data)
CustomAbilities:OnAbilityBuy(data.PlayerID, data.ability)
end)
CustomGameEventManager:RegisterListener("ability_shop_sell", Dynamic_Wrap(CustomAbilities, "OnAbilitySell"))
CustomGameEventManager:RegisterListener("ability_shop_downgrade", Dynamic_Wrap(CustomAbilities, "OnAbilityDowngrade"))
PlayerTables:CreateTable("ability_shop_data", CustomAbilities.ClientData, AllPlayersInterval)
end
function CustomAbilities:GetAbilityListInfo(abilityname)
return CustomAbilities.AbilityInfo[abilityname]
end
function CustomAbilities:OnAbilityBuy(PlayerID, abilityname)
local hero = PlayerResource:GetSelectedHeroEntity(PlayerID)
if not hero then return end
local abilityInfo = CustomAbilities:GetAbilityListInfo(abilityname)
if not abilityInfo then return end
local function Buy()
local cost = abilityInfo.cost
if not IsValidEntity(hero) or hero:GetAbilityPoints() < cost then return end
for _,v in ipairs(abilityInfo.banned_with) do
if hero:HasAbility(v) then return end
end
local abilityh = hero:FindAbilityByName(abilityname)
if abilityh and not abilityh:IsHidden() then
if abilityh:GetLevel() < abilityh:GetMaxLevel() then
hero:SetAbilityPoints(hero:GetAbilityPoints() - cost)
abilityh:SetLevel(abilityh:GetLevel() + 1)
end
elseif hero:HasAbility("ability_empty") then
if abilityh and abilityh:IsHidden() then
RemoveAbilityWithModifiers(hero, abilityh)
end
hero:SetAbilityPoints(hero:GetAbilityPoints() - cost)
hero:RemoveAbility("ability_empty")
GameMode:PrecacheUnitQueueed(abilityInfo.hero)
local a, linked = hero:AddNewAbility(abilityname)
a:SetLevel(1)
if linked then
for _,v in ipairs(linked) do
if v:GetAbilityName() == "phoenix_launch_fire_spirit" then
v:SetLevel(1)
end
end
end
hero:CalculateStatBonus()
CustomGameEventManager:Send_ServerToPlayer(PlayerResource:GetPlayer(PlayerID), "dota_ability_changed", {})
end
end
if hero:HasAbility(abilityname) then
Buy()
else
PrecacheItemByNameAsync(abilityname, Buy)
end
end
function CustomAbilities:OnAbilitySell(data)
local hero = PlayerResource:GetSelectedHeroEntity(data.PlayerID)
local listDataInfo = CustomAbilities:GetAbilityListInfo(data.ability)
if hero and hero:HasAbility(data.ability) and not hero:IsChanneling() and listDataInfo then
local cost = listDataInfo.cost
local abilityh = hero:FindAbilityByName(data.ability)
local gold = CustomAbilities:CalculateDowngradeCost(data.ability, cost) * abilityh:GetLevel()
if Gold:GetGold(data.PlayerID) >= gold and not abilityh:IsHidden() then
Gold:RemoveGold(data.PlayerID, gold)
hero:SetAbilityPoints(hero:GetAbilityPoints() + cost*abilityh:GetLevel())
RemoveAbilityWithModifiers(hero, abilityh)
local link = LINKED_ABILITIES[data.ability]
if link then
for _,v in ipairs(link) do
hero:RemoveAbility(v)
end
end
if data.ability == "puck_illusory_orb" then
local etherealJaunt = hero:FindAbilityByName("puck_ethereal_jaunt")
if etherealJaunt then etherealJaunt:SetActivated(false) end
end
hero:AddAbility("ability_empty")
end
end
CustomGameEventManager:Send_ServerToPlayer(PlayerResource:GetPlayer(data.PlayerID), "dota_ability_changed", {})
end
function CustomAbilities:OnAbilityDowngrade(data)
local hero = PlayerResource:GetSelectedHeroEntity(data.PlayerID)
local listDataInfo = CustomAbilities:GetAbilityListInfo(data.ability)
if hero and hero:HasAbility(data.ability) and listDataInfo then
local cost = listDataInfo.cost
local abilityh = hero:FindAbilityByName(data.ability)
if abilityh:GetLevel() <= 1 then
CustomAbilities:OnAbilitySell(data)
else
local gold = CustomAbilities:CalculateDowngradeCost(data.ability, cost)
if Gold:GetGold(data.PlayerID) >= gold and not abilityh:IsHidden() then
Gold:RemoveGold(data.PlayerID, gold)
abilityh:SetLevel(abilityh:GetLevel() - 1)
hero:SetAbilityPoints(hero:GetAbilityPoints() + cost)
end
end
end
CustomGameEventManager:Send_ServerToPlayer(PlayerResource:GetPlayer(data.PlayerID), "dota_ability_changed", {})
end
function CustomAbilities:CalculateDowngradeCost(abilityname, upgradecost)
return (upgradecost*60) + (upgradecost*10*GetDOTATimeInMinutesFull())
end
|
fix(ability_shop): quick ability purchasing bypasses combination bans
|
fix(ability_shop): quick ability purchasing bypasses combination bans
Fixes #387.
|
Lua
|
mit
|
ark120202/aabs
|
feefc600ed052207a9cef1f331abf2eedea35a66
|
modules/luci-mod-rpc/luasrc/controller/rpc.lua
|
modules/luci-mod-rpc/luasrc/controller/rpc.lua
|
-- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local require = require
local pairs = pairs
local print = print
local pcall = pcall
local table = table
module "luci.controller.rpc"
function index()
local function authenticator(validator, accs)
local auth = luci.http.formvalue("auth", true)
if auth then -- if authentication token was given
local sdat = (luci.util.ubus("session", "get", { ubus_rpc_session = auth }) or { }).values
if sdat then -- if given token is valid
if sdat.user and luci.util.contains(accs, sdat.user) then
return sdat.user, auth
end
end
end
luci.http.status(403, "Forbidden")
end
local rpc = node("rpc")
rpc.sysauth = "root"
rpc.sysauth_authenticator = authenticator
rpc.notemplate = true
entry({"rpc", "uci"}, call("rpc_uci"))
entry({"rpc", "fs"}, call("rpc_fs"))
entry({"rpc", "sys"}, call("rpc_sys"))
entry({"rpc", "ipkg"}, call("rpc_ipkg"))
entry({"rpc", "auth"}, call("rpc_auth")).sysauth = false
end
function rpc_auth()
local jsonrpc = require "luci.jsonrpc"
local http = require "luci.http"
local sys = require "luci.sys"
local ltn12 = require "luci.ltn12"
local util = require "luci.util"
local loginstat
local server = {}
server.challenge = function(user, pass)
local sid, token, secret
local config = require "luci.config"
if sys.user.checkpasswd(user, pass) then
local sdat = util.ubus("session", "create", { timeout = config.sauth.sessiontime })
if sdat then
sid = sdat.ubus_rpc_session
token = sys.uniqueid(16)
secret = sys.uniqueid(16)
http.header("Set-Cookie", "sysauth="..sid.."; path=/")
util.ubus("session", "set", {
ubus_rpc_session = sid,
values = {
user = user,
token = token,
secret = secret
}
})
end
end
return sid and {sid=sid, token=token, secret=secret}
end
server.login = function(...)
local challenge = server.challenge(...)
return challenge and challenge.sid
end
http.prepare_content("application/json")
ltn12.pump.all(jsonrpc.handle(server, http.source()), http.write)
end
function rpc_uci()
if not pcall(require, "luci.model.uci") then
luci.http.status(404, "Not Found")
return nil
end
local uci = require "luci.jsonrpcbind.uci"
local jsonrpc = require "luci.jsonrpc"
local http = require "luci.http"
local ltn12 = require "luci.ltn12"
http.prepare_content("application/json")
ltn12.pump.all(jsonrpc.handle(uci, http.source()), http.write)
end
function rpc_fs()
local util = require "luci.util"
local io = require "io"
local fs2 = util.clone(require "nixio.fs")
local jsonrpc = require "luci.jsonrpc"
local http = require "luci.http"
local ltn12 = require "luci.ltn12"
function fs2.readfile(filename)
local stat, mime = pcall(require, "mime")
if not stat then
error("Base64 support not available. Please install LuaSocket.")
end
local fp = io.open(filename)
if not fp then
return nil
end
local output = {}
local sink = ltn12.sink.table(output)
local source = ltn12.source.chain(ltn12.source.file(fp), mime.encode("base64"))
return ltn12.pump.all(source, sink) and table.concat(output)
end
function fs2.writefile(filename, data)
local stat, mime = pcall(require, "mime")
if not stat then
error("Base64 support not available. Please install LuaSocket.")
end
local file = io.open(filename, "w")
local sink = file and ltn12.sink.chain(mime.decode("base64"), ltn12.sink.file(file))
return sink and ltn12.pump.all(ltn12.source.string(data), sink) or false
end
http.prepare_content("application/json")
ltn12.pump.all(jsonrpc.handle(fs2, http.source()), http.write)
end
function rpc_sys()
local sys = require "luci.sys"
local jsonrpc = require "luci.jsonrpc"
local http = require "luci.http"
local ltn12 = require "luci.ltn12"
http.prepare_content("application/json")
ltn12.pump.all(jsonrpc.handle(sys, http.source()), http.write)
end
function rpc_ipkg()
if not pcall(require, "luci.model.ipkg") then
luci.http.status(404, "Not Found")
return nil
end
local ipkg = require "luci.model.ipkg"
local jsonrpc = require "luci.jsonrpc"
local http = require "luci.http"
local ltn12 = require "luci.ltn12"
http.prepare_content("application/json")
ltn12.pump.all(jsonrpc.handle(ipkg, http.source()), http.write)
end
|
-- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local require = require
local pairs = pairs
local print = print
local pcall = pcall
local table = table
local type = type
local tonumber = tonumber
module "luci.controller.rpc"
local function session_retrieve(sid, allowed_users)
local util = require "luci.util"
local sdat = util.ubus("session", "get", {
ubus_rpc_session = sid
})
if type(sdat) == "table" and
type(sdat.values) == "table" and
type(sdat.values.token) == "string" and
type(sdat.values.secret) == "string" and
type(sdat.values.username) == "string" and
util.contains(allowed_users, sdat.values.username)
then
return sid, sdat.values
end
return nil
end
local function authenticator(validator, accs)
local auth = luci.http.formvalue("auth", true)
or luci.http.getcookie("sysauth")
if auth then -- if authentication token was given
local sid, sdat = session_retrieve(auth, accs)
if sdat then -- if given token is valid
return sdat.username, sid
end
luci.http.status(403, "Forbidden")
end
end
function index()
local rpc = node("rpc")
rpc.sysauth = "root"
rpc.sysauth_authenticator = authenticator
rpc.notemplate = true
entry({"rpc", "uci"}, call("rpc_uci"))
entry({"rpc", "fs"}, call("rpc_fs"))
entry({"rpc", "sys"}, call("rpc_sys"))
entry({"rpc", "ipkg"}, call("rpc_ipkg"))
entry({"rpc", "auth"}, call("rpc_auth")).sysauth = false
end
function rpc_auth()
local jsonrpc = require "luci.jsonrpc"
local http = require "luci.http"
local sys = require "luci.sys"
local ltn12 = require "luci.ltn12"
local util = require "luci.util"
local server = {}
server.challenge = function(user, pass)
local config = require "luci.config"
local login = util.ubus("session", "login", {
username = user,
password = pass,
timeout = tonumber(config.sauth.sessiontime)
})
if type(login) == "table" and
type(login.ubus_rpc_session) == "string"
then
util.ubus("session", "set", {
ubus_rpc_session = login.ubus_rpc_session,
values = {
token = sys.uniqueid(16),
secret = sys.uniqueid(16)
}
})
local sid, sdat = session_retrieve(login.ubus_rpc_session, { user })
if sdat then
return {
sid = sid,
token = sdat.token,
secret = sdat.secret
}
end
end
return nil
end
server.login = function(...)
local challenge = server.challenge(...)
if challenge then
http.header("Set-Cookie", 'sysauth=%s; path=%s' %{
challenge.sid,
http.getenv("SCRIPT_NAME")
})
return challenge.sid
end
end
http.prepare_content("application/json")
ltn12.pump.all(jsonrpc.handle(server, http.source()), http.write)
end
function rpc_uci()
if not pcall(require, "luci.model.uci") then
luci.http.status(404, "Not Found")
return nil
end
local uci = require "luci.jsonrpcbind.uci"
local jsonrpc = require "luci.jsonrpc"
local http = require "luci.http"
local ltn12 = require "luci.ltn12"
http.prepare_content("application/json")
ltn12.pump.all(jsonrpc.handle(uci, http.source()), http.write)
end
function rpc_fs()
local util = require "luci.util"
local io = require "io"
local fs2 = util.clone(require "nixio.fs")
local jsonrpc = require "luci.jsonrpc"
local http = require "luci.http"
local ltn12 = require "luci.ltn12"
function fs2.readfile(filename)
local stat, mime = pcall(require, "mime")
if not stat then
error("Base64 support not available. Please install LuaSocket.")
end
local fp = io.open(filename)
if not fp then
return nil
end
local output = {}
local sink = ltn12.sink.table(output)
local source = ltn12.source.chain(ltn12.source.file(fp), mime.encode("base64"))
return ltn12.pump.all(source, sink) and table.concat(output)
end
function fs2.writefile(filename, data)
local stat, mime = pcall(require, "mime")
if not stat then
error("Base64 support not available. Please install LuaSocket.")
end
local file = io.open(filename, "w")
local sink = file and ltn12.sink.chain(mime.decode("base64"), ltn12.sink.file(file))
return sink and ltn12.pump.all(ltn12.source.string(data), sink) or false
end
http.prepare_content("application/json")
ltn12.pump.all(jsonrpc.handle(fs2, http.source()), http.write)
end
function rpc_sys()
local sys = require "luci.sys"
local jsonrpc = require "luci.jsonrpc"
local http = require "luci.http"
local ltn12 = require "luci.ltn12"
http.prepare_content("application/json")
ltn12.pump.all(jsonrpc.handle(sys, http.source()), http.write)
end
function rpc_ipkg()
if not pcall(require, "luci.model.ipkg") then
luci.http.status(404, "Not Found")
return nil
end
local ipkg = require "luci.model.ipkg"
local jsonrpc = require "luci.jsonrpc"
local http = require "luci.http"
local ltn12 = require "luci.ltn12"
http.prepare_content("application/json")
ltn12.pump.all(jsonrpc.handle(ipkg, http.source()), http.write)
end
|
luci-mod-rpc: rework authentication and session handling
|
luci-mod-rpc: rework authentication and session handling
- Use the ubus session.login procedure to authenticate credentials
- Fix testing of allowed usernames
- Support authentication via sysauth cookie
Fixes #1300, #1700, #1711
Signed-off-by: Jo-Philipp Wich <bd73d35759d75cc215150d1bbc94f1b1078bee01@mein.io>
|
Lua
|
apache-2.0
|
nmav/luci,kuoruan/luci,nmav/luci,chris5560/openwrt-luci,remakeelectric/luci,openwrt/luci,kuoruan/luci,tobiaswaldvogel/luci,artynet/luci,rogerpueyo/luci,kuoruan/luci,openwrt/luci,remakeelectric/luci,981213/luci-1,hnyman/luci,nmav/luci,kuoruan/luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,Noltari/luci,nmav/luci,remakeelectric/luci,artynet/luci,kuoruan/lede-luci,tobiaswaldvogel/luci,tobiaswaldvogel/luci,wongsyrone/luci-1,nmav/luci,artynet/luci,rogerpueyo/luci,kuoruan/lede-luci,artynet/luci,Noltari/luci,981213/luci-1,Noltari/luci,hnyman/luci,kuoruan/luci,remakeelectric/luci,wongsyrone/luci-1,wongsyrone/luci-1,rogerpueyo/luci,openwrt-es/openwrt-luci,kuoruan/lede-luci,kuoruan/lede-luci,rogerpueyo/luci,artynet/luci,Noltari/luci,981213/luci-1,hnyman/luci,lbthomsen/openwrt-luci,artynet/luci,Noltari/luci,chris5560/openwrt-luci,rogerpueyo/luci,remakeelectric/luci,hnyman/luci,kuoruan/lede-luci,lbthomsen/openwrt-luci,chris5560/openwrt-luci,nmav/luci,wongsyrone/luci-1,chris5560/openwrt-luci,openwrt/luci,Noltari/luci,artynet/luci,nmav/luci,nmav/luci,kuoruan/lede-luci,openwrt-es/openwrt-luci,openwrt-es/openwrt-luci,openwrt-es/openwrt-luci,artynet/luci,wongsyrone/luci-1,wongsyrone/luci-1,rogerpueyo/luci,openwrt-es/openwrt-luci,openwrt/luci,lbthomsen/openwrt-luci,wongsyrone/luci-1,tobiaswaldvogel/luci,lbthomsen/openwrt-luci,kuoruan/luci,hnyman/luci,tobiaswaldvogel/luci,tobiaswaldvogel/luci,openwrt-es/openwrt-luci,Noltari/luci,openwrt/luci,openwrt/luci,remakeelectric/luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,Noltari/luci,chris5560/openwrt-luci,981213/luci-1,981213/luci-1,chris5560/openwrt-luci,openwrt/luci,981213/luci-1,chris5560/openwrt-luci,rogerpueyo/luci,kuoruan/luci,hnyman/luci,hnyman/luci,kuoruan/lede-luci,remakeelectric/luci,nmav/luci,wongsyrone/luci-1,artynet/luci,openwrt/luci,remakeelectric/luci,kuoruan/luci,rogerpueyo/luci,Noltari/luci,hnyman/luci,981213/luci-1,kuoruan/lede-luci,openwrt-es/openwrt-luci,openwrt-es/openwrt-luci,chris5560/openwrt-luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci
|
0e71278f1616a55e4e0a3b719abbe978a4ad71af
|
src/lua-factory/sources/grl-metrolyrics.lua
|
src/lua-factory/sources/grl-metrolyrics.lua
|
--[[
* Copyright (C) 2014 Victor Toso.
*
* Contact: Victor Toso <me@victortoso.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; version 2.1 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
--]]
---------------------------
-- Source initialization --
---------------------------
source = {
id = "grl-metrolyrics",
name = "Metrolyrics",
description = "a source for lyrics",
supported_keys = { "lyrics" },
supported_media = { 'audio', 'video' },
resolve_keys = {
["type"] = "audio",
required = { "artist", "title" },
},
tags = { 'music', 'net:internet', 'net:plaintext' },
}
netopts = {
user_agent = "Grilo Source Metrolyrics/0.2.8",
}
------------------
-- Source utils --
------------------
METROLYRICS_INVALID_URL_CHARS = "[" .. "%(%)%[%]%$%&" .. "]"
METROLYRICS_DEFAULT_QUERY = "http://www.metrolyrics.com/%s-lyrics-%s.html"
---------------------------------
-- Handlers of Grilo functions --
---------------------------------
function grl_source_resolve()
local url, req
local artist, title
req = grl.get_media_keys()
if not req or not req.artist or not req.title
or #req.artist == 0 or #req.title == 0 then
grl.callback()
return
end
-- Prepare artist and title strings to the url
artist = req.artist:gsub(METROLYRICS_INVALID_URL_CHARS, "")
artist = artist:gsub("%s+", "-")
title = req.title:gsub(METROLYRICS_INVALID_URL_CHARS, "")
title = title:gsub("%s+", "-")
url = string.format(METROLYRICS_DEFAULT_QUERY, title, artist)
grl.fetch(url, "fetch_page_cb", netopts)
end
---------------
-- Utilities --
---------------
function fetch_page_cb(feed)
local media = nil
if feed and not feed:find("notfound") then
media = metrolyrics_get_lyrics(feed)
end
grl.callback(media, 0)
end
function metrolyrics_get_lyrics(feed)
local media = {}
local lyrics_body = '<div id="lyrics%-body%-text".->(.-)</div>'
local noise_array = {
{ noise = "</p>", sub = "\n\n" },
{ noise = "<p class='verse'><p class='verse'>", sub = "\n\n" },
{ noise = "<p class='verse'>", sub = "" },
{ noise = "<br/>", sub = "" },
{ noise = "<br>", sub = "" },
}
-- remove html noise
feed = feed:match(lyrics_body)
if not feed then
grl.warning ("This Lyrics do not match our parser! Please file a bug!")
return nil
end
for _, it in ipairs (noise_array) do
feed = feed:gsub(it.noise, it.sub)
end
-- strip the lyrics
feed = feed:gsub("^[%s%W]*(.-)[%s%W]*$", "%1")
-- switch table to string
media.lyrics = feed
return media
end
|
--[[
* Copyright (C) 2014 Victor Toso.
*
* Contact: Victor Toso <me@victortoso.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; version 2.1 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
--]]
---------------------------
-- Source initialization --
---------------------------
source = {
id = "grl-metrolyrics",
name = "Metrolyrics",
description = "a source for lyrics",
supported_keys = { "lyrics" },
supported_media = { 'audio', 'video' },
resolve_keys = {
["type"] = "audio",
required = { "artist", "title" },
},
tags = { 'music', 'net:internet', 'net:plaintext' },
}
netopts = {
user_agent = "Grilo Source Metrolyrics/0.2.8",
}
------------------
-- Source utils --
------------------
METROLYRICS_INVALID_URL_CHARS = "[" .. "%(%)%[%]%$%&" .. "]"
METROLYRICS_DEFAULT_QUERY = "http://www.metrolyrics.com/%s-lyrics-%s.html"
---------------------------------
-- Handlers of Grilo functions --
---------------------------------
function grl_source_resolve(media, options, callback)
local url
local artist, title
if not media or not media.artist or not media.title
or #media.artist == 0 or #media.title == 0 then
callback()
return
end
-- Prepare artist and title strings to the url
artist = media.artist:gsub(METROLYRICS_INVALID_URL_CHARS, "")
artist = artist:gsub("%s+", "-")
title = media.title:gsub(METROLYRICS_INVALID_URL_CHARS, "")
title = title:gsub("%s+", "-")
url = string.format(METROLYRICS_DEFAULT_QUERY, title, artist)
local userdata = {callback = callback, media = media}
grl.fetch(url, netopts, fetch_page_cb, userdata)
end
---------------
-- Utilities --
---------------
function fetch_page_cb(feed, userdata)
if feed and not feed:find("notfound") then
local lyrics = metrolyrics_get_lyrics(feed)
if not lyrics then
userdata.callback()
return
end
userdata.media.lyrics = lyrics
end
userdata.callback(userdata.media, 0)
end
function metrolyrics_get_lyrics(feed)
local lyrics_body = '<div id="lyrics%-body%-text".->(.-)</div>'
local noise_array = {
{ noise = "</p>", sub = "\n\n" },
{ noise = "<p class='verse'><p class='verse'>", sub = "\n\n" },
{ noise = "<p class='verse'>", sub = "" },
{ noise = "<br/>", sub = "" },
{ noise = "<br>", sub = "" },
}
-- remove html noise
feed = feed:match(lyrics_body)
if not feed then
grl.warning ("This Lyrics do not match our parser! Please file a bug!")
return nil
end
for _, it in ipairs (noise_array) do
feed = feed:gsub(it.noise, it.sub)
end
-- strip the lyrics
feed = feed:gsub("^[%s%W]*(.-)[%s%W]*$", "%1")
return feed
end
|
lua-factory: port grl-metrolyrics.lua to the new lua system
|
lua-factory: port grl-metrolyrics.lua to the new lua system
https://bugzilla.gnome.org/show_bug.cgi?id=753141
Acked-by: Victor Toso <b1c1d8736f20db3fb6c1c66bb1455ed43909f0d8@victortoso.com>
|
Lua
|
lgpl-2.1
|
MikePetullo/grilo-plugins,MikePetullo/grilo-plugins,jasuarez/grilo-plugins,GNOME/grilo-plugins,jasuarez/grilo-plugins,MikePetullo/grilo-plugins,grilofw/grilo-plugins,grilofw/grilo-plugins,GNOME/grilo-plugins
|
163b0fd06837ffca7be334bbafdaf15557f91368
|
lua/entities/gmod_wire_user.lua
|
lua/entities/gmod_wire_user.lua
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire User"
ENT.WireDebugName = "User"
function ENT:SetupDataTables()
self:NetworkVar( "Float", 0, "BeamLength" )
end
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Inputs = Wire_CreateInputs(self, { "Fire"})
self:Setup(2048)
end
function ENT:Setup(Range)
if Range then self:SetBeamLength(Range) end
end
function ENT:TriggerInput(iname, value)
if (iname == "Fire") then
if (value ~= 0) then
local vStart = self:GetPos()
local trace = util.TraceLine( {
start = vStart,
endpos = vStart + (self:GetUp() * self:GetBeamLength()),
filter = { self },
})
if not IsValid(trace.Entity) then return false end
local ply = self:GetPlayer()
if not IsValid(ply) then ply = self end
if trace.Entity.Use then
trace.Entity:Use(ply,ply,USE_ON,0)
else
trace.Entity:Fire("use","1",0)
end
end
end
end
duplicator.RegisterEntityClass("gmod_wire_user", WireLib.MakeWireEnt, "Data", "Range")
|
AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire User"
ENT.RenderGroup = RENDERGROUP_BOTH
ENT.WireDebugName = "User"
function ENT:SetupDataTables()
self:NetworkVar( "Float", 0, "BeamLength" )
end
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Inputs = Wire_CreateInputs(self, { "Fire"})
self:Setup(2048)
end
function ENT:Setup(Range)
if Range then self:SetBeamLength(Range) end
end
function ENT:TriggerInput(iname, value)
if (iname == "Fire") then
if (value ~= 0) then
local vStart = self:GetPos()
local trace = util.TraceLine( {
start = vStart,
endpos = vStart + (self:GetUp() * self:GetBeamLength()),
filter = { self },
})
if not IsValid(trace.Entity) then return false end
local ply = self:GetPlayer()
if not IsValid(ply) then ply = self end
if trace.Entity.Use then
trace.Entity:Use(ply,ply,USE_ON,0)
else
trace.Entity:Fire("use","1",0)
end
end
end
end
duplicator.RegisterEntityClass("gmod_wire_user", WireLib.MakeWireEnt, "Data", "Range")
|
Fixed User entity beam appearing behind props.
|
Fixed User entity beam appearing behind props.
Fixed User entity beam appearing behind props by adding in missing
RenderGroup.
|
Lua
|
apache-2.0
|
CaptainPRICE/wire,Python1320/wire,bigdogmat/wire,wiremod/wire,notcake/wire,plinkopenguin/wiremod,Grocel/wire,dvdvideo1234/wire,mitterdoo/wire,garrysmodlua/wire,rafradek/wire,NezzKryptic/Wire,sammyt291/wire,immibis/wiremod,mms92/wire,thegrb93/wire
|
380d62363b04be3a52cf61b4fe8b2b76a538c59f
|
spec/proxy_spec.lua
|
spec/proxy_spec.lua
|
local configuration_store = require 'configuration_store'
describe('Proxy', function()
local configuration, proxy
before_each(function()
configuration = configuration_store.new()
proxy = require('proxy').new(configuration)
end)
it('has access function', function()
assert.truthy(proxy.access)
assert.same('function', type(proxy.access))
end)
describe(':call', function()
before_each(function()
ngx.var = { backend_endpoint = 'http://localhost:1853' }
configuration:add({ id = 42, hosts = { 'localhost' }})
end)
it('has authorize function after call', function()
proxy:call('localhost')
assert.truthy(proxy.authorize)
assert.same('function', type(proxy.authorize))
end)
it('returns access function', function()
local access = proxy:call('localhost')
assert.same('function', type(access))
end)
it('returns oauth handler when matches oauth route', function()
local service = configuration:find_by_id(42)
service.backend_version = 'oauth'
stub(ngx.req, 'get_method', function() return 'GET' end)
ngx.var.uri = '/authorize'
local access, handler = proxy:call('localhost')
assert.equal(nil, access)
assert.same('function', type(handler))
end)
end)
it('has post_action function', function()
assert.truthy(proxy.post_action)
assert.same('function', type(proxy.post_action))
end)
it('finds service by host', function()
local example = { id = 42, hosts = { 'example.com'} }
configuration:add(example)
assert.same(example, proxy:find_service('example.com'))
assert.falsy(proxy:find_service('unknown'))
end)
it('does not return old configuration when new one is available', function()
local foo = { id = '42', hosts = { 'foo.example.com'} }
local bar = { id = '42', hosts = { 'bar.example.com'} }
configuration:add(foo, -1) -- expired record
assert.equal(foo, proxy:find_service('foo.example.com'))
configuration:add(bar, -1) -- expired record
assert.equal(bar, proxy:find_service('bar.example.com'))
assert.falsy(proxy:find_service('foo.example.com'))
end)
describe('.get_upstream', function()
local get_upstream = proxy.get_upstream
it('sets correct upstream port', function()
assert.same(443, get_upstream({ api_backend = 'https://example.com' }).port)
assert.same(80, get_upstream({ api_backend = 'http://example.com' }).port)
assert.same(8080, get_upstream({ api_backend = 'http://example.com:8080' }).port)
end)
end)
describe('.authorize', function()
local authorize = proxy.authorize
local service = { backend_authentication = { value = 'not_baz' } }
local usage = 'foo'
local credentials = 'client_id=blah'
it('takes ttl value if sent', function()
local ttl = 80
ngx.var = { cached_key = credentials, usage=usage, credentials=credentials, http_x_3scale_debug='baz', real_url='blah' }
ngx.ctx = { backend_upstream = ''}
ngx.shared = { api_keys = { cached_key = 'client_id=blah:foo', get = function () return {} end } }
stub(ngx.shared.api_keys, 'set')
stub(ngx.location, 'capture', function() return { status = 200 } end)
authorize(proxy, service, usage, credentials, ttl)
assert.spy(ngx.shared.api_keys.set).was.called_with(ngx.shared.api_keys, 'client_id=blah:foo', 200, 80)
end)
it('works with no ttl', function()
ngx.var = { cached_key = "client_id=blah", usage=usage, credentials=credentials, http_x_3scale_debug='baz', real_url='blah' }
ngx.ctx = { backend_upstream = ''}
ngx.shared = { api_keys = { cached_key = 'client_id=blah:foo', get = function () return {} end } }
stub(ngx.shared.api_keys, 'set')
stub(ngx.location, 'capture', function() return { status = 200 } end)
authorize(proxy, service, usage, credentials)
assert.spy(ngx.shared.api_keys.set).was.called_with(ngx.shared.api_keys, 'client_id=blah:foo', 200, 0)
end)
end)
end)
|
local configuration_store = require 'configuration_store'
describe('Proxy', function()
local configuration, proxy
before_each(function()
configuration = configuration_store.new()
proxy = require('proxy').new(configuration)
end)
it('has access function', function()
assert.truthy(proxy.access)
assert.same('function', type(proxy.access))
end)
describe(':call', function()
before_each(function()
ngx.var = { backend_endpoint = 'http://localhost:1853' }
configuration:add({ id = 42, hosts = { 'localhost' }})
end)
it('has authorize function after call', function()
proxy:call('localhost')
assert.truthy(proxy.authorize)
assert.same('function', type(proxy.authorize))
end)
it('returns access function', function()
local access = proxy:call('localhost')
assert.same('function', type(access))
end)
it('returns oauth handler when matches oauth route', function()
local service = configuration:find_by_id(42)
service.backend_version = 'oauth'
stub(ngx.req, 'get_method', function() return 'GET' end)
ngx.var.uri = '/authorize'
local access, handler = proxy:call('localhost')
assert.equal(nil, access)
assert.same('function', type(handler))
end)
end)
it('has post_action function', function()
assert.truthy(proxy.post_action)
assert.same('function', type(proxy.post_action))
end)
it('finds service by host', function()
local example = { id = 42, hosts = { 'example.com'} }
configuration:add(example)
assert.same(example, proxy:find_service('example.com'))
assert.falsy(proxy:find_service('unknown'))
end)
it('does not return old configuration when new one is available', function()
local foo = { id = '42', hosts = { 'foo.example.com'} }
local bar = { id = '42', hosts = { 'bar.example.com'} }
configuration:add(foo, -1) -- expired record
assert.equal(foo, proxy:find_service('foo.example.com'))
configuration:add(bar, -1) -- expired record
assert.equal(bar, proxy:find_service('bar.example.com'))
assert.falsy(proxy:find_service('foo.example.com'))
end)
describe('.get_upstream', function()
local get_upstream
before_each(function() get_upstream = proxy.get_upstream end)
it('sets correct upstream port', function()
assert.same(443, get_upstream({ api_backend = 'https://example.com' }).port)
assert.same(80, get_upstream({ api_backend = 'http://example.com' }).port)
assert.same(8080, get_upstream({ api_backend = 'http://example.com:8080' }).port)
end)
end)
describe('.authorize', function()
local authorize
local service = { backend_authentication = { value = 'not_baz' } }
local usage = 'foo'
local credentials = 'client_id=blah'
before_each(function()
authorize = proxy.authorize
end)
it('takes ttl value if sent', function()
local ttl = 80
ngx.var = { cached_key = credentials, usage=usage, credentials=credentials, http_x_3scale_debug='baz', real_url='blah' }
ngx.ctx = { backend_upstream = ''}
ngx.shared = { api_keys = { cached_key = 'client_id=blah:foo', get = function () return {} end } }
stub(ngx.shared.api_keys, 'set')
stub(ngx.location, 'capture', function() return { status = 200 } end)
authorize(proxy, service, usage, credentials, ttl)
assert.spy(ngx.shared.api_keys.set).was.called_with(ngx.shared.api_keys, 'client_id=blah:foo', 200, 80)
end)
it('works with no ttl', function()
ngx.var = { cached_key = "client_id=blah", usage=usage, credentials=credentials, http_x_3scale_debug='baz', real_url='blah' }
ngx.ctx = { backend_upstream = ''}
ngx.shared = { api_keys = { cached_key = 'client_id=blah:foo', get = function () return {} end } }
stub(ngx.shared.api_keys, 'set')
stub(ngx.location, 'capture', function() return { status = 200 } end)
authorize(proxy, service, usage, credentials)
assert.spy(ngx.shared.api_keys.set).was.called_with(ngx.shared.api_keys, 'client_id=blah:foo', 200, 0)
end)
end)
end)
|
[busted] fix possible nil values
|
[busted] fix possible nil values
|
Lua
|
mit
|
3scale/apicast,3scale/docker-gateway,3scale/apicast,3scale/apicast,3scale/apicast,3scale/docker-gateway
|
f4a8cb6534c9a0564ecbb6a87b3bde9002276da9
|
mod_auth_ldap/mod_auth_ldap.lua
|
mod_auth_ldap/mod_auth_ldap.lua
|
-- mod_auth_ldap
local new_sasl = require "util.sasl".new;
local lualdap = require "lualdap";
local function ldap_filter_escape(s) return (s:gsub("[\\*\\(\\)\\\\%z]", function(c) return ("\\%02x"):format(c:byte()) end)); end
-- Config options
local ldap_server = module:get_option_string("ldap_server", "localhost");
local ldap_rootdn = module:get_option_string("ldap_rootdn", "");
local ldap_password = module:get_option_string("ldap_password", "");
local ldap_tls = module:get_option_boolean("ldap_tls");
local ldap_scope = module:get_option_string("ldap_scope", "onelevel");
local ldap_filter = module:get_option_string("ldap_filter", "(uid=$user)"):gsub("%%s", "$user", 1);
local ldap_base = assert(module:get_option_string("ldap_base"), "ldap_base is a required option for ldap");
local ldap_mode = module:get_option_string("ldap_mode", "getpasswd");
local host = ldap_filter_escape(module:get_option_string("realm", module.host));
-- Initiate connection
local ld = assert(lualdap.open_simple(ldap_server, ldap_rootdn, ldap_password, ldap_tls));
module.unload = function() ld:close(); end
local function get_user(username)
module:log("debug", "get_user(%q)", username);
return ld:search({
base = ldap_base;
scope = ldap_scope;
filter = ldap_filter:gsub("%$(%a+)", {
user = ldap_filter_escape(username);
host = host;
});
})();
end
local provider = {};
function provider.create_user(username, password)
return nil, "Account creation not available with LDAP.";
end
function provider.user_exists(username)
return not not get_user(username);
end
function provider.set_password(username, password)
local dn, attr = get_user(username);
if not dn then return nil, attr end
if attr.userPassword == password then return true end
return ld:modify(dn, { '=', userPassword = password })();
end
if ldap_mode == "getpasswd" then
function provider.get_password(username)
local dn, attr = get_user(username);
if dn and attr then
return attr.userPassword;
end
end
function provider.test_password(username, password)
return provider.get_password(username) == password;
end
function provider.get_sasl_handler()
return new_sasl(module.host, {
plain = function(sasl, username)
local password = provider.get_password(username);
if not password then return "", nil; end
return password, true;
end
});
end
elseif ldap_mode == "bind" then
local function test_password(userdn, password)
return not not lualdap.open_simple(ldap_server, userdn, password, ldap_tls);
end
function provider.test_password(username, password)
local dn = get_user(username);
if not dn then return end
return test_password(dn, password)
end
function provider.get_sasl_handler()
return new_sasl(module.host, {
plain_test = function(sasl, username, password)
return provider.test_password(username, password), true;
end
});
end
else
module:log("error", "Unsupported ldap_mode %s", tostring(ldap_mode));
end
module:provides("auth", provider);
|
-- mod_auth_ldap
local new_sasl = require "util.sasl".new;
local lualdap = require "lualdap";
local function ldap_filter_escape(s) return (s:gsub("[\\*\\(\\)\\\\%z]", function(c) return ("\\%02x"):format(c:byte()) end)); end
-- Config options
local ldap_server = module:get_option_string("ldap_server", "localhost");
local ldap_rootdn = module:get_option_string("ldap_rootdn", "");
local ldap_password = module:get_option_string("ldap_password", "");
local ldap_tls = module:get_option_boolean("ldap_tls");
local ldap_scope = module:get_option_string("ldap_scope", "onelevel");
local ldap_filter = module:get_option_string("ldap_filter", "(uid=$user)"):gsub("%%s", "$user", 1);
local ldap_base = assert(module:get_option_string("ldap_base"), "ldap_base is a required option for ldap");
local ldap_mode = module:get_option_string("ldap_mode", "getpasswd");
local host = ldap_filter_escape(module:get_option_string("realm", module.host));
-- Initiate connection
local ld = assert(lualdap.open_simple(ldap_server, ldap_rootdn, ldap_password, ldap_tls));
module.unload = function() ld:close(); end
local function get_user(username)
module:log("debug", "get_user(%q)", username);
for dn, attr in ld:search({
base = ldap_base;
scope = ldap_scope;
filter = ldap_filter:gsub("%$(%a+)", {
user = ldap_filter_escape(username);
host = host;
});
}) do return dn, attr; end
end
local provider = {};
function provider.create_user(username, password)
return nil, "Account creation not available with LDAP.";
end
function provider.user_exists(username)
return not not get_user(username);
end
function provider.set_password(username, password)
local dn, attr = get_user(username);
if not dn then return nil, attr end
if attr.userPassword == password then return true end
return ld:modify(dn, { '=', userPassword = password })();
end
if ldap_mode == "getpasswd" then
function provider.get_password(username)
local dn, attr = get_user(username);
if dn and attr then
return attr.userPassword;
end
end
function provider.test_password(username, password)
return provider.get_password(username) == password;
end
function provider.get_sasl_handler()
return new_sasl(module.host, {
plain = function(sasl, username)
local password = provider.get_password(username);
if not password then return "", nil; end
return password, true;
end
});
end
elseif ldap_mode == "bind" then
local function test_password(userdn, password)
return not not lualdap.open_simple(ldap_server, userdn, password, ldap_tls);
end
function provider.test_password(username, password)
local dn = get_user(username);
if not dn then return end
return test_password(dn, password)
end
function provider.get_sasl_handler()
return new_sasl(module.host, {
plain_test = function(sasl, username, password)
return provider.test_password(username, password), true;
end
});
end
else
module:log("error", "Unsupported ldap_mode %s", tostring(ldap_mode));
end
module:provides("auth", provider);
|
mod_auth_ldap: Fix issue with some versions of LuaLDAP
|
mod_auth_ldap: Fix issue with some versions of LuaLDAP
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
02a8c732d2b3c81584d9a8e7ffba03642efa77ff
|
testserver/content/areas.lua
|
testserver/content/areas.lua
|
-- here, areas can be added
require("base.polygons");
module("content.areas", package.seeall);
function Init()
if AreaList then
return;
end
AreaList = {};
--[[ Example: I want to add the area "test area", which comprises a triangle on level 0 and a rectangle on level 1 and 2.
AddArea("test area", {
{{position(0,0,0),position(1,0,0),position(1,1,0)},{0}},
{{position(0,0,0),position(3,0,0),position(3,2,0),position(0,2,0)},{1,2}} } );
NOTE: The points form a line strip, so each neighbour is connected (and the last and first!). Any polygon is allowed.
The z-coordinate in the positions does not matter, only the second entry of the tuple is important.
Please use a uniform naming format for the areas, especially lower case letters. You may use spaces.
]]
-- ## ADD AREAS BELOW ##
AddArea("cadomyr guard 1", {
{{position(118,637,0),position(118,633,0),position(110,633,0),position(110,637,0)}, {0}}
});
AddArea("galmair guard 1", {
{{position(416,247,0),position(413,247,0),position(413,252,0),position(416,252,0)}, {0}}
});
AddArea("galmair guard 2", {
{{position(388,332,0),position(382,332,0),position(382,327,0),position(388,327,0)}, {0}}
});
AddArea("runewick guard 1", {
{{position(839,825,0),position(839,819,0),position(846,819,0),position(846,825,0)}, {0}}
});
end
--- adds an area
-- @param string The name for the new area.
-- @param list({list(posStruct),list(int)}) A list of tuples, each tuple forms a polygon with 1. a list of positions and 2. a list of valid z levels
-- @return boolean False if entry already exists, true if adding the area worked.
function AddArea(name, aList)
if AreaList[name] then
debug("Area already exists.");
return false; -- entry already exists
end
AreaList[name] = {};
for _,poly in pairs(aList) do
table.insert(AreaList[name], base.polygons.Polygon(poly[1],poly[2]));
end
return true;
end
--- Test if a point is in an area
-- @param posStruct The point to be tested
-- @param string The name of the area
-- @return boolean True if point is in area with areaName
function PointInArea(point, areaName)
if not AreaList[areaName] then
debug("Area does not exist.");
return false;
end
for _,poly in pairs(AreaList[areaName]) do
if poly:pip(point) then
return true;
end
end
return false;
end
|
-- here, areas can be added
require("base.polygons");
module("content.areas", package.seeall);
function Init()
if AreaList then
return;
end
AreaList = {};
--[[ Example: I want to add the area "test area", which comprises a triangle on level 0 and a rectangle on level 1 and 2.
AddArea("test area", {
{{position(0,0,0),position(1,0,0),position(1,1,0)},{0}},
{{position(0,0,0),position(3,0,0),position(3,2,0),position(0,2,0)},{1,2}} } );
NOTE: The points form a line strip, so each neighbour is connected (and the last and first!). Any polygon is allowed.
The z-coordinate in the positions does not matter, only the second entry of the tuple is important.
Please use a uniform naming format for the areas, especially lower case letters. You may use spaces.
]]
-- ## ADD AREAS BELOW ##
AddArea("cadomyr guard 1", {
{{position(118,637,0),position(118,633,0),position(110,633,0),position(110,637,0)}, {0}}
});
AddArea("galmair guard 1", {
{{position(416,247,0),position(413,247,0),position(413,252,0),position(416,252,0)}, {0}}
});
AddArea("galmair guard 2", {
{{position(388,332,0),position(382,332,0),position(382,327,0),position(388,327,0)}, {0}}
});
AddArea("runewick guard 1", {
{{position(839,825,0),position(839,819,0),position(846,819,0),position(846,825,0)}, {0}}
});
end
--- adds an area
-- @param string The name for the new area.
-- @param list({list(posStruct),list(int)}) A list of tuples, each tuple forms a polygon with 1. a list of positions and 2. a list of valid z levels
-- @return boolean False if entry already exists, true if adding the area worked.
function AddArea(name, aList)
if AreaList[name] then
debug("Area already exists.");
return false; -- entry already exists
end
AreaList[name] = {};
for _,poly in pairs(aList) do
table.insert(AreaList[name], base.polygons.Polygon(poly[1],poly[2]));
end
return true;
end
--- Test if a point is in an area
-- @param posStruct The point to be tested
-- @param string The name of the area
-- @return boolean True if point is in area with areaName
function PointInArea(point, areaName)
if not AreaList then
Init();
end
if not AreaList[areaName] then
debug("Area does not exist.");
return false;
end
for _,poly in pairs(AreaList[areaName]) do
if poly:pip(point) then
return true;
end
end
return false;
end
|
AreaList nil value fix
|
AreaList nil value fix
|
Lua
|
agpl-3.0
|
Illarion-eV/Illarion-Content,vilarion/Illarion-Content,Baylamon/Illarion-Content,LaFamiglia/Illarion-Content,KayMD/Illarion-Content
|
bb1527020a18c9e377608ea0a446ffb6cd065201
|
libs/httpd/luasrc/httpd/handler/luci.lua
|
libs/httpd/luasrc/httpd/handler/luci.lua
|
--[[
HTTP server implementation for LuCI - luci handler
(c) 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.httpd.handler.luci", package.seeall)
require("luci.dispatcher")
require("luci.http")
require("luci.http.protocol.date")
require("ltn12")
Luci = luci.util.class(luci.httpd.module.Handler)
Response = luci.httpd.module.Response
function Luci.__init__(self)
luci.httpd.module.Handler.__init__(self)
end
function Luci.handle_head(self, ...)
local response, sourceout = self:handle_get(...)
return response
end
function Luci.handle_post(self, ...)
return self:handle_get(...)
end
function Luci.handle_get(self, request, sourcein, sinkerr)
local r = luci.http.Request(
request.env,
sourcein,
sinkerr
)
local res, id, data1, data2 = true, 0, nil, nil
local headers = {}
local status = 200
local x = coroutine.create(luci.dispatcher.httpdispatch)
while not id or id < 3 do
coroutine.yield()
res, id, data1, data2 = coroutine.resume(x, r)
if not res then
status = 500
headers["Content-Type"] = "text/plain"
local err = {id}
return Response( status, headers ), function() return table.remove(err) end
end
if id == 1 then
status = data1
elseif id == 2 then
headers[data1] = data2
end
end
<<<<<<< HEAD:libs/httpd/luasrc/httpd/handler/luci.lua
=======
>>>>>>> * libs/httpd: Added Cache-Control header to LuCI:libs/httpd/luasrc/httpd/handler/luci.lua
local function iter()
local res, id, data = coroutine.resume(x)
if not res then
return nil, id
elseif not id then
return true
elseif id == 5 then
return nil
else
return data
end
end
headers["Expires"] = luci.http.protocol.date.to_http( os.time() )
headers["Date"] = headers["Expires"]
headers["Cache-Control"] = "no-cache"
return Response(status, headers), iter
end
|
--[[
HTTP server implementation for LuCI - luci handler
(c) 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.httpd.handler.luci", package.seeall)
require("luci.dispatcher")
require("luci.http")
require("luci.http.protocol.date")
require("ltn12")
Luci = luci.util.class(luci.httpd.module.Handler)
Response = luci.httpd.module.Response
function Luci.__init__(self)
luci.httpd.module.Handler.__init__(self)
end
function Luci.handle_head(self, ...)
local response, sourceout = self:handle_get(...)
return response
end
function Luci.handle_post(self, ...)
return self:handle_get(...)
end
function Luci.handle_get(self, request, sourcein, sinkerr)
local r = luci.http.Request(
request.env,
sourcein,
sinkerr
)
local res, id, data1, data2 = true, 0, nil, nil
local headers = {}
local status = 200
local x = coroutine.create(luci.dispatcher.httpdispatch)
while not id or id < 3 do
coroutine.yield()
res, id, data1, data2 = coroutine.resume(x, r)
if not res then
status = 500
headers["Content-Type"] = "text/plain"
local err = {id}
return Response( status, headers ), function() return table.remove(err) end
end
if id == 1 then
status = data1
elseif id == 2 then
headers[data1] = data2
end
end
local function iter()
local res, id, data = coroutine.resume(x)
if not res then
return nil, id
elseif not id then
return true
elseif id == 5 then
return nil
else
return data
end
end
headers["Expires"] = luci.http.protocol.date.to_http( os.time() )
headers["Date"] = headers["Expires"]
headers["Cache-Control"] = "no-cache"
return Response(status, headers), iter
end
|
* Fixed last commit
|
* Fixed last commit
git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@2453 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
ch3n2k/luci,jschmidlapp/luci,phi-psi/luci,saraedum/luci-packages-old,saraedum/luci-packages-old,projectbismark/luci-bismark,Flexibity/luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,gwlim/luci,Flexibity/luci,Flexibity/luci,8devices/carambola2-luci,saraedum/luci-packages-old,8devices/carambola2-luci,Flexibity/luci,stephank/luci,dtaht/cerowrt-luci-3.3,ch3n2k/luci,zwhfly/openwrt-luci,phi-psi/luci,ch3n2k/luci,stephank/luci,eugenesan/openwrt-luci,ReclaimYourPrivacy/cloak-luci,alxhh/piratenluci,alxhh/piratenluci,jschmidlapp/luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,alxhh/piratenluci,stephank/luci,jschmidlapp/luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,ch3n2k/luci,projectbismark/luci-bismark,jschmidlapp/luci,zwhfly/openwrt-luci,yeewang/openwrt-luci,dtaht/cerowrt-luci-3.3,eugenesan/openwrt-luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,Canaan-Creative/luci,vhpham80/luci,dtaht/cerowrt-luci-3.3,gwlim/luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,projectbismark/luci-bismark,ThingMesh/openwrt-luci,yeewang/openwrt-luci,Flexibity/luci,8devices/carambola2-luci,stephank/luci,phi-psi/luci,8devices/carambola2-luci,8devices/carambola2-luci,freifunk-gluon/luci,alxhh/piratenluci,alxhh/piratenluci,freifunk-gluon/luci,Canaan-Creative/luci,8devices/carambola2-luci,phi-psi/luci,stephank/luci,alxhh/piratenluci,projectbismark/luci-bismark,dtaht/cerowrt-luci-3.3,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,ch3n2k/luci,alxhh/piratenluci,ch3n2k/luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,ThingMesh/openwrt-luci,gwlim/luci,gwlim/luci,8devices/carambola2-luci,phi-psi/luci,vhpham80/luci,vhpham80/luci,projectbismark/luci-bismark,Canaan-Creative/luci,vhpham80/luci,gwlim/luci,ThingMesh/openwrt-luci,ThingMesh/openwrt-luci,Flexibity/luci,eugenesan/openwrt-luci,projectbismark/luci-bismark,projectbismark/luci-bismark,Flexibity/luci,gwlim/luci,dtaht/cerowrt-luci-3.3,vhpham80/luci,zwhfly/openwrt-luci,stephank/luci,jschmidlapp/luci,gwlim/luci,freifunk-gluon/luci,Canaan-Creative/luci,yeewang/openwrt-luci,saraedum/luci-packages-old,jschmidlapp/luci,projectbismark/luci-bismark,freifunk-gluon/luci,vhpham80/luci,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,eugenesan/openwrt-luci,saraedum/luci-packages-old,ch3n2k/luci,jschmidlapp/luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,dtaht/cerowrt-luci-3.3,Flexibity/luci,yeewang/openwrt-luci,Canaan-Creative/luci,ReclaimYourPrivacy/cloak-luci,phi-psi/luci,freifunk-gluon/luci,eugenesan/openwrt-luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,Canaan-Creative/luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,ThingMesh/openwrt-luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,freifunk-gluon/luci
|
32f22bea121fd4db98351cdd8e7b2444fa165255
|
mod/mpi/config/scripts/run_vifm.lua
|
mod/mpi/config/scripts/run_vifm.lua
|
local mp_utils = require('mp.utils')
function run_vifm()
local path = mp.get_property('path')
local running = mp_utils.subprocess(
{args = {'pidof', 'vifm'},
cancellable=false,
})['status'] == 0
local args
if running then
args = {'vifm'}
vifm_server_name = os.getenv('VIFM_SERVER_NAME')
if vifm_server_name then
table.insert(args, '--server-name')
table.insert(args, vifm_server_name)
end
table.insert(args, '--remote')
table.insert(args, '--select')
table.insert(args, path)
else
args = {'urxvt', '-e', 'vifm'}
end
mp_utils.subprocess_detached({args=args})
end
mp.register_script_message('run-vifm', run_vifm)
|
local mp_utils = require('mp.utils')
local last_known_path = nil
function playback_started(event)
last_known_path = mp.get_property('path')
end
function run_vifm()
local running = mp_utils.subprocess({
args = {'pidof', 'vifm'},
cancellable=false,
})['status'] == 0
local args
if running then
args = {'vifm'}
vifm_server_name = os.getenv('VIFM_SERVER_NAME')
if vifm_server_name then
table.insert(args, '--server-name')
table.insert(args, vifm_server_name)
end
table.insert(args, '--remote')
table.insert(args, '--select')
table.insert(args, last_known_path)
else
args = {'urxvt', '-e', 'vifm'}
end
mp_utils.subprocess_detached({args=args})
end
mp.register_script_message('run-vifm', run_vifm)
mp.add_hook('on_load', 50, playback_started)
|
mod/mpi: fix returning to vifm
|
mod/mpi: fix returning to vifm
|
Lua
|
mit
|
rr-/dotfiles,rr-/dotfiles,rr-/dotfiles
|
b4c4545031f5b34b0aa48d18fa59785c20e57f82
|
src/QuikSharp/lua/qscallbacks.lua
|
src/QuikSharp/lua/qscallbacks.lua
|
--~ Copyright Ⓒ 2015 Victor Baybekov
package.path = package.path..";"..".\\?.lua;"..".\\?.luac"
package.cpath = package.cpath..";"..'.\\clibs\\?.dll'
local util = require("qsutils")
local qscallbacks = {}
--- Мы сохраняем пропущенные значения только если скрипт работает, но соединение прервалось
-- Если скрипт останавливается, то мы удаляем накопленные пропущенные значения
-- QuikSharp должен работать пока работает Квик, он не рассчитан на остановку внутри Квика.
-- При этом клиент может подключаться и отключаться сколько угодно и всегда получит пропущенные
-- сообщения после переподключения (если хватит места на диске)
local function CleanUp()
-- close log
pcall(logfile:close(logfile))
-- discard missed values if any
if missed_values_file then
pcall(missed_values_file:close(missed_values_file))
missed_values_file = nil
pcall(os.remove, missed_values_file_name)
missed_values_file_name = nil
end
end
--- Функция вызывается когда соединение с QuikSharp клиентом обрывается
function OnQuikSharpDisconnected()
-- TODO any recovery or risk management logic here
end
--- Функция вызывается когда скрипт ловит ошибку в функциях обратного вызова
function OnError(message)
msg.cmd = "lua_error"
msg.data = "Lua error: " .. message
sendCallback(msg)
end
--- Функция вызывается терминалом QUIK при установлении связи с сервером QUIK.
function OnConnected()
if is_connected then
local msg = {}
msg.t = timemsec()
msg.cmd = "OnConnected"
msg.data = ""
sendCallback(msg)
end
end
--- Функция вызывается терминалом QUIK при установлении связи с сервером QUIK.
function OnDisconnected()
if is_connected then
local msg = {}
msg.t = timemsec()
msg.cmd = "OnDisconnected"
msg.data = ""
sendCallback(msg)
end
end
--- Функция вызывается терминалом QUIK при получении обезличенной сделки.
function OnAllTrade(alltrade)
if is_connected then
local msg = {}
msg.t = timemsec()
msg.cmd = "OnAllTrade"
msg.data = alltrade
sendCallback(msg)
end
end
--- Функция вызывается перед закрытием терминала QUIK.
function OnClose()
if is_connected then
local msg = {}
msg.cmd = "OnClose"
msg.t = timemsec()
msg.data = ""
sendCallback(msg)
end
CleanUp()
end
--- Функция вызывается терминалом QUIK перед вызовом функции main().
-- В качестве параметра принимает значение полного пути к запускаемому скрипту.
function OnInit(script_path)
if is_connected then
local msg = {}
msg.cmd = "OnInit"
msg.t = timemsec()
msg.data = script_path
sendCallback(msg)
end
log("Hello, QuikSharp! Running inside Quik from the path: "..getScriptPath(), 1)
end
--- Функция вызывается терминалом QUIK при получении сделки.
function OnOrder(order)
local msg = {}
msg.t = timemsec()
msg.id = nil -- значение в order.trans_id
msg.data = order
msg.cmd = "OnOrder"
sendCallback(msg)
end
--- Функция вызывается терминалом QUIK при получении изменения стакана котировок.
function OnQuote(class_code, sec_code)
if true then -- is_connected
local msg = {}
msg.cmd = "OnQuote"
msg.t = timemsec()
local server_time = getInfoParam("SERVERTIME")
local status, ql2 = pcall(getQuoteLevel2, class_code, sec_code)
if status then
msg.data = ql2
msg.data.class_code = class_code
msg.data.sec_code = sec_code
msg.data.server_time = server_time
sendCallback(msg)
else
OnError(ql2)
end
end
end
--- Функция вызывается терминалом QUIK при остановке скрипта из диалога управления и при закрытии терминала QUIK.
function OnStop(s)
is_started = false
if is_connected then
local msg = {}
msg.cmd = "OnStop"
msg.t = timemsec()
msg.data = s
sendCallback(msg)
end
log("Bye, QuikSharp!")
CleanUp()
-- send disconnect
return 1000
end
--- Функция вызывается терминалом QUIK при получении сделки.
function OnTrade(trade)
local msg = {}
msg.t = timemsec()
msg.id = nil -- значение в OnTrade.trans_id
msg.data = trade
msg.cmd = "OnTrade"
sendCallback(msg)
end
--- Функция вызывается терминалом QUIK при получении ответа на транзакцию пользователя.
function OnTransReply(trans_reply)
local msg = {}
msg.t = timemsec()
msg.id = nil -- значение в trans_reply.trans_id
msg.data = trans_reply
msg.cmd = "OnTransReply"
sendCallback(msg)
end
function OnStopOrder(stop_order)
local msg = {}
msg.t = timemsec()
msg.data = stop_order
msg.cmd = "OnStopOrder"
sendCallback(msg)
end
return qscallbacks
|
--~ Copyright Ⓒ 2015 Victor Baybekov
package.path = package.path..";"..".\\?.lua;"..".\\?.luac"
package.cpath = package.cpath..";"..'.\\clibs\\?.dll'
local util = require("qsutils")
local qscallbacks = {}
--- Мы сохраняем пропущенные значения только если скрипт работает, но соединение прервалось
-- Если скрипт останавливается, то мы удаляем накопленные пропущенные значения
-- QuikSharp должен работать пока работает Квик, он не рассчитан на остановку внутри Квика.
-- При этом клиент может подключаться и отключаться сколько угодно и всегда получит пропущенные
-- сообщения после переподключения (если хватит места на диске)
local function CleanUp()
-- close log
pcall(logfile:close(logfile))
-- discard missed values if any
if missed_values_file then
pcall(missed_values_file:close(missed_values_file))
missed_values_file = nil
pcall(os.remove, missed_values_file_name)
missed_values_file_name = nil
end
end
--- Функция вызывается когда соединение с QuikSharp клиентом обрывается
function OnQuikSharpDisconnected()
-- TODO any recovery or risk management logic here
end
--- Функция вызывается когда скрипт ловит ошибку в функциях обратного вызова
function OnError(message)
if is_connected then
local msg = {}
msg.t = timemsec()
msg.cmd = "lua_error"
msg.data = "Lua error: " .. message
sendCallback(msg)
end
end
--- Функция вызывается терминалом QUIK при установлении связи с сервером QUIK.
function OnConnected()
if is_connected then
local msg = {}
msg.t = timemsec()
msg.cmd = "OnConnected"
msg.data = ""
sendCallback(msg)
end
end
--- Функция вызывается терминалом QUIK при установлении связи с сервером QUIK.
function OnDisconnected()
if is_connected then
local msg = {}
msg.t = timemsec()
msg.cmd = "OnDisconnected"
msg.data = ""
sendCallback(msg)
end
end
--- Функция вызывается терминалом QUIK при получении обезличенной сделки.
function OnAllTrade(alltrade)
if is_connected then
local msg = {}
msg.t = timemsec()
msg.cmd = "OnAllTrade"
msg.data = alltrade
sendCallback(msg)
end
end
--- Функция вызывается перед закрытием терминала QUIK.
function OnClose()
if is_connected then
local msg = {}
msg.cmd = "OnClose"
msg.t = timemsec()
msg.data = ""
sendCallback(msg)
end
CleanUp()
end
--- Функция вызывается терминалом QUIK перед вызовом функции main().
-- В качестве параметра принимает значение полного пути к запускаемому скрипту.
function OnInit(script_path)
if is_connected then
local msg = {}
msg.cmd = "OnInit"
msg.t = timemsec()
msg.data = script_path
sendCallback(msg)
end
log("Hello, QuikSharp! Running inside Quik from the path: "..getScriptPath(), 1)
end
--- Функция вызывается терминалом QUIK при получении сделки.
function OnOrder(order)
local msg = {}
msg.t = timemsec()
msg.id = nil -- значение в order.trans_id
msg.data = order
msg.cmd = "OnOrder"
sendCallback(msg)
end
--- Функция вызывается терминалом QUIK при получении изменения стакана котировок.
function OnQuote(class_code, sec_code)
if true then -- is_connected
local msg = {}
msg.cmd = "OnQuote"
msg.t = timemsec()
local server_time = getInfoParam("SERVERTIME")
local status, ql2 = pcall(getQuoteLevel2, class_code, sec_code)
if status then
msg.data = ql2
msg.data.class_code = class_code
msg.data.sec_code = sec_code
msg.data.server_time = server_time
sendCallback(msg)
else
OnError(ql2)
end
end
end
--- Функция вызывается терминалом QUIK при остановке скрипта из диалога управления и при закрытии терминала QUIK.
function OnStop(s)
is_started = false
if is_connected then
local msg = {}
msg.cmd = "OnStop"
msg.t = timemsec()
msg.data = s
sendCallback(msg)
end
log("Bye, QuikSharp!")
CleanUp()
-- send disconnect
return 1000
end
--- Функция вызывается терминалом QUIK при получении сделки.
function OnTrade(trade)
local msg = {}
msg.t = timemsec()
msg.id = nil -- значение в OnTrade.trans_id
msg.data = trade
msg.cmd = "OnTrade"
sendCallback(msg)
end
--- Функция вызывается терминалом QUIK при получении ответа на транзакцию пользователя.
function OnTransReply(trans_reply)
local msg = {}
msg.t = timemsec()
msg.id = nil -- значение в trans_reply.trans_id
msg.data = trans_reply
msg.cmd = "OnTransReply"
sendCallback(msg)
end
function OnStopOrder(stop_order)
local msg = {}
msg.t = timemsec()
msg.data = stop_order
msg.cmd = "OnStopOrder"
sendCallback(msg)
end
return qscallbacks
|
Lua error was not sent to client as "msg" was global and "msg" was null. Fixed.
|
Lua error was not sent to client as "msg" was global and "msg" was null. Fixed.
|
Lua
|
apache-2.0
|
buybackoff/QuikSharp,nubick/QuikSharp,finsight/QuikSharp,sm00vik/QuikSharp
|
15ed55d68aab1e5a2e40d9d5bf120e3d0db53945
|
src/api-umbrella/cli/reload.lua
|
src/api-umbrella/cli/reload.lua
|
local path = require "pl.path"
local run_command = require "api-umbrella.utils.run_command"
local setup = require "api-umbrella.cli.setup"
local status = require "api-umbrella.cli.status"
local function reload_perp(perp_base)
local _, _, err = run_command("perphup " .. perp_base)
if err then
print("Failed to reload perp\n" .. err)
os.exit(1)
end
end
local function reload_trafficserver(perp_base)
local _, _, err = run_command("perpctl -b " .. perp_base .. " hup trafficserver")
if err then
print("Failed to reload trafficserver\n" .. err)
os.exit(1)
end
end
local function reload_nginx(perp_base)
local _, _, err = run_command("perpctl -b " .. perp_base .. " hup nginx")
if err then
print("Failed to reload nginx\n" .. err)
os.exit(1)
end
end
return function()
local running = status()
if not running then
print("api-umbrella is stopped")
os.exit(1)
end
local config = setup()
local perp_base = path.join(config["etc_dir"], "perp")
reload_perp(perp_base)
reload_trafficserver(perp_base)
reload_nginx(perp_base)
end
|
local path = require "pl.path"
local run_command = require "api-umbrella.utils.run_command"
local setup = require "api-umbrella.cli.setup"
local status = require "api-umbrella.cli.status"
local function reload_perp(perp_base)
local _, _, err = run_command("perphup " .. perp_base)
if err then
print("Failed to reload perp\n" .. err)
os.exit(1)
end
end
local function reload_web_delayed_job(perp_base)
local _, _, err = run_command("perpctl -b " .. perp_base .. " term web-delayed-job")
if err then
print("Failed to reload web-delayed-job\n" .. err)
os.exit(1)
end
end
local function reload_web_puma(perp_base)
local _, _, err = run_command("perpctl -b " .. perp_base .. " 2 web-puma")
if err then
print("Failed to reload web-puma\n" .. err)
os.exit(1)
end
end
local function reload_trafficserver(perp_base)
local _, _, err = run_command("perpctl -b " .. perp_base .. " hup trafficserver")
if err then
print("Failed to reload trafficserver\n" .. err)
os.exit(1)
end
end
local function reload_nginx(perp_base)
local _, _, err = run_command("perpctl -b " .. perp_base .. " hup nginx")
if err then
print("Failed to reload nginx\n" .. err)
os.exit(1)
end
end
return function()
local running = status()
if not running then
print("api-umbrella is stopped")
os.exit(1)
end
local config = setup()
local perp_base = path.join(config["etc_dir"], "perp")
reload_perp(perp_base)
if config["_service_web_enabled?"] then
reload_web_delayed_job(perp_base)
reload_web_puma(perp_base)
end
if config["_service_router_enabled?"] then
reload_trafficserver(perp_base)
reload_nginx(perp_base)
end
end
|
Reload rails apps when sending reload signal.
|
Reload rails apps when sending reload signal.
Also fix reload command so that it only reloads the appropriate services
depending on what's enabled on the server.
|
Lua
|
mit
|
apinf/api-umbrella,apinf/api-umbrella,NREL/api-umbrella,apinf/api-umbrella,NREL/api-umbrella,apinf/api-umbrella,NREL/api-umbrella,NREL/api-umbrella,apinf/api-umbrella
|
e2d2f25027ea5acb3f9caff47e2919f9577e6318
|
src/adorneeutils/src/Shared/AdorneeUtils.lua
|
src/adorneeutils/src/Shared/AdorneeUtils.lua
|
---
-- @module AdorneeUtils
-- @author Quenty
local AdorneeUtils = {}
function AdorneeUtils.getCenter(adornee)
assert(typeof(adornee) == "Instance", "Adornee must by of type 'Instance'")
if adornee:IsA("BasePart") then
return adornee.Position
elseif adornee:IsA("Model") then
return adornee:GetBoundingBox().p
elseif adornee:IsA("Attachment") then
return adornee.WorldPosition
elseif adornee:IsA("Humanoid") then
local rootPart = adornee.RootPart
if rootPart then
return rootPart.Position
else
return nil
end
elseif adornee:IsA("Accessory") or adornee:IsA("Clothing") then
local handle = adornee:FindFirstChildWhichIsA("BasePart")
if handle then
return handle.Position
else
return nil
end
elseif adornee:IsA("Tool") then
local handle = adornee:FindFirstChild("Handle")
if handle and handle:IsA("BasePart") then
return handle.Position
else
return nil
end
else
return nil
end
end
function AdorneeUtils.getBoundingBox(adornee)
if adornee:IsA("Model") then
return adornee:GetBoundingBox()
else
return AdorneeUtils.getPartCFrame(adornee), AdorneeUtils.getAlignedSize(adornee)
end
end
function AdorneeUtils.isPartOfAdornee(adornee, part)
assert(part:IsA("BasePart"))
if adornee:IsA("Humanoid") then
if not adornee.Parent then
return false
end
return part:IsDescendantOf(adornee.Parent)
end
return adornee == part or part:IsDescendantOf(adornee)
end
function AdorneeUtils.getParts(adornee)
assert(typeof(adornee) == "Instance", "Adornee must by of type 'Instance'")
local parts = {}
if adornee:IsA("BasePart") then
table.insert(parts, adornee)
end
local searchParent
if adornee:IsA("Humanoid") then
searchParent = adornee.Parent
else
searchParent = adornee
end
if searchParent then
for _, part in pairs(searchParent:GetDescendants()) do
if part:IsA("BasePart") then
table.insert(parts, part)
end
end
end
return parts
end
function AdorneeUtils.getAlignedSize(adornee)
if adornee:IsA("Model") then
return select(2, adornee:GetBoundingBox())
elseif adornee:IsA("Humanoid") then
if adornee.Parent then
return select(2, adornee.Parent:GetBoundingBox())
else
return nil
end
else
local part = AdorneeUtils.getPart(adornee)
if part then
return part.Size
end
end
return nil
end
function AdorneeUtils.getPartCFrame(adornee)
assert(typeof(adornee) == "Instance", "Adornee must by of type 'Instance'")
local part = AdorneeUtils.getPart(adornee)
if not part then
return nil
end
return part.CFrame
end
function AdorneeUtils.getPartPosition(adornee)
assert(typeof(adornee) == "Instance", "Adornee must by of type 'Instance'")
local part = AdorneeUtils.getPart(adornee)
if not part then
return nil
end
return part.Position
end
function AdorneeUtils.getPartVelocity(adornee)
local part = AdorneeUtils.getPart(adornee)
if not part then
return nil
end
return part.Velocity
end
function AdorneeUtils.getPart(adornee)
assert(typeof(adornee) == "Instance", "Adornee must by of type 'Instance'")
if adornee:IsA("BasePart") then
return adornee
elseif adornee:IsA("Model") then
if adornee.PrimaryPart then
return adornee.PrimaryPart
else
return adornee:FindFirstChildWhichIsA("BasePart")
end
elseif adornee:IsA("Attachment") then
return adornee.Parent
elseif adornee:IsA("Humanoid") then
return adornee.RootPart
elseif adornee:IsA("Accessory") or adornee:IsA("Clothing") then
return adornee:FindFirstChildWhichIsA("BasePart")
elseif adornee:IsA("Tool") then
local handle = adornee:FindFirstChild("Handle")
if handle and handle:IsA("BasePart") then
return handle
else
return nil
end
else
return nil
end
end
function AdorneeUtils.getRenderAdornee(adornee)
assert(typeof(adornee) == "Instance", "Adornee must by of type 'Instance'")
if adornee:IsA("BasePart") then
return adornee
elseif adornee:IsA("Model") then
return adornee
elseif adornee:IsA("Attachment") then
return adornee
elseif adornee:IsA("Humanoid") then
return adornee.Parent
elseif adornee:IsA("Accessory") or adornee:IsA("Clothing") then
return adornee:FindFirstChildWhichIsA("BasePart")
elseif adornee:IsA("Tool") then
local handle = adornee:FindFirstChild("Handle")
if handle and handle:IsA("BasePart") then
return handle
else
return nil
end
else
return nil
end
end
return AdorneeUtils
|
---
-- @module AdorneeUtils
-- @author Quenty
local AdorneeUtils = {}
function AdorneeUtils.getCenter(adornee)
assert(typeof(adornee) == "Instance", "Adornee must by of type 'Instance'")
if adornee:IsA("BasePart") then
return adornee.Position
elseif adornee:IsA("Model") then
return adornee:GetBoundingBox().p
elseif adornee:IsA("Attachment") then
return adornee.WorldPosition
elseif adornee:IsA("Humanoid") then
local rootPart = adornee.RootPart
if rootPart then
return rootPart.Position
else
return nil
end
elseif adornee:IsA("Accessory") or adornee:IsA("Clothing") then
local handle = adornee:FindFirstChildWhichIsA("BasePart")
if handle then
return handle.Position
else
return nil
end
elseif adornee:IsA("Tool") then
local handle = adornee:FindFirstChild("Handle")
if handle and handle:IsA("BasePart") then
return handle.Position
else
return nil
end
else
return nil
end
end
function AdorneeUtils.getBoundingBox(adornee)
if adornee:IsA("Model") then
return adornee:GetBoundingBox()
elseif adornee:IsA("Attachment") then
return adornee.WorldCFrame, Vector3.new(0, 0, 0) -- This is a point
else
return AdorneeUtils.getPartCFrame(adornee), AdorneeUtils.getAlignedSize(adornee)
end
end
function AdorneeUtils.isPartOfAdornee(adornee, part)
assert(part:IsA("BasePart"))
if adornee:IsA("Humanoid") then
if not adornee.Parent then
return false
end
return part:IsDescendantOf(adornee.Parent)
end
return adornee == part or part:IsDescendantOf(adornee)
end
function AdorneeUtils.getParts(adornee)
assert(typeof(adornee) == "Instance", "Adornee must by of type 'Instance'")
local parts = {}
if adornee:IsA("BasePart") then
table.insert(parts, adornee)
end
local searchParent
if adornee:IsA("Humanoid") then
searchParent = adornee.Parent
else
searchParent = adornee
end
if searchParent then
for _, part in pairs(searchParent:GetDescendants()) do
if part:IsA("BasePart") then
table.insert(parts, part)
end
end
end
return parts
end
function AdorneeUtils.getAlignedSize(adornee)
if adornee:IsA("Model") then
return select(2, adornee:GetBoundingBox())
elseif adornee:IsA("Humanoid") then
if adornee.Parent then
return select(2, adornee.Parent:GetBoundingBox())
else
return nil
end
else
local part = AdorneeUtils.getPart(adornee)
if part then
return part.Size
end
end
return nil
end
function AdorneeUtils.getPartCFrame(adornee)
assert(typeof(adornee) == "Instance", "Adornee must by of type 'Instance'")
local part = AdorneeUtils.getPart(adornee)
if not part then
return nil
end
return part.CFrame
end
function AdorneeUtils.getPartPosition(adornee)
assert(typeof(adornee) == "Instance", "Adornee must by of type 'Instance'")
local part = AdorneeUtils.getPart(adornee)
if not part then
return nil
end
return part.Position
end
function AdorneeUtils.getPartVelocity(adornee)
local part = AdorneeUtils.getPart(adornee)
if not part then
return nil
end
return part.Velocity
end
function AdorneeUtils.getPart(adornee)
assert(typeof(adornee) == "Instance", "Adornee must by of type 'Instance'")
if adornee:IsA("BasePart") then
return adornee
elseif adornee:IsA("Model") then
if adornee.PrimaryPart then
return adornee.PrimaryPart
else
return adornee:FindFirstChildWhichIsA("BasePart")
end
elseif adornee:IsA("Attachment") then
return adornee.Parent
elseif adornee:IsA("Humanoid") then
return adornee.RootPart
elseif adornee:IsA("Accessory") or adornee:IsA("Clothing") then
return adornee:FindFirstChildWhichIsA("BasePart")
elseif adornee:IsA("Tool") then
local handle = adornee:FindFirstChild("Handle")
if handle and handle:IsA("BasePart") then
return handle
else
return nil
end
else
return nil
end
end
function AdorneeUtils.getRenderAdornee(adornee)
assert(typeof(adornee) == "Instance", "Adornee must by of type 'Instance'")
if adornee:IsA("BasePart") then
return adornee
elseif adornee:IsA("Model") then
return adornee
elseif adornee:IsA("Attachment") then
return adornee
elseif adornee:IsA("Humanoid") then
return adornee.Parent
elseif adornee:IsA("Accessory") or adornee:IsA("Clothing") then
return adornee:FindFirstChildWhichIsA("BasePart")
elseif adornee:IsA("Tool") then
local handle = adornee:FindFirstChild("Handle")
if handle and handle:IsA("BasePart") then
return handle
else
return nil
end
else
return nil
end
end
return AdorneeUtils
|
fix: Add attachment for bounding box in adornee utils
|
fix: Add attachment for bounding box in adornee utils
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
1a333ee8ee6675c64a4a32075f44a8546795b605
|
main.lua
|
main.lua
|
io.stdout:setvbuf("no")
require("api")
function love.mousepressed(x,y,button,istouch)
local x,y = _ScreenToLiko(x,y) if x < 0 or x > 192 or y < 0 or y > 128 then return end
_auto_mpress(x,y,button,istouch)
end
function love.mousemoved(x,y,dx,dy,istouch)
local x, y = _ScreenToLiko(x,y) if x < 0 or x > 192 or y < 0 or y > 128 then return end
_auto_mmove(x,y,dx,dy,istouch)
end
function love.mousereleased(x,y,button,istouch)
local x, y = _ScreenToLiko(x,y) if x < 0 or x > 192 or y < 0 or y > 128 then return end
_auto_mrelease(x,y,button,istouch)
end
function love.wheelmoved(x,y)
_auto_mmove(x,y,0,0,false,true) --Mouse button 0 is the wheel
end
function love.touchpressed(id,x,y,dx,dy,pressure)
local x, y = _ScreenToLiko(x,y) if x < 0 or x > 192 or y < 0 or y > 128 then return end
_auto_tpress(id,x,y,pressure)
end
function love.touchmoved(id,x,y,dx,dy,pressure)
local x, y = _ScreenToLiko(x,y) if x < 0 or x > 192 or y < 0 or y > 128 then return end
_auto_tmove(id,x,y,pressure)
end
function love.touchreleased(id,x,y,dx,dy,pressure)
local x, y = _ScreenToLiko(x,y) if x < 0 or x > 192 or y < 0 or y > 128 then return end
_auto_trelease(id,x,y,pressure)
end
function love.keypressed(key,scancode,isrepeat)
_auto_kpress(key,scancode,isrepeat)
end
function love.keyreleased(key,scancode)
_auto_krelease(key,scancode)
end
function love.textinput(text)
_auto_tinput(text)
end
--Internal Callbacks--
function love.load()
--love.keyboard.setTextInput(true)
loadDefaultCursors()
_ScreenCanvas = love.graphics.newCanvas(192,128)
_ScreenCanvas:setFilter("nearest")
love.graphics.clear(0,0,0,255)
love.graphics.setCanvas(_ScreenCanvas)
love.graphics.clear(0,0,0,255)
love.graphics.translate(_ScreenTX,_ScreenTY)
love.resize(love.graphics.getDimensions())
love.graphics.setLineStyle("rough")
love.graphics.setLineJoin("miter")
love.graphics.setDefaultFilter("nearest")
love.graphics.setFont(_Font)
clear() --Clear the canvas for the first time
stroke(1)
require("autorun")
--require("debugrun")
--require("editor")
_auto_startup()
end
function love.resize(w,h)
_ScreenWidth, _ScreenHeight = w, h
local TSX, TSY = w/192, h/128 --TestScaleX, TestScaleY
if TSX < TSY then
_ScreenScaleX, _ScreenScaleY, _ScreenScale = w/192, w/192, w/192
_ScreenX, _ScreenY = 0, (_ScreenHeight-128*_ScreenScaleY)/2
else
_ScreenScaleX, _ScreenScaleY, _ScreenScale = h/128, h/128, h/128
_ScreenX, _ScreenY = (_ScreenWidth-192*_ScreenScaleX)/2, 0
end
clearCursorsCache()
_ShouldDraw = true
end
function love.update(dt)
local mx, my = _ScreenToLiko(love.mouse.getPosition())
love.window.setTitle(_ScreenTitle.." FPS: "..love.timer.getFPS().." ShouldDraw: "..(_ForceDraw and "FORCE" or (_ShouldDraw and "Yes" or "No")).." MX, MY: "..mx..","..my)
_auto_update(dt)
end
function love.visible(v)
_ForceDraw = not v
_ShouldDraw = v
end
function love.focus(f)
_ForceDraw = not f
ShouldDraw = f
end
function love.run()
if love.math then
love.math.setRandomSeed(os.time())
end
if love.load then love.load(arg) end
-- We don't want the first frame's dt to include time taken by love.load.
if love.timer then love.timer.step() end
local dt = 0
-- Main loop time.
while true do
-- Process events.
if love.event then
love.event.pump()
for name, a,b,c,d,e,f in love.event.poll() do
if name == "quit" then
if not love.quit or not love.quit() then
return a
end
end
love.handlers[name](a,b,c,d,e,f)
end
end
-- Update dt, as we'll be passing it to update
if love.timer then
love.timer.step()
dt = love.timer.getDelta()
end
-- Call update and draw
if love.update then love.update(dt) end -- will pass 0 if love.timer is disabled
if love.graphics and love.graphics.isActive() and (_ShouldDraw or _ForceDraw) then
love.graphics.setCanvas()
love.graphics.origin()
love.graphics.setColor(255,255,255)
love.graphics.draw(_ScreenCanvas, _ScreenX,_ScreenY, 0, _ScreenScaleX,_ScreenScaleY)
--love.graphics.points(1,1,_ScreenWidth,_ScreenHeight)
love.graphics.present()
love.graphics.setCanvas(_ScreenCanvas)
love.graphics.translate(_ScreenTX,_ScreenTY)
_ShouldDraw = false
end
if love.timer then love.timer.sleep(0.001) end
end
end
|
io.stdout:setvbuf("no")
love.graphics.setDefaultFilter("nearest")
require("api")
function love.mousepressed(x,y,button,istouch)
local x,y = _ScreenToLiko(x,y) if x < 0 or x > 192 or y < 0 or y > 128 then return end
_auto_mpress(x,y,button,istouch)
end
function love.mousemoved(x,y,dx,dy,istouch)
local x, y = _ScreenToLiko(x,y) if x < 0 or x > 192 or y < 0 or y > 128 then return end
_auto_mmove(x,y,dx,dy,istouch)
end
function love.mousereleased(x,y,button,istouch)
local x, y = _ScreenToLiko(x,y) if x < 0 or x > 192 or y < 0 or y > 128 then return end
_auto_mrelease(x,y,button,istouch)
end
function love.wheelmoved(x,y)
_auto_mmove(x,y,0,0,false,true) --Mouse button 0 is the wheel
end
function love.touchpressed(id,x,y,dx,dy,pressure)
local x, y = _ScreenToLiko(x,y) if x < 0 or x > 192 or y < 0 or y > 128 then return end
_auto_tpress(id,x,y,pressure)
end
function love.touchmoved(id,x,y,dx,dy,pressure)
local x, y = _ScreenToLiko(x,y) if x < 0 or x > 192 or y < 0 or y > 128 then return end
_auto_tmove(id,x,y,pressure)
end
function love.touchreleased(id,x,y,dx,dy,pressure)
local x, y = _ScreenToLiko(x,y) if x < 0 or x > 192 or y < 0 or y > 128 then return end
_auto_trelease(id,x,y,pressure)
end
function love.keypressed(key,scancode,isrepeat)
_auto_kpress(key,scancode,isrepeat)
end
function love.keyreleased(key,scancode)
_auto_krelease(key,scancode)
end
function love.textinput(text)
_auto_tinput(text)
end
--Internal Callbacks--
function love.load()
--love.keyboard.setTextInput(true)
loadDefaultCursors()
_ScreenCanvas = love.graphics.newCanvas(192,128)
_ScreenCanvas:setFilter("nearest")
love.graphics.clear(0,0,0,255)
love.graphics.setCanvas(_ScreenCanvas)
love.graphics.clear(0,0,0,255)
love.graphics.translate(_ScreenTX,_ScreenTY)
love.resize(love.graphics.getDimensions())
love.graphics.setLineStyle("rough")
love.graphics.setLineJoin("miter")
love.graphics.setFont(_Font)
clear() --Clear the canvas for the first time
stroke(1)
require("autorun")
--require("debugrun")
--require("editor")
_auto_startup()
end
function love.resize(w,h)
_ScreenWidth, _ScreenHeight = w, h
local TSX, TSY = w/192, h/128 --TestScaleX, TestScaleY
if TSX < TSY then
_ScreenScaleX, _ScreenScaleY, _ScreenScale = w/192, w/192, w/192
_ScreenX, _ScreenY = 0, (_ScreenHeight-128*_ScreenScaleY)/2
else
_ScreenScaleX, _ScreenScaleY, _ScreenScale = h/128, h/128, h/128
_ScreenX, _ScreenY = (_ScreenWidth-192*_ScreenScaleX)/2, 0
end
clearCursorsCache()
_ShouldDraw = true
end
function love.update(dt)
local mx, my = _ScreenToLiko(love.mouse.getPosition())
love.window.setTitle(_ScreenTitle.." FPS: "..love.timer.getFPS().." ShouldDraw: "..(_ForceDraw and "FORCE" or (_ShouldDraw and "Yes" or "No")).." MX, MY: "..mx..","..my)
_auto_update(dt)
end
function love.visible(v)
_ForceDraw = not v
_ShouldDraw = v
end
function love.focus(f)
_ForceDraw = not f
ShouldDraw = f
end
function love.run()
if love.math then
love.math.setRandomSeed(os.time())
end
if love.load then love.load(arg) end
-- We don't want the first frame's dt to include time taken by love.load.
if love.timer then love.timer.step() end
local dt = 0
-- Main loop time.
while true do
-- Process events.
if love.event then
love.event.pump()
for name, a,b,c,d,e,f in love.event.poll() do
if name == "quit" then
if not love.quit or not love.quit() then
return a
end
end
love.handlers[name](a,b,c,d,e,f)
end
end
-- Update dt, as we'll be passing it to update
if love.timer then
love.timer.step()
dt = love.timer.getDelta()
end
-- Call update and draw
if love.update then love.update(dt) end -- will pass 0 if love.timer is disabled
if love.graphics and love.graphics.isActive() and (_ShouldDraw or _ForceDraw) then
love.graphics.setCanvas()
love.graphics.origin()
love.graphics.setColor(255,255,255)
love.graphics.draw(_ScreenCanvas, _ScreenX,_ScreenY, 0, _ScreenScaleX,_ScreenScaleY)
--love.graphics.points(1,1,_ScreenWidth,_ScreenHeight)
love.graphics.present()
love.graphics.setCanvas(_ScreenCanvas)
love.graphics.translate(_ScreenTX,_ScreenTY)
_ShouldDraw = false
end
if love.timer then love.timer.sleep(0.001) end
end
end
|
Fixed editorsheet scalling being leanier
|
Fixed editorsheet scalling being leanier
|
Lua
|
mit
|
RamiLego4Game/LIKO-12
|
b6306b14a96c214ebd04f88c9f18d2f9a5660478
|
mod_webpresence/mod_webpresence.lua
|
mod_webpresence/mod_webpresence.lua
|
module:depends("http");
local jid_split = require "util.jid".prepped_split;
local function require_resource(name)
local icon_path = module:get_option_string("presence_icons", "icons");
local f, err = module:load_resource(icon_path.."/"..name);
if f then
return f:read("*a");
end
module:log("warn", "Failed to open image file %s", icon_path..name);
return "";
end
local statuses = { online = {}, away = {}, xa = {}, dnd = {}, chat = {}, offline = {} };
for status, _ in pairs(statuses) do
statuses[status].image = { status_code = 200, headers = { content_type = "image/png" },
body = require_resource("status_"..status..".png") };
statuses[status].text = { status_code = 200, headers = { content_type = "plain/text" },
body = status };
end
local function handle_request(event, path)
local status;
local jid, type = path:match("([^/]+)/?(.*)$");
if jid then
local user, host = jid_split(jid);
if host and not user then
user, host = host, event.request.headers.host;
if host then host = host:gsub(":%d+$", ""); end
end
if user and host then
local user_sessions = hosts[host] and hosts[host].sessions[user];
if user_sessions then
status = user_sessions.top_resources[1];
if status and status.presence then
status = status.presence:child_with_name("show");
if not status then
status = "online";
else
status = status:get_text();
end
end
end
end
end
status = status or "offline";
return (type and type == "text") and statuses[status].text or statuses[status].image;
end
module:provides("http", {
default_path = "/status";
route = {
["GET /*"] = handle_request;
};
});
|
module:depends("http");
local jid_split = require "util.jid".prepped_split;
local b64 = require "util.encodings".base64.encode;
local sha1 = require "util.hashes".sha1;
local function require_resource(name)
local icon_path = module:get_option_string("presence_icons", "icons");
local f, err = module:load_resource(icon_path.."/"..name);
if f then
return f:read("*a");
end
module:log("warn", "Failed to open image file %s", icon_path..name);
return "";
end
local statuses = { online = {}, away = {}, xa = {}, dnd = {}, chat = {}, offline = {} };
--[[for status, _ in pairs(statuses) do
statuses[status].image = { status_code = 200, headers = { content_type = "image/png" },
body = require_resource("status_"..status..".png") };
statuses[status].text = { status_code = 200, headers = { content_type = "text/plain" },
body = status };
end]]
local function handle_request(event, path)
local status, message;
local jid, type = path:match("([^/]+)/?(.*)$");
if jid then
local user, host = jid_split(jid);
if host and not user then
user, host = host, event.request.headers.host;
if host then host = host:gsub(":%d+$", ""); end
end
if user and host then
local user_sessions = hosts[host] and hosts[host].sessions[user];
if user_sessions then
status = user_sessions.top_resources[1];
if status and status.presence then
message = status.presence:child_with_name("status");
status = status.presence:child_with_name("show");
if not status then
status = "online";
else
status = status:get_text();
end
if message then
message = message:get_text();
end
end
end
end
end
status = status or "offline";
if type == "" then type = "image" end;
if type == "image" then
statuses[status].image = { status_code = 200, headers = { content_type = "image/png" },
body = require_resource("status_"..status..".png") };
elseif type == "html" then
statuses[status].html = { status_code = 200, headers = { content_type = "text/html" },
body = [[<div id="]]..sha1(jid,true)..[[_status" class="xmpp_status">]]..
[[<img id="]]..sha1(jid,true)..[[_img" class="xmpp_status_image" ]]..
[[src="data:image/png;base64,]]..
b64(require_resource("status_"..status..".png"))..[[">]]..
[[<span id="]]..sha1(jid,true)..[[_name" ]]..
[[class="xmpp_status_name">]]..status..[[</span>]]..
(message and [[<span id="]]..sha1(jid,true)..[[_message" ]]..
[[class="xmpp_status_message">]]..message..[[</span>]] or "")..
[[</div>]] };
elseif type == "text" then
statuses[status].text = { status_code = 200, headers = { content_type = "text/plain" },
body = status };
elseif type == "message" then
statuses[status].message = { status_code = 200, headers = { content_type = "text/plain" },
body = (message and message or "") };
end
return statuses[status][type];
end
module:provides("http", {
default_path = "/status";
route = {
["GET /*"] = handle_request;
};
});
|
mod_webpresence: fixed text notation, added html, added status message output
|
mod_webpresence: fixed text notation, added html, added status message output
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
a8525e575bd56cce7a6a635cc3e0f827593f5e11
|
packages/pullquote.lua
|
packages/pullquote.lua
|
SILE.require("packages/color")
SILE.require("packages/raiselower")
SILE.require("packages/rebox")
SILE.registerCommand("pullquote:font", function (_, _)
end, "The font chosen for the pullquote environment")
SILE.registerCommand("pullquote:author-font", function (_, _)
SILE.settings.set("font.style", "italic")
end, "The font style with which to typeset the author attribution.")
SILE.registerCommand("pullquote:mark-font", function (_, _)
SILE.settings.set("font.family", "Libertinus Serif")
end, "The font from which to pull the quotation marks.")
local typesetMark = function (open, setback, scale, color, mark)
SILE.settings.temporarily(function ()
SILE.call("pullquote:mark-font")
SILE.call("raise", { height = -(open and (scale+1) or scale) .. "ex" }, function ()
SILE.settings.set("font.size", SILE.settings.get("font.size")*scale)
SILE.call("color", { color = color }, function ()
if open then
SILE.typesetter:pushGlue({ width = -setback })
SILE.call("rebox", { width = setback, height = 0 }, { mark })
else
SILE.typesetter:pushGlue(SILE.nodefactory.hfillglue())
local hbox = SILE.call("hbox", {}, { mark })
table.remove(SILE.typesetter.state.nodes) -- steal it back
SILE.typesetter:pushGlue({ width = setback - hbox.width })
SILE.call("rebox", { width = hbox.width, height = 0 }, { mark })
SILE.typesetter:pushGlue({ width = -setback })
end
end)
end)
end)
end
SILE.registerCommand("pullquote", function (options, content)
local author = options.author or nil
local scale = options.scale or 3
local color = options.color or "#999999"
SILE.settings.temporarily(function ()
SILE.call("pullquote:font")
local setback = SU.cast("length", options.setback or "2em"):absolute()
SILE.settings.set("document.rskip", SILE.nodefactory.glue(setback))
SILE.settings.set("document.lskip", SILE.nodefactory.glue(setback))
SILE.settings.set("current.parindent", SILE.nodefactory.glue())
typesetMark(true, setback, scale, color, "“")
SILE.process(content)
typesetMark(false, setback, scale, color, "”")
if author then
SILE.settings.temporarily(function ()
SILE.typesetter:leaveHmode()
SILE.call("pullquote:author-font")
SILE.call("raggedleft", {}, function ()
SILE.typesetter:typeset("— " .. author)
end)
end)
else
SILE.call("par")
end
end)
end, "Typesets its contents in a formatted blockquote with decorative quotation\
marks in the margins.")
return { documentation = [[\begin{document}
The \code{pullquote} command formats longer quotations in an indented
blockquote block with decorative quotation marks in the margins.
Here is some text set in a pullquote environment:
\begin[author=Anatole France]{pullquote}
An education is not how much you have committed to memory, or even how much you
know. It is being able to differentiate between what you do know and what you
do not know.
\end{pullquote}
Optional values are available for:
• \code{author} to add an attribution line\par
• \code{setback} to set the bilateral margins around the block\par
• \code{color} to change the color of the quote marks\par
• \code{scale} to change the relative size of the quote marks\par
If you want to specify what font the pullquote environment should use, you
can redefine the \code{pullquote:font} command. By default it will be the same
as the surrounding document. The font style used for the attribution line
can likewise be set using \code{pullquote:author-font} and the font used for
the quote marks can be set using \code{pullquote:mark-font}.
\end{document}]] }
|
SILE.require("packages/color")
SILE.require("packages/raiselower")
SILE.require("packages/rebox")
SILE.registerCommand("pullquote:font", function (_, _)
end, "The font chosen for the pullquote environment")
SILE.registerCommand("pullquote:author-font", function (_, _)
SILE.settings.set("font.style", "italic")
end, "The font style with which to typeset the author attribution.")
SILE.registerCommand("pullquote:mark-font", function (_, _)
SILE.settings.set("font.family", "Libertinus Serif")
end, "The font from which to pull the quotation marks.")
local typesetMark = function (open, setback, scale, color, mark)
SILE.settings.temporarily(function ()
SILE.call("pullquote:mark-font")
SILE.call("raise", { height = -(open and (scale+1) or scale) .. "ex" }, function ()
SILE.settings.set("font.size", SILE.settings.get("font.size")*scale)
SILE.call("color", { color = color }, function ()
if open then
SILE.typesetter:pushGlue({ width = -setback })
SILE.call("rebox", { width = setback, height = 0 }, { mark })
else
SILE.typesetter:pushGlue(SILE.nodefactory.hfillglue())
local hbox = SILE.call("hbox", {}, { mark })
table.remove(SILE.typesetter.state.nodes) -- steal it back
SILE.typesetter:pushGlue({ width = setback - hbox.width })
SILE.call("rebox", { width = hbox.width, height = 0 }, { mark })
SILE.typesetter:pushGlue({ width = -setback })
end
end)
end)
end)
end
SILE.registerCommand("pullquote", function (options, content)
local author = options.author or nil
local scale = options.scale or 3
local color = options.color or "#999999"
SILE.settings.temporarily(function ()
SILE.call("pullquote:font")
local setback = SU.cast("length", options.setback or "2em"):absolute()
SILE.settings.set("document.rskip", SILE.nodefactory.glue(setback))
SILE.settings.set("document.lskip", SILE.nodefactory.glue(setback))
SILE.call("noindent")
typesetMark(true, setback, scale, color, "“")
SILE.call("indent")
SILE.process(content)
typesetMark(false, setback, scale, color, "”")
if author then
SILE.settings.temporarily(function ()
SILE.typesetter:leaveHmode()
SILE.call("pullquote:author-font")
SILE.call("raggedleft", {}, function ()
SILE.typesetter:typeset("— " .. author)
end)
end)
else
SILE.call("par")
end
end)
end, "Typesets its contents in a formatted blockquote with decorative quotation\
marks in the margins.")
return { documentation = [[\begin{document}
The \code{pullquote} command formats longer quotations in an indented
blockquote block with decorative quotation marks in the margins.
Here is some text set in a pullquote environment:
\begin[author=Anatole France]{pullquote}
An education is not how much you have committed to memory, or even how much you
know. It is being able to differentiate between what you do know and what you
do not know.
\end{pullquote}
Optional values are available for:
• \code{author} to add an attribution line\par
• \code{setback} to set the bilateral margins around the block\par
• \code{color} to change the color of the quote marks\par
• \code{scale} to change the relative size of the quote marks\par
If you want to specify what font the pullquote environment should use, you
can redefine the \code{pullquote:font} command. By default it will be the same
as the surrounding document. The font style used for the attribution line
can likewise be set using \code{pullquote:author-font} and the font used for
the quote marks can be set using \code{pullquote:mark-font}.
\end{document}]] }
|
fix(packages): Fix indentation of second paragraph in pullquotes
|
fix(packages): Fix indentation of second paragraph in pullquotes
|
Lua
|
mit
|
alerque/sile,alerque/sile,alerque/sile,alerque/sile
|
84774f812cf76569248f383d09e7baab42922bbe
|
logout-menu-widget/logout-menu.lua
|
logout-menu-widget/logout-menu.lua
|
-------------------------------------------------
-- Logout Menu Widget for Awesome Window Manager
-- More details could be found here:
-- https://github.com/streetturtle/awesome-wm-widgets/tree/master/logout-menu-widget
-- @author Pavel Makhov
-- @copyright 2020 Pavel Makhov
-------------------------------------------------
local awful = require("awful")
local wibox = require("wibox")
local spawn = require("awful.spawn")
local gears = require("gears")
local beautiful = require("beautiful")
local HOME = os.getenv('HOME')
local ICON_DIR = HOME .. '/.config/awesome/awesome-wm-widgets/logout-menu-widget/icons/'
local logout_menu_widget = wibox.widget {
{
image = ICON_DIR .. 'power_w.svg',
resize = true,
widget = wibox.widget.imagebox,
},
margins = 4,
layout = wibox.container.margin
}
local popup = awful.popup {
ontop = true,
visible = false,
shape = function(cr, width, height)
gears.shape.rounded_rect(cr, width, height, 4)
end,
border_width = 1,
border_color = beautiful.bg_focus,
maximum_width = 400,
offset = { y = 5 },
widget = {}
}
local rows = { layout = wibox.layout.fixed.vertical }
local function worker(user_args)
local args = user_args or {}
local font = args.font or beautiful.font
local onlogout = args.onlogout or function () awesome.quit() end
local onlock = args.onlock or function() awful.spawn.with_shell("i3lock") end
local onreboot = args.onreboot or function() awful.spawn.with_shell("reboot") end
local onsuspend = args.onsuspend or function() awful.spawn.with_shell("systemctl suspend") end
local onpoweroff = args.onpoweroff or function() awful.spawn.with_shell("shutdown now") end
local menu_items = {
{ name = 'Log out', icon_name = 'log-out.svg', command = onlogout },
{ name = 'Lock', icon_name = 'lock.svg', command = onlock },
{ name = 'Reboot', icon_name = 'refresh-cw.svg', command = onreboot },
{ name = 'Suspend', icon_name = 'moon.svg', command = onsuspend },
{ name = 'Power off', icon_name = 'power.svg', command = onpoweroff },
}
for _, item in ipairs(menu_items) do
local row = wibox.widget {
{
{
{
image = ICON_DIR .. item.icon_name,
resize = false,
widget = wibox.widget.imagebox
},
{
text = item.name,
font = font,
widget = wibox.widget.textbox
},
spacing = 12,
layout = wibox.layout.fixed.horizontal
},
margins = 8,
layout = wibox.container.margin
},
bg = beautiful.bg_normal,
widget = wibox.container.background
}
row:connect_signal("mouse::enter", function(c) c:set_bg(beautiful.bg_focus) end)
row:connect_signal("mouse::leave", function(c) c:set_bg(beautiful.bg_normal) end)
local old_cursor, old_wibox
row:connect_signal("mouse::enter", function()
local wb = mouse.current_wibox
old_cursor, old_wibox = wb.cursor, wb
wb.cursor = "hand1"
end)
row:connect_signal("mouse::leave", function()
if old_wibox then
old_wibox.cursor = old_cursor
old_wibox = nil
end
end)
row:buttons(awful.util.table.join(awful.button({}, 1, function()
popup.visible = not popup.visible
item.command()
end)))
table.insert(rows, row)
end
popup:setup(rows)
logout_menu_widget:buttons(
awful.util.table.join(
awful.button({}, 1, function()
if popup.visible then
popup.visible = not popup.visible
else
popup:move_next_to(mouse.current_widget_geometry)
end
end)
)
)
return logout_menu_widget
end
return setmetatable(logout_menu_widget, { __call = function(_, ...) return worker(...) end })
|
-------------------------------------------------
-- Logout Menu Widget for Awesome Window Manager
-- More details could be found here:
-- https://github.com/streetturtle/awesome-wm-widgets/tree/master/logout-menu-widget
-- @author Pavel Makhov
-- @copyright 2020 Pavel Makhov
-------------------------------------------------
local awful = require("awful")
local wibox = require("wibox")
local gears = require("gears")
local beautiful = require("beautiful")
local HOME = os.getenv('HOME')
local ICON_DIR = HOME .. '/.config/awesome/awesome-wm-widgets/logout-menu-widget/icons/'
local logout_menu_widget = wibox.widget {
{
image = ICON_DIR .. 'power_w.svg',
resize = true,
widget = wibox.widget.imagebox,
},
margins = 4,
layout = wibox.container.margin
}
local popup = awful.popup {
ontop = true,
visible = false,
shape = function(cr, width, height)
gears.shape.rounded_rect(cr, width, height, 4)
end,
border_width = 1,
border_color = beautiful.bg_focus,
maximum_width = 400,
offset = { y = 5 },
widget = {}
}
local rows = { layout = wibox.layout.fixed.vertical }
local function worker(user_args)
local args = user_args or {}
local font = args.font or beautiful.font
local onlogout = args.onlogout or function () awesome.quit() end
local onlock = args.onlock or function() awful.spawn.with_shell("i3lock") end
local onreboot = args.onreboot or function() awful.spawn.with_shell("reboot") end
local onsuspend = args.onsuspend or function() awful.spawn.with_shell("systemctl suspend") end
local onpoweroff = args.onpoweroff or function() awful.spawn.with_shell("shutdown now") end
local menu_items = {
{ name = 'Log out', icon_name = 'log-out.svg', command = onlogout },
{ name = 'Lock', icon_name = 'lock.svg', command = onlock },
{ name = 'Reboot', icon_name = 'refresh-cw.svg', command = onreboot },
{ name = 'Suspend', icon_name = 'moon.svg', command = onsuspend },
{ name = 'Power off', icon_name = 'power.svg', command = onpoweroff },
}
for _, item in ipairs(menu_items) do
local row = wibox.widget {
{
{
{
image = ICON_DIR .. item.icon_name,
resize = false,
widget = wibox.widget.imagebox
},
{
text = item.name,
font = font,
widget = wibox.widget.textbox
},
spacing = 12,
layout = wibox.layout.fixed.horizontal
},
margins = 8,
layout = wibox.container.margin
},
bg = beautiful.bg_normal,
widget = wibox.container.background
}
row:connect_signal("mouse::enter", function(c) c:set_bg(beautiful.bg_focus) end)
row:connect_signal("mouse::leave", function(c) c:set_bg(beautiful.bg_normal) end)
local old_cursor, old_wibox
row:connect_signal("mouse::enter", function()
local wb = mouse.current_wibox
old_cursor, old_wibox = wb.cursor, wb
wb.cursor = "hand1"
end)
row:connect_signal("mouse::leave", function()
if old_wibox then
old_wibox.cursor = old_cursor
old_wibox = nil
end
end)
row:buttons(awful.util.table.join(awful.button({}, 1, function()
popup.visible = not popup.visible
item.command()
end)))
table.insert(rows, row)
end
popup:setup(rows)
logout_menu_widget:buttons(
awful.util.table.join(
awful.button({}, 1, function()
if popup.visible then
popup.visible = not popup.visible
else
popup:move_next_to(mouse.current_widget_geometry)
end
end)
)
)
return logout_menu_widget
end
return setmetatable(logout_menu_widget, { __call = function(_, ...) return worker(...) end })
|
[logout-menu] luacheck fix
|
[logout-menu] luacheck fix
|
Lua
|
mit
|
streetturtle/awesome-wm-widgets,streetturtle/awesome-wm-widgets
|
5e017be9ffe280bc89a65306ccb09a8a0139098d
|
lua/philosophers.lua
|
lua/philosophers.lua
|
local Cosy = require "cosy.helper"
local function add (model)
model.number = model.number () + 1
local number = model.number ()
print ("Adding philosopher ${number}." % {
number = number
})
local name = "#${n}" % { n = number }
local next_name = "#${n}" % { n = 1 }
-- Update all positions:
for _, x in pairs (model) do
if Cosy.is_instance (x) then
if Cosy.is (x, model.think_type) then
think_position (x)
elseif Cosy.is (x, model.wait_type) then
wait_position (x)
elseif Cosy.is (x, model.eat_type) then
eat_position (x)
elseif Cosy.is (x, model.fork_type) then
fork_position (x)
elseif Cosy.is (x, model.left_type) then
left_position (x)
elseif Cosy.is (x, model.right_type) then
right_position (x)
elseif Cosy.is (x, model.release_type) then
release_position (x)
end
end
end
-- Compute useful things:
local wait_next
local fork_next
for _, place in pairs (model) do
if Cosy.is (place, model.wait_type)
and place.i () == 1 then
wait_next = place
elseif Cosy.is (place, model.fork_type)
and place.i () == 1 then
fork_next = place
end
end
-- Places:
local think = Cosy.instantiate (model, model.think_type, {
name = name .. " is thinking",
marking = true,
i = number,
})
local wait = Cosy.instantiate (model, model.wait_type, {
name = name .. " is waiting",
marking = false,
i = number,
})
local eat = Cosy.instantiate (model, model.eat_type, {
name = name .. " is eating",
marking = false,
i = number,
})
local fork = Cosy.instantiate (model, model.fork_type, {
name = name .. "'s fork",
marking = true,
i = number,
})
-- Transitions:
local left = Cosy.instantiate (model, model.left_type, {
name = name .. " takes his fork",
i = number,
})
Cosy.instantiate (model, model.arc_type, {
source = think,
target = left,
})
Cosy.instantiate (model, model.arc_type, {
source = fork,
target = left,
})
Cosy.instantiate (model, model.arc_type, {
source = left,
target = wait,
})
local right = Cosy.instantiate (model, model.right_type, {
name = name .. " takes " .. next_name .. "'s fork",
i = number,
})
Cosy.instantiate (model, model.arc_type, {
source = wait,
target = right,
})
Cosy.instantiate (model, model.arc_type, {
source = wait_next,
target = right,
})
Cosy.instantiate (model, model.arc_type, {
source = right,
target = eat,
})
local release = Cosy.instantiate (model, model.release_type, {
name = name .. " releases forks",
i = number,
})
Cosy.instantiate (model, model.arc_type, {
source = eat,
target = release,
})
Cosy.instantiate (model, model.arc_type, {
source = release,
target = think,
})
Cosy.instantiate (model, model.arc_type, {
source = release,
target = fork,
})
Cosy.instantiate (model, model.arc_type, {
source = release,
target = fork_next,
})
-- Arcs that pointed to the first philosophers must also
-- be updated:
for _, arc in pairs (model) do
if Cosy.is_arc (arc)
and Cosy.is (Cosy.source (arc), model.release_type)
and Cosy.is (Cosy.target (arc), model.fork_type)
and Cosy.source (arc).i == number - 1
and Cosy.target (arc).i == 1 then
arc.target = fork
elseif Cosy.is_arc (arc)
and Cosy.is (Cosy.source (arc), model.wait_type)
and Cosy.is (Cosy.target (arc), model.right_type)
and Cosy.source (arc).i == 1
and Cosy.target (arc).i == number - 1 then
arc.source = wait
end
end
end
local model = Cosy.resource ("cosyverif.io/philosophers")
model.number = 0
-- Create types:
model.place_type = {}
model.transition_type = {}
model.arc_type = {}
model.think_type = model.place_type * {}
Cosy.set_position (model.think_type, function (x)
local n = model.number ()
local i = x.i ()
return i and "${angle}:${distance}" % {
angle = 360 / n * i,
distance = 300,
}
end)
model.wait_type = model.place_type * {}
Cosy.set_position (model.wait_type, function (x)
local n = model.number ()
local i = x.i ()
return i and "${angle}:${distance}" % {
angle = 360 / n * i,
distance = 200,
}
end)
model.eat_type = model.place_type * {}
Cosy.set_position (model.eat_type, function (x)
local n = model.number ()
local i = x.i ()
return i and "${angle}:${distance}" % {
angle = 360 / n * i,
distance = 100,
}
end)
model.fork_type = model.place_type * {}
Cosy.set_position (model.fork_type, function (x)
local n = model.number ()
local i = x.i ()
return i and "${angle}:${distance}" % {
angle = 360 / n * i * 1.5,
distance = 250,
}
end)
model.left_type = model.transition_type * {}
Cosy.set_position (model.left_type, function (x)
local n = model.number ()
local i = x.i ()
return i and "${angle}:${distance}" % {
angle = 360 / n * i,
distance = 250,
}
end)
model.right_type = model.transition_type * {}
Cosy.set_position (model.right_type, function (x)
local n = model.number ()
local i = x.i ()
return i and "${angle}:${distance}" % {
angle = 360 / n * i,
distance = 150,
}
end)
model.release_type = model.transition_type * {}
Cosy.set_position (model.release_type, function (x)
local n = model.number ()
local i = x.i ()
return i and "${angle}:${distance}" % {
angle = 360 / n * i,
distance = 50,
}
end)
-- Add two philosophers:
add (model)
add (model)
model.insert = Cosy.instantiate (model, model.transition_type, {
name = "+1"
})
model.stop = Cosy.instantiate (model, model.transition_type, {
name = "stop"
})
Data.on_write.philosophers = function (target)
if model.insert <= target and Cosy.is_selected (model.insert) then
Cosy.deselect (model.insert)
add (model)
elseif model.stop <= target and Cosy.is_selected (model.stop) then
Cosy.remove (model.insert)
Cosy.remove (model.stop)
Cosy.stop ()
end
end
|
local Cosy = require "cosy"
--[[
Cosy.configure_server ("cosyverif.io", {
www = "www.cosyverif.io",
rest = "rest.cosyverif.io",
websocket = "ws.cosyverif.io",
username = "alban",
password = "toto",
})
--]]
local model = Cosy.resource ("cosyverif.io/philosophers")
model.number = 0
-- Graph types:
model.vertex_type = Cosy.new_type ()
model.link_type = Cosy.new_type ()
Cosy.hide (model.vertex_type)
Cosy.hide (model.link_type)
-- Petri net types:
model.place_type = Cosy.new_type (model.vertex_type)
model.transition_type = Cosy.new_type (model.vertex_type)
model.arc_type = Cosy.new_type (model.link_type)
Cosy.hide (model.place_type)
Cosy.hide (model.transition_type)
function Cosy.is_place (x)
return model.place_type < x
end
function Cosy.is_transition (x)
return model.transition_type < x
end
function Cosy.is_arc (x)
return model.arc_type < x
end
-- Philosophers types:
model.think_type = Cosy.new_type (model.place_type)
Cosy.set_position (model.think_type, function (x)
local n = model.number ()
local i = x.i ()
return i and "${angle}:${distance}" % {
angle = 360 / n * i,
distance = 300,
}
end)
model.wait_type = Cosy.new_type (model.place_type)
Cosy.set_position (model.wait_type, function (x)
local n = model.number ()
local i = x.i ()
return i and "${angle}:${distance}" % {
angle = 360 / n * i,
distance = 200,
}
end)
model.eat_type = Cosy.new_type (model.place_type)
Cosy.set_position (model.eat_type, function (x)
local n = model.number ()
local i = x.i ()
return i and "${angle}:${distance}" % {
angle = 360 / n * i,
distance = 100,
}
end)
model.fork_type = Cosy.new_type (model.place_type)
Cosy.set_position (model.fork_type, function (x)
local n = model.number ()
local i = x.i ()
return i and "${angle}:${distance}" % {
angle = 360 / n * i * 1.5,
distance = 250,
}
end)
model.left_type = Cosy.new_type (model.transition_type)
Cosy.set_position (model.left_type, function (x)
local n = model.number ()
local i = x.i ()
return i and "${angle}:${distance}" % {
angle = 360 / n * i,
distance = 250,
}
end)
model.right_type = Cosy.new_type (model.transition_type)
Cosy.set_position (model.right_type, function (x)
local n = model.number ()
local i = x.i ()
return i and "${angle}:${distance}" % {
angle = 360 / n * i,
distance = 150,
}
end)
model.release_type = Cosy.new_type (model.transition_type)
Cosy.set_position (model.release_type, function (x)
local n = model.number ()
local i = x.i ()
return i and "${angle}:${distance}" % {
angle = 360 / n * i,
distance = 50,
}
end)
function Cosy.create (source, link_type, target_type, data)
ignore (link_type, target_type)
local place_type = model.place_type
local transition_type = model.transition_type
local arc_type = model.arc_type
if place_type < source then
model [#model + 1] = Cosy.new_instance (transition_type, data)
elseif transition_type < source then
model [#model + 1] = Cosy.new_instance (place_type, data)
else
assert (false)
end
model [#model + 1] = Cosy.new_instance (arc_type, {
source = source,
target = target,
})
return model [#model - 1]
end
local function add (model)
model.number = model.number () + 1
local number = model.number ()
print ("Adding philosopher ${number}." % {
number = number
})
local name = "#${n}" % { n = number }
local next_name = "#${n}" % { n = 1 }
-- Compute useful things:
local wait_next
local fork_next
for _, place in pairs (model) do
if model.wait_type < place
and place.i () == 1 then
wait_next = place
elseif model.fork_type < place
and place.i () == 1 then
fork_next = place
end
end
-- Places:
local think = Cosy.insert (model, Cosy.new_instance (model.think_type, {
name = name .. " is thinking",
marking = true,
i = number,
}))
local wait = Cosy.insert (model, Cosy.new_instance (model.wait_type, {
name = name .. " is waiting",
marking = false,
i = number,
}))
local eat = Cosy.insert (model, Cosy.new_instance (model.eat_type, {
name = name .. " is eating",
marking = false,
i = number,
}))
local fork = Cosy.insert (model, Cosy.new_instance (model.fork_type, {
name = name .. "'s fork",
marking = true,
i = number,
}))
-- Transitions:
local left = Cosy.insert (model, Cosy.new_instance (model.left_type, {
name = name .. " takes his fork",
i = number,
}))
Cosy.insert (model, Cosy.new_instance (model.arc_type, {
source = think,
target = left,
}))
Cosy.insert (model, Cosy.new_instance (model.arc_type, {
source = fork,
target = left,
}))
Cosy.insert (model, Cosy.new_instance (model.arc_type, {
source = left,
target = wait,
}))
local right = Cosy.insert (model, Cosy.new_instance (model.right_type, {
name = name .. " takes " .. next_name .. "'s fork",
i = number,
}))
Cosy.insert (model, Cosy.new_instance (model.arc_type, {
source = wait,
target = right,
}))
Cosy.new_instance (model.arc_type, {
source = wait_next,
target = right,
})
Cosy.insert (model, Cosy.new_instance (model.arc_type, {
source = right,
target = eat,
}))
local release = Cosy.insert (model, Cosy.new_instance (model.release_type, {
name = name .. " releases forks",
i = number,
}))
Cosy.insert (model, Cosy.new_instance (model.arc_type, {
source = eat,
target = release,
}))
Cosy.insert (model, Cosy.new_instance (model.arc_type, {
source = release,
target = think,
}))
Cosy.insert (model, Cosy.new_instance (model.arc_type, {
source = release,
target = fork,
}))
Cosy.insert (model, Cosy.new_instance (model.arc_type, {
source = release,
target = fork_next,
}))
-- Arcs that pointed to the first philosophers must also
-- be updated:
for _, arc in pairs (model) do
if Cosy.is_arc (arc)
and Cosy.is (Cosy.source (arc), model.release_type)
and Cosy.is (Cosy.target (arc), model.fork_type)
and Cosy.source (arc).i == number - 1
and Cosy.target (arc).i == 1 then
arc.target = fork
elseif Cosy.is_arc (arc)
and Cosy.is (Cosy.source (arc), model.wait_type)
and Cosy.is (Cosy.target (arc), model.right_type)
and Cosy.source (arc).i == 1
and Cosy.target (arc).i == number - 1 then
arc.source = wait
end
end
end
model.button_type = Cosy.new_type (model.transition_type)
model.insert = Cosy.new_instance (model.button_type, {
name = "+1"
})
model.stop = Cosy.new_instance (model.button_type, {
name = "stop"
})
-- Add two philosophers:
add (model)
add (model)
Cosy.on_write( function (target)
if model.insert <= target and Cosy.is_selected (model.insert) then
Cosy.deselect (model.insert)
add (model)
elseif model.stop <= target and Cosy.is_selected (model.stop) then
Cosy.remove (model.insert)
Cosy.remove (model.stop)
Cosy.stop ()
end
end)
|
Fix philosophers script.
|
Fix philosophers script.
|
Lua
|
mit
|
CosyVerif/webclient,CosyVerif/webclient
|
f672a9d10bb33617a4c9140abeaf6ba7fcc8f512
|
sessions.lua
|
sessions.lua
|
local check_type = require("textadept-nim.utils").check_type
local errortips = require("textadept-nim.errortips")
local parse_errors = errortips.parse_errors
local error_handler = errortips.error_handler
local get_project = require("textadept-nim.project").detect_project
local consts = require("textadept-nim.constants")
local nimsuggest_executable = consts.nimsuggest_exe
local _M = {}
-- There is placed active sessions
_M.active = {}
-- Filename-to-sessionname association
_M.session_of = {}
function _M:get_handle(filename)
-- Creates new session for file if it isn't exist and returns
-- handle for the session
check_type("string", filename)
local session_name = _M.session_of[filename]
if session_name == nil or _M.active[session_name] == nil
then
local project = get_project(filename)
session_name = project.root
if _M.active[session_name] == nil
then
_M.active[session_name] = {name = session_name, project = project}
else
_M.active[session_name].project = project
end
_M.session_of[filename] = session_name
end
local session = _M.active[session_name]
if session.handle == nil or
session.handle:status() ~= "running"
then
-- create new session
local current_dir = session_name:match("^(.+)[/\\][^/\\]+$") or "."
local current_handler = function(code)
--Hints mistakenly treated as errors
if code:match("^Hint.*") then return end
error_handler(_M.active[session_name], code)
end
if consts.VERMAGIC < 807 then
session.handle = spawn(nimsuggest_executable.." --stdin --tester --debug --v2 "..
session_name, current_dir, current_handler,
parse_errors, current_handler)
else
session.handle = spawn(nimsuggest_executable.." --stdin --tester --debug --v2 "..
session_name, current_dir, nil, current_handler,
parse_errors, current_handler)
end
local ans = ""
-- Skip until eof
repeat
ans = session.handle:read()
until ans == nil or ans:sub(1,5) == "!EOF!"
if session.handle == nil or
session.handle:status() ~= "running"
then
error("Cann't start nimsuggest!")
end
end
if session.files == nil
then
session.files = {}
end
session.files[filename] = true
return session.handle
end
function _M:detach(filename)
-- Stops nimsuggest session for filename if no other file uses it
check_type("string", filename)
local session_name = _M.session_of[filename]
if session_name == nil
then
return
end
_M.session_of[filename] = nil
local session = _M.active[session_name]
if session ~= nil
then
session.files[filename] = nil
if #session.files == 0
then
if session.handle ~= nil and session.handle:status() ~= "terminated"
then
session.handle:write("quit\n\n")
session.handle:close()
end
_M.active[session_name] = nil
end
end
end
function _M:request(command, filename)
-- Requesting nimsuggest to do command and returns
-- parsed answer as a structure
local nimhandle = _M:get_handle(filename)
nimhandle:write(command.."\n")
local message_list = {}
repeat
local answer = nimhandle:read()
if answer:sub(1,5) == "!EOF!" then
break
end
table.insert(message_list, answer)
until answer == nil
return message_list
end
function _M:stop_all()
-- Stops all nimsuggest sessions.
-- Use at exit or reset only
for file, session in pairs(_M.active)
do
if session.handle ~= nil and session.handle:status() ~= "terminated"
then
session.handle:write("quit\n\n")
session.handle:close()
end
end
_M.active = nil
_M.session_of = nil
end
return _M
|
local check_type = require("textadept-nim.utils").check_type
local errortips = require("textadept-nim.errortips")
local parse_errors = errortips.parse_errors
local error_handler = errortips.error_handler
local get_project = require("textadept-nim.project").detect_project
local consts = require("textadept-nim.constants")
local nimsuggest_executable = consts.nimsuggest_exe
local _M = {}
-- There is placed active sessions
_M.active = {}
-- Filename-to-sessionname association
_M.session_of = {}
function _M:get_handle(filename)
-- Creates new session for file if it isn't exist and returns
-- handle for the session
check_type("string", filename)
local session_name = _M.session_of[filename]
if session_name == nil or _M.active[session_name] == nil
then
local project = get_project(filename)
session_name = project.root
if _M.active[session_name] == nil
then
_M.active[session_name] = {name = session_name, project = project}
else
_M.active[session_name].project = project
end
_M.session_of[filename] = session_name
end
local session = _M.active[session_name]
if session.handle == nil or
session.handle:status() ~= "running"
then
-- create new session
local current_dir = session_name:match("^(.+)[/\\][^/\\]+$") or "."
local current_handler = function(code)
--Hints mistakenly treated as errors
if code:match("^Hint.*") then return end
error_handler(_M.active[session_name], code)
end
if consts.VERMAGIC < 807 then
session.handle = spawn(nimsuggest_executable.." --stdin --tester --debug --v2 "..
session_name, current_dir, current_handler,
parse_errors, current_handler)
elseif consts.VERMAGIC < 1002 then
session.handle = spawn(nimsuggest_executable.." --stdin --tester --debug --v2 "..
session_name, current_dir, nil, current_handler,
parse_errors, current_handler)
else
session.handle = os.spawn(nimsuggest_executable.." --stdin --tester --debug --v2 "..
session_name, current_dir, nil, current_handler,
parse_errors, current_handler)
end
local ans = ""
-- Skip until eof
repeat
ans = session.handle:read()
until ans == nil or ans:sub(1,5) == "!EOF!"
if session.handle == nil or
session.handle:status() ~= "running"
then
error("Cann't start nimsuggest!")
end
end
if session.files == nil
then
session.files = {}
end
session.files[filename] = true
return session.handle
end
function _M:detach(filename)
-- Stops nimsuggest session for filename if no other file uses it
check_type("string", filename)
local session_name = _M.session_of[filename]
if session_name == nil
then
return
end
_M.session_of[filename] = nil
local session = _M.active[session_name]
if session ~= nil
then
session.files[filename] = nil
if #session.files == 0
then
if session.handle ~= nil and session.handle:status() ~= "terminated"
then
session.handle:write("quit\n\n")
session.handle:close()
end
_M.active[session_name] = nil
end
end
end
function _M:request(command, filename)
-- Requesting nimsuggest to do command and returns
-- parsed answer as a structure
local nimhandle = _M:get_handle(filename)
nimhandle:write(command.."\n")
local message_list = {}
repeat
local answer = nimhandle:read()
if answer:sub(1,5) == "!EOF!" then
break
end
table.insert(message_list, answer)
until answer == nil
return message_list
end
function _M:stop_all()
-- Stops all nimsuggest sessions.
-- Use at exit or reset only
for file, session in pairs(_M.active)
do
if session.handle ~= nil and session.handle:status() ~= "terminated"
then
session.handle:write("quit\n\n")
session.handle:close()
end
end
_M.active = nil
_M.session_of = nil
end
return _M
|
Fixes spawn command for textadept 10.2+
|
Fixes spawn command for textadept 10.2+
|
Lua
|
mit
|
xomachine/textadept-nim
|
1e17e4c29153e13cd2edfbf2f7539bf8a1e86e3d
|
frontend/ui/widget/toggleswitch.lua
|
frontend/ui/widget/toggleswitch.lua
|
local TextWidget = require("ui/widget/textwidget")
local InputContainer = require("ui/widget/container/inputcontainer")
local FrameContainer = require("ui/widget/container/framecontainer")
local CenterContainer = require("ui/widget/container/centercontainer")
local HorizontalGroup = require("ui/widget/horizontalgroup")
local VerticalGroup = require("ui/widget/verticalgroup")
local Font = require("ui/font")
local Geom = require("ui/geometry")
local RenderText = require("ui/rendertext")
local UIManager = require("ui/uimanager")
local Screen = require("device").screen
local Device = require("device")
local GestureRange = require("ui/gesturerange")
local Blitbuffer = require("ffi/blitbuffer")
local _ = require("gettext")
local ToggleLabel = TextWidget:new{
bold = true,
bgcolor = Blitbuffer.COLOR_WHITE,
fgcolor = Blitbuffer.COLOR_BLACK,
}
function ToggleLabel:paintTo(bb, x, y)
RenderText:renderUtf8Text(bb, x, y+self._height*0.75, self.face, self.text, true, self.bold, self.fgcolor)
end
local ToggleSwitch = InputContainer:new{
width = Screen:scaleBySize(216),
height = Screen:scaleBySize(30),
bgcolor = Blitbuffer.COLOR_WHITE, -- unfoused item color
fgcolor = Blitbuffer.COLOR_GREY, -- focused item color
font_face = "cfont",
font_size = 16,
enabled = true,
row_count = 1,
}
function ToggleSwitch:init()
-- Item count per row
self.n_pos = math.ceil(#self.toggle / self.row_count)
self.position = nil
self.toggle_frame = FrameContainer:new{
background = Blitbuffer.COLOR_WHITE,
color = Blitbuffer.COLOR_GREY,
radius = 7,
bordersize = 1,
padding = 2,
dim = not self.enabled,
}
self.toggle_content = VerticalGroup:new{}
for i = 1, self.row_count do
table.insert(self.toggle_content, HorizontalGroup:new{})
end
local center_dimen = Geom:new{
w = self.width / self.n_pos,
h = self.height / self.row_count,
}
for i = 1, #self.toggle do
local label = ToggleLabel:new{
align = "center",
text = self.toggle[i],
face = Font:getFace(self.font_face, self.font_size),
}
local content = CenterContainer:new{
dimen = center_dimen,
label,
}
local button = FrameContainer:new{
background = Blitbuffer.COLOR_WHITE,
color = Blitbuffer.COLOR_GREY,
margin = 0,
radius = 5,
bordersize = 1,
padding = 0,
content,
}
table.insert(self.toggle_content[math.ceil(i / self.n_pos)], button)
end
self.toggle_frame[1] = self.toggle_content
self[1] = self.toggle_frame
self.dimen = Geom:new(self.toggle_frame:getSize())
if Device:isTouchDevice() then
self.ges_events = {
TapSelect = {
GestureRange:new{
ges = "tap",
range = self.dimen,
},
doc = "Toggle switch",
},
HoldSelect = {
GestureRange:new{
ges = "hold",
range = self.dimen,
},
doc = "Hold switch",
},
}
end
end
function ToggleSwitch:update()
local pos = self.position
for i = 1, #self.toggle_content do
local row = self.toggle_content[i]
for j = 1, #row do
local cell = row[j]
if pos == (i - 1) * self.n_pos + j then
cell.color = self.fgcolor
cell.background = self.fgcolor
cell[1][1].fgcolor = Blitbuffer.COLOR_WHITE
else
cell.color = self.bgcolor
cell.background = self.bgcolor
cell[1][1].fgcolor = Blitbuffer.COLOR_BLACK
end
end
end
end
function ToggleSwitch:setPosition(position)
self.position = position
self:update()
end
function ToggleSwitch:togglePosition(position)
if self.n_pos == 2 and self.alternate ~= false then
self.position = (self.position+1)%self.n_pos
self.position = self.position == 0 and self.n_pos or self.position
elseif self.n_pos == 1 then
self.position = self.position == 1 and 0 or 1
else
self.position = position
end
self:update()
end
function ToggleSwitch:calculatePosition(gev)
local x = (gev.pos.x - self.dimen.x) / self.dimen.w * self.n_pos
local y = (gev.pos.y - self.dimen.y) / self.dimen.h * self.row_count
return math.ceil(x) + math.floor(y) * self.n_pos
end
function ToggleSwitch:onTapSelect(arg, gev)
if not self.enabled then return true end
local position = self:calculatePosition(gev)
self:togglePosition(position)
--[[
if self.values then
self.values = self.values or {}
self.config:onConfigChoice(self.name, self.values[self.position])
end
if self.event then
self.args = self.args or {}
self.config:onConfigEvent(self.event, self.args[self.position])
end
if self.events then
self.config:onConfigEvents(self.events, self.position)
end
--]]
self.config:onConfigChoose(self.values, self.name,
self.event, self.args, self.events, self.position)
UIManager:setDirty(self.config, function()
return "ui", self.dimen
end)
return true
end
function ToggleSwitch:onHoldSelect(arg, gev)
local position = self:calculatePosition(gev)
self.config:onMakeDefault(self.name, self.name_text,
self.values or self.args, self.toggle, position)
return true
end
return ToggleSwitch
|
local TextWidget = require("ui/widget/textwidget")
local InputContainer = require("ui/widget/container/inputcontainer")
local FrameContainer = require("ui/widget/container/framecontainer")
local CenterContainer = require("ui/widget/container/centercontainer")
local HorizontalGroup = require("ui/widget/horizontalgroup")
local VerticalGroup = require("ui/widget/verticalgroup")
local Font = require("ui/font")
local Geom = require("ui/geometry")
local RenderText = require("ui/rendertext")
local UIManager = require("ui/uimanager")
local Screen = require("device").screen
local Device = require("device")
local GestureRange = require("ui/gesturerange")
local Blitbuffer = require("ffi/blitbuffer")
local _ = require("gettext")
local ToggleLabel = TextWidget:new{
bold = true,
bgcolor = Blitbuffer.COLOR_WHITE,
fgcolor = Blitbuffer.COLOR_BLACK,
}
function ToggleLabel:paintTo(bb, x, y)
RenderText:renderUtf8Text(bb, x, y+self._height*0.75, self.face, self.text, true, self.bold, self.fgcolor)
end
local ToggleSwitch = InputContainer:new{
width = Screen:scaleBySize(216),
height = Screen:scaleBySize(30),
bgcolor = Blitbuffer.COLOR_WHITE, -- unfoused item color
fgcolor = Blitbuffer.COLOR_GREY, -- focused item color
font_face = "cfont",
font_size = 16,
enabled = true,
row_count = 1,
}
function ToggleSwitch:init()
-- Item count per row
self.n_pos = math.ceil(#self.toggle / self.row_count)
self.position = nil
self.toggle_frame = FrameContainer:new{
background = Blitbuffer.COLOR_WHITE,
color = Blitbuffer.COLOR_GREY,
radius = 7,
bordersize = 1,
padding = 2,
dim = not self.enabled,
}
self.toggle_content = VerticalGroup:new{}
for i = 1, self.row_count do
table.insert(self.toggle_content, HorizontalGroup:new{})
end
local center_dimen = Geom:new{
w = self.width / self.n_pos,
h = self.height / self.row_count,
}
for i = 1, #self.toggle do
local label = ToggleLabel:new{
align = "center",
text = self.toggle[i],
face = Font:getFace(self.font_face, self.font_size),
}
local content = CenterContainer:new{
dimen = center_dimen,
label,
}
local button = FrameContainer:new{
background = Blitbuffer.COLOR_WHITE,
color = Blitbuffer.COLOR_GREY,
margin = 0,
radius = 5,
bordersize = 1,
padding = 0,
content,
}
table.insert(self.toggle_content[math.ceil(i / self.n_pos)], button)
end
self.toggle_frame[1] = self.toggle_content
self[1] = self.toggle_frame
self.dimen = Geom:new(self.toggle_frame:getSize())
if Device:isTouchDevice() then
self.ges_events = {
TapSelect = {
GestureRange:new{
ges = "tap",
range = self.dimen,
},
doc = "Toggle switch",
},
HoldSelect = {
GestureRange:new{
ges = "hold",
range = self.dimen,
},
doc = "Hold switch",
},
}
end
end
function ToggleSwitch:update()
local pos = self.position
for i = 1, #self.toggle_content do
local row = self.toggle_content[i]
for j = 1, #row do
local cell = row[j]
if pos == (i - 1) * self.n_pos + j then
cell.color = self.fgcolor
cell.background = self.fgcolor
cell[1][1].fgcolor = Blitbuffer.COLOR_WHITE
else
cell.color = self.bgcolor
cell.background = self.bgcolor
cell[1][1].fgcolor = Blitbuffer.COLOR_BLACK
end
end
end
end
function ToggleSwitch:setPosition(position)
self.position = position
self:update()
end
function ToggleSwitch:togglePosition(position)
if self.n_pos == 2 and self.alternate ~= false then
self.position = (self.position+1)%self.n_pos
self.position = self.position == 0 and self.n_pos or self.position
elseif self.n_pos == 1 then
self.position = self.position == 1 and 0 or 1
else
self.position = position
end
self:update()
end
function ToggleSwitch:calculatePosition(gev)
local x = (gev.pos.x - self.dimen.x) / self.dimen.w * self.n_pos
local y = (gev.pos.y - self.dimen.y) / self.dimen.h * self.row_count
return math.max(1, math.ceil(x)) + math.min(self.row_count-1, math.floor(y)) * self.n_pos
end
function ToggleSwitch:onTapSelect(arg, gev)
if not self.enabled then return true end
local position = self:calculatePosition(gev)
self:togglePosition(position)
--[[
if self.values then
self.values = self.values or {}
self.config:onConfigChoice(self.name, self.values[self.position])
end
if self.event then
self.args = self.args or {}
self.config:onConfigEvent(self.event, self.args[self.position])
end
if self.events then
self.config:onConfigEvents(self.events, self.position)
end
--]]
self.config:onConfigChoose(self.values, self.name,
self.event, self.args, self.events, self.position)
UIManager:setDirty(self.config, function()
return "ui", self.dimen
end)
return true
end
function ToggleSwitch:onHoldSelect(arg, gev)
local position = self:calculatePosition(gev)
self.config:onMakeDefault(self.name, self.name_text,
self.values or self.args, self.toggle, position)
return true
end
return ToggleSwitch
|
Fix crash when tapping on toggleswitch left or bottom borders (#3181)
|
Fix crash when tapping on toggleswitch left or bottom borders (#3181)
|
Lua
|
agpl-3.0
|
koreader/koreader,houqp/koreader,Frenzie/koreader,koreader/koreader,mihailim/koreader,lgeek/koreader,apletnev/koreader,pazos/koreader,Markismus/koreader,mwoz123/koreader,poire-z/koreader,poire-z/koreader,Frenzie/koreader,Hzj-jie/koreader,NiLuJe/koreader,NiLuJe/koreader
|
777a935d0b1c81a8f96de3a57ac94eeca9dae54e
|
examples/premake5.lua
|
examples/premake5.lua
|
require "android_studio"
dofile "../tools/premake/options.lua"
dofile "../tools/premake/globals.lua"
dofile "../tools/premake/app_template.lua"
-- Solution
solution "examples"
location ("build/" .. platform_dir )
configurations { "Debug", "Release" }
startproject "empty_project"
buildoptions { build_cmd }
linkoptions { link_cmd }
-- Engine Project
dofile "../pen/project.lua"
-- Toolkit Project
dofile "../put/project.lua"
-- Example projects
-- ( project name, current script dir, )
create_app_example( "empty_project", script_path() )
create_app_example( "basic_triangle", script_path() )
create_app_example( "basic_texture", script_path() )
create_app_example( "render_target", script_path() )
create_app_example( "debug_text", script_path() )
create_app_example( "play_sound", script_path() )
create_app_example( "imgui", script_path() )
create_app_example( "input", script_path() )
create_app_example( "audio_player", script_path() )
create_app_example( "shader_toy", script_path() )
create_app_example( "scene_editor", script_path() )
create_app_example( "rigid_body_primitives", script_path() )
create_app_example( "physics_constraints", script_path() )
create_app_example( "instancing", script_path() )
create_app_example( "shadows", script_path() )
create_app_example( "cubemap", script_path() )
create_app_example( "texture_formats", script_path() )
create_app_example( "skinning", script_path() )
create_app_example( "vertex_stream_out", script_path() )
create_app_example( "volume_texture", script_path() )
create_app_example( "multiple_render_targets", script_path() )
create_app_example( "maths_functions", script_path() )
create_app_example( "sdf_shadow", script_path() )
|
if _ACTION == "android-studio" then
require "android_studio"
end
dofile "../tools/premake/options.lua"
dofile "../tools/premake/globals.lua"
dofile "../tools/premake/app_template.lua"
-- Solution
solution "examples"
location ("build/" .. platform_dir )
configurations { "Debug", "Release" }
startproject "empty_project"
buildoptions { build_cmd }
linkoptions { link_cmd }
-- Engine Project
dofile "../pen/project.lua"
-- Toolkit Project
dofile "../put/project.lua"
-- Example projects
-- ( project name, current script dir, )
create_app_example( "empty_project", script_path() )
create_app_example( "basic_triangle", script_path() )
create_app_example( "basic_texture", script_path() )
create_app_example( "render_target", script_path() )
create_app_example( "debug_text", script_path() )
create_app_example( "play_sound", script_path() )
create_app_example( "imgui", script_path() )
create_app_example( "input", script_path() )
create_app_example( "audio_player", script_path() )
create_app_example( "shader_toy", script_path() )
create_app_example( "scene_editor", script_path() )
create_app_example( "rigid_body_primitives", script_path() )
create_app_example( "physics_constraints", script_path() )
create_app_example( "instancing", script_path() )
create_app_example( "shadows", script_path() )
create_app_example( "cubemap", script_path() )
create_app_example( "texture_formats", script_path() )
create_app_example( "skinning", script_path() )
create_app_example( "vertex_stream_out", script_path() )
create_app_example( "volume_texture", script_path() )
create_app_example( "multiple_render_targets", script_path() )
create_app_example( "maths_functions", script_path() )
create_app_example( "sdf_shadow", script_path() )
|
fix win32 ci
|
fix win32 ci
|
Lua
|
mit
|
polymonster/pmtech,polymonster/pmtech,polymonster/pmtech,polymonster/pmtech,polymonster/pmtech,polymonster/pmtech
|
0a1ad0a4b5a4f9fe0ff232a5d714ed28fd391ac7
|
shared/basicauth.lua
|
shared/basicauth.lua
|
require 'stringutil'
-- Notice that the namespace for the module matches the module name - i.e. basicauth
-- When we use it within the code it is desirable to do:
-- basicauth = require 'basicauth'
-- Since this keeps the name of the module very consistent.
-- Basic authentication is part of the HTTP protocol. See this reference:
-- http://en.wikipedia.org/wiki/Basic_access_authentication
-- This module takes the user name and password from the user and validates the user id
-- against the local Iguana user id. If an invalid user name and password is given it won't be possilble to login.
local basicauth = {}
local function getCreds(Headers)
if not Headers.Authorization then
return false
end
local Auth64Str = Headers.Authorization:sub(#"Basic " + 1)
local Creds = filter.base64.dec(Auth64Str):split(":")
return {username=Creds[1], password=Creds[2]}
end
function basicauth.isAuthorized(Request)
local Credentials = getCreds(Request.headers)
if not Credentials then
return false
end
-- webInfo requires Iguana 5.6.4 or above
local WebInfo = iguana.webInfo()
-- TODO - it would be really nice if we could have a Lua API
-- to do this against the local Iguana instance - it would be
-- a tinsy winsy bit faster.
local Status, Code = net.http.post{
url=WebInfo.ip..":"..WebInfo.web_config.port.."/status",
auth=Credentials,
live=true}
return Code == 200
end
function basicauth.requireAuthorization()
net.http.respond{
code=401,
headers={["WWW-Authenticate"]='Basic realm=Channel Manager'},
body="Please Authenticate"}
end
function basicauth.getCredentials(HttpMsg)
return getCreds(HttpMsg.headers)
end
return basicauth
|
require 'stringutil'
-- Notice that the namespace for the module matches the module name - i.e. basicauth
-- When we use it within the code it is desirable to do:
-- basicauth = require 'basicauth'
-- Since this keeps the name of the module very consistent.
-- Basic authentication is part of the HTTP protocol. See this reference:
-- http://en.wikipedia.org/wiki/Basic_access_authentication
-- This module takes the user name and password from the user and validates the user id
-- against the local Iguana user id. If an invalid user name and password is given it won't be possilble to login.
local basicauth = {}
local function getCreds(Headers)
if not Headers.Authorization then
return false
end
local Auth64Str = Headers.Authorization:sub(#"Basic " + 1)
local Creds = filter.base64.dec(Auth64Str):split(":")
local Host = Headers.Host:split(':')[1] --this is kinda funny cuz it can read as localhost
return {username=Creds[1], password=Creds[2]}, Host
end
function basicauth.isAuthorized(Request)
local Credentials, Host = getCreds(Request.headers)
if not Credentials then
return false
end
-- webInfo requires Iguana 5.6.4 or above
local WebInfo = iguana.webInfo()
-- TODO - it would be really nice if we could have a Lua API
-- to do this against the local Iguana instance - it would be
-- a tinsy winsy bit faster.
local Status, Code = net.http.post{
url=Host..':'..WebInfo.web_config.port..'/status',
auth=Credentials,
live=true}
return Code == 200
end
function basicauth.requireAuthorization()
net.http.respond{
code=401,
headers={["WWW-Authenticate"]='Basic realm=Channel Manager'},
body="Please Authenticate"}
end
function basicauth.getCredentials(HttpMsg)
return getCreds(HttpMsg.headers)
end
return basicauth
|
Put in a patch from Rick Thiessen to basicauth.
|
Put in a patch from Rick Thiessen to basicauth.
On VPNs this fixes a problem where iguana.webInfo is returning
the IP of the VPN rather than the host/ip that Iguana is running
on.
|
Lua
|
mit
|
interfaceware/iguana-web-apps,interfaceware/iguana-web-apps
|
e6eb1d749ed680c0def9e95e00bafc48de977b46
|
libs/web/luasrc/template.lua
|
libs/web/luasrc/template.lua
|
--[[
LuCI - Template Parser
Description:
A template parser supporting includes, translations, Lua code blocks
and more. It can be used either as a compiler or as an interpreter.
FileId: $Id$
License:
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local fs = require"luci.fs"
local sys = require "luci.sys"
local util = require "luci.util"
local table = require "table"
local string = require "string"
local config = require "luci.config"
local coroutine = require "coroutine"
local tostring, pairs, loadstring = tostring, pairs, loadstring
local setmetatable, loadfile = setmetatable, loadfile
local getfenv, setfenv = getfenv, setfenv
local assert, type, error = assert, type, error
--- LuCI template library.
module "luci.template"
config.template = config.template or {}
viewdir = config.template.viewdir or util.libpath() .. "/view"
compiledir = config.template.compiledir or util.libpath() .. "/view"
-- Compile modes:
-- memory: Always compile, do not save compiled files, ignore precompiled
-- file: Compile on demand, save compiled files, update precompiled
compiler_mode = config.template.compiler_mode or "memory"
-- Define the namespace for template modules
context = util.threadlocal()
viewns = {
include = function(name) Template(name):render(getfenv(2)) end,
}
--- Manually compile a given template into an executable Lua function
-- @param template LuCI template
-- @return Lua template function
function compile(template)
local expr = {}
-- Search all <% %> expressions
local function expr_add(ws1, skip1, command, skip2, ws2)
table.insert(expr, command)
return ( #skip1 > 0 and "" or ws1 ) ..
"<%" .. tostring(#expr) .. "%>" ..
( #skip2 > 0 and "" or ws2 )
end
-- Save all expressiosn to table "expr"
template = template:gsub("(%s*)<%%(%-?)(.-)(%-?)%%>(%s*)", expr_add)
local function sanitize(s)
s = "%q" % s
return s:sub(2, #s-1)
end
-- Escape and sanitize all the template (all non-expressions)
template = sanitize(template)
-- Template module header/footer declaration
local header = 'write("'
local footer = '")'
template = header .. template .. footer
-- Replacements
local r_include = '")\ninclude("%s")\nwrite("'
local r_i18n = '"..translate("%1","%2").."'
local r_i18n2 = '"..translate("%1", "").."'
local r_pexec = '"..(%s or "").."'
local r_exec = '")\n%s\nwrite("'
-- Parse the expressions
for k,v in pairs(expr) do
local p = v:sub(1, 1)
v = v:gsub("%%", "%%%%")
local re = nil
if p == "+" then
re = r_include:format(sanitize(string.sub(v, 2)))
elseif p == ":" then
if v:find(" ") then
re = sanitize(v):gsub(":(.-) (.*)", r_i18n)
else
re = sanitize(v):gsub(":(.+)", r_i18n2)
end
elseif p == "=" then
re = r_pexec:format(v:sub(2))
elseif p == "#" then
re = ""
else
re = r_exec:format(v)
end
template = template:gsub("<%%"..tostring(k).."%%>", re)
end
return loadstring(template)
end
--- Render a certain template.
-- @param name Template name
-- @param scope Scope to assign to template (optional)
function render(name, scope)
return Template(name):render(scope or getfenv(2))
end
-- Template class
Template = util.class()
-- Shared template cache to store templates in to avoid unnecessary reloading
Template.cache = setmetatable({}, {__mode = "v"})
-- Constructor - Reads and compiles the template on-demand
function Template.__init__(self, name, srcfile, comfile)
local function _encode_filename(str)
local function __chrenc( chr )
return "%%%02x" % string.byte( chr )
end
if type(str) == "string" then
str = str:gsub(
"([^a-zA-Z0-9$_%-%.%+!*'(),])",
__chrenc
)
end
return str
end
self.template = self.cache[name]
self.name = name
-- Create a new namespace for this template
self.viewns = {sink=self.sink}
-- Copy over from general namespace
util.update(self.viewns, viewns)
if context.viewns then
util.update(self.viewns, context.viewns)
end
-- If we have a cached template, skip compiling and loading
if self.template then
return
end
-- Enforce cache security
local cdir = compiledir .. "/" .. sys.process.info("uid")
-- Compile and build
local sourcefile = srcfile or (viewdir .. "/" .. name .. ".htm")
local compiledfile = comfile or (cdir .. "/" .. _encode_filename(name) .. ".lua")
local err
if compiler_mode == "file" then
local tplmt = fs.mtime(sourcefile)
local commt = fs.mtime(compiledfile)
if not fs.mtime(cdir) then
fs.mkdir(cdir, true)
fs.chmod(fs.dirname(cdir), "a+rxw")
end
-- Build if there is no compiled file or if compiled file is outdated
if ((commt == nil) and not (tplmt == nil))
or (not (commt == nil) and not (tplmt == nil) and commt < tplmt) then
local source
source, err = fs.readfile(sourcefile)
if source then
local compiled, err = compile(source)
fs.writefile(compiledfile, util.get_bytecode(compiled))
fs.chmod(compiledfile, "a-rwx,u+rw")
self.template = compiled
end
else
assert(
sys.process.info("uid") == fs.stat(compiledfile, "uid")
and fs.stat(compiledfile, "mode") == "rw-------",
"Fatal: Cachefile is not sane!"
)
self.template, err = loadfile(compiledfile)
end
elseif compiler_mode == "memory" then
local source
source, err = fs.readfile(sourcefile)
if source then
self.template, err = compile(source)
end
end
-- If we have no valid template throw error, otherwise cache the template
if not self.template then
error(err)
else
self.cache[name] = self.template
end
end
-- Renders a template
function Template.render(self, scope)
scope = scope or getfenv(2)
-- Save old environment
local oldfenv = getfenv(self.template)
-- Put our predefined objects in the scope of the template
util.resfenv(self.template)
util.updfenv(self.template, scope)
util.updfenv(self.template, self.viewns)
-- Now finally render the thing
local stat, err = util.copcall(self.template)
if not stat then
setfenv(self.template, oldfenv)
error("Error in template %s: %s" % {self.name, err})
end
-- Reset environment
setfenv(self.template, oldfenv)
end
|
--[[
LuCI - Template Parser
Description:
A template parser supporting includes, translations, Lua code blocks
and more. It can be used either as a compiler or as an interpreter.
FileId: $Id$
License:
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local fs = require"luci.fs"
local sys = require "luci.sys"
local util = require "luci.util"
local table = require "table"
local string = require "string"
local config = require "luci.config"
local coroutine = require "coroutine"
local tostring, pairs, loadstring = tostring, pairs, loadstring
local setmetatable, loadfile = setmetatable, loadfile
local getfenv, setfenv = getfenv, setfenv
local assert, type, error = assert, type, error
--- LuCI template library.
module "luci.template"
config.template = config.template or {}
viewdir = config.template.viewdir or util.libpath() .. "/view"
compiledir = config.template.compiledir or util.libpath() .. "/view"
-- Compile modes:
-- memory: Always compile, do not save compiled files, ignore precompiled
-- file: Compile on demand, save compiled files, update precompiled
compiler_mode = config.template.compiler_mode or "memory"
-- Define the namespace for template modules
context = util.threadlocal()
viewns = {
include = function(name) Template(name):render(getfenv(2)) end,
}
--- Manually compile a given template into an executable Lua function
-- @param template LuCI template
-- @return Lua template function
function compile(template)
local expr = {}
-- Search all <% %> expressions
local function expr_add(ws1, skip1, command, skip2, ws2)
table.insert(expr, command)
return ( #skip1 > 0 and "" or ws1 ) ..
"<%" .. tostring(#expr) .. "%>" ..
( #skip2 > 0 and "" or ws2 )
end
-- Save all expressiosn to table "expr"
template = template:gsub("(%s*)<%%(%-?)(.-)(%-?)%%>(%s*)", expr_add)
local function sanitize(s)
s = "%q" % s
return s:sub(2, #s-1)
end
-- Escape and sanitize all the template (all non-expressions)
template = sanitize(template)
-- Template module header/footer declaration
local header = 'write("'
local footer = '")'
template = header .. template .. footer
-- Replacements
local r_include = '")\ninclude("%s")\nwrite("'
local r_i18n = '"..translate("%1","%2").."'
local r_i18n2 = '"..translate("%1", "").."'
local r_pexec = '"..(%s or "").."'
local r_exec = '")\n%s\nwrite("'
-- Parse the expressions
for k,v in pairs(expr) do
local p = v:sub(1, 1)
v = v:gsub("%%", "%%%%")
local re = nil
if p == "+" then
re = r_include:format(sanitize(string.sub(v, 2)))
elseif p == ":" then
if v:find(" ") then
re = sanitize(v):gsub(":(.-) (.*)", r_i18n)
else
re = sanitize(v):gsub(":(.+)", r_i18n2)
end
elseif p == "=" then
re = r_pexec:format(v:sub(2))
elseif p == "#" then
re = ""
else
re = r_exec:format(v)
end
template = template:gsub("<%%"..tostring(k).."%%>", re)
end
return loadstring(template)
end
--- Render a certain template.
-- @param name Template name
-- @param scope Scope to assign to template (optional)
function render(name, scope)
return Template(name):render(scope or getfenv(2))
end
-- Template class
Template = util.class()
-- Shared template cache to store templates in to avoid unnecessary reloading
Template.cache = setmetatable({}, {__mode = "v"})
-- Constructor - Reads and compiles the template on-demand
function Template.__init__(self, name)
local function _encode_filename(str)
local function __chrenc( chr )
return "%%%02x" % string.byte( chr )
end
if type(str) == "string" then
str = str:gsub(
"([^a-zA-Z0-9$_%-%.%+!*'(),])",
__chrenc
)
end
return str
end
self.template = self.cache[name]
self.name = name
-- Create a new namespace for this template
self.viewns = {sink=self.sink}
-- Copy over from general namespace
util.update(self.viewns, viewns)
if context.viewns then
util.update(self.viewns, context.viewns)
end
-- If we have a cached template, skip compiling and loading
if self.template then
return
end
-- Enforce cache security
local cdir = compiledir .. "/" .. sys.process.info("uid")
-- Compile and build
local sourcefile = viewdir .. "/" .. name
local compiledfile = cdir .. "/" .. _encode_filename(name) .. ".lua"
local err
if compiler_mode == "file" then
local tplmt = fs.mtime(sourcefile) or fs.mtime(sourcefile .. ".htm")
local commt = fs.mtime(compiledfile)
if not fs.mtime(cdir) then
fs.mkdir(cdir, true)
fs.chmod(fs.dirname(cdir), "a+rxw")
end
assert(tplmt or commt, "No such template: " .. name)
-- Build if there is no compiled file or if compiled file is outdated
if not commt or (commt and tplmt and commt < tplmt) then
local source
source, err = fs.readfile(sourcefile) or fs.readfile(sourcefile .. ".htm")
if source then
local compiled, err = compile(source)
fs.writefile(compiledfile, util.get_bytecode(compiled))
fs.chmod(compiledfile, "a-rwx,u+rw")
self.template = compiled
end
else
assert(
sys.process.info("uid") == fs.stat(compiledfile, "uid")
and fs.stat(compiledfile, "mode") == "rw-------",
"Fatal: Cachefile is not sane!"
)
self.template, err = loadfile(compiledfile)
end
elseif compiler_mode == "memory" then
local source
source, err = fs.readfile(sourcefile) or fs.readfile(sourcefile .. ".htm")
if source then
self.template, err = compile(source)
end
end
-- If we have no valid template throw error, otherwise cache the template
if not self.template then
error(err)
else
self.cache[name] = self.template
end
end
-- Renders a template
function Template.render(self, scope)
scope = scope or getfenv(2)
-- Save old environment
local oldfenv = getfenv(self.template)
-- Put our predefined objects in the scope of the template
util.resfenv(self.template)
util.updfenv(self.template, scope)
util.updfenv(self.template, self.viewns)
-- Now finally render the thing
local stat, err = util.copcall(self.template)
if not stat then
setfenv(self.template, oldfenv)
error("Error in template %s: %s" % {self.name, err})
end
-- Reset environment
setfenv(self.template, oldfenv)
end
|
libs/web: Fixed luci.template
|
libs/web: Fixed luci.template
|
Lua
|
apache-2.0
|
deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci
|
0b9424cb2991c1f153c007b60fb138bf07ce7c44
|
AceGUI-3.0/widgets/AceGUIWidget-Slider.lua
|
AceGUI-3.0/widgets/AceGUIWidget-Slider.lua
|
local AceGUI = LibStub("AceGUI-3.0")
--------------------------
-- Slider --
--------------------------
do
local Type = "Slider"
local Version = 7
local function OnAcquire(self)
self:SetWidth(200)
self:SetHeight(44)
self:SetDisabled(false)
self:SetIsPercent(nil)
self:SetSliderValues(0,100,1)
self:SetValue(0)
end
local function OnRelease(self)
self.frame:ClearAllPoints()
self.frame:Hide()
self.slider:EnableMouseWheel(false)
self:SetDisabled(false)
end
local function Control_OnEnter(this)
this.obj:Fire("OnEnter")
end
local function Control_OnLeave(this)
this.obj:Fire("OnLeave")
end
local function UpdateText(self)
local value = self.value or 0
if self.ispercent then
self.editbox:SetText(("%s%%"):format(math.floor(value*1000+0.5)/10))
else
self.editbox:SetText(math.floor(value*100+0.5)/100)
end
end
local function UpdateLabels(self)
local min, max = (self.min or 0), (self.max or 100)
if self.ispercent then
self.lowtext:SetFormattedText("%s%%",(min * 100))
self.hightext:SetFormattedText("%s%%",(max * 100))
else
self.lowtext:SetText(min)
self.hightext:SetText(max)
end
end
local function Slider_OnValueChanged(this)
local self = this.obj
if not this.setup then
local newvalue
newvalue = this:GetValue()
if newvalue ~= self.value and not self.disabled then
self.value = newvalue
self:Fire("OnValueChanged", newvalue)
end
if self.value then
local value = self.value
UpdateText(self)
end
end
end
local function Slider_OnMouseUp(this)
local self = this.obj
self:Fire("OnMouseUp",this:GetValue())
end
local function Slider_OnMouseWheel(this, v)
local self = this.obj
if not self.disabled then
local value = self.value
if v > 0 then
value = math.min(value + (self.step or 1),self.max)
else
value = math.max(value - (self.step or 1), self.min)
end
self.slider:SetValue(value)
end
end
local function SetDisabled(self, disabled)
self.disabled = disabled
if disabled then
self.slider:EnableMouse(false)
self.label:SetTextColor(.5,.5,.5)
self.hightext:SetTextColor(.5,.5,.5)
self.lowtext:SetTextColor(.5,.5,.5)
--self.valuetext:SetTextColor(.5,.5,.5)
self.editbox:SetTextColor(.5,.5,.5)
self.editbox:EnableMouse(false)
self.editbox:ClearFocus()
else
self.slider:EnableMouse(true)
self.label:SetTextColor(1,.82,0)
self.hightext:SetTextColor(1,1,1)
self.lowtext:SetTextColor(1,1,1)
--self.valuetext:SetTextColor(1,1,1)
self.editbox:SetTextColor(1,1,1)
self.editbox:EnableMouse(true)
end
end
local function SetValue(self, value)
self.slider.setup = true
self.slider:SetValue(value)
self.value = value
UpdateText(self)
self.slider.setup = nil
end
local function SetLabel(self, text)
self.label:SetText(text)
end
local function SetSliderValues(self, min, max, step)
local frame = self.slider
frame.setup = true
self.min = min
self.max = max
self.step = step
frame:SetMinMaxValues(min or 0,max or 100)
UpdateLabels(self)
frame:SetValueStep(step or 1)
frame.setup = nil
end
local function EditBox_OnEscapePressed(this)
this:ClearFocus()
end
local function EditBox_OnEnterPressed(this)
local self = this.obj
local value = this:GetText()
if self.ispercent then
value = value:gsub('%%','')
value = tonumber(value) / 100
else
value = tonumber(value)
end
if value then
self:Fire("OnMouseUp",value)
end
end
local function SetIsPercent(self, value)
self.ispercent = value
UpdateLabels(self)
UpdateText(self)
end
local function FrameOnMouseDown(this)
this.obj.slider:EnableMouseWheel(true)
AceGUI:ClearFocus()
end
local SliderBackdrop = {
bgFile = "Interface\\Buttons\\UI-SliderBar-Background",
edgeFile = "Interface\\Buttons\\UI-SliderBar-Border",
tile = true, tileSize = 8, edgeSize = 8,
insets = { left = 3, right = 3, top = 6, bottom = 6 }
}
local function Constructor()
local frame = CreateFrame("Frame",nil,UIParent)
local self = {}
self.type = Type
self.OnRelease = OnRelease
self.OnAcquire = OnAcquire
self.frame = frame
frame.obj = self
self.SetDisabled = SetDisabled
self.SetValue = SetValue
self.SetSliderValues = SetSliderValues
self.SetLabel = SetLabel
self.SetIsPercent = SetIsPercent
self.alignoffset = 25
frame:EnableMouse(true)
frame:SetScript("OnMouseDown",FrameOnMouseDown)
self.slider = CreateFrame("Slider",nil,frame)
local slider = self.slider
slider:SetScript("OnEnter",Control_OnEnter)
slider:SetScript("OnLeave",Control_OnLeave)
slider:SetScript("OnMouseUp", Slider_OnMouseUp)
slider.obj = self
slider:SetOrientation("HORIZONTAL")
slider:SetHeight(15)
slider:SetHitRectInsets(0,0,-10,0)
slider:SetBackdrop(SliderBackdrop)
--slider:EnableMouseWheel(true)
slider:SetScript("OnMouseWheel", Slider_OnMouseWheel)
local label = frame:CreateFontString(nil,"OVERLAY","GameFontNormal")
label:SetPoint("TOPLEFT",frame,"TOPLEFT",0,0)
label:SetPoint("TOPRIGHT",frame,"TOPRIGHT",0,0)
label:SetJustifyH("CENTER")
label:SetHeight(15)
self.label = label
self.lowtext = slider:CreateFontString(nil,"ARTWORK","GameFontHighlightSmall")
self.lowtext:SetPoint("TOPLEFT",slider,"BOTTOMLEFT",2,3)
self.hightext = slider:CreateFontString(nil,"ARTWORK","GameFontHighlightSmall")
self.hightext:SetPoint("TOPRIGHT",slider,"BOTTOMRIGHT",-2,3)
local editbox = CreateFrame("EditBox",nil,frame)
editbox:SetAutoFocus(false)
editbox:SetFontObject(GameFontHighlightSmall)
editbox:SetPoint("TOP",slider,"BOTTOM",0,0)
editbox:SetHeight(14)
editbox:SetWidth(70)
editbox:SetJustifyH("CENTER")
editbox:EnableMouse(true)
editbox:SetScript("OnEscapePressed",EditBox_OnEscapePressed)
editbox:SetScript("OnEnterPressed",EditBox_OnEnterPressed)
self.editbox = editbox
editbox.obj = self
local bg = editbox:CreateTexture(nil,"BACKGROUND")
editbox.bg = bg
bg:SetTexture("Interface\\ChatFrame\\ChatFrameBackground")
bg:SetVertexColor(0,0,0,0.25)
bg:SetAllPoints(editbox)
slider:SetThumbTexture("Interface\\Buttons\\UI-SliderBar-Button-Horizontal")
frame:SetWidth(200)
frame:SetHeight(44)
slider:SetPoint("TOP",label,"BOTTOM",0,0)
slider:SetPoint("LEFT",frame,"LEFT",3,0)
slider:SetPoint("RIGHT",frame,"RIGHT",-3,0)
slider:SetValue(self.value or 0)
slider:SetScript("OnValueChanged",Slider_OnValueChanged)
AceGUI:RegisterAsWidget(self)
return self
end
AceGUI:RegisterWidgetType(Type,Constructor,Version)
end
|
local AceGUI = LibStub("AceGUI-3.0")
--------------------------
-- Slider --
--------------------------
do
local Type = "Slider"
local Version = 8
local function OnAcquire(self)
self:SetWidth(200)
self:SetHeight(44)
self:SetDisabled(false)
self:SetIsPercent(nil)
self:SetSliderValues(0,100,1)
self:SetValue(0)
end
local function OnRelease(self)
self.frame:ClearAllPoints()
self.frame:Hide()
self.slider:EnableMouseWheel(false)
self:SetDisabled(false)
end
local function Control_OnEnter(this)
this.obj:Fire("OnEnter")
end
local function Control_OnLeave(this)
this.obj:Fire("OnLeave")
end
local function UpdateText(self)
local value = self.value or 0
if self.ispercent then
self.editbox:SetText(("%s%%"):format(math.floor(value*1000+0.5)/10))
else
self.editbox:SetText(math.floor(value*100+0.5)/100)
end
end
local function UpdateLabels(self)
local min, max = (self.min or 0), (self.max or 100)
if self.ispercent then
self.lowtext:SetFormattedText("%s%%",(min * 100))
self.hightext:SetFormattedText("%s%%",(max * 100))
else
self.lowtext:SetText(min)
self.hightext:SetText(max)
end
end
local function Slider_OnValueChanged(this)
local self = this.obj
if not this.setup then
local newvalue
newvalue = this:GetValue()
if newvalue ~= self.value and not self.disabled then
self.value = newvalue
self:Fire("OnValueChanged", newvalue)
end
if self.value then
local value = self.value
UpdateText(self)
end
end
end
local function Slider_OnMouseUp(this)
local self = this.obj
self:Fire("OnMouseUp",this:GetValue())
end
local function Slider_OnMouseWheel(this, v)
local self = this.obj
if not self.disabled then
local value = self.value
if v > 0 then
value = math.min(value + (self.step or 1),self.max)
else
value = math.max(value - (self.step or 1), self.min)
end
self.slider:SetValue(value)
end
end
local function SetDisabled(self, disabled)
self.disabled = disabled
if disabled then
self.slider:EnableMouse(false)
self.label:SetTextColor(.5,.5,.5)
self.hightext:SetTextColor(.5,.5,.5)
self.lowtext:SetTextColor(.5,.5,.5)
--self.valuetext:SetTextColor(.5,.5,.5)
self.editbox:SetTextColor(.5,.5,.5)
self.editbox:EnableMouse(false)
self.editbox:ClearFocus()
else
self.slider:EnableMouse(true)
self.label:SetTextColor(1,.82,0)
self.hightext:SetTextColor(1,1,1)
self.lowtext:SetTextColor(1,1,1)
--self.valuetext:SetTextColor(1,1,1)
self.editbox:SetTextColor(1,1,1)
self.editbox:EnableMouse(true)
end
end
local function SetValue(self, value)
self.slider.setup = true
self.slider:SetValue(value)
self.value = value
UpdateText(self)
self.slider.setup = nil
end
local function SetLabel(self, text)
self.label:SetText(text)
end
local function SetSliderValues(self, min, max, step)
local frame = self.slider
frame.setup = true
self.min = min
self.max = max
self.step = step
frame:SetMinMaxValues(min or 0,max or 100)
UpdateLabels(self)
frame:SetValueStep(step or 1)
if self.value then
frame:SetValue(self.value)
end
frame.setup = nil
end
local function EditBox_OnEscapePressed(this)
this:ClearFocus()
end
local function EditBox_OnEnterPressed(this)
local self = this.obj
local value = this:GetText()
if self.ispercent then
value = value:gsub('%%','')
value = tonumber(value) / 100
else
value = tonumber(value)
end
if value then
self:Fire("OnMouseUp",value)
end
end
local function SetIsPercent(self, value)
self.ispercent = value
UpdateLabels(self)
UpdateText(self)
end
local function FrameOnMouseDown(this)
this.obj.slider:EnableMouseWheel(true)
AceGUI:ClearFocus()
end
local SliderBackdrop = {
bgFile = "Interface\\Buttons\\UI-SliderBar-Background",
edgeFile = "Interface\\Buttons\\UI-SliderBar-Border",
tile = true, tileSize = 8, edgeSize = 8,
insets = { left = 3, right = 3, top = 6, bottom = 6 }
}
local function Constructor()
local frame = CreateFrame("Frame",nil,UIParent)
local self = {}
self.type = Type
self.OnRelease = OnRelease
self.OnAcquire = OnAcquire
self.frame = frame
frame.obj = self
self.SetDisabled = SetDisabled
self.SetValue = SetValue
self.SetSliderValues = SetSliderValues
self.SetLabel = SetLabel
self.SetIsPercent = SetIsPercent
self.alignoffset = 25
frame:EnableMouse(true)
frame:SetScript("OnMouseDown",FrameOnMouseDown)
self.slider = CreateFrame("Slider",nil,frame)
local slider = self.slider
slider:SetScript("OnEnter",Control_OnEnter)
slider:SetScript("OnLeave",Control_OnLeave)
slider:SetScript("OnMouseUp", Slider_OnMouseUp)
slider.obj = self
slider:SetOrientation("HORIZONTAL")
slider:SetHeight(15)
slider:SetHitRectInsets(0,0,-10,0)
slider:SetBackdrop(SliderBackdrop)
--slider:EnableMouseWheel(true)
slider:SetScript("OnMouseWheel", Slider_OnMouseWheel)
local label = frame:CreateFontString(nil,"OVERLAY","GameFontNormal")
label:SetPoint("TOPLEFT",frame,"TOPLEFT",0,0)
label:SetPoint("TOPRIGHT",frame,"TOPRIGHT",0,0)
label:SetJustifyH("CENTER")
label:SetHeight(15)
self.label = label
self.lowtext = slider:CreateFontString(nil,"ARTWORK","GameFontHighlightSmall")
self.lowtext:SetPoint("TOPLEFT",slider,"BOTTOMLEFT",2,3)
self.hightext = slider:CreateFontString(nil,"ARTWORK","GameFontHighlightSmall")
self.hightext:SetPoint("TOPRIGHT",slider,"BOTTOMRIGHT",-2,3)
local editbox = CreateFrame("EditBox",nil,frame)
editbox:SetAutoFocus(false)
editbox:SetFontObject(GameFontHighlightSmall)
editbox:SetPoint("TOP",slider,"BOTTOM",0,0)
editbox:SetHeight(14)
editbox:SetWidth(70)
editbox:SetJustifyH("CENTER")
editbox:EnableMouse(true)
editbox:SetScript("OnEscapePressed",EditBox_OnEscapePressed)
editbox:SetScript("OnEnterPressed",EditBox_OnEnterPressed)
self.editbox = editbox
editbox.obj = self
local bg = editbox:CreateTexture(nil,"BACKGROUND")
editbox.bg = bg
bg:SetTexture("Interface\\ChatFrame\\ChatFrameBackground")
bg:SetVertexColor(0,0,0,0.25)
bg:SetAllPoints(editbox)
slider:SetThumbTexture("Interface\\Buttons\\UI-SliderBar-Button-Horizontal")
frame:SetWidth(200)
frame:SetHeight(44)
slider:SetPoint("TOP",label,"BOTTOM",0,0)
slider:SetPoint("LEFT",frame,"LEFT",3,0)
slider:SetPoint("RIGHT",frame,"RIGHT",-3,0)
slider:SetValue(self.value or 0)
slider:SetScript("OnValueChanged",Slider_OnValueChanged)
AceGUI:RegisterAsWidget(self)
return self
end
AceGUI:RegisterWidgetType(Type,Constructor,Version)
end
|
Fix for blizzard slider bug: If you SetMinMax after SetValue, it wouldn't move the draghandle like it should. So now, if someone calls SetMinMax, we re-call SetValue.
|
Fix for blizzard slider bug: If you SetMinMax after SetValue, it wouldn't move the draghandle like it should. So now, if someone calls SetMinMax, we re-call SetValue.
git-svn-id: e768786be8df873dac9515156656ebbdc6d77160@837 5debad98-a965-4143-8383-f471b3509dcf
|
Lua
|
bsd-3-clause
|
sarahgerweck/Ace3
|
98187975f9ec118501b0867dc5ab39c234027ea3
|
libs/uci/luasrc/model/uci/bind.lua
|
libs/uci/luasrc/model/uci/bind.lua
|
--[[
LuCI - UCI utilities for model classes
Copyright 2009 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local assert, pairs, type = assert, pairs, type
local utl = require "luci.util"
module "luci.model.uci.bind"
bind = utl.class()
function bind.__init__(self, config, cursor)
assert(config, "call to bind() without config file")
self.cfg = config
self.uci = cursor
end
function bind.init(self, cursor)
assert(cursor, "call to init() without uci cursor")
self.uci = cursor
end
function bind.section(self, stype)
local x = utl.class(bsection)
x.__init__ = function(inst, sid)
assert(self.uci:get(self.cfg, sid) == stype,
"attempt to instantiate bsection(%q) of wrong type, expected %q"
% { sid, stype })
inst.bind = self
inst.stype = stype
inst.sid = sid
end
return x
end
function bind.usection(self, stype)
local x = utl.class(bsection)
x.__init__ = function(inst)
inst.bind = self
inst.stype = stype
inst.sid = true
end
return x()
end
function bind.list(self, list, add, rem)
local lookup = { }
if type(list) == "string" then
local item
for item in list:gmatch("%S+") do
lookup[item] = true
end
elseif type(list) == "table" then
local item
for _, item in pairs(list) do
lookup[item] = true
end
end
if add then lookup[add] = true end
if rem then lookup[rem] = nil end
return utl.keys(lookup)
end
function bind.bool(self, v)
return ( v == "1" or v == "true" or v == "yes" or v == "on" )
end
bsection = utl.class()
function bsection.uciop(self, op, ...)
assert(self.bind and self.bind.uci,
"attempt to use unitialized binding")
if op then
return self.bind.uci[op](self.bind.uci, self.bind.cfg, ...)
else
return self.bind.uci
end
end
function bsection.get(self, k, c)
local v
if type(c) == "string" then
v = self:uciop("get", c, k)
else
self:uciop("foreach", self.stype,
function(s)
if type(c) == "table" then
local ck, cv
for ck, cv in pairs(c) do
if s[ck] ~= cv then return true end
end
end
if k ~= nil then
v = s[k]
else
v = s
end
return false
end)
end
return v
end
function bsection.set(self, k, v, c)
local stat
if type(c) == "string" then
stat = self:uciop("set", c, k, v)
else
self:uciop("foreach", self.stype,
function(s)
if type(c) == "table" then
local ck, cv
for ck, cv in pairs(c) do
if s[ck] ~= cv then return true end
end
end
stat = self:uciop("set", c, k, v)
return false
end)
end
return stat or false
end
function bsection.property(self, k, n)
self[n or k] = function(c, val)
if val == nil then
return c:get(k, c.sid)
else
return c:set(k, val, c.sid)
end
end
end
function bsection.property_bool(self, k, n)
self[n or k] = function(c, val)
if val == nil then
return self.bind:bool(c:get(k, c.sid))
else
return c:set(k, self.bind:bool(val) and "1" or "0", c.sid)
end
end
end
|
--[[
LuCI - UCI utilities for model classes
Copyright 2009 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local assert, pairs, type = assert, pairs, type
local utl = require "luci.util"
module "luci.model.uci.bind"
bind = utl.class()
function bind.__init__(self, config, cursor)
assert(config, "call to bind() without config file")
self.cfg = config
self.uci = cursor
end
function bind.init(self, cursor)
assert(cursor, "call to init() without uci cursor")
self.uci = cursor
end
function bind.section(self, stype)
local x = utl.class(bsection)
x.__init__ = function(inst, sid)
assert(self.uci:get(self.cfg, sid) == stype,
"attempt to instantiate bsection(%q) of wrong type, expected %q"
% { sid, stype })
inst.bind = self
inst.stype = stype
inst.sid = sid
end
return x
end
function bind.usection(self, stype)
local x = utl.class(bsection)
x.__init__ = function(inst)
inst.bind = self
inst.stype = stype
inst.sid = true
end
return x()
end
function bind.list(self, list, add, rem)
local lookup = { }
if type(list) == "string" then
local item
for item in list:gmatch("%S+") do
lookup[item] = true
end
elseif type(list) == "table" then
local item
for _, item in pairs(list) do
lookup[item] = true
end
end
if add then lookup[add] = true end
if rem then lookup[rem] = nil end
return utl.keys(lookup)
end
function bind.bool(self, v)
return ( v == "1" or v == "true" or v == "yes" or v == "on" )
end
bsection = utl.class()
function bsection.uciop(self, op, ...)
assert(self.bind and self.bind.uci,
"attempt to use unitialized binding")
if op then
return self.bind.uci[op](self.bind.uci, self.bind.cfg, ...)
else
return self.bind.uci
end
end
function bsection.get(self, k, c)
local v
if type(c) == "string" then
v = self:uciop("get", c, k)
else
self:uciop("foreach", self.stype,
function(s)
if type(c) == "table" then
local ck, cv
for ck, cv in pairs(c) do
if s[ck] ~= cv then return true end
end
end
if k ~= nil then
v = s[k]
else
v = s
end
return false
end)
end
return v
end
function bsection.set(self, k, v, c)
local stat
if type(c) == "string" then
if type(v) == "table" and #v == 0 then
stat = self:uciop("delete", c, k)
else
stat = self:uciop("set", c, k, v)
end
else
self:uciop("foreach", self.stype,
function(s)
if type(c) == "table" then
local ck, cv
for ck, cv in pairs(c) do
if s[ck] ~= cv then return true end
end
end
stat = self:uciop("set", c, k, v)
return false
end)
end
return stat or false
end
function bsection.property(self, k, n)
self[n or k] = function(c, val)
if val == nil then
return c:get(k, c.sid)
else
return c:set(k, val, c.sid)
end
end
end
function bsection.property_bool(self, k, n)
self[n or k] = function(c, val)
if val == nil then
return self.bind:bool(c:get(k, c.sid))
else
return c:set(k, self.bind:bool(val) and "1" or "0", c.sid)
end
end
end
|
libs/uci: fix attempt to assign empty tables in uci bind class
|
libs/uci: fix attempt to assign empty tables in uci bind class
|
Lua
|
apache-2.0
|
zhaoxx063/luci,tcatm/luci,sujeet14108/luci,ff94315/luci-1,kuoruan/luci,obsy/luci,palmettos/test,openwrt/luci,chris5560/openwrt-luci,aa65535/luci,marcel-sch/luci,keyidadi/luci,deepak78/new-luci,opentechinstitute/luci,Hostle/openwrt-luci-multi-user,joaofvieira/luci,LazyZhu/openwrt-luci-trunk-mod,cshore/luci,Wedmer/luci,artynet/luci,Hostle/luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,ReclaimYourPrivacy/cloak-luci,harveyhu2012/luci,981213/luci-1,LuttyYang/luci,bittorf/luci,jchuang1977/luci-1,urueedi/luci,thess/OpenWrt-luci,Wedmer/luci,jchuang1977/luci-1,MinFu/luci,artynet/luci,florian-shellfire/luci,deepak78/new-luci,jchuang1977/luci-1,slayerrensky/luci,RedSnake64/openwrt-luci-packages,oyido/luci,remakeelectric/luci,Wedmer/luci,mumuqz/luci,nmav/luci,mumuqz/luci,oyido/luci,tcatm/luci,taiha/luci,hnyman/luci,maxrio/luci981213,openwrt/luci,Sakura-Winkey/LuCI,harveyhu2012/luci,MinFu/luci,Noltari/luci,hnyman/luci,tcatm/luci,shangjiyu/luci-with-extra,male-puppies/luci,rogerpueyo/luci,Noltari/luci,artynet/luci,jorgifumi/luci,cshore-firmware/openwrt-luci,openwrt-es/openwrt-luci,RedSnake64/openwrt-luci-packages,obsy/luci,cappiewu/luci,bittorf/luci,chris5560/openwrt-luci,cshore-firmware/openwrt-luci,RedSnake64/openwrt-luci-packages,dismantl/luci-0.12,chris5560/openwrt-luci,dwmw2/luci,NeoRaider/luci,obsy/luci,marcel-sch/luci,thesabbir/luci,dismantl/luci-0.12,lbthomsen/openwrt-luci,cshore/luci,Noltari/luci,RedSnake64/openwrt-luci-packages,ff94315/luci-1,bright-things/ionic-luci,jorgifumi/luci,jorgifumi/luci,LazyZhu/openwrt-luci-trunk-mod,sujeet14108/luci,oneru/luci,RuiChen1113/luci,tcatm/luci,palmettos/test,fkooman/luci,sujeet14108/luci,wongsyrone/luci-1,LazyZhu/openwrt-luci-trunk-mod,openwrt-es/openwrt-luci,openwrt/luci,shangjiyu/luci-with-extra,opentechinstitute/luci,palmettos/cnLuCI,daofeng2015/luci,kuoruan/lede-luci,taiha/luci,jlopenwrtluci/luci,dwmw2/luci,florian-shellfire/luci,MinFu/luci,aa65535/luci,slayerrensky/luci,db260179/openwrt-bpi-r1-luci,teslamint/luci,Wedmer/luci,aa65535/luci,lcf258/openwrtcn,palmettos/cnLuCI,hnyman/luci,bittorf/luci,aircross/OpenWrt-Firefly-LuCI,thesabbir/luci,NeoRaider/luci,david-xiao/luci,marcel-sch/luci,Kyklas/luci-proto-hso,kuoruan/lede-luci,cappiewu/luci,tcatm/luci,daofeng2015/luci,cshore-firmware/openwrt-luci,jlopenwrtluci/luci,RuiChen1113/luci,fkooman/luci,daofeng2015/luci,keyidadi/luci,jorgifumi/luci,palmettos/test,RedSnake64/openwrt-luci-packages,LuttyYang/luci,jlopenwrtluci/luci,981213/luci-1,LazyZhu/openwrt-luci-trunk-mod,nwf/openwrt-luci,thesabbir/luci,981213/luci-1,artynet/luci,Hostle/luci,Kyklas/luci-proto-hso,maxrio/luci981213,obsy/luci,dwmw2/luci,slayerrensky/luci,daofeng2015/luci,wongsyrone/luci-1,remakeelectric/luci,florian-shellfire/luci,nwf/openwrt-luci,deepak78/new-luci,jchuang1977/luci-1,kuoruan/lede-luci,Hostle/luci,marcel-sch/luci,slayerrensky/luci,shangjiyu/luci-with-extra,aircross/OpenWrt-Firefly-LuCI,thess/OpenWrt-luci,wongsyrone/luci-1,981213/luci-1,daofeng2015/luci,bittorf/luci,urueedi/luci,ollie27/openwrt_luci,forward619/luci,aa65535/luci,ReclaimYourPrivacy/cloak-luci,thesabbir/luci,opentechinstitute/luci,lcf258/openwrtcn,male-puppies/luci,sujeet14108/luci,artynet/luci,cshore-firmware/openwrt-luci,taiha/luci,sujeet14108/luci,kuoruan/luci,jlopenwrtluci/luci,Hostle/luci,Noltari/luci,kuoruan/luci,deepak78/new-luci,kuoruan/luci,artynet/luci,forward619/luci,ReclaimYourPrivacy/cloak-luci,oyido/luci,harveyhu2012/luci,artynet/luci,palmettos/test,Kyklas/luci-proto-hso,oyido/luci,artynet/luci,ReclaimYourPrivacy/cloak-luci,teslamint/luci,tobiaswaldvogel/luci,LuttyYang/luci,nwf/openwrt-luci,ollie27/openwrt_luci,opentechinstitute/luci,david-xiao/luci,Sakura-Winkey/LuCI,remakeelectric/luci,db260179/openwrt-bpi-r1-luci,kuoruan/lede-luci,Hostle/openwrt-luci-multi-user,opentechinstitute/luci,hnyman/luci,kuoruan/lede-luci,mumuqz/luci,ollie27/openwrt_luci,RuiChen1113/luci,dismantl/luci-0.12,deepak78/new-luci,lcf258/openwrtcn,cshore/luci,wongsyrone/luci-1,dwmw2/luci,marcel-sch/luci,sujeet14108/luci,fkooman/luci,harveyhu2012/luci,joaofvieira/luci,lcf258/openwrtcn,ollie27/openwrt_luci,remakeelectric/luci,db260179/openwrt-bpi-r1-luci,jchuang1977/luci-1,palmettos/cnLuCI,nmav/luci,tobiaswaldvogel/luci,kuoruan/luci,teslamint/luci,Noltari/luci,oneru/luci,palmettos/cnLuCI,slayerrensky/luci,joaofvieira/luci,RuiChen1113/luci,cshore/luci,thesabbir/luci,marcel-sch/luci,daofeng2015/luci,joaofvieira/luci,keyidadi/luci,forward619/luci,nwf/openwrt-luci,bright-things/ionic-luci,tobiaswaldvogel/luci,shangjiyu/luci-with-extra,taiha/luci,harveyhu2012/luci,kuoruan/lede-luci,bittorf/luci,Sakura-Winkey/LuCI,rogerpueyo/luci,florian-shellfire/luci,florian-shellfire/luci,NeoRaider/luci,Hostle/luci,NeoRaider/luci,teslamint/luci,sujeet14108/luci,LuttyYang/luci,maxrio/luci981213,Sakura-Winkey/LuCI,NeoRaider/luci,Hostle/openwrt-luci-multi-user,ff94315/luci-1,rogerpueyo/luci,nmav/luci,schidler/ionic-luci,slayerrensky/luci,Hostle/luci,openwrt/luci,cappiewu/luci,wongsyrone/luci-1,jchuang1977/luci-1,openwrt-es/openwrt-luci,teslamint/luci,dismantl/luci-0.12,aircross/OpenWrt-Firefly-LuCI,oneru/luci,slayerrensky/luci,bright-things/ionic-luci,zhaoxx063/luci,chris5560/openwrt-luci,dismantl/luci-0.12,thesabbir/luci,nwf/openwrt-luci,remakeelectric/luci,jchuang1977/luci-1,oneru/luci,cshore/luci,palmettos/cnLuCI,obsy/luci,schidler/ionic-luci,981213/luci-1,Hostle/luci,keyidadi/luci,LuttyYang/luci,palmettos/test,harveyhu2012/luci,nmav/luci,openwrt/luci,jlopenwrtluci/luci,Wedmer/luci,fkooman/luci,RuiChen1113/luci,male-puppies/luci,joaofvieira/luci,bright-things/ionic-luci,nmav/luci,ff94315/luci-1,cappiewu/luci,thess/OpenWrt-luci,981213/luci-1,dwmw2/luci,LuttyYang/luci,nmav/luci,tobiaswaldvogel/luci,Noltari/luci,taiha/luci,male-puppies/luci,Kyklas/luci-proto-hso,wongsyrone/luci-1,male-puppies/luci,aa65535/luci,keyidadi/luci,fkooman/luci,shangjiyu/luci-with-extra,thess/OpenWrt-luci,cshore/luci,urueedi/luci,tobiaswaldvogel/luci,oneru/luci,tobiaswaldvogel/luci,nmav/luci,cappiewu/luci,forward619/luci,kuoruan/luci,palmettos/test,keyidadi/luci,thess/OpenWrt-luci,david-xiao/luci,Hostle/openwrt-luci-multi-user,chris5560/openwrt-luci,tobiaswaldvogel/luci,MinFu/luci,db260179/openwrt-bpi-r1-luci,tobiaswaldvogel/luci,joaofvieira/luci,remakeelectric/luci,lcf258/openwrtcn,wongsyrone/luci-1,nmav/luci,RuiChen1113/luci,aa65535/luci,urueedi/luci,openwrt-es/openwrt-luci,florian-shellfire/luci,zhaoxx063/luci,harveyhu2012/luci,rogerpueyo/luci,Wedmer/luci,lcf258/openwrtcn,LuttyYang/luci,schidler/ionic-luci,remakeelectric/luci,rogerpueyo/luci,schidler/ionic-luci,david-xiao/luci,jlopenwrtluci/luci,chris5560/openwrt-luci,cshore/luci,lcf258/openwrtcn,david-xiao/luci,cshore-firmware/openwrt-luci,taiha/luci,lcf258/openwrtcn,forward619/luci,rogerpueyo/luci,jlopenwrtluci/luci,cappiewu/luci,lbthomsen/openwrt-luci,david-xiao/luci,mumuqz/luci,sujeet14108/luci,joaofvieira/luci,openwrt-es/openwrt-luci,palmettos/test,jorgifumi/luci,mumuqz/luci,palmettos/cnLuCI,mumuqz/luci,aa65535/luci,lcf258/openwrtcn,ReclaimYourPrivacy/cloak-luci,forward619/luci,Wedmer/luci,palmettos/cnLuCI,Kyklas/luci-proto-hso,oneru/luci,shangjiyu/luci-with-extra,male-puppies/luci,maxrio/luci981213,thesabbir/luci,opentechinstitute/luci,forward619/luci,aircross/OpenWrt-Firefly-LuCI,aircross/OpenWrt-Firefly-LuCI,ReclaimYourPrivacy/cloak-luci,daofeng2015/luci,remakeelectric/luci,zhaoxx063/luci,Sakura-Winkey/LuCI,lbthomsen/openwrt-luci,joaofvieira/luci,cshore-firmware/openwrt-luci,RedSnake64/openwrt-luci-packages,db260179/openwrt-bpi-r1-luci,taiha/luci,chris5560/openwrt-luci,hnyman/luci,oyido/luci,taiha/luci,ollie27/openwrt_luci,NeoRaider/luci,lbthomsen/openwrt-luci,openwrt/luci,cshore/luci,nwf/openwrt-luci,shangjiyu/luci-with-extra,bright-things/ionic-luci,schidler/ionic-luci,wongsyrone/luci-1,MinFu/luci,db260179/openwrt-bpi-r1-luci,LazyZhu/openwrt-luci-trunk-mod,Hostle/luci,dwmw2/luci,hnyman/luci,Wedmer/luci,opentechinstitute/luci,bright-things/ionic-luci,dismantl/luci-0.12,db260179/openwrt-bpi-r1-luci,Kyklas/luci-proto-hso,bright-things/ionic-luci,urueedi/luci,opentechinstitute/luci,ReclaimYourPrivacy/cloak-luci,maxrio/luci981213,db260179/openwrt-bpi-r1-luci,palmettos/cnLuCI,fkooman/luci,teslamint/luci,cappiewu/luci,ff94315/luci-1,ollie27/openwrt_luci,thesabbir/luci,zhaoxx063/luci,slayerrensky/luci,bittorf/luci,Hostle/openwrt-luci-multi-user,openwrt/luci,nmav/luci,schidler/ionic-luci,Sakura-Winkey/LuCI,ReclaimYourPrivacy/cloak-luci,openwrt-es/openwrt-luci,tcatm/luci,NeoRaider/luci,ollie27/openwrt_luci,oyido/luci,Sakura-Winkey/LuCI,RedSnake64/openwrt-luci-packages,artynet/luci,nwf/openwrt-luci,keyidadi/luci,hnyman/luci,cshore-firmware/openwrt-luci,teslamint/luci,florian-shellfire/luci,LazyZhu/openwrt-luci-trunk-mod,bittorf/luci,deepak78/new-luci,Noltari/luci,aircross/OpenWrt-Firefly-LuCI,jlopenwrtluci/luci,lbthomsen/openwrt-luci,kuoruan/lede-luci,kuoruan/luci,marcel-sch/luci,NeoRaider/luci,oneru/luci,teslamint/luci,mumuqz/luci,shangjiyu/luci-with-extra,tcatm/luci,thess/OpenWrt-luci,RuiChen1113/luci,urueedi/luci,florian-shellfire/luci,thess/OpenWrt-luci,daofeng2015/luci,urueedi/luci,Hostle/openwrt-luci-multi-user,schidler/ionic-luci,lbthomsen/openwrt-luci,Kyklas/luci-proto-hso,dwmw2/luci,Hostle/openwrt-luci-multi-user,Noltari/luci,openwrt-es/openwrt-luci,obsy/luci,oyido/luci,oyido/luci,tcatm/luci,MinFu/luci,obsy/luci,dwmw2/luci,rogerpueyo/luci,jorgifumi/luci,zhaoxx063/luci,ollie27/openwrt_luci,kuoruan/lede-luci,MinFu/luci,bittorf/luci,kuoruan/luci,Sakura-Winkey/LuCI,mumuqz/luci,nwf/openwrt-luci,maxrio/luci981213,fkooman/luci,aa65535/luci,cappiewu/luci,deepak78/new-luci,cshore-firmware/openwrt-luci,keyidadi/luci,deepak78/new-luci,LazyZhu/openwrt-luci-trunk-mod,rogerpueyo/luci,LuttyYang/luci,RuiChen1113/luci,jchuang1977/luci-1,aircross/OpenWrt-Firefly-LuCI,ff94315/luci-1,fkooman/luci,LazyZhu/openwrt-luci-trunk-mod,jorgifumi/luci,chris5560/openwrt-luci,981213/luci-1,marcel-sch/luci,bright-things/ionic-luci,dismantl/luci-0.12,david-xiao/luci,male-puppies/luci,MinFu/luci,obsy/luci,openwrt-es/openwrt-luci,urueedi/luci,maxrio/luci981213,ff94315/luci-1,ff94315/luci-1,male-puppies/luci,palmettos/test,zhaoxx063/luci,oneru/luci,david-xiao/luci,forward619/luci,Hostle/openwrt-luci-multi-user,jorgifumi/luci,zhaoxx063/luci,hnyman/luci,schidler/ionic-luci,maxrio/luci981213,thess/OpenWrt-luci,openwrt/luci,lcf258/openwrtcn,Noltari/luci
|
97a381e51486224b4093385fff3ec06a60621754
|
mod_register_json/mod_register_json.lua
|
mod_register_json/mod_register_json.lua
|
-- Expose a simple servlet to handle user registrations from web pages
-- via JSON.
--
-- A Good chunk of the code is from mod_data_access.lua by Kim Alvefur
-- aka Zash.
local jid_prep = require "util.jid".prep;
local jid_split = require "util.jid".split;
local usermanager = require "core.usermanager";
local b64_decode = require "util.encodings".base64.decode;
local json_decode = require "util.json".decode;
module.host = "*" -- HTTP/BOSH Servlets need to be global.
-- Pick up configuration.
local set_realm_name = module:get_option("reg_servlet_realm") or "Restricted";
local throttle_time = module:get_option("reg_servlet_ttime") or false;
local whitelist = module:get_option("reg_servlet_wl") or {};
local blacklist = module:get_option("reg_servlet_bl") or {};
local recent_ips = {};
-- Begin
for _, ip in ipairs(whitelist) do whitelisted_ips[ip] = true; end
for _, ip in ipairs(blacklist) do blacklisted_ips[ip] = true; end
local function http_response(code, message, extra_headers)
local response = {
status = code .. " " .. message;
body = message .. "\n"; }
if extra_headers then response.headers = extra_headers; end
return response
end
local function handle_req(method, body, request)
if request.method ~= "POST" then
return http_response(405, "Bad method...", {["Allow"] = "POST"});
end
if not request.headers["authorization"] then
return http_response(401, "No... No...",
{["WWW-Authenticate"]='Basic realm="'.. set_realm_name ..'"'})
end
local user, password = b64_decode(request.headers.authorization
:match("[^ ]*$") or ""):match("([^:]*):(.*)");
user = jid_prep(user);
if not user or not password then return http_response(400, "What's this..?"); end
local user_node, user_host = jid_split(user)
if not hosts[user_host] then return http_response(401, "Negative."); end
module:log("warn", "%s is authing to submit a new user registration data", user)
if not usermanager.test_password(user_node, user_host, password) then
module:log("warn", "%s failed authentication", user)
return http_response(401, "Who the hell are you?! Guards!");
end
local req_body;
-- We check that what we have is valid JSON wise else we throw an error...
if not pcall(function() req_body = json_decode(body) end) then
module:log("debug", "JSON data submitted for user registration by %s failed to Decode.", user);
return http_response(400, "JSON Decoding failed.");
else
-- Check if user is an admin of said host
if not usermanager.is_admin(user, req_body["host"]) then
module:log("warn", "%s tried to submit registration data for %s but he's not an admin", user, req_body["host"]);
return http_response(401, "I obey only to my masters... Have a nice day.");
else
-- Checks for both Throttling/Whitelist and Blacklist (basically copycatted from prosody's register.lua code)
if blacklist[req_body["ip"]] then module:log("warn", "Attempt of reg. submission to the JSON servlet from blacklisted address: %s", req_body["ip"]); return http_response(403, "The specified address is blacklisted, sorry sorry."); end
if throttle_time and not whitelist[req_body["ip"]] then
if not recent_ips[req_body["ip"]] then
recent_ips[req_body["ip"]] = { time = os_time(), count = 1 };
else
local ip = recent_ips[req_body["ip"]];
ip.count = ip.count + 1;
if os_time() - ip.time < throttle_time then
ip.time = os_time();
module:log("warn", "JSON Registration request from %s has been throttled.", req_body["ip"]);
return http_response(503, "Woah... How many users you want to register..? Request throttled, wait a bit and try again.");
end
ip.time = os_time();
end
end
-- We first check if the supplied username for registration is already there.
if not usermanager.user_exists(req_body["username"], req_body["host"]) then
usermanager.create_user(req_body["username"], req_body["password"], req_body["host"]);
module:log("debug", "%s registration data submission for %s is successful", user, req_body["user"]);
return http_response(200, "Done.");
else
module:log("debug", "%s registration data submission for %s failed (user already exists)", user, req_body["user"]);
return http_response(409, "User already exists.");
end
end
end
end
-- Set it up!
local function setup()
local ports = module:get_option("reg_servlet_port") or { 9280 };
local base_name = module:get_option("reg_servlet_base") or "register_account";
local ssl_cert = module:get_option("reg_servlet_sslcert") or false;
local ssl_key = module:get_option("reg_servlet_sslkey") or false;
if not ssl_cert or not ssl_key then
require "net.httpserver".new_from_config(ports, handle_req, { base = base_name });
else
if module:get_option("reg_servlet_port") == nil then ports = { 9443 }; end
require "net.httpserver".new_from_config(ports, handle_req, { ssl = { key = ssl_key, certificate = ssl_cert }, base = base_name });
end
end
if prosody.start_time then -- already started
setup();
else
prosody.events.add_handler("server-started", setup);
end
|
-- Expose a simple servlet to handle user registrations from web pages
-- via JSON.
--
-- A Good chunk of the code is from mod_data_access.lua by Kim Alvefur
-- aka Zash.
local jid_prep = require "util.jid".prep;
local jid_split = require "util.jid".split;
local usermanager = require "core.usermanager";
local b64_decode = require "util.encodings".base64.decode;
local json_decode = require "util.json".decode;
module.host = "*" -- HTTP/BOSH Servlets need to be global.
-- Pick up configuration.
local set_realm_name = module:get_option("reg_servlet_realm") or "Restricted";
local throttle_time = module:get_option("reg_servlet_ttime") or false;
local whitelist = module:get_option("reg_servlet_wl") or {};
local blacklist = module:get_option("reg_servlet_bl") or {};
local recent_ips = {};
-- Begin
for _, ip in ipairs(whitelist) do whitelisted_ips[ip] = true; end
for _, ip in ipairs(blacklist) do blacklisted_ips[ip] = true; end
local function http_response(code, message, extra_headers)
local response = {
status = code .. " " .. message;
body = message .. "\n"; }
if extra_headers then response.headers = extra_headers; end
return response
end
local function handle_req(method, body, request)
if request.method ~= "POST" then
return http_response(405, "Bad method...", {["Allow"] = "POST"});
end
if not request.headers["authorization"] then
return http_response(401, "No... No...",
{["WWW-Authenticate"]='Basic realm="'.. set_realm_name ..'"'})
end
local user, password = b64_decode(request.headers.authorization
:match("[^ ]*$") or ""):match("([^:]*):(.*)");
user = jid_prep(user);
if not user or not password then return http_response(400, "What's this..?"); end
local user_node, user_host = jid_split(user)
if not hosts[user_host] then return http_response(401, "Negative."); end
module:log("warn", "%s is authing to submit a new user registration data", user)
if not usermanager.test_password(user_node, user_host, password) then
module:log("warn", "%s failed authentication", user)
return http_response(401, "Who the hell are you?! Guards!");
end
local req_body;
-- We check that what we have is valid JSON wise else we throw an error...
if not pcall(function() req_body = json_decode(body) end) then
module:log("debug", "JSON data submitted for user registration by %s failed to Decode.", user);
return http_response(400, "JSON Decoding failed.");
else
-- Decode JSON data and check that all bits are there else throw an error
req_body = json_decode(body);
if req_body["username"] == nil or req_body["password"] == nil or req_body["host"] == nil or req_body["ip"] == nil then
module:log("debug", "%s supplied an insufficent number of elements or wrong elements for the JSON registration", user);
return http_response(400, "Invalid syntax.");
end
-- Check if user is an admin of said host
if not usermanager.is_admin(user, req_body["host"]) then
module:log("warn", "%s tried to submit registration data for %s but he's not an admin", user, req_body["host"]);
return http_response(401, "I obey only to my masters... Have a nice day.");
else
-- Checks for both Throttling/Whitelist and Blacklist (basically copycatted from prosody's register.lua code)
if blacklist[req_body["ip"]] then module:log("warn", "Attempt of reg. submission to the JSON servlet from blacklisted address: %s", req_body["ip"]); return http_response(403, "The specified address is blacklisted, sorry sorry."); end
if throttle_time and not whitelist[req_body["ip"]] then
if not recent_ips[req_body["ip"]] then
recent_ips[req_body["ip"]] = { time = os_time(), count = 1 };
else
local ip = recent_ips[req_body["ip"]];
ip.count = ip.count + 1;
if os_time() - ip.time < throttle_time then
ip.time = os_time();
module:log("warn", "JSON Registration request from %s has been throttled.", req_body["ip"]);
return http_response(503, "Woah... How many users you want to register..? Request throttled, wait a bit and try again.");
end
ip.time = os_time();
end
end
-- We first check if the supplied username for registration is already there.
if not usermanager.user_exists(req_body["username"], req_body["host"]) then
usermanager.create_user(req_body["username"], req_body["password"], req_body["host"]);
module:log("debug", "%s registration data submission for %s is successful", user, req_body["user"]);
return http_response(200, "Done.");
else
module:log("debug", "%s registration data submission for %s failed (user already exists)", user, req_body["user"]);
return http_response(409, "User already exists.");
end
end
end
end
-- Set it up!
local function setup()
local ports = module:get_option("reg_servlet_port") or { 9280 };
local base_name = module:get_option("reg_servlet_base") or "register_account";
local ssl_cert = module:get_option("reg_servlet_sslcert") or false;
local ssl_key = module:get_option("reg_servlet_sslkey") or false;
if not ssl_cert or not ssl_key then
require "net.httpserver".new_from_config(ports, handle_req, { base = base_name });
else
if module:get_option("reg_servlet_port") == nil then ports = { 9443 }; end
require "net.httpserver".new_from_config(ports, handle_req, { ssl = { key = ssl_key, certificate = ssl_cert }, base = base_name });
end
end
if prosody.start_time then -- already started
setup();
else
prosody.events.add_handler("server-started", setup);
end
|
mod_register_json: Let's call it the first commit, fixed all code errors (aka it works).
|
mod_register_json: Let's call it the first commit, fixed all code errors (aka it works).
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
48fc294fcc435fbc1edf414846aac1d8c1b35d57
|
agents/monitoring/lua/lib/protocol/connection.lua
|
agents/monitoring/lua/lib/protocol/connection.lua
|
--[[
Copyright 2012 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local os = require('os')
local timer = require('timer')
local AgentProtocol = require('./protocol')
local Emitter = require('core').Emitter
local Error = require('core').Error
local JSON = require('json')
local fmt = require('string').format
local logging = require('logging')
local msg = require ('./messages')
local table = require('table')
local utils = require('utils')
-- Response timeouts in ms
local HANDSHAKE_TIMEOUT = 30000
local STATES = {}
STATES.INITIAL = 1
STATES.HANDSHAKE = 2
STATES.RUNNING = 3
local AgentProtocolConnection = Emitter:extend()
function AgentProtocolConnection:initialize(log, myid, token, conn)
assert(conn ~= nil)
assert(myid ~= nil)
self._log = log
self._myid = myid
self._token = token
self._conn = conn
self._conn:on('data', utils.bind(AgentProtocolConnection._onData, self))
self._buf = ""
self._msgid = 0
self._endpoints = { }
self._target = 'endpoint'
self._timeoutIds = {}
self._completions = {}
self:setState(STATES.INITIAL)
end
function AgentProtocolConnection:_onData(data)
local client = self._conn, obj, status
newline = data:find("\n")
if newline then
-- TODO: use a better buffer
self._buf = self._buf .. data:sub(1, newline - 1)
self._log(logging.DEBUG, fmt('RECV: %s', self._buf))
status, obj = pcall(JSON.parse, self._buf)
self._buf = data:sub(newline + 1)
if not status then
self._log(logging.ERROR, fmt('Failed to parse incoming line: line=%s,err=%s', self._buf, obj))
return
end
self:_processMessage(obj)
else
self._buf = self._buf .. data
end
end
function AgentProtocolConnection:_processMessage(msg)
-- request
if msg.method ~= nil then
self:emit('message', msg)
else
-- response
local key = msg.source .. ':' .. msg.id
local callback = self._completions[key]
if callback then
self._completions[key] = nil
callback(null, msg)
end
end
end
function AgentProtocolConnection:_send(msg, timeout, expectedCode, callback)
msg.target = 'endpoint'
msg.source = self._myid
local data = JSON.stringify(msg) .. '\n'
local key = msg.target .. ':' .. msg.id
if not expectedCode then expectedCode = 200 end
self._log(logging.DEBUG, fmt('SEND: %s', data))
if timeout then
self:_setCommandTimeoutHandler(key, timeout, callback)
end
if callback then
self._completions[key] = function(err, msg)
local result = nil
if msg and msg.result then result = msg.result end
if self._timeoutIds[key] ~= nil then
timer.clearTimer(self._timeoutIds[key])
end
if not err and msg and result and result.code and result.code ~= expectedCode then
err = Error:new(fmt('Unexpected status code returned: code=%s, message=%s', result.code, result.message))
end
callback(err, msg)
end
end
self._conn:write(data)
self._msgid = self._msgid + 1
end
--[[
Set a timeout handler for a function.
key - Command key.
timeout - Timeout in ms.
callback - Callback which is called with (err) if timeout has been reached.
]]--
function AgentProtocolConnection:_setCommandTimeoutHandler(key, timeout, callback)
local timeoutId
timeoutId = timer.setTimeout(timeout, function()
callback(Error:new(fmt('Command timeout, haven\'t received response in %d ms', timeout)))
end)
self._timeoutIds[key] = timeoutId
end
--[[ Protocol Functions ]]--
function AgentProtocolConnection:sendHandshakeHello(agentId, token, callback)
local m = msg.HandshakeHello:new(token, agentId)
self:_send(m:serialize(self._msgid), HANDSHAKE_TIMEOUT, 200, callback)
end
function AgentProtocolConnection:sendPing(timestamp, callback)
local m = msg.Ping:new(timestamp)
self:_send(m:serialize(self._msgid), nil, 200, callback)
end
function AgentProtocolConnection:sendSystemInfo(request, callback)
local m = msg.SystemInfoResponse:new(request)
self:_send(m:serialize(self._msgid), nil, 200, callback)
end
function AgentProtocolConnection:sendManifest(callback)
local m = msg.Manifest:new()
self:_send(m:serialize(self._msgid), nil, 200, callback)
end
function AgentProtocolConnection:sendMetrics(check, checkResults, callback)
local m = msg.MetricsRequest:new(check, checkResults)
self:_send(m:serialize(self._msgid), nil, 200, callback)
end
--[[ Public Functions ]] --
function AgentProtocolConnection:setState(state)
self._state = state
end
function AgentProtocolConnection:startHandshake(callback)
self:setState(STATES.HANDSHAKE)
self:sendHandshakeHello(self._myid, self._token, function(err, msg)
if err then
self._log(logging.ERR, fmt('handshake failed (message=%s)', err.message))
callback(err, msg)
return
end
if msg.result.code and msg.result.code ~= 200 then
err = Error:new(fmt('handshake failed [message=%s,code=%s]', msg.result.message, msg.result.code))
self._log(logging.ERR, err.message)
callback(err, msg)
return
end
self:setState(STATES.RUNNING)
self._log(logging.INFO, fmt('handshake successful (ping_interval=%dms)', msg.result.ping_interval))
callback(nil, msg)
end)
end
function AgentProtocolConnection:getManifest(callback)
self:sendManifest(function(err, response)
if err then
callback(err)
else
callback(nil, response.result)
end
end)
end
--[[
Process an async message
msg - The Incoming Message
]]--
function AgentProtocolConnection:execute(msg)
if msg.method == 'system.info' then
self:sendSystemInfo(msg)
else
local err = Error:new(fmt('invalid method [method=%s]', msg.method))
self:emit('error', err)
end
end
return AgentProtocolConnection
|
--[[
Copyright 2012 Rackspace
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local os = require('os')
local timer = require('timer')
local AgentProtocol = require('./protocol')
local Emitter = require('core').Emitter
local Error = require('core').Error
local JSON = require('json')
local fmt = require('string').format
local logging = require('logging')
local msg = require ('./messages')
local table = require('table')
local utils = require('utils')
-- Response timeouts in ms
local HANDSHAKE_TIMEOUT = 30000
local STATES = {}
STATES.INITIAL = 1
STATES.HANDSHAKE = 2
STATES.RUNNING = 3
local AgentProtocolConnection = Emitter:extend()
function AgentProtocolConnection:initialize(log, myid, token, conn)
assert(conn ~= nil)
assert(myid ~= nil)
self._log = log
self._myid = myid
self._token = token
self._conn = conn
self._conn:on('data', utils.bind(AgentProtocolConnection._onData, self))
self._buf = ''
self._msgid = 0
self._endpoints = { }
self._target = 'endpoint'
self._timeoutIds = {}
self._completions = {}
self:setState(STATES.INITIAL)
end
function AgentProtocolConnection:_popLine()
local line = false
local index = self._buf:find('\n')
if index then
line = self._buf:sub(0, index - 1)
self._buf = self._buf:sub(index + 1)
end
return line
end
function AgentProtocolConnection:_onData(data)
local obj, status, line
self._buf = self._buf .. data
line = self:_popLine()
while line do
status, obj = pcall(JSON.parse, line)
if not status then
self._log(logging.ERROR, fmt('Failed to parse incoming line: line="%s",err=%s', line, obj))
else
self:_processMessage(obj)
end
line = self:_popLine()
end
end
function AgentProtocolConnection:_processMessage(msg)
-- request
if msg.method ~= nil then
self:emit('message', msg)
else
-- response
local key = msg.source .. ':' .. msg.id
local callback = self._completions[key]
if callback then
self._completions[key] = nil
callback(null, msg)
end
end
end
function AgentProtocolConnection:_send(msg, timeout, expectedCode, callback)
msg.target = 'endpoint'
msg.source = self._myid
local data = JSON.stringify(msg) .. '\n'
local key = msg.target .. ':' .. msg.id
if not expectedCode then expectedCode = 200 end
self._log(logging.DEBUG, fmt('SEND: %s', data))
if timeout then
self:_setCommandTimeoutHandler(key, timeout, callback)
end
if callback then
self._completions[key] = function(err, msg)
local result = nil
if msg and msg.result then result = msg.result end
if self._timeoutIds[key] ~= nil then
timer.clearTimer(self._timeoutIds[key])
end
if not err and msg and result and result.code and result.code ~= expectedCode then
err = Error:new(fmt('Unexpected status code returned: code=%s, message=%s', result.code, result.message))
end
callback(err, msg)
end
end
self._conn:write(data)
self._msgid = self._msgid + 1
end
--[[
Set a timeout handler for a function.
key - Command key.
timeout - Timeout in ms.
callback - Callback which is called with (err) if timeout has been reached.
]]--
function AgentProtocolConnection:_setCommandTimeoutHandler(key, timeout, callback)
local timeoutId
timeoutId = timer.setTimeout(timeout, function()
callback(Error:new(fmt('Command timeout, haven\'t received response in %d ms', timeout)))
end)
self._timeoutIds[key] = timeoutId
end
--[[ Protocol Functions ]]--
function AgentProtocolConnection:sendHandshakeHello(agentId, token, callback)
local m = msg.HandshakeHello:new(token, agentId)
self:_send(m:serialize(self._msgid), HANDSHAKE_TIMEOUT, 200, callback)
end
function AgentProtocolConnection:sendPing(timestamp, callback)
local m = msg.Ping:new(timestamp)
self:_send(m:serialize(self._msgid), nil, 200, callback)
end
function AgentProtocolConnection:sendSystemInfo(request, callback)
local m = msg.SystemInfoResponse:new(request)
self:_send(m:serialize(self._msgid), nil, 200, callback)
end
function AgentProtocolConnection:sendManifest(callback)
local m = msg.Manifest:new()
self:_send(m:serialize(self._msgid), nil, 200, callback)
end
function AgentProtocolConnection:sendMetrics(check, checkResults, callback)
local m = msg.MetricsRequest:new(check, checkResults)
self:_send(m:serialize(self._msgid), nil, 200, callback)
end
--[[ Public Functions ]] --
function AgentProtocolConnection:setState(state)
self._state = state
end
function AgentProtocolConnection:startHandshake(callback)
self:setState(STATES.HANDSHAKE)
self:sendHandshakeHello(self._myid, self._token, function(err, msg)
if err then
self._log(logging.ERR, fmt('handshake failed (message=%s)', err.message))
callback(err, msg)
return
end
if msg.result.code and msg.result.code ~= 200 then
err = Error:new(fmt('handshake failed [message=%s,code=%s]', msg.result.message, msg.result.code))
self._log(logging.ERR, err.message)
callback(err, msg)
return
end
self:setState(STATES.RUNNING)
self._log(logging.INFO, fmt('handshake successful (ping_interval=%dms)', msg.result.ping_interval))
callback(nil, msg)
end)
end
function AgentProtocolConnection:getManifest(callback)
self:sendManifest(function(err, response)
if err then
callback(err)
else
callback(nil, response.result)
end
end)
end
--[[
Process an async message
msg - The Incoming Message
]]--
function AgentProtocolConnection:execute(msg)
if msg.method == 'system.info' then
self:sendSystemInfo(msg)
else
local err = Error:new(fmt('invalid method [method=%s]', msg.method))
self:emit('error', err)
end
end
return AgentProtocolConnection
|
Fix line parsing - use a better approach.
|
Fix line parsing - use a better approach.
|
Lua
|
apache-2.0
|
kans/zirgo,kans/zirgo,kans/zirgo
|
3334bf8fe7692d352cae9ab5f93af939cdb9c298
|
reader.lua
|
reader.lua
|
#!./luajit
-- load default settings
require "defaults"
local DataStorage = require("datastorage")
pcall(dofile, DataStorage:getDataDir() .. "/defaults.persistent.lua")
-- set search path for 'require()'
package.path =
"common/?.lua;rocks/share/lua/5.1/?.lua;frontend/?.lua;" ..
package.path
package.cpath =
"common/?.so;common/?.dll;/usr/lib/lua/?.so;rocks/lib/lua/5.1/?.so;" ..
package.cpath
-- set search path for 'ffi.load()'
local ffi = require("ffi")
local util = require("ffi/util")
ffi.cdef[[
char *getenv(const char *name);
int putenv(const char *envvar);
int _putenv(const char *envvar);
]]
if ffi.os == "Windows" then
ffi.C._putenv("PATH=libs;common;")
end
local DocSettings = require("docsettings")
local _ = require("gettext")
-- read settings and check for language override
-- has to be done before requiring other files because
-- they might call gettext on load
G_reader_settings = DocSettings:open(".reader")
local lang_locale = G_reader_settings:readSetting("language")
if lang_locale then
_.changeLang(lang_locale)
end
-- option parsing:
local longopts = {
debug = "d",
profile = "p",
help = "h",
}
local function showusage()
print("usage: ./reader.lua [OPTION] ... path")
print("Read all the books on your E-Ink reader")
print("")
print("-d start in debug mode")
print("-p enable Lua code profiling")
print("-h show this usage help")
print("")
print("If you give the name of a directory instead of a file path, a file")
print("chooser will show up and let you select a file")
print("")
print("If you don't pass any path, the last viewed document will be opened")
print("")
print("This software is licensed under the AGPLv3.")
print("See http://github.com/koreader/koreader for more info.")
return
end
-- should check DEBUG option in arg and turn on DEBUG before loading other
-- modules, otherwise DEBUG in some modules may not be printed.
local DEBUG = require("dbg")
local Profiler = nil
local ARGV = arg
local argidx = 1
while argidx <= #ARGV do
local arg = ARGV[argidx]
argidx = argidx + 1
if arg == "--" then break end
-- parse longopts
if arg:sub(1,2) == "--" then
local opt = longopts[arg:sub(3)]
if opt ~= nil then arg = "-"..opt end
end
-- code for each option
if arg == "-h" then
return showusage()
elseif arg == "-d" then
DEBUG:turnOn()
elseif arg == "-p" then
Profiler = require("jit.p")
Profiler.start("la")
else
-- not a recognized option, should be a filename
argidx = argidx - 1
break
end
end
local lfs = require("libs/libkoreader-lfs")
local UIManager = require("ui/uimanager")
local Device = require("device")
local Screen = require("device").screen
local Font = require("ui/font")
-- read some global reader setting here:
-- font
local fontmap = G_reader_settings:readSetting("fontmap")
if fontmap ~= nil then
Font.fontmap = fontmap
end
-- last file
local last_file = G_reader_settings:readSetting("lastfile")
if last_file and lfs.attributes(last_file, "mode") ~= "file" then
last_file = nil
end
-- load last opened file
local open_last = G_reader_settings:readSetting("open_last")
-- night mode
if G_reader_settings:readSetting("night_mode") then
Screen:toggleNightMode()
end
-- restore kobo frontlight settings and probe kobo touch coordinates
if Device:isKobo() then
local powerd = Device:getPowerDevice()
if powerd and powerd.restore_settings then
-- UIManager:init() should have sanely set up the frontlight_stuff by this point
local intensity = G_reader_settings:readSetting("frontlight_intensity")
powerd.fl_intensity = intensity or powerd.fl_intensity
local is_frontlight_on = G_reader_settings:readSetting("is_frontlight_on")
if is_frontlight_on then
-- default powerd.is_fl_on is false, turn it on
powerd:toggleFrontlight()
else
-- the light can still be turned on manually outside of koreader
-- or nickel. so we always set the intensity to 0 here to keep it
-- in sync with powerd.is_fl_on (false by default)
-- NOTE: we cant use setIntensity method here because for kobo the
-- min intensity is 1 :(
powerd.fl:setBrightness(0)
end
end
if Device:getCodeName() == "trilogy" then
require("utils/kobo_touch_probe")
end
end
if ARGV[argidx] and ARGV[argidx] ~= "" then
local file = nil
if lfs.attributes(ARGV[argidx], "mode") == "file" then
file = ARGV[argidx]
elseif open_last and last_file then
file = last_file
end
-- if file is given in command line argument or open last document is set
-- true, the given file or the last file is opened in the reader
if file then
local ReaderUI = require("apps/reader/readerui")
ReaderUI:showReader(file)
-- we assume a directory is given in command line argument
-- the filemanger will show the files in that path
else
local FileManager = require("apps/filemanager/filemanager")
local home_dir =
G_reader_settings:readSetting("home_dir") or ARGV[argidx]
FileManager:showFiles(home_dir)
end
UIManager:run()
elseif last_file then
local ReaderUI = require("apps/reader/readerui")
ReaderUI:showReader(last_file)
UIManager:run()
else
return showusage()
end
local function exitReader()
local ReaderActivityIndicator =
require("apps/reader/modules/readeractivityindicator")
G_reader_settings:close()
-- Close lipc handles
ReaderActivityIndicator:coda()
-- shutdown hardware abstraction
Device:exit()
if Profiler then Profiler.stop() end
os.exit(0)
end
exitReader()
|
#!./luajit
-- load default settings
require "defaults"
local DataStorage = require("datastorage")
pcall(dofile, DataStorage:getDataDir() .. "/defaults.persistent.lua")
-- set search path for 'require()'
package.path =
"common/?.lua;rocks/share/lua/5.1/?.lua;frontend/?.lua;" ..
package.path
package.cpath =
"common/?.so;common/?.dll;/usr/lib/lua/?.so;rocks/lib/lua/5.1/?.so;" ..
package.cpath
-- set search path for 'ffi.load()'
local ffi = require("ffi")
local util = require("ffi/util")
ffi.cdef[[
char *getenv(const char *name);
int putenv(const char *envvar);
int _putenv(const char *envvar);
]]
if ffi.os == "Windows" then
ffi.C._putenv("PATH=libs;common;")
end
local DocSettings = require("docsettings")
local _ = require("gettext")
-- read settings and check for language override
-- has to be done before requiring other files because
-- they might call gettext on load
G_reader_settings = DocSettings:open(".reader")
local lang_locale = G_reader_settings:readSetting("language")
if lang_locale then
_.changeLang(lang_locale)
end
-- option parsing:
local longopts = {
debug = "d",
profile = "p",
help = "h",
}
local function showusage()
print("usage: ./reader.lua [OPTION] ... path")
print("Read all the books on your E-Ink reader")
print("")
print("-d start in debug mode")
print("-p enable Lua code profiling")
print("-h show this usage help")
print("")
print("If you give the name of a directory instead of a file path, a file")
print("chooser will show up and let you select a file")
print("")
print("If you don't pass any path, the last viewed document will be opened")
print("")
print("This software is licensed under the AGPLv3.")
print("See http://github.com/koreader/koreader for more info.")
return
end
-- should check DEBUG option in arg and turn on DEBUG before loading other
-- modules, otherwise DEBUG in some modules may not be printed.
local DEBUG = require("dbg")
local Profiler = nil
local ARGV = arg
local argidx = 1
while argidx <= #ARGV do
local arg = ARGV[argidx]
argidx = argidx + 1
if arg == "--" then break end
-- parse longopts
if arg:sub(1,2) == "--" then
local opt = longopts[arg:sub(3)]
if opt ~= nil then arg = "-"..opt end
end
-- code for each option
if arg == "-h" then
return showusage()
elseif arg == "-d" then
DEBUG:turnOn()
elseif arg == "-p" then
Profiler = require("jit.p")
Profiler.start("la")
else
-- not a recognized option, should be a filename
argidx = argidx - 1
break
end
end
local lfs = require("libs/libkoreader-lfs")
local UIManager = require("ui/uimanager")
local Device = require("device")
local Screen = require("device").screen
local Font = require("ui/font")
-- read some global reader setting here:
-- font
local fontmap = G_reader_settings:readSetting("fontmap")
if fontmap ~= nil then
Font.fontmap = fontmap
end
-- last file
local last_file = G_reader_settings:readSetting("lastfile")
if last_file and lfs.attributes(last_file, "mode") ~= "file" then
last_file = nil
end
-- load last opened file
local open_last = G_reader_settings:readSetting("open_last")
-- night mode
if G_reader_settings:readSetting("night_mode") then
Screen:toggleNightMode()
end
-- restore kobo frontlight settings and probe kobo touch coordinates
if Device:isKobo() then
local powerd = Device:getPowerDevice()
if powerd and powerd.restore_settings then
-- UIManager:init() should have sanely set up the frontlight_stuff by this point
local intensity = G_reader_settings:readSetting("frontlight_intensity")
powerd.fl_intensity = intensity or powerd.fl_intensity
local is_frontlight_on = G_reader_settings:readSetting("is_frontlight_on")
if is_frontlight_on then
-- default powerd.is_fl_on is false, turn it on
powerd:toggleFrontlight()
else
-- the light can still be turned on manually outside of koreader
-- or nickel. so we always set the intensity to 0 here to keep it
-- in sync with powerd.is_fl_on (false by default)
-- NOTE: we cant use setIntensity method here because for kobo the
-- min intensity is 1 :(
powerd.fl:setBrightness(0)
end
end
if Device:getCodeName() == "trilogy" then
require("utils/kobo_touch_probe")
end
end
if ARGV[argidx] and ARGV[argidx] ~= "" then
local file = nil
if lfs.attributes(ARGV[argidx], "mode") == "file" then
file = ARGV[argidx]
elseif open_last and last_file then
file = last_file
end
-- if file is given in command line argument or open last document is set
-- true, the given file or the last file is opened in the reader
if file then
local ReaderUI = require("apps/reader/readerui")
UIManager:nextTick(function()
ReaderUI:showReader(file)
end)
-- we assume a directory is given in command line argument
-- the filemanger will show the files in that path
else
local FileManager = require("apps/filemanager/filemanager")
local home_dir =
G_reader_settings:readSetting("home_dir") or ARGV[argidx]
UIManager:nextTick(function()
FileManager:showFiles(home_dir)
end)
end
UIManager:run()
elseif last_file then
local ReaderUI = require("apps/reader/readerui")
UIManager:nextTick(function()
ReaderUI:showReader(last_file)
end)
UIManager:run()
else
return showusage()
end
local function exitReader()
local ReaderActivityIndicator =
require("apps/reader/modules/readeractivityindicator")
G_reader_settings:close()
-- Close lipc handles
ReaderActivityIndicator:coda()
-- shutdown hardware abstraction
Device:exit()
if Profiler then Profiler.stop() end
os.exit(0)
end
exitReader()
|
fix: delay showReader after UIManager:run is called
|
fix: delay showReader after UIManager:run is called
|
Lua
|
agpl-3.0
|
Markismus/koreader,koreader/koreader,Hzj-jie/koreader,robert00s/koreader,Frenzie/koreader,lgeek/koreader,NiLuJe/koreader,pazos/koreader,houqp/koreader,mwoz123/koreader,poire-z/koreader,chihyang/koreader,Frenzie/koreader,koreader/koreader,NiLuJe/koreader,frankyifei/koreader,apletnev/koreader,NickSavage/koreader,mihailim/koreader,poire-z/koreader
|
eb06ee140485359e0110fe0fa0b54887a2f8713c
|
test/test-gridfs.lua
|
test/test-gridfs.lua
|
local test = require 'test'
local client = mongo.Client(test.uri)
local gridfs = client:getGridFS(test.dbname)
local chunks = gridfs:getChunks()
local files = gridfs:getFiles()
gridfs:drop()
local t = {}
for i = 1, 50000 do
t[#t + 1] = ('%s'):format(i % 10)
end
local data = table.concat(t)
-- GridFS file
local file = assert(gridfs:createFile())
assert(file:getAliases() == nil)
assert(file:getChunkSize() > 0)
assert(file:getContentType() == nil)
assert(file:getFilename() == nil)
assert(mongo.type(file:getId()) == 'mongo.ObjectID')
assert(file:getLength() == 0)
assert(file:getMD5() == nil)
assert(file:getMetadata() == nil)
-- FIXME This fails on 32-bit system due to bug in mongoc_gridfs_file_get_upload_date(); bug report pending
-- assert(file:getUploadDate() > 0)
file:setAliases '[ "a", "b" ]'
file:setContentType('content-type1')
file:setFilename('myfile1')
file:setId(123)
file:setMD5('abc')
file:setMetadata '{ "a" : 1, "b" : 2 }'
assert(file:save())
assert(tostring(file:getAliases()) == '{ "0" : "a", "1" : "b" }')
assert(file:getContentType() == 'content-type1')
assert(file:getFilename() == 'myfile1')
assert(file:getId() == 123)
assert(file:getMD5() == 'abc')
assert(tostring(file:getMetadata()) == '{ "a" : 1, "b" : 2 }')
assert(file:write(data) == #data)
assert(file:read(#data) == nil) -- Reading past the end -> EOF
assert(file:seek(0))
assert(file:tell() == 0)
assert(file:read(#data) == data) -- Reading from the beginning
assert(file:tell() == #data)
file = nil
collectgarbage()
file = assert(gridfs:createFile {
aliases = '[ "a", "b", "c" ]',
chunkSize = 10000,
contentType = 'content-type2',
filename = 'myfile2',
md5 = 'def',
metadata = '{ "a" : 1, "b" : 2, "c" : 3 }',
})
assert(tostring(file:getAliases()) == '{ "0" : "a", "1" : "b", "2" : "c" }')
assert(file:getChunkSize() == 10000)
assert(file:getContentType() == 'content-type2')
assert(file:getFilename() == 'myfile2')
assert(file:getMD5() == 'def')
assert(tostring(file:getMetadata()) == '{ "a" : 1, "b" : 2, "c" : 3 }')
-- Write in chunks
local m, n = 0, 256
while m < #data do
local d = data:sub(m + 1, n)
assert(file:write(d) == #d)
m = m + #d
n = n * 2
end
assert(file:read(#data) == nil) -- Reading past the end -> EOF
assert(file:seek(0))
assert(file:tell() == 0)
-- Read in chunks
local m, n = 0, 256
while true do
local d, e = file:read(n)
if d == nil then
assert(e == nil) -- No error, plain EOF
break
end
m = m + #d
n = n * 2
end
assert(m == #data)
assert(file:tell() == #data)
assert(file:seek(10, 'end'))
assert(file:tell() == #data + 10)
assert(file:seek(10, 'cur'))
assert(file:tell() == #data + 20)
assert(not file:seek(-10)) -- Invalid 'offset'
test.failure(file.seek, file, 10, 'aaa') -- Invalid 'whence'
assert(chunks:count() == 5)
assert(files:count() == 2)
-- list:next()
local list = gridfs:find {} -- Find all
assert(mongo.type(list:next()) == 'mongo.GridFSFile') -- #1
assert(mongo.type(list:next()) == 'mongo.GridFSFile') -- #2
local r, e = list:next()
assert(r == nil and e == nil) -- nil + no error
r, e = list:next()
assert(r == nil and type(e) == 'string') -- nil + error
collectgarbage()
-- list:iterator()
local i, s = gridfs:find({}, { sort = { filename = 1 } }):iterator()
local f1 = assert(i(s))
local f2 = assert(i(s))
assert(f1:getFilename() == 'myfile1')
assert(f2:getFilename() == 'myfile2')
assert(i(s) == nil) -- No more items
test.failure(i, s) -- Exception is thrown
collectgarbage()
assert(file:remove())
-- gridfs:createFileFrom()
test.error(gridfs:createFileFrom('NON-EXISTENT-FILE'))
local f = io.open(test.filename, 'w')
if f then
f:write(data)
f:close()
file = assert(gridfs:createFileFrom(test.filename, { filename = 'myfile3' }))
os.remove(test.filename)
assert(file:read(#data) == data)
assert(file:tell() == #data)
assert(file:remove())
else
print 'gridfs:createFileFrom() testing skipped - unable to create local file!'
end
file = nil
collectgarbage()
-- GridFS
assert(gridfs:findOne { _id = 123 })
assert(gridfs:findOneByFilename('myfile1'))
-- FIXME Follow up with bug report: https://jira.mongodb.org/browse/CDRIVER-2006
-- test.error(gridfs:findOne { filename = 'myfile2' })
-- test.error(gridfs:findOneByFilename('myfile2'))
assert(gridfs:removeByFilename('myfile1'))
assert(chunks:count() == 0)
assert(files:count() == 0)
assert(gridfs:drop())
-- FIXME Follow up with bug report: https://jira.mongodb.org/browse/CDRIVER-2007
-- local c = mongo.Client 'mongodb://INVALID-URI'
-- test.error(c:getGridFS(test.dbname))
|
local test = require 'test'
local client = mongo.Client(test.uri)
local gridfs = client:getGridFS(test.dbname)
local chunks = gridfs:getChunks()
local files = gridfs:getFiles()
gridfs:drop()
local t = {}
for i = 1, 50000 do
t[#t + 1] = ('%s'):format(i % 10)
end
local data = table.concat(t)
-- GridFS file
local file = assert(gridfs:createFile())
assert(file:getAliases() == nil)
assert(file:getChunkSize() > 0)
assert(file:getContentType() == nil)
assert(file:getFilename() == nil)
assert(mongo.type(file:getId()) == 'mongo.ObjectID')
assert(file:getLength() == 0)
assert(file:getMD5() == nil)
assert(file:getMetadata() == nil)
-- FIXME Follow up with bug report: https://jira.mongodb.org/browse/CDRIVER-2028
-- assert(file:getUploadDate() > 1486000000)
file:setAliases '[ "a", "b" ]'
file:setContentType('content-type1')
file:setFilename('myfile1')
file:setId(123)
file:setMD5('abc')
file:setMetadata '{ "a" : 1, "b" : 2 }'
assert(file:save())
assert(tostring(file:getAliases()) == '{ "0" : "a", "1" : "b" }')
assert(file:getContentType() == 'content-type1')
assert(file:getFilename() == 'myfile1')
assert(file:getId() == 123)
assert(file:getMD5() == 'abc')
assert(tostring(file:getMetadata()) == '{ "a" : 1, "b" : 2 }')
assert(file:write(data) == #data)
assert(file:read(#data) == nil) -- Reading past the end -> EOF
assert(file:seek(0))
assert(file:tell() == 0)
assert(file:read(#data) == data) -- Reading from the beginning
assert(file:tell() == #data)
file = nil
collectgarbage()
file = assert(gridfs:createFile {
aliases = '[ "a", "b", "c" ]',
chunkSize = 10000,
contentType = 'content-type2',
filename = 'myfile2',
md5 = 'def',
metadata = '{ "a" : 1, "b" : 2, "c" : 3 }',
})
assert(tostring(file:getAliases()) == '{ "0" : "a", "1" : "b", "2" : "c" }')
assert(file:getChunkSize() == 10000)
assert(file:getContentType() == 'content-type2')
assert(file:getFilename() == 'myfile2')
assert(file:getMD5() == 'def')
assert(tostring(file:getMetadata()) == '{ "a" : 1, "b" : 2, "c" : 3 }')
-- Write in chunks
local m, n = 0, 256
while m < #data do
local d = data:sub(m + 1, n)
assert(file:write(d) == #d)
m = m + #d
n = n * 2
end
assert(file:read(#data) == nil) -- Reading past the end -> EOF
assert(file:seek(0))
assert(file:tell() == 0)
-- Read in chunks
local m, n = 0, 256
while true do
local d, e = file:read(n)
if d == nil then
assert(e == nil) -- No error, plain EOF
break
end
m = m + #d
n = n * 2
end
assert(m == #data)
assert(file:tell() == #data)
assert(file:seek(10, 'end'))
assert(file:tell() == #data + 10)
assert(file:seek(10, 'cur'))
assert(file:tell() == #data + 20)
assert(not file:seek(-10)) -- Invalid 'offset'
test.failure(file.seek, file, 10, 'aaa') -- Invalid 'whence'
assert(chunks:count() == 5)
assert(files:count() == 2)
-- list:next()
local list = gridfs:find {} -- Find all
assert(mongo.type(list:next()) == 'mongo.GridFSFile') -- #1
assert(mongo.type(list:next()) == 'mongo.GridFSFile') -- #2
local r, e = list:next()
assert(r == nil and e == nil) -- nil + no error
r, e = list:next()
assert(r == nil and type(e) == 'string') -- nil + error
collectgarbage()
-- list:iterator()
local i, s = gridfs:find({}, { sort = { filename = 1 } }):iterator()
local f1 = assert(i(s))
local f2 = assert(i(s))
assert(f1:getFilename() == 'myfile1')
assert(f2:getFilename() == 'myfile2')
assert(i(s) == nil) -- No more items
test.failure(i, s) -- Exception is thrown
collectgarbage()
assert(file:remove())
-- gridfs:createFileFrom()
test.error(gridfs:createFileFrom('NON-EXISTENT-FILE'))
local f = io.open(test.filename, 'w')
if f then
f:write(data)
f:close()
file = assert(gridfs:createFileFrom(test.filename, { filename = 'myfile3' }))
os.remove(test.filename)
assert(file:read(#data) == data)
assert(file:tell() == #data)
assert(file:remove())
else
print 'gridfs:createFileFrom() testing skipped - unable to create local file!'
end
file = nil
collectgarbage()
-- GridFS
assert(gridfs:findOne { _id = 123 })
assert(gridfs:findOneByFilename('myfile1'))
-- FIXME Follow up with bug report: https://jira.mongodb.org/browse/CDRIVER-2006
-- test.error(gridfs:findOne { filename = 'myfile2' })
-- test.error(gridfs:findOneByFilename('myfile2'))
assert(gridfs:removeByFilename('myfile1'))
assert(chunks:count() == 0)
assert(files:count() == 0)
assert(gridfs:drop())
-- FIXME Follow up with bug report: https://jira.mongodb.org/browse/CDRIVER-2007
-- local c = mongo.Client 'mongodb://INVALID-URI'
-- test.error(c:getGridFS(test.dbname))
|
Test: add bug report reference
|
Test: add bug report reference
|
Lua
|
mit
|
neoxic/lua-mongo
|
d98d050989b5d6a5dce1f96cce01c47a68616fa6
|
lua/starfall/libs_sh/serverinfo.lua
|
lua/starfall/libs_sh/serverinfo.lua
|
--- Server info functions.
-- @shared
local serverinfo_library, _ = SF.Libraries.Register("serverinfo")
--- Same as Glua's physenv.GetPerformanceSettings()
--@return Table containing physics environment settings
function serverinfo_library.GetPerformanceSettings()
return physenv.GetPerformanceSettings()
end
--- Same as Glua's physenv.GetGravity()
--@return Vector describing acceleration due to gravity setting
function serverinfo_library.GetGravity()
return physenv.GetGravity()
end
--- Same as Glua's physenv.GetAirDensity()
--@return Number describing air density setting
function serverinfo_library.GetAirDensity()
return physenv.GetAirDensity()
end
--- Same as Glua's game.GetMap()
--@return The map name as a string
function serverinfo_library.GetMap()
return game.GetMap()
end
--- Returns The hostname convar
--@return The hostname convar
function serverinfo_library.GetHostname()
return GetConVar("hostname"):GetString()
end
--- Returns true if the server is on a LAN
function serverinfo_library.isLan()
return GetConVar("sv_lan"):GetBool()
end
--- Returns the gamemode as a String
--@return The name of the gamemode
function serverinfo_library.GetGamemode()
return gmod.GetGamemode().Name
end
--- Same as GLua's SinglePlayer()
function serverinfo_library.SinglePlayer()
return SinglePlayer()
end
--- Same as GLua's isDedicatedServer()
function serverinfo_library.isDedicatedServer()
return isDedicatedServer()
end
--- Returns the number of players on the server
--@return The number of players on the server
function serverinfo_library.numPlayers()
return #player.GetAll()
end
--- Same as GLua's MaxPlayers()
function serverinfo_library.MaxPlayers()
return MaxPlayers()
end
|
--- Server info functions.
-- @shared
local serverinfo_library, _ = SF.Libraries.Register("serverinfo")
--- Returns a table containing physics environment settings. See GLua's physenv.GetPerformanceSettings()
-- for more info.
function serverinfo_library.performanceSettings()
return table.Copy(physenv.GetPerformanceSettings())
end
--- Returns the server's acceleration due to gravity vector.
function serverinfo_library.gravity()
return physenv.GetGravity()
end
--- Returns the air density. See Glua's physenv.GetAirDensity()
function serverinfo_library.airDensity()
return physenv.GetAirDensity()
end
--- Returns the map name
function serverinfo_library.map()
return game.GetMap()
end
--- Returns The hostname
function serverinfo_library.hostname()
return GetConVar("hostname"):GetString()
end
--- Returns true if the server is on a LAN
function serverinfo_library.isLan()
return GetConVar("sv_lan"):GetBool()
end
--- Returns the gamemode as a String
function serverinfo_library.gamemode()
return gmod.GetGamemode().Name
end
--- Returns whether or not the current game is single player
function serverinfo_library.isSinglePlayer()
return SinglePlayer()
end
--- Returns whether or not the server is a dedicated server
function serverinfo_library.isDedicatedServer()
return isDedicatedServer()
end
--- Returns the number of players on the server
function serverinfo_library.numPlayers()
return #player.GetAll()
end
--- Returns the maximum player limit
function serverinfo_library.maxPlayers()
return MaxPlayers()
end
|
Fixed serverinfo naming conventions, and modified documentation
|
Fixed serverinfo naming conventions, and modified documentation
|
Lua
|
bsd-3-clause
|
Jazzelhawk/Starfall,Xandaros/Starfall,Ingenious-Gaming/Starfall,Jazzelhawk/Starfall,INPStarfall/Starfall,Xandaros/Starfall,INPStarfall/Starfall,Ingenious-Gaming/Starfall
|
2d6e83e688e54cccf3eb3149f8a28acd71dda5b2
|
neovim/.config/nvim/lua/plugins.lua
|
neovim/.config/nvim/lua/plugins.lua
|
-- Only required if you have packer in your `opt` pack
vim.cmd [[packadd packer.nvim]]
return require('packer').startup(function(use)
-- Packer can manage itself as an optional plugin
use {'wbthomason/packer.nvim', opt = true}
use 'justinmk/vim-ipmotion'
use 'arp242/jumpy.vim'
use {
'bronzehedwick/vim-colors-xcode',
branch = 'lsp-treesitter-highlights'
}
use 'cormacrelf/dark-notify'
use 'justinmk/vim-dirvish'
use 'mbbill/undotree'
use 'neovim/nvim-lspconfig'
use 'bronzehedwick/vim-primary-terminal'
use 'phaazon/hop.nvim'
-- Disabled until #37 is resolved.
-- https://github.com/rstacruz/vim-closer/issues/37
-- use 'rstacruz/vim-closer'
use 'tommcdo/vim-fubitive'
use 'tpope/vim-commentary'
use 'tpope/vim-eunuch'
use 'tpope/vim-fugitive'
use 'tpope/vim-rhubarb'
use 'tpope/vim-repeat'
use 'tpope/vim-rsi'
use 'tpope/vim-sleuth'
use 'tpope/vim-surround'
use 'tpope/vim-unimpaired'
use 'vim-scripts/fountain.vim'
use { 'mattn/emmet-vim', opt = true }
use { 'nvim-treesitter/nvim-treesitter', run = ':TSUpdate' }
use { 'nvim-orgmode/orgmode', config = function()
require('orgmode').setup{}
end }
use {
'tpope/vim-dispatch',
opt = true,
cmd = {'Dispatch', 'Make', 'Focus', 'Start'}
}
end)
|
-- Only required if you have packer in your `opt` pack
vim.cmd [[packadd packer.nvim]]
return require('packer').startup(function(use)
-- Packer can manage itself as an optional plugin
use {'wbthomason/packer.nvim', opt = true}
use 'justinmk/vim-ipmotion'
use 'arp242/jumpy.vim'
use {
'bronzehedwick/vim-colors-xcode',
branch = 'lsp-treesitter-highlights'
}
use 'cormacrelf/dark-notify'
use 'justinmk/vim-dirvish'
use 'mbbill/undotree'
use 'neovim/nvim-lspconfig'
use 'bronzehedwick/vim-primary-terminal'
use 'phaazon/hop.nvim'
use 'rstacruz/vim-closer'
use 'tommcdo/vim-fubitive'
use 'tpope/vim-commentary'
use 'tpope/vim-eunuch'
use 'tpope/vim-fugitive'
use 'tpope/vim-rhubarb'
use 'tpope/vim-repeat'
use 'tpope/vim-rsi'
use 'tpope/vim-sleuth'
use 'tpope/vim-surround'
use 'tpope/vim-unimpaired'
use 'vim-scripts/fountain.vim'
use { 'mattn/emmet-vim', opt = true }
use { 'nvim-treesitter/nvim-treesitter', run = ':TSUpdate' }
use { 'nvim-orgmode/orgmode', config = function()
require('orgmode').setup{}
end }
use {
'tpope/vim-dispatch',
opt = true,
cmd = {'Dispatch', 'Make', 'Focus', 'Start'}
}
end)
|
Add back vim closer
|
Add back vim closer
The bug is fixed!
|
Lua
|
mit
|
bronzehedwick/dotfiles,bronzehedwick/dotfiles,bronzehedwick/dotfiles,bronzehedwick/dotfiles
|
504e83b1316fc43460f68a87273852bae8116d62
|
scripts/openal.lua
|
scripts/openal.lua
|
--
-- Copyright (c) 2012-2020 Daniele Bartolini and individual contributors.
-- License: https://github.com/dbartolini/crown/blob/master/LICENSE
--
function openal_project(_kind)
project "openal"
kind (_kind)
configuration {}
local AL_DIR = (CROWN_DIR .. "3rdparty/openal/")
defines {
"_LARGE_FILES",
"_LARGEFILE_SOURCE",
"AL_ALEXT_PROTOTYPES",
"AL_BUILD_LIBRARY",
"HAVE_C99_BOOL",
"HAVE_FENV_H",
"HAVE_FLOAT_H",
"HAVE_LRINTF",
"HAVE_MALLOC_H",
"HAVE_STAT",
"HAVE_STDBOOL_H",
"HAVE_STDINT_H",
"HAVE_STRTOF",
}
configuration { "not vs*" }
defines {
"HAVE_C99_VLA",
"HAVE_DIRENT_H",
"HAVE_GCC_DESTRUCTOR",
"HAVE_GCC_FORMAT",
"HAVE_PTHREAD_SETNAME_NP",
"HAVE_PTHREAD_SETSCHEDPARAM",
"HAVE_STRINGS_H",
"restrict=__restrict",
"SIZEOF_LONG=8",
"SIZEOF_LONG_LONG=8",
-- These are needed on non-Windows systems for extra features
"_GNU_SOURCE=1",
"_POSIX_C_SOURCE=200809L",
"_XOPEN_SOURCE=700",
}
buildoptions {
"-fPIC",
"-Winline",
"-fvisibility=hidden",
"-fexceptions" -- :(
}
configuration { "linux-* or android-*" }
defines {
"HAVE_DLFCN_H",
"HAVE_GCC_GET_CPUID",
}
configuration { "not android-*" }
defines {
"HAVE_SSE",
"HAVE_SSE2",
}
files {
AL_DIR .. "alc/mixer/mixer_sse2.cpp",
AL_DIR .. "alc/mixer/mixer_sse.cpp",
}
configuration { "android-*" }
files {
AL_DIR .. "alc/backends/opensl.cpp"
}
links {
"OpenSLES",
}
configuration { "linux-*" }
defines {
"HAVE_CPUID_H",
"HAVE_POSIX_MEMALIGN",
"HAVE_PTHREAD_MUTEX_TIMEDLOCK",
"HAVE_PULSEAUDIO",
}
files {
AL_DIR .. "alc/backends/pulseaudio.cpp",
}
configuration { "vs* or mingw-*"}
defines {
"_WIN32_WINNT=0x0502",
"_WINDOWS",
"HAVE___CONTROL87_2",
"HAVE__ALIGNED_MALLOC",
"HAVE__CONTROLFP",
"HAVE_CPUID_INTRINSIC",
"HAVE_DSOUND",
"HAVE_GUIDDEF_H",
"HAVE_INTRIN_H",
"HAVE_IO_H",
"HAVE_WASAPI",
"HAVE_WINDOWS_H",
"HAVE_WINMM",
}
files {
AL_DIR .. "alc/backends/dsound.cpp",
AL_DIR .. "alc/backends/wasapi.cpp",
AL_DIR .. "alc/backends/winmm.cpp",
}
links {
"winmm",
"ole32",
}
configuration { "vs*" }
defines {
"_CRT_NONSTDC_NO_DEPRECATE",
"restrict=",
"SIZEOF_LONG=4",
"SIZEOF_LONG_LONG=8",
"strcasecmp=_stricmp",
"strncasecmp=_strnicmp",
}
buildoptions {
"/wd4098",
"/wd4267",
"/wd4244",
"/EHs", -- :(
}
configuration {}
includedirs {
AL_DIR .. "al/include",
AL_DIR .. "alc",
AL_DIR .. "common",
AL_DIR .. "include",
AL_DIR,
}
files {
AL_DIR .. "al/*.cpp",
AL_DIR .. "alc/*.cpp",
AL_DIR .. "alc/backends/base.cpp",
AL_DIR .. "alc/backends/loopback.cpp",
AL_DIR .. "alc/backends/null.cpp",
AL_DIR .. "alc/effects/*.cpp",
AL_DIR .. "alc/filters/*.cpp",
AL_DIR .. "alc/midi/*.cpp",
AL_DIR .. "alc/mixer/mixer_c.cpp",
AL_DIR .. "common/*.cpp",
}
configuration {}
end
|
--
-- Copyright (c) 2012-2020 Daniele Bartolini and individual contributors.
-- License: https://github.com/dbartolini/crown/blob/master/LICENSE
--
function openal_project(_kind)
project "openal"
kind (_kind)
configuration {}
local AL_DIR = (CROWN_DIR .. "3rdparty/openal/")
defines {
"_LARGE_FILES",
"_LARGEFILE_SOURCE",
"AL_ALEXT_PROTOTYPES",
"AL_BUILD_LIBRARY",
"HAVE_C99_BOOL",
"HAVE_FENV_H",
"HAVE_FLOAT_H",
"HAVE_LRINTF",
"HAVE_MALLOC_H",
"HAVE_STAT",
"HAVE_STDBOOL_H",
"HAVE_STDINT_H",
"HAVE_STRTOF",
}
configuration { "not vs*" }
defines {
"HAVE_C99_VLA",
"HAVE_DIRENT_H",
"HAVE_GCC_DESTRUCTOR",
"HAVE_GCC_FORMAT",
"HAVE_PTHREAD_SETNAME_NP",
"HAVE_PTHREAD_SETSCHEDPARAM",
"HAVE_STRINGS_H",
"restrict=__restrict",
"SIZEOF_LONG=8",
"SIZEOF_LONG_LONG=8",
-- These are needed on non-Windows systems for extra features
"_GNU_SOURCE=1",
"_POSIX_C_SOURCE=200809L",
"_XOPEN_SOURCE=700",
}
buildoptions {
"-fPIC",
"-Winline",
"-fvisibility=hidden",
"-fexceptions" -- :(
}
configuration { "linux-* or android-*" }
defines {
"HAVE_DLFCN_H",
"HAVE_GCC_GET_CPUID",
}
configuration { "not android-*" }
defines {
"HAVE_SSE",
"HAVE_SSE2",
}
files {
AL_DIR .. "alc/mixer/mixer_sse2.cpp",
AL_DIR .. "alc/mixer/mixer_sse.cpp",
}
configuration { "android-*" }
files {
AL_DIR .. "alc/backends/opensl.cpp"
}
links {
"OpenSLES",
}
configuration { "linux-*" }
defines {
"HAVE_CPUID_H",
"HAVE_POSIX_MEMALIGN",
"HAVE_PTHREAD_MUTEX_TIMEDLOCK",
"HAVE_PULSEAUDIO",
}
files {
AL_DIR .. "alc/backends/pulseaudio.cpp",
}
configuration { "vs* or mingw-*"}
defines {
"_WIN32_WINNT=0x0502",
"_WINDOWS",
"HAVE___CONTROL87_2",
"HAVE__ALIGNED_MALLOC",
"HAVE__CONTROLFP",
"HAVE_CPUID_INTRINSIC",
"HAVE_DSOUND",
"HAVE_GUIDDEF_H",
"HAVE_INTRIN_H",
"HAVE_IO_H",
"HAVE_WASAPI",
"HAVE_WINDOWS_H",
"HAVE_WINMM",
"strcasecmp=_stricmp",
"strncasecmp=_strnicmp",
}
files {
AL_DIR .. "alc/backends/dsound.cpp",
AL_DIR .. "alc/backends/wasapi.cpp",
AL_DIR .. "alc/backends/winmm.cpp",
}
links {
"winmm",
"ole32",
}
configuration { "vs*" }
defines {
"_CRT_NONSTDC_NO_DEPRECATE",
"restrict=",
"SIZEOF_LONG=4",
"SIZEOF_LONG_LONG=8",
"strcasecmp=_stricmp",
"strncasecmp=_strnicmp",
}
buildoptions {
"/wd4098",
"/wd4267",
"/wd4244",
"/EHs", -- :(
}
configuration {}
includedirs {
AL_DIR .. "al/include",
AL_DIR .. "alc",
AL_DIR .. "common",
AL_DIR .. "include",
AL_DIR,
}
files {
AL_DIR .. "al/*.cpp",
AL_DIR .. "alc/*.cpp",
AL_DIR .. "alc/backends/base.cpp",
AL_DIR .. "alc/backends/loopback.cpp",
AL_DIR .. "alc/backends/null.cpp",
AL_DIR .. "alc/effects/*.cpp",
AL_DIR .. "alc/filters/*.cpp",
AL_DIR .. "alc/midi/*.cpp",
AL_DIR .. "alc/mixer/mixer_c.cpp",
AL_DIR .. "common/*.cpp",
}
configuration {}
end
|
scripts: fix MinGW build
|
scripts: fix MinGW build
|
Lua
|
mit
|
dbartolini/crown,taylor001/crown,mikymod/crown,galek/crown,mikymod/crown,galek/crown,dbartolini/crown,galek/crown,dbartolini/crown,mikymod/crown,taylor001/crown,taylor001/crown,taylor001/crown,dbartolini/crown,mikymod/crown,galek/crown
|
2c6727bfb56c8576e181b8f41e0b4a95525236f1
|
src_trunk/resources/item-system/ghettoblaster/c_ghettoblaster.lua
|
src_trunk/resources/item-system/ghettoblaster/c_ghettoblaster.lua
|
blasters = { }
function elementStreamIn()
if (getElementType(source)=="object") then
local model = getElementModel(source)
if (model==2226) then
local x, y, z = getElementPosition(source)
local sound = playSound3D("ghettoblaster/loop.mp3", x, y, z, true)
blasters[source] = sound
setSoundMaxDistance(sound, 20)
if (isPedInVehicle(getLocalPlayer())) then
setSoundVolume(sound, 0.5)
end
end
end
end
addEventHandler("onClientElementStreamIn", getRootElement(), elementStreamIn)
function elementStreamOut()
if (blasters[source]~=nil) then
local sound = blasters[source]
stopSound(sound)
blasters[source] = nil
end
end
addEventHandler("onClientElementStreamOut", getRootElement(), elementStreamOut)
addEventHandler("onClientElementDestroy", getRootElement(), elementStreamOut)
function dampenSound(thePlayer)
for key, value in pairs(blasters) do
setSoundVolume(value, 0.5)
end
end
addEventHandler("onClientVehicleEnter", getRootElement(), dampenSound)
function boostSound(thePlayer)
for key, value in pairs(blasters) do
setSoundVolume(value, 1.0)
end
end
addEventHandler("onClientVehicleExit", getRootElement(), boostSound)
|
blasters = { }
local localPlayer = getLocalPlayer()
function elementStreamIn()
if (getElementType(source)=="object") then
local model = getElementModel(source)
if (model==2226) then
local x, y, z = getElementPosition(source)
local px, py, pz = getElementPosition(localPlayer)
if (getDistanceBetweenPoints3D(x, y, z, px, py, pz)<300) then
local sound = playSound3D("ghettoblaster/loop.mp3", x, y, z, true)
blasters[source] = sound
setSoundMaxDistance(sound, 20)
if (isPedInVehicle(getLocalPlayer())) then
setSoundVolume(sound, 0.5)
end
end
end
end
end
addEventHandler("onClientElementStreamIn", getRootElement(), elementStreamIn)
function elementStreamOut()
if (blasters[source]~=nil) then
local sound = blasters[source]
stopSound(sound)
blasters[source] = nil
end
end
addEventHandler("onClientElementStreamOut", getRootElement(), elementStreamOut)
addEventHandler("onClientElementDestroy", getRootElement(), elementStreamOut)
function dampenSound(thePlayer)
for key, value in pairs(blasters) do
setSoundVolume(value, 0.5)
end
end
addEventHandler("onClientVehicleEnter", getRootElement(), dampenSound)
function boostSound(thePlayer)
for key, value in pairs(blasters) do
setSoundVolume(value, 1.0)
end
end
addEventHandler("onClientVehicleExit", getRootElement(), boostSound)
|
Ghettoblaster fixes
|
Ghettoblaster fixes
git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@533 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
|
Lua
|
bsd-3-clause
|
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
|
263ac6627242c2a3d4d53ecfbdf579dbf6c63d55
|
tundra.lua
|
tundra.lua
|
-----------------------------------------------------------------------------------------------------------------------
local mac_opts = {
"-Wall",
"-I.", "-DPRODBG_MAC",
"-Weverything", "-Werror",
"-Wno-c11-extensions",
"-Wno-variadic-macros",
"-Wno-c++98-compat-pedantic",
"-Wno-old-style-cast",
"-Wno-documentation",
"-Wno-missing-prototypes",
"-Wno-gnu-anonymous-struct",
"-Wno-nested-anon-types",
"-Wno-padded",
"-Wno-c99-extensions",
"-Wno-missing-field-initializers",
"-Wno-weak-vtables",
"-Wno-format-nonliteral",
"-Wno-non-virtual-dtor",
"-DOBJECT_DIR=\\\"$(OBJECTDIR)\\\"",
{ "-O0", "-g"; Config = "*-*-debug" },
{ "-O3", "-g"; Config = "*-*-release" },
}
local macosx = {
Env = {
CCOPTS = {
mac_opts,
},
CXXOPTS = {
mac_opts,
"-std=c++11",
},
SHLIBOPTS = { "-lstdc++" },
PROGCOM = { "-lstdc++" },
BGFX_SHADERC = "$(OBJECTDIR)$(SEP)bgfx_shaderc$(PROGSUFFIX)",
},
Frameworks = { "Cocoa" },
}
local macosx_wx = {
Env = {
CCOPTS = {
mac_opts,
"-PRODBG_WX",
},
CXXOPTS = {
mac_opts,
"-PRODBG_WX",
},
},
Frameworks = { "Cocoa" },
}
local macosx_test = {
Env = {
CCOPTS = {
mac_opts,
},
CXXOPTS = {
mac_opts,
"-Wno-everything",
"-coverage",
"-std=c++11",
},
SHLIBOPTS = { "-lstdc++", "-coverage" },
PROGCOM = { "-lstdc++", "-coverage" },
BGFX_SHADERC = "$(OBJECTDIR)$(SEP)bgfx_shaderc$(PROGSUFFIX)",
},
Frameworks = { "Cocoa" },
}
-----------------------------------------------------------------------------------------------------------------------
local gcc_opts = {
"-I.",
"-Wno-array-bounds", "-Wno-attributes", "-Wno-unused-value",
"-DOBJECT_DIR=\\\"$(OBJECTDIR)\\\"",
"-Wall", "-DPRODBG_UNIX",
"-fPIC",
{ "-O0", "-g"; Config = "*-*-debug" },
{ "-O3", "-g"; Config = "*-*-release" },
}
local gcc_env = {
Env = {
CCOPTS = {
gcc_opts,
},
CXXOPTS = {
gcc_opts,
"-std=c++11",
},
BGFX_SHADERC = "$(OBJECTDIR)$(SEP)bgfx_shaderc$(PROGSUFFIX)",
},
ReplaceEnv = {
PROGCOM = "$(LD) $(PROGOPTS) $(LIBPATH:p-L) -o $(@) -Wl,--start-group $(LIBS:p-l) $(<) -Wl,--end-group"
},
}
-----------------------------------------------------------------------------------------------------------------------
local win64_opts = {
"/DPRODBG_WIN",
"/EHsc", "/FS", "/MT", "/W3", "/I.", "/WX", "/DUNICODE", "/D_UNICODE", "/DWIN32", "/D_CRT_SECURE_NO_WARNINGS", "/wd4200", "/wd4152", "/wd4996", "/wd4389", "/wd4201", "/wd4152", "/wd4996", "/wd4389",
"\"/DOBJECT_DIR=$(OBJECTDIR:#)\"",
{ "/Od"; Config = "*-*-debug" },
{ "/O2"; Config = "*-*-release" },
}
local win64 = {
Env = {
GENERATE_PDB = "1",
CCOPTS = {
win64_opts,
},
CXXOPTS = {
win64_opts,
},
BGFX_SHADERC = "$(OBJECTDIR)$(SEP)bgfx_shaderc$(PROGSUFFIX)",
OBJCCOM = "meh",
},
}
-----------------------------------------------------------------------------------------------------------------------
Build {
Passes = {
BuildTools = { Name="Build Tools", BuildOrder = 1 },
GenerateSources = { Name="Generate sources", BuildOrder = 2 },
},
Units = {
"units.tools.lua",
"units.libs.lua",
"units.misc.lua",
"units.plugins.lua",
"units.prodbg.lua",
"units.tests.lua",
},
Configs = {
Config { Name = "macosx-clang", DefaultOnHost = "macosx", Inherit = macosx, Tools = { "clang-osx" } },
Config { Name = "macosx_test-clang", SupportedHosts = { "macosx" }, Inherit = macosx_test, Tools = { "clang-osx" } },
Config { Name = "macosx_wx-clang", SupportedHosts = { "macosx" }, Inherit = macosx_test, Tools = { "clang-osx" } },
Config { Name = "win64-msvc", DefaultOnHost = { "windows" }, Inherit = win64, Tools = { { "msvc" }, "generic-asm" } },
Config { Name = "linux-gcc", DefaultOnHost = { "linux" }, Inherit = gcc_env, Tools = { "gcc" } },
},
IdeGenerationHints = {
Msvc = {
-- Remap config names to MSVC platform names (affects things like header scanning & debugging)
PlatformMappings = {
['win64-msvc'] = 'x64',
},
-- Remap variant names to MSVC friendly names
VariantMappings = {
['release'] = 'Release',
['debug'] = 'Debug',
},
},
MsvcSolutions = {
['ProDBG.sln'] = { } -- will get everything
},
},
}
|
-----------------------------------------------------------------------------------------------------------------------
local mac_opts = {
"-Wall",
"-I.", "-DPRODBG_MAC",
"-Weverything", "-Werror",
"-Wno-c11-extensions",
"-Wno-variadic-macros",
"-Wno-c++98-compat-pedantic",
"-Wno-old-style-cast",
"-Wno-documentation",
"-Wno-missing-prototypes",
"-Wno-gnu-anonymous-struct",
"-Wno-nested-anon-types",
"-Wno-padded",
"-Wno-c99-extensions",
"-Wno-missing-field-initializers",
"-Wno-weak-vtables",
"-Wno-format-nonliteral",
"-Wno-non-virtual-dtor",
"-DOBJECT_DIR=\\\"$(OBJECTDIR)\\\"",
{ "-O0", "-g"; Config = "*-*-debug" },
{ "-O3", "-g"; Config = "*-*-release" },
}
local macosx = {
Env = {
CCOPTS = {
mac_opts,
},
CXXOPTS = {
mac_opts,
"-std=c++11",
},
SHLIBOPTS = { "-lstdc++" },
PROGCOM = { "-lstdc++" },
BGFX_SHADERC = "$(OBJECTDIR)$(SEP)bgfx_shaderc$(PROGSUFFIX)",
},
Frameworks = { "Cocoa" },
}
local macosx_wx = {
Env = {
CCOPTS = {
mac_opts,
"-PRODBG_WX",
},
CXXOPTS = {
mac_opts,
"-PRODBG_WX",
},
},
Frameworks = { "Cocoa" },
}
local macosx_test = {
Env = {
CCOPTS = {
mac_opts,
"-Wno-everything",
"-coverage",
},
CXXOPTS = {
mac_opts,
"-Wno-everything",
"-coverage",
"-std=c++11",
},
SHLIBOPTS = { "-lstdc++", "-coverage" },
PROGCOM = { "-lstdc++", "-coverage" },
BGFX_SHADERC = "$(OBJECTDIR)$(SEP)bgfx_shaderc$(PROGSUFFIX)",
},
Frameworks = { "Cocoa" },
}
-----------------------------------------------------------------------------------------------------------------------
local gcc_opts = {
"-I.",
"-Wno-array-bounds", "-Wno-attributes", "-Wno-unused-value",
"-DOBJECT_DIR=\\\"$(OBJECTDIR)\\\"",
"-Wall", "-DPRODBG_UNIX",
"-fPIC",
{ "-O0", "-g"; Config = "*-*-debug" },
{ "-O3", "-g"; Config = "*-*-release" },
}
local gcc_env = {
Env = {
CCOPTS = {
gcc_opts,
},
CXXOPTS = {
gcc_opts,
"-std=c++11",
},
BGFX_SHADERC = "$(OBJECTDIR)$(SEP)bgfx_shaderc$(PROGSUFFIX)",
},
ReplaceEnv = {
PROGCOM = "$(LD) $(PROGOPTS) $(LIBPATH:p-L) -o $(@) -Wl,--start-group $(LIBS:p-l) $(<) -Wl,--end-group"
},
}
-----------------------------------------------------------------------------------------------------------------------
local win64_opts = {
"/DPRODBG_WIN",
"/EHsc", "/FS", "/MT", "/W3", "/I.", "/WX", "/DUNICODE", "/D_UNICODE", "/DWIN32", "/D_CRT_SECURE_NO_WARNINGS", "/wd4200", "/wd4152", "/wd4996", "/wd4389", "/wd4201", "/wd4152", "/wd4996", "/wd4389",
"\"/DOBJECT_DIR=$(OBJECTDIR:#)\"",
{ "/Od"; Config = "*-*-debug" },
{ "/O2"; Config = "*-*-release" },
}
local win64 = {
Env = {
GENERATE_PDB = "1",
CCOPTS = {
win64_opts,
},
CXXOPTS = {
win64_opts,
},
BGFX_SHADERC = "$(OBJECTDIR)$(SEP)bgfx_shaderc$(PROGSUFFIX)",
OBJCCOM = "meh",
},
}
-----------------------------------------------------------------------------------------------------------------------
Build {
Passes = {
BuildTools = { Name="Build Tools", BuildOrder = 1 },
GenerateSources = { Name="Generate sources", BuildOrder = 2 },
},
Units = {
"units.tools.lua",
"units.libs.lua",
"units.misc.lua",
"units.plugins.lua",
"units.prodbg.lua",
"units.tests.lua",
},
Configs = {
Config { Name = "macosx-clang", DefaultOnHost = "macosx", Inherit = macosx, Tools = { "clang-osx" } },
Config { Name = "macosx_test-clang", SupportedHosts = { "macosx" }, Inherit = macosx_test, Tools = { "clang-osx" } },
Config { Name = "macosx_wx-clang", SupportedHosts = { "macosx" }, Inherit = macosx_test, Tools = { "clang-osx" } },
Config { Name = "win64-msvc", DefaultOnHost = { "windows" }, Inherit = win64, Tools = { { "msvc" }, "generic-asm" } },
Config { Name = "linux-gcc", DefaultOnHost = { "linux" }, Inherit = gcc_env, Tools = { "gcc" } },
},
IdeGenerationHints = {
Msvc = {
-- Remap config names to MSVC platform names (affects things like header scanning & debugging)
PlatformMappings = {
['win64-msvc'] = 'x64',
},
-- Remap variant names to MSVC friendly names
VariantMappings = {
['release'] = 'Release',
['debug'] = 'Debug',
},
},
MsvcSolutions = {
['ProDBG.sln'] = { } -- will get everything
},
},
}
|
Fixed broken mac_test build
|
Fixed broken mac_test build
|
Lua
|
mit
|
ashemedai/ProDBG,RobertoMalatesta/ProDBG,SlNPacifist/ProDBG,emoon/ProDBG,ashemedai/ProDBG,RobertoMalatesta/ProDBG,SlNPacifist/ProDBG,kondrak/ProDBG,emoon/ProDBG,v3n/ProDBG,SlNPacifist/ProDBG,RobertoMalatesta/ProDBG,kondrak/ProDBG,SlNPacifist/ProDBG,SlNPacifist/ProDBG,emoon/ProDBG,ashemedai/ProDBG,ashemedai/ProDBG,kondrak/ProDBG,emoon/ProDBG,v3n/ProDBG,SlNPacifist/ProDBG,v3n/ProDBG,ashemedai/ProDBG,kondrak/ProDBG,v3n/ProDBG,emoon/ProDBG,RobertoMalatesta/ProDBG,kondrak/ProDBG,ashemedai/ProDBG,kondrak/ProDBG,v3n/ProDBG,emoon/ProDBG,RobertoMalatesta/ProDBG,v3n/ProDBG
|
329376b622eac6a6ae74f17a0fa08ba7354593eb
|
Resources/Scripts/Modules/Camera.lua
|
Resources/Scripts/Modules/Camera.lua
|
WINDOW = { width, height }
WINDOW.width, WINDOW.height = window.size()
panels = { left = { width = 128, height = 768, center = { x = -WINDOW.width / 2, y = 0 } }, right = { width = 32, height = 768, center = { x = WINDOW.width / 2, y = 0 } } }
cameraRatio = { current = 1, num = 2, target = 1 }
aspectRatio = WINDOW.width / WINDOW.height
camera = { w = WINDOW.width / cameraRatio.current, h }
camera.h = camera.w / aspectRatio
shipAdjust = .045 * camera.w
timeInterval = 1
zoomTime = 0
function CameraToWindow()
return { -WINDOW.width / 2, -WINDOW.height / 2, WINDOW.width / 2, WINDOW.height / 2 }
end
function UpdateWindow()
WINDOW.width, WINDOW.height = window.size()
panels.left.center = { x = -WINDOW.width / 2 + panels.left.width / 2, y = 0 }
panels.right.center = { x = WINDOW.width / 2 - panels.right.width / 2, y = 0 }
end
CAMERA_RATIO_OPTIONS = {
2, 1, 1/2, 1/4, 1/16,
function() -- zoom to nearest hostile
local object, distance = GetClosestHostile(scen.playerShip)
local ratio = WINDOW.height / 3 / distance
ratio = math.min(ratio, 2.0)
return ratio
end,
function() -- zoom to nearest object
local object, distance = GetClosestObject(scen.playerShip)
local ratio = WINDOW.height / 3 / distance
ratio = math.min(ratio, 2.0)
return ratio
end,
function() -- zoom to all
local object, distance = GetFurthestObject(scen.playerShip)
local ratio = WINDOW.height / 3 / distance
ratio = math.min(ratio, 2.0)
return ratio
end
}
CAMERA_DYNAMIC_THRESHOLD = 6
CAMERA_RATIO = { curr = 1, num = 2, target = 1 }
-- how this works when not zooming: curr = target = CAMERA_RATIO_OPTIONS[num]
-- when moving, zooming from curr = CAMERA_RATIO_OPTIONS[num] to target, set num
-- to the proper value once we reachy the target
-- should I add a function that checks to make sure that the camera ratio is the
-- same as the target, and adjusting if not? [ADAM] [TODO]
<<<<<<< HEAD
function CameraInterpolate(dt) -- note: this function now controlls both quadratic zooming and snap zooming (not good from a code design philosophy)
if cameraChanging == true then
=======
function CameraInterpolate(dt)
local oldRatio = cameraRatio.current
local zoomGoal
if cameraRatio.target < CAMERA_DYNAMIC_THRESHOLD then
--Normal scaling
zoomGoal = CAMERA_RATIO_OPTIONS[cameraRatio.target]
else
--Dynamic scaling
zoomGoal = CAMERA_RATIO_OPTIONS[cameraRatio.target]()
end
local zoomTime = math.max(math.abs(math.log(zoomGoal/cameraRatio.current)/math.log(2)),1)
if zoomTime ~= 0 then
cameraRatio.current = cameraRatio.current + (zoomGoal-cameraRatio.current)*(zoomTime*dt)
end
if (cameraRatio.current < 1 / 4 and oldRatio > 1 / 4)
or (cameraRatio.current > 1 / 4 and oldRatio < 1 / 4) then
sound.play("ZoomChange")
end
camera = { w = WINDOW.width / cameraRatio.current, h }
camera.h = camera.w / aspectRatio
shipAdjust = .045 * camera.w
arrowLength = ARROW_LENGTH / cameraRatio.current
arrowVar = ARROW_VAR / cameraRatio.current
arrowDist = ARROW_DIST / cameraRatio.current
--[==[
if cameraRatio. >= CAMERA_DYNAMIC_THRESHOLD
or then
>>>>>>> gamefreak/zooming
zoomTime = zoomTime - dt
if zoomTime < 0 then
zoomTime = 0
cameraChanging = false
-- scen.playerShip.weapon.beam.width = cameraRatio
soundJustPlayed = false
end
if zoomTime >= 0 then
cameraRatio = cameraRatioOrig + cameraRatioOrig * multiplier * math.pow(math.abs((timeInterval - zoomTime) / timeInterval), 2)
--[[* (((x - timeInterval) * (x - timeInterval) * math.sqrt(math.abs(x - timeInterval))) / (timeInterval * timeInterval * math.sqrt(math.abs(timeInterval))))--]]
end
camera = { w = WINDOW.width / cameraRatio, h }
camera.h = camera.w / aspectRatio
shipAdjust = .045 * camera.w
arrowLength = ARROW_LENGTH / cameraRatio
arrowVar = ARROW_VAR / cameraRatio
arrowDist = ARROW_DIST / cameraRatio
if (cameraRatio < 1 / 4 and cameraRatioOrig > 1 / 4) or (cameraRatio > 1 / 4 and cameraRatioOrig < 1 / 4) then
if soundJustPlayed == false then
sound.play("ZoomChange")
soundJustPlayed = true
end
end
end
--]==]
end
-- Adam's replacement for CameraInterpolate(dt)
-- Quadratic ease-in of the ship camera
function CameraEaseIn(dt, zoomLevel)
zoomLevel = zoomLevel or 1 -- optional arguments, huzzah
-- yet to be written [ADAM] [DEMO3]
end
-- To be used when the camera is in algorithmic zooms, possibly (may be built
-- into the CAMERA_RATIO_OPTIONS table)
function CameraFollow(dt, zoomLevel)
-- to be written
end
function CameraSnap()
if cameraChanging == true then
cameraRatio = cameraRatioTarget
camera = { w = WINDOW.width / cameraRatio, h }
camera.h = camera.w / aspectRatio
shipAdjust = .045 * camera.w
arrowLength = ARROW_LENGTH / cameraRatio
arrowVar = ARROW_VAR / cameraRatio
arrowDist = ARROW_DIST / cameraRatio
end
end
-- Adam's replacement for CameraSnap()
function InstantCamera(zoomLevel)
zoomLevel = zoomLevel or 1 -- optional arguments, huzzah
print(zoomLevel, "ZOOM LEVEL")
CAMERA_RATIO.target = CAMERA_RATIO_OPTIONS[zoomLevel]() -- currently, no error checking
CAMERA_RATIO.curr = CAMERA_RATIO.target
ChangeCamAndWindow()
UpdateWindow()
end
function ChangeCamAndWindow()
camera = { w = WINDOW.width / CAMERA_RATIO.curr, h }
camera.h = camera.w / aspectRatio
shipAdjust = .045 * camera.w
arrowLength = ARROW_LENGTH / CAMERA_RATIO.curr
arrowVar = ARROW_VAR / CAMERA_RATIO.curr
arrowDist = ARROW_DIST / CAMERA_RATIO.curr
end
function CameraToObject(object)
local pos = object.physics.position
graphics.set_camera(
-pos.x + shipAdjust - (camera.w / 2.0),
-pos.y - (camera.h / 2.0),
-pos.x + shipAdjust + (camera.w / 2.0),
-pos.y + (camera.h / 2.0))
end
|
WINDOW = { width, height }
WINDOW.width, WINDOW.height = window.size()
panels = { left = { width = 128, height = 768, center = { x = -WINDOW.width / 2, y = 0 } }, right = { width = 32, height = 768, center = { x = WINDOW.width / 2, y = 0 } } }
cameraRatio = { current = 1, num = 2, target = 1 }
aspectRatio = WINDOW.width / WINDOW.height
camera = { w = WINDOW.width / cameraRatio.current, h }
camera.h = camera.w / aspectRatio
shipAdjust = .045 * camera.w
timeInterval = 1
zoomTime = 0
function CameraToWindow()
return { -WINDOW.width / 2, -WINDOW.height / 2, WINDOW.width / 2, WINDOW.height / 2 }
end
function UpdateWindow()
WINDOW.width, WINDOW.height = window.size()
panels.left.center = { x = -WINDOW.width / 2 + panels.left.width / 2, y = 0 }
panels.right.center = { x = WINDOW.width / 2 - panels.right.width / 2, y = 0 }
end
CAMERA_RATIO_OPTIONS = {
2, 1, 1/2, 1/4, 1/16,
function() -- zoom to nearest hostile
local object, distance = GetClosestHostile(scen.playerShip)
local ratio = WINDOW.height / 3 / distance
ratio = math.min(ratio, 2.0)
return ratio
end,
function() -- zoom to nearest object
local object, distance = GetClosestObject(scen.playerShip)
local ratio = WINDOW.height / 3 / distance
ratio = math.min(ratio, 2.0)
return ratio
end,
function() -- zoom to all
local object, distance = GetFurthestObject(scen.playerShip)
local ratio = WINDOW.height / 3 / distance
ratio = math.min(ratio, 2.0)
return ratio
end
}
CAMERA_DYNAMIC_THRESHOLD = 6
CAMERA_RATIO = { curr = 1, num = 2, target = 1 }
-- how this works when not zooming: curr = target = CAMERA_RATIO_OPTIONS[num]
-- when moving, zooming from curr = CAMERA_RATIO_OPTIONS[num] to target, set num
-- to the proper value once we reachy the target
-- should I add a function that checks to make sure that the camera ratio is the
-- same as the target, and adjusting if not? [ADAM] [TODO]
function CameraInterpolate(dt)
local oldRatio = cameraRatio.current
local zoomGoal
if cameraRatio.target < CAMERA_DYNAMIC_THRESHOLD then
--Normal scaling
zoomGoal = CAMERA_RATIO_OPTIONS[cameraRatio.target]
else
--Dynamic scaling
zoomGoal = CAMERA_RATIO_OPTIONS[cameraRatio.target]()
end
local zoomTime = math.max(math.abs(math.log(zoomGoal/cameraRatio.current)/math.log(2)),1)
if zoomTime ~= 0 then
cameraRatio.current = cameraRatio.current + (zoomGoal-cameraRatio.current)*(zoomTime*dt)
end
if (cameraRatio.current < 1 / 4 and oldRatio > 1 / 4)
or (cameraRatio.current > 1 / 4 and oldRatio < 1 / 4) then
sound.play("ZoomChange")
end
camera = { w = WINDOW.width / cameraRatio.current, h }
camera.h = camera.w / aspectRatio
shipAdjust = .045 * camera.w
arrowLength = ARROW_LENGTH / cameraRatio.current
arrowVar = ARROW_VAR / cameraRatio.current
arrowDist = ARROW_DIST / cameraRatio.current
--[==[
if cameraRatio. >= CAMERA_DYNAMIC_THRESHOLD
or then
zoomTime = zoomTime - dt
if zoomTime < 0 then
zoomTime = 0
cameraChanging = false
-- scen.playerShip.weapon.beam.width = cameraRatio
soundJustPlayed = false
end
if zoomTime >= 0 then
cameraRatio = cameraRatioOrig + cameraRatioOrig * multiplier * math.pow(math.abs((timeInterval - zoomTime) / timeInterval), 2)
--[[* (((x - timeInterval) * (x - timeInterval) * math.sqrt(math.abs(x - timeInterval))) / (timeInterval * timeInterval * math.sqrt(math.abs(timeInterval))))--]]
end
camera = { w = WINDOW.width / cameraRatio, h }
camera.h = camera.w / aspectRatio
shipAdjust = .045 * camera.w
arrowLength = ARROW_LENGTH / cameraRatio
arrowVar = ARROW_VAR / cameraRatio
arrowDist = ARROW_DIST / cameraRatio
if (cameraRatio < 1 / 4 and cameraRatioOrig > 1 / 4) or (cameraRatio > 1 / 4 and cameraRatioOrig < 1 / 4) then
if soundJustPlayed == false then
sound.play("ZoomChange")
soundJustPlayed = true
end
end
end
--]==]
end
-- Adam's replacement for CameraInterpolate(dt)
-- Quadratic ease-in of the ship camera
function CameraEaseIn(dt, zoomLevel)
zoomLevel = zoomLevel or 1 -- optional arguments, huzzah
-- yet to be written [ADAM] [DEMO3]
end
-- To be used when the camera is in algorithmic zooms, possibly (may be built
-- into the CAMERA_RATIO_OPTIONS table)
function CameraFollow(dt, zoomLevel)
-- to be written
end
function CameraSnap()
if cameraChanging == true then
cameraRatio = cameraRatioTarget
camera = { w = WINDOW.width / cameraRatio, h }
camera.h = camera.w / aspectRatio
shipAdjust = .045 * camera.w
arrowLength = ARROW_LENGTH / cameraRatio
arrowVar = ARROW_VAR / cameraRatio
arrowDist = ARROW_DIST / cameraRatio
end
end
-- Adam's replacement for CameraSnap()
function InstantCamera(zoomLevel)
zoomLevel = zoomLevel or 1 -- optional arguments, huzzah
print(zoomLevel, "ZOOM LEVEL")
CAMERA_RATIO.target = CAMERA_RATIO_OPTIONS[zoomLevel]() -- currently, no error checking
CAMERA_RATIO.curr = CAMERA_RATIO.target
ChangeCamAndWindow()
UpdateWindow()
end
function ChangeCamAndWindow()
camera = { w = WINDOW.width / CAMERA_RATIO.curr, h }
camera.h = camera.w / aspectRatio
shipAdjust = .045 * camera.w
arrowLength = ARROW_LENGTH / CAMERA_RATIO.curr
arrowVar = ARROW_VAR / CAMERA_RATIO.curr
arrowDist = ARROW_DIST / CAMERA_RATIO.curr
end
function CameraToObject(object)
local pos = object.physics.position
graphics.set_camera(
-pos.x + shipAdjust - (camera.w / 2.0),
-pos.y - (camera.h / 2.0),
-pos.x + shipAdjust + (camera.w / 2.0),
-pos.y + (camera.h / 2.0))
end
|
Fixed the (broken) Camera.lua script.
|
Fixed the (broken) Camera.lua script.
Signed-off-by: Alastair Lynn <4665d361aaf271b139147017031ea99df777ca5a@gmail.com>
|
Lua
|
mit
|
adam000/xsera,adam000/xsera,prophile/xsera,prophile/xsera,prophile/xsera,prophile/xsera,adam000/xsera,prophile/xsera,adam000/xsera
|
952a86a9cd7c7e1067ba79cf5d5db41c2fd6926f
|
src/tbox/micro.lua
|
src/tbox/micro.lua
|
-- add target
target("tbox")
-- make as a static library
set_kind("static")
-- add defines
add_defines("__tb_prefix__=\"tbox\"")
-- set the auto-generated config.h
set_configdir("$(buildir)/$(plat)/$(arch)/$(mode)")
add_configfiles("tbox.config.h.in")
-- add include directories
add_includedirs("..", {public = true})
add_includedirs("$(buildir)/$(plat)/$(arch)/$(mode)", {public = true})
-- add the header files for installing
add_headerfiles("../(tbox/**.h)|**/impl/**.h")
add_headerfiles("../(tbox/prefix/**/prefix.S)")
add_headerfiles("../(tbox/math/impl/*.h)")
add_headerfiles("../(tbox/utils/impl/*.h)")
add_headerfiles("$(buildir)/$(plat)/$(arch)/$(mode)/tbox.config.h", {prefixdir = "tbox"})
-- add options
add_options("info", "float", "wchar", "micro", "coroutine")
-- add the source files
add_files("tbox.c")
add_files("libc/string/memset.c")
add_files("libc/string/memmov.c")
add_files("libc/string/memcpy.c")
add_files("libc/string/strstr.c")
add_files("libc/string/strdup.c")
add_files("libc/string/strlen.c")
add_files("libc/string/strnlen.c")
add_files("libc/string/strcmp.c")
add_files("libc/string/strncmp.c")
add_files("libc/string/stricmp.c")
add_files("libc/string/strnicmp.c")
add_files("libc/string/strlcpy.c")
add_files("libc/string/strncpy.c")
add_files("libc/stdio/vsnprintf.c")
add_files("libc/stdio/snprintf.c")
add_files("libc/stdio/printf.c")
add_files("libc/stdlib/stdlib.c")
add_files("libc/impl/libc.c")
add_files("libm/impl/libm.c")
add_files("math/impl/math.c")
add_files("utils/used.c")
add_files("utils/bits.c")
add_files("utils/trace.c")
add_files("utils/singleton.c")
add_files("memory/allocator.c")
add_files("memory/native_allocator.c")
add_files("memory/static_allocator.c")
add_files("memory/impl/static_large_allocator.c")
add_files("memory/impl/memory.c")
add_files("network/ipv4.c")
add_files("network/ipv6.c")
add_files("network/ipaddr.c")
add_files("network/impl/network.c")
add_files("platform/page.c")
add_files("platform/time.c")
add_files("platform/file.c")
add_files("platform/path.c")
add_files("platform/sched.c")
add_files("platform/print.c")
add_files("platform/thread.c")
add_files("platform/socket.c")
add_files("platform/addrinfo.c")
add_files("platform/poller.c")
add_files("platform/native_memory.c")
add_files("platform/impl/sockdata.c")
add_files("platform/impl/platform.c")
add_files("container/iterator.c")
add_files("container/list_entry.c")
add_files("container/single_list_entry.c")
-- add the source files for debug mode
if is_mode("debug") then
add_files("utils/dump.c")
add_files("memory/impl/prefix.c")
add_files("platform/backtrace.c")
end
-- add the source files for float
if has_config("float") then
add_files("libm/isinf.c")
add_files("libm/isinff.c")
add_files("libm/isnan.c")
add_files("libm/isnanf.c")
end
-- add the source for the windows
if is_os("windows") then
add_files("libc/stdlib/mbstowcs.c")
add_files("platform/dynamic.c")
add_files("platform/atomic64.c")
add_files("platform/windows/windows.c")
add_files("platform/windows/interface/ws2_32.c")
add_files("platform/windows/interface/mswsock.c")
add_files("platform/windows/interface/kernel32.c")
if is_mode("debug") then
add_files("platform/windows/interface/dbghelp.c")
end
end
-- add the source files for coroutine
if has_config("coroutine") then
add_files("coroutine/stackless/*.c")
add_files("coroutine/impl/stackless/*.c")
end
-- check interfaces
check_interfaces()
|
-- add target
target("tbox")
-- make as a static library
set_kind("static")
-- add defines
add_defines("__tb_prefix__=\"tbox\"")
-- set the auto-generated config.h
set_configdir("$(buildir)/$(plat)/$(arch)/$(mode)")
add_configfiles("tbox.config.h.in")
-- add include directories
add_includedirs("..", {public = true})
add_includedirs("$(buildir)/$(plat)/$(arch)/$(mode)", {public = true})
-- add the header files for installing
add_headerfiles("../(tbox/**.h)|**/impl/**.h")
add_headerfiles("../(tbox/prefix/**/prefix.S)")
add_headerfiles("../(tbox/math/impl/*.h)")
add_headerfiles("../(tbox/utils/impl/*.h)")
add_headerfiles("$(buildir)/$(plat)/$(arch)/$(mode)/tbox.config.h", {prefixdir = "tbox"})
-- add options
add_options("info", "float", "wchar", "micro", "coroutine")
-- add the source files
add_files("tbox.c")
add_files("libc/string/memset.c")
add_files("libc/string/memmov.c")
add_files("libc/string/memcpy.c")
add_files("libc/string/strstr.c")
add_files("libc/string/strdup.c")
add_files("libc/string/strlen.c")
add_files("libc/string/strnlen.c")
add_files("libc/string/strcmp.c")
add_files("libc/string/strncmp.c")
add_files("libc/string/stricmp.c")
add_files("libc/string/strnicmp.c")
add_files("libc/string/strlcpy.c")
add_files("libc/string/strncpy.c")
add_files("libc/stdio/vsnprintf.c")
add_files("libc/stdio/snprintf.c")
add_files("libc/stdio/printf.c")
add_files("libc/stdlib/stdlib.c")
add_files("libc/impl/libc.c")
add_files("libm/impl/libm.c")
add_files("math/impl/math.c")
add_files("utils/used.c")
add_files("utils/bits.c")
add_files("utils/trace.c")
add_files("utils/singleton.c")
add_files("memory/allocator.c")
add_files("memory/native_allocator.c")
add_files("memory/static_allocator.c")
add_files("memory/impl/static_large_allocator.c")
add_files("memory/impl/memory.c")
add_files("network/ipv4.c")
add_files("network/ipv6.c")
add_files("network/unix.c")
add_files("network/ipaddr.c")
add_files("network/impl/network.c")
add_files("platform/page.c")
add_files("platform/time.c")
add_files("platform/file.c")
add_files("platform/path.c")
add_files("platform/sched.c")
add_files("platform/print.c")
add_files("platform/thread.c")
add_files("platform/socket.c")
add_files("platform/addrinfo.c")
add_files("platform/poller.c")
add_files("platform/native_memory.c")
add_files("platform/impl/sockdata.c")
add_files("platform/impl/platform.c")
add_files("container/iterator.c")
add_files("container/list_entry.c")
add_files("container/single_list_entry.c")
-- add the source files for debug mode
if is_mode("debug") then
add_files("utils/dump.c")
add_files("memory/impl/prefix.c")
add_files("platform/backtrace.c")
end
-- add the source files for float
if has_config("float") then
add_files("libm/isinf.c")
add_files("libm/isinff.c")
add_files("libm/isnan.c")
add_files("libm/isnanf.c")
end
-- add the source for the windows
if is_os("windows") then
add_files("libc/stdlib/mbstowcs.c")
add_files("platform/dynamic.c")
add_files("platform/atomic64.c")
add_files("platform/windows/windows.c")
add_files("platform/windows/interface/ws2_32.c")
add_files("platform/windows/interface/mswsock.c")
add_files("platform/windows/interface/kernel32.c")
if is_mode("debug") then
add_files("platform/windows/interface/dbghelp.c")
end
end
-- add the source files for coroutine
if has_config("coroutine") then
add_files("coroutine/stackless/*.c")
add_files("coroutine/impl/stackless/*.c")
end
-- check interfaces
check_interfaces()
|
fix unix socket support in micro mode
|
fix unix socket support in micro mode
|
Lua
|
apache-2.0
|
waruqi/tbox,tboox/tbox,waruqi/tbox,tboox/tbox
|
f2fb04821d28429c92142007686ae75df13fe645
|
bin/monitor_clients.lua
|
bin/monitor_clients.lua
|
package.path = package.path .. ';../freedomportal/?.lua'
local clients = require('freedomportal.clients')
local utils = require('freedomportal.utils')
local posix = require('posix')
local iwinfo = require('iwinfo')
local INTERVAL = 1
local INTERFACE = 'wlan0'
local ARP_FILEPATH = '/proc/net/arp'
while true do
clients.refresh(function()
-- Table {MAC -> infos} containing only currently connected clients
local connected_clients_table = iwinfo[iwinfo.type(INTERFACE)].assoclist(INTERFACE)
-- Table {MAC -> IP}
local mac_ip_table = utils.arp_parse(ARP_FILEPATH)
for mac, infos in pairs(connected_clients_table) do
if type(mac_ip_table[mac]) == 'string' then
connected_clients_table[mac] = mac_ip_table[mac]
else
print('warning : couldnt find an IP mapping for MAC address ' .. mac)
end
end
return connected_clients_table
end)
posix.sleep(1)
end
|
package.path = package.path .. ';../freedomportal/?.lua'
local clients = require('freedomportal.clients')
local utils = require('freedomportal.utils')
local posix = require('posix')
local iwinfo = require('iwinfo')
local INTERVAL = 1
local INTERFACE = 'wlan0'
local ARP_FILEPATH = '/proc/net/arp'
while true do
clients.refresh(function()
local clients_table = {}
-- Table {MAC -> infos} containing only currently connected clients
local connected_clients_table = iwinfo[iwinfo.type(INTERFACE)].assoclist(INTERFACE)
-- Table {MAC -> IP}
local mac_ip_table = utils.arp_parse(ARP_FILEPATH)
for mac, infos in pairs(connected_clients_table) do
if type(mac_ip_table[mac]) == 'string' then
clients_table[mac] = mac_ip_table[mac]
else
print('warning : couldnt find an IP mapping for MAC address ' .. mac)
end
end
return clients_table
end)
posix.sleep(1)
end
|
fixed monitor script
|
fixed monitor script
|
Lua
|
mit
|
sebpiq/FreedomPortal,sebpiq/FreedomPortal
|
8d3612c147b0e8acf3a82a72cb5130b5b11f0ffc
|
[resources]/GTWclothes/clothes_s.lua
|
[resources]/GTWclothes/clothes_s.lua
|
--[[
********************************************************************************
Project owner: GTWGames
Project name: GTW-RPG
Developers: GTWCode
Source code: https://github.com/GTWCode/GTW-RPG/
Bugtracker: http://forum.albonius.com/bug-reports/
Suggestions: http://forum.albonius.com/mta-servers-development/
Version: Open source
License: GPL v.3 or later
Status: Stable release
********************************************************************************
]]--
-- Storage for skins
t_skins = { }
t_skins.all_skins = { }
t_skins.by_category = { }
--[[ Initialize and load all the skins from XML ]]--
function initialize_skins()
local xml = xmlLoadFile("skin_data.xml")
for i1, category in pairs(xmlNodeGetChildren(xml)) do
local c_name = xmlNodeGetAttribute(category, "name")
t_skins.by_category[c_name] = {}
for i2, skin in pairs(xmlNodeGetChildren(category)) do
local id, name = xmlNodeGetAttribute(skin, "model"), xmlNodeGetAttribute(skin, "name")
t_skins.by_category[c_name][id] = name
t_skins.all_skins[id] = name
end
end
xmlUnloadFile(xml)
end
addEventHandler("onResourceStart", resourceRoot, initialize_skins)
--[[ Return available skins from table ]]--
function get_skins(category)
if not category then
return t_skins.by_category or false
elseif category == "all" then
return t_skins.all_skins or false
else
return t_skins[category] or false
end
return false
end
--[[ Initialize the skin shops ]]--
function make_the_shop()
for i, shop in pairs(shops) do
local x, y, z, int, dim, type = shop.x, shop.y, shop.z, shop.int, shop.dim, shop.type
marker = createMarker(x, y, z, "cylinder", 1.5, 255, 255, 255, 30)
setElementInterior(marker, int)
setElementDimension(marker, dim)
if type == 2 then
setElementAlpha(marker,0)
end
addEventHandler("onMarkerHit", marker, on_marker_hit)
end
for i2, shop_blip in pairs(shop_blips) do
local x, y, z = shop_blip.x, shop_blip.y, shop_blip.z
blip = createBlip( x, y, z, 45, 2, 0, 0, 0, 255, 2, 180 )
end
end
addEventHandler("onResourceStart", resourceRoot, make_the_shop)
--[[ On entering the shop ]]--
function on_marker_hit(plr, matchingDim)
if (plr and getElementType(plr) == "player" and matchingDim) then
local skins = get_skins()
triggerClientEvent(plr, "GTWclothes.showSkin", plr, skins)
triggerClientEvent(plr, "GTWclothes.showSkin", plr, skins)
end
end
--[[ On client request buy skin ]]--
function buy_the_skin(model)
if getPlayerMoney(client) >= 50 then
takePlayerMoney(client, 50)
exports.GTWtopbar:dm("You have succesfully bought a new skin!", client, 0, 255, 0)
setAccountData(getPlayerAccount(client), "clothes.boughtSkin", model)
setElementData(client, "clothes.boughtSkin", model)
setElementModel(client, model)
else
exports.GTWtopbar:dm( "Feck off you little pleb, get yourself some cash before you come back.", client, 255, 0, 0 )
end
end
addEvent("GTWclothes.buy_the_skin", true)
addEventHandler("GTWclothes.buy_the_skin", root, buy_the_skin)
--[[ Exported function to get the current skin ]]--
function getBoughtSkin(player)
if (not isElement(player)) then return end
return tonumber(getAccountData(getPlayerAccount(player), "clothes.boughtSkin")) or getElementModel(player) or 0
end
--[[ Save the skin as element data ]]--
function save_skin( )
setElementData(source, "clothes.boughtSkin", getBoughtSkin(source))
end
addEventHandler("onPlayerLogin", root, save_skin)
|
--[[
********************************************************************************
Project owner: GTWGames
Project name: GTW-RPG
Developers: GTWCode
Source code: https://github.com/GTWCode/GTW-RPG/
Bugtracker: http://forum.albonius.com/bug-reports/
Suggestions: http://forum.albonius.com/mta-servers-development/
Version: Open source
License: GPL v.3 or later
Status: Stable release
********************************************************************************
]]--
-- Storage for skins
t_skins = { }
t_skins.all_skins = { }
t_skins.by_category = { }
--[[ Initialize and load all the skins from XML ]]--
function initialize_skins()
local xml = xmlLoadFile("skin_data.xml")
for i1, category in pairs(xmlNodeGetChildren(xml)) do
local c_name = xmlNodeGetAttribute(category, "name")
t_skins.by_category[c_name] = {}
for i2, skin in pairs(xmlNodeGetChildren(category)) do
local id, name = xmlNodeGetAttribute(skin, "model"), xmlNodeGetAttribute(skin, "name")
t_skins.by_category[c_name][id] = name
t_skins.all_skins[id] = name
end
end
xmlUnloadFile(xml)
end
addEventHandler("onResourceStart", resourceRoot, initialize_skins)
--[[ Return available skins from table ]]--
function get_skins(category)
if not category then
return t_skins.by_category or false
elseif category == "all" then
return t_skins.all_skins or false
else
return t_skins[category] or false
end
return false
end
--[[ Initialize the skin shops ]]--
function make_the_shop()
for i, shop in pairs(shops) do
local x, y, z, int, dim, type = shop.x, shop.y, shop.z, shop.int, shop.dim, shop.type
marker = createMarker(x, y, z, "cylinder", 1.5, 255, 255, 255, 30)
setElementInterior(marker, int)
setElementDimension(marker, dim)
if type == 2 then
setElementAlpha(marker,0)
end
addEventHandler("onMarkerHit", marker, on_marker_hit)
end
for i2, shop_blip in pairs(shop_blips) do
local x, y, z = shop_blip.x, shop_blip.y, shop_blip.z
blip = createBlip( x, y, z, 45, 2, 0, 0, 0, 255, 2, 180 )
end
end
addEventHandler("onResourceStart", resourceRoot, make_the_shop)
--[[ On entering the shop ]]--
function on_marker_hit(plr, matchingDim)
if (plr and getElementType(plr) == "player" and matchingDim) then
local skins = get_skins()
triggerClientEvent(plr, "GTWclothes.show_skin", plr, skins)
end
end
--[[ On client request buy skin ]]--
function buy_the_skin(model)
if getPlayerMoney(client) >= 50 then
takePlayerMoney(client, 50)
exports.GTWtopbar:dm("You have succesfully bought a new skin!", client, 0, 255, 0)
setAccountData(getPlayerAccount(client), "clothes.boughtSkin", model)
setElementData(client, "clothes.boughtSkin", model)
setElementModel(client, model)
else
exports.GTWtopbar:dm( "Feck off you little pleb, get yourself some cash before you come back.", client, 255, 0, 0 )
end
end
addEvent("GTWclothes.buy_the_skin", true)
addEventHandler("GTWclothes.buy_the_skin", root, buy_the_skin)
--[[ Exported function to get the current skin ]]--
function getBoughtSkin(player)
if (not isElement(player)) then return end
return tonumber(getAccountData(getPlayerAccount(player), "clothes.boughtSkin")) or getElementModel(player) or 0
end
--[[ Save the skin as element data ]]--
function save_skin( )
setElementData(source, "clothes.boughtSkin", getBoughtSkin(source))
end
addEventHandler("onPlayerLogin", root, save_skin)
|
[Patch] Fixed an event trigger bug
|
[Patch] Fixed an event trigger bug
* Renamed event trigger as it didn't synced correctly
|
Lua
|
bsd-2-clause
|
GTWCode/GTW-RPG,404rq/GTW-RPG,GTWCode/GTW-RPG,404rq/GTW-RPG,SpRoXx/GTW-RPG,404rq/GTW-RPG,SpRoXx/GTW-RPG,GTWCode/GTW-RPG
|
64122cf036bbe5e9690c0b103b9658e2e3ceea4f
|
gmod_wire_starfall_processor/compiler/compiler.lua
|
gmod_wire_starfall_processor/compiler/compiler.lua
|
local SF_Compiler = SF_Compiler or {}
SF_Compiler.__index = SF_Compiler
function SF_Compiler:Error(message, instr)
error(message .. " at line " .. instr[2][1] .. ", char " .. instr[2][2], 0)
end
function SF_Compiler:Process(root, inputs, outputs, params)
self.contexts = {}
self:PushContext()
self.inputs = inputs
self.outputs = outputs
self.code = ""
end
function SF_Compiler:EvaluateStatement(args, index)
local name = string.upper(args[index + 2][1])
local ex, tp = SF_Compiler["Instr" .. name](self, args[index + 2])
return ex, tp
end
function SF_Compiler:Evaluate(args, index)
local ex, tp = self:EvaluateStatement(args, index)
if tp == "" then
self:Error("Function has no return value (void), cannot be part of expression or assigned", args)
end
return ex, tp
end
-- ---------------------------------------- --
-- Context Management --
-- ---------------------------------------- --
function SF_Compiler:PushContext()
local tbl = {
vars = {},
code = "",
cost = 0
}
self.contexts[#self.contexts + 1] = tbl
end
function SF_Compiler:PopContext(ending)
ending = ending or "end"
local tbl = self.contexts[#self.contexts]
self.contexts[#self.contexts] = nil
if tbl.vars[1] then
local varsdef = "local "
for _,var in ipairs(tbl.vars) do
varsdef = varsdef .. var .. ", "
end
self:AddCode(varsdef:sub(1,varsdef:len()-2)
end
self:AddCode("SF_Self:IncrementCost("..tbl.cost..")\n")
self:AddCode(tbl.code.."\n"..ending.."\n")
end
function SF_Compiler:AddCode(code)
-- Adds code to the current context.
-- ONLY statement instructions should call this!
local tbl = self.contexts[#self.contexts]
tbl.code = tbl.code .. code
end
function SF_Compiler:IncrementCost(cost)
local tbl = self.contexts[#self.contexts]
tbl.cost = tbl.cost + cost
end
-- ---------------------------------------- --
-- Variable Management --
-- ---------------------------------------- --
function SF_Compiler:DefineVar(name, typ, instr)
--local name, typ = args[2], args[3]
local curcontext = self.contexts[#self.contexts]
if curcontext[name] ~= typ then
self:Error("Types for variable "..var.." do not match (expected "..self:GetVarType(var,instr)..", got "..tp..")",args)
end
curcontext[name] = typ
end
--[[TODO: Don't think we need this
function SF_Compiler:DefineGlobalVar(name, typ)
if self.contexts[1][name] ~= typ then
self:Error("Type mismatch for variable " .. name .. " (expected " .. self.contexts[1][name] .. ", got " .. typ)
end
self.contexts[1][name] = typ
end]]
function SF_Compiler:GetVarType(name, instr)
for i = #self.contexts, 1, -1 do
if self.contexts[i][name] then
return self.contexts[i][name]
end
end
if self.outputs[name] then return self.outputs[name] end
if self.inputs[name] then return self.inputs[name] end
self:Error("Undefined variable (" .. name .. ")", instr)
end
-- ---------------------------------------- --
-- Instructions - Statements --
-- ---------------------------------------- --
function SF_Compiler:InstrDECL(args)
local typ, name, val = args[3],args[4],args[5]
self:DefineVar(name, typ, instr)
if val then
local ex, tp = self:Evaluate(args,3)
self:AddCode(name .. " = " .. ex)
end
end
function SF_Compiler:InstrASS(args)
local var = args[3]
local ex, tp = self:Evaluate(args,2)
if tp ~= self:GetVarType(var) then
self:Error("Types for variable "..var.." do not match (expected "..self:GetVarType(var,instr)..", got "..tp..")",args)
end
end
-- ---------------------------------------- --
-- Instructions - Expression --
-- ---------------------------------------- --
function SF_Compiler:InstrVAR(args)
local name = args[3]
local typ = self:GetVarType(name)
return self:GenerateLua_VariableReference(name), typ
end
function SF_Compiler:InstrNUM(args)
local num = args[3]
return num, "number"
end
function SF_Compiler:InstrSTR(args)
local str = args[3]
str = str:replace('"',"\\\"")
str = "\""..str.."\""
return str, "string"
end
-- ---------------------------------------- --
-- Lua Generation Functions --
-- ---------------------------------------- --
function SF_Compiler:GenerateLua_VariableReference(name)
for i = #self.contexts, 1, -1 do
if self.contexts[i][name] then
return self.contexts[i][name]
end
end
if self.outputs[name] then return "SF_Ent.outputs[\"" .. name .. "\"]" end
if self.inputs[name] then return "SF_Ent.inputs[\"" .. name .. "\"]" end
error("Internal Error: Tried to generate Lua code for undefined variable \""..name.."\"! Post your code & this error at wiremod.com.")
end
|
local SF_Compiler = SF_Compiler or {}
SF_Compiler.__index = SF_Compiler
function SF_Compiler:Error(message, instr)
error(message .. " at line " .. instr[2][1] .. ", char " .. instr[2][2], 0)
end
function SF_Compiler:Process(root, inputs, outputs, params)
self.contexts = {}
self:PushContext("do")
self.inputs = inputs
self.outputs = outputs
self.code = ""
self:PopContext()
-- Debug code
if #self.contexts > 0 then
error("SF Internal Error: Did not pop all contexts.")
end
end
function SF_Compiler:EvaluateStatement(args, index)
local name = string.upper(args[index + 2][1])
local ex, tp = SF_Compiler["Instr" .. name](self, args[index + 2])
return ex, tp
end
function SF_Compiler:Evaluate(args, index)
local ex, tp = self:EvaluateStatement(args, index)
if tp == "" then
self:Error("Function has no return value (void), cannot be part of expression or assigned", args)
end
return ex, tp
end
-- ---------------------------------------- --
-- Context Management --
-- ---------------------------------------- --
function SF_Compiler:PushContext(beginning)
local tbl = {
vars = {},
code = "",
cost = 0
}
self.contexts[#self.contexts + 1] = tbl
self:AddCode(beginning or "")
end
function SF_Compiler:PopContext(ending)
ending = ending or "end"
local tbl = self.contexts[#self.contexts]
self.contexts[#self.contexts] = nil
if tbl.vars[1] then
local varsdef = "local "
for _,var in ipairs(tbl.vars) do
varsdef = varsdef .. var .. ", "
end
self:AddCode(varsdef:sub(1,varsdef:len()-2)
end
self:AddCode("SF_Self:IncrementCost("..tbl.cost..")\n")
self:AddCode(tbl.code.."\n"..ending.."\n")
end
function SF_Compiler:AddCode(code)
-- Adds code to the current context.
-- ONLY statement instructions should call this!
local tbl = self.contexts[#self.contexts]
tbl.code = tbl.code .. code
end
function SF_Compiler:IncrementCost(cost)
local tbl = self.contexts[#self.contexts]
tbl.cost = tbl.cost + cost
end
-- ---------------------------------------- --
-- Variable Management --
-- ---------------------------------------- --
function SF_Compiler:DefineVar(name, typ, instr)
--local name, typ = args[2], args[3]
local curcontext = self.contexts[#self.contexts]
if curcontext[name] ~= typ then
self:Error("Types for variable "..var.." do not match (expected "..self:GetVarType(var,instr)..", got "..tp..")",args)
end
curcontext[name] = typ
end
--[[TODO: Don't think we need this
function SF_Compiler:DefineGlobalVar(name, typ)
if self.contexts[1][name] ~= typ then
self:Error("Type mismatch for variable " .. name .. " (expected " .. self.contexts[1][name] .. ", got " .. typ)
end
self.contexts[1][name] = typ
end]]
function SF_Compiler:GetVarType(name, instr)
for i = #self.contexts, 1, -1 do
if self.contexts[i][name] then
return self.contexts[i][name]
end
end
if self.outputs[name] then return self.outputs[name] end
if self.inputs[name] then return self.inputs[name] end
if SFLib.functions[name] then
return "function"
end
self:Error("Undefined variable (" .. name .. ")", instr)
end
-- ---------------------------------------- --
-- Instructions - Statements --
-- ---------------------------------------- --
function SF_Compiler:InstrDECL(args)
local typ, name, val = args[3],args[4],args[5]
self:DefineVar(name, typ, args)
if val then
local ex, tp = self:Evaluate(args,3)
self:AddCode(name .. " = " .. ex)
end
end
function SF_Compiler:InstrASS(args)
local var = args[3]
local ex, tp = self:Evaluate(args,2)
if tp ~= self:GetVarType(var, args) then
self:Error("Types for variable "..var.." do not match (expected "..self:GetVarType(var,args)..", got "..tp..")",args)
end
end
-- ---------------------------------------- --
-- Instructions - Expression --
-- ---------------------------------------- --
function SF_Compiler:InstrVAR(args)
local name = args[3]
local typ = self:GetVarType(name)
return self:GenerateLua_VariableReference(name), typ
end
function SF_Compiler:InstrNUM(args)
local num = args[3]
return num, "number"
end
function SF_Compiler:InstrSTR(args)
local str = args[3]
str = str:replace('"',"\\\""):replace("\n","\\n")
str = "\""..str.."\""
return str, "string"
end
function SF_Compiler:InstrCALL(args)
local ex, tp = self:Evaluate(args,1)
local instrs = args[4]
local exprs = {}
local tps = {}
if tp ~= "function" then
self:Error("Tried to call non-function value",args)
end
for i=1,#args[4] do
local ex, tp = self:Evaluate(args[4], i - 2)
tps[#tps + 1] = tp
exprs[#exprs + 1] = ex
end
end
-- ---------------------------------------- --
-- Lua Generation Functions --
-- ---------------------------------------- --
function SF_Compiler:GenerateLua_VariableReference(name)
for i = #self.contexts, 1, -1 do
if self.contexts[i][name] then
return self.contexts[i][name]
end
end
if self.outputs[name] then return "SF_Ent.outputs[\"" .. name .. "\"]" end
if self.inputs[name] then return "SF_Ent.inputs[\"" .. name .. "\"]" end
if SFLib.functions[name] then
return "SFLib.functions[\""..name.."\"]"
end
error("Internal Error: Tried to generate Lua code for undefined variable \""..name.."\"! Post your code & this error at wiremod.com.")
end
|
[Starfall] [compiler.lua] Added stuff to main method, GetType() now returns "function" for functions, fixed several incorrect variable names, added incomplete "call" instruction
|
[Starfall]
[compiler.lua] Added stuff to main method,
GetType() now returns "function" for functions,
fixed several incorrect variable names,
added incomplete "call" instruction
|
Lua
|
bsd-3-clause
|
Jazzelhawk/Starfall,Ingenious-Gaming/Starfall,Jazzelhawk/Starfall,Ingenious-Gaming/Starfall,INPStarfall/Starfall,INPStarfall/Starfall,Xandaros/Starfall,Xandaros/Starfall
|
1a1e16e9dffff6b43e7ed91c40d05376e9b2e4fe
|
xmake-repo/packages/n/nodeeditor/xmake.lua
|
xmake-repo/packages/n/nodeeditor/xmake.lua
|
package("nodeeditor")
set_homepage("https://github.com/paceholder/nodeeditor")
set_description("Qt Node Editor. Dataflow programming framework")
set_license("BSD-3")
set_urls("https://github.com/paceholder/nodeeditor/archive/refs/tags/$(version).tar.gz",
"https://github.com/paceholder/nodeeditor.git")
add_versions("2.1.3", "4e3194a04ac4a2a2bf4bc8eb6cc27d5cc154923143c1ecf579ce7f0115a90585")
add_patches("2.1.3", path.join(os.scriptdir(), "patches", "2.1.3", "fix_qt.patch"), "17cdcb44a4e1d7b7a959d3717e71b068c356f2a09d910ae5a7b33e5c65c25139")
add_deps("cmake")
on_load(function (package)
if package:config("shared") then
package:add("defines", "NODE_EDITOR_SHARED")
else
package:add("defines", "NODE_EDITOR_STATIC")
end
end)
on_install("windows", "linux", "mingw", "macosx", function (package)
import("detect.sdks.find_qt")
local qt = find_qt()
local configs = {"-DBUILD_EXAMPLES=OFF", "-DBUILD_TESTING=OFF"}
table.insert(configs, "-DBUILD_SHARED_LIBS=" .. (package:config("shared") and "ON" or "OFF"))
table.insert(configs, "-DCMAKE_BUILD_TYPE=" .. (package:debug() and "Debug" or "Release"))
if qt then
table.insert(configs, "-DQt5_DIR=" .. path.join(qt.libdir, "cmake", "Qt5"))
end
import("package.tools.cmake").install(package, configs)
end)
on_test(function (package)
do
-- Disable test until I can test with Qt
return
end
assert(package:check_cxxsnippets({test = [[
void test() {
QtNodes::FlowScene scene(std::make_shared<QtNodes::DataModelRegistry>());
QtNodes::FlowView view(&scene);
}
]]}, {configs = {languages = "c++11"}, includes = {"nodes/FlowScene", "nodes/FlowView"}}))
end)
|
package("nodeeditor")
set_homepage("https://github.com/paceholder/nodeeditor")
set_description("Qt Node Editor. Dataflow programming framework")
set_license("BSD-3")
set_urls("https://github.com/paceholder/nodeeditor/archive/refs/tags/$(version).tar.gz",
"https://github.com/paceholder/nodeeditor.git")
add_versions("2.1.3", "4e3194a04ac4a2a2bf4bc8eb6cc27d5cc154923143c1ecf579ce7f0115a90585")
add_patches("2.1.3", path.join(os.scriptdir(), "patches", "2.1.3", "fix_qt.patch"), "804ee98d47b675c578981414ed25a745f1b12d0cd8b03ea7d7b079c7e1ce1ea9")
add_deps("cmake")
on_load(function (package)
if package:config("shared") then
package:add("defines", "NODE_EDITOR_SHARED")
else
package:add("defines", "NODE_EDITOR_STATIC")
end
end)
on_install("windows", "linux", "mingw", "macosx", function (package)
import("detect.sdks.find_qt")
local qt = find_qt()
local configs = {"-DBUILD_EXAMPLES=OFF", "-DBUILD_TESTING=OFF"}
table.insert(configs, "-DBUILD_SHARED_LIBS=" .. (package:config("shared") and "ON" or "OFF"))
table.insert(configs, "-DCMAKE_BUILD_TYPE=" .. (package:debug() and "Debug" or "Release"))
if qt then
table.insert(configs, "-DQt5_DIR=" .. path.join(qt.libdir, "cmake", "Qt5"))
end
import("package.tools.cmake").install(package, configs)
end)
on_test(function (package)
do
-- Disable test until I can test with Qt
return
end
assert(package:check_cxxsnippets({test = [[
void test() {
QtNodes::FlowScene scene(std::make_shared<QtNodes::DataModelRegistry>());
QtNodes::FlowView view(&scene);
}
]]}, {configs = {languages = "c++11"}, includes = {"nodes/FlowScene", "nodes/FlowView"}}))
end)
|
Fix nodeeditor patch checksum
|
Fix nodeeditor patch checksum
|
Lua
|
mit
|
DigitalPulseSoftware/NazaraEngine
|
0e1099f25abcbcef723686b5486dc5c8f6b252fa
|
src/patch/ui/lib/mppatch_runtime.lua
|
src/patch/ui/lib/mppatch_runtime.lua
|
-- Copyright (c) 2015-2016 Lymia Alusyia <lymia@lymiahugs.com>
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
local function createTable()
_mpPatch = {}
_mpPatch._mt = {}
setmetatable(_mpPatch, _mpPatch._mt)
end
local function patchCriticalError(error, statusMarker)
createTable()
print("[MPPatch] Cannot load due to critical error: "..error)
_mpPatch.enabled = false
_mpPatch.canEnable = false
if statusMarker then _mpPatch[statusMarker] = true end
function _mpPatch._mt.__index(_, k)
error("Access to field "..k.." in MpPatch runtime without patch installed.")
end
function _mpPatch._mt.__newindex(_, k, v)
error("Write to field "..k.." in MpPatch runtime without patch installed.")
end
end
local patch = DB.GetMemoryUsage("216f0090-85dd-4061-8371-3d8ba2099a70")
if not patch.__mppatch_marker then
patchCriticalError("Could not load binary patch.")
return
end
createTable()
_mpPatch.patch = patch
do
include "mppatch_version.lua"
if not _mpPatch.version then
patchCriticalError("Could not load version information.")
return
end
local platformString = patch.version.platform.."_"..patch.version.sha256
local expectedBuildId = _mpPatch.version.buildId[platformString]
if not expectedBuildId or expectedBuildId ~= patch.version.buildId then
patchCriticalError("BuildID mismatch.")
return
end
end
_mpPatch.context = "<init>"
_mpPatch.uuid = "df74f698-2343-11e6-89c4-8fef6d8f889e"
_mpPatch.enabled = ContentManager.IsActive(_mpPatch.uuid, ContentType.GAMEPLAY)
_mpPatch.canEnable = true
_mpPatch.debug = patch.config.enableDebug
function _mpPatch.debugPrint(...)
local args = {...}
local accum = ""
local count = 0
for k, _ in pairs(args) do
if k > count then count = k end
end
for i=1,count do
accum = accum .. args[i]
if i ~= count then accum = accum .. "\t" end
end
print("[MPPatch] "..accum)
patch.debugPrint(_mpPatch.fullPath..": "..accum)
end
include "mppatch_mtutils.lua"
include "mppatch_utils.lua"
include "mppatch_modutils.lua"
include "mppatch_uiutils.lua"
_mpPatch.debugPrint("MPPatch runtime loaded")
_mpPatch.context = _mpPatch.fullPath
_mpPatch.debugPrint("Current UI path: ".._mpPatch.context)
|
-- Copyright (c) 2015-2016 Lymia Alusyia <lymia@lymiahugs.com>
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
local function createTable()
_mpPatch = {}
_mpPatch._mt = {}
setmetatable(_mpPatch, _mpPatch._mt)
end
local function patchCriticalError(error, statusMarker)
createTable()
print("[MPPatch] Cannot load due to critical error: "..error)
_mpPatch.enabled = false
_mpPatch.canEnable = false
if statusMarker then _mpPatch[statusMarker] = true end
function _mpPatch._mt.__index(_, k)
error("Access to field "..k.." in MpPatch runtime without patch installed.")
end
function _mpPatch._mt.__newindex(_, k, v)
error("Write to field "..k.." in MpPatch runtime without patch installed.")
end
end
local patch = DB.GetMemoryUsage("216f0090-85dd-4061-8371-3d8ba2099a70")
if not patch.__mppatch_marker then
patchCriticalError("Could not load binary patch.")
return
end
createTable()
_mpPatch.patch = patch
do
include "mppatch_version.lua"
if not _mpPatch.version then
patchCriticalError("Could not load version information.")
return
end
local platformString = patch.version.platform.."_"..patch.version.sha256
local expectedBuildId = _mpPatch.version.buildId[platformString]
if not expectedBuildId or expectedBuildId ~= patch.version.buildId then
patchCriticalError("BuildID mismatch.")
return
end
end
_mpPatch.versionString = patch.version.versionString
_mpPatch.context = "<init>"
_mpPatch.uuid = "df74f698-2343-11e6-89c4-8fef6d8f889e"
_mpPatch.enabled = ContentManager.IsActive(_mpPatch.uuid, ContentType.GAMEPLAY)
_mpPatch.canEnable = true
_mpPatch.debug = patch.config.enableDebug
function _mpPatch.debugPrint(...)
local args = {...}
local accum = ""
local count = 0
for k, _ in pairs(args) do
if k > count then count = k end
end
for i=1,count do
accum = accum .. args[i]
if i ~= count then accum = accum .. "\t" end
end
print("[MPPatch] "..accum)
patch.debugPrint(_mpPatch.fullPath..": "..accum)
end
include "mppatch_mtutils.lua"
include "mppatch_utils.lua"
include "mppatch_modutils.lua"
include "mppatch_uiutils.lua"
_mpPatch.debugPrint("MPPatch runtime loaded")
_mpPatch.context = _mpPatch.fullPath
_mpPatch.debugPrint("Current UI path: ".._mpPatch.context)
|
Fix mainmenu version.
|
Fix mainmenu version.
|
Lua
|
mit
|
Lymia/MPPatch,Lymia/MPPatch,Lymia/MPPatch,Lymia/MPPatch,Lymia/MultiverseModManager,Lymia/MultiverseModManager,Lymia/CivV_Mod2DLC
|
d4b183de41706158eb91c083d8d8ca89d2d7ee86
|
vrp/modules/money.lua
|
vrp/modules/money.lua
|
local lang = vRP.lang
-- Money module, wallet/bank API
-- The money is managed with direct SQL requests to prevent most potential value corruptions
-- the wallet empty itself when respawning (after death)
MySQL.createCommand("vRP/money_tables", [[
CREATE TABLE IF NOT EXISTS vrp_user_moneys(
user_id INTEGER,
wallet INTEGER,
bank INTEGER,
CONSTRAINT pk_user_moneys PRIMARY KEY(user_id),
CONSTRAINT fk_user_moneys_users FOREIGN KEY(user_id) REFERENCES vrp_users(id) ON DELETE CASCADE
);
]])
MySQL.createCommand("vRP/money_init_user","INSERT IGNORE INTO vrp_user_moneys(user_id,wallet,bank) VALUES(@user_id,@wallet,@bank)")
MySQL.createCommand("vRP/get_money","SELECT wallet,bank FROM vrp_user_moneys WHERE user_id = @user_id")
MySQL.createCommand("vRP/set_money","UPDATE vrp_user_moneys SET wallet = @wallet, bank = @bank WHERE user_id = @user_id")
-- init tables
MySQL.execute("vRP/money_tables")
-- load config
local cfg = module("cfg/money")
-- API
-- get money
-- cbreturn nil if error
function vRP.getMoney(user_id)
local tmp = vRP.getUserTmpTable(user_id)
if tmp then
return tmp.wallet or 0
else
return 0
end
end
-- set money
function vRP.setMoney(user_id,value)
local tmp = vRP.getUserTmpTable(user_id)
if tmp then
tmp.wallet = value
end
-- update client display
local source = vRP.getUserSource(user_id)
if source ~= nil then
vRPclient.setDivContent(source,{"money",lang.money.display({value})})
end
end
-- try a payment
-- return true or false (debited if true)
function vRP.tryPayment(user_id,amount)
local money = vRP.getMoney(user_id)
if money >= amount then
vRP.setMoney(user_id,money-amount)
return true
else
return false
end
end
-- give money
function vRP.giveMoney(user_id,amount)
local money = vRP.getMoney(user_id)
vRP.setMoney(user_id,money+amount)
end
-- get bank money
function vRP.getBankMoney(user_id)
local tmp = vRP.getUserTmpTable(user_id)
if tmp then
return tmp.bank or 0
else
return 0
end
end
-- set bank money
function vRP.setBankMoney(user_id,value)
local tmp = vRP.getUserTmpTable(user_id)
if tmp then
tmp.bank = value
end
end
-- give bank money
function vRP.giveBankMoney(user_id,amount)
if amount > 0 then
local money = vRP.getBankMoney(user_id)
vRP.setBankMoney(user_id,money+amount)
end
end
-- try a withdraw
-- return true or false (withdrawn if true)
function vRP.tryWithdraw(user_id,amount)
local money = vRP.getBankMoney(user_id)
if amount > 0 and money >= amount then
vRP.setBankMoney(user_id,money-amount)
vRP.giveMoney(user_id,amount)
return true
else
return false
end
end
-- try a deposit
-- return true or false (deposited if true)
function vRP.tryDeposit(user_id,amount)
if amount > 0 and vRP.tryPayment(user_id,amount) then
vRP.giveBankMoney(user_id,amount)
return true
else
return false
end
end
-- try full payment (wallet + bank to complete payment)
-- return true or false (debited if true)
function vRP.tryFullPayment(user_id,amount)
local money = vRP.getMoney(user_id)
if money >= amount then -- enough, simple payment
return vRP.tryPayment(user_id, amount)
else -- not enough, withdraw -> payment
if vRP.tryWithdraw(user_id, amount-money) then -- withdraw to complete amount
return vRP.tryPayment(user_id, amount)
end
end
return false
end
-- events, init user account if doesn't exist at connection
AddEventHandler("vRP:playerJoin",function(user_id,source,name,last_login)
MySQL.execute("vRP/money_init_user", {user_id = user_id, wallet = cfg.open_wallet, bank = cfg.open_bank}, function(affected)
-- load money (wallet,bank)
local tmp = vRP.getUserTmpTable(user_id)
if tmp then
MySQL.query("vRP/get_money", {user_id = user_id}, function(rows, affected)
if #rows > 0 then
tmp.bank = rows[1].bank
tmp.wallet = rows[1].wallet
end
end)
end
end)
end)
-- save money on leave
AddEventHandler("vRP:playerLeave",function(user_id,source)
-- (wallet,bank)
local tmp = vRP.getUserTmpTable(user_id)
if tmp and tmp.wallet ~= nil and tmp.bank ~= nil then
MySQL.execute("vRP/set_money", {user_id = user_id, wallet = tmp.wallet, bank = tmp.bank})
end
end)
-- save money (at same time that save datatables)
AddEventHandler("vRP:save", function()
for k,v in pairs(vRP.user_tmp_tables) do
if v.wallet ~= nil and v.bank ~= nil then
MySQL.execute("vRP/set_money", {user_id = k, wallet = v.wallet, bank = v.bank})
end
end
end)
-- money hud
AddEventHandler("vRP:playerSpawn",function(user_id, source, first_spawn)
if first_spawn then
-- add money display
vRPclient.setDiv(source,{"money",cfg.display_css,lang.money.display({vRP.getMoney(user_id)})})
end
end)
local function ch_give(player,choice)
-- get nearest player
local user_id = vRP.getUserId(player)
if user_id ~= nil then
vRPclient.getNearestPlayer(player,{10},function(nplayer)
if nplayer ~= nil then
local nuser_id = vRP.getUserId(nplayer)
if nuser_id ~= nil then
-- prompt number
vRP.prompt(player,lang.money.give.prompt(),"",function(player,amount)
local amount = parseInt(amount)
if amount > 0 and vRP.tryPayment(user_id,amount) then
vRP.giveMoney(nuser_id,amount)
vRPclient.notify(player,{lang.money.given({amount})})
vRPclient.notify(nplayer,{lang.money.received({amount})})
else
vRPclient.notify(player,{lang.money.not_enough()})
end
end)
else
vRPclient.notify(player,{lang.common.no_player_near()})
end
else
vRPclient.notify(player,{lang.common.no_player_near()})
end
end)
end
end
-- add player give money to main menu
vRP.registerMenuBuilder("main", function(add, data)
local user_id = vRP.getUserId(data.player)
if user_id ~= nil then
local choices = {}
choices[lang.money.give.title()] = {ch_give, lang.money.give.description()}
add(choices)
end
end)
|
local lang = vRP.lang
-- Money module, wallet/bank API
-- The money is managed with direct SQL requests to prevent most potential value corruptions
-- the wallet empty itself when respawning (after death)
MySQL.createCommand("vRP/money_tables", [[
CREATE TABLE IF NOT EXISTS vrp_user_moneys(
user_id INTEGER,
wallet INTEGER,
bank INTEGER,
CONSTRAINT pk_user_moneys PRIMARY KEY(user_id),
CONSTRAINT fk_user_moneys_users FOREIGN KEY(user_id) REFERENCES vrp_users(id) ON DELETE CASCADE
);
]])
MySQL.createCommand("vRP/money_init_user","INSERT IGNORE INTO vrp_user_moneys(user_id,wallet,bank) VALUES(@user_id,@wallet,@bank)")
MySQL.createCommand("vRP/get_money","SELECT wallet,bank FROM vrp_user_moneys WHERE user_id = @user_id")
MySQL.createCommand("vRP/set_money","UPDATE vrp_user_moneys SET wallet = @wallet, bank = @bank WHERE user_id = @user_id")
-- init tables
MySQL.execute("vRP/money_tables")
-- load config
local cfg = module("cfg/money")
-- API
-- get money
-- cbreturn nil if error
function vRP.getMoney(user_id)
local tmp = vRP.getUserTmpTable(user_id)
if tmp then
return tmp.wallet or 0
else
return 0
end
end
-- set money
function vRP.setMoney(user_id,value)
local tmp = vRP.getUserTmpTable(user_id)
if tmp then
tmp.wallet = value
end
-- update client display
local source = vRP.getUserSource(user_id)
if source ~= nil then
vRPclient.setDivContent(source,{"money",lang.money.display({value})})
end
end
-- try a payment
-- return true or false (debited if true)
function vRP.tryPayment(user_id,amount)
local money = vRP.getMoney(user_id)
if amount >= 0 and money >= amount then
vRP.setMoney(user_id,money-amount)
return true
else
return false
end
end
-- give money
function vRP.giveMoney(user_id,amount)
if amount > 0 then
local money = vRP.getMoney(user_id)
vRP.setMoney(user_id,money+amount)
end
end
-- get bank money
function vRP.getBankMoney(user_id)
local tmp = vRP.getUserTmpTable(user_id)
if tmp then
return tmp.bank or 0
else
return 0
end
end
-- set bank money
function vRP.setBankMoney(user_id,value)
local tmp = vRP.getUserTmpTable(user_id)
if tmp then
tmp.bank = value
end
end
-- give bank money
function vRP.giveBankMoney(user_id,amount)
if amount > 0 then
local money = vRP.getBankMoney(user_id)
vRP.setBankMoney(user_id,money+amount)
end
end
-- try a withdraw
-- return true or false (withdrawn if true)
function vRP.tryWithdraw(user_id,amount)
local money = vRP.getBankMoney(user_id)
if amount >= 0 and money >= amount then
vRP.setBankMoney(user_id,money-amount)
vRP.giveMoney(user_id,amount)
return true
else
return false
end
end
-- try a deposit
-- return true or false (deposited if true)
function vRP.tryDeposit(user_id,amount)
if amount >= 0 and vRP.tryPayment(user_id,amount) then
vRP.giveBankMoney(user_id,amount)
return true
else
return false
end
end
-- try full payment (wallet + bank to complete payment)
-- return true or false (debited if true)
function vRP.tryFullPayment(user_id,amount)
local money = vRP.getMoney(user_id)
if money >= amount then -- enough, simple payment
return vRP.tryPayment(user_id, amount)
else -- not enough, withdraw -> payment
if vRP.tryWithdraw(user_id, amount-money) then -- withdraw to complete amount
return vRP.tryPayment(user_id, amount)
end
end
return false
end
-- events, init user account if doesn't exist at connection
AddEventHandler("vRP:playerJoin",function(user_id,source,name,last_login)
MySQL.execute("vRP/money_init_user", {user_id = user_id, wallet = cfg.open_wallet, bank = cfg.open_bank}, function(affected)
-- load money (wallet,bank)
local tmp = vRP.getUserTmpTable(user_id)
if tmp then
MySQL.query("vRP/get_money", {user_id = user_id}, function(rows, affected)
if #rows > 0 then
tmp.bank = rows[1].bank
tmp.wallet = rows[1].wallet
end
end)
end
end)
end)
-- save money on leave
AddEventHandler("vRP:playerLeave",function(user_id,source)
-- (wallet,bank)
local tmp = vRP.getUserTmpTable(user_id)
if tmp and tmp.wallet ~= nil and tmp.bank ~= nil then
MySQL.execute("vRP/set_money", {user_id = user_id, wallet = tmp.wallet, bank = tmp.bank})
end
end)
-- save money (at same time that save datatables)
AddEventHandler("vRP:save", function()
for k,v in pairs(vRP.user_tmp_tables) do
if v.wallet ~= nil and v.bank ~= nil then
MySQL.execute("vRP/set_money", {user_id = k, wallet = v.wallet, bank = v.bank})
end
end
end)
-- money hud
AddEventHandler("vRP:playerSpawn",function(user_id, source, first_spawn)
if first_spawn then
-- add money display
vRPclient.setDiv(source,{"money",cfg.display_css,lang.money.display({vRP.getMoney(user_id)})})
end
end)
local function ch_give(player,choice)
-- get nearest player
local user_id = vRP.getUserId(player)
if user_id ~= nil then
vRPclient.getNearestPlayer(player,{10},function(nplayer)
if nplayer ~= nil then
local nuser_id = vRP.getUserId(nplayer)
if nuser_id ~= nil then
-- prompt number
vRP.prompt(player,lang.money.give.prompt(),"",function(player,amount)
local amount = parseInt(amount)
if amount > 0 and vRP.tryPayment(user_id,amount) then
vRP.giveMoney(nuser_id,amount)
vRPclient.notify(player,{lang.money.given({amount})})
vRPclient.notify(nplayer,{lang.money.received({amount})})
else
vRPclient.notify(player,{lang.money.not_enough()})
end
end)
else
vRPclient.notify(player,{lang.common.no_player_near()})
end
else
vRPclient.notify(player,{lang.common.no_player_near()})
end
end)
end
end
-- add player give money to main menu
vRP.registerMenuBuilder("main", function(add, data)
local user_id = vRP.getUserId(data.player)
if user_id ~= nil then
local choices = {}
choices[lang.money.give.title()] = {ch_give, lang.money.give.description()}
add(choices)
end
end)
|
Money cheat fix (untested).
|
Money cheat fix (untested).
|
Lua
|
mit
|
ImagicTheCat/vRP,ImagicTheCat/vRP
|
f86cbeca93d433e0d7a953a8c9a26349aad2bbb2
|
LUA/ak/data/AkSlotNamesParser.lua
|
LUA/ak/data/AkSlotNamesParser.lua
|
local SlotNamesParser = {}
local function isModuleAvailable(name)
if package.loaded[name] then
return true
else
for _, searcher in ipairs(package.searchers or package.loaders) do
local loader = searcher(name)
if type(loader) == 'function' then
package.preload[name] = loader
return true
end
end
return false
end
end
local namesToSlots = {}
local slotTable
local _
local SlotFuncs
function SlotNamesParser.updateSlotNames()
local function recursiveLookup(currentSlotTable, prefix, ...)
for k, v in pairs(currentSlotTable) do
local path = ... and { table.unpack(...) } or {}
table.insert(path, k)
local pathString = table.concat(path, ".")
if type(v) == 'table' then
-- print(pathString .. '> Lookup Table ' .. pathString)
recursiveLookup(v, prefix .. "--", path)
else
local slotNumber = SlotFuncs.lookupSlotNr(table.unpack(path))
-- print(pathString .. '> Found Slot: ' .. tostring(s))
namesToSlots[tostring(slotNumber)] = pathString
end
end
end
recursiveLookup(slotTable, '#', {})
end
if isModuleAvailable('SlotNames_BH2') then
slotTable, _, SlotFuncs = require('SlotNames_BH2')()
SlotNamesParser.updateSlotNames()
end
function SlotNamesParser.getSlotName(slot)
if (slotTable) then
return namesToSlots[tostring(slot)]
else
return '?'
end
end
return SlotNamesParser
|
local SlotNamesParser = {}
local function isModuleAvailable(name)
if package.loaded[name] then
return true
else
for _, searcher in ipairs(package.searchers or package.loaders) do
local loader = searcher(name)
if type(loader) == 'function' then
package.preload[name] = loader
return true
end
end
return false
end
end
local namesToSlots = {}
local slotTable
local _
local SlotFuncs
function SlotNamesParser.updateSlotNames()
if slotTable then
local function recursiveLookup(currentSlotTable, prefix, ...)
for k, v in pairs(currentSlotTable) do
local path = ... and { table.unpack(...) } or {}
table.insert(path, k)
local pathString = table.concat(path, ".")
if type(v) == 'table' then
-- print(pathString .. '> Lookup Table ' .. pathString)
recursiveLookup(v, prefix .. "--", path)
else
local slotNumber = SlotFuncs.lookupSlotNr(table.unpack(path))
-- print(pathString .. '> Found Slot: ' .. tostring(s))
namesToSlots[tostring(slotNumber)] = pathString
end
end
end
recursiveLookup(slotTable, '#', {})
end
end
if isModuleAvailable('SlotNames_BH2') then
slotTable, _, SlotFuncs = require('SlotNames_BH2')()
SlotNamesParser.updateSlotNames()
end
function SlotNamesParser.getSlotName(slot)
if slotTable then
return namesToSlots[tostring(slot)]
else
return '?'
end
end
return SlotNamesParser
|
fix: Fehler wenn BH2 Slotnames nicht vorhanden sind
|
fix: Fehler wenn BH2 Slotnames nicht vorhanden sind
|
Lua
|
mit
|
Andreas-Kreuz/ak-lua-skripte-fuer-eep,Andreas-Kreuz/ak-lua-skripte-fuer-eep
|
ed2b5e03e48ecfafc1d2b8e665c234e2f5ca0035
|
mod_ircd/mod_ircd.lua
|
mod_ircd/mod_ircd.lua
|
local irc_listener = { default_port = 6667, default_mode = "*l" };
local sessions = {};
local commands = {};
local nicks = {};
local st = require "util.stanza";
local conference_server = module:get_option("conference_server") or "conference.jabber.org";
local function irc_close_session(session)
session.conn:close();
end
function irc_listener.onincoming(conn, data)
local session = sessions[conn];
if not session then
session = { conn = conn, host = module.host, reset_stream = function () end,
close = irc_close_session, log = logger.init("irc"..(conn.id or "1")),
roster = {} };
sessions[conn] = session;
function session.data(data)
module:log("debug", "Received: %s", data);
local command, args = data:match("^%s*([^ ]+) *(.*)%s*$");
if not command then
module:log("warn", "Invalid command: %s", data);
return;
end
command = command:upper();
module:log("debug", "Received command: %s", command);
if commands[command] then
local ret = commands[command](session, args);
if ret then
session.send(ret.."\r\n");
end
end
end
function session.send(data)
module:log("debug", "sending: %s", data);
return conn:write(data.."\r\n");
end
end
if data then
session.data(data);
end
end
function irc_listener.ondisconnect(conn, error)
module:log("debug", "Client disconnected");
sessions[conn] = nil;
end
function commands.NICK(session, nick)
nick = nick:match("^[%w_]+");
if nicks[nick] then
session.send(":"..session.host.." 433 * The nickname "..nick.." is already in use");
return;
end
nicks[nick] = session;
session.nick = nick;
session.full_jid = nick.."@"..module.host.."/ircd";
session.type = "c2s";
module:log("debug", "Client bound to %s", session.full_jid);
session.send(":"..session.host.." 001 "..session.nick.." :Welcome to XMPP via the "..session.host.." gateway "..session.nick);
end
local joined_mucs = {};
function commands.JOIN(session, channel)
if not joined_mucs[channel] then
joined_mucs[channel] = { occupants = {}, sessions = {} };
end
joined_mucs[channel].sessions[session] = true;
local join_stanza = st.presence({ from = session.full_jid, to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick });
core_process_stanza(session, join_stanza);
session.send(":"..session.nick.." JOIN :"..channel);
session.send(":"..session.host.." 332 "..session.nick.." "..channel.." :Connection in progress...");
session.send(":"..session.host.." 353 "..session.nick.." = "..channel.." :"..session.nick);
session.send(":"..session.host.." 366 "..session.nick.." "..channel.." :End of /NAMES list.");
end
function commands.PART(session, channel)
local channel, part_message = channel:match("^([^:]+):?(.*)$");
channel = channel:match("^([%S]*)");
core_process_stanza(session, st.presence{ type = "unavailable", from = session.full_jid,
to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }:tag("status"):text(part_message));
session.send(":"..session.nick.." PART :"..channel);
end
function commands.PRIVMSG(session, message)
local who, message = message:match("^(%S+) :(.+)$");
if joined_mucs[who] then
core_process_stanza(session, st.message{to=who:gsub("^#", "").."@"..conference_server, type="groupchat"}:tag("body"):text(message));
end
end
function commands.PING(session, server)
session.send(":"..session.host..": PONG "..server);
end
function commands.WHO(session, channel)
if joined_mucs[channel] then
for nick in pairs(joined_mucs[channel].occupants) do
--n=MattJ 91.85.191.50 irc.freenode.net MattJ H :0 Matthew Wild
session.send(":"..session.host.." 352 "..session.nick.." "..channel.." "..nick.." "..nick.." "..session.host.." "..nick.." H :0 "..nick);
end
session.send(":"..session.host.." 315 "..session.nick.." "..channel.. " :End of /WHO list");
end
end
function commands.MODE(session, channel)
session.send(":"..session.host.." 324 "..session.nick.." "..channel.." +J");
end
--- Component (handle stanzas from the server for IRC clients)
function irc_component(origin, stanza)
local from, from_bare = stanza.attr.from, jid.bare(stanza.attr.from);
local from_node = "#"..jid.split(stanza.attr.from);
if joined_mucs[from_node] and from_bare == from then
-- From room itself
local joined_muc = joined_mucs[from_node];
if stanza.name == "message" then
local subject = stanza:get_child("subject");
if subject then
local subject_text = subject:get_text();
for session in pairs(joined_muc.sessions) do
session.send(":"..session.host.." 332 "..session.nick.." "..from_node.." :"..subject_text);
end
end
end
elseif joined_mucs[from_node] then
-- From room occupant
local joined_muc = joined_mucs[from_node];
local nick = select(3, jid.split(from)):gsub(" ", "_");
if stanza.name == "presence" then
local what;
if not stanza.attr.type then
if joined_muc.occupants[nick] then
return;
end
joined_muc.occupants[nick] = true;
what = "JOIN";
else
joined_muc.occupants[nick] = nil;
what = "PART";
end
for session in pairs(joined_muc.sessions) do
if nick ~= session.nick then
session.send(":"..nick.."!"..nick.." "..what.." :"..from_node);
end
end
elseif stanza.name == "message" then
local body = stanza:get_child("body");
local hasdelay = stanza:get_child("delay", "urn:xmpp:delay");
if body then
for session in pairs(joined_muc.sessions) do
if nick ~= session.nick or hasdelay then
session.send(":"..nick.." PRIVMSG "..from_node.." :"..body:get_text());
end
end
end
end
end
end
require "core.componentmanager".register_component(module.host, irc_component);
prosody.events.add_handler("server-stopping", function (shutdown)
module:log("debug", "Closing IRC connections prior to shutdown");
for channel, joined_muc in pairs(joined_mucs) do
for session in pairs(joined_muc.sessions) do
core_process_stanza(session,
st.presence{ type = "unavailable", from = session.full_jid,
to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }
:tag("status")
:text("Connection closed: Server is shutting down"..(shutdown.reason and (": "..shutdown.reason) or "")));
session:close();
end
end
end);
require "net.connlisteners".register("irc", irc_listener);
require "net.connlisteners".start("irc", { port = module:get_option("port") });
|
local irc_listener = { default_port = 6667, default_mode = "*l" };
local sessions = {};
local commands = {};
local nicks = {};
local st = require "util.stanza";
local conference_server = module:get_option("conference_server") or "conference.jabber.org";
local function irc_close_session(session)
session.conn:close();
end
function irc_listener.onincoming(conn, data)
local session = sessions[conn];
if not session then
session = { conn = conn, host = module.host, reset_stream = function () end,
close = irc_close_session, log = logger.init("irc"..(conn.id or "1")),
roster = {} };
sessions[conn] = session;
function session.data(data)
module:log("debug", "Received: %s", data);
local command, args = data:match("^%s*([^ ]+) *(.*)%s*$");
if not command then
module:log("warn", "Invalid command: %s", data);
return;
end
command = command:upper();
module:log("debug", "Received command: %s", command);
if commands[command] then
local ret = commands[command](session, args);
if ret then
session.send(ret.."\r\n");
end
end
end
function session.send(data)
module:log("debug", "sending: %s", data);
return conn:write(data.."\r\n");
end
end
if data then
session.data(data);
end
end
function irc_listener.ondisconnect(conn, error)
module:log("debug", "Client disconnected");
sessions[conn] = nil;
end
function commands.NICK(session, nick)
nick = nick:match("^[%w_]+");
if nicks[nick] then
session.send(":"..session.host.." 433 * The nickname "..nick.." is already in use");
return;
end
nicks[nick] = session;
session.nick = nick;
session.full_jid = nick.."@"..module.host.."/ircd";
session.type = "c2s";
module:log("debug", "Client bound to %s", session.full_jid);
session.send(":"..session.host.." 001 "..session.nick.." :Welcome to XMPP via the "..session.host.." gateway "..session.nick);
end
local joined_mucs = {};
function commands.JOIN(session, channel)
if not joined_mucs[channel] then
joined_mucs[channel] = { occupants = {}, sessions = {} };
end
joined_mucs[channel].sessions[session] = true;
local join_stanza = st.presence({ from = session.full_jid, to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick });
core_process_stanza(session, join_stanza);
session.send(":"..session.nick.." JOIN :"..channel);
session.send(":"..session.host.." 332 "..session.nick.." "..channel.." :Connection in progress...");
session.send(":"..session.host.." 353 "..session.nick.." = "..channel.." :"..session.nick);
session.send(":"..session.host.." 366 "..session.nick.." "..channel.." :End of /NAMES list.");
end
function commands.PART(session, channel)
local channel, part_message = channel:match("^([^:]+):?(.*)$");
channel = channel:match("^([%S]*)");
core_process_stanza(session, st.presence{ type = "unavailable", from = session.full_jid,
to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }:tag("status"):text(part_message));
session.send(":"..session.nick.." PART :"..channel);
end
function commands.PRIVMSG(session, message)
local who, message = message:match("^(%S+) :(.+)$");
if joined_mucs[who] then
core_process_stanza(session, st.message{to=who:gsub("^#", "").."@"..conference_server, type="groupchat"}:tag("body"):text(message));
end
end
function commands.PING(session, server)
session.send(":"..session.host..": PONG "..server);
end
function commands.WHO(session, channel)
if joined_mucs[channel] then
for nick in pairs(joined_mucs[channel].occupants) do
--n=MattJ 91.85.191.50 irc.freenode.net MattJ H :0 Matthew Wild
session.send(":"..session.host.." 352 "..session.nick.." "..channel.." "..nick.." "..nick.." "..session.host.." "..nick.." H :0 "..nick);
end
session.send(":"..session.host.." 315 "..session.nick.." "..channel.. " :End of /WHO list");
end
end
function commands.MODE(session, channel)
session.send(":"..session.host.." 324 "..session.nick.." "..channel.." +J");
end
--- Component (handle stanzas from the server for IRC clients)
function irc_component(origin, stanza)
local from, from_bare = stanza.attr.from, jid.bare(stanza.attr.from);
local from_node = "#"..jid.split(stanza.attr.from);
if joined_mucs[from_node] and from_bare == from then
-- From room itself
local joined_muc = joined_mucs[from_node];
if stanza.name == "message" then
local subject = stanza:get_child("subject");
if subject then
local subject_text = subject:get_text();
for session in pairs(joined_muc.sessions) do
session.send(":"..session.host.." 332 "..session.nick.." "..from_node.." :"..subject_text);
end
end
end
elseif joined_mucs[from_node] then
-- From room occupant
local joined_muc = joined_mucs[from_node];
local nick = select(3, jid.split(from)):gsub(" ", "_");
if stanza.name == "presence" then
local what;
if not stanza.attr.type then
if joined_muc.occupants[nick] then
return;
end
joined_muc.occupants[nick] = true;
what = "JOIN";
else
joined_muc.occupants[nick] = nil;
what = "PART";
end
for session in pairs(joined_muc.sessions) do
if nick ~= session.nick then
session.send(":"..nick.."!"..nick.." "..what.." :"..from_node);
end
end
elseif stanza.name == "message" then
local body = stanza:get_child("body");
body = body and body:get_text() or "";
local hasdelay = stanza:get_child("delay", "urn:xmpp:delay");
if body ~= "" then
for session in pairs(joined_muc.sessions) do
if nick ~= session.nick or hasdelay then
session.send(":"..nick.." PRIVMSG "..from_node.." :"..body);
end
end
end
end
end
end
require "core.componentmanager".register_component(module.host, irc_component);
prosody.events.add_handler("server-stopping", function (shutdown)
module:log("debug", "Closing IRC connections prior to shutdown");
for channel, joined_muc in pairs(joined_mucs) do
for session in pairs(joined_muc.sessions) do
core_process_stanza(session,
st.presence{ type = "unavailable", from = session.full_jid,
to = channel:gsub("^#", "").."@"..conference_server.."/"..session.nick }
:tag("status")
:text("Connection closed: Server is shutting down"..(shutdown.reason and (": "..shutdown.reason) or "")));
session:close();
end
end
end);
require "net.connlisteners".register("irc", irc_listener);
require "net.connlisteners".start("irc", { port = module:get_option("port") });
|
mod_ircd: Fixed handling of empty <body/> elements.
|
mod_ircd: Fixed handling of empty <body/> elements.
|
Lua
|
mit
|
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
|
ac7aca604f2dd7a780cec58502cd649547659db8
|
Statlist-unique.lua
|
Statlist-unique.lua
|
--[[
This module prints a list of all Pokémon
having unique base stat total
--]]
local u = {}
-- stylua: ignore start
local txt = require('Wikilib-strings')
local tab = require('Wikilib-tables')
local css = require('Css')
local ms = require('MiniSprite')
local gamesUtil = require('Wikilib-games')
local genUtil = require('Wikilib-gens')
local list = require('Wikilib-lists')
local oop = require('Wikilib-oop')
local statsUtil = require('Wikilib-stats')
local multigen = require('Wikilib-multigen')
local gendata = require("Gens-data")
local pokes = require('Poké-data')
-- stylua: ignore end
--[[
Mapreduce part of the module: returns a table
whose keys are Pokémon names and values their
base stat total, filtering only unique base
stat total values.
Even though makeList allows for some form of
filtering, it does not allow conditions to be
based on the whole collection, making a separate
function necessary.
--]]
local uniqueStatTotal = function(allStats, gen)
local pokesInGen = tab.filter(allStats, function(_, poke)
return not txt.parseInt(poke) and gamesUtil.isInGen(poke, gen)
end)
-- Mapping to base stat totals
local tots = tab.map(pokesInGen, function(pokeStats)
return statsUtil.statsSum(statsUtil.getStatsGen(pokeStats, gen))
end)
--[[
Filtering unique base stat totals only:
checks if there's not any base stat total
equal to the current one but of a different
Pokémon
--]]
return tab.filter(tots, function(tot, poke)
return not tab.any(tots, function(otherTot, otherPoke)
return tot == otherTot and poke ~= otherPoke
end)
end)
end
--[[
Class representing an entry for the unique stat total
list. By subclassing PokeSortableEntry it implements
all the interfaces needed for sortForm, sortNdex
and makeList in Wikilib/lists
--]]
local Entry = oop.makeClass(list.PokeSortableEntry)
--[[
Constructor: the first argument is a base stat total
and the second the name of the Pokémon having it.
Filtering requires checking other entries, and is
therefore not implemented here: hence, this constructor
never returns nil.
--]]
Entry.new = function(total, name)
local this = tab.merge(Entry.super.new(name), multigen.getGen(pokes[name]))
this.total = total
return setmetatable(this, Entry)
end
--[[
Wikicode for a list entry: shows Pokémon ndex,
mini sprite, name and base stats, plus total
and average.
--]]
Entry.__tostring = function(this)
return txt.interp(
[=[| class="hidden-xs" style="padding: 0.3ex 0.6ex" | ${ndex}
| style="padding: 0.3ex 0.6ex" | ${ms}
| style="padding: 0.3ex 0.6ex" | [[${name}|<span style="color: #000;">${name}</span>]]${form}
| style="padding: 0.3ex 0.6ex" | '''${total}''']=],
{
ndex = genUtil.ndexToString(this.ndex),
ms = ms.staticLua({
txt.tf(this.ndex or 0)
.. (this.formAbbr == "base" and "" or this.formAbbr or ""),
}),
name = this.name,
form = this.formsData and this.formsData.blacklinks[this.formAbbr]
or "",
total = this.total,
}
)
end
--[[
Wiki interface function: returns the list
of all Pokémon having unique base stat total
in the provided generation, which defaults
to the latest.
Examples:
Latest generation:
{{#invoke: Statlist/unique | statlistUnique }}
Specific generation:
{{#invoke: Statlist/unique | statlistUnique | 4 }}
--]]
u.statlistUnique = function(frame)
local gen = tonumber(frame.args[1]) or gendata.latest
return list.makeList({
source = uniqueStatTotal(require("PokéStats-data"), gen),
makeEntry = Entry,
header = txt.interp(
[=[{| class="sortable roundy-corners pull-center text-center white-rows" style="border-spacing: 0; padding: 0.3ex; ${bg};"
|-
! class="hidden-xs" style="padding-top: 0.8ex; padding-bottom: 0.8ex; padding-left: 0.8ex;" | [[Pokédex Nazionale|<span style="color: #000;">#</span>]]
! style="padding-top: 0.8ex; padding-bottom: 0.8ex; padding-left: 0.8ex;" |
! style="padding-top: 0.8ex; padding-bottom: 0.8ex; padding-left: 0.8ex;" | Pokémon
! style="padding-top: 0.8ex; padding-bottom: 0.8ex; padding-left: 0.8ex;" | Totale]=],
{ bg = css.horizGradLua({ type = "pcwiki" }) }
),
})
end
u.StatlistUnique = u.statlistUnique
return u
|
--[[
This module prints a list of all Pokémon
having unique base stat total
--]]
local u = {}
-- stylua: ignore start
local txt = require('Wikilib-strings')
local tab = require('Wikilib-tables')
local css = require('Css')
local ms = require('MiniSprite')
local gamesUtil = require('Wikilib-games')
local genUtil = require('Wikilib-gens')
local list = require('Wikilib-lists')
local oop = require('Wikilib-oop')
local statsUtil = require('Wikilib-stats')
local multigen = require('Wikilib-multigen')
local gendata = require("Gens-data")
local pokes = require('Poké-data')
local pokestats = require('PokéStats-data')
-- stylua: ignore end
--[[
Mapreduce part of the module: returns a table
whose keys are Pokémon names and values their
base stat total, filtering only unique base
stat total values.
Even though makeList allows for some form of
filtering, it does not allow conditions to be
based on the whole collection, making a separate
function necessary.
--]]
local uniqueStatTotal = function(allStats, gen)
local pokesInGen = tab.filter(allStats, function(_, poke)
return not txt.parseInt(poke) and gamesUtil.isInGen(poke, gen)
end)
-- Mapping to base stat totals
local tots = tab.map(pokesInGen, function(pokeStats)
return statsUtil.statsSum(statsUtil.getStatsGen(pokeStats, gen))
end)
--[[
Filtering unique base stat totals only:
checks if there's not any base stat total
equal to the current one but of a different
Pokémon
--]]
return tab.filter(tots, function(tot, poke)
return not tab.any(tots, function(otherTot, otherPoke)
return tot == otherTot and poke ~= otherPoke
end)
end)
end
--[[
Class representing an entry for the unique stat total
list. By subclassing PokeSortableEntry it implements
all the interfaces needed for sortForm, sortNdex
and makeList in Wikilib/lists
--]]
local Entry = oop.makeClass(list.PokeSortableEntry)
--[[
Constructor: the first argument is a base stat total
and the second the name of the Pokémon having it.
Filtering requires checking other entries, and is
therefore not implemented here: hence, this constructor
never returns nil.
--]]
Entry.new = function(total, name)
local this = tab.merge(Entry.super.new(name), multigen.getGen(pokes[name]))
this.total = total
return setmetatable(this, Entry)
end
--[[
Wikicode for a list entry: shows Pokémon ndex,
mini sprite, name and base stats, plus total
and average.
--]]
Entry.__tostring = function(this)
return txt.interp(
[=[| class="hidden-xs" style="padding: 0.3ex 0.6ex" | ${ndex}
| style="padding: 0.3ex 0.6ex" | ${ms}
| style="padding: 0.3ex 0.6ex" | [[${name}|<span style="color: #000;">${name}</span>]]${form}
| style="padding: 0.3ex 0.6ex" | '''${total}''']=],
{
ndex = genUtil.ndexToString(this.ndex),
ms = ms.staticLua({
txt.tf(this.ndex or 0)
.. (this.formAbbr == "base" and "" or this.formAbbr or ""),
}),
name = this.name,
form = this.formsData and this.formsData.blacklinks[this.formAbbr]
or "",
total = this.total,
}
)
end
--[[
Wiki interface function: returns the list
of all Pokémon having unique base stat total
in the provided generation, which defaults
to the latest.
Examples:
Latest generation:
{{#invoke: Statlist/unique | statlistUnique }}
Specific generation:
{{#invoke: Statlist/unique | statlistUnique | 4 }}
--]]
u.statlistUnique = function(frame)
local gen = tonumber(frame.args[1]) or gendata.latest
return list.makeList({
source = uniqueStatTotal(pokestats, gen),
makeEntry = Entry,
header = txt.interp(
[=[{| class="sortable roundy-corners pull-center text-center white-rows" style="border-spacing: 0; padding: 0.3ex; ${bg};"
|-
! class="hidden-xs" style="padding-top: 0.8ex; padding-bottom: 0.8ex; padding-left: 0.8ex;" | [[Pokédex Nazionale|<span style="color: #000;">#</span>]]
! style="padding-top: 0.8ex; padding-bottom: 0.8ex; padding-left: 0.8ex;" |
! style="padding-top: 0.8ex; padding-bottom: 0.8ex; padding-left: 0.8ex;" | Pokémon
! style="padding-top: 0.8ex; padding-bottom: 0.8ex; padding-left: 0.8ex;" | Totale]=],
{ bg = css.horizGradLua({ type = "pcwiki" }) }
),
})
end
u.StatlistUnique = u.statlistUnique
return u
|
Fixing require in Statlist-unique
|
Fixing require in Statlist-unique
|
Lua
|
cc0-1.0
|
pokemoncentral/wiki-lua-modules
|
4d0d2d4dea9d38b4d54e3ceab18a4aa99511acfa
|
cookbooks/neovim/files/nvim/lua/plugins.lua
|
cookbooks/neovim/files/nvim/lua/plugins.lua
|
-- Packer.nvim bootstrapping
-- see https://github.com/wbthomason/packer.nvim#bootstrapping
-- TODO: Move to ~/.config/nvim/lua/init.lua
local execute = vim.api.nvim_command
local fn = vim.fn
local install_path = fn.stdpath('data')..'/site/pack/packer/start/packer.nvim'
if fn.empty(fn.glob(install_path)) > 0 then
fn.system({'git', 'clone', 'https://github.com/wbthomason/packer.nvim', install_path})
execute 'packadd packer.nvim'
end
-- Plugins
local packer = require('packer')
packer.init {
display = {
open_fn = require('packer.util').float,
},
}
return packer.startup(function(use)
-- lua plugins
use {
{ 'wbthomason/packer.nvim' },
{
'neovim/nvim-lspconfig',
requires = {
'nvim-lua/lsp-status.nvim',
},
config = function()
require('lsp')
end
},
{
'hrsh7th/nvim-compe',
setup = function()
-- see https://github.com/hrsh7th/nvim-compe#prerequisite
vim.o.completeopt = 'menuone,noselect'
end,
config = function()
require('compe').setup {
enabled = true,
autocomplete = true,
source = {
path = true,
buffer = true,
calc = true,
nvim_lsp = true,
nvim_lua = true,
},
}
end,
},
{
'folke/which-key.nvim',
-- TODO: Lazy loading
-- cmd = { 'WhichKey' },
-- keys = { '<leader>', '<Space>' },
config = function()
local wk = require('which-key')
wk.register({
G = {
name = '+git',
g = { '<cmd>Telescope ghq list cwd=~ theme=get_dropdown<CR>', 'List ghq repository' },
o = { '<cmd>OpenGithubFile<CR>', 'Open GitHub file' },
},
l = {
name = '+lsp',
r = { vim.lsp.buf.references, 'references' },
d = { '<cmd>LspTroubleToggle<CR>', 'diagnostics' },
},
f = { '<cmd>Telescope find_files theme=get_dropdown<CR>', 'find_files' },
b = { '<cmd>Telescope buffers theme=get_dropdown<CR>', 'buffers' },
g = { '<cmd>Telescope live_grep theme=get_dropdown<CR>', 'live_grep' },
p = { '<cmd>BufferLineCyclePrev<CR>', 'buffer prev' },
n = { '<cmd>BufferLineCycleNext<CR>', 'buffer next' },
},
{ prefix = '<leader>' })
end
},
{
'lewis6991/gitsigns.nvim',
requires = { 'nvim-lua/plenary.nvim' },
config = function()
require('gitsigns').setup {
signs = {
-- default: text = '_'
delete = { hl = 'GitSignsDelete', text = '│', numhl='GitSignsDeleteNr', linehl='GitSignsDeleteLn' },
},
}
end
},
{
'hoob3rt/lualine.nvim',
requires = {
'kyazdani42/nvim-web-devicons',
'nvim-lua/lsp-status.nvim',
},
config = function()
local lsp_status = require('lsp-status')
require('lualine').setup{
options = { theme = 'iceberg_dark' },
sections = {
lualine_x = { lsp_status.status, 'encoding', 'fileformat', 'filetype' },
},
}
end
},
{
'folke/lsp-trouble.nvim',
requires = { 'kyazdani42/nvim-web-devicons' },
config = function()
require('trouble').setup {
auto_open = true, -- not working
auto_close = true,
}
end
},
{
'windwp/nvim-autopairs',
config = function()
require('nvim-autopairs').setup()
end,
},
{
'nvim-telescope/telescope.nvim',
cmd = { 'Telescope' },
requires = {
'nvim-lua/popup.nvim',
'nvim-lua/plenary.nvim',
'nvim-telescope/telescope-ghq.nvim',
},
config = function()
local telescope = require('telescope')
telescope.load_extension('ghq')
telescope.setup {
defaults = {
mappings = {
i = {
-- see https://github.com/nvim-telescope/telescope.nvim/issues/499
["<C-u>"] = false,
},
},
},
}
end,
},
{
'akinsho/nvim-bufferline.lua',
requires = {
'kyazdani42/nvim-web-devicons',
},
config = function()
require('bufferline').setup {
options = {
separator_style = 'thin',
diagnostics = "nvim_lsp",
},
}
end,
},
}
-- vimscript plugins
use {
{ 'cocopon/iceberg.vim' },
{ 'tpope/vim-fugitive' },
{ 'tpope/vim-endwise' },
{ 'tpope/vim-surround' },
{ 'hashivim/vim-terraform', ft = 'terraform' },
{ 'tmux-plugins/vim-tmux', ft = 'tmux' },
{ 'cespare/vim-toml' },
{ 'dag/vim-fish' },
{
'tyru/caw.vim',
keys = { '<C-k>' },
config = function()
vim.api.nvim_set_keymap('', '<C-k>', '<Plug>(caw:hatpos:toggle)', {})
end
},
{
'scrooloose/nerdtree',
cmd = { 'NERDTreeFind', 'NERDTreeToggle' },
keys = { '<F2>', '<F3>' },
setup = function()
vim.g.NERDTreeChDirMode = 0
vim.g.NERDTreeShowHidden = 1
vim.g.NERDTreeWinSize = 30
end,
config = function()
vim.api.nvim_set_keymap('n', '<F2>', ':NERDTreeFind<CR>', { noremap = true, silent = true })
vim.api.nvim_set_keymap('n', '<F3>', ':NERDTreeToggle<CR>', { noremap = true, silent = true })
end
},
{
'tyru/open-browser-github.vim',
requires = { 'tyru/open-browser.vim', opt = true },
cmd = {
'OpenGithubFile',
'OpenGithubIssue',
'OpenGithubPullReq',
'OpenGithubProject',
'OpenGithubCommit'
},
setup = function()
vim.g.openbrowser_github_url_exists_check = 'ignore'
end
},
}
end)
|
-- Packer.nvim bootstrapping
-- see https://github.com/wbthomason/packer.nvim#bootstrapping
-- TODO: Move to ~/.config/nvim/lua/init.lua
local execute = vim.api.nvim_command
local fn = vim.fn
local install_path = fn.stdpath('data')..'/site/pack/packer/start/packer.nvim'
if fn.empty(fn.glob(install_path)) > 0 then
fn.system({'git', 'clone', 'https://github.com/wbthomason/packer.nvim', install_path})
execute 'packadd packer.nvim'
end
-- Plugins
local packer = require('packer')
packer.init {
display = {
open_fn = require('packer.util').float,
},
}
return packer.startup(function(use)
-- lua plugins
use {
{ 'wbthomason/packer.nvim' },
{
'neovim/nvim-lspconfig',
requires = {
'nvim-lua/lsp-status.nvim',
},
config = function()
require('lsp')
end
},
{
'hrsh7th/nvim-compe',
setup = function()
-- see https://github.com/hrsh7th/nvim-compe#prerequisite
vim.o.completeopt = 'menuone,noselect'
end,
config = function()
require('compe').setup {
enabled = true,
autocomplete = true,
source = {
path = true,
buffer = true,
calc = true,
nvim_lsp = true,
nvim_lua = true,
},
}
end,
},
{
'folke/which-key.nvim',
-- TODO: Lazy loading
-- cmd = { 'WhichKey' },
-- keys = { '<leader>', '<Space>' },
config = function()
local wk = require('which-key')
wk.register({
G = {
name = '+git',
g = { '<cmd>Telescope ghq list cwd=~ theme=get_dropdown<CR>', 'List ghq repository' },
o = { '<cmd>OpenGithubFile<CR>', 'Open GitHub file' },
},
l = {
name = '+lsp',
r = { vim.lsp.buf.references, 'references' },
d = { '<cmd>LspTroubleToggle<CR>', 'diagnostics' },
},
f = { '<cmd>Telescope find_files theme=get_dropdown<CR>', 'find_files' },
b = { '<cmd>Telescope buffers theme=get_dropdown<CR>', 'buffers' },
g = { '<cmd>Telescope live_grep theme=get_dropdown<CR>', 'live_grep' },
p = { '<cmd>BufferLineCyclePrev<CR>', 'buffer prev' },
n = { '<cmd>BufferLineCycleNext<CR>', 'buffer next' },
P = {
name = '+packer',
u = { '<cmd>PackerUpdate<CR>', 'update' },
s = { '<cmd>PackerSync<CR>', 'sync' },
i = { '<cmd>PackerInstall<CR>', 'install' },
c = { '<cmd>PackerCompile<CR>', 'compile' },
},
},
{ prefix = '<leader>' })
end
},
{
'lewis6991/gitsigns.nvim',
requires = { 'nvim-lua/plenary.nvim' },
config = function()
require('gitsigns').setup {
signs = {
-- default: text = '_'
delete = { hl = 'GitSignsDelete', text = '│', numhl='GitSignsDeleteNr', linehl='GitSignsDeleteLn' },
},
}
end
},
{
'hoob3rt/lualine.nvim',
requires = {
'kyazdani42/nvim-web-devicons',
'nvim-lua/lsp-status.nvim',
},
config = function()
local lsp_status = require('lsp-status')
require('lualine').setup{
options = { theme = 'iceberg_dark' },
sections = {
lualine_x = { lsp_status.status, 'encoding', 'fileformat', 'filetype' },
},
}
end
},
{
'folke/lsp-trouble.nvim',
requires = { 'kyazdani42/nvim-web-devicons' },
config = function()
require('trouble').setup {
auto_open = true, -- not working
auto_close = true,
}
end
},
{
'windwp/nvim-autopairs',
config = function()
require('nvim-autopairs').setup()
end,
},
{
'nvim-telescope/telescope.nvim',
cmd = { 'Telescope' },
requires = {
'nvim-lua/popup.nvim',
'nvim-lua/plenary.nvim',
'nvim-telescope/telescope-ghq.nvim',
},
config = function()
local telescope = require('telescope')
telescope.load_extension('ghq')
telescope.setup {
defaults = {
mappings = {
i = {
-- see https://github.com/nvim-telescope/telescope.nvim/issues/499
["<C-u>"] = false,
},
},
},
}
end,
},
{
'akinsho/nvim-bufferline.lua',
requires = {
'kyazdani42/nvim-web-devicons',
},
config = function()
require('bufferline').setup {
options = {
separator_style = 'thin',
diagnostics = "nvim_lsp",
},
}
end,
},
}
-- vimscript plugins
use {
{ 'cocopon/iceberg.vim' },
{ 'tpope/vim-fugitive' },
{ 'tpope/vim-endwise' },
{ 'tpope/vim-surround' },
{ 'hashivim/vim-terraform', ft = 'terraform' },
{ 'tmux-plugins/vim-tmux', ft = 'tmux' },
{ 'cespare/vim-toml' },
{ 'dag/vim-fish' },
{
'tyru/caw.vim',
keys = { '<C-k>' },
config = function()
vim.api.nvim_set_keymap('', '<C-k>', '<Plug>(caw:hatpos:toggle)', {})
end
},
{
'scrooloose/nerdtree',
cmd = { 'NERDTreeFind', 'NERDTreeToggle' },
keys = { '<F2>', '<F3>' },
setup = function()
vim.g.NERDTreeChDirMode = 0
vim.g.NERDTreeShowHidden = 1
vim.g.NERDTreeWinSize = 30
end,
config = function()
vim.api.nvim_set_keymap('n', '<F2>', ':NERDTreeFind<CR>', { noremap = true, silent = true })
vim.api.nvim_set_keymap('n', '<F3>', ':NERDTreeToggle<CR>', { noremap = true, silent = true })
end
},
{
'tyru/open-browser-github.vim',
requires = { 'tyru/open-browser.vim', opt = true },
cmd = {
'OpenGithubFile',
'OpenGithubIssue',
'OpenGithubPullReq',
'OpenGithubProject',
'OpenGithubCommit'
},
setup = function()
vim.g.openbrowser_github_url_exists_check = 'ignore'
end
},
}
end)
|
Add which-key.nvim prefix for packer.nvim
|
Add which-key.nvim prefix for packer.nvim
|
Lua
|
mit
|
tsub/dotfiles,tsub/dotfiles,tsub/dotfiles,tsub/dotfiles,tsub/dotfiles
|
0f189af4eb027ae2df788d2e43a2229546fbe5cd
|
kong/resty/ctx.lua
|
kong/resty/ctx.lua
|
-- A module for sharing ngx.ctx between subrequests.
-- Original work by Alex Zhang (openresty/lua-nginx-module/issues/1057)
-- updated by 3scale/apicast.
--
-- Copyright (c) 2016 3scale Inc.
-- Licensed under the Apache License, Version 2.0.
-- License text: See LICENSE
--
-- Modifications by Kong Inc.
-- * updated module functions signatures
-- * made module function idempotent
-- * replaced thrown errors with warn logs
local ffi = require "ffi"
local base = require "resty.core.base"
local C = ffi.C
local ngx = ngx
local tonumber = tonumber
local registry = debug.getregistry()
local FFI_NO_REQ_CTX = base.FFI_NO_REQ_CTX
local _M = {}
function _M.stash_ref(ctx)
local r = base.get_request()
if not r then
ngx.log(ngx.WARN, "could not stash ngx.ctx ref: no request found")
return
end
do
local ctx_ref = ngx.var.ctx_ref
if not ctx_ref or ctx_ref ~= "" then
return
end
if not ctx then
local _ = ngx.ctx -- load context if not previously loaded
end
end
local ctx_ref = C.ngx_http_lua_ffi_get_ctx_ref(r)
if ctx_ref == FFI_NO_REQ_CTX then
ngx.log(ngx.WARN, "could not stash ngx.ctx ref: no ctx found")
return
end
ngx.var.ctx_ref = ctx_ref
end
function _M.apply_ref()
local r = base.get_request()
if not r then
ngx.log(ngx.WARN, "could not apply ngx.ctx: no request found")
return
end
local ctx_ref = ngx.var.ctx_ref
if not ctx_ref or ctx_ref == "" then
return
end
ctx_ref = tonumber(ctx_ref)
if not ctx_ref then
return
end
local orig_ctx = registry.ngx_lua_ctx_tables[ctx_ref]
if not orig_ctx then
ngx.log(ngx.WARN, "could not apply ngx.ctx: no ctx found")
return
end
ngx.ctx = orig_ctx
ngx.var.ctx_ref = ""
end
return _M
|
-- A module for sharing ngx.ctx between subrequests.
-- Original work by Alex Zhang (openresty/lua-nginx-module/issues/1057)
-- updated by 3scale/apicast.
--
-- Copyright (c) 2016 3scale Inc.
-- Licensed under the Apache License, Version 2.0.
-- License text: See LICENSE
--
-- Modifications by Kong Inc.
-- * updated module functions signatures
-- * made module function idempotent
-- * replaced thrown errors with warn logs
-- * allow passing of context
-- * updated to work with new 1.19.x apis
local ffi = require "ffi"
local base = require "resty.core.base"
local C = ffi.C
local ngx = ngx
local tonumber = tonumber
local registry = debug.getregistry()
local subsystem = ngx.config.subsystem
local ngx_lua_ffi_get_ctx_ref
if subsystem == "http" then
ngx_lua_ffi_get_ctx_ref = C.ngx_http_lua_ffi_get_ctx_ref
elseif subsystem == "stream" then
ngx_lua_ffi_get_ctx_ref = C.ngx_stream_lua_ffi_get_ctx_ref
end
local in_ssl_phase = ffi.new("int[1]")
local ssl_ctx_ref = ffi.new("int[1]")
local FFI_NO_REQ_CTX = base.FFI_NO_REQ_CTX
local _M = {}
function _M.stash_ref(ctx)
local r = base.get_request()
if not r then
ngx.log(ngx.WARN, "could not stash ngx.ctx ref: no request found")
return
end
do
local ctx_ref = ngx.var.ctx_ref
if not ctx_ref or ctx_ref ~= "" then
return
end
if not ctx then
local _ = ngx.ctx -- load context if not previously loaded
end
end
local ctx_ref = ngx_lua_ffi_get_ctx_ref(r, in_ssl_phase, ssl_ctx_ref)
if ctx_ref == FFI_NO_REQ_CTX then
ngx.log(ngx.WARN, "could not stash ngx.ctx ref: no ctx found")
return
end
ngx.var.ctx_ref = ctx_ref
end
function _M.apply_ref()
local r = base.get_request()
if not r then
ngx.log(ngx.WARN, "could not apply ngx.ctx: no request found")
return
end
local ctx_ref = ngx.var.ctx_ref
if not ctx_ref or ctx_ref == "" then
return
end
ctx_ref = tonumber(ctx_ref)
if not ctx_ref then
return
end
local orig_ctx = registry.ngx_lua_ctx_tables[ctx_ref]
if not orig_ctx then
ngx.log(ngx.WARN, "could not apply ngx.ctx: no ctx found")
return
end
ngx.ctx = orig_ctx
ngx.var.ctx_ref = ""
end
return _M
|
fix(core) resty.ctx to use new api in openresty 1.19.x.x
|
fix(core) resty.ctx to use new api in openresty 1.19.x.x
|
Lua
|
apache-2.0
|
Kong/kong,Kong/kong,Kong/kong
|
861b32ea331641771474ebcd592b2a8639b8b310
|
util/datamanager.lua
|
util/datamanager.lua
|
local format = string.format;
local setmetatable, type = setmetatable, type;
local pairs = pairs;
local char = string.char;
local loadfile, setfenv, pcall = loadfile, setfenv, pcall;
local log = log;
local io_open = io.open;
local tostring = tostring;
local error = error;
module "datamanager"
---- utils -----
local encode, decode;
local log = function (type, msg) return log(type, "datamanager", msg); end
do
local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end });
decode = function (s)
return s and (s:gsub("+", " "):gsub("%%([a-fA-F0-9][a-fA-F0-9])", urlcodes));
end
encode = function (s)
return s and (s:gsub("%W", function (c) return format("%%%x", c:byte()); end));
end
end
local function basicSerialize (o)
if type(o) == "number" or type(o) == "boolean" then
return tostring(o)
else -- assume it is a string
return format("%q", tostring(o))
end
end
local function simplesave (f, o)
if type(o) == "number" then
f:write(o)
elseif type(o) == "string" then
f:write(format("%q", o))
elseif type(o) == "table" then
f:write("{\n")
for k,v in pairs(o) do
f:write(" [", basicSerialize(k), "] = ")
simplesave(f, v)
f:write(",\n")
end
f:write("}\n")
elseif type(o) == "boolean" then
f:write(o and "true" or "false");
else
error("cannot serialize a " .. type(o))
end
end
------- API -------------
function getpath(username, host, datastore)
if username then
return format("data/%s/%s/%s.dat", encode(host), datastore, encode(username));
elseif host then
return format("data/%s/%s.dat", encode(host), datastore);
else
return format("data/%s.dat", datastore);
end
end
function load(username, host, datastore)
local data, ret = loadfile(getpath(username, host, datastore));
if not data then
log("warn", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..(username or nil).."@"..(host or nil));
return nil;
end
setfenv(data, {});
local success, ret = pcall(data);
if not success then
log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..(username or nil).."@"..(host or nil));
return nil;
end
return ret;
end
function store(username, host, datastore, data)
local f, msg = io_open(getpath(username, host, datastore), "w+");
if not f then
log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or nil).."@"..(host or nil));
return nil;
end
f:write("return ");
simplesave(f, data);
f:close();
return true;
end
return _M;
|
local format = string.format;
local setmetatable, type = setmetatable, type;
local pairs = pairs;
local char = string.char;
local loadfile, setfenv, pcall = loadfile, setfenv, pcall;
local log = log;
local io_open = io.open;
local tostring = tostring;
local error = error;
local indent = function(f, i)
for n = 1, i do
f:write("\t");
end
end
module "datamanager"
---- utils -----
local encode, decode;
local log = function (type, msg) return log(type, "datamanager", msg); end
do
local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end });
decode = function (s)
return s and (s:gsub("+", " "):gsub("%%([a-fA-F0-9][a-fA-F0-9])", urlcodes));
end
encode = function (s)
return s and (s:gsub("%W", function (c) return format("%%%x", c:byte()); end));
end
end
local function basicSerialize (o)
if type(o) == "number" or type(o) == "boolean" then
return tostring(o);
else -- assume it is a string -- FIXME make sure it's a string. throw an error otherwise.
return (format("%q", tostring(o)):gsub("\\\n", "\\n"));
end
end
local function simplesave (f, o, ind)
if type(o) == "number" then
f:write(o)
elseif type(o) == "string" then
f:write((format("%q", o):gsub("\\\n", "\\n")))
elseif type(o) == "table" then
f:write("{\n")
for k,v in pairs(o) do
indent(f, ind);
f:write("[", basicSerialize(k), "] = ")
simplesave(f, v, ind+1)
f:write(",\n")
end
indent(f, ind-1);
f:write("}")
elseif type(o) == "boolean" then
f:write(o and "true" or "false");
else
error("cannot serialize a " .. type(o))
end
end
------- API -------------
function getpath(username, host, datastore)
if username then
return format("data/%s/%s/%s.dat", encode(host), datastore, encode(username));
elseif host then
return format("data/%s/%s.dat", encode(host), datastore);
else
return format("data/%s.dat", datastore);
end
end
function load(username, host, datastore)
local data, ret = loadfile(getpath(username, host, datastore));
if not data then
log("warn", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
return nil;
end
setfenv(data, {});
local success, ret = pcall(data);
if not success then
log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
return nil;
end
return ret;
end
function store(username, host, datastore, data)
local f, msg = io_open(getpath(username, host, datastore), "w+");
if not f then
log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
return nil;
end
f:write("return ");
simplesave(f, data, 1);
f:close();
return true;
end
return _M;
|
Datamanager Fixes and improvements - Pretty printing - Fixed bug causing a nil concatenation error when saving a datastore for nil user or host
|
Datamanager Fixes and improvements
- Pretty printing
- Fixed bug causing a nil concatenation error when saving a datastore for nil user or host
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
8eaabb460ed9c9c01ddbe97ffc29a9cb6e1e81ec
|
util/datamanager.lua
|
util/datamanager.lua
|
local format = string.format;
local setmetatable, type = setmetatable, type;
local pairs, ipairs = pairs, ipairs;
local char = string.char;
local loadfile, setfenv, pcall = loadfile, setfenv, pcall;
local log = log;
local io_open = io.open;
local os_remove = os.remove;
local tostring, tonumber = tostring, tonumber;
local error = error;
local next = next;
local t_insert = table.insert;
local indent = function(f, i)
for n = 1, i do
f:write("\t");
end
end
local data_path = "data";
module "datamanager"
---- utils -----
local encode, decode;
local log = function (type, msg) return log(type, "datamanager", msg); end
do
local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end });
decode = function (s)
return s and (s:gsub("+", " "):gsub("%%([a-fA-F0-9][a-fA-F0-9])", urlcodes));
end
encode = function (s)
return s and (s:gsub("%W", function (c) return format("%%%x", c:byte()); end));
end
end
local function basicSerialize (o)
if type(o) == "number" or type(o) == "boolean" then
return tostring(o);
else -- assume it is a string -- FIXME make sure it's a string. throw an error otherwise.
return (format("%q", tostring(o)):gsub("\\\n", "\\n"));
end
end
local function simplesave (f, o, ind)
if type(o) == "number" then
f:write(o)
elseif type(o) == "string" then
f:write((format("%q", o):gsub("\\\n", "\\n")))
elseif type(o) == "table" then
f:write("{\n")
for k,v in pairs(o) do
indent(f, ind);
f:write("[", basicSerialize(k), "] = ")
simplesave(f, v, ind+1)
f:write(",\n")
end
indent(f, ind-1);
f:write("}")
elseif type(o) == "boolean" then
f:write(o and "true" or "false");
else
error("cannot serialize a " .. type(o))
end
end
------- API -------------
function set_data_path(path)
data_path = path;
end
function getpath(username, host, datastore, ext)
ext = ext or "dat";
if username then
return format("%s/%s/%s/%s.%s", data_path, encode(host), datastore, encode(username), ext);
elseif host then
return format("%s/%s/%s.%s", data_path, encode(host), datastore, ext);
else
return format("%s/%s.%s", data_path, datastore, ext);
end
end
function load(username, host, datastore)
local data, ret = loadfile(getpath(username, host, datastore));
if not data then
log("warn", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
return nil;
end
setfenv(data, {});
local success, ret = pcall(data);
if not success then
log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
return nil;
end
return ret;
end
function store(username, host, datastore, data)
if not data then
data = {};
end
-- save the datastore
local f, msg = io_open(getpath(username, host, datastore), "w+");
if not f then
log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
return;
end
f:write("return ");
simplesave(f, data, 1);
f:close();
if not next(data) then -- try to delete empty datastore
os_remove(getpath(username, host, datastore));
end
-- we write data even when we are deleting because lua doesn't have a
-- platform independent way of checking for non-exisitng files
return true;
end
function list_append(username, host, datastore, data)
if not data then return; end
-- save the datastore
local f, msg = io_open(getpath(username, host, datastore, "list"), "a+");
if not f then
log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
return;
end
f:write("item(");
simplesave(f, data, 1);
f:write(");\n");
f:close();
return true;
end
function list_store(username, host, datastore, data)
if not data then
data = {};
end
-- save the datastore
local f, msg = io_open(getpath(username, host, datastore, "list"), "w+");
if not f then
log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
return;
end
for _, d in ipairs(data) do
f:write("item(");
simplesave(f, d, 1);
f:write(");\n");
end
f:close();
if not next(data) then -- try to delete empty datastore
os_remove(getpath(username, host, datastore, "list"));
end
-- we write data even when we are deleting because lua doesn't have a
-- platform independent way of checking for non-exisitng files
return true;
end
function list_load(username, host, datastore)
local data, ret = loadfile(getpath(username, host, datastore, "list"));
if not data then
log("warn", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
return nil;
end
local items = {};
setfenv(data, {item = function(i) t_insert(items, i); end});
local success, ret = pcall(data);
if not success then
log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
return nil;
end
return items;
end
return _M;
|
local format = string.format;
local setmetatable, type = setmetatable, type;
local pairs, ipairs = pairs, ipairs;
local char = string.char;
local loadfile, setfenv, pcall = loadfile, setfenv, pcall;
local log = require "util.logger".init("datamanager");
local io_open = io.open;
local os_remove = os.remove;
local tostring, tonumber = tostring, tonumber;
local error = error;
local next = next;
local t_insert = table.insert;
local indent = function(f, i)
for n = 1, i do
f:write("\t");
end
end
local data_path = "data";
module "datamanager"
---- utils -----
local encode, decode;
do
local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end });
decode = function (s)
return s and (s:gsub("+", " "):gsub("%%([a-fA-F0-9][a-fA-F0-9])", urlcodes));
end
encode = function (s)
return s and (s:gsub("%W", function (c) return format("%%%x", c:byte()); end));
end
end
local function basicSerialize (o)
if type(o) == "number" or type(o) == "boolean" then
return tostring(o);
else -- assume it is a string -- FIXME make sure it's a string. throw an error otherwise.
return (format("%q", tostring(o)):gsub("\\\n", "\\n"));
end
end
local function simplesave (f, o, ind)
if type(o) == "number" then
f:write(o)
elseif type(o) == "string" then
f:write((format("%q", o):gsub("\\\n", "\\n")))
elseif type(o) == "table" then
f:write("{\n")
for k,v in pairs(o) do
indent(f, ind);
f:write("[", basicSerialize(k), "] = ")
simplesave(f, v, ind+1)
f:write(",\n")
end
indent(f, ind-1);
f:write("}")
elseif type(o) == "boolean" then
f:write(o and "true" or "false");
else
error("cannot serialize a " .. type(o))
end
end
------- API -------------
function set_data_path(path)
data_path = path;
end
function getpath(username, host, datastore, ext)
ext = ext or "dat";
if username then
return format("%s/%s/%s/%s.%s", data_path, encode(host), datastore, encode(username), ext);
elseif host then
return format("%s/%s/%s.%s", data_path, encode(host), datastore, ext);
else
return format("%s/%s.%s", data_path, datastore, ext);
end
end
function load(username, host, datastore)
local data, ret = loadfile(getpath(username, host, datastore));
if not data then
log("warn", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
return nil;
end
setfenv(data, {});
local success, ret = pcall(data);
if not success then
log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
return nil;
end
return ret;
end
function store(username, host, datastore, data)
if not data then
data = {};
end
-- save the datastore
local f, msg = io_open(getpath(username, host, datastore), "w+");
if not f then
log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
return;
end
f:write("return ");
simplesave(f, data, 1);
f:close();
if not next(data) then -- try to delete empty datastore
os_remove(getpath(username, host, datastore));
end
-- we write data even when we are deleting because lua doesn't have a
-- platform independent way of checking for non-exisitng files
return true;
end
function list_append(username, host, datastore, data)
if not data then return; end
-- save the datastore
local f, msg = io_open(getpath(username, host, datastore, "list"), "a+");
if not f then
log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
return;
end
f:write("item(");
simplesave(f, data, 1);
f:write(");\n");
f:close();
return true;
end
function list_store(username, host, datastore, data)
if not data then
data = {};
end
-- save the datastore
local f, msg = io_open(getpath(username, host, datastore, "list"), "w+");
if not f then
log("error", "Unable to write to "..datastore.." storage ('"..msg.."') for user: "..(username or "nil").."@"..(host or "nil"));
return;
end
for _, d in ipairs(data) do
f:write("item(");
simplesave(f, d, 1);
f:write(");\n");
end
f:close();
if not next(data) then -- try to delete empty datastore
os_remove(getpath(username, host, datastore, "list"));
end
-- we write data even when we are deleting because lua doesn't have a
-- platform independent way of checking for non-exisitng files
return true;
end
function list_load(username, host, datastore)
local data, ret = loadfile(getpath(username, host, datastore, "list"));
if not data then
log("warn", "Failed to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
return nil;
end
local items = {};
setfenv(data, {item = function(i) t_insert(items, i); end});
local success, ret = pcall(data);
if not success then
log("error", "Unable to load "..datastore.." storage ('"..ret.."') for user: "..(username or "nil").."@"..(host or "nil"));
return nil;
end
return items;
end
return _M;
|
Fixed logging in datamanager
|
Fixed logging in datamanager
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
a5899c9656bd3e488d3ff75595f70b55f7b4278b
|
busted/outputHandlers/junit.lua
|
busted/outputHandlers/junit.lua
|
local xml = require 'pl.xml'
local socket = require("socket")
local string = require("string")
return function(options, busted)
local handler = require 'busted.outputHandlers.base'(busted)
local xml_doc
local suiteStartTime
handler.suiteStart = function()
suiteStartTime = socket.gettime()
xml_doc = xml.new('testsuite', {
tests = 0,
errors = 0,
failures = 0,
skip = 0,
})
return nil, true
end
local function now()
return string.format("%.2f", (socket.gettime() - suiteStartTime))
end
handler.suiteEnd = function()
xml_doc.attr.time = now()
print(xml.tostring(xml_doc, '', '\t', nil, false))
return nil, true
end
handler.testEnd = function(element, parent, status)
xml_doc.attr.tests = xml_doc.attr.tests + 1
local testcase_node = xml.new('testcase', {
classname = element.trace.short_src .. ':' .. element.trace.currentline,
name = handler.getFullName(element),
time = now()
})
xml_doc:add_direct_child(testcase_node)
if status == 'failure' then
local formatted = handler.inProgress[tostring(element)]
xml_doc.attr.failures = xml_doc.attr.failures + 1
testcase_node:addtag('failure')
if next(formatted) then
testcase_node:text(formatted.message)
if formatted.trace and formatted.trace.traceback then
testcase_node:text(formatted.trace.traceback)
end
end
testcase_node:up()
elseif status == 'pending' then
local formatted = handler.inProgress[tostring(element)]
xml_doc.attr.skip = xml_doc.attr.skip + 1
testcase_node:addtag('pending')
if next(formatted) then
testcase_node:text(formatted.message)
if formatted.trace and formatted.trace.traceback then
testcase_node:text(formatted.trace.traceback)
end
else
testcase_node:text(element.trace.traceback)
end
testcase_node:up()
end
return nil, true
end
handler.error = function(element, parent, message, trace)
xml_doc.attr.errors = xml_doc.attr.errors + 1
xml_doc:addtag('error')
xml_doc:text(message)
if trace and trace.traceback then
xml_doc:text(trace.traceback)
end
xml_doc:up()
return nil, true
end
handler.failure = function(element, parent, message, trace)
if element.descriptor ~= 'it' then
handler.error(element, parent, message, trace)
end
return nil, true
end
busted.subscribe({ 'suite', 'start' }, handler.suiteStart)
busted.subscribe({ 'suite', 'end' }, handler.suiteEnd)
busted.subscribe({ 'test', 'end' }, handler.testEnd, { predicate = handler.cancelOnPending })
busted.subscribe({ 'error' }, handler.error)
busted.subscribe({ 'failure' }, handler.failure)
return handler
end
|
local xml = require 'pl.xml'
local socket = require("socket")
local string = require("string")
return function(options, busted)
local handler = require 'busted.outputHandlers.base'(busted)
local xml_doc
local suiteStartTime
handler.suiteStart = function()
suiteStartTime = socket.gettime()
xml_doc = xml.new('testsuite', {
tests = 0,
errors = 0,
failures = 0,
skip = 0,
})
return nil, true
end
local function now()
return string.format("%.2f", (socket.gettime() - suiteStartTime))
end
handler.suiteEnd = function()
xml_doc.attr.time = now()
print(xml.tostring(xml_doc, '', '\t', nil, false))
return nil, true
end
local function testStatus(element, parent, message, status, trace)
local testcase_node = xml.new('testcase', {
classname = element.trace.short_src .. ':' .. element.trace.currentline,
name = handler.getFullName(element),
time = now()
})
xml_doc:add_direct_child(testcase_node)
if status ~= 'success' then
testcase_node:addtag(status)
if message then testcase_node:text(message) end
if trace and trace.traceback then testcase_node:text(trace.traceback) end
testcase_node:up()
end
end
handler.testEnd = function(element, parent, status)
xml_doc.attr.tests = xml_doc.attr.tests + 1
if status == 'success' then
testStatus(element, parent, nil, 'success')
elseif status == 'pending' then
xml_doc.attr.skip = xml_doc.attr.skip + 1
local formatted = handler.inProgress[tostring(element)] or {}
testStatus(element, parent, formatted.message, 'skipped', formatted.trace)
end
return nil, true
end
handler.failureTest = function(element, parent, message, trace)
xml_doc.attr.failures = xml_doc.attr.failures + 1
testStatus(element, parent, message, 'failure', trace)
return nil, true
end
handler.errorTest = function(element, parent, message, trace)
xml_doc.attr.errors = xml_doc.attr.errors + 1
testStatus(element, parent, message, 'error', trace)
return nil, true
end
handler.error = function(element, parent, message, trace)
if element.descriptor ~= 'it' then
xml_doc.attr.errors = xml_doc.attr.errors + 1
xml_doc:addtag('error')
xml_doc:text(message)
if trace and trace.traceback then
xml_doc:text(trace.traceback)
end
xml_doc:up()
end
return nil, true
end
busted.subscribe({ 'suite', 'start' }, handler.suiteStart)
busted.subscribe({ 'suite', 'end' }, handler.suiteEnd)
busted.subscribe({ 'test', 'end' }, handler.testEnd, { predicate = handler.cancelOnPending })
busted.subscribe({ 'error', 'it' }, handler.errorTest)
busted.subscribe({ 'failure', 'it' }, handler.failureTest)
busted.subscribe({ 'error' }, handler.error)
busted.subscribe({ 'failure' }, handler.error)
return handler
end
|
Fix junit output to better match junit xml format
|
Fix junit output to better match junit xml format
Update the junit output handler to better match the junit xml format
* Mark pending tests as `<skipped/>`
* Nest errors that occur in a test inside `<testcase>`
|
Lua
|
mit
|
DorianGray/busted,Olivine-Labs/busted,istr/busted,mpeterv/busted,leafo/busted,sobrinho/busted,xyliuke/busted,ryanplusplus/busted,o-lim/busted,nehz/busted
|
155b5a7b90acb6c5e59a712c1e4416bbf0b1229d
|
joueur/run.lua
|
joueur/run.lua
|
return function(args)
local client = require("joueur.client")
local GameManager = require("joueur.gameManager")
local safeCall = require("joueur.safeCall")
local splitServer = args.server:split(":")
args.server = splitServer[1]
args.port = tonumber(splitServer[2] or args.port)
local game, ai, gameManager = nil, nil, nil
safeCall(function()
game = require("games." .. args.game .. ".game")()
ai = require("games." .. args.game .. ".ai")(game)
gameManager = GameManager(game)
end, "GAME_NOT_FOUND", "Could not find game files for '" .. args.game .. "'")
client:setup(game, ai, gameManager, args.server, args.port, args)
client:send("play", {
gameName = args.game,
requestedSession = args.session,
clientType = "Lua",
playerName = args.playerName or ai:getName() or "Lua Player",
password = args.password,
gameSettings = args.gameSettings,
})
local lobbyData = client:waitForEvent("lobbied")
print("In Lobby for game '" .. lobbyData.gameName .. "' in session '" .. lobbyData.gameSession .. "'")
gameManager:setConstants(lobbyData.constants)
local startData = client:waitForEvent("start")
print("Game starting")
ai:setPlayer(game:getGameObject(startData.playerID))
safeCall(function()
ai:start()
ai:gameUpdated()
end, "AI_ERRORED", "AI errored when game starting.")
client:play()
end
|
return function(args)
local client = require("joueur.client")
local GameManager = require("joueur.gameManager")
local safeCall = require("joueur.safeCall")
local splitServer = args.server:split(":")
args.server = splitServer[1]
args.port = tonumber(splitServer[2] or args.port)
local game, ai, gameManager = nil, nil, nil
safeCall(function()
game = require("games." .. args.game:uncapitalize() .. ".game")()
ai = require("games." .. args.game:uncapitalize() .. ".ai")(game)
gameManager = GameManager(game)
end, "GAME_NOT_FOUND", "Could not find game files for '" .. args.game .. "'")
client:setup(game, ai, gameManager, args.server, args.port, args)
client:send("play", {
gameName = args.game,
requestedSession = args.session,
clientType = "Lua",
playerName = args.playerName or ai:getName() or "Lua Player",
password = args.password,
gameSettings = args.gameSettings,
})
local lobbyData = client:waitForEvent("lobbied")
print("In Lobby for game '" .. lobbyData.gameName .. "' in session '" .. lobbyData.gameSession .. "'")
gameManager:setConstants(lobbyData.constants)
local startData = client:waitForEvent("start")
print("Game starting")
ai:setPlayer(game:getGameObject(startData.playerID))
safeCall(function()
ai:start()
ai:gameUpdated()
end, "AI_ERRORED", "AI errored when game starting.")
client:play()
end
|
fixing linux game name error
|
fixing linux game name error
|
Lua
|
mit
|
siggame/Joueur.lua,siggame/Joueur.lua,JacobFischer/Joueur.lua
|
e5faa6c1257d90a194ec644c167d881719a0455c
|
Modules/Camera/Effects/LagPointCamera.lua
|
Modules/Camera/Effects/LagPointCamera.lua
|
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local NevermoreEngine = require(ReplicatedStorage:WaitForChild("NevermoreEngine"))
local LoadCustomLibrary = NevermoreEngine.LoadLibrary
local CameraState = LoadCustomLibrary("CameraState")
local SummedCamera = LoadCustomLibrary("SummedCamera")
local SpringPhysics = LoadCustomLibrary("SpringPhysics")
local LagPointCamera = {}
LagPointCamera.ClassName = "LagPointCamera"
-- Intent: Point a current element
function LagPointCamera.new(OriginCamera, FocusCamera)
-- @param OriginCamera A camera to use
-- @param FocusCamera The Camera to look at.
local self = setmetatable({}, LagPointCamera)
self.FocusSpring = SpringPhysics.VectorSpring.New()
self.OriginCamera = OriginCamera or error("Must have OriginCamera")
self.FocusCamera = FocusCamera or error("Must have OriginCamera")
self.Speed = 10
return self
end
function LagPointCamera:__add(Other)
return SummedCamera.new(self, Other)
end
function LagPointCamera:__newindex(Index, Value)
if Index == "FocusCamera" then
rawset(self, Index, Value)
self.FocusSpring.Target = self.FocusCamera.CameraState.qPosition
self.FocusSpring.Position = self.FocusSpring.Target
self.FocusSpring.Velocity = Vector3.new(0, 0, 0)
elseif Index == "OriginCamera" or Index == "LastFocusUpdate" or Index == "FocusSpring" then
rawset(self, Index, Value)
elseif Index == "Speed" or Index == "Damper" or Index == "Velocity" then
self.FocusSpring[Index] = Value
else
error(Index .. " is not a valid member of LagPointCamera")
end
end
function LagPointCamera:__index(Index)
if Index == "State" or Index == "CameraState" or Index == "Camera" then
local Origin, FocusPosition = self.Origin, self.FocusPosition
local State = CameraState.new()
State.FieldOfView = Origin.FieldOfView + self.FocusCamera.CameraState.FieldOfView
State.CoordinateFrame = CFrame.new(
Origin.qPosition,
FocusPosition)
return State
elseif Index == "FocusPosition" then
local Delta
if self.LastFocusUpdate then
Delta = tick() - self.LastFocusUpdate
end
self.LastFocusUpdate = tick()
self.FocusSpring.Target = self.FocusCamera.CameraState.qPosition
if Delta then
self.FocusSpring:TimeSkip(Delta)
end
return self.FocusSpring.Position
elseif Index == "Speed" or Index == "Damper" or Index == "Velocity" then
return self.FocusSpring[Index]
elseif Index == "Origin" then
return self.OriginCamera.CameraState
else
return LagPointCamera[Index]
end
end
return LagPointCamera
|
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local NevermoreEngine = require(ReplicatedStorage:WaitForChild("NevermoreEngine"))
local LoadCustomLibrary = NevermoreEngine.LoadLibrary
local CameraState = LoadCustomLibrary("CameraState")
local SummedCamera = LoadCustomLibrary("SummedCamera")
local SpringPhysics = LoadCustomLibrary("SpringPhysics")
local LagPointCamera = {}
LagPointCamera.ClassName = "LagPointCamera"
LagPointCamera._FocusCamera = nil
LagPointCamera._OriginCamera = nil
-- Intent: Point a current element but lag behind for a smoother experience
function LagPointCamera.new(OriginCamera, FocusCamera)
-- @param OriginCamera A camera to use
-- @param FocusCamera The Camera to look at.
local self = setmetatable({}, LagPointCamera)
self.FocusSpring = SpringPhysics.VectorSpring.New()
self.OriginCamera = OriginCamera or error("Must have OriginCamera")
self.FocusCamera = FocusCamera or error("Must have FocusCamera")
self.Speed = 10
return self
end
function LagPointCamera:__add(Other)
return SummedCamera.new(self, Other)
end
function LagPointCamera:__newindex(Index, Value)
if Index == "FocusCamera" then
rawset(self, "_" .. Index, Value)
self.FocusSpring.Target = self.FocusCamera.CameraState.qPosition
self.FocusSpring.Position = self.FocusSpring.Target
self.FocusSpring.Velocity = Vector3.new(0, 0, 0)
elseif Index == "OriginCamera" then
rawset(self, "_" .. Index, Value)
elseif Index == "LastFocusUpdate" or Index == "FocusSpring" then
rawset(self, Index, Value)
elseif Index == "Speed" or Index == "Damper" or Index == "Velocity" then
self.FocusSpring[Index] = Value
else
error(Index .. " is not a valid member of LagPointCamera")
end
end
function LagPointCamera:__index(Index)
if Index == "State" or Index == "CameraState" or Index == "Camera" then
local Origin, FocusPosition = self.Origin, self.FocusPosition
local State = CameraState.new()
State.FieldOfView = Origin.FieldOfView + self.FocusCamera.CameraState.FieldOfView
State.CoordinateFrame = CFrame.new(
Origin.qPosition,
FocusPosition)
return State
elseif Index == "FocusPosition" then
local Delta
if self.LastFocusUpdate then
Delta = tick() - self.LastFocusUpdate
end
self.LastFocusUpdate = tick()
self.FocusSpring.Target = self.FocusCamera.CameraState.qPosition
if Delta then
self.FocusSpring:TimeSkip(Delta)
end
return self.FocusSpring.Position
elseif Index == "Speed" or Index == "Damper" or Index == "Velocity" then
return self.FocusSpring[Index]
elseif Index == "Origin" then
return self.OriginCamera.CameraState
elseif Index == "FocusCamera" or Index == "OriginCamera" then
return rawget(self, "_" .. Index) or error("Internal error: Index does not exist")
else
return LagPointCamera[Index]
end
end
return LagPointCamera
|
Standardized documentation, fixed FocusCamera/OriginCamera indexing,
|
Standardized documentation, fixed FocusCamera/OriginCamera indexing,
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
7a28d85b30eede6f21400f806e209d976564e23a
|
src/ui/MapView.lua
|
src/ui/MapView.lua
|
--MapView.lua
local class = require 'lib/30log'
local statemachine = require('lib/statemachine')
local Interfaceable = require 'src/component/Interfaceable'
local Renderable = require 'src/component/Renderable'
local Transform = require 'src/component/Transform'
local TouchDelegate = require 'src/datatype/TouchDelegate'
local GameObject = require 'src/GameObject'
local Polygon = require 'src/datatype/Polygon'
local MainMenuView = require 'src/ui/MainMenuView'
local QuickCommandPanelView = require 'src/ui/QuickCommandPanelView'
local ConfirmationDialogBoxView = require 'src/ui/ConfirmationDialogBoxView'
local TurnStartView = require 'src/ui/TurnStartView'
local CityInspectorView = require 'src/ui/CityInspectorView'
local ArmyInspectorView = require 'src/ui/ArmyInspectorView'
local MapView = class("MapView", {
})
function MapView:init( registry, scenegraph, tiles, cities, units )
self.registry = registry
self.scenegraph = scenegraph
local Map_Layer = registry:add(GameObject:new('Map Layer', {
Transform:new()
}))
local Tile_Layer = registry:add(GameObject:new('Tile_Layer',{}))
local City_Layer = registry:add(GameObject:new('City_Layer',{}))
local Unit_Layer = registry:add(GameObject:new('Unit_Layer',{}))
local UI_Layer = registry:add(GameObject:new('UI_Layer',{}))
local Turn_Start_View = TurnStartView:new(registry, scenegraph)
local Main_Menu_View = MainMenuView:new(registry, scenegraph)
local Quick_Command_Panel_View = QuickCommandPanelView:new(registry, scenegraph)
local Confirmation_Dialog_Box_View = ConfirmationDialogBoxView:new(registry, scenegraph)
local City_Inspector_View = CityInspectorView:new(registry, scenegraph)
local Army_Inspector_View = ArmyInspectorView:new(registry, scenegraph)
local Inspector = registry:add(GameObject:new('Inspector',{
Transform:new(0,675),
Renderable:new(
Polygon:new({w=1200, h=125}),
nil,
{50,100,100,125},
"Inspector Panel (has some commands, cursor information, minimap, etc). Press Escape to bring up the Main Menu")
}))
local Map_View_Touch_Delegate = TouchDelegate:new()
Map_View_Touch_Delegate:setHandler('onDrag', function(this, x,y,dx,dy)
if not Main_Menu_View.is_attached and registry:get(Map_Layer):hasComponent('Transform') then
local t = registry:get(Map_Layer):getComponent('Transform')
t:translate(dx,dy)
end
end)
Map_View_Touch_Delegate:setHandler('onKeypress', function(this, btn)
print('key pressed on map view: ' .. btn .. ' while showing_main_menu == ' .. tostring(Main_Menu_View.is_attached))
if btn == 'escape' then
if Main_Menu_View.is_attached then
Main_Menu_View:hide()
else
Main_Menu_View:show(UI_Layer)
end
end
end)
local Map_View = registry:add(GameObject:new('Map_View',{
Transform:new(0,0),
Interfaceable:new(
Polygon:new({w=1200, h=800}),
Map_View_Touch_Delegate)
}))
scenegraph:attach(Map_View)
scenegraph:attachAll({Map_Layer,UI_Layer}, Map_View)
scenegraph:attachAll({Tile_Layer,City_Layer,Unit_Layer,UI_Layer}, Map_Layer)
scenegraph:attachAll(tiles, Tile_Layer)
scenegraph:attachAll(cities, City_Layer)
scenegraph:attachAll(units, Unit_Layer)
scenegraph:attachAll({Inspector},UI_Layer)
scenegraph:attachAll({Quick_Command_Panel_View.root},Inspector)
for i, tile in ipairs(tiles) do
scenegraph:attach(tile.root, Tile_Layer)
end
for i, city in ipairs(cities) do
scenegraph:attach(city.root, City_Layer)
end
for i, unit in ipairs(units) do
scenegraph:attach(unit.root, Unit_Layer)
end
scenegraph:setRoot(Map_View)
registry:subscribe("selectCity", function(this, msg)
if msg.icon_type == 'city' then
print('Show city inspector for ' .. inspect(msg.address.address))
City_Inspector_View:hide()
City_Inspector_View:show(Inspector,msg)
end
end)
registry:subscribe("selectArmy", function(this, msg)
if msg.icon_type == 'army' then
print('Show army inspector for ' .. inspect(msg.address.address))
Army_Inspector_View:hide()
Army_Inspector_View:show(Inspector,msg)
end
end)
registry:subscribe(Quick_Command_Panel_View.root .. ":startTurnRequest", function(this, msg)
Turn_Start_View:show(UI_Layer, self.registry:findComponent("GameInfo",{gs_type="player", is_current=true}))
end)
registry:subscribe(Quick_Command_Panel_View.root .. ":endTurnRequest", function(this, msg)
if self.is_frozen then return end
self.is_frozen = true
local unsubConfirm = function() print('oops') end
local unsubCancel = function() print('oops') end
Confirmation_Dialog_Box_View:show(UI_Layer,"Whoa hey! You sure you want to end your turn?")
unsubConfirm = self.registry:subscribe("confirm",function(this, msg)
if not self.is_frozen then return end
self.registry:publish("triggerEndTurn")
self.registry:publish(Quick_Command_Panel_View.root .. ":startTurnRequest")
unsubCancel()
unsubConfirm()
self.is_frozen = false
end)
unsubCancel = self.registry:subscribe("cancel",function(this,msg)
if not self.is_frozen then return end
unsubCancel()
unsubConfirm()
self.is_frozen = false
end)
end)
end
return MapView
|
--MapView.lua
local class = require 'lib/30log'
local statemachine = require('lib/statemachine')
local Interfaceable = require 'src/component/Interfaceable'
local Renderable = require 'src/component/Renderable'
local Transform = require 'src/component/Transform'
local TouchDelegate = require 'src/datatype/TouchDelegate'
local GameObject = require 'src/GameObject'
local Polygon = require 'src/datatype/Polygon'
local MainMenuView = require 'src/ui/MainMenuView'
local QuickCommandPanelView = require 'src/ui/QuickCommandPanelView'
local ConfirmationDialogBoxView = require 'src/ui/ConfirmationDialogBoxView'
local TurnStartView = require 'src/ui/TurnStartView'
local CityInspectorView = require 'src/ui/CityInspectorView'
local ArmyInspectorView = require 'src/ui/ArmyInspectorView'
local MapView = class("MapView", {
})
function MapView:init( registry, scenegraph, tiles, cities, units )
self.registry = registry
self.scenegraph = scenegraph
local Map_Layer = registry:add(GameObject:new('Map Layer', {
Transform:new()
}))
local Tile_Layer = registry:add(GameObject:new('Tile_Layer',{}))
local City_Layer = registry:add(GameObject:new('City_Layer',{}))
local Unit_Layer = registry:add(GameObject:new('Unit_Layer',{}))
local UI_Layer = registry:add(GameObject:new('UI_Layer',{}))
local Turn_Start_View = TurnStartView:new(registry, scenegraph)
local Main_Menu_View = MainMenuView:new(registry, scenegraph)
local Quick_Command_Panel_View = QuickCommandPanelView:new(registry, scenegraph)
local Confirmation_Dialog_Box_View = ConfirmationDialogBoxView:new(registry, scenegraph)
local City_Inspector_View = CityInspectorView:new(registry, scenegraph)
local Army_Inspector_View = ArmyInspectorView:new(registry, scenegraph)
local Inspector = registry:add(GameObject:new('Inspector',{
Transform:new(0,675),
Renderable:new(
Polygon:new({w=1200, h=125}),
nil,
{50,100,100,125},
"Inspector Panel (has some commands, cursor information, minimap, etc). Press Escape to bring up the Main Menu")
}))
local Map_View_Touch_Delegate = TouchDelegate:new()
Map_View_Touch_Delegate:setHandler('onDrag', function(this, x,y,dx,dy)
if not Main_Menu_View.is_attached and registry:get(Map_Layer):hasComponent('Transform') then
local t = registry:get(Map_Layer):getComponent('Transform')
t:translate(dx,dy)
end
end)
Map_View_Touch_Delegate:setHandler('onKeypress', function(this, btn)
print('key pressed on map view: ' .. btn .. ' while showing_main_menu == ' .. tostring(Main_Menu_View.is_attached))
if btn == 'escape' then
if Main_Menu_View.is_attached then
Main_Menu_View:hide()
else
Main_Menu_View:show(UI_Layer)
end
end
end)
local Map_View = registry:add(GameObject:new('Map_View',{
Transform:new(0,0),
Interfaceable:new(
Polygon:new({w=1200, h=800}),
Map_View_Touch_Delegate)
}))
scenegraph:attach(Map_View)
scenegraph:attachAll({Map_Layer,UI_Layer}, Map_View)
scenegraph:attachAll({Tile_Layer,City_Layer,Unit_Layer}, Map_Layer)
scenegraph:attachAll({Inspector},UI_Layer)
scenegraph:attachAll({Quick_Command_Panel_View.root},Inspector)
for i, tile in ipairs(tiles) do
scenegraph:attach(tile.root, Tile_Layer)
end
for i, city in ipairs(cities) do
scenegraph:attach(city.root, City_Layer)
end
for i, unit in ipairs(units) do
scenegraph:attach(unit.root, Unit_Layer)
end
scenegraph:setRoot(Map_View)
registry:subscribe("selectCity", function(this, msg)
if msg.icon_type == 'city' then
print('Show city inspector for ' .. inspect(msg.address.address))
City_Inspector_View:hide()
City_Inspector_View:show(Inspector,msg)
end
end)
registry:subscribe("selectArmy", function(this, msg)
if msg.icon_type == 'army' then
print('Show army inspector for ' .. inspect(msg.address.address))
Army_Inspector_View:hide()
Army_Inspector_View:show(Inspector,msg)
end
end)
registry:subscribe(Quick_Command_Panel_View.root .. ":startTurnRequest", function(this, msg)
Turn_Start_View:show(UI_Layer, self.registry:findComponent("GameInfo",{gs_type="player", is_current=true}))
end)
registry:subscribe(Quick_Command_Panel_View.root .. ":endTurnRequest", function(this, msg)
if self.is_frozen then return end
self.is_frozen = true
local unsubConfirm = function() print('oops') end
local unsubCancel = function() print('oops') end
Confirmation_Dialog_Box_View:show(UI_Layer,"Whoa hey! You sure you want to end your turn?")
unsubConfirm = self.registry:subscribe("confirm",function(this, msg)
if not self.is_frozen then return end
self.registry:publish("triggerEndTurn")
self.registry:publish(Quick_Command_Panel_View.root .. ":startTurnRequest")
unsubCancel()
unsubConfirm()
self.is_frozen = false
end)
unsubCancel = self.registry:subscribe("cancel",function(this,msg)
if not self.is_frozen then return end
unsubCancel()
unsubConfirm()
self.is_frozen = false
end)
end)
end
return MapView
|
fix parenting
|
fix parenting
|
Lua
|
mit
|
Sewerbird/Helios2400,Sewerbird/Helios2400,Sewerbird/Helios2400
|
b73ce9264919606f3bfdaa0f6824eba16d449208
|
lua/entities/gmod_wire_value/init.lua
|
lua/entities/gmod_wire_value/init.lua
|
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include('shared.lua')
ENT.WireDebugName = "Value"
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Outputs = Wire_CreateOutputs(self, { "Out" })
end
local function ReturnType( DataType )
// Supported Data Types.
// Should be requested by client and only kept serverside.
local DataTypes = {
["NORMAL"] = "number",
["STRING"] = "string",
["VECTOR"] = "vector",
["ANGLE"] = "angle"
}
for k,v in pairs(DataTypes) do
if(v == DataType:lower()) then
return k
end
end
return nil
end
local function StringToNumber( str )
local val = tonumber(str) or 0
return val
end
local function StringToVector( str )
if str != nil and str != "" then
local tbl = string.Split(str, ",")
if #tbl >= 2 and #tbl <=3 then
local vec = Vector(0,0,0)
vec.x = StringToNumber(tbl[1])
vec.y = StringToNumber(tbl[2])
if #tbl == 3 then
vec.z = StringToNumber(tbl[3])
end
return vec
end
end
return Vector(0,0,0)
end
local function StringToAngle( str )
if str != nil and str != "" then
local tbl = string.Split(str, ",")
if #tbl == 3 then
local ang = Angle(0,0,0)
ang.p = StringToNumber(tbl[1])
ang.y = StringToNumber(tbl[2])
ang.r = StringToNumber(tbl[3])
return ang
end
end
return Angle(0,0,0)
end
local tbl = {
["NORMAL"] = StringToNumber,
["STRING"] = tostring,
["VECTOR"] = StringToVector,
["ANGLE"] = StringToAngle,
}
local function TranslateType( Value, DataType )
if tbl[DataType] then
return tbl[DataType]( Value )
end
return 0
end
function ENT:Setup(valuesin)
self.value = valuesin -- Wirelink/Duplicator Info
local names = {}
local types = {}
local values = {}
for k,v in pairs(valuesin) do
names[k] = tostring( k )
values[k] = TranslateType(v.Value, ReturnType(v.DataType))
types[k] = ReturnType(v.DataType)
end
// this is where storing the values as strings comes in: they are the descriptions for the inputs.
WireLib.AdjustSpecialOutputs(self, names, types, values )
local txt = ""
for k,v in pairs(valuesin) do
txt = txt .. names[k] .. " [" .. tostring(v.DataType) .. "]: " .. tostring(values[k]) .. "\n"
Wire_TriggerOutput( self, names[k], values[k] )
end
self:SetOverlayText(string.Left(txt,#txt-1)) -- Cut off the last \n
end
function ENT:ReadCell( Address )
return self.value[Address+1]
end
function MakeWireValue( ply, Pos, Ang, model, value )
if (!ply:CheckLimit("wire_values")) then return false end
local wire_value = ents.Create("gmod_wire_value")
if (!wire_value:IsValid()) then return false end
wire_value:SetAngles(Ang)
wire_value:SetPos(Pos)
wire_value:SetModel(model)
wire_value:Spawn()
if value then
local _,val = next(value)
if istable(val) then
-- The new Gmod13 format, good
wire_value:Setup(value)
else
-- The old Gmod12 dupe format, lets convert it
local convertedValues = {}
local convtbl = {
["NORMAL"] = "Number",
["ANGLE"] = "Angle",
["VECTOR"] = "Vector",
["VECTOR2"] = "Vector",
["VECTOR4"] = "Vector",
["STRING"] = "String",
}
for k,v in pairs(value) do
local theType,theValue = string.match (v, "^ *([^: ]+) *:(.*)$")
theType = string.upper(theType or "NORMAL")
if not convtbl[theType] then
theType = "NORMAL"
end
table.insert(convertedValues, { DataType=convtbl[theType], Value=theValue or v } )
end
wire_value:Setup( convertedValues )
end
end
wire_value:SetPlayer(ply)
ply:AddCount("wire_values", wire_value)
return wire_value
end
duplicator.RegisterEntityClass("gmod_wire_value", MakeWireValue, "Pos", "Ang", "Model", "value")
|
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include('shared.lua')
ENT.WireDebugName = "Value"
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Outputs = Wire_CreateOutputs(self, { "Out" })
end
local function ReturnType( DataType )
// Supported Data Types.
// Should be requested by client and only kept serverside.
local DataTypes = {
["NORMAL"] = "number",
["STRING"] = "string",
["VECTOR"] = "vector",
["ANGLE"] = "angle"
}
for k,v in pairs(DataTypes) do
if(v == DataType:lower()) then
return k
end
end
return nil
end
local function StringToNumber( str )
local val = tonumber(str) or 0
return val
end
local function StringToVector( str )
if str != nil and str != "" then
local tbl = string.Split(str, ",")
if #tbl >= 2 and #tbl <=3 then
local vec = Vector(0,0,0)
vec.x = StringToNumber(tbl[1])
vec.y = StringToNumber(tbl[2])
if #tbl == 3 then
vec.z = StringToNumber(tbl[3])
end
return vec
end
end
return Vector(0,0,0)
end
local function StringToAngle( str )
if str != nil and str != "" then
local tbl = string.Split(str, ",")
if #tbl == 3 then
local ang = Angle(0,0,0)
ang.p = StringToNumber(tbl[1])
ang.y = StringToNumber(tbl[2])
ang.r = StringToNumber(tbl[3])
return ang
end
end
return Angle(0,0,0)
end
local tbl = {
["NORMAL"] = StringToNumber,
["STRING"] = tostring,
["VECTOR"] = StringToVector,
["ANGLE"] = StringToAngle,
}
local function TranslateType( Value, DataType )
if tbl[DataType] then
return tbl[DataType]( Value )
end
return 0
end
function ENT:Setup(valuesin, legacynames)
self.value = valuesin -- Wirelink/Duplicator Info
local names = {}
local types = {}
local values = {}
for k,v in pairs(valuesin) do
names[k] = tostring( k )
values[k] = TranslateType(v.Value, ReturnType(v.DataType))
types[k] = ReturnType(v.DataType)
end
if legacynames then
-- Gmod12 Constant Values will have outputs like Value1, Value2...
-- To avoid breaking old dupes, we'll use those names if we're created from an old dupe
for k,v in pairs(names) do
names[k] = "Value"..v
end
end
// this is where storing the values as strings comes in: they are the descriptions for the inputs.
WireLib.AdjustSpecialOutputs(self, names, types, values )
local txt = ""
for k,v in pairs(valuesin) do
txt = txt .. names[k] .. " [" .. tostring(v.DataType) .. "]: " .. tostring(values[k]) .. "\n"
Wire_TriggerOutput( self, names[k], values[k] )
end
self:SetOverlayText(string.Left(txt,#txt-1)) -- Cut off the last \n
end
function ENT:ReadCell( Address )
return self.value[Address+1]
end
function MakeWireValue( ply, Pos, Ang, model, value )
if (!ply:CheckLimit("wire_values")) then return false end
local wire_value = ents.Create("gmod_wire_value")
if (!wire_value:IsValid()) then return false end
wire_value:SetAngles(Ang)
wire_value:SetPos(Pos)
wire_value:SetModel(model)
wire_value:Spawn()
if value then
local _,val = next(value)
if istable(val) then
-- The new Gmod13 format, good
wire_value:Setup(value)
else
-- The old Gmod12 dupe format, lets convert it
local convertedValues = {}
local convtbl = {
["NORMAL"] = "Number",
["ANGLE"] = "Angle",
["VECTOR"] = "Vector",
["VECTOR2"] = "Vector",
["VECTOR4"] = "Vector",
["STRING"] = "String",
}
for k,v in pairs(value) do
local theType,theValue = string.match (v, "^ *([^: ]+) *:(.*)$")
theType = string.upper(theType or "NORMAL")
if not convtbl[theType] then
theType = "NORMAL"
end
table.insert(convertedValues, { DataType=convtbl[theType], Value=theValue or v } )
end
wire_value:Setup( convertedValues, true )
end
end
wire_value:SetPlayer(ply)
ply:AddCount("wire_values", wire_value)
return wire_value
end
duplicator.RegisterEntityClass("gmod_wire_value", MakeWireValue, "Pos", "Ang", "Model", "value")
|
Constant Value: Fixed old dupes becoming unwired Fixes #152
|
Constant Value: Fixed old dupes becoming unwired
Fixes #152
|
Lua
|
apache-2.0
|
immibis/wiremod,thegrb93/wire,wiremod/wire,Grocel/wire,mms92/wire,plinkopenguin/wiremod,mitterdoo/wire,notcake/wire,sammyt291/wire,bigdogmat/wire,rafradek/wire,CaptainPRICE/wire,NezzKryptic/Wire,garrysmodlua/wire,dvdvideo1234/wire,Python1320/wire
|
f1ca40651255bd8194803722fcc7cd6f51a556f4
|
src/cosy/cli/init.lua
|
src/cosy/cli/init.lua
|
local Loader = require "cosy.loader"
Loader.nolog = true
local Configuration = require "cosy.configuration"
local Value = require "cosy.value"
local Lfs = require "lfs"
local I18n = require "cosy.i18n"
local Cliargs = require "cliargs"
local Colors = require "ansicolors"
local Websocket = require "websocket"
Configuration.load {
"cosy.cli",
"cosy.daemon",
}
local i18n = I18n.load {
"cosy.cli",
"cosy.commands",
"cosy.daemon",
}
i18n._locale = Configuration.cli.locale
local Cli = {}
local function read (filename)
local file = io.open (filename, "r")
if not file then
return nil
end
local data = file:read "*all"
file:close ()
return Value.decode (data)
end
function Cli.configure (arguments)
for _, key in ipairs { -- key to parse
"server",
"color",
} do
local pattern = "%-%-" .. key .. "=(.*)"
local j = 1
while j <= #arguments do
local argument = arguments [j]
local value = argument:match (pattern) -- value contains only right hand side of equals
if value then -- matched
assert (not Cli [key]) -- (better) nil or false
Cli [key] = value
table.remove (arguments, j)
else
j = j + 1
end
end
end
Cli.arguments = arguments
end
function Cli.start ()
local directory = Configuration.cli.directory
Lfs.mkdir (directory)
local daemondata = read (Configuration.daemon.data)
if Cli.arguments [1] == "--no-color" then
_G.nocolor = true
table.remove (Cli.arguments, 1)
end
if _G.nocolor then
Colors = function (s)
return s:gsub ("(%%{(.-)})", "")
end
end
local ws = Websocket.client.sync {
timeout = 10,
}
if not daemondata
or not ws:connect ("ws://{{{interface}}}:{{{port}}}/ws" % {
interface = daemondata.interface,
port = daemondata.port,
}, "cosy") then
os.execute ([==[
if [ -f "{{{pid}}}" ]
then
kill -9 $(cat {{{pid}}}) 2> /dev/null
fi
rm -f {{{pid}}} {{{log}}}
luajit -e '_G.logfile = "{{{log}}}"; require "cosy.daemon" .start ()' &
]==] % {
pid = Configuration.daemon.pid,
log = Configuration.daemon.log,
})
local tries = 0
repeat
os.execute ([[sleep {{{time}}}]] % { time = 0.5 })
daemondata = read (Configuration.daemon.data)
tries = tries + 1
until daemondata or tries == 5
if not daemondata
or not ws:connect ("ws://{{{interface}}}:{{{port}}}/ws" % {
interface = daemondata.interface,
port = daemondata.port,
}, "cosy") then
print (Colors ("%{white redbg}" .. i18n ["failure"] % {}),
Colors ("%{white redbg}" .. i18n ["daemon:unreachable"] % {}))
os.exit (1)
end
end
local Commands = require "cosy.commands"
local commands = Commands.new (ws)
local command = commands [Cli.arguments [1] or false]
Cliargs:set_name (Cli.arguments [0] .. " " .. Cli.arguments [1])
table.remove (Cli.arguments, 1)
local ok, result = xpcall (command, function ()
print (Colors ("%{white redbg}" .. i18n ["error:unexpected"] % {}))
-- print (Value.expression (e))
-- print (debug.traceback ())
end)
if not ok then
if result then
print (Colors ("%{white redbg}" .. i18n (result.error).message))
end
end
if result and result.success then
os.exit (0)
else
os.exit (1)
end
end
function Cli.stop ()
end
return Cli
|
local Loader = require "cosy.loader"
Loader.nolog = true
local Configuration = require "cosy.configuration"
local Value = require "cosy.value"
local Lfs = require "lfs"
local I18n = require "cosy.i18n"
local Cliargs = require "cliargs"
local Colors = require "ansicolors"
local Websocket = require "websocket"
Configuration.load {
"cosy.cli",
"cosy.daemon",
}
local i18n = I18n.load {
"cosy.cli",
"cosy.commands",
"cosy.daemon",
}
i18n._locale = Configuration.cli.locale
local Cli = {}
local function read (filename)
local file = io.open (filename, "r")
if not file then
return nil
end
local data = file:read "*all"
file:close ()
return Value.decode (data)
end
function Cli.configure (arguments)
for _, key in ipairs { -- key to parse
"server",
"color",
} do
local pattern = "%-%-" .. key .. "=(.*)"
local j = 1
while j <= #arguments do
local argument = arguments [j]
local value = argument:match (pattern) -- value contains only right hand side of equals
if value then -- matched
assert (not Cli [key]) -- (better) nil or false
Cli [key] = value
table.remove (arguments, j)
else
j = j + 1
end
end
end
Cli.arguments = arguments
end
function Cli.start ()
local directory = Configuration.cli.directory
Lfs.mkdir (directory)
local daemondata = read (Configuration.daemon.data)
if not Cli.color then
Colors = function (s)
return s:gsub ("(%%{(.-)})", "")
end
end
local ws = Websocket.client.sync {
timeout = 10,
}
if not daemondata
or not ws:connect ("ws://{{{interface}}}:{{{port}}}/ws" % {
interface = daemondata.interface,
port = daemondata.port,
}, "cosy") then
os.execute ([==[
if [ -f "{{{pid}}}" ]
then
kill -9 $(cat {{{pid}}}) 2> /dev/null
fi
rm -f {{{pid}}} {{{log}}}
luajit -e '_G.logfile = "{{{log}}}"; require "cosy.daemon" .start ()' &
]==] % {
pid = Configuration.daemon.pid,
log = Configuration.daemon.log,
})
local tries = 0
repeat
os.execute ([[sleep {{{time}}}]] % { time = 0.5 })
daemondata = read (Configuration.daemon.data)
tries = tries + 1
until daemondata or tries == 5
if not daemondata
or not ws:connect ("ws://{{{interface}}}:{{{port}}}/ws" % {
interface = daemondata.interface,
port = daemondata.port,
}, "cosy") then
print (Colors ("%{white redbg}" .. i18n ["failure"] % {}),
Colors ("%{white redbg}" .. i18n ["daemon:unreachable"] % {}))
os.exit (1)
end
end
local Commands = require "cosy.commands"
local commands = Commands.new (ws)
local command = commands [Cli.arguments [1] or false]
Cliargs:set_name (Cli.arguments [0] .. " " .. Cli.arguments [1])
table.remove (Cli.arguments, 1)
local ok, result = xpcall (command, function ()
print (Colors ("%{white redbg}" .. i18n ["error:unexpected"] % {}))
-- print (Value.expression (e))
-- print (debug.traceback ())
end)
if not ok then
if result then
print (Colors ("%{white redbg}" .. i18n (result.error).message))
end
end
if result and result.success then
os.exit (0)
else
os.exit (1)
end
end
function Cli.stop ()
end
return Cli
|
Fix color option handling
|
Fix color option handling
|
Lua
|
mit
|
CosyVerif/library,CosyVerif/library,CosyVerif/library
|
1e245d9a669406fd2c2ad02c356d4e26304cff42
|
nvim/lua/user/plugins/bufferline.lua
|
nvim/lua/user/plugins/bufferline.lua
|
require('bufferline').setup({
options = {
indicator_icon = ' ',
show_close_icon = false,
tab_size = 0,
max_name_length = 25,
offsets = {
{
filetype = 'NvimTree',
text = ' Files',
highlight = 'StatusLine',
text_align = 'left',
},
},
separator_style = 'slant',
modified_icon = '',
custom_areas = {
left = function()
return {
{ text = ' ', guifg = '#8fff6d' },
}
end,
},
},
highlights = {
fill = {
guibg = { attribute = 'bg', highlight = 'StatusLine' },
},
background = {
guibg = { attribute = 'bg', highlight = 'StatusLine' },
},
tab = {
guibg = { attribute = 'bg', highlight = 'StatusLine' },
},
buffer_visible = {
guibg = { attribute = 'bg', highlight = 'StatusLine' },
},
close_button = {
guibg = { attribute = 'bg', highlight = 'StatusLine' },
guifg = { attribute = 'fg', highlight = 'StatusLineNonText' },
},
close_button_selected = {
guifg = { attribute = 'fg', highlight = 'StatusLineNonText' },
},
close_button_visible = {
guibg = { attribute = 'bg', highlight = 'StatusLine' },
guifg = { attribute = 'fg', highlight = 'StatusLineNonText' },
},
tab_close = {
guibg = { attribute = 'bg', highlight = 'StatusLine' },
},
modified = {
guibg = { attribute = 'bg', highlight = 'StatusLine' },
},
separator = {
guifg = { attribute = 'bg', highlight = 'StatusLine' },
guibg = { attribute = 'bg', highlight = 'StatusLine' },
},
separator_selected = {
guifg = { attribute = 'bg', highlight = 'StatusLine' },
guibg = { attribute = 'bg', highlight = 'Normal' }
},
separator_visible = {
guifg = { attribute = 'bg', highlight = 'StatusLine' },
guibg = { attribute = 'bg', highlight = 'StatusLine' },
},
},
})
|
require('bufferline').setup({
options = {
indicator_icon = ' ',
show_close_icon = false,
tab_size = 0,
max_name_length = 25,
offsets = {
{
filetype = 'NvimTree',
text = ' Files',
highlight = 'StatusLine',
text_align = 'left',
},
},
separator_style = 'slant',
modified_icon = '',
custom_areas = {
left = function()
return {
{ text = ' ', guifg = '#8fff6d' },
}
end,
},
},
highlights = {
fill = {
guibg = { attribute = 'bg', highlight = 'StatusLine' },
},
background = {
guibg = { attribute = 'bg', highlight = 'StatusLine' },
},
tab = {
guibg = { attribute = 'bg', highlight = 'StatusLine' },
},
buffer_visible = {
guibg = { attribute = 'bg', highlight = 'StatusLine' },
},
close_button = {
guibg = { attribute = 'bg', highlight = 'StatusLine' },
guifg = { attribute = 'fg', highlight = 'StatusLineNonText' },
},
close_button_selected = {
guifg = { attribute = 'fg', highlight = 'StatusLineNonText' },
},
close_button_visible = {
guibg = { attribute = 'bg', highlight = 'StatusLine' },
guifg = { attribute = 'fg', highlight = 'StatusLineNonText' },
},
tab_close = {
guibg = { attribute = 'bg', highlight = 'StatusLine' },
},
modified = {
guibg = { attribute = 'bg', highlight = 'StatusLine' },
},
modified_visible = {
guibg = { attribute = 'bg', highlight = 'StatusLine' },
},
separator = {
guifg = { attribute = 'bg', highlight = 'StatusLine' },
guibg = { attribute = 'bg', highlight = 'StatusLine' },
},
separator_selected = {
guifg = { attribute = 'bg', highlight = 'StatusLine' },
guibg = { attribute = 'bg', highlight = 'Normal' }
},
separator_visible = {
guifg = { attribute = 'bg', highlight = 'StatusLine' },
guibg = { attribute = 'bg', highlight = 'StatusLine' },
},
},
})
|
Fix bufferline modified bg when visible
|
Fix bufferline modified bg when visible
|
Lua
|
mit
|
jessarcher/dotfiles,jessarcher/dotfiles,jessarcher/dotfiles
|
cf8b8f874981a06d4dd41494ea3fb98157b60a3b
|
protocols/6x4/luasrc/model/network/proto_6x4.lua
|
protocols/6x4/luasrc/model/network/proto_6x4.lua
|
--[[
LuCI - Network model - 6to4 & 6in4 protocol extension
Copyright 2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local netmod = luci.model.network
local _, p
for _, p in ipairs({"6in4", "6to4"}) do
local proto = netmod:register_protocol(p)
function proto.get_i18n(self)
if p == "6in4" then
return luci.i18n.translate("IPv6-in-IPv4 (RFC4213)")
elseif p == "6to4" then
return luci.i18n.translate("IPv6-over-IPv4")
end
end
function proto.ifname(self)
return p .. "-" .. self.sid
end
function proto.opkg_package(self)
return p
end
function proto.is_installed(self)
return nixio.fs.access("/lib/network/" .. p .. ".sh")
end
function proto.is_floating(self)
return true
end
function proto.is_virtual(self)
return true
end
function proto.get_interfaces(self)
return nil
end
function proto.contains_interface(self, ifname)
return (netmod:ifnameof(ifc) == self:ifname())
end
netmod:register_pattern_virtual("^%s-%%w" % p)
end
|
--[[
LuCI - Network model - 6to4 & 6in4 protocol extension
Copyright 2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local netmod = luci.model.network
local _, p
for _, p in ipairs({"6in4", "6to4"}) do
local proto = netmod:register_protocol(p)
function proto.get_i18n(self)
if p == "6in4" then
return luci.i18n.translate("IPv6-in-IPv4 (RFC4213)")
elseif p == "6to4" then
return luci.i18n.translate("IPv6-over-IPv4")
end
end
function proto.ifname(self)
return p .. "-" .. self.sid
end
function proto.opkg_package(self)
return p
end
function proto.is_installed(self)
return nixio.fs.access("/lib/network/" .. p .. ".sh") or
nixio.fs.access("/lib/netifd/proto/" .. p .. ".sh")
end
function proto.is_floating(self)
return true
end
function proto.is_virtual(self)
return true
end
function proto.get_interfaces(self)
return nil
end
function proto.contains_interface(self, ifname)
return (netmod:ifnameof(ifc) == self:ifname())
end
netmod:register_pattern_virtual("^%s-%%w" % p)
end
|
protocols/6x4: fix install state detection with netifd
|
protocols/6x4: fix install state detection with netifd
|
Lua
|
apache-2.0
|
jorgifumi/luci,keyidadi/luci,cappiewu/luci,Sakura-Winkey/LuCI,jlopenwrtluci/luci,harveyhu2012/luci,zhaoxx063/luci,kuoruan/lede-luci,shangjiyu/luci-with-extra,Hostle/openwrt-luci-multi-user,981213/luci-1,ff94315/luci-1,artynet/luci,dwmw2/luci,deepak78/new-luci,thess/OpenWrt-luci,wongsyrone/luci-1,urueedi/luci,joaofvieira/luci,dismantl/luci-0.12,florian-shellfire/luci,ff94315/luci-1,shangjiyu/luci-with-extra,male-puppies/luci,oneru/luci,Noltari/luci,tcatm/luci,RedSnake64/openwrt-luci-packages,dismantl/luci-0.12,palmettos/test,981213/luci-1,aircross/OpenWrt-Firefly-LuCI,bright-things/ionic-luci,jorgifumi/luci,rogerpueyo/luci,nwf/openwrt-luci,tcatm/luci,marcel-sch/luci,deepak78/new-luci,rogerpueyo/luci,Hostle/openwrt-luci-multi-user,openwrt/luci,Sakura-Winkey/LuCI,david-xiao/luci,taiha/luci,wongsyrone/luci-1,kuoruan/lede-luci,remakeelectric/luci,joaofvieira/luci,aircross/OpenWrt-Firefly-LuCI,palmettos/test,bright-things/ionic-luci,LuttyYang/luci,marcel-sch/luci,ollie27/openwrt_luci,sujeet14108/luci,schidler/ionic-luci,keyidadi/luci,Kyklas/luci-proto-hso,cshore/luci,jchuang1977/luci-1,cshore/luci,nwf/openwrt-luci,Noltari/luci,LazyZhu/openwrt-luci-trunk-mod,marcel-sch/luci,deepak78/new-luci,Noltari/luci,db260179/openwrt-bpi-r1-luci,taiha/luci,dwmw2/luci,maxrio/luci981213,obsy/luci,palmettos/test,fkooman/luci,palmettos/cnLuCI,fkooman/luci,NeoRaider/luci,ollie27/openwrt_luci,mumuqz/luci,chris5560/openwrt-luci,mumuqz/luci,schidler/ionic-luci,hnyman/luci,ollie27/openwrt_luci,tobiaswaldvogel/luci,thesabbir/luci,aa65535/luci,Sakura-Winkey/LuCI,lcf258/openwrtcn,palmettos/cnLuCI,forward619/luci,nwf/openwrt-luci,david-xiao/luci,RedSnake64/openwrt-luci-packages,david-xiao/luci,oyido/luci,sujeet14108/luci,aircross/OpenWrt-Firefly-LuCI,taiha/luci,LazyZhu/openwrt-luci-trunk-mod,remakeelectric/luci,bright-things/ionic-luci,Hostle/openwrt-luci-multi-user,thess/OpenWrt-luci,openwrt/luci,kuoruan/luci,deepak78/new-luci,jorgifumi/luci,obsy/luci,Sakura-Winkey/LuCI,teslamint/luci,jlopenwrtluci/luci,ReclaimYourPrivacy/cloak-luci,tcatm/luci,cappiewu/luci,cshore-firmware/openwrt-luci,artynet/luci,tobiaswaldvogel/luci,kuoruan/luci,shangjiyu/luci-with-extra,chris5560/openwrt-luci,jlopenwrtluci/luci,db260179/openwrt-bpi-r1-luci,kuoruan/luci,openwrt/luci,dwmw2/luci,bittorf/luci,RedSnake64/openwrt-luci-packages,thesabbir/luci,lcf258/openwrtcn,teslamint/luci,Kyklas/luci-proto-hso,bright-things/ionic-luci,kuoruan/luci,openwrt-es/openwrt-luci,jorgifumi/luci,rogerpueyo/luci,aa65535/luci,obsy/luci,oneru/luci,joaofvieira/luci,kuoruan/lede-luci,Noltari/luci,LuttyYang/luci,981213/luci-1,lcf258/openwrtcn,Kyklas/luci-proto-hso,nwf/openwrt-luci,male-puppies/luci,thess/OpenWrt-luci,dismantl/luci-0.12,sujeet14108/luci,cshore-firmware/openwrt-luci,obsy/luci,Hostle/luci,keyidadi/luci,hnyman/luci,aircross/OpenWrt-Firefly-LuCI,LazyZhu/openwrt-luci-trunk-mod,rogerpueyo/luci,remakeelectric/luci,openwrt/luci,jchuang1977/luci-1,cshore/luci,wongsyrone/luci-1,oyido/luci,cshore-firmware/openwrt-luci,harveyhu2012/luci,aa65535/luci,chris5560/openwrt-luci,jorgifumi/luci,obsy/luci,joaofvieira/luci,ReclaimYourPrivacy/cloak-luci,bittorf/luci,mumuqz/luci,shangjiyu/luci-with-extra,thesabbir/luci,RuiChen1113/luci,male-puppies/luci,oneru/luci,zhaoxx063/luci,taiha/luci,schidler/ionic-luci,daofeng2015/luci,male-puppies/luci,cappiewu/luci,dismantl/luci-0.12,opentechinstitute/luci,aircross/OpenWrt-Firefly-LuCI,ReclaimYourPrivacy/cloak-luci,harveyhu2012/luci,MinFu/luci,david-xiao/luci,cshore/luci,Kyklas/luci-proto-hso,aa65535/luci,palmettos/test,RuiChen1113/luci,cshore/luci,ReclaimYourPrivacy/cloak-luci,forward619/luci,taiha/luci,teslamint/luci,jchuang1977/luci-1,ff94315/luci-1,db260179/openwrt-bpi-r1-luci,mumuqz/luci,aa65535/luci,Wedmer/luci,LuttyYang/luci,nmav/luci,bittorf/luci,slayerrensky/luci,MinFu/luci,Wedmer/luci,thess/OpenWrt-luci,obsy/luci,joaofvieira/luci,dwmw2/luci,LuttyYang/luci,florian-shellfire/luci,tobiaswaldvogel/luci,nmav/luci,ReclaimYourPrivacy/cloak-luci,Hostle/openwrt-luci-multi-user,chris5560/openwrt-luci,NeoRaider/luci,forward619/luci,florian-shellfire/luci,ReclaimYourPrivacy/cloak-luci,tobiaswaldvogel/luci,marcel-sch/luci,daofeng2015/luci,kuoruan/lede-luci,dwmw2/luci,cshore/luci,dismantl/luci-0.12,oyido/luci,wongsyrone/luci-1,tcatm/luci,cappiewu/luci,kuoruan/lede-luci,schidler/ionic-luci,fkooman/luci,ReclaimYourPrivacy/cloak-luci,artynet/luci,shangjiyu/luci-with-extra,teslamint/luci,cshore-firmware/openwrt-luci,keyidadi/luci,LazyZhu/openwrt-luci-trunk-mod,marcel-sch/luci,lcf258/openwrtcn,Sakura-Winkey/LuCI,urueedi/luci,db260179/openwrt-bpi-r1-luci,hnyman/luci,Hostle/luci,Kyklas/luci-proto-hso,deepak78/new-luci,remakeelectric/luci,Hostle/luci,jlopenwrtluci/luci,forward619/luci,sujeet14108/luci,kuoruan/lede-luci,thesabbir/luci,hnyman/luci,zhaoxx063/luci,schidler/ionic-luci,bittorf/luci,deepak78/new-luci,urueedi/luci,nwf/openwrt-luci,tcatm/luci,thesabbir/luci,rogerpueyo/luci,NeoRaider/luci,Wedmer/luci,Hostle/openwrt-luci-multi-user,lbthomsen/openwrt-luci,oyido/luci,palmettos/cnLuCI,keyidadi/luci,fkooman/luci,Wedmer/luci,lbthomsen/openwrt-luci,mumuqz/luci,lbthomsen/openwrt-luci,palmettos/test,981213/luci-1,ReclaimYourPrivacy/cloak-luci,openwrt-es/openwrt-luci,Hostle/luci,lbthomsen/openwrt-luci,bright-things/ionic-luci,thess/OpenWrt-luci,taiha/luci,ff94315/luci-1,kuoruan/lede-luci,wongsyrone/luci-1,thesabbir/luci,florian-shellfire/luci,ollie27/openwrt_luci,openwrt-es/openwrt-luci,remakeelectric/luci,oneru/luci,fkooman/luci,keyidadi/luci,ollie27/openwrt_luci,openwrt-es/openwrt-luci,RuiChen1113/luci,palmettos/cnLuCI,artynet/luci,MinFu/luci,Kyklas/luci-proto-hso,jlopenwrtluci/luci,opentechinstitute/luci,lcf258/openwrtcn,bittorf/luci,rogerpueyo/luci,jorgifumi/luci,Noltari/luci,forward619/luci,jchuang1977/luci-1,RedSnake64/openwrt-luci-packages,Noltari/luci,MinFu/luci,wongsyrone/luci-1,lbthomsen/openwrt-luci,fkooman/luci,dwmw2/luci,florian-shellfire/luci,openwrt/luci,MinFu/luci,opentechinstitute/luci,maxrio/luci981213,tobiaswaldvogel/luci,obsy/luci,maxrio/luci981213,RedSnake64/openwrt-luci-packages,RedSnake64/openwrt-luci-packages,db260179/openwrt-bpi-r1-luci,jchuang1977/luci-1,cshore-firmware/openwrt-luci,RuiChen1113/luci,male-puppies/luci,opentechinstitute/luci,Noltari/luci,RuiChen1113/luci,palmettos/cnLuCI,LazyZhu/openwrt-luci-trunk-mod,daofeng2015/luci,hnyman/luci,Hostle/openwrt-luci-multi-user,bright-things/ionic-luci,db260179/openwrt-bpi-r1-luci,zhaoxx063/luci,NeoRaider/luci,palmettos/cnLuCI,shangjiyu/luci-with-extra,david-xiao/luci,forward619/luci,nmav/luci,fkooman/luci,LazyZhu/openwrt-luci-trunk-mod,opentechinstitute/luci,cappiewu/luci,zhaoxx063/luci,keyidadi/luci,ff94315/luci-1,joaofvieira/luci,joaofvieira/luci,dwmw2/luci,tobiaswaldvogel/luci,cshore-firmware/openwrt-luci,981213/luci-1,ff94315/luci-1,cappiewu/luci,maxrio/luci981213,LazyZhu/openwrt-luci-trunk-mod,nmav/luci,maxrio/luci981213,jorgifumi/luci,deepak78/new-luci,LuttyYang/luci,deepak78/new-luci,daofeng2015/luci,dismantl/luci-0.12,oneru/luci,Hostle/openwrt-luci-multi-user,mumuqz/luci,slayerrensky/luci,nmav/luci,palmettos/test,maxrio/luci981213,jorgifumi/luci,slayerrensky/luci,ollie27/openwrt_luci,oyido/luci,Hostle/luci,slayerrensky/luci,981213/luci-1,nmav/luci,openwrt-es/openwrt-luci,zhaoxx063/luci,slayerrensky/luci,taiha/luci,male-puppies/luci,schidler/ionic-luci,artynet/luci,lcf258/openwrtcn,nwf/openwrt-luci,RuiChen1113/luci,oyido/luci,nwf/openwrt-luci,marcel-sch/luci,mumuqz/luci,Wedmer/luci,jlopenwrtluci/luci,thesabbir/luci,sujeet14108/luci,teslamint/luci,marcel-sch/luci,urueedi/luci,obsy/luci,lbthomsen/openwrt-luci,rogerpueyo/luci,sujeet14108/luci,remakeelectric/luci,shangjiyu/luci-with-extra,teslamint/luci,urueedi/luci,Wedmer/luci,sujeet14108/luci,Kyklas/luci-proto-hso,male-puppies/luci,Noltari/luci,cshore-firmware/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,daofeng2015/luci,remakeelectric/luci,jlopenwrtluci/luci,jchuang1977/luci-1,oneru/luci,openwrt/luci,Noltari/luci,bittorf/luci,tobiaswaldvogel/luci,Sakura-Winkey/LuCI,slayerrensky/luci,opentechinstitute/luci,RuiChen1113/luci,nmav/luci,schidler/ionic-luci,ff94315/luci-1,dwmw2/luci,aa65535/luci,oneru/luci,harveyhu2012/luci,bittorf/luci,lcf258/openwrtcn,cshore/luci,jchuang1977/luci-1,MinFu/luci,lbthomsen/openwrt-luci,artynet/luci,LuttyYang/luci,keyidadi/luci,zhaoxx063/luci,oyido/luci,marcel-sch/luci,aa65535/luci,kuoruan/lede-luci,jchuang1977/luci-1,cappiewu/luci,NeoRaider/luci,cshore-firmware/openwrt-luci,taiha/luci,LuttyYang/luci,ollie27/openwrt_luci,david-xiao/luci,thess/OpenWrt-luci,bittorf/luci,teslamint/luci,forward619/luci,david-xiao/luci,thess/OpenWrt-luci,MinFu/luci,tcatm/luci,palmettos/cnLuCI,MinFu/luci,981213/luci-1,slayerrensky/luci,joaofvieira/luci,slayerrensky/luci,nmav/luci,harveyhu2012/luci,artynet/luci,artynet/luci,nwf/openwrt-luci,urueedi/luci,bright-things/ionic-luci,maxrio/luci981213,harveyhu2012/luci,david-xiao/luci,lbthomsen/openwrt-luci,lcf258/openwrtcn,daofeng2015/luci,db260179/openwrt-bpi-r1-luci,Wedmer/luci,openwrt/luci,hnyman/luci,Hostle/luci,tcatm/luci,db260179/openwrt-bpi-r1-luci,oyido/luci,thess/OpenWrt-luci,chris5560/openwrt-luci,kuoruan/luci,sujeet14108/luci,aa65535/luci,openwrt-es/openwrt-luci,Hostle/luci,remakeelectric/luci,RuiChen1113/luci,aircross/OpenWrt-Firefly-LuCI,palmettos/test,chris5560/openwrt-luci,shangjiyu/luci-with-extra,bright-things/ionic-luci,daofeng2015/luci,dismantl/luci-0.12,NeoRaider/luci,cshore/luci,nmav/luci,wongsyrone/luci-1,LuttyYang/luci,tobiaswaldvogel/luci,harveyhu2012/luci,hnyman/luci,maxrio/luci981213,RedSnake64/openwrt-luci-packages,florian-shellfire/luci,Hostle/openwrt-luci-multi-user,kuoruan/luci,cappiewu/luci,Sakura-Winkey/LuCI,LazyZhu/openwrt-luci-trunk-mod,opentechinstitute/luci,Sakura-Winkey/LuCI,urueedi/luci,NeoRaider/luci,kuoruan/luci,opentechinstitute/luci,jlopenwrtluci/luci,palmettos/cnLuCI,openwrt-es/openwrt-luci,fkooman/luci,openwrt/luci,chris5560/openwrt-luci,lcf258/openwrtcn,hnyman/luci,lcf258/openwrtcn,florian-shellfire/luci,kuoruan/luci,palmettos/test,Hostle/luci,mumuqz/luci,NeoRaider/luci,Wedmer/luci,ollie27/openwrt_luci,forward619/luci,oneru/luci,rogerpueyo/luci,urueedi/luci,teslamint/luci,tcatm/luci,male-puppies/luci,daofeng2015/luci,ff94315/luci-1,florian-shellfire/luci,schidler/ionic-luci,wongsyrone/luci-1,zhaoxx063/luci,thesabbir/luci,openwrt-es/openwrt-luci,artynet/luci,chris5560/openwrt-luci
|
215f10b32bd4a36a8fc1a169ba0e425dc39ae22c
|
libs/core/luasrc/model/wireless.lua
|
libs/core/luasrc/model/wireless.lua
|
--[[
LuCI - Wireless model
Copyright 2009 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local pairs, i18n, uci, math = pairs, luci.i18n, luci.model.uci, math
local iwi = require "iwinfo"
local utl = require "luci.util"
local uct = require "luci.model.uci.bind"
module "luci.model.network.wireless"
local ub = uct.bind("wireless")
local st, ifs
function init(self, cursor)
cursor:unload("wireless")
cursor:load("wireless")
ub:init(cursor)
st = uci.cursor_state()
ifs = { }
local count = 0
ub.uci:foreach("wireless", "wifi-iface",
function(s)
count = count + 1
local id = "%s.network%d" %{ self.device, count }
ifs[id] = {
id = id,
sid = s['.name'],
count = count
}
local dev = st:get("wireless", s['.name'], "ifname")
or st:get("wireless", s['.name'], "device")
local wtype = dev and iwi.type(dev)
if dev and wtype then
ifs[id].winfo = iwi[wtype]
ifs[id].wdev = dev
end
end)
end
function get_device(self, dev)
return device(dev)
end
function get_network(self, id)
if ifs[id] then
return network(ifs[id].sid)
else
local n
for n, _ in pairs(ifs) do
if ifs[n].sid == id then
return network(id)
end
end
end
end
function shortname(self, iface)
if iface.dev and iface.dev.wifi then
return "%s %q" %{
i18n.translate("a_s_if_iwmode_" .. (iface.dev.wifi.mode or "ap")),
iface.dev.wifi.ssid or iface.dev.wifi.bssid or "(hidden)"
}
else
return iface:name()
end
end
function get_i18n(self, iface)
if iface.dev and iface.dev.wifi then
return "%s: %s %q" %{
i18n.translate("a_s_if_wifinet", "Wireless Network"),
i18n.translate("a_s_if_iwmode_" .. (iface.dev.wifi.mode or "ap"), iface.dev.wifi.mode or "AP"),
iface.dev.wifi.ssid or iface.dev.wifi.bssid or "(hidden)"
}
else
return "%s: %q" %{ i18n.translate("a_s_if_wifinet", "Wireless Network"), iface:name() }
end
end
function rename_network(self, old, new)
local i
for i, _ in pairs(ifs) do
if ifs[i].network == old then
ifs[i].network = new
end
end
ub.uci:foreach("wireless", "wifi-iface",
function(s)
if s.network == old then
if new then
ub.uci:set("wireless", s['.name'], "network", new)
else
ub.uci:delete("wireless", s['.name'], "network")
end
end
end)
end
function del_network(self, old)
return self:rename_network(old, nil)
end
function find_interfaces(self, iflist, brlist)
local iface
for iface, _ in pairs(ifs) do
iflist[iface] = ifs[iface]
end
end
function ignore_interface(self, iface)
if ifs and ifs[iface] then
return false
else
return iwi.type(iface) and true or false
end
end
function add_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:set("wireless", ifs[iface].sid, "network", net:name())
ifs[iface].network = net:name()
return true
end
return false
end
function del_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:delete("wireless", ifs[iface].sid, "network")
--return true
end
return false
end
device = ub:section("wifi-device")
device:property("type")
device:property("channel")
device:property("disabled")
function device.name(self)
return self.sid
end
function device.get_networks(self)
local nets = { }
ub.uci:foreach("wireless", "wifi-iface",
function(s)
if s.device == self:name() then
nets[#nets+1] = network(s['.name'])
end
end)
return nets
end
network = ub:section("wifi-iface")
network:property("mode")
network:property("ssid")
network:property("bssid")
network:property("network")
function network._init(self, sid)
local count = 0
ub.uci:foreach("wireless", "wifi-iface",
function(s)
count = count + 1
return s['.name'] ~= sid
end)
self.id = "%s.network%d" %{ self.device, count }
local dev = st:get("wireless", sid, "ifname")
or st:get("wireless", sid, "device")
local wtype = dev and iwi.type(dev)
if dev and wtype then
self.winfo = iwi[wtype]
self.wdev = dev
end
end
function network.name(self)
return self.id
end
function network.ifname(self)
return self.wdev
end
function network.get_device(self)
if self.device then
return device(self.device)
end
end
function network.active_mode(self)
local m = self.winfo and self.winfo.mode(self.wdev)
if m == "Master" or m == "Auto" then
m = "ap"
elseif m == "Ad-Hoc" then
m = "adhoc"
elseif m == "Client" then
m = "sta"
elseif m then
m = m:lower()
else
m = self:mode()
end
return m or "ap"
end
function network.active_mode_i18n(self)
return i18n.translate("a_s_if_iwmode_" .. self:active_mode())
end
function network.active_ssid(self)
return self.winfo and self.winfo.ssid(self.wdev) or
self:ssid()
end
function network.active_bssid(self)
return self.winfo and self.winfo.bssid(self.wdev) or
self:bssid() or "00:00:00:00:00:00"
end
function network.signal(self)
return self.winfo and self.winfo.signal(self.wdev) or 0
end
function network.noise(self)
return self.winfo and self.winfo.noise(self.wdev) or 0
end
function network.signal_level(self)
if self:active_bssid() ~= "00:00:00:00:00:00" then
local signal = self:signal()
local noise = self:noise()
if signal > 0 and noise > 0 then
local snr = -1 * (noise - signal)
return math.floor(snr / 5)
else
return 0
end
else
return -1
end
end
function network.signal_percent(self)
local qc = self.winfo and
self.winfo.quality(self.wdev) or 0
local qm = self.winfo and
self.winfo.quality_max(self.wdev) or 0
if qc > 0 and qm > 0 then
return math.floor((100 / qm) * qc)
else
return 0
end
end
|
--[[
LuCI - Wireless model
Copyright 2009 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local pairs, i18n, uci, math = pairs, luci.i18n, luci.model.uci, math
local iwi = require "iwinfo"
local utl = require "luci.util"
local uct = require "luci.model.uci.bind"
module "luci.model.wireless"
local ub = uct.bind("wireless")
local st, ifs
function init(cursor)
cursor:unload("wireless")
cursor:load("wireless")
ub:init(cursor)
st = uci.cursor_state()
ifs = { }
local count = 0
ub.uci:foreach("wireless", "wifi-iface",
function(s)
count = count + 1
local id = "%s.network%d" %{ s.device, count }
ifs[id] = {
id = id,
sid = s['.name'],
count = count
}
local dev = st:get("wireless", s['.name'], "ifname")
or st:get("wireless", s['.name'], "device")
local wtype = dev and iwi.type(dev)
if dev and wtype then
ifs[id].winfo = iwi[wtype]
ifs[id].wdev = dev
end
end)
end
function get_device(self, dev)
return device(dev)
end
function get_network(self, id)
if ifs[id] then
return network(ifs[id].sid)
else
local n
for n, _ in pairs(ifs) do
if ifs[n].sid == id then
return network(id)
end
end
end
end
function shortname(self, iface)
if iface.wdev and iface.winfo then
return "%s %q" %{
i18n.translate("a_s_if_iwmode_" .. iface:active_mode(), iface.winfo.mode(iface.wdev)),
iface:active_ssid() or "(hidden)"
}
else
return iface:name()
end
end
function get_i18n(self, iface)
if iface.wdev and iface.winfo then
return "%s: %s %q (%s)" %{
i18n.translate("a_s_if_wifinet", "Wireless Network"),
i18n.translate("a_s_if_iwmode_" .. iface:active_mode(), iface.winfo.mode(iface.wdev)),
iface:active_ssid() or "(hidden)", iface.wdev
}
else
return "%s: %q" %{ i18n.translate("a_s_if_wifinet", "Wireless Network"), iface:name() }
end
end
function rename_network(self, old, new)
local i
for i, _ in pairs(ifs) do
if ifs[i].network == old then
ifs[i].network = new
end
end
ub.uci:foreach("wireless", "wifi-iface",
function(s)
if s.network == old then
if new then
ub.uci:set("wireless", s['.name'], "network", new)
else
ub.uci:delete("wireless", s['.name'], "network")
end
end
end)
end
function del_network(self, old)
return self:rename_network(old, nil)
end
function find_interfaces(self, iflist, brlist)
local iface
for iface, _ in pairs(ifs) do
iflist[iface] = ifs[iface]
end
end
function ignore_interface(self, iface)
if ifs and ifs[iface] then
return false
else
return iwi.type(iface) and true or false
end
end
function add_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:set("wireless", ifs[iface].sid, "network", net:name())
ifs[iface].network = net:name()
return true
end
return false
end
function del_interface(self, net, iface)
if ifs and ifs[iface] and ifs[iface].sid then
ub.uci:delete("wireless", ifs[iface].sid, "network")
--return true
end
return false
end
device = ub:section("wifi-device")
device:property("type")
device:property("channel")
device:property("disabled")
function device.name(self)
return self.sid
end
function device.get_networks(self)
local nets = { }
ub.uci:foreach("wireless", "wifi-iface",
function(s)
if s.device == self:name() then
nets[#nets+1] = network(s['.name'])
end
end)
return nets
end
network = ub:section("wifi-iface")
network:property("mode")
network:property("ssid")
network:property("bssid")
network:property("network")
function network._init(self, sid)
local count = 0
ub.uci:foreach("wireless", "wifi-iface",
function(s)
count = count + 1
return s['.name'] ~= sid
end)
local dev = st:get("wireless", sid, "ifname")
or st:get("wireless", sid, "device")
if dev then
self.id = "%s.network%d" %{ dev, count }
local wtype = iwi.type(dev)
if dev and wtype then
self.winfo = iwi[wtype]
self.wdev = dev
end
end
end
function network.name(self)
return self.id
end
function network.ifname(self)
return self.wdev
end
function network.get_device(self)
if self.device then
return device(self.device)
end
end
function network.active_mode(self)
local m = self.winfo and self.winfo.mode(self.wdev)
if m == "Master" or m == "Auto" then
m = "ap"
elseif m == "Ad-Hoc" then
m = "adhoc"
elseif m == "Client" then
m = "sta"
elseif m then
m = m:lower()
else
m = self:mode()
end
return m or "ap"
end
function network.active_mode_i18n(self)
return i18n.translate("a_s_if_iwmode_" .. self:active_mode())
end
function network.active_ssid(self)
return self.winfo and self.winfo.ssid(self.wdev) or
self:ssid()
end
function network.active_bssid(self)
return self.winfo and self.winfo.bssid(self.wdev) or
self:bssid() or "00:00:00:00:00:00"
end
function network.signal(self)
return self.winfo and self.winfo.signal(self.wdev) or 0
end
function network.noise(self)
return self.winfo and self.winfo.noise(self.wdev) or 0
end
function network.signal_level(self)
if self:active_bssid() ~= "00:00:00:00:00:00" then
local signal = self:signal()
local noise = self:noise()
if signal > 0 and noise > 0 then
local snr = -1 * (noise - signal)
return math.floor(snr / 5)
else
return 0
end
else
return -1
end
end
function network.signal_percent(self)
local qc = self.winfo and
self.winfo.quality(self.wdev) or 0
local qm = self.winfo and
self.winfo.quality_max(self.wdev) or 0
if qc > 0 and qm > 0 then
return math.floor((100 / qm) * qc)
else
return 0
end
end
|
libs/core: fixes luci.model.wireless
|
libs/core: fixes luci.model.wireless
git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5438 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
|
Lua
|
apache-2.0
|
phi-psi/luci,Canaan-Creative/luci,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,8devices/carambola2-luci,zwhfly/openwrt-luci,8devices/carambola2-luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci,8devices/carambola2-luci,stephank/luci,ch3n2k/luci,Canaan-Creative/luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,gwlim/luci,ThingMesh/openwrt-luci,projectbismark/luci-bismark,Canaan-Creative/luci,8devices/carambola2-luci,Flexibity/luci,projectbismark/luci-bismark,jschmidlapp/luci,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,stephank/luci,jschmidlapp/luci,freifunk-gluon/luci,gwlim/luci,stephank/luci,projectbismark/luci-bismark,projectbismark/luci-bismark,freifunk-gluon/luci,vhpham80/luci,dtaht/cerowrt-luci-3.3,Flexibity/luci,stephank/luci,dtaht/cerowrt-luci-3.3,jschmidlapp/luci,projectbismark/luci-bismark,vhpham80/luci,Canaan-Creative/luci,freifunk-gluon/luci,zwhfly/openwrt-luci,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,ch3n2k/luci,ThingMesh/openwrt-luci,gwlim/luci,zwhfly/openwrt-luci,8devices/carambola2-luci,projectbismark/luci-bismark,jschmidlapp/luci,Flexibity/luci,eugenesan/openwrt-luci,phi-psi/luci,eugenesan/openwrt-luci,8devices/carambola2-luci,yeewang/openwrt-luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,yeewang/openwrt-luci,jschmidlapp/luci,dtaht/cerowrt-luci-3.3,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,Canaan-Creative/luci,yeewang/openwrt-luci,ch3n2k/luci,stephank/luci,yeewang/openwrt-luci,jschmidlapp/luci,saraedum/luci-packages-old,Canaan-Creative/luci,jschmidlapp/luci,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,Flexibity/luci,gwlim/luci,phi-psi/luci,vhpham80/luci,ch3n2k/luci,saraedum/luci-packages-old,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,gwlim/luci,saraedum/luci-packages-old,Flexibity/luci,Canaan-Creative/luci,vhpham80/luci,phi-psi/luci,Flexibity/luci,freifunk-gluon/luci,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,ReclaimYourPrivacy/cloak-luci,freifunk-gluon/luci,zwhfly/openwrt-luci,vhpham80/luci,yeewang/openwrt-luci,phi-psi/luci,saraedum/luci-packages-old,yeewang/openwrt-luci,gwlim/luci,phi-psi/luci,Flexibity/luci,zwhfly/openwrt-luci,ch3n2k/luci,freifunk-gluon/luci,projectbismark/luci-bismark,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,zwhfly/openwrt-luci,ch3n2k/luci,phi-psi/luci,ThingMesh/openwrt-luci,jschmidlapp/luci,freifunk-gluon/luci,Flexibity/luci,eugenesan/openwrt-luci,Canaan-Creative/luci,stephank/luci,zwhfly/openwrt-luci,ch3n2k/luci,8devices/carambola2-luci,projectbismark/luci-bismark,dtaht/cerowrt-luci-3.3
|
dca8f045205a24c0263fe93a7f15cf1af9e78c2f
|
tools/pulldefs.lua
|
tools/pulldefs.lua
|
-- A slightly hacky way of pulling FFI definitions.
local args = {...}
print("local ffi = require(\"ffi\")")
print("ffi.cdef [[")
local constants = {}
local previousstate = "none" -- for debugging.
local state = "waiting"
local state_targetenum = nil
local state_enumindex = nil
local state_enumconstname = nil
-- reaction = {"nextState", optFunction}
-- Note that the state change happens before the function runs, so it can be overridden.
-- The function is called with the token.
-- state = {["tokenText"] = reaction, [0] = reaction}
-- state_machine = {["name"] = state}
local function generate_error(e)
return function ()
error(e)
end
end
local state_machine = {
["waiting"] = {
["enum"] = {"grab_enum_name"},
["typedef"] = {"type_check"},
[0] = {"wait_for_semicolon"},
},
["wait_for_semicolon"] = {
[";"] = {"waiting"},
[0] = {"wait_for_semicolon"},
},
["type_check"] = {
["enum"] = {"grab_enum_name"},
[0] = {"wait_for_semicolon"},
},
["grab_enum_name"] = {
["{"] = {"read_enum_constant_name", function ()
state_targetenum = {}
end},
[0] = {"read_enum_start", function (tkn)
state_targetenum = {}
constants[tkn] = state_targetenum
end},
},
-- state_targetenum must be initialized by this point
["read_enum_start"] = {
["{"] = {"read_enum_constant_name"},
[0] = {"", generate_error("Unexpected non-{ during enum reading.")},
},
["read_enum_constant_name"] = {
["{"] = {"", generate_error("Unexpected { during enum reading.")},
["}"] = {"enum_epilogue"},
[0] = {"read_enum_equals", function (tkn)
state_enumconstname = tkn
end}
},
["read_enum_equals"] = {
["="] = {"read_enum_constant_val"},
["}"] = {"enum_epilogue", function (tkn)
state_targetenum[state_enumconstname] = state_enumindex
end},
[","] = {"read_enum_constant_name", function (tkn)
state_targetenum[state_enumconstname] = state_enumindex
state_enumindex = state_enumindex + 1
end},
[0] = {"", generate_error("Unexpected token after enum constant name")}
},
["read_enum_constant_val"] = {
[0] = {"read_enum_constant_comma", function (tkn)
local n = tonumber(tkn)
if not n then error("Value not number: " .. tkn) end
state_targetenum[state_enumconstname] = state_enumindex
state_enumindex = n
end},
},
["read_enum_constant_comma"] = {
["}"] = {"enum_epilogue"},
[","] = {"read_enum_constant_name"},
[0] = {"", generate_error("Unexpected token inside enum in place of comma or epilogue")},
},
["enum_epilogue"] = {
[";"] = {"waiting"},
[0] = {"wait_for_semicolon", function (tkn)
constants[tkn] = state_targetenum
end},
},
}
local function submit_token(tkn, meaning)
if tkn == "" then return end
if meaning == "ws" then return end
local cstate = state_machine[state]
local reaction = cstate[tkn]
if not reaction then
reaction = cstate[0]
end
if not reaction then
error("State machine could not handle default @ " .. state)
end
local oldstate = state
state = reaction[1]
if reaction[2] then
local ok, e = pcall(reaction[2], tkn)
if not ok then
error("Failure in state " .. oldstate .. ", previously " .. previousstate .. ", token '" .. tkn .. "': " .. e)
end
end
previousstate = oldstate
end
local splitters = {
[" "] = "ws",
["\t"] = "ws",
["\r"] = "ws",
["\n"] = "ws",
["{"] = true,
["}"] = true,
["("] = true,
[")"] = true,
["*"] = true,
[","] = true,
[";"] = true,
["["] = true,
["]"] = true,
}
local function tokenize_line(line)
local token_start = 1
for i = 1, line:len() do
local meaning = splitters[line:sub(i, i)]
if meaning then
submit_token(line:sub(token_start, i - 1), false)
submit_token(line:sub(i, i), meaning)
token_start = i + 1
end
end
submit_token(line:sub(token_start), false)
end
local function end_file()
print("]]")
print("return {")
for k, v in pairs(constants) do
print("\t[\"" .. k .. "\"] = {")
for k, v in pairs(v) do
print("\t\t[\"" .. k .. "\"] = " .. v .. ",")
end
print("\t},")
end
print("}")
if state == "wait_for_semicolon" then
io.stderr:write("pulldefs.lua: Warning: stopped while waiting for a semicolon. Check state machine & tokenization logic.\n")
end
end
local allow = false
while true do
local l = io.read()
if not l then
end_file()
return
end
if l:sub(1, 1) == "#" then
local s = l:find("\"")
if not s then
error("Unknown preprocessor -> compiler directive.")
end
local f = l:sub(s + 1)
f = f:sub(1, f:find("\"") - 1)
allow = (f:sub(1, args[1]:len()) == args[1])
else
if not l:find("^[ \t\r\n]*$") then
if allow then
print(l)
tokenize_line(l)
end
end
end
end
|
-- A slightly hacky way of pulling FFI definitions.
local args = {...}
print("local ffi = require(\"ffi\")")
print("ffi.cdef [[")
local constants = {}
local previousstate = "none" -- for debugging.
local state = "waiting"
local state_targetenum = nil
local state_enumindex = nil
local state_enumconstname = nil
-- reaction = {"nextState", optFunction}
-- Note that the state change happens before the function runs, so it can be overridden.
-- The function is called with the token.
-- state = {["tokenText"] = reaction, [0] = reaction}
-- state_machine = {["name"] = state}
local function generate_error(e)
return function ()
error(e)
end
end
local state_machine = {
["waiting"] = {
["enum"] = {"grab_enum_name"},
["typedef"] = {"type_check"},
[0] = {"wait_for_semicolon"},
},
["wait_for_semicolon"] = {
[";"] = {"waiting"},
[0] = {"wait_for_semicolon"},
},
["type_check"] = {
["enum"] = {"grab_enum_name"},
[0] = {"wait_for_semicolon"},
},
["grab_enum_name"] = {
["{"] = {"read_enum_constant_name", function ()
state_targetenum = {}
end},
[0] = {"read_enum_start", function (tkn)
state_targetenum = {}
constants[tkn] = state_targetenum
end},
},
-- state_targetenum must be initialized by this point
["read_enum_start"] = {
["{"] = {"read_enum_constant_name"},
[0] = {"", generate_error("Unexpected non-{ during enum reading.")},
},
["read_enum_constant_name"] = {
["{"] = {"", generate_error("Unexpected { during enum reading.")},
["}"] = {"enum_epilogue"},
[0] = {"read_enum_equals", function (tkn)
state_enumconstname = tkn
end}
},
["read_enum_equals"] = {
["="] = {"read_enum_constant_val"},
["}"] = {"enum_epilogue", function (tkn)
state_targetenum[state_enumconstname] = state_enumindex
end},
[","] = {"read_enum_constant_name", function (tkn)
state_targetenum[state_enumconstname] = state_enumindex
state_enumindex = state_enumindex + 1
end},
[0] = {"", generate_error("Unexpected token after enum constant name")}
},
["read_enum_constant_val"] = {
[0] = {"read_enum_constant_comma", function (tkn)
local n = tonumber(tkn)
if not n then error("Value not number: " .. tkn) end
state_targetenum[state_enumconstname] = n
state_enumindex = n
end},
},
["read_enum_constant_comma"] = {
["}"] = {"enum_epilogue"},
[","] = {"read_enum_constant_name"},
[0] = {"", generate_error("Unexpected token inside enum in place of comma or epilogue")},
},
["enum_epilogue"] = {
[";"] = {"waiting"},
[0] = {"wait_for_semicolon", function (tkn)
constants[tkn] = state_targetenum
state_enumindex = nil
end},
},
}
local function submit_token(tkn, meaning)
if tkn == "" then return end
if meaning == "ws" then return end
local cstate = state_machine[state]
local reaction = cstate[tkn]
if not reaction then
reaction = cstate[0]
end
if not reaction then
error("State machine could not handle default @ " .. state)
end
local oldstate = state
state = reaction[1]
if reaction[2] then
local ok, e = pcall(reaction[2], tkn)
if not ok then
error("Failure in state " .. oldstate .. ", previously " .. previousstate .. ", token '" .. tkn .. "': " .. e)
end
end
previousstate = oldstate
end
local splitters = {
[" "] = "ws",
["\t"] = "ws",
["\r"] = "ws",
["\n"] = "ws",
["{"] = true,
["}"] = true,
["("] = true,
[")"] = true,
["*"] = true,
[","] = true,
[";"] = true,
["["] = true,
["]"] = true,
}
local function tokenize_line(line)
local token_start = 1
for i = 1, line:len() do
local meaning = splitters[line:sub(i, i)]
if meaning then
submit_token(line:sub(token_start, i - 1), false)
submit_token(line:sub(i, i), meaning)
token_start = i + 1
end
end
submit_token(line:sub(token_start), false)
end
local function end_file()
print("]]")
print("return {")
for k, v in pairs(constants) do
print("\t[\"" .. k .. "\"] = {")
for k, v in pairs(v) do
print("\t\t[\"" .. k .. "\"] = " .. v .. ",")
end
print("\t},")
end
print("}")
if state == "wait_for_semicolon" then
io.stderr:write("pulldefs.lua: Warning: stopped while waiting for a semicolon. Check state machine & tokenization logic.\n")
end
end
local allow = false
while true do
local l = io.read()
if not l then
end_file()
return
end
if l:sub(1, 1) == "#" then
local s = l:find("\"")
if not s then
error("Unknown preprocessor -> compiler directive.")
end
local f = l:sub(s + 1)
f = f:sub(1, f:find("\"") - 1)
allow = (f:sub(1, args[1]:len()) == args[1])
else
if not l:find("^[ \t\r\n]*$") then
if allow then
print(l)
tokenize_line(l)
end
end
end
end
|
Fix pulldefs enum values.
|
Fix pulldefs enum values.
whoops
|
Lua
|
mit
|
vifino/ljwm
|
08c72e62032810f8aad39a1132854d5079ad3364
|
src/assert.lua
|
src/assert.lua
|
local s = require 'say'
local __assertion_meta = {
__call = function(self, ...)
local state = self.state
local val = self.callback(state, ...)
local data_type = type(val)
if data_type == "boolean" then
if val ~= state.mod then
if state.mod then
error(s(self.positive_message, assert:format({...})) or "assertion failed!", 2)
else
error(s(self.negative_message, assert:format({...})) or "assertion failed!", 2)
end
else
return state
end
end
return val
end
}
local __state_meta = {
__call = function(self, payload, callback)
self.payload = payload or rawget(self, "payload")
if callback then callback(self) end
return self
end,
__index = function(self, key)
if rawget(self.parent, "modifier")[key] then
rawget(self.parent, "modifier")[key].state = self
return self(nil,
rawget(self.parent, "modifier")[key]
)
else
rawget(self.parent, "assertion")[key].state = self
return rawget(self.parent, "assertion")[key]
end
end
}
local obj = {
-- list of registered assertions
assertion = {},
state = function(obj) return setmetatable({mod=true, payload=nil, parent=obj}, __state_meta) end,
-- list of registered modifiers
modifier = {},
-- list of registered formatters
formatter = {},
-- registers a function in namespace
register = function(self, namespace, name, callback, positive_message, negative_message)
-- register
local lowername = name:lower()
if not self[namespace] then
self[namespace] = {}
end
self[namespace][lowername] = setmetatable({
callback = callback,
name = lowername,
positive_message=positive_message,
negative_message=negative_message
}, __assertion_meta)
end,
-- registers a formatter
-- a formatter takes a single argument, and converts it to a string, or returns nil if it cannot format the argument
addformatter = function(self, callback)
table.insert(self.formatter, callback)
end,
-- unregisters a formatter
removeformatter = function(self, formatter)
for i, v in ipairs(self.formatter) do
if v == formatter then
table.remove(self.formatter, i)
break
end
end
end,
format = function(self, args)
if #args == 0 then return end
for i, val in ipairs(args) do
local valfmt = nil
for n, fmt in ipairs(self.formatter) do
valfmt = fmt(val)
if valfmt ~= nil then break end
end
if valfmt == nil then valfmt = tostring(val) end -- no formatter found
args[i] = valfmt
end
return args
end
}
local __meta = {
__call = function(self, bool, message)
if not bool then
error(message or "assertion failed!", 2)
end
return bool
end,
__index = function(self, key) return self.state(self)[key] end,
}
return setmetatable(obj, __meta)
|
local s = require 'say'
local __assertion_meta = {
__call = function(self, ...)
local state = self.state
local val = self.callback(state, ...)
local data_type = type(val)
if data_type == "boolean" then
if val ~= state.mod then
if state.mod then
error(s(self.positive_message, assert:format({...})) or "assertion failed!", 2)
else
error(s(self.negative_message, assert:format({...})) or "assertion failed!", 2)
end
else
return state
end
end
return val
end
}
local __state_meta = {
__call = function(self, payload, callback)
self.payload = payload or rawget(self, "payload")
if callback then callback(self) end
return self
end,
__index = function(self, key)
if rawget(self.parent, "modifier")[key] then
rawget(self.parent, "modifier")[key].state = self
return self(nil,
rawget(self.parent, "modifier")[key]
)
elseif rawget(self.parent, "assertion")[key] then
rawget(self.parent, "assertion")[key].state = self
return rawget(self.parent, "assertion")[key]
else
error("luassert: unknown modifier/assertion: '" .. tostring(key).."'", 2)
end
end
}
local obj = {
-- list of registered assertions
assertion = {},
state = function(obj) return setmetatable({mod=true, payload=nil, parent=obj}, __state_meta) end,
-- list of registered modifiers
modifier = {},
-- list of registered formatters
formatter = {},
-- registers a function in namespace
register = function(self, namespace, name, callback, positive_message, negative_message)
-- register
local lowername = name:lower()
if not self[namespace] then
self[namespace] = {}
end
self[namespace][lowername] = setmetatable({
callback = callback,
name = lowername,
positive_message=positive_message,
negative_message=negative_message
}, __assertion_meta)
end,
-- registers a formatter
-- a formatter takes a single argument, and converts it to a string, or returns nil if it cannot format the argument
addformatter = function(self, callback)
table.insert(self.formatter, callback)
end,
-- unregisters a formatter
removeformatter = function(self, formatter)
for i, v in ipairs(self.formatter) do
if v == formatter then
table.remove(self.formatter, i)
break
end
end
end,
format = function(self, args)
if #args == 0 then return end
for i, val in ipairs(args) do
local valfmt = nil
for n, fmt in ipairs(self.formatter) do
valfmt = fmt(val)
if valfmt ~= nil then break end
end
if valfmt == nil then valfmt = tostring(val) end -- no formatter found
args[i] = valfmt
end
return args
end
}
local __meta = {
__call = function(self, bool, message)
if not bool then
error(message or "assertion failed!", 2)
end
return bool
end,
__index = function(self, key) return self.state(self)[key] end,
}
return setmetatable(obj, __meta)
|
Bugfix; when an unknown assertion/modifier is used, display a proper error message.
|
Bugfix; when an unknown assertion/modifier is used, display a proper error message.
Try: assert.this_does_not_exist.equal("hello","hello")
|
Lua
|
mit
|
tst2005/lua-luassert,o-lim/luassert,mpeterv/luassert,ZyX-I/luassert
|
3856ba6d21c4fde1e35b19c6d8c2dae3647d4e45
|
examples/asteroids.lua
|
examples/asteroids.lua
|
-- Simple Asteroids-alike game.
-- Copyright (C) 2012 Salvatore Sanfilippo.
-- This code is released under the BSD two-clause license.
function setup()
ticks = 0 -- Number of iteration of the program
shipx = WIDTH/2 -- Ship x position
shipy = HEIGHT/2 -- Ship y position
shipa = 0 -- Ship rotation angle
shipvx = 0 -- Ship x velocity
shipvy = 0 -- Ship y velocity
bullets = {} -- An array of bullets
asteroids = {} -- An array of asteroids
asteroids_num = 0; -- Number of asteroids on screen
asteroids_max = 2; -- Max number of asteroids to show
last_bullet_ticks = 0 -- Ticks at the time the last bullet was fired
-- Populate the game with asteroids at start
while(asteroids_num < asteroids_max) do
addAsteroid()
end
end
-- The following functions move objects adding the velocity
-- to the position at every iteration.
function moveShip()
shipx = (shipx + shipvx) % WIDTH
shipy = (shipy + shipvy) % HEIGHT
end
function moveBullets()
local i,b
for i,b in pairs(bullets) do
b.x = b.x+b.vx
b.y = b.y+b.vy
b.ttl = b.ttl - 1
if b.ttl == 0 then bullets[i] = nil end
end
end
function moveAsteroids()
local i,a
for i,a in pairs(asteroids) do
a.x = (a.x+a.vx) % WIDTH
a.y = (a.y+a.vy) % HEIGHT
end
end
-- Add an asteroid. Create a random asteroid so that it's
-- not too close to the ship.
function addAsteroid()
local x,y,a,ray
while true do
x = math.random(WIDTH)
y = math.random(HEIGHT)
ray = math.random(20,40)
if math.abs(x-shipx) > ray and
math.abs(y-shipy) > ray then
break
end
end
a = { x = x, y = y, vx = math.random(), vy = math.random(),
ray = ray }
table.insert(asteroids,a)
asteroids_num = asteroids_num + 1
end
-- Fire a bullet with velocity 2,2 and the same orientation
-- as the ship orientation.
function fire()
local b
-- Don't fire again if we already fired
-- less than 5 iterations ago.
if ticks - last_bullet_ticks < 5 then return end
b = { x = shipx, y = shipy,
vx = shipvx+(2*math.sin(shipa)),
vy = shipvy+(2*math.cos(shipa)),
ttl=300 }
table.insert(bullets,b)
last_bullet_ticks = ticks
end
-- Draw the screen, move objects, detect collisions.
function draw()
ticks = ticks+1
-- Handle keyboard events.
if keyboard.pressed['left'] then shipa = shipa - 0.05 end
if keyboard.pressed['right'] then shipa = shipa + 0.05 end
if keyboard.pressed['up'] then
shipvx = shipvx + 0.05*math.sin(shipa)
shipvy = shipvy + 0.05*math.cos(shipa)
end
if keyboard.pressed['space'] then fire() end
-- Create a new asteroid from time to time if needed
if asteroids_num < asteroids_max and (ticks % 500) == 0 then
while(asteroids_num < asteroids_max) do addAsteroid() end
end
-- Move all the objects of the game.
moveShip()
moveBullets()
moveAsteroids()
checkBulletCollision()
-- Draw the current game screen.
background(0,0,0)
drawBullets()
drawAsteroids()
drawShip(shipx,shipy,shipa)
end
-- Math formula to rotate a point counterclockwise, with
-- rotation center at 0,0.
function rotatePoint(x,y,a)
return x*math.cos(a)-y*math.sin(a),
y*math.cos(a)+x*math.sin(a)
end
-- Draw the ship, that is composed of three vertex,
-- rotating the vertexes using rotatePoint().
function drawShip(x,y,a)
local triangles = {}
table.insert(triangles,
{x0 = -10, y0 = -10, x1 = 0, y1 = 20, x2 = 10, y2 = -10,
r = 255, g = 0, b = 0, alpha = 1 })
if keyboard.pressed['up'] then
table.insert(triangles,
{x0 = -5, y0 = -10, x1 = 0, y1 = math.random(-25,-20), x2 = 5, y2 = -10,
r = 255, g = 255, b = 0, alpha = 1 })
end
for i,t in pairs(triangles) do
fill(t.r,t.g,t.b,t.alpha)
t.x0,t.y0 = rotatePoint(t.x0,t.y0,-a);
t.x1,t.y1 = rotatePoint(t.x1,t.y1,-a);
t.x2,t.y2 = rotatePoint(t.x2,t.y2,-a);
triangle(x+t.x0,y+t.y0,x+t.x1,y+t.y1,x+t.x2,y+t.y2)
end
end
-- Draw a bullet, that's just a single pixel.
function drawBullets()
local i,b
for i,b in pairs(bullets) do
fill(255,255,255,1)
rect(b.x,b.y,1,1)
end
end
-- Draw an asteroid.
function drawAsteroids()
local i,a
for i,a in pairs(asteroids) do
fill(150,150,150,1)
ellipse(a.x,a.y,a.ray,a.ray)
end
end
-- This function detects the collision between a bullet
-- and an asteroid, and removes both the bullet and the
-- asteroid from the game when they collide.
function checkBulletCollision()
local i,j,b,a,del_asteroids,del_bullets
del_asteroids = {}
del_bullets = {}
for i,b in pairs(bullets) do
for j,a in pairs(asteroids) do
local distance,dx,dy
dx = a.x-b.x
dy = a.y-b.y
distance = math.sqrt((dx*dx)+(dy*dy))
if distance < a.ray then
del_asteroids[j] = true
del_bullets[i] = true
break
end
end
end
for i,b in pairs(del_bullets) do
table.remove(bullets,i)
end
for i,a in pairs(del_asteroids) do
table.remove(asteroids,i)
asteroids_num = asteroids_num - 1
if asteroids_num == 0 then
asteroids_max = asteroids_max + 1
end
end
end
|
-- Simple Asteroids-alike game.
-- Copyright (C) 2012 Salvatore Sanfilippo.
-- This code is released under the BSD two-clause license.
function setup()
ticks = 0 -- Number of iteration of the program
shipx = WIDTH/2 -- Ship x position
shipy = HEIGHT/2 -- Ship y position
shipa = 0 -- Ship rotation angle
shipvx = 0 -- Ship x velocity
shipvy = 0 -- Ship y velocity
bullets = {} -- An array of bullets
asteroids = {} -- An array of asteroids
asteroids_num = 0; -- Number of asteroids on screen
asteroids_max = 2; -- Max number of asteroids to show
last_bullet_ticks = 0 -- Ticks at the time the last bullet was fired
-- Populate the game with asteroids at start
while(asteroids_num < asteroids_max) do
addAsteroid()
end
end
-- The following functions move objects adding the velocity
-- to the position at every iteration.
function moveShip()
shipx = (shipx + shipvx) % WIDTH
shipy = (shipy + shipvy) % HEIGHT
end
function moveBullets()
local i,b
for i,b in pairs(bullets) do
b.x = b.x+b.vx
b.y = b.y+b.vy
b.ttl = b.ttl - 1
if b.ttl == 0 then bullets[i] = nil end
end
end
function moveAsteroids()
local i,a
for i,a in pairs(asteroids) do
a.x = (a.x+a.vx) % WIDTH
a.y = (a.y+a.vy) % HEIGHT
end
end
-- Add an asteroid. Create a random asteroid so that it's
-- not too close to the ship.
function addAsteroid()
local x,y,a,ray
while true do
x = math.random(WIDTH)
y = math.random(HEIGHT)
ray = math.random(20,40)
if math.abs(x-shipx) > ray and
math.abs(y-shipy) > ray then
break
end
end
a = { x = x, y = y, vx = math.random(), vy = math.random(),
ray = ray }
table.insert(asteroids,a)
asteroids_num = asteroids_num + 1
end
-- Fire a bullet with velocity 2,2 and the same orientation
-- as the ship orientation.
function fire()
local b
-- Don't fire again if we already fired
-- less than 5 iterations ago.
if ticks - last_bullet_ticks < 5 then return end
b = { x = shipx, y = shipy,
vx = shipvx+(2*math.sin(shipa)),
vy = shipvy+(2*math.cos(shipa)),
ttl=300 }
-- Make sure that the bullet originaes from ship head
b.x = b.x+(20*math.sin(shipa))
b.y = b.y+(20*math.cos(shipa))
-- Finally insert the bullet in the table of bullets
table.insert(bullets,b)
last_bullet_ticks = ticks
end
-- Draw the screen, move objects, detect collisions.
function draw()
ticks = ticks+1
-- Handle keyboard events.
if keyboard.pressed['left'] then shipa = shipa - 0.05 end
if keyboard.pressed['right'] then shipa = shipa + 0.05 end
if keyboard.pressed['up'] then
shipvx = shipvx + 0.05*math.sin(shipa)
shipvy = shipvy + 0.05*math.cos(shipa)
end
if keyboard.pressed['space'] then fire() end
-- Create a new asteroid from time to time if needed
if asteroids_num < asteroids_max and (ticks % 500) == 0 then
while(asteroids_num < asteroids_max) do addAsteroid() end
end
-- Move all the objects of the game.
moveShip()
moveBullets()
moveAsteroids()
checkBulletCollision()
-- Draw the current game screen.
background(0,0,0)
drawBullets()
drawAsteroids()
drawShip(shipx,shipy,shipa)
end
-- Math formula to rotate a point counterclockwise, with
-- rotation center at 0,0.
function rotatePoint(x,y,a)
return x*math.cos(a)-y*math.sin(a),
y*math.cos(a)+x*math.sin(a)
end
-- Draw the ship, that is composed of three vertex,
-- rotating the vertexes using rotatePoint().
function drawShip(x,y,a)
local triangles = {}
table.insert(triangles,
{x0 = -10, y0 = -10, x1 = 0, y1 = 20, x2 = 10, y2 = -10,
r = 255, g = 0, b = 0, alpha = 1 })
if keyboard.pressed['up'] then
table.insert(triangles,
{x0 = -5, y0 = -10, x1 = 0, y1 = math.random(-25,-20), x2 = 5, y2 = -10,
r = 255, g = 255, b = 0, alpha = 1 })
end
for i,t in pairs(triangles) do
fill(t.r,t.g,t.b,t.alpha)
t.x0,t.y0 = rotatePoint(t.x0,t.y0,-a);
t.x1,t.y1 = rotatePoint(t.x1,t.y1,-a);
t.x2,t.y2 = rotatePoint(t.x2,t.y2,-a);
triangle(x+t.x0,y+t.y0,x+t.x1,y+t.y1,x+t.x2,y+t.y2)
end
end
-- Draw a bullet, that's just a single pixel.
function drawBullets()
local i,b
for i,b in pairs(bullets) do
fill(255,255,255,1)
rect(b.x,b.y,1,1)
end
end
-- Draw an asteroid.
function drawAsteroids()
local i,a
for i,a in pairs(asteroids) do
fill(150,150,150,1)
ellipse(a.x,a.y,a.ray,a.ray)
end
end
-- This function detects the collision between a bullet
-- and an asteroid, and removes both the bullet and the
-- asteroid from the game when they collide.
function checkBulletCollision()
local i,j,b,a,del_asteroids,del_bullets
del_asteroids = {}
del_bullets = {}
for i,b in pairs(bullets) do
for j,a in pairs(asteroids) do
local distance,dx,dy
dx = a.x-b.x
dy = a.y-b.y
distance = math.sqrt((dx*dx)+(dy*dy))
if distance < a.ray then
del_asteroids[j] = true
del_bullets[i] = true
break
end
end
end
for i,b in pairs(del_bullets) do
table.remove(bullets,i)
end
for i,a in pairs(del_asteroids) do
table.remove(asteroids,i)
asteroids_num = asteroids_num - 1
if asteroids_num == 0 then
asteroids_max = asteroids_max + 1
end
end
end
|
Small fix for Asteroids.lua: Make sure that the bullet originaes from ship head.
|
Small fix for Asteroids.lua: Make sure that the bullet originaes from ship head.
|
Lua
|
bsd-2-clause
|
saisai/load81,seclorum/load81,saisai/load81,saisai/load81,saisai/load81,antirez/load81,seclorum/load81,antirez/load81,seclorum/load81,saisai/load81,seclorum/load81,antirez/load81,antirez/load81,antirez/load81,seclorum/load81
|
06d296eea64deea5d171f769d43ff67537b04ed5
|
src/camerastoryutils/src/Client/CameraStoryUtils.lua
|
src/camerastoryutils/src/Client/CameraStoryUtils.lua
|
---
-- @module CameraStoryUtils
-- @author Quenty
local require = require(script.Parent.loader).load(script)
local RunService = game:GetService("RunService")
local InsertServiceUtils = require("InsertServiceUtils")
local Promise = require("Promise")
local Math = require("Math")
local CameraStoryUtils = {}
function CameraStoryUtils.reflectCamera(maid, topCamera)
local camera = Instance.new("Camera")
camera.Name = "ReflectedCamera"
maid:GiveTask(camera)
local function update()
camera.FieldOfView = topCamera.FieldOfView
camera.CFrame = topCamera.CFrame
end
maid:GiveTask(topCamera:GetPropertyChangedSignal("CFrame"):Connect(update))
maid:GiveTask(topCamera:GetPropertyChangedSignal("FieldOfView"):Connect(update))
update()
return camera
end
function CameraStoryUtils.setupViewportFrame(maid, target)
local viewportFrame = Instance.new("ViewportFrame")
viewportFrame.ZIndex = 0
viewportFrame.BorderSizePixel = 0
viewportFrame.BackgroundColor3 = Color3.new(0.7, 0.7, 0.7)
viewportFrame.Size = UDim2.new(1, 0, 1, 0)
maid:GiveTask(viewportFrame)
local reflectedCamera = CameraStoryUtils.reflectCamera(maid, workspace.CurrentCamera)
reflectedCamera.Parent = viewportFrame
viewportFrame.CurrentCamera = reflectedCamera
viewportFrame.Parent = target
return viewportFrame
end
function CameraStoryUtils.promiseCrate(maid, viewportFrame, color)
return maid:GivePromise(InsertServiceUtils.promiseAsset(182451181)):Then(function(model)
maid:GiveTask(model)
local crate = model:GetChildren()[1]
if not crate then
return Promise.rejected()
end
for _, item in pairs(crate:GetDescendants()) do
if item:IsA("BasePart") then
item.Color = color
item.Transparency = 0.5
end
end
crate.Parent = viewportFrame
return Promise.resolved(crate)
end)
end
function CameraStoryUtils.getInterpolationFactory(maid, viewportFrame, low, high, period, toCFrame)
assert(maid, "Bad maid")
assert(viewportFrame, "Bad viewportFrame")
assert(type(low) == "number", "Bad low")
assert(type(high) == "number", "Bad high")
assert(type(period) == "number", "Bad period")
assert(type(toCFrame) == "function", "Bad toCFrame")
return function(interpolate, color)
assert(type(interpolate) == "function", "Bad interpolate")
assert(typeof(color) == "Color3", "Bad color")
maid:GivePromise(CameraStoryUtils.promiseCrate(maid, viewportFrame, color))
:Then(function(crate)
maid:GiveTask(RunService.RenderStepped:Connect(function()
local t = (os.clock()/period % 2/period)*period
if t >= 1 then
t = 1 - (t % 1)
end
t = Math.map(t, 0, 1, low, high)
t = math.clamp(t, low, high)
local cframe = toCFrame(interpolate(t))
crate:SetPrimaryPartCFrame(cframe)
end))
end)
end
end
return CameraStoryUtils
|
---
-- @module CameraStoryUtils
-- @author Quenty
local require = require(script.Parent.loader).load(script)
local RunService = game:GetService("RunService")
local InsertServiceUtils = require("InsertServiceUtils")
local Promise = require("Promise")
local Math = require("Math")
local CameraStoryUtils = {}
function CameraStoryUtils.reflectCamera(maid, topCamera)
local camera = Instance.new("Camera")
camera.Name = "ReflectedCamera"
maid:GiveTask(camera)
local function update()
camera.FieldOfView = topCamera.FieldOfView
camera.CFrame = topCamera.CFrame
end
maid:GiveTask(topCamera:GetPropertyChangedSignal("CFrame"):Connect(update))
maid:GiveTask(topCamera:GetPropertyChangedSignal("FieldOfView"):Connect(update))
update()
return camera
end
function CameraStoryUtils.setupViewportFrame(maid, target)
local viewportFrame = Instance.new("ViewportFrame")
viewportFrame.ZIndex = 0
viewportFrame.BorderSizePixel = 0
viewportFrame.BackgroundColor3 = Color3.new(0.7, 0.7, 0.7)
viewportFrame.Size = UDim2.new(1, 0, 1, 0)
maid:GiveTask(viewportFrame)
local reflectedCamera = CameraStoryUtils.reflectCamera(maid, workspace.CurrentCamera)
reflectedCamera.Parent = viewportFrame
viewportFrame.CurrentCamera = reflectedCamera
viewportFrame.Parent = target
return viewportFrame
end
function CameraStoryUtils.promiseCrate(maid, viewportFrame, properties)
return maid:GivePromise(InsertServiceUtils.promiseAsset(182451181)):Then(function(model)
maid:GiveTask(model)
local crate = model:GetChildren()[1]
if not crate then
return Promise.rejected()
end
if properties then
for _, item in pairs(crate:GetDescendants()) do
if item:IsA("BasePart") then
for property, value in pairs(properties) do
item[property] = value
end
end
end
end
crate.Parent = viewportFrame
return Promise.resolved(crate)
end)
end
function CameraStoryUtils.getInterpolationFactory(maid, viewportFrame, low, high, period, toCFrame)
assert(maid, "Bad maid")
assert(viewportFrame, "Bad viewportFrame")
assert(type(low) == "number", "Bad low")
assert(type(high) == "number", "Bad high")
assert(type(period) == "number", "Bad period")
assert(type(toCFrame) == "function", "Bad toCFrame")
return function(interpolate, color)
assert(type(interpolate) == "function", "Bad interpolate")
assert(typeof(color) == "Color3", "Bad color")
maid:GivePromise(CameraStoryUtils.promiseCrate(maid, viewportFrame, {
Color = color;
Transparency = 0.5
}))
:Then(function(crate)
maid:GiveTask(RunService.RenderStepped:Connect(function()
local t = (os.clock()/period % 2/period)*period
if t >= 1 then
t = 1 - (t % 1)
end
t = Math.map(t, 0, 1, low, high)
t = math.clamp(t, low, high)
local cframe = toCFrame(interpolate(t))
crate:SetPrimaryPartCFrame(cframe)
end))
end)
end
end
return CameraStoryUtils
|
fix: Fix CameraStoryUtils
|
fix: Fix CameraStoryUtils
|
Lua
|
mit
|
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
|
9f281af60565054d79b4e3523fc200a5575421ba
|
src/virtio.lua
|
src/virtio.lua
|
-- virtio.lua -- Linux 'vhost' interface for ethernet I/O towards the kernel.
module(...,package.seeall)
local ffi = require("ffi")
local C = ffi.C
require("vhost_client_h")
require("virtio_h")
require("tuntap_h")
function new (tapinterface)
local M = {}
local vio = ffi.new("struct vio")
local rx_freelist, tx_freelist
local rxring, txring = vio.vring[0], vio.vring[1]
local txpackets, rxpackets = 0, 0
function init ()
-- XXX do this better!
os.execute("modprobe tun")
os.execute("modprobe vhost_net")
local tapfd = C.open_tap(tapinterface);
assert(C.vhost_open(vio, tapfd, memory_regions()) == 0)
-- Initialize freelists
rx_freelist, tx_freelist = {}, {}
for i = 0, C.VIO_VRING_SIZE-1 do
rx_freelist[i+1] = i
tx_freelist[i+1] = i
end
end M.init = init
function print_vio (vio)
print("avail[0].idx:" .. tostring(vio.vring[0].avail.idx))
print(" used[0].idx:" .. tostring(vio.vring[0].used.idx))
print(" used[0].pktlen: " .. tostring(vio.vring[0].used.ring[0].len))
print("avail[1].idx:" .. tostring(vio.vring[1].avail.idx))
print(" used[1].idx:" .. tostring(vio.vring[1].used.idx))
end
local next_tx_avail = 0 -- Next available position in the tx avail ring
function transmit (address, size)
local descindex = init_transmit_descriptor(address, size)
assert(descindex < C.VIO_VRING_SIZE)
txring.avail.ring[next_tx_avail % C.VIO_VRING_SIZE] = descindex
next_tx_avail = (next_tx_avail + 1) % 65536
end M.transmit = transmit
function init_transmit_descriptor (address, size)
local index = get_transmit_buffer()
assert(index <= C.VIO_VRING_SIZE)
local d = txring.desc[index]
d.addr, d.len, d.flags, d.next = tonumber(ffi.cast("uint64_t",address)), size, 0, 0
return index
end
-- Return the index of an available transmit buffer.
-- Precondition: transmit_ready() tested to return true.
function get_transmit_buffer ()
assert(can_transmit())
return table.remove(tx_freelist)
end
local txused = 0
function can_reclaim_buffer ()
return txused ~= txring.used.idx
end M.can_reclaim_buffer = can_reclaim_buffer
function reclaim_buffer ()
assert(can_reclaim_buffer())
table.insert(tx_freelist, txring.used.ring[txused % C.VIO_VRING_SIZE].id)
assert(#tx_freelist <= C.VIO_VRING_SIZE)
txused = (txused + 1) % 65536
txpackets = txpackets + 1
end M.reclaim_buffer = reclaim_buffer
function sync_transmit ()
C.full_memory_barrier() txring.avail.idx = next_tx_avail kick(txring)
end M.sync_transmit = sync_transmit
function can_transmit ()
if tx_freelist[1] == nil then return nil, 'no free descriptors'
else return true end
end M.can_transmit = can_transmit
local next_rx_avail = 0 -- Next available position in the rx avail ring
function add_receive_buffer (address, size)
local bufferindex = get_rx_buffer()
assert(bufferindex < C.VIO_VRING_SIZE)
local desc = rxring.desc[bufferindex]
desc.addr, desc.len = ffi.cast("uint64_t", address), size
desc.flags, desc.next = C.VIO_DESC_F_WRITE, 0
next_rx_avail = (next_rx_avail + 1) % 65536
-- XXX memory.lua should call this automatically when needed
update_vhost_memory_map()
end M.add_receive_buffer = add_receive_buffer
function get_rx_buffer ()
assert(can_add_receive_buffer())
return table.remove(rx_freelist)
end
-- Is there a receive descriptor available to store a new buffer in?
function can_add_receive_buffer ()
return rx_freelist[1] ~= nil
end M.can_add_receive_buffer = can_add_receive_buffer
local rxused = 0
function receive ()
assert(can_receive())
local index = rxring.used.ring[rxused % C.VIO_VRING_SIZE].id
local length = rxring.used.ring[rxused % C.VIO_VRING_SIZE].len
local address = rxring.desc[index].addr
rxused = (rxused + 1) % 65536
table.insert(rx_freelist, index)
assert(#rx_freelist <= C.VIO_VRING_SIZE)
rxpackets = rxpackets + 1
return address, length
end M.receive = receive
function can_receive ()
return rxused ~= rxring.used.idx
end M.can_receive = can_receive
function sync_receive ()
C.full_memory_barrier() rxring.avail.idx = next_rx_avail kick(rxring)
end M.sync_receive = sync_receive
-- Make all of our DMA memory usable as vhost packet buffers.
function update_vhost_memory_map ()
C.vhost_set_memory(vio, memory_regions())
end
-- Construct a vhost memory map for the kernel. The memory map
-- includes all of our currently allocated DMA buffers and reuses
-- the address space of this process. This means that we can use
-- ordinary pointer addresses to DMA buffers in our vring
-- descriptors.
function memory_regions ()
local vio_memory = ffi.new("struct vio_memory")
local chunks = memory.chunks
vio_memory.nregions = #chunks
vio_memory.padding = 0
local vio_index = 0
for _,chunk in ipairs(chunks) do
local r = vio_memory.regions + vio_index
r.guest_phys_addr = ffi.cast("uint64_t", chunk.pointer)
r.userspace_addr = ffi.cast("uint64_t", chunk.pointer)
r.memory_size = chunk.size
r.flags_padding = 0
vio_index = vio_index + 1
end
return vio_memory
end
function print_stats ()
print("packets transmitted: " .. lib.comma_value(txpackets))
print("packets received: " .. lib.comma_value(rxpackets))
end
-- Selftest procedure to read packets from a tap device and write them back.
function M.selftest (opts)
local secs = (opts and opts.secs) or 1
local deadline = C.get_time_ns() + secs * 1e9
local done = function () return C.get_time_ns() > deadline end
print("Echoing packets for "..secs.." second(s).")
repeat
while can_add_receive_buffer() do
add_receive_buffer(memory.dma_alloc(2048), 2048)
end
while can_transmit() and can_receive() do
local address, length = receive()
transmit(address, length)
end
sync_receive()
sync_transmit()
while can_reclaim_buffer() do
reclaim_buffer()
end
until done()
print_stats()
end
-- Signal the kernel via the 'kick' eventfd that there is new data.
function kick (ring)
local value = ffi.new("uint64_t[1]")
value[0] = 1
C.write(ring.kickfd, value, 8)
end
return M
end
function selftest ()
print("Testing vhost (virtio) support.")
local v = virtio.new("vio%d")
v.init()
v.selftest()
end
|
-- virtio.lua -- Linux 'vhost' interface for ethernet I/O towards the kernel.
module(...,package.seeall)
local ffi = require("ffi")
local C = ffi.C
local memory = require("memory")
local buffer = require("buffer")
require("vhost_client_h")
require("virtio_h")
require("tuntap_h")
function new (tapinterface)
local M = {}
local vio = ffi.new("struct vio")
local rx_freelist, tx_freelist
local rxring, txring = vio.vring[0], vio.vring[1]
local txpackets, rxpackets = 0, 0
function init ()
-- XXX do this better!
os.execute("modprobe tun")
os.execute("modprobe vhost_net")
local tapfd = C.open_tap(tapinterface);
assert(C.vhost_open(vio, tapfd, memory_regions()) == 0)
-- Initialize freelists
rx_freelist, tx_freelist = {}, {}
for i = 0, C.VIO_VRING_SIZE-1 do
rx_freelist[i+1] = i
tx_freelist[i+1] = i
end
end M.init = init
function print_vio (vio)
print("avail[0].idx:" .. tostring(vio.vring[0].avail.idx))
print(" used[0].idx:" .. tostring(vio.vring[0].used.idx))
print(" used[0].pktlen: " .. tostring(vio.vring[0].used.ring[0].len))
print("avail[1].idx:" .. tostring(vio.vring[1].avail.idx))
print(" used[1].idx:" .. tostring(vio.vring[1].used.idx))
end
local next_tx_avail = 0 -- Next available position in the tx avail ring
local txbuffers = {}
function transmit (buf)
local bufferindex = init_transmit_descriptor(buf.ptr, buf.size)
assert(bufferindex < C.VIO_VRING_SIZE)
txbuffers[bufferindex] = buf
txring.avail.ring[next_tx_avail % C.VIO_VRING_SIZE] = bufferindex
next_tx_avail = (next_tx_avail + 1) % 65536
buffer.ref(buf)
end M.transmit = transmit
function init_transmit_descriptor (address, size)
local index = get_transmit_buffer()
assert(index <= C.VIO_VRING_SIZE)
local d = txring.desc[index]
d.addr, d.len, d.flags, d.next = tonumber(ffi.cast("uint64_t",address)), size, 0, 0
return index
end
-- Return the index of an available transmit buffer.
-- Precondition: transmit_ready() tested to return true.
function get_transmit_buffer ()
assert(can_transmit())
return table.remove(tx_freelist)
end
local txused = 0
function can_reclaim_buffer ()
return txused ~= txring.used.idx
end M.can_reclaim_buffer = can_reclaim_buffer
function reclaim_buffer ()
assert(can_reclaim_buffer())
local descindex = txused % C.VIO_VRING_SIZE
local bufferindex = txring.used.ring[descindex].id
local buf = txbuffers[bufferindex]
table.insert(tx_freelist, bufferindex)
assert(#tx_freelist <= C.VIO_VRING_SIZE)
buffer.deref(buf)
txbuffers[bufferindex] = nil
txused = (txused + 1) % 65536
txpackets = txpackets + 1
end M.reclaim_buffer = reclaim_buffer
function sync_transmit ()
while can_reclaim_buffer() do reclaim_buffer() end
C.full_memory_barrier() txring.avail.idx = next_tx_avail kick(txring)
end M.sync_transmit = sync_transmit
function can_transmit ()
if tx_freelist[1] == nil then return nil, 'no free descriptors'
else return true end
end M.can_transmit = can_transmit
local next_rx_avail = 0 -- Next available position in the rx avail ring
local rxbuffers = {}
function add_receive_buffer (buf)
local bufferindex = get_rx_buffer()
assert(bufferindex < C.VIO_VRING_SIZE)
rxbuffers[bufferindex] = buf
buffer.ref(buf)
local desc = rxring.desc[next_rx_avail % C.VIO_VRING_SIZE]
rxring.avail.ring[next_rx_avail % C.VIO_VRING_SIZE] = bufferindex
desc.addr, desc.len = ffi.cast("uint64_t", buf.ptr), buf.maxsize
desc.flags, desc.next = C.VIO_DESC_F_WRITE, 0
next_rx_avail = (next_rx_avail + 1) % 65536
-- XXX memory.lua should call this automatically when needed
update_vhost_memory_map()
end M.add_receive_buffer = add_receive_buffer
function get_rx_buffer ()
assert(can_add_receive_buffer())
return table.remove(rx_freelist)
end
-- Is there a receive descriptor available to store a new buffer in?
function can_add_receive_buffer ()
return rx_freelist[1] ~= nil
end M.can_add_receive_buffer = can_add_receive_buffer
local rxused = 0
function receive ()
assert(can_receive())
local index = rxring.used.ring[rxused % C.VIO_VRING_SIZE].id
local buf = rxbuffers[index]
assert(buf)
buf.size = rxring.used.ring[rxused % C.VIO_VRING_SIZE].len
buffer.deref(buf)
rxbuffers[index] = nil
rxused = (rxused + 1) % 65536
table.insert(rx_freelist, index)
assert(#rx_freelist <= C.VIO_VRING_SIZE)
rxpackets = rxpackets + 1
return buf
end M.receive = receive
function can_receive ()
return rxused ~= rxring.used.idx
end M.can_receive = can_receive
function sync_receive ()
C.full_memory_barrier() rxring.avail.idx = next_rx_avail kick(rxring)
end M.sync_receive = sync_receive
-- Make all of our DMA memory usable as vhost packet buffers.
function update_vhost_memory_map ()
C.vhost_set_memory(vio, memory_regions())
end
-- Construct a vhost memory map for the kernel. The memory map
-- includes all of our currently allocated DMA buffers and reuses
-- the address space of this process. This means that we can use
-- ordinary pointer addresses to DMA buffers in our vring
-- descriptors.
function memory_regions ()
local vio_memory = ffi.new("struct vio_memory")
local chunks = memory.chunks
vio_memory.nregions = #chunks
vio_memory.padding = 0
local vio_index = 0
for _,chunk in ipairs(chunks) do
local r = vio_memory.regions + vio_index
r.guest_phys_addr = ffi.cast("uint64_t", chunk.pointer)
r.userspace_addr = ffi.cast("uint64_t", chunk.pointer)
r.memory_size = chunk.size
r.flags_padding = 0
vio_index = vio_index + 1
end
return vio_memory
end
function print_stats ()
print("packets transmitted: " .. lib.comma_value(txpackets))
print("packets received: " .. lib.comma_value(rxpackets))
end
-- Selftest procedure to read packets from a tap device and write them back.
function M.selftest (options)
local port = require("port")
print("virtio selftest")
options = options or {}
options.device = M
options.program = port.Port.echo
options.secs = 60
M.init()
port.selftest(options)
print_stats()
end
-- Signal the kernel via the 'kick' eventfd that there is new data.
function kick (ring)
local value = ffi.new("uint64_t[1]")
value[0] = 1
C.write(ring.kickfd, value, 8)
end
return M
end
function selftest ()
print("Testing vhost (virtio) support.")
local v = virtio.new("vio%d")
v.init()
v.selftest()
end
|
virtio.lua: Updated to the new I/O API and fixed bugs.
|
virtio.lua: Updated to the new I/O API and fixed bugs.
selftest now calls into port.lua's echo test.
|
Lua
|
apache-2.0
|
andywingo/snabbswitch,hb9cwp/snabbswitch,SnabbCo/snabbswitch,wingo/snabbswitch,SnabbCo/snabbswitch,dpino/snabb,hb9cwp/snabbswitch,virtualopensystems/snabbswitch,andywingo/snabbswitch,dpino/snabb,alexandergall/snabbswitch,justincormack/snabbswitch,andywingo/snabbswitch,fhanik/snabbswitch,Igalia/snabb,Igalia/snabbswitch,wingo/snabbswitch,heryii/snabb,eugeneia/snabbswitch,dpino/snabbswitch,pavel-odintsov/snabbswitch,eugeneia/snabb,heryii/snabb,alexandergall/snabbswitch,snabbnfv-goodies/snabbswitch,Igalia/snabb,dwdm/snabbswitch,wingo/snabb,andywingo/snabbswitch,lukego/snabb,Igalia/snabbswitch,xdel/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,wingo/snabbswitch,heryii/snabb,plajjan/snabbswitch,kellabyte/snabbswitch,snabbnfv-goodies/snabbswitch,snabbco/snabb,kellabyte/snabbswitch,snabbco/snabb,dwdm/snabbswitch,hb9cwp/snabbswitch,wingo/snabb,Igalia/snabb,virtualopensystems/snabbswitch,kbara/snabb,snabbco/snabb,mixflowtech/logsensor,snabbnfv-goodies/snabbswitch,hb9cwp/snabbswitch,Igalia/snabbswitch,Igalia/snabbswitch,eugeneia/snabb,mixflowtech/logsensor,alexandergall/snabbswitch,lukego/snabb,dpino/snabb,heryii/snabb,pirate/snabbswitch,lukego/snabb,mixflowtech/logsensor,kbara/snabb,pavel-odintsov/snabbswitch,kbara/snabb,snabbco/snabb,justincormack/snabbswitch,wingo/snabb,alexandergall/snabbswitch,eugeneia/snabb,Igalia/snabb,snabbco/snabb,wingo/snabb,wingo/snabb,Igalia/snabb,pirate/snabbswitch,lukego/snabbswitch,aperezdc/snabbswitch,Igalia/snabbswitch,aperezdc/snabbswitch,kbara/snabb,Igalia/snabb,eugeneia/snabb,eugeneia/snabb,eugeneia/snabb,eugeneia/snabbswitch,kellabyte/snabbswitch,pavel-odintsov/snabbswitch,wingo/snabb,justincormack/snabbswitch,heryii/snabb,xdel/snabbswitch,mixflowtech/logsensor,javierguerragiraldez/snabbswitch,dpino/snabb,javierguerragiraldez/snabbswitch,aperezdc/snabbswitch,eugeneia/snabb,xdel/snabbswitch,snabbco/snabb,justincormack/snabbswitch,snabbco/snabb,Igalia/snabb,dwdm/snabbswitch,dpino/snabbswitch,plajjan/snabbswitch,alexandergall/snabbswitch,fhanik/snabbswitch,javierguerragiraldez/snabbswitch,snabbnfv-goodies/snabbswitch,dpino/snabbswitch,alexandergall/snabbswitch,eugeneia/snabbswitch,kbara/snabb,lukego/snabbswitch,lukego/snabb,alexandergall/snabbswitch,wingo/snabbswitch,eugeneia/snabbswitch,fhanik/snabbswitch,dpino/snabb,eugeneia/snabb,virtualopensystems/snabbswitch,SnabbCo/snabbswitch,pirate/snabbswitch,plajjan/snabbswitch,lukego/snabbswitch,mixflowtech/logsensor,lukego/snabbswitch,dpino/snabbswitch,dpino/snabb,heryii/snabb,SnabbCo/snabbswitch,aperezdc/snabbswitch,dpino/snabb,plajjan/snabbswitch,snabbco/snabb,kbara/snabb
|
aa69dfe15fba7f10b670cae25953ed5c93b18f65
|
tools/erlparse.lua
|
tools/erlparse.lua
|
-- Prosody IM
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local file = nil;
local last = nil;
local function read(expected)
local ch;
if last then
ch = last; last = nil;
else ch = file:read(1); end
if expected and ch ~= expected then error("expected: "..expected.."; got: "..(ch or "nil")); end
return ch;
end
local function pushback(ch)
if last then error(); end
last = ch;
end
local function peek()
if not last then last = read(); end
return last;
end
local _A, _a, _Z, _z, _0, _9, __, _at, _space = string.byte("AaZz09@_ ", 1, 9);
local function isLowerAlpha(ch)
ch = string.byte(ch) or 0;
return (ch >= _a and ch <= _z);
end
local function isNumeric(ch)
ch = string.byte(ch) or 0;
return (ch >= _0 and ch <= _9);
end
local function isAtom(ch)
ch = string.byte(ch) or 0;
return (ch >= _A and ch <= _Z) or (ch >= _a and ch <= _z) or (ch >= _0 and ch <= _9) or ch == __ or ch == _at;
end
local function isSpace(ch)
ch = string.byte(ch) or "x";
return ch <= _space;
end
local function readString()
read("\""); -- skip quote
local slash = nil;
local str = "";
while true do
local ch = read();
if ch == "\"" and not slash then break; end
str = str..ch;
end
str = str:gsub("\\.", {["\\b"]="\b", ["\\d"]="\d", ["\\e"]="\e", ["\\f"]="\f", ["\\n"]="\n", ["\\r"]="\r", ["\\s"]="\s", ["\\t"]="\t", ["\\v"]="\v", ["\\\""]="\"", ["\\'"]="'", ["\\\\"]="\\"});
return str;
end
local function readAtom1()
local var = read();
while isAtom(peek()) do
var = var..read();
end
return var;
end
local function readAtom2()
local str = read("'");
local slash = nil;
while true do
local ch = read();
str = str..ch;
if ch == "'" and not slash then break; end
end
return str;
end
local function readNumber()
local num = read();
while isNumeric(peek()) do
num = num..read();
end
return tonumber(num);
end
local readItem = nil;
local function readTuple()
local t = {};
local s = ""; -- string representation
read(); -- read {, or [, or <
while true do
local item = readItem();
if not item then break; end
if type(item) ~= type(0) or item > 255 then
s = nil;
elseif s then
s = s..string.char(item);
end
table.insert(t, item);
end
read(); -- read }, or ], or >
if s and s ~= "" then
return s
else
return t
end;
end
local function readBinary()
read("<"); -- read <
local t = readTuple();
read(">") -- read >
local ch = peek();
if type(t) == type("") then
-- binary is a list of integers
return t;
elseif type(t) == type({}) then
if t[1] then
-- binary contains string
return t[1];
else
-- binary is empty
return "";
end;
else
error();
end
end
readItem = function()
local ch = peek();
if ch == nil then return nil end
if ch == "{" or ch == "[" then
return readTuple();
elseif isLowerAlpha(ch) then
return readAtom1();
elseif ch == "'" then
return readAtom2();
elseif isNumeric(ch) then
return readNumber();
elseif ch == "\"" then
return readString();
elseif ch == "<" then
return readBinary();
elseif isSpace(ch) or ch == "," or ch == "|" then
read();
return readItem();
else
--print("Unknown char: "..ch);
return nil;
end
end
local function readChunk()
local x = readItem();
if x then read("."); end
return x;
end
local function readFile(filename)
file = io.open(filename);
if not file then error("File not found: "..filename); os.exit(0); end
return function()
local x = readChunk();
if not x and peek() then error("Invalid char: "..peek()); end
return x;
end;
end
module "erlparse"
function parseFile(file)
return readFile(file);
end
return _M;
|
-- Prosody IM
-- Copyright (C) 2008-2009 Matthew Wild
-- Copyright (C) 2008-2009 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local file = nil;
local last = nil;
local function read(expected)
local ch;
if last then
ch = last; last = nil;
else ch = file:read(1); end
if expected and ch ~= expected then error("expected: "..expected.."; got: "..(ch or "nil")); end
return ch;
end
local function pushback(ch)
if last then error(); end
last = ch;
end
local function peek()
if not last then last = read(); end
return last;
end
local _A, _a, _Z, _z, _0, _9, __, _at, _space = string.byte("AaZz09@_ ", 1, 9);
local function isLowerAlpha(ch)
ch = string.byte(ch) or 0;
return (ch >= _a and ch <= _z);
end
local function isNumeric(ch)
ch = string.byte(ch) or 0;
return (ch >= _0 and ch <= _9);
end
local function isAtom(ch)
ch = string.byte(ch) or 0;
return (ch >= _A and ch <= _Z) or (ch >= _a and ch <= _z) or (ch >= _0 and ch <= _9) or ch == __ or ch == _at;
end
local function isSpace(ch)
ch = string.byte(ch) or "x";
return ch <= _space;
end
local escapes = {["\\b"]="\b", ["\\d"]="\d", ["\\e"]="\e", ["\\f"]="\f", ["\\n"]="\n", ["\\r"]="\r", ["\\s"]="\s", ["\\t"]="\t", ["\\v"]="\v", ["\\\""]="\"", ["\\'"]="'", ["\\\\"]="\\"};
local function readString()
read("\""); -- skip quote
local slash = nil;
local str = "";
while true do
local ch = read();
if slash then
slash = slash..ch;
if not escapes[slash] then error("Unknown escape sequence: "..slash); end
str = str..escapes[slash];
slash = nil;
elseif ch == "\"" then
break;
elseif ch == "\\" then
slash = ch;
else
str = str..ch;
end
end
return str;
end
local function readAtom1()
local var = read();
while isAtom(peek()) do
var = var..read();
end
return var;
end
local function readAtom2()
local str = read("'");
local slash = nil;
while true do
local ch = read();
str = str..ch;
if ch == "'" and not slash then break; end
end
return str;
end
local function readNumber()
local num = read();
while isNumeric(peek()) do
num = num..read();
end
return tonumber(num);
end
local readItem = nil;
local function readTuple()
local t = {};
local s = ""; -- string representation
read(); -- read {, or [, or <
while true do
local item = readItem();
if not item then break; end
if type(item) ~= type(0) or item > 255 then
s = nil;
elseif s then
s = s..string.char(item);
end
table.insert(t, item);
end
read(); -- read }, or ], or >
if s and s ~= "" then
return s
else
return t
end;
end
local function readBinary()
read("<"); -- read <
local t = readTuple();
read(">") -- read >
local ch = peek();
if type(t) == type("") then
-- binary is a list of integers
return t;
elseif type(t) == type({}) then
if t[1] then
-- binary contains string
return t[1];
else
-- binary is empty
return "";
end;
else
error();
end
end
readItem = function()
local ch = peek();
if ch == nil then return nil end
if ch == "{" or ch == "[" then
return readTuple();
elseif isLowerAlpha(ch) then
return readAtom1();
elseif ch == "'" then
return readAtom2();
elseif isNumeric(ch) then
return readNumber();
elseif ch == "\"" then
return readString();
elseif ch == "<" then
return readBinary();
elseif isSpace(ch) or ch == "," or ch == "|" then
read();
return readItem();
else
--print("Unknown char: "..ch);
return nil;
end
end
local function readChunk()
local x = readItem();
if x then read("."); end
return x;
end
local function readFile(filename)
file = io.open(filename);
if not file then error("File not found: "..filename); os.exit(0); end
return function()
local x = readChunk();
if not x and peek() then error("Invalid char: "..peek()); end
return x;
end;
end
module "erlparse"
function parseFile(file)
return readFile(file);
end
return _M;
|
ejabberd2prosody: Fixed escape code processing when parsing strings.
|
ejabberd2prosody: Fixed escape code processing when parsing strings.
|
Lua
|
mit
|
sarumjanuch/prosody,sarumjanuch/prosody
|
74694fd7573cedc48da611a9f949a214fb5ebc5f
|
[resources]/GTWcore/misc/c_2dview.lua
|
[resources]/GTWcore/misc/c_2dview.lua
|
--[[
********************************************************************************
Project owner: RageQuit community
Project name: GTW-RPG
Developers: Mr_Moose
Source code: https://github.com/GTWCode/GTW-RPG/
Bugtracker: https://forum.404rq.com/bug-reports/
Suggestions: https://forum.404rq.com/mta-servers-development/
Version: Open source
License: BSD 2-Clause
Status: Stable release
********************************************************************************
]]--
-- Enable/disable 2D view
local view_2D = false
local dummy_object = nil
local zoom = 30
sx,sy = guiGetScreenSize()
--[[ Render 2D view if enabled ]]--
function update_2d_view()
if not view_2D then return end
local x,y,z = getElementPosition(localPlayer)
local dx,dy,dz = getElementPosition(dummy_object)
setCameraMatrix(x,y,z + zoom, dx,dy,dz)
end
--[[ Manage zoom ]]--
function manage_zoom(up_down)
if up_down == 1 and zoom < 70 then zoom = zoom + up_down
elseif zoom > 10 then zoom = zoom - up_down end
end
addEventHandler("onClientMouseWheel", root, manage_zoom)
--[[ Toggle 2D view ]]--
function toggle_2d(plr)
view_2D = not view_2D
if not view_2D then
setCameraTarget(localPlayer)
removeEventHandler("onClientPreRender", root, update_2d_view)
detachElements(dummy_object)
destroyElement(dummy_object)
else
addEventHandler("onClientPreRender", root, update_2d_view)
dummy_object = createMarker(0,0,0, "cylinder", 0.1, 0,0,0, 0)
attachElements(dummy_object, localPlayer, 0, 1, 0)
end
end
addCommandHandler("2d", toggle_2d)
addCommandHandler("toggle2d", toggle_2d)
|
--[[
********************************************************************************
Project owner: RageQuit community
Project name: GTW-RPG
Developers: Mr_Moose
Source code: https://github.com/GTWCode/GTW-RPG/
Bugtracker: https://forum.404rq.com/bug-reports/
Suggestions: https://forum.404rq.com/mta-servers-development/
Version: Open source
License: BSD 2-Clause
Status: Stable release
********************************************************************************
]]--
-- Enable/disable 2D view
local view_2D = false
local dummy_object = nil
local zoom = 30
sx,sy = guiGetScreenSize()
--[[ Render 2D view if enabled ]]--
function update_2d_view()
if not view_2D then return end
local x,y,z = getElementPosition(localPlayer)
local dx,dy,dz = getElementPosition(dummy_object)
setCameraMatrix(x,y,z + zoom, dx,dy,dz)
end
--[[ Manage zoom ]]--
function zoom_in()
if zoom > 5 then zoom = zoom - 1 else
exports.GTWtopbar:dm("You cannot zoom in any further", 255,0,0)
end
end
function zoom_out()
if zoom < 70 then zoom = zoom + 1 else
exports.GTWtopbar:dm("You cannot zoom out any further", 255,0,0)
end
end
bindKey("num_add", "down", zoom_in)
bindKey("num_sub", "down", zoom_out)
--[[ Toggle 2D view ]]--
function toggle_2d(plr)
view_2D = not view_2D
if not view_2D then
setCameraTarget(localPlayer)
removeEventHandler("onClientPreRender", root, update_2d_view)
detachElements(dummy_object)
destroyElement(dummy_object)
else
addEventHandler("onClientPreRender", root, update_2d_view)
dummy_object = createMarker(0,0,0, "cylinder", 0.1, 0,0,0, 0)
attachElements(dummy_object, localPlayer, 0, 1, 0)
end
end
addCommandHandler("2d", toggle_2d)
addCommandHandler("toggle2d", toggle_2d)
|
[Patch] Fixed zoom functionality in 2D view
|
[Patch] Fixed zoom functionality in 2D view
|
Lua
|
bsd-2-clause
|
GTWCode/GTW-RPG,404rq/GTW-RPG,GTWCode/GTW-RPG,GTWCode/GTW-RPG,404rq/GTW-RPG,404rq/GTW-RPG
|
996d24d155952a4c8205ee58832c7d5f4ac342f1
|
vi_mode_search.lua
|
vi_mode_search.lua
|
-- Handle the vim search emulation
-- Modeled on textadept's command_entry.lua
local M = {}
M.search_hl_indic = _SCINTILLA.next_indic_number()
local function set_colours()
buffer.indic_fore[M.search_hl_indic] = 0x00FFFF
buffer.indic_style[M.search_hl_indic] = _SCINTILLA.constants.INDIC_ROUNDBOX
buffer.indic_alpha[M.search_hl_indic] = 100
-- Find all occurrences to highlight.
buffer.indicator_current = M.search_hl_indic
buffer:indicator_clear_range(0, buffer.length)
end
M.state = {
in_search_mode = false,
backwards = false,
pattern = "",
}
local state = M.state
local function do_search(backwards)
ui.statusbar_text = "Search: "..state.pattern
local saved_pos = buffer.current_pos
buffer:search_anchor()
local search_flags = (_SCINTILLA.constants.FIND_REGEXP +
_SCINTILLA.constants.FIND_POSIX)
local searcher = function(...) return buffer:search_next(...) end
-- Search from the end. We'll jump to the first one "after" the current pos.
buffer.current_pos = 0
buffer:search_anchor()
pos = searcher(search_flags, state.pattern)
set_colours()
if pos >= 0 then
local saved_flags = buffer.search_flags
buffer.search_flags = search_flags
local new_pos = nil
-- Need to use search_in_target to find the actual search extents.
buffer.target_start = 0
buffer.target_end = buffer.length
local occurences = 0
local first_pos = nil
local last_pos = nil
while buffer.search_in_target(state.pattern) >= 0 do
local match_len = buffer.target_end - buffer.target_start
last_pos = buffer.target_start
if first_pos == nil then
first_pos = buffer.target_start
end
-- Work out the current pos, ie first hit after the saved position.
if backwards then
if buffer.target_start < saved_pos then
new_pos = buffer.target_start
end
else
-- Forwards - take the first one after saved_pos
if new_pos == nil and buffer.target_start > saved_pos then
new_pos = buffer.target_start
end
end
buffer:indicator_fill_range(buffer.target_start, match_len)
if buffer.target_end == buffer.target_start then
-- Zero length match - not useful, abort here.
buffer.current_pos = saved_pos
ui.statusbar_text = "Not found"
return
end
-- Ensure we make some progress
if buffer.target_end == buffer.target_start then
buffer.target_start = buffer.target_end + 1
else
buffer.target_start = buffer.target_end
end
buffer.target_end = buffer.length
if buffer.target_start >= buffer.length then
break
end
occurences = occurences + 1
end
-- Handle wrapping search
if new_pos == nil then
if backwards then
new_pos = last_pos
else
new_pos = first_pos
end
ui.statusbar_text = "WRAPPED SEARCH"
else
ui.statusbar_text = "Found " .. tostring(occurences)
end
-- Restore global search flags
buffer.search_flags = saved_flags
buffer.goto_pos(new_pos)
buffer.selection_start = new_pos
else
buffer.current_pos = saved_pos
ui.statusbar_text = "Not found"
end
end
local function handle_search_command(command)
if state.in_search_mode then
state.pattern = command
do_search(state.backwards)
state.in_search_mode = false
return false -- make sure this isn't handled again
end
end
-- Register our key bindings for the command entry
local ui_ce = ui.command_entry
keys.vi_search_command = {
['\n'] = function ()
local exit = state.exitfunc
state.exitfunc = nil
return ui_ce.finish_mode(function(text)
if string.len(text) == 0 then
text = state.pattern
end
handle_search_command(text)
exit()
end)
end,
cv = {
['\t'] = function()
local text = ui_ce.entry_text
ui_ce.enter_mode(nil)
ui_ce.entry_text = text .. "\t"
ui_ce.enter_mode("vi_search_command")
end,
},
['esc'] = function()
ui_ce.enter_mode(nil) -- Exit command_entry mode
keys.MODE = "vi_command"
end,
}
local function start_common(exitfunc)
state.in_search_mode = true
state.exitfunc = exitfunc
ui.command_entry.entry_text = ""
ui.command_entry.enter_mode('vi_search_command')
end
function M.start(exitfunc)
state.backwards = false
return start_common(exitfunc)
end
function M.start_rev(exitfunc)
state.backwards = true
return start_common(exitfunc)
end
function M.restart()
do_search(state.backwards)
end
function M.restart_rev()
do_search(not state.backwards)
end
local function search_word_common(backwards)
-- Search for the word under the cursor
-- TODO: quote properly, or better don't use regex'
-- Uses ideas from editing.lua
local pos = buffer.current_pos
local s, e = buffer:word_start_position(pos, true), buffer:word_end_position(pos)
local word = buffer:text_range(s, e)
state.pattern = '\\<' .. word .. '\\>'
state.backwards = backwards
if backwards then
-- Avoid hitting the current word again if the cursor isn't at the
-- start.
buffer.current_pos = s
end
do_search(backwards)
end
function M.search_word()
search_word_common(false)
end
function M.search_word_rev()
search_word_common(true)
end
return M
|
-- Handle the vim search emulation
-- Modeled on textadept's command_entry.lua
local M = {}
M.search_hl_indic = _SCINTILLA.next_indic_number()
local function set_colours()
buffer.indic_fore[M.search_hl_indic] = 0x00FFFF
buffer.indic_style[M.search_hl_indic] = _SCINTILLA.constants.INDIC_ROUNDBOX
buffer.indic_alpha[M.search_hl_indic] = 100
-- Find all occurrences to highlight.
buffer.indicator_current = M.search_hl_indic
buffer:indicator_clear_range(0, buffer.length)
end
M.state = {
in_search_mode = false,
backwards = false,
pattern = "",
}
local state = M.state
local function do_search(backwards)
ui.statusbar_text = "Search: "..state.pattern
local saved_pos = buffer.current_pos
buffer:search_anchor()
-- Hack - need the old FIND_POSIX|FIND_REGEXP, but one's gone.
local search_flags = (_SCINTILLA.constants.FIND_REGEXP + _SCINTILLA.constants.FIND_REGEXP/2)
local searcher = function(...) return buffer:search_next(...) end
-- Search from the end. We'll jump to the first one "after" the current pos.
buffer.current_pos = 0
buffer:search_anchor()
pos = searcher(search_flags, state.pattern)
set_colours()
if pos >= 0 then
local saved_flags = buffer.search_flags
buffer.search_flags = search_flags
local new_pos = nil
-- Need to use search_in_target to find the actual search extents.
buffer.target_start = 0
buffer.target_end = buffer.length
local occurences = 0
local first_pos = nil
local last_pos = nil
while buffer.search_in_target(state.pattern) >= 0 do
local match_len = buffer.target_end - buffer.target_start
last_pos = buffer.target_start
if first_pos == nil then
first_pos = buffer.target_start
end
-- Work out the current pos, ie first hit after the saved position.
if backwards then
if buffer.target_start < saved_pos then
new_pos = buffer.target_start
end
else
-- Forwards - take the first one after saved_pos
if new_pos == nil and buffer.target_start > saved_pos then
new_pos = buffer.target_start
end
end
buffer:indicator_fill_range(buffer.target_start, match_len)
if buffer.target_end == buffer.target_start then
-- Zero length match - not useful, abort here.
buffer.current_pos = saved_pos
ui.statusbar_text = "Not found"
return
end
-- Ensure we make some progress
if buffer.target_end == buffer.target_start then
buffer.target_start = buffer.target_end + 1
else
buffer.target_start = buffer.target_end
end
buffer.target_end = buffer.length
if buffer.target_start >= buffer.length then
break
end
occurences = occurences + 1
end
-- Handle wrapping search
if new_pos == nil then
if backwards then
new_pos = last_pos
else
new_pos = first_pos
end
ui.statusbar_text = "WRAPPED SEARCH"
else
ui.statusbar_text = "Found " .. tostring(occurences)
end
-- Restore global search flags
buffer.search_flags = saved_flags
buffer.goto_pos(new_pos)
buffer.selection_start = new_pos
else
buffer.current_pos = saved_pos
ui.statusbar_text = "Not found"
end
end
local function handle_search_command(command)
if state.in_search_mode then
state.pattern = command
do_search(state.backwards)
state.in_search_mode = false
return false -- make sure this isn't handled again
end
end
-- Register our key bindings for the command entry
local ui_ce = ui.command_entry
keys.vi_search_command = {
['\n'] = function ()
local exit = state.exitfunc
state.exitfunc = nil
return ui_ce.finish_mode(function(text)
if string.len(text) == 0 then
text = state.pattern
end
handle_search_command(text)
exit()
end)
end,
cv = {
['\t'] = function()
local text = ui_ce.entry_text
ui_ce.enter_mode(nil)
ui_ce.entry_text = text .. "\t"
ui_ce.enter_mode("vi_search_command")
end,
},
['esc'] = function()
ui_ce.enter_mode(nil) -- Exit command_entry mode
keys.MODE = "vi_command"
end,
}
local function start_common(exitfunc)
state.in_search_mode = true
state.exitfunc = exitfunc
ui.command_entry.entry_text = ""
ui.command_entry.enter_mode('vi_search_command')
end
function M.start(exitfunc)
state.backwards = false
return start_common(exitfunc)
end
function M.start_rev(exitfunc)
state.backwards = true
return start_common(exitfunc)
end
function M.restart()
do_search(state.backwards)
end
function M.restart_rev()
do_search(not state.backwards)
end
local function search_word_common(backwards)
-- Search for the word under the cursor
-- TODO: quote properly, or better don't use regex'
-- Uses ideas from editing.lua
local pos = buffer.current_pos
local s, e = buffer:word_start_position(pos, true), buffer:word_end_position(pos)
local word = buffer:text_range(s, e)
state.pattern = '\\<' .. word .. '\\>'
state.backwards = backwards
if backwards then
-- Avoid hitting the current word again if the cursor isn't at the
-- start.
buffer.current_pos = s
end
do_search(backwards)
end
function M.search_word()
search_word_common(false)
end
function M.search_word_rev()
search_word_common(true)
end
return M
|
Temporary hack to fix regex searches.
|
Temporary hack to fix regex searches.
|
Lua
|
mit
|
jugglerchris/textadept-vi,erig0/textadept-vi,jugglerchris/textadept-vi
|
f0fa5cdf2f5c5a823b6b95ffddeddd9fe9e011fd
|
spec/integration/cli/restart_spec.lua
|
spec/integration/cli/restart_spec.lua
|
local spec_helper = require "spec.spec_helpers"
local constants = require "kong.constants"
local stringy = require "stringy"
local IO = require "kong.tools.io"
describe("CLI", function()
setup(function()
pcall(spec_helper.stop_kong)
end)
teardown(function()
pcall(spec_helper.stop_kong)
end)
it("should restart kong when it's not running", function()
local res, code = spec_helper.restart_kong()
assert.are.same(0, code)
end)
it("should restart kong when it's running", function()
local res, code = spec_helper.stop_kong()
assert.are.same(0, code)
local res, code = spec_helper.start_kong()
assert.are.same(0, code)
local res, code = spec_helper.restart_kong()
assert.are.same(0, code)
end)
it("should restart kong when it's crashed", function()
os.execute("pkill -9 nginx")
local res, code = spec_helper.restart_kong()
assert.are.same(0, code)
end)
it("should not restart kong when the port is taken", function()
spec_helper.stop_kong()
local thread = spec_helper.start_tcp_server(spec_helper.TEST_PROXY_PORT)
local ok, res = pcall(spec_helper.restart_kong)
assert.falsy(ok)
thread:join()
end)
end)
|
local spec_helper = require "spec.spec_helpers"
local constants = require "kong.constants"
local stringy = require "stringy"
local IO = require "kong.tools.io"
describe("CLI", function()
setup(function()
pcall(spec_helper.stop_kong)
end)
teardown(function()
pcall(spec_helper.stop_kong)
end)
it("should restart kong when it's not running", function()
local res, code = spec_helper.restart_kong()
assert.are.same(0, code)
end)
it("should restart kong when it's running", function()
local res, code = spec_helper.stop_kong()
assert.are.same(0, code)
local res, code = spec_helper.start_kong()
assert.are.same(0, code)
local res, code = spec_helper.restart_kong()
assert.are.same(0, code)
end)
it("should restart kong when it's crashed", function()
os.execute("pkill -9 nginx")
local res, code = spec_helper.restart_kong()
assert.are.same(0, code)
end)
end)
|
Fixing tests
|
Fixing tests
|
Lua
|
apache-2.0
|
peterayeni/kong,Skyscanner/kong,sbuettner/kong,skynet/kong,wakermahmud/kong,puug/kong,bbalu/kong,ChristopherBiscardi/kong,paritoshmmmec/kong,AnsonSmith/kong,chourobin/kong,vmercierfr/kong
|
fc73dce74f0594515e131000b2872f7c1b33fbbc
|
dataloader.lua
|
dataloader.lua
|
--
-- Copyright (c) 2016, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
--
-- Multi-threaded data loader
--
local datasets = require 'datasets/init'
local Threads = require 'threads'
Threads.serialization('threads.sharedserialize')
local M = {}
local DataLoader = torch.class('resnet.DataLoader', M)
function DataLoader.create(opt)
-- The train and val loader
local loaders = {}
for i, split in ipairs{'train', 'val'} do
local dataset = datasets.create(opt, split)
loaders[i] = M.DataLoader(dataset, opt, split)
end
return table.unpack(loaders)
end
function DataLoader:__init(dataset, opt, split)
local manualSeed = opt.manualSeed or 0
local function init()
require('datasets/' .. opt.dataset)
end
local function main(idx)
if manualSeed ~= 0 then
torch.manualSeed(manualSeed + idx)
end
torch.setnumthreads(1)
_G.dataset = dataset
_G.preprocess = dataset:preprocess()
_G.get_input_target = dataset:get_input_target()
return dataset:size()
end
local threads, sizes = Threads(opt.nThreads, init, main)
self.nCrops = 1
self.threads = threads
self.__size = sizes[1][1]
self.batchSize = opt.batch_size
end
function DataLoader:size()
return math.ceil(self.__size / self.batchSize)
end
function DataLoader:get()
self.loop = self.loop or self:run()
local n, out = self.loop()
if out then
return out
else
print ('new loop')
self.loop = self:run()
local n, out = self.loop()
return out
end
end
function DataLoader:run()
local threads = self.threads
local size, batchSize = self.__size, self.batchSize
local perm = torch.randperm(size)
local idx, sample = 1, nil
local function enqueue()
while idx <= size and threads:acceptsjob() do
local indices = perm:narrow(1, idx, math.min(batchSize, size - idx + 1))
threads:addjob(
function(indices, nCrops)
local sz = indices:size(1)
local batch_input, batch_target, imageSize
for i, idx in ipairs(indices:totable()) do
-- if it's too small reject
local out = _G.dataset:get(idx)
if not out then
while true do
out = _G.dataset:get(torch.random(size))
if out then
break
end
end
end
local img = _G.preprocess(out.img)
local sample = _G.get_input_target(img)
local input = sample.input
local target = sample.target
if not batch_target then
imageSize = input:size():totable()
targetSize = target:size():totable()
-- if nCrops > 1 then table.remove(imageSize, 1) end
batch_input = torch.FloatTensor(sz, table.unpack(imageSize))
batch_target = torch.FloatTensor(sz, table.unpack(targetSize))
end
batch_input[i]:copy(sample.input)
batch_target[i]:copy(sample.target)
end
collectgarbage()
return {
input = batch_input,
target = batch_target,
}
end,
function(_sample_)
sample = _sample_
end,
indices,
self.nCrops
)
idx = idx + batchSize
end
end
local n = 0
local function loop()
enqueue()
if not threads:hasjob() then
return -1, nil
end
threads:dojob()
if threads:haserror() then
threads:synchronize()
end
enqueue()
n = n + 1
-- local ss = sample.input:clone()
return n, sample
end
return loop
end
return M.DataLoader
|
--
-- Copyright (c) 2016, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
--
-- Multi-threaded data loader
--
local datasets = require 'datasets/init'
local Threads = require 'threads'
Threads.serialization('threads.sharedserialize')
local M = {}
local DataLoader = torch.class('resnet.DataLoader', M)
function DataLoader.create(opt)
-- The train and val loader
local loaders = {}
for i, split in ipairs{'train', 'val'} do
local dataset = datasets.create(opt, split)
loaders[i] = M.DataLoader(dataset, opt, split)
end
return table.unpack(loaders)
end
function DataLoader:__init(dataset, opt, split)
local manualSeed = opt.manualSeed or 0
local function init()
require('datasets/' .. opt.dataset)
end
local function main(idx)
if manualSeed ~= 0 then
torch.manualSeed(manualSeed + idx)
end
torch.setnumthreads(1)
_G.dataset = dataset
_G.preprocess = dataset:preprocess()
_G.get_input_target = dataset:get_input_target()
return dataset:size()
end
local threads, sizes = Threads(opt.nThreads, init, main)
self.nCrops = 1
self.threads = threads
self.__size = sizes[1][1]
self.batchSize = opt.batch_size
end
function DataLoader:size()
return math.ceil(self.__size / self.batchSize)
end
function DataLoader:get()
self.loop = self.loop or self:run()
local n, out = self.loop()
if out then
return out
else
print ('new loop')
self.loop = self:run()
local n, out = self.loop()
return out
end
end
function DataLoader:run()
local threads = self.threads
local size, batchSize = self.__size, self.batchSize
local perm = torch.randperm(size)
local idx, sample = 1, nil
local function enqueue()
while idx <= size and threads:acceptsjob() do
local indices = torch.Tensor(batchSize):random(size)
threads:addjob(
function(indices, nCrops)
local sz = indices:size(1)
local batch_input, batch_target, imageSize
for i, idx in ipairs(indices:totable()) do
-- if it's too small reject
local out = _G.dataset:get(idx)
if not out then
while true do
out = _G.dataset:get(torch.random(size))
if out then
break
end
end
end
local img = _G.preprocess(out.img)
local sample = _G.get_input_target(img)
local input = sample.input
local target = sample.target
if not batch_target then
imageSize = input:size():totable()
targetSize = target:size():totable()
-- if nCrops > 1 then table.remove(imageSize, 1) end
batch_input = torch.FloatTensor(sz, table.unpack(imageSize))
batch_target = torch.FloatTensor(sz, table.unpack(targetSize))
end
batch_input[i]:copy(sample.input)
batch_target[i]:copy(sample.target)
end
collectgarbage()
return {
input = batch_input,
target = batch_target,
}
end,
function(_sample_)
sample = _sample_
end,
indices,
self.nCrops
)
idx = idx + batchSize
end
end
local n = 0
local function loop()
enqueue()
if not threads:hasjob() then
return -1, nil
end
threads:dojob()
if threads:haserror() then
threads:synchronize()
end
enqueue()
n = n + 1
-- local ss = sample.input:clone()
return n, sample
end
return loop
end
return M.DataLoader
|
fix possible nans due to `last slice` issue in dataloader
|
fix possible nans due to `last slice` issue in dataloader
|
Lua
|
apache-2.0
|
DmitryUlyanov/texture_nets
|
d8c191e53236eeeb6f6608d5494c55dc69a0d273
|
testserver/item/id_90_flute.lua
|
testserver/item/id_90_flute.lua
|
-- I_90 Floete spielen
-- UPDATE common SET com_script='item.id_90_flute' WHERE com_itemid=90;
require("item.base.music")
require("item.general.wood")
module("item.id_90_flute", package.seeall)
skill = Character.flute
item.base.music.addTalkText("#me produces some squeaking sounds on the flute.","#me macht einige quietschende Gerusche auf der Flte.", skill);
item.base.music.addTalkText("#me plays a horribly out of tune melody.","#me spielt eine frchterlich verstimmte Melodie auf der Flte.", skill);
item.base.music.addTalkText("#me plays an out of tune melody.","#me spielt eine verstimmte Melodie auf der Flte.", skill);
item.base.music.addTalkText("#me plays an airy tune on the flute.","#me spielt eine leichte Melodie auf der Flte.", skill);
item.base.music.addTalkText("#me plays a wild tune on the flute.","#me spielt eine wilde Melodie auf der Flte.", skill);
function UseItem(User,SourceItem,TargetItem,Counter,Param)
item.base.music.PlayInstrument(User,SourceItem,skill);
--Testing fireball, only activates if flute's data key name is used -Dyluck
local targetPos
local targetChar
local extraPos
local graphicNum
if ( SourceItem:getData("name") == "fireball" ) then
User:talk(Character.say, "#me casts Fireball ");
if ( User:getFaceTo() == 0) then --if facing north
targetPos = position(User.pos.x, User.pos.y - 3, User.pos.z);
world:makeSound(5, targetPos);
graphicNum = tonumber(SourceItem:getData("num"));
--[[
targetPos2 = position(targetPos.x -1, targetPos.y, targetPos.z);
targetPos3 = position(targetPos.x +1, targetPos.y, targetPos.z);
world:gfx(9, targetPos);
world:gfx(9, targetPos2);
world:gfx(9, targetPos3);
]]--
for i = 0, 2, 1 do
for j = 0, 2, 1 do
extraPos = position(targetPos.x -1 +i, targetPos.y -1 +j, targetPos.z);
if graphicNum ~= "" then
world:gfx(graphicNum, extraPos);
else
world:gfx(9, extraPos);
end
if world:isCharacterOnField(extraPos) then --if there's a target char on target position
targetChar = world:getCharacterOnField(extraPos); --find the char
targetChar:increaseAttrib("hitpoints", -1000);
world:makeSound(1, extraPos);
end
end
end
--[[
if world:isCharacterOnField(targetPos) then --if there's a target char on target position
targetChar = world:getCharacterOnField(targetPos); --find the char
targetChar:increaseAttrib("hitpoints", -1000);
world:makeSound(1, targetPos);
end
if world:isCharacterOnField(targetPos2) then --if there's a target char on target position
targetChar = world:getCharacterOnField(targetPos2); --find the char
targetChar:increaseAttrib("hitpoints", -1000);
world:makeSound(1, targetPos);
end
if world:isCharacterOnField(targetPos3) then --if there's a target char on target position
targetChar = world:getCharacterOnField(targetPos3); --find the char
targetChar:increaseAttrib("hitpoints", -1000);
world:makeSound(1, targetPos);
end
]]--
end
end
--End Test
end
LookAtItem = item.general.wood.LookAtItem
|
-- I_90 Floete spielen
-- UPDATE common SET com_script='item.id_90_flute' WHERE com_itemid=90;
require("item.base.music")
require("item.general.wood")
module("item.id_90_flute", package.seeall)
skill = Character.flute
item.base.music.addTalkText("#me produces some squeaking sounds on the flute.","#me macht einige quietschende Gerusche auf der Flte.", skill);
item.base.music.addTalkText("#me plays a horribly out of tune melody.","#me spielt eine frchterlich verstimmte Melodie auf der Flte.", skill);
item.base.music.addTalkText("#me plays an out of tune melody.","#me spielt eine verstimmte Melodie auf der Flte.", skill);
item.base.music.addTalkText("#me plays an airy tune on the flute.","#me spielt eine leichte Melodie auf der Flte.", skill);
item.base.music.addTalkText("#me plays a wild tune on the flute.","#me spielt eine wilde Melodie auf der Flte.", skill);
function UseItem(User,SourceItem,TargetItem,Counter,Param)
item.base.music.PlayInstrument(User,SourceItem,skill);
--Testing fireball, only activates if flute's data key name is used -Dyluck
local targetPos
local targetChar
local extraPos
local graphicNum = tonumber(SourceItem:getData("spell"));
if ( graphicNum ~= nil ) then
User:talk(Character.say, "#me casts Fireball ");
if ( User:getFaceTo() == 0) then --if facing north
targetPos = position(User.pos.x, User.pos.y - 3, User.pos.z);
world:makeSound(5, targetPos);
graphicNum = tonumber(SourceItem:getData("num"));
for i = 0, 2, 1 do
for j = 0, 2, 1 do
extraPos = position(targetPos.x -1 +i, targetPos.y -1 +j, targetPos.z);
if (graphicNum ~= nil) then
world:gfx(graphicNum, extraPos);
else
User:talk(Character.say, "No graphic for this number");
end
if world:isCharacterOnField(extraPos) then --if there's a target char on target position
targetChar = world:getCharacterOnField(extraPos); --find the char
targetChar:increaseAttrib("hitpoints", -1000);
world:makeSound(1, extraPos);
end
end
end
end
end
--End Test
end
LookAtItem = item.general.wood.LookAtItem
|
-Effects_GFX.txt was wrong for 4,5,6. Fixed it. -Test Script for flute
|
-Effects_GFX.txt was wrong for 4,5,6. Fixed it.
-Test Script for flute
|
Lua
|
agpl-3.0
|
LaFamiglia/Illarion-Content,Baylamon/Illarion-Content,Illarion-eV/Illarion-Content,vilarion/Illarion-Content,KayMD/Illarion-Content
|
0bc74e2c65aa4ca81fb7f653a104ecaa526e0dac
|
ffi/input_android.lua
|
ffi/input_android.lua
|
local ffi = require("ffi")
local bit = require("bit")
local android = require("android")
local dummy = require("ffi/linux_input_h")
-- to trigger refreshes for certain Android framework events:
local fb = require("ffi/framebuffer_android").open()
local input = {}
function input.open()
end
local inputQueue = {}
local ev_time = ffi.new("struct timeval")
local function genEmuEvent(evtype, code, value)
ffi.C.gettimeofday(ev_time, nil)
local ev = {
type = tonumber(evtype),
code = tonumber(code),
value = tonumber(value),
time = { sec = tonumber(ev_time.tv_sec), usec = tonumber(ev_time.tv_usec) }
}
table.insert(inputQueue, ev)
end
local function genTouchDownEvent(event, id)
local x = ffi.C.AMotionEvent_getX(event, id)
local y = ffi.C.AMotionEvent_getY(event, id)
genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_SLOT, id)
genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_TRACKING_ID, id)
genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_POSITION_X, x)
genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_POSITION_Y, y)
genEmuEvent(ffi.C.EV_SYN, ffi.C.SYN_REPORT, 0)
end
local function genTouchUpEvent(event, id)
local x = ffi.C.AMotionEvent_getX(event, id)
local y = ffi.C.AMotionEvent_getY(event, id)
genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_SLOT, id)
genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_TRACKING_ID, -1)
genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_POSITION_X, x)
genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_POSITION_Y, y)
genEmuEvent(ffi.C.EV_SYN, ffi.C.SYN_REPORT, 0)
end
local function genTouchMoveEvent(event, id, index)
local x = ffi.C.AMotionEvent_getX(event, index)
local y = ffi.C.AMotionEvent_getY(event, index)
genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_SLOT, id)
genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_POSITION_X, x)
genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_POSITION_Y, y)
genEmuEvent(ffi.C.EV_SYN, ffi.C.SYN_REPORT, 0)
end
local is_in_touch = false
local function motionEventHandler(motion_event)
local action = ffi.C.AMotionEvent_getAction(motion_event)
local pointer_count = ffi.C.AMotionEvent_getPointerCount(motion_event)
local pointer_index = bit.rshift(
bit.band(action, ffi.C.AMOTION_EVENT_ACTION_POINTER_INDEX_MASK),
ffi.C.AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT)
local id = ffi.C.AMotionEvent_getPointerId(motion_event, pointer_index)
local flags = bit.band(action, ffi.C.AMOTION_EVENT_ACTION_MASK)
if flags == ffi.C.AMOTION_EVENT_ACTION_DOWN then
is_in_touch = true
genTouchDownEvent(motion_event, id)
elseif flags == ffi.C.AMOTION_EVENT_ACTION_POINTER_DOWN then
is_in_touch = true
genTouchDownEvent(motion_event, id)
elseif flags == ffi.C.AMOTION_EVENT_ACTION_UP then
is_in_touch = false
genTouchUpEvent(motion_event, id)
elseif flags == ffi.C.AMOTION_EVENT_ACTION_POINTER_UP then
is_in_touch = false
genTouchUpEvent(motion_event, id)
elseif flags == ffi.C.AMOTION_EVENT_ACTION_MOVE then
if is_in_touch then
for index = 0, pointer_count - 1 do
id = ffi.C.AMotionEvent_getPointerId(motion_event, index)
genTouchMoveEvent(motion_event, id, index)
end
end
end
end
local function keyEventHandler(key_event)
local code = ffi.C.AKeyEvent_getKeyCode(key_event)
local action = ffi.C.AKeyEvent_getAction(key_event)
if action == ffi.C.AKEY_EVENT_ACTION_DOWN then
genEmuEvent(ffi.C.EV_KEY, code, 1)
elseif action == ffi.C.AKEY_EVENT_ACTION_UP then
genEmuEvent(ffi.C.EV_KEY, code, 0)
end
end
local function commandHandler(code, value)
genEmuEvent(ffi.C.EV_MSC, code, value)
end
function input.waitForEvent(usecs)
local timeout = math.ceil(usecs and usecs/1000 or -1)
while true do
-- check for queued events
if #inputQueue > 0 then
-- return oldest FIFO element
return table.remove(inputQueue, 1)
end
local events = ffi.new("int[1]")
local source = ffi.new("struct android_poll_source*[1]")
local poll_state = ffi.C.ALooper_pollAll(timeout, nil, events, ffi.cast("void**", source))
if poll_state >= 0 then
if source[0] ~= nil then
--source[0].process(android.app, source[0])
if source[0].id == ffi.C.LOOPER_ID_MAIN then
local cmd = ffi.C.android_app_read_cmd(android.app)
ffi.C.android_app_pre_exec_cmd(android.app, cmd)
android.LOGI("got command: " .. tonumber(cmd))
commandHandler(cmd, 1)
if cmd == ffi.C.APP_CMD_INIT_WINDOW then
fb:refresh()
elseif cmd == ffi.C.APP_CMD_TERM_WINDOW then
-- do nothing for now
elseif cmd == ffi.C.APP_CMD_LOST_FOCUS then
-- do we need this here?
fb:refresh()
end
ffi.C.android_app_post_exec_cmd(android.app, cmd)
elseif source[0].id == ffi.C.LOOPER_ID_INPUT then
local event = ffi.new("AInputEvent*[1]")
while ffi.C.AInputQueue_getEvent(android.app.inputQueue, event) >= 0 do
if ffi.C.AInputQueue_preDispatchEvent(android.app.inputQueue, event[0]) == 0 then
local event_type = ffi.C.AInputEvent_getType(event[0])
if event_type == ffi.C.AINPUT_EVENT_TYPE_MOTION then
motionEventHandler(event[0])
elseif event_type == ffi.C.AINPUT_EVENT_TYPE_KEY then
keyEventHandler(event[0])
end
ffi.C.AInputQueue_finishEvent(android.app.inputQueue, event[0], 1)
end
end
end
end
if android.app.destroyRequested ~= 0 then
android.LOGI("Engine thread destroy requested!")
error("application forced to quit")
return
end
elseif poll_state == ffi.C.ALOOPER_POLL_TIMEOUT then
error("Waiting for input failed: timeout\n")
end
end
end
function input.fakeTapInput() end
function input.closeAll() end
return input
|
local ffi = require("ffi")
local bit = require("bit")
local android = require("android")
local dummy = require("ffi/linux_input_h")
local input = {
-- to trigger refreshes for certain Android framework events:
device = nil,
}
function input.open()
end
local inputQueue = {}
local ev_time = ffi.new("struct timeval")
local function genEmuEvent(evtype, code, value)
ffi.C.gettimeofday(ev_time, nil)
local ev = {
type = tonumber(evtype),
code = tonumber(code),
value = tonumber(value),
time = { sec = tonumber(ev_time.tv_sec), usec = tonumber(ev_time.tv_usec) }
}
table.insert(inputQueue, ev)
end
local function genTouchDownEvent(event, id)
local x = ffi.C.AMotionEvent_getX(event, id)
local y = ffi.C.AMotionEvent_getY(event, id)
genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_SLOT, id)
genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_TRACKING_ID, id)
genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_POSITION_X, x)
genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_POSITION_Y, y)
genEmuEvent(ffi.C.EV_SYN, ffi.C.SYN_REPORT, 0)
end
local function genTouchUpEvent(event, id)
local x = ffi.C.AMotionEvent_getX(event, id)
local y = ffi.C.AMotionEvent_getY(event, id)
genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_SLOT, id)
genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_TRACKING_ID, -1)
genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_POSITION_X, x)
genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_POSITION_Y, y)
genEmuEvent(ffi.C.EV_SYN, ffi.C.SYN_REPORT, 0)
end
local function genTouchMoveEvent(event, id, index)
local x = ffi.C.AMotionEvent_getX(event, index)
local y = ffi.C.AMotionEvent_getY(event, index)
genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_SLOT, id)
genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_POSITION_X, x)
genEmuEvent(ffi.C.EV_ABS, ffi.C.ABS_MT_POSITION_Y, y)
genEmuEvent(ffi.C.EV_SYN, ffi.C.SYN_REPORT, 0)
end
local is_in_touch = false
local function motionEventHandler(motion_event)
local action = ffi.C.AMotionEvent_getAction(motion_event)
local pointer_count = ffi.C.AMotionEvent_getPointerCount(motion_event)
local pointer_index = bit.rshift(
bit.band(action, ffi.C.AMOTION_EVENT_ACTION_POINTER_INDEX_MASK),
ffi.C.AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT)
local id = ffi.C.AMotionEvent_getPointerId(motion_event, pointer_index)
local flags = bit.band(action, ffi.C.AMOTION_EVENT_ACTION_MASK)
if flags == ffi.C.AMOTION_EVENT_ACTION_DOWN then
is_in_touch = true
genTouchDownEvent(motion_event, id)
elseif flags == ffi.C.AMOTION_EVENT_ACTION_POINTER_DOWN then
is_in_touch = true
genTouchDownEvent(motion_event, id)
elseif flags == ffi.C.AMOTION_EVENT_ACTION_UP then
is_in_touch = false
genTouchUpEvent(motion_event, id)
elseif flags == ffi.C.AMOTION_EVENT_ACTION_POINTER_UP then
is_in_touch = false
genTouchUpEvent(motion_event, id)
elseif flags == ffi.C.AMOTION_EVENT_ACTION_MOVE then
if is_in_touch then
for index = 0, pointer_count - 1 do
id = ffi.C.AMotionEvent_getPointerId(motion_event, index)
genTouchMoveEvent(motion_event, id, index)
end
end
end
end
local function keyEventHandler(key_event)
local code = ffi.C.AKeyEvent_getKeyCode(key_event)
local action = ffi.C.AKeyEvent_getAction(key_event)
if action == ffi.C.AKEY_EVENT_ACTION_DOWN then
genEmuEvent(ffi.C.EV_KEY, code, 1)
elseif action == ffi.C.AKEY_EVENT_ACTION_UP then
genEmuEvent(ffi.C.EV_KEY, code, 0)
end
end
local function commandHandler(code, value)
genEmuEvent(ffi.C.EV_MSC, code, value)
end
function input.waitForEvent(usecs)
local timeout = math.ceil(usecs and usecs/1000 or -1)
while true do
-- check for queued events
if #inputQueue > 0 then
-- return oldest FIFO element
return table.remove(inputQueue, 1)
end
local events = ffi.new("int[1]")
local source = ffi.new("struct android_poll_source*[1]")
local poll_state = ffi.C.ALooper_pollAll(timeout, nil, events, ffi.cast("void**", source))
if poll_state >= 0 then
if source[0] ~= nil then
--source[0].process(android.app, source[0])
if source[0].id == ffi.C.LOOPER_ID_MAIN then
local cmd = ffi.C.android_app_read_cmd(android.app)
ffi.C.android_app_pre_exec_cmd(android.app, cmd)
android.LOGI("got command: " .. tonumber(cmd))
commandHandler(cmd, 1)
if cmd == ffi.C.APP_CMD_INIT_WINDOW then
if self.device and self.device.screen then
self.device.screen:refreshFull()
end
elseif cmd == ffi.C.APP_CMD_TERM_WINDOW then
-- do nothing for now
elseif cmd == ffi.C.APP_CMD_LOST_FOCUS then
-- do we need this here?
if self.device and self.device.screen then
self.device.screen:refreshFull()
end
end
ffi.C.android_app_post_exec_cmd(android.app, cmd)
elseif source[0].id == ffi.C.LOOPER_ID_INPUT then
local event = ffi.new("AInputEvent*[1]")
while ffi.C.AInputQueue_getEvent(android.app.inputQueue, event) >= 0 do
if ffi.C.AInputQueue_preDispatchEvent(android.app.inputQueue, event[0]) == 0 then
local event_type = ffi.C.AInputEvent_getType(event[0])
if event_type == ffi.C.AINPUT_EVENT_TYPE_MOTION then
motionEventHandler(event[0])
elseif event_type == ffi.C.AINPUT_EVENT_TYPE_KEY then
keyEventHandler(event[0])
end
ffi.C.AInputQueue_finishEvent(android.app.inputQueue, event[0], 1)
end
end
end
end
if android.app.destroyRequested ~= 0 then
android.LOGI("Engine thread destroy requested!")
error("application forced to quit")
return
end
elseif poll_state == ffi.C.ALOOPER_POLL_TIMEOUT then
error("Waiting for input failed: timeout\n")
end
end
end
function input.fakeTapInput() end
function input.closeAll() end
return input
|
fix old framebuffer API usage in input_android
|
fix old framebuffer API usage in input_android
the Android input module triggers refreshes under certain circumstances.
This was not considered when refactoring the framebuffer API.
|
Lua
|
agpl-3.0
|
koreader/koreader-base,houqp/koreader-base,koreader/koreader-base,houqp/koreader-base,houqp/koreader-base,houqp/koreader-base,NiLuJe/koreader-base,Frenzie/koreader-base,frankyifei/koreader-base,Frenzie/koreader-base,frankyifei/koreader-base,apletnev/koreader-base,Hzj-jie/koreader-base,Hzj-jie/koreader-base,koreader/koreader-base,Frenzie/koreader-base,NiLuJe/koreader-base,Hzj-jie/koreader-base,Frenzie/koreader-base,frankyifei/koreader-base,frankyifei/koreader-base,apletnev/koreader-base,NiLuJe/koreader-base,apletnev/koreader-base,Hzj-jie/koreader-base,koreader/koreader-base,apletnev/koreader-base,NiLuJe/koreader-base
|
d0b1dde9222caed18de4bdefae1905d52198e7d7
|
awesome/battery.lua
|
awesome/battery.lua
|
-- This function returns a formatted string with the current battery status. It
-- can be used to populate a text widget in the awesome window manager. Based
-- on the "Gigamo Battery Widget" found in the wiki at awesome.naquadah.org
local naughty = require("naughty")
local beautiful = require("beautiful")
function readBatFile(adapter, ...)
local basepath = "/sys/class/power_supply/"..adapter.."/"
for i, name in pairs({...}) do
file = io.open(basepath..name, "r")
if file then
local str = file:read()
file:close()
return str
end
end
end
function batteryInfo(adapter)
local fh = io.open("/sys/class/power_supply/"..adapter.."/present", "r")
if fh == nil then
battery = "A/C"
icon = ""
percent = ""
else
local cur = readBatFile(adapter, "charge_now", "energy_now")
local cap = readBatFile(adapter, "charge_full", "energy_full")
local sta = readBatFile(adapter, "status")
battery = math.floor(cur * 100 / cap)
if sta:match("Charging") then
icon = "⚡"
percent = "%"
elseif sta:match("Discharging") then
icon = ""
percent = "%"
if tonumber(battery) < 15 then
naughty.notify({ title = "Battery Warning"
, text = "Battery low!".." "..battery..percent.." ".."left!"
, timeout = 5
, position = "top_right"
, fg = beautiful.fg_focus
, bg = beautiful.bg_focus
})
end
else
-- If we are neither charging nor discharging, assume that we are on A/C
battery = "A/C"
icon = ""
percent = ""
end
end
return " "..icon..battery..percent.." "
end
|
-- This function returns a formatted string with the current battery status. It
-- can be used to populate a text widget in the awesome window manager. Based
-- on the "Gigamo Battery Widget" found in the wiki at awesome.naquadah.org
local naughty = require("naughty")
local beautiful = require("beautiful")
function readBatFile(adapter, ...)
local basepath = "/sys/class/power_supply/"..adapter.."/"
for i, name in pairs({...}) do
file = io.open(basepath..name, "r")
if file then
local str = file:read()
file:close()
return str
end
end
end
function batteryInfo(adapter)
local fh = io.open("/sys/class/power_supply/"..adapter.."/present", "r")
if fh == nil then
battery = "A/C"
icon = ""
percent = ""
else
local cur = readBatFile(adapter, "charge_now", "energy_now")
local cap = readBatFile(adapter, "charge_full", "energy_full")
local sta = readBatFile(adapter, "status")
battery = math.floor(cur * 100 / cap)
if sta:match("Charging") then
icon = "⚡"
percent = "%"
elseif sta:match("Discharging") then
icon = ""
percent = "%"
if tonumber(battery) < 15 then
naughty.notify({ title = "Battery Warning"
, text = "Battery low!".." "..battery..percent.." ".."left!"
, timeout = 5
, position = "top_right"
, fg = beautiful.fg_focus
, bg = beautiful.bg_focus
})
end
else
-- If we are neither charging nor discharging, assume that we are on A/C
battery = "A/C"
icon = ""
percent = ""
end
-- fix 'too many open files' bug on awesome 4.0
fh:close()
end
return " "..icon..battery..percent.." "
end
|
[awesome] Update battery widget to fix leaking fh
|
[awesome] Update battery widget to fix leaking fh
|
Lua
|
mit
|
koenwtje/dotfiles
|
09c1f35191a67c3c86680264951c4f8ba4c6de58
|
frontend/device/remarkable/device.lua
|
frontend/device/remarkable/device.lua
|
local Generic = require("device/generic/device") -- <= look at this file!
local TimeVal = require("ui/timeval")
local logger = require("logger")
local function yes() return true end
local function no() return false end
local EV_ABS = 3
local ABS_X = 00
local ABS_Y = 01
local ABS_MT_POSITION_X = 53
local ABS_MT_POSITION_Y = 54
-- Resolutions from libremarkable src/framebuffer/common.rs
local screen_width = 1404 -- unscaled_size_check: ignore
local screen_height = 1872 -- unscaled_size_check: ignore
local wacom_width = 15725 -- unscaled_size_check: ignore
local wacom_height = 20967 -- unscaled_size_check: ignore
local wacom_scale_x = screen_width / wacom_width
local wacom_scale_y = screen_height / wacom_height
local Remarkable = Generic:new{
isRemarkable = yes,
hasKeys = yes,
needsScreenRefreshAfterResume = no,
hasOTAUpdates = yes,
canReboot = yes,
canPowerOff = yes,
isTouchDevice = yes,
hasFrontlight = no,
display_dpi = 226,
-- Despite the SoC supporting it, it's finicky in practice (#6772)
canHWInvert = no,
home_dir = "/home/root",
}
local Remarkable1 = Remarkable:new{
model = "reMarkable",
mt_width = 767, -- unscaled_size_check: ignore
mt_height = 1023, -- unscaled_size_check: ignore
input_wacom = "/dev/input/event0",
input_ts = "/dev/input/event1",
input_buttons = "/dev/input/event2",
battery_path = "/sys/class/power_supply/bq27441-0/capacity",
status_path = "/sys/class/power_supply/bq27441-0/status",
}
function Remarkable1:adjustTouchEvent(ev, by)
if ev.type == EV_ABS then
ev.time = TimeVal:now()
-- Mirror X and Y and scale up both X & Y as touch input is different res from
-- display
if ev.code == ABS_MT_POSITION_X then
ev.value = (Remarkable1.mt_width - ev.value) * by.mt_scale_x
end
if ev.code == ABS_MT_POSITION_Y then
ev.value = (Remarkable1.mt_height - ev.value) * by.mt_scale_y
end
end
end
local Remarkable2 = Remarkable:new{
model = "reMarkable 2",
mt_width = 1403, -- unscaled_size_check: ignore
mt_height = 1871, -- unscaled_size_check: ignore
input_wacom = "/dev/input/event1",
input_ts = "/dev/input/event2",
input_buttons = "/dev/input/event0",
battery_path = "/sys/class/power_supply/max77818_battery/capacity",
status_path = "/sys/class/power_supply/max77818-charger/status",
}
function Remarkable2:adjustTouchEvent(ev, by)
if ev.type == EV_ABS then
ev.time = TimeVal:now()
-- Mirror Y and scale up both X & Y as touch input is different res from
-- display
if ev.code == ABS_MT_POSITION_X then
ev.value = (ev.value) * by.mt_scale_x
end
if ev.code == ABS_MT_POSITION_Y then
ev.value = (Remarkable2.mt_height - ev.value) * by.mt_scale_y
end
end
end
local adjustAbsEvt = function(self, ev)
if ev.type == EV_ABS then
if ev.code == ABS_X then
ev.code = ABS_Y
ev.value = (wacom_height - ev.value) * wacom_scale_y
elseif ev.code == ABS_Y then
ev.code = ABS_X
ev.value = ev.value * wacom_scale_x
end
end
end
function Remarkable:init()
self.screen = require("ffi/framebuffer_mxcfb"):new{device = self, debug = logger.dbg}
self.powerd = require("device/remarkable/powerd"):new{
device = self,
capacity_file = self.battery_path,
status_file = self.status_path,
}
self.input = require("device/input"):new{
device = self,
event_map = require("device/remarkable/event_map"),
}
self.input.open(self.input_wacom) -- Wacom
self.input.open(self.input_ts) -- Touchscreen
self.input.open(self.input_buttons) -- Buttons
local scalex = screen_width / self.mt_width
local scaley = screen_height / self.mt_height
self.input:registerEventAdjustHook(adjustAbsEvt)
self.input:registerEventAdjustHook(self.adjustTouchEvent, {mt_scale_x=scalex, mt_scale_y=scaley})
-- USB plug/unplug, battery charge/not charging are generated as fake events
self.input.open("fake_events")
local rotation_mode = self.screen.ORIENTATION_PORTRAIT
self.screen.native_rotation_mode = rotation_mode
self.screen.cur_rotation_mode = rotation_mode
Generic.init(self)
end
function Remarkable:supportsScreensaver() return true end
function Remarkable:setDateTime(year, month, day, hour, min, sec)
if hour == nil or min == nil then return true end
local command
if year and month and day then
command = string.format("timedatectl set-time '%d-%d-%d %d:%d:%d'", year, month, day, hour, min, sec)
else
command = string.format("timedatectl set-time '%d:%d'",hour, min)
end
return os.execute(command) == 0
end
function Remarkable:_clearScreen()
self.screen:clear()
self.screen:refreshFull()
end
function Remarkable:suspend()
self:_clearScreen()
os.execute("systemctl suspend")
end
function Remarkable:resume()
end
function Remarkable:powerOff()
self:_clearScreen()
os.execute("systemctl poweroff")
end
function Remarkable:reboot()
self:_clearScreen()
os.execute("systemctl reboot")
end
local f = io.open("/sys/devices/soc0/machine")
if not f then error("missing sysfs entry for a remarkable") end
local deviceType = f:read("*line")
f:close()
logger.info("deviceType: ", deviceType)
if deviceType == "reMarkable 2.0" then
if not os.getenv("RM2FB_SHIM") then
error("reMarkable2 requires RM2FB to work (https://github.com/ddvk/remarkable2-framebuffer)")
end
return Remarkable2
else
return Remarkable1
end
|
local Generic = require("device/generic/device") -- <= look at this file!
local TimeVal = require("ui/timeval")
local logger = require("logger")
local function yes() return true end
local function no() return false end
local EV_ABS = 3
local ABS_X = 00
local ABS_Y = 01
local ABS_MT_POSITION_X = 53
local ABS_MT_POSITION_Y = 54
-- Resolutions from libremarkable src/framebuffer/common.rs
local screen_width = 1404 -- unscaled_size_check: ignore
local screen_height = 1872 -- unscaled_size_check: ignore
local wacom_width = 15725 -- unscaled_size_check: ignore
local wacom_height = 20967 -- unscaled_size_check: ignore
local wacom_scale_x = screen_width / wacom_width
local wacom_scale_y = screen_height / wacom_height
local Remarkable = Generic:new{
isRemarkable = yes,
hasKeys = yes,
needsScreenRefreshAfterResume = no,
hasOTAUpdates = yes,
canReboot = yes,
canPowerOff = yes,
isTouchDevice = yes,
hasFrontlight = no,
display_dpi = 226,
-- Despite the SoC supporting it, it's finicky in practice (#6772)
canHWInvert = no,
home_dir = "/home/root",
}
local Remarkable1 = Remarkable:new{
model = "reMarkable",
mt_width = 767, -- unscaled_size_check: ignore
mt_height = 1023, -- unscaled_size_check: ignore
input_wacom = "/dev/input/event0",
input_ts = "/dev/input/event1",
input_buttons = "/dev/input/event2",
battery_path = "/sys/class/power_supply/bq27441-0/capacity",
status_path = "/sys/class/power_supply/bq27441-0/status",
}
function Remarkable1:adjustTouchEvent(ev, by)
if ev.type == EV_ABS then
ev.time = TimeVal:now()
-- Mirror X and Y and scale up both X & Y as touch input is different res from
-- display
if ev.code == ABS_MT_POSITION_X then
ev.value = (Remarkable1.mt_width - ev.value) * by.mt_scale_x
end
if ev.code == ABS_MT_POSITION_Y then
ev.value = (Remarkable1.mt_height - ev.value) * by.mt_scale_y
end
end
end
local Remarkable2 = Remarkable:new{
model = "reMarkable 2",
mt_width = 1403, -- unscaled_size_check: ignore
mt_height = 1871, -- unscaled_size_check: ignore
input_wacom = "/dev/input/event1",
input_ts = "/dev/input/event2",
input_buttons = "/dev/input/event0",
battery_path = "/sys/class/power_supply/max77818_battery/capacity",
status_path = "/sys/class/power_supply/max77818-charger/status",
}
function Remarkable2:adjustTouchEvent(ev, by)
if ev.type == EV_ABS then
ev.time = TimeVal:now()
-- Mirror Y and scale up both X & Y as touch input is different res from
-- display
if ev.code == ABS_MT_POSITION_X then
ev.value = (ev.value) * by.mt_scale_x
end
if ev.code == ABS_MT_POSITION_Y then
ev.value = (Remarkable2.mt_height - ev.value) * by.mt_scale_y
end
end
end
local adjustAbsEvt = function(self, ev)
if ev.type == EV_ABS then
if ev.code == ABS_X then
ev.code = ABS_Y
ev.value = (wacom_height - ev.value) * wacom_scale_y
elseif ev.code == ABS_Y then
ev.code = ABS_X
ev.value = ev.value * wacom_scale_x
end
end
end
function Remarkable:init()
self.screen = require("ffi/framebuffer_mxcfb"):new{device = self, debug = logger.dbg}
self.powerd = require("device/remarkable/powerd"):new{
device = self,
capacity_file = self.battery_path,
status_file = self.status_path,
}
self.input = require("device/input"):new{
device = self,
event_map = require("device/remarkable/event_map"),
}
self.input.open(self.input_wacom) -- Wacom
self.input.open(self.input_ts) -- Touchscreen
self.input.open(self.input_buttons) -- Buttons
local scalex = screen_width / self.mt_width
local scaley = screen_height / self.mt_height
self.input:registerEventAdjustHook(adjustAbsEvt)
self.input:registerEventAdjustHook(self.adjustTouchEvent, {mt_scale_x=scalex, mt_scale_y=scaley})
-- USB plug/unplug, battery charge/not charging are generated as fake events
self.input.open("fake_events")
local rotation_mode = self.screen.ORIENTATION_PORTRAIT
self.screen.native_rotation_mode = rotation_mode
self.screen.cur_rotation_mode = rotation_mode
Generic.init(self)
end
function Remarkable:supportsScreensaver() return true end
function Remarkable:setDateTime(year, month, day, hour, min, sec)
if hour == nil or min == nil then return true end
local command
if year and month and day then
command = string.format("timedatectl set-time '%d-%d-%d %d:%d:%d'", year, month, day, hour, min, sec)
else
command = string.format("timedatectl set-time '%d:%d'",hour, min)
end
return os.execute(command) == 0
end
function Remarkable:suspend()
os.execute("systemctl suspend")
end
function Remarkable:resume()
end
function Remarkable:powerOff()
os.execute("systemctl poweroff")
end
function Remarkable:reboot()
os.execute("systemctl reboot")
end
local f = io.open("/sys/devices/soc0/machine")
if not f then error("missing sysfs entry for a remarkable") end
local deviceType = f:read("*line")
f:close()
logger.info("deviceType: ", deviceType)
if deviceType == "reMarkable 2.0" then
if not os.getenv("RM2FB_SHIM") then
error("reMarkable2 requires RM2FB to work (https://github.com/ddvk/remarkable2-framebuffer)")
end
return Remarkable2
else
return Remarkable1
end
|
rM: Unbreak PowerEvents (#7043)
|
rM: Unbreak PowerEvents (#7043)
Most of this is scheduled with delays for reasons, so this was a stupid
idea, my bad ;).
Fix #7033
|
Lua
|
agpl-3.0
|
NiLuJe/koreader,Frenzie/koreader,Frenzie/koreader,koreader/koreader,Markismus/koreader,poire-z/koreader,Hzj-jie/koreader,poire-z/koreader,mwoz123/koreader,NiLuJe/koreader,koreader/koreader,pazos/koreader
|
ea2768401a30390e0ed8f5b4edee9aaee66b3828
|
modules/admin-core/luasrc/controller/admin/uci.lua
|
modules/admin-core/luasrc/controller/admin/uci.lua
|
module("luci.controller.admin.uci", package.seeall)
require("luci.util")
require("luci.sys")
function index()
node("admin", "uci", "changes").target = call("action_changes")
node("admin", "uci", "revert").target = call("action_revert")
node("admin", "uci", "apply").target = call("action_apply")
end
function convert_changes(changes)
local ret = {}
for r, tbl in pairs(changes) do
for s, os in pairs(tbl) do
for o, v in pairs(os) do
local val, str
if (v == "") then
str = "-"
val = ""
else
str = ""
val = "="..v
end
str = r.."."..s
if o ~= ".type" then
str = str.."."..o
end
table.insert(ret, str..val)
end
end
end
return table.concat(ret, "\n")
end
function action_changes()
local changes = convert_changes(luci.model.uci.changes())
luci.template.render("admin_uci/changes", {changes=changes})
end
function action_apply()
local changes = luci.model.uci.changes()
local output = ""
if changes then
local com = {}
local run = {}
-- Collect files to be applied and commit changes
for r, tbl in pairs(changes) do
if r then
luci.model.uci.load(r)
luci.model.uci.commit(r)
luci.model.uci.unload(r)
if luci.config.uci_oncommit and luci.config.uci_oncommit[r] then
run[luci.config.uci_oncommit[r]] = true
end
end
end
-- Search for post-commit commands
for cmd, i in pairs(run) do
output = output .. cmd .. ":" .. luci.sys.exec(cmd) .. "\n"
end
end
luci.template.render("admin_uci/apply", {changes=convert_changes(changes), output=output})
end
function action_revert()
local changes = luci.model.uci.changes()
if changes then
local revert = {}
-- Collect files to be reverted
for r, tbl in pairs(changes) do
luci.model.uci.load(r)
luci.model.uci.revert(r)
luci.model.uci.unload(r)
end
end
luci.template.render("admin_uci/revert", {changes=convert_changes(changes)})
end
|
module("luci.controller.admin.uci", package.seeall)
function index()
node("admin", "uci", "changes").target = call("action_changes")
node("admin", "uci", "revert").target = call("action_revert")
node("admin", "uci", "apply").target = call("action_apply")
end
function convert_changes(changes)
local ret = {}
for r, tbl in pairs(changes) do
for s, os in pairs(tbl) do
for o, v in pairs(os) do
local val, str
if (v == "") then
str = "-"
val = ""
else
str = ""
val = "="..v
end
str = r.."."..s
if o ~= ".type" then
str = str.."."..o
end
table.insert(ret, str..val)
end
end
end
return table.concat(ret, "\n")
end
function action_changes()
local changes = convert_changes(luci.model.uci.changes())
luci.template.render("admin_uci/changes", {changes=changes})
end
function action_apply()
local changes = luci.model.uci.changes()
local output = ""
if changes then
local com = {}
local run = {}
-- Collect files to be applied and commit changes
for r, tbl in pairs(changes) do
if r then
luci.model.uci.load(r)
luci.model.uci.commit(r)
luci.model.uci.unload(r)
if luci.config.uci_oncommit and luci.config.uci_oncommit[r] then
run[luci.config.uci_oncommit[r]] = true
end
end
end
-- Search for post-commit commands
for cmd, i in pairs(run) do
output = output .. cmd .. ":" .. luci.sys.exec(cmd) .. "\n"
end
end
luci.template.render("admin_uci/apply", {changes=convert_changes(changes), output=output})
end
function action_revert()
local changes = luci.model.uci.changes()
if changes then
local revert = {}
-- Collect files to be reverted
for r, tbl in pairs(changes) do
luci.model.uci.load(r)
luci.model.uci.revert(r)
luci.model.uci.unload(r)
end
end
luci.template.render("admin_uci/revert", {changes=convert_changes(changes)})
end
|
* Fixed an issue that prevented the controller from working with fastindex
|
* Fixed an issue that prevented the controller from working with fastindex
|
Lua
|
apache-2.0
|
deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.