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
ddb2c83a64fbf5ac2a3b0bd6060df62a28977ed0
controller/FlangChip.lua
controller/FlangChip.lua
require("lang.base.flang_import") FlangChip = {} FlangChip.__index = FlangChip function FlangChip:new(o) if not o then error("nil constructor!") end o = { entity = o.entity, source = o.source or "", interpreter = nil, is_running = o.is_running or false, -- debug shit -- optional straight to player console function printer = o.printer } setmetatable(o, self) self.__index = self return o end function FlangChip:update_source(source) self:stop_execution() self.source = source end --[[ Start the program, recreate the Flang interpreter. Does not call interpret however, simply readies the interpreter for it ]] function FlangChip:start_execution() -- recreate everything local success, result = pcall(create_flang_interpreter, self.source, self.entity, self.printer) if success then self.interpreter = result self.is_running = true self.printer("interpreter execution successful", true) else self.printer("interpreter error", true) self:on_error(result) self.is_running = false end return result end --[[ Stops the program. Does not modify the interpreter ]] function FlangChip:stop_execution() if (self.is_running) then self.printer("execution stopped") end self.is_running = false end function FlangChip:execute() if not self.is_running then return end if not self.interpreter then -- create the interpreter self:start_execution() -- if the interpreter failed here, then just return -- this check is duplicated so we don't keep trying to create the interpreter -- and error loop into oblivion if not self.is_running then return end end local success, result = pcall(self.interpreter.interpret, self.interpreter) if success then -- result is our symbol table for k,v in pairs(self.interpreter.global_symbol_scope.variable_table) do self.printer("key " .. k .. " val " .. v) end else self.is_running = false self.printer("execution error") self:on_error(result) end end function FlangChip:on_error(error) -- fuck self.printer("got error!") self.printer(tostring(error)) end function create_flang_interpreter(source, entity, printer) local lexer = Flang.Lexer:new({sourceText = source}) local parser = Flang.Parser:new({lexer = lexer}) -- Create our wrapper to pass in for function calls local wrapper = { entity = entity, printer = printer } local interpreter = Flang.Interpreter:new({parser = parser, wrapper = wrapper}) return interpreter end function FlangChip:__tostring() print("source:\n" .. self.source) end -- Flang.DEBUG_LOGGING = true -- -- Routes all print statements to the player chat. -- -- SHOULD NOT BE PRESENT IN PRODUCTION! -- local oldprint = print -- print = function(...) -- player_info_window_print(..., false) -- end
require("lang.base.flang_import") FlangChip = {} FlangChip.__index = FlangChip function FlangChip:new(o) if not o then error("nil constructor!") end o = { entity = o.entity, source = o.source or "", interpreter = nil, is_running = o.is_running or false, -- debug shit -- optional straight to player console function printer = o.printer } setmetatable(o, self) self.__index = self return o end function FlangChip:update_source(source) self:stop_execution() self.source = source end --[[ Start the program, recreate the Flang interpreter. Does not call interpret however, simply readies the interpreter for it ]] function FlangChip:start_execution() -- recreate everything local success, result = pcall(create_flang_interpreter, self.source, self.entity, self.printer) if success then self.interpreter = result self.is_running = true self.printer("interpreter execution successful", true) else self.printer("interpreter error", true) self:on_error(result) self.is_running = false end return result end --[[ Stops the program. Does not modify the interpreter ]] function FlangChip:stop_execution() if (self.is_running) then self.printer("execution stopped") end self.is_running = false end function FlangChip:execute() if not self.is_running then return end if not self.interpreter then -- create the interpreter self:start_execution() -- if the interpreter failed here, then just return -- this check is duplicated so we don't keep trying to create the interpreter -- and error loop into oblivion if not self.is_running then return end end local success, result = pcall(self.interpreter.interpret, self.interpreter) if success then -- result is our symbol table for k,value in pairs(self.interpreter.global_symbol_scope.variable_table) do if (Util.isTable(value)) then self.printer(k .. " = " .. Util.set_to_string(value, true)) else self.printer(k .. " = " .. tostring(value)) end end else self.is_running = false self.printer("execution error") self:on_error(result) end end function FlangChip:on_error(error) -- fuck self.printer("got error!") self.printer(tostring(error)) end function create_flang_interpreter(source, entity, printer) local lexer = Flang.Lexer:new({sourceText = source}) local parser = Flang.Parser:new({lexer = lexer}) -- Create our wrapper to pass in for function calls local wrapper = { entity = entity, printer = printer } local interpreter = Flang.Interpreter:new({parser = parser, wrapper = wrapper}) return interpreter end function FlangChip:__tostring() print("source:\n" .. self.source) end -- Flang.DEBUG_LOGGING = true -- -- Routes all print statements to the player chat. -- -- SHOULD NOT BE PRESENT IN PRODUCTION! -- local oldprint = print -- print = function(...) -- player_info_window_print(..., false) -- end
fixed table printing issue
fixed table printing issue
Lua
mit
radixdev/flang
02a9d0876614d0b882a5dba3cb1ea4701becda7f
share/lua/playlist/vimeo.lua
share/lua/playlist/vimeo.lua
--[[ $Id$ Copyright © 2009-2013 the VideoLAN team Authors: Konstantin Pavlov ([email protected]) François Revol ([email protected]) Pierre Ynard 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. --]] -- Probe function. function probe() return ( vlc.access == "http" or vlc.access == "https" ) and ( string.match( vlc.path, "vimeo%.com/%d+$" ) or string.match( vlc.path, "player%.vimeo%.com" ) ) -- do not match other addresses, -- else we'll also try to decode the actual video url end -- Parse function. function parse() if not string.match( vlc.path, "player%.vimeo%.com" ) then -- Web page URL while true do local line = vlc.readline() if not line then break end path = string.match( line, "data%-config%-url=\"(.-)\"" ) if path then path = vlc.strings.resolve_xml_special_chars( path ) return { { path = path } } end end vlc.msg.err( "Couldn't extract vimeo video URL, please check for updates to this script" ) return { } else -- API URL local prefres = vlc.var.inherit(nil, "preferred-resolution") local line = vlc.readline() -- data is on one line only for stream in string.gmatch( line, "{([^}]*\"profile\":[^}]*)}" ) do local url = string.match( stream, "\"url\":\"(.-)\"" ) if url then path = url if prefres < 0 then break end local height = string.match( stream, "\"height\":(%d+)[,}]" ) if not height or tonumber(height) <= prefres then break end end end if not path then vlc.msg.err( "Couldn't extract vimeo video URL, please check for updates to this script" ) return { } end local name = string.match( line, "\"title\":\"(.-)\"" ) local artist = string.match( line, "\"owner\":{[^}]-\"name\":\"(.-)\"" ) local arturl = string.match( line, "\"thumbs\":{\"[^\"]+\":\"(.-)\"" ) local duration = string.match( line, "\"duration\":(%d+)[,}]" ) return { { path = path; name = name; artist = artist; arturl = arturl; duration = duration } } end end
--[[ $Id$ Copyright © 2009-2013 the VideoLAN team Authors: Konstantin Pavlov ([email protected]) François Revol ([email protected]) Pierre Ynard 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. --]] -- Probe function. function probe() return ( vlc.access == "http" or vlc.access == "https" ) and ( string.match( vlc.path, "vimeo%.com/%d+$" ) or string.match( vlc.path, "player%.vimeo%.com" ) ) -- do not match other addresses, -- else we'll also try to decode the actual video url end -- Parse function. function parse() if not string.match( vlc.path, "player%.vimeo%.com" ) then -- Web page URL while true do local line = vlc.readline() if not line then break end path = string.match( line, "data%-config%-url=\"(.-)\"" ) if path then path = vlc.strings.resolve_xml_special_chars( path ) return { { path = path } } end end vlc.msg.err( "Couldn't extract vimeo video URL, please check for updates to this script" ) return { } else -- API URL local prefres = vlc.var.inherit(nil, "preferred-resolution") local bestres = nil local line = vlc.readline() -- data is on one line only for stream in string.gmatch( line, "{([^}]*\"profile\":[^}]*)}" ) do local url = string.match( stream, "\"url\":\"(.-)\"" ) if url then -- Apparently the different formats available are listed -- in uncertain order of quality, so compare with what -- we have so far. local height = string.match( stream, "\"height\":(%d+)[,}]" ) height = tonumber( height ) -- Better than nothing if not path or ( height and ( not bestres -- Better quality within limits or ( ( prefres < 0 or height <= prefres ) and height > bestres ) -- Lower quality more suited to limits or ( prefres > -1 and bestres > prefres and height < bestres ) ) ) then path = url bestres = height end end end if not path then vlc.msg.err( "Couldn't extract vimeo video URL, please check for updates to this script" ) return { } end local name = string.match( line, "\"title\":\"(.-)\"" ) local artist = string.match( line, "\"owner\":{[^}]-\"name\":\"(.-)\"" ) local arturl = string.match( line, "\"thumbs\":{\"[^\"]+\":\"(.-)\"" ) local duration = string.match( line, "\"duration\":(%d+)[,}]" ) return { { path = path; name = name; artist = artist; arturl = arturl; duration = duration } } end end
vimeo.lua: fix video quality selection
vimeo.lua: fix video quality selection Fixes #15778
Lua
lgpl-2.1
xkfz007/vlc,xkfz007/vlc,xkfz007/vlc,xkfz007/vlc,xkfz007/vlc,xkfz007/vlc,xkfz007/vlc
77ef9215fbee22b5e29e3e847073d63564f0ad6c
patch.lua
patch.lua
--- @module patch local patch = {} local function shallow_copy(t) local new = {} for k, v in pairs(t) do new[k] = v end setmetatable(new, getmetatable(t)) return new end local visit local function merge(orig, diff, mutate) if not next(diff) then -- empty diff return orig, nil end local new = orig if mutate == false then new = shallow_copy(orig) end local undo = {} for k, v in pairs(diff) do local new_v, undo_v = visit(orig[k], v, mutate) undo[k] = undo_v new[k] = new_v end return new, undo end local replace_mt = {} local update_mt = {} function visit(orig, diff, mutate) if diff == patch.Nil then diff = nil end if diff == orig then return orig, nil -- no-op end if orig == nil then orig = patch.Nil end if getmetatable(diff) == replace_mt then return diff.v, orig elseif getmetatable(diff) == update_mt then return diff.fn(orig, unpack(diff.args, 1, diff.n)), orig elseif type(diff) == 'table' then return merge(orig, diff, mutate) else return diff, orig end end --- The "nil" updater. When you want to set a field to nil, use this instead of -- nil directly. patch.Nil = {} --- Returns a "replace" updater. This forces patch() to replace the field with -- the given value. This can be used for anything, including `nil` and other. -- updaters. -- @param v the new value function patch.replace(v) return setmetatable({v = v}, replace_mt) end --- Returns a custom updater. Takes a function that, given an old value, -- returns an a new, updated value. -- @param fn the updater function -- @param ... extra arguments to pass to fn function patch.update(fn, ...) return setmetatable({fn = fn, n = select('#', ...), args = {...}}, update_mt) end --- Returns the patched version of the input value. Patches are a compound -- datatype that can be made of normal Lua values, as well as "updaters" that -- have specific patching strategies. -- @tparam any input the input value -- @tparam Diff patch the patch to apply function patch.apply(input, patch) return visit(input, patch, false) end --- Applies a patch to the input value directly. This should return the same -- thing as patch.apply(), but the input value is left in an undefined state. -- @tparam any input the input value -- @tparam Diff patch the patch to apply function patch.apply_inplace(input, patch) return visit(input, patch, true) end return patch
--- @module patch local patch = {} local function shallow_copy(t) local new = {} for k, v in pairs(t) do new[k] = v end setmetatable(new, getmetatable(t)) return new end local visit local function merge(orig, diff, mutate) if not next(diff) then -- empty diff return orig, nil end local new = orig if mutate == false then new = shallow_copy(orig) end local undo = {} for k, v in pairs(diff) do local new_v, undo_v = visit(orig[k], v, mutate) undo[k] = undo_v new[k] = new_v end return new, undo end local function remove_i(orig, i, mutate) local new = orig if mutate == false then new = shallow_copy(orig) end local v = table.remove(new, i) return new, patch.insert_i(i, v) end local function insert_i(orig, i, v, mutate) local new = orig if mutate == false then new = shallow_copy(orig) end table.insert(new, i, v) return new, patch.remove_i(i) end local replace_mt = {REPLACE=true} local remove_i_mt = {REMOVE_I=true} local insert_i_mt = {INSERT_I=true} local update_mt = {UPDATE=true} function visit(orig, diff, mutate) if diff == patch.Nil then diff = nil end if diff == orig then return orig, nil -- no-op end if orig == nil then orig = patch.Nil end if getmetatable(diff) == replace_mt then return diff.v, patch.replace(orig) elseif getmetatable(diff) == remove_i_mt then assert(orig ~= patch.Nil) assert(type(orig) == 'table') return remove_i(orig, diff.i, mutate) elseif getmetatable(diff) == insert_i_mt then assert(orig ~= patch.Nil) assert(type(orig) == 'table') return insert_i(orig, diff.i, diff.v, mutate) elseif orig == patch.Nil then return diff, orig elseif getmetatable(diff) == update_mt then return diff.fn(orig, unpack(diff.args, 1, diff.n)), patch.replace(orig) elseif type(diff) == 'table' and type(orig) == 'table' then return merge(orig, diff, mutate) else return diff, patch.replace(orig) end end --- The "nil" updater. When you want to set a field to nil, use this instead of -- nil directly. patch.Nil = setmetatable({}, {NIL = true}) --- Returns a "replace" updater. This forces patch() to replace the field with -- the given value. This can be used for anything, including `nil` and other. -- updaters. -- @param v the new value function patch.replace(v) return setmetatable({v = v}, replace_mt) end --- Returns a "remove_i" updater. This is equivalent to table.remove. function patch.remove_i(i) assert(i == nil or type(i) == 'number') return setmetatable({i = i}, remove_i_mt) end --- Returns an "insert_i" updater. This is equivalent to table.insert() function patch.insert_i(i, v) assert(i == nil or type(i) == 'number') return setmetatable({i = i, v = v}, insert_i_mt) end --- Returns a custom updater. Takes a function that, given an old value, -- returns an a new, updated value. -- @param fn the updater function -- @param ... extra arguments to pass to fn function patch.update(fn, ...) return setmetatable({fn = fn, n = select('#', ...), args = {...}}, update_mt) end -- joins multiple patches together function patch.join(...) error("NYI") end --- Returns the patched version of the input value. Patches are a compound -- datatype that can be made of normal Lua values, as well as "updaters" that -- have specific patching strategies. -- @tparam any input the input value -- @tparam Diff patch the patch to apply function patch.apply(input, patch) return visit(input, patch, false) end --- Applies a patch to the input value directly. This should return the same -- thing as patch.apply(), but the input value is left in an undefined state. -- @tparam any input the input value -- @tparam Diff patch the patch to apply function patch.apply_inplace(input, patch) return visit(input, patch, true) end return patch
Backport fixes from private repo
Backport fixes from private repo oops indentation
Lua
mit
Alloyed/patch.lua
71cadc8a0e3e8b662346ad61b7f80a79f0c26f21
AceGUI-3.0/widgets/AceGUIWidget-EditBox.lua
AceGUI-3.0/widgets/AceGUIWidget-EditBox.lua
local AceGUI = LibStub("AceGUI-3.0") -------------------------- -- Edit box -- -------------------------- --[[ Events : OnTextChanged OnEnterPressed ]] do local Type = "EditBox" local Version = 8 local function OnAcquire(self) self:SetDisabled(false) self.showbutton = true end local function OnRelease(self) self.frame:ClearAllPoints() self.frame:Hide() 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 EditBox_OnEscapePressed(this) this:ClearFocus() end local function ShowButton(self) if self.showbutton then self.button:Show() self.editbox:SetTextInsets(0,20,3,3) end end local function HideButton(self) self.button:Hide() self.editbox:SetTextInsets(0,0,3,3) end local function EditBox_OnEnterPressed(this) local self = this.obj local value = this:GetText() local cancel = self:Fire("OnEnterPressed",value) if not cancel then HideButton(self) end end local function Button_OnClick(this) local editbox = this.obj.editbox editbox:ClearFocus() EditBox_OnEnterPressed(editbox) end local function EditBox_OnReceiveDrag(this) local self = this.obj local type, id, info = GetCursorInfo() if type == "item" then self:SetText(info) self:Fire("OnEnterPressed",info) ClearCursor() elseif type == "spell" then local name, rank = GetSpellName(id, info) if rank and rank:match("%d") then name = name.."("..rank..")" end self:SetText(name) self:Fire("OnEnterPressed",name) ClearCursor() end HideButton(self) AceGUI:ClearFocus() end local function EditBox_OnTextChanged(this) local self = this.obj local value = this:GetText() if value ~= self.lasttext then self:Fire("OnTextChanged",value) self.lasttext = value ShowButton(self) end end local function SetDisabled(self, disabled) self.disabled = disabled if disabled then self.editbox:EnableMouse(false) self.editbox:ClearFocus() self.editbox:SetTextColor(0.5,0.5,0.5) self.label:SetTextColor(0.5,0.5,0.5) else self.editbox:EnableMouse(true) self.editbox:SetTextColor(1,1,1) self.label:SetTextColor(1,.82,0) end end local function SetText(self, text) self.lasttext = text or "" self.editbox:SetText(text or "") self.editbox:SetCursorPosition(0) HideButton(self) end local function SetWidth(self, width) self.frame:SetWidth(width) end local function SetLabel(self, text) if text and text ~= "" then self.label:SetText(text) self.label:Show() self.editbox:SetPoint("TOPLEFT",self.frame,"TOPLEFT",7,-18) self.frame:SetHeight(44) else self.label:SetText("") self.label:Hide() self.editbox:SetPoint("TOPLEFT",self.frame,"TOPLEFT",7,0) self.frame:SetHeight(26) end end local function Constructor() local num = AceGUI:GetNextWidgetNum(Type) local frame = CreateFrame("Frame",nil,UIParent) local editbox = CreateFrame("EditBox","AceGUI-3.0EditBox"..num,frame,"InputBoxTemplate") local self = {} self.type = Type self.num = num self.OnRelease = OnRelease self.OnAcquire = OnAcquire self.SetDisabled = SetDisabled self.SetText = SetText self.SetWidth = SetWidth self.SetLabel = SetLabel self.frame = frame frame.obj = self self.editbox = editbox editbox.obj = self self.alignoffset = 30 frame:SetHeight(44) frame:SetWidth(200) editbox:SetScript("OnEnter",Control_OnEnter) editbox:SetScript("OnLeave",Control_OnLeave) editbox:SetAutoFocus(false) editbox:SetFontObject(ChatFontNormal) editbox:SetScript("OnEscapePressed",EditBox_OnEscapePressed) editbox:SetScript("OnEnterPressed",EditBox_OnEnterPressed) editbox:SetScript("OnTextChanged",EditBox_OnTextChanged) editbox:SetScript("OnReceiveDrag", EditBox_OnReceiveDrag) editbox:SetScript("OnMouseDown", EditBox_OnReceiveDrag) editbox:SetTextInsets(0,0,3,3) editbox:SetMaxLetters(256) editbox:SetPoint("BOTTOMLEFT",frame,"BOTTOMLEFT",6,0) editbox:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",0,0) editbox:SetHeight(19) local label = frame:CreateFontString(nil,"OVERLAY","GameFontNormalSmall") label:SetPoint("TOPLEFT",frame,"TOPLEFT",0,-2) label:SetPoint("TOPRIGHT",frame,"TOPRIGHT",0,-2) label:SetJustifyH("LEFT") label:SetHeight(18) self.label = label local button = CreateFrame("Button",nil,editbox,"UIPanelButtonTemplate") button:SetWidth(40) button:SetHeight(20) button:SetPoint("RIGHT",editbox,"RIGHT",-2,0) button:SetText(OKAY) button:SetScript("OnClick", Button_OnClick) button:Hide() self.button = button button.obj = self AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(Type,Constructor,Version) end
local AceGUI = LibStub("AceGUI-3.0") -------------------------- -- Edit box -- -------------------------- --[[ Events : OnTextChanged OnEnterPressed ]] do local Type = "EditBox" local Version = 9 local function OnAcquire(self) self:SetDisabled(false) self.showbutton = true end local function OnRelease(self) self.frame:ClearAllPoints() self.frame:Hide() 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 EditBox_OnEscapePressed(this) this:ClearFocus() end local function ShowButton(self) if self.showbutton then self.button:Show() self.editbox:SetTextInsets(0,20,3,3) end end local function HideButton(self) self.button:Hide() self.editbox:SetTextInsets(0,0,3,3) end local function EditBox_OnEnterPressed(this) local self = this.obj local value = this:GetText() local cancel = self:Fire("OnEnterPressed",value) if not cancel then HideButton(self) end end local function Button_OnClick(this) local editbox = this.obj.editbox editbox:ClearFocus() EditBox_OnEnterPressed(editbox) end local function EditBox_OnReceiveDrag(this) local self = this.obj local type, id, info = GetCursorInfo() if type == "item" then self:SetText(info) self:Fire("OnEnterPressed",info) ClearCursor() elseif type == "spell" then local name, rank = GetSpellName(id, info) if rank and rank:match("%d") then name = name.."("..rank..")" end self:SetText(name) self:Fire("OnEnterPressed",name) ClearCursor() end HideButton(self) AceGUI:ClearFocus() end local function EditBox_OnTextChanged(this) local self = this.obj local value = this:GetText() if value ~= self.lasttext then self:Fire("OnTextChanged",value) self.lasttext = value ShowButton(self) end end local function SetDisabled(self, disabled) self.disabled = disabled if disabled then self.editbox:EnableMouse(false) self.editbox:ClearFocus() self.editbox:SetTextColor(0.5,0.5,0.5) self.label:SetTextColor(0.5,0.5,0.5) else self.editbox:EnableMouse(true) self.editbox:SetTextColor(1,1,1) self.label:SetTextColor(1,.82,0) end end local function SetText(self, text) self.lasttext = text or "" self.editbox:SetText(text or "") self.editbox:SetCursorPosition(0) HideButton(self) end local function SetWidth(self, width) self.frame:SetWidth(width) end local function SetLabel(self, text) if text and text ~= "" then self.label:SetText(text) self.label:Show() self.editbox:SetPoint("TOPLEFT",self.frame,"TOPLEFT",7,-18) self.frame:SetHeight(44) self.alignoffset = 30 else self.label:SetText("") self.label:Hide() self.editbox:SetPoint("TOPLEFT",self.frame,"TOPLEFT",7,0) self.frame:SetHeight(26) self.alignoffset = 12 end end local function Constructor() local num = AceGUI:GetNextWidgetNum(Type) local frame = CreateFrame("Frame",nil,UIParent) local editbox = CreateFrame("EditBox","AceGUI-3.0EditBox"..num,frame,"InputBoxTemplate") local self = {} self.type = Type self.num = num self.OnRelease = OnRelease self.OnAcquire = OnAcquire self.SetDisabled = SetDisabled self.SetText = SetText self.SetWidth = SetWidth self.SetLabel = SetLabel self.frame = frame frame.obj = self self.editbox = editbox editbox.obj = self self.alignoffset = 30 frame:SetHeight(44) frame:SetWidth(200) editbox:SetScript("OnEnter",Control_OnEnter) editbox:SetScript("OnLeave",Control_OnLeave) editbox:SetAutoFocus(false) editbox:SetFontObject(ChatFontNormal) editbox:SetScript("OnEscapePressed",EditBox_OnEscapePressed) editbox:SetScript("OnEnterPressed",EditBox_OnEnterPressed) editbox:SetScript("OnTextChanged",EditBox_OnTextChanged) editbox:SetScript("OnReceiveDrag", EditBox_OnReceiveDrag) editbox:SetScript("OnMouseDown", EditBox_OnReceiveDrag) editbox:SetTextInsets(0,0,3,3) editbox:SetMaxLetters(256) editbox:SetPoint("BOTTOMLEFT",frame,"BOTTOMLEFT",6,0) editbox:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",0,0) editbox:SetHeight(19) local label = frame:CreateFontString(nil,"OVERLAY","GameFontNormalSmall") label:SetPoint("TOPLEFT",frame,"TOPLEFT",0,-2) label:SetPoint("TOPRIGHT",frame,"TOPRIGHT",0,-2) label:SetJustifyH("LEFT") label:SetHeight(18) self.label = label local button = CreateFrame("Button",nil,editbox,"UIPanelButtonTemplate") button:SetWidth(40) button:SetHeight(20) button:SetPoint("RIGHT",editbox,"RIGHT",-2,0) button:SetText(OKAY) button:SetScript("OnClick", Button_OnClick) button:Hide() self.button = button button.obj = self AceGUI:RegisterAsWidget(self) return self end AceGUI:RegisterWidgetType(Type,Constructor,Version) end
AceGUI-3.0: Fix EditBox alignment if the label is disabled.
AceGUI-3.0: Fix EditBox alignment if the label is disabled. Closes Ticket #13 git-svn-id: e768786be8df873dac9515156656ebbdc6d77160@720 5debad98-a965-4143-8383-f471b3509dcf
Lua
bsd-3-clause
sarahgerweck/Ace3
fc06688c19a7ece6f9af70a3f10631c170f00955
rules/regexp/upstream_spam_filters.lua
rules/regexp/upstream_spam_filters.lua
--[[ Copyright (c) 2011-2016, Vsevolod Stakhov <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 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. ]]-- -- Rules for upstream services that have already run spam checks reconf['PRECEDENCE_BULK'] = { re = 'Precedence=/bulk/Hi', score = 0.1, description = "Message marked as bulk", group = 'upstream_spam_filters' } reconf['MICROSOFT_SPAM'] = { -- https://technet.microsoft.com/en-us/library/dn205071(v=exchg.150).aspx re = 'X-Forefront-Antispam-Report=/SFV:SPM/H', score = 10, description = "Microsoft says the messge is spam", group = 'upstream_spam_filters' } reconf['AOL_SPAM'] = { re = 'X-AOL-Global-Disposition=/^S/H', score = 5, description = "AOL says this message is spam", group = 'upstream_spam_filters' } reconf['SPAM_FLAG'] = { re = 'X-Spam-Flag=/^(?:yes|true)/Hi', score = 5, description = "Message was already marked as spam", group = 'upstream_spam_filters' }
--[[ Copyright (c) 2011-2016, Vsevolod Stakhov <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 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. ]]-- -- Rules for upstream services that have already run spam checks local reconf = config['regexp'] reconf['PRECEDENCE_BULK'] = { re = 'Precedence=/bulk/Hi', score = 0.1, description = "Message marked as bulk", group = 'upstream_spam_filters' } reconf['MICROSOFT_SPAM'] = { -- https://technet.microsoft.com/en-us/library/dn205071(v=exchg.150).aspx re = 'X-Forefront-Antispam-Report=/SFV:SPM/H', score = 10, description = "Microsoft says the messge is spam", group = 'upstream_spam_filters' } reconf['AOL_SPAM'] = { re = 'X-AOL-Global-Disposition=/^S/H', score = 5, description = "AOL says this message is spam", group = 'upstream_spam_filters' } reconf['SPAM_FLAG'] = { re = 'X-Spam-Flag=/^(?:yes|true)/Hi', score = 5, description = "Message was already marked as spam", group = 'upstream_spam_filters' }
Fix upstream_spam_filters
Fix upstream_spam_filters
Lua
apache-2.0
minaevmike/rspamd,AlexeySa/rspamd,minaevmike/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,minaevmike/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,minaevmike/rspamd,andrejzverev/rspamd,minaevmike/rspamd,minaevmike/rspamd,AlexeySa/rspamd,minaevmike/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,minaevmike/rspamd,minaevmike/rspamd,AlexeySa/rspamd,andrejzverev/rspamd,AlexeySa/rspamd,andrejzverev/rspamd
c4a95b2f5c11828970ecf266e910cd24e6df87ed
hostinfo/misc.lua
hostinfo/misc.lua
--[[ Copyright 2015 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 table = require('table') local misc = require('virgo/util/misc') local async = require('async') local childProcess = require('childprocess') local string = require('string') local fs = require('fs') local function execFileToBuffers(command, args, options, callback) local child, stdout, stderr, exitCode stdout = {} stderr = {} callback = misc.fireOnce(callback) child = childProcess.spawn(command, args, options) child.stdout:on('data', function (chunk) table.insert(stdout, chunk) end) child.stderr:on('data', function (chunk) table.insert(stderr, chunk) end) async.parallel({ function(callback) child.stdout:on('end', callback) end, function(callback) child.stderr:on('end', callback) end, function(callback) local onExit function onExit(code) exitCode = code callback() end child:on('exit', onExit) end }, function(err) callback(err, exitCode, table.concat(stdout, ""), table.concat(stderr, "")) end) end local function readCast(filePath, errHandler, outTable, casterFunc, callback) -- Sanity checks if (type(filePath) ~= 'string') then filePath = '' end if (type(errHandler) ~= 'table') then errHandler = {} end if (type(outTable) ~= 'table') then outTable = {} end if (type(casterFunc) ~= 'function') then function casterFunc(...) end end if (type(callback) ~= 'function') then function callback(...) end end local obj = {} fs.exists(filePath, function(err, file) if err then table.insert(errHandler, string.format('fs.exists in fstab.lua erred: %s', err)) return callback() end if file then fs.readFile(filePath, function(err, data) if err then table.insert(errHandler, string.format('fs.readline erred: %s', err)) return callback() end for line in data:gmatch("[^\r\n]+") do local iscomment = string.match(line, '^#') local isblank = string.len(line:gsub("%s+", "")) <= 0 if not iscomment and not isblank then -- split the line and assign key vals local iter = line:gmatch("%S+") casterFunc(iter, obj, line) end end -- Flatten single entry objects if #obj == 1 then obj = obj[1] end -- Dont insert empty objects into the outTable if next(obj) then table.insert(outTable, obj) end return callback() end) else table.insert(errHandler, 'file not found') return callback() end end) end return {execFileToBuffers=execFileToBuffers, readCast=readCast}
--[[ Copyright 2015 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 table = require('table') local async = require('async') local childProcess = require('childprocess') local string = require('string') local fs = require('fs') local function execFileToBuffers(command, args, options, callback) local child, stdout, stderr, exitCode stdout = {} stderr = {} child = childProcess.spawn(command, args, options) child.stdout:on('data', function (chunk) table.insert(stdout, chunk) end) child.stderr:on('data', function (chunk) table.insert(stderr, chunk) end) async.parallel({ function(callback) child.stdout:on('end', callback) end, function(callback) child.stderr:on('end', callback) end, function(callback) local onExit function onExit(code) exitCode = code callback() end child:on('exit', onExit) end }, function(err) callback(err, exitCode, table.concat(stdout, ""), table.concat(stderr, "")) end) end local function readCast(filePath, errTable, outTable, casterFunc, callback) -- Sanity checks if (type(filePath) ~= 'string') then filePath = '' end if (type(errTable) ~= 'table') then errTable = {} end if (type(outTable) ~= 'table') then outTable = {} end if (type(casterFunc) ~= 'function') then function casterFunc(iter, obj, line) end end if (type(callback) ~= 'function') then function callback() end end local obj = {} fs.exists(filePath, function(err, file) if err then table.insert(errTable, string.format('File not found : { fs.exists erred: %s }', err)) return callback() end if file then fs.readFile(filePath, function(err, data) if err then table.insert(errTable, string.format('File couldnt be read : { fs.readline erred: %s }', err)) return callback() end for line in data:gmatch("[^\r\n]+") do local iscomment = string.match(line, '^#') local isblank = string.len(line:gsub("%s+", "")) <= 0 if not iscomment and not isblank then -- split the line and assign key vals local iter = line:gmatch("%S+") casterFunc(iter, obj, line) end end -- Flatten single entry objects if #obj == 1 then obj = obj[1] end -- Dont insert empty objects into the outTable if next(obj) then table.insert(outTable, obj) end return callback() end) else table.insert(errTable, 'file not found') return callback() end end) end local function asyncSpawn(dataArr, spawnFunc, successFunc, finalCb) -- Sanity checks if type(dataArr) ~= 'table' then if dataArr ~= nil then local obj = {} table.insert(obj, dataArr) dataArr = obj return end dataArr = {} end if type(spawnFunc) ~= 'function' then function spawnFunc(datum) return '', {} end end if type(successFunc) ~= 'function' then function successFunc(data, emptyObj, datum) end end if type(finalCb) ~= 'function' then function finalCb(obj, errdata) end end -- Asynchronous spawn cps & gather data local obj = {} async.forEachLimit(dataArr, 5, function(datum, cb) local function _successFunc(err, exitcode, data, stderr) successFunc(data, obj, datum, exitcode) return cb() end local cmd, args = spawnFunc(datum) return execFileToBuffers(cmd, args, opts, _successFunc) end, function() return finalCb(obj, errdata) end) end return {execFileToBuffers=execFileToBuffers, readCast=readCast, asyncSpawn=asyncSpawn}
feat(hostinfo/misc): Added a reusable async spawn and data gather function in misc
feat(hostinfo/misc): Added a reusable async spawn and data gather function in misc fix(hostinfo/misc): remove redundant fireonce from execfiletobuffers and rewrite asyncspawn to rely on execfiletobuffers
Lua
apache-2.0
kaustavha/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent
bdde6ae161db2b717574547c20f7095363ff5320
kong/api/routes/kong.lua
kong/api/routes/kong.lua
local singletons = require "kong.singletons" local conf_loader = require "kong.conf_loader" local cjson = require "cjson" local api_helpers = require "kong.api.api_helpers" local Schema = require "kong.db.schema" local Errors = require "kong.db.errors" local process = require "ngx.process" local kong = kong local knode = (kong and kong.node) and kong.node or require "kong.pdk.node".new() local errors = Errors.new() local tagline = "Welcome to " .. _KONG._NAME local version = _KONG._VERSION local lua_version = jit and jit.version or _VERSION local strip_foreign_schemas = function(fields) for _, field in ipairs(fields) do local fname = next(field) local fdata = field[fname] if fdata["type"] == "foreign" then fdata.schema = nil end end end local function validate_schema(db_entity_name, params) local entity = kong.db[db_entity_name] local schema = entity and entity.schema or nil if not schema then return kong.response.exit(404, { message = "No entity named '" .. db_entity_name .. "'" }) end local schema = assert(Schema.new(schema)) local _, err_t = schema:validate(schema:process_auto_fields(params, "insert")) if err_t then return kong.response.exit(400, errors:schema_violation(err_t)) end return kong.response.exit(200, { message = "schema validation successful" }) end return { ["/"] = { GET = function(self, dao, helpers) local distinct_plugins = setmetatable({}, cjson.array_mt) local pids = { master = process.get_master_pid() } do local set = {} for row, err in kong.db.plugins:each() do if err then kong.log.err(err) return kong.response.exit(500, { message = "An unexpected error happened" }) end if not set[row.name] then distinct_plugins[#distinct_plugins+1] = row.name set[row.name] = true end end end do local kong_shm = ngx.shared.kong local worker_count = ngx.worker.count() - 1 for i = 0, worker_count do local worker_pid, err = kong_shm:get("pids:" .. i) if not worker_pid then err = err or "not found" ngx.log(ngx.ERR, "could not get worker process id for worker #", i , ": ", err) else if not pids.workers then pids.workers = {} end pids.workers[i + 1] = worker_pid end end end local node_id, err = knode.get_id() if node_id == nil then ngx.log(ngx.ERR, "could not get node id: ", err) end local available_plugins = {} for name in pairs(singletons.configuration.loaded_plugins) do available_plugins[name] = { version = kong.db.plugins.handlers[name].VERSION, priority = kong.db.plugins.handlers[name].PRIORITY, } end return kong.response.exit(200, { tagline = tagline, version = version, hostname = knode.get_hostname(), node_id = node_id, timers = { running = ngx.timer.running_count(), pending = ngx.timer.pending_count(), }, plugins = { available_on_server = available_plugins, enabled_in_cluster = distinct_plugins, }, lua_version = lua_version, configuration = conf_loader.remove_sensitive(singletons.configuration), pids = pids, }) end }, ["/endpoints"] = { GET = function(self, dao, helpers) local endpoints = setmetatable({}, cjson.array_mt) local lapis_endpoints = require("kong.api").ordered_routes for k, v in pairs(lapis_endpoints) do if type(k) == "string" then -- skip numeric indices endpoints[#endpoints + 1] = k:gsub(":([^/:]+)", function(m) return "{" .. m .. "}" end) end end table.sort(endpoints, function(a, b) -- when sorting use lower-ascii char for "/" to enable segment based -- sorting, so not this: -- /a -- /ab -- /ab/a -- /a/z -- But this: -- /a -- /a/z -- /ab -- /ab/a return a:gsub("/", "\x00") < b:gsub("/", "\x00") end) return kong.response.exit(200, { data = endpoints }) end }, ["/schemas/:name"] = { GET = function(self, db, helpers) local entity = kong.db[self.params.name] local schema = entity and entity.schema or nil if not schema then return kong.response.exit(404, { message = "No entity named '" .. self.params.name .. "'" }) end local copy = api_helpers.schema_to_jsonable(schema) strip_foreign_schemas(copy.fields) return kong.response.exit(200, copy) end }, ["/schemas/plugins/validate"] = { POST = function(self, db, helpers) return validate_schema("plugins", self.params) end }, ["/schemas/:db_entity_name/validate"] = { POST = function(self, db, helpers) local db_entity_name = self.params.db_entity_name -- What happens when db_entity_name is a field name in the schema? self.params.db_entity_name = nil return validate_schema(db_entity_name, self.params) end }, ["/schemas/plugins/:name"] = { GET = function(self, db, helpers) local subschema = kong.db.plugins.schema.subschemas[self.params.name] if not subschema then return kong.response.exit(404, { message = "No plugin named '" .. self.params.name .. "'" }) end local copy = api_helpers.schema_to_jsonable(subschema) strip_foreign_schemas(copy.fields) return kong.response.exit(200, copy) end }, }
local singletons = require "kong.singletons" local conf_loader = require "kong.conf_loader" local cjson = require "cjson" local api_helpers = require "kong.api.api_helpers" local Schema = require "kong.db.schema" local Errors = require "kong.db.errors" local process = require "ngx.process" local kong = kong local knode = (kong and kong.node) and kong.node or require "kong.pdk.node".new() local errors = Errors.new() local tagline = "Welcome to " .. _KONG._NAME local version = _KONG._VERSION local lua_version = jit and jit.version or _VERSION local strip_foreign_schemas = function(fields) for _, field in ipairs(fields) do local fname = next(field) local fdata = field[fname] if fdata["type"] == "foreign" then fdata.schema = nil end end end local function validate_schema(db_entity_name, params) local entity = kong.db[db_entity_name] local schema = entity and entity.schema or nil if not schema then return kong.response.exit(404, { message = "No entity named '" .. db_entity_name .. "'" }) end local schema = assert(Schema.new(schema)) local _, err_t = schema:validate(schema:process_auto_fields(params, "insert")) if err_t then return kong.response.exit(400, errors:schema_violation(err_t)) end return kong.response.exit(200, { message = "schema validation successful" }) end return { ["/"] = { GET = function(self, dao, helpers) local distinct_plugins = setmetatable({}, cjson.array_mt) local pids = { master = process.get_master_pid() } do local set = {} for row, err in kong.db.plugins:each() do if err then kong.log.err(err) return kong.response.exit(500, { message = "An unexpected error happened" }) end if not set[row.name] then distinct_plugins[#distinct_plugins+1] = row.name set[row.name] = true end end end do local kong_shm = ngx.shared.kong local worker_count = ngx.worker.count() - 1 for i = 0, worker_count do local worker_pid, err = kong_shm:get("pids:" .. i) if not worker_pid then err = err or "not found" ngx.log(ngx.ERR, "could not get worker process id for worker #", i , ": ", err) else if not pids.workers then pids.workers = {} end pids.workers[i + 1] = worker_pid end end end local node_id, err = knode.get_id() if node_id == nil then ngx.log(ngx.ERR, "could not get node id: ", err) end local available_plugins = {} for name in pairs(singletons.configuration.loaded_plugins) do local pr = kong.db.plugins.handlers[name].PRIORITY if pr ~= nil then if type(pr) ~= "number" or math.abs(pr) == math.huge then pr = tostring(pr) end end available_plugins[name] = { version = kong.db.plugins.handlers[name].VERSION, priority = pr, } end return kong.response.exit(200, { tagline = tagline, version = version, hostname = knode.get_hostname(), node_id = node_id, timers = { running = ngx.timer.running_count(), pending = ngx.timer.pending_count(), }, plugins = { available_on_server = available_plugins, enabled_in_cluster = distinct_plugins, }, lua_version = lua_version, configuration = conf_loader.remove_sensitive(singletons.configuration), pids = pids, }) end }, ["/endpoints"] = { GET = function(self, dao, helpers) local endpoints = setmetatable({}, cjson.array_mt) local lapis_endpoints = require("kong.api").ordered_routes for k, v in pairs(lapis_endpoints) do if type(k) == "string" then -- skip numeric indices endpoints[#endpoints + 1] = k:gsub(":([^/:]+)", function(m) return "{" .. m .. "}" end) end end table.sort(endpoints, function(a, b) -- when sorting use lower-ascii char for "/" to enable segment based -- sorting, so not this: -- /a -- /ab -- /ab/a -- /a/z -- But this: -- /a -- /a/z -- /ab -- /ab/a return a:gsub("/", "\x00") < b:gsub("/", "\x00") end) return kong.response.exit(200, { data = endpoints }) end }, ["/schemas/:name"] = { GET = function(self, db, helpers) local entity = kong.db[self.params.name] local schema = entity and entity.schema or nil if not schema then return kong.response.exit(404, { message = "No entity named '" .. self.params.name .. "'" }) end local copy = api_helpers.schema_to_jsonable(schema) strip_foreign_schemas(copy.fields) return kong.response.exit(200, copy) end }, ["/schemas/plugins/validate"] = { POST = function(self, db, helpers) return validate_schema("plugins", self.params) end }, ["/schemas/:db_entity_name/validate"] = { POST = function(self, db, helpers) local db_entity_name = self.params.db_entity_name -- What happens when db_entity_name is a field name in the schema? self.params.db_entity_name = nil return validate_schema(db_entity_name, self.params) end }, ["/schemas/plugins/:name"] = { GET = function(self, db, helpers) local subschema = kong.db.plugins.schema.subschemas[self.params.name] if not subschema then return kong.response.exit(404, { message = "No plugin named '" .. self.params.name .. "'" }) end local copy = api_helpers.schema_to_jsonable(subschema) strip_foreign_schemas(copy.fields) return kong.response.exit(200, copy) end }, }
fix(api) metadata represent infinity and non-numbers (#8833)
fix(api) metadata represent infinity and non-numbers (#8833)
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
611ccde8ff7a2a342255ed93b2a706208a6c545f
core/ext/mime_types.lua
core/ext/mime_types.lua
-- Copyright 2007-2009 Mitchell mitchell<att>caladbolg.net. See LICENSE. local textadept = _G.textadept local locale = _G.locale --- -- Handles file-specific settings. module('textadept.mime_types', package.seeall) -- Markdown: -- ## Overview -- -- Files can be recognized and associated with programming language lexers in -- three ways: -- -- * By file extension. -- * By keywords in the file's shebang (`#!/path/to/exe`) line. -- * By a pattern that matches the file's first line. -- -- If a lexer is not associated with a file you open, first make sure the lexer -- exists in `lexers/`. If it does not, you will need to write one. Consult the -- [lexer][lexer] module for a tutorial. -- -- [lexer]: ../modules/lexer.html -- -- ## Configuration File -- -- `core/ext/mime_types.conf` is the configuration file for mime-type detection. -- -- #### Detection by File Extension -- -- file_ext lexer -- -- Note: `file_ext` should not start with a `.` (period). -- -- #### Detection by Shebang Keywords -- -- #shebang_word lexer -- -- Examples of `shebang_word`'s are `lua`, `ruby`, `python`. -- -- #### Detection by Pattern -- -- /pattern lexer -- -- Only the last space, the one separating the pattern from the lexer, is -- significant. No spaces in the pattern need to be escaped. -- -- ## Extras -- -- This module adds an extra function to `buffer`: -- -- * **buffer:set\_lexer** (language)<br /> -- Replacement for [`buffer:set_lexer_language()`][buffer_set_lexer_language].<br /> -- Sets a buffer._lexer field so it can be restored without querying the -- mime-types tables. Also if the user manually sets the lexer, it should be -- restored.<br /> -- Loads the language-specific module if it exists. -- - lang: The string language to set. -- -- [buffer_set_lexer_language]: buffer.html#buffer:set_lexer_language --- -- File extensions with their associated lexers. -- @class table -- @name extensions extensions = {} --- -- Shebang words and their associated lexers. -- @class table -- @name shebangs shebangs = {} --- -- First-line patterns and their associated lexers. -- @class table -- @name patterns patterns = {} -- Load mime-types from mime_types.conf local f = io.open(_HOME..'/core/ext/mime_types.conf', 'rb') if f then for line in f:lines() do if not line:find('^%s*%%') then if line:find('^%s*[^#/]') then -- extension definition local ext, lexer_name = line:match('^%s*(.+)%s+(%S+)$') if ext and lexer_name then extensions[ext] = lexer_name end else -- shebang or pattern local ch, text, lexer_name = line:match('^%s*([#/])(.+)%s+(%S+)$') if ch and text and lexer_name then (ch == '#' and shebangs or patterns)[text] = lexer_name end end end end f:close() end -- -- Replacement for buffer:set_lexer_language(). -- Sets a buffer._lexer field so it can be restored without querying the -- mime-types tables. Also if the user manually sets the lexer, it should be -- restored. -- Loads the language-specific module if it exists. -- @param buffer The buffer to set the lexer language of. -- @param lang The string language to set. -- @usage buffer:set_lexer('language_name') local function set_lexer(buffer, lang) buffer._lexer = lang buffer:set_lexer_language(lang) local ret, err = pcall(require, lang) if ret then _m[lang].set_buffer_properties() elseif not ret and not err:find("^module '"..lang.."' not found:") then error(err) end end textadept.events.add_handler('buffer_new', function() buffer.set_lexer = set_lexer end) buffer.set_lexer = set_lexer -- Scintilla's first buffer doesn't have this -- Performs actions suitable for a new buffer. -- Sets the buffer's lexer language and loads the language module. local function handle_new() local lexer if buffer.filename then lexer = extensions[buffer.filename:match('[^/\\.]+$')] end if not lexer then local line = buffer:get_line(0) if line:find('^#!') then for word in line:gsub('[/\\]', ' '):gmatch('%S+') do lexer = shebangs[word] if lexer then break end end end if not lexer then for patt, lex in pairs(patterns) do if line:find(patt) then lexer = lex break end end end end buffer:set_lexer(lexer or 'container') end -- Sets the buffer's lexer based on filename, shebang words, or -- first line pattern. local function restore_lexer() buffer:set_lexer_language(buffer._lexer or 'container') end textadept.events.add_handler('file_opened', handle_new) textadept.events.add_handler('file_saved_as', handle_new) textadept.events.add_handler('buffer_after_switch', restore_lexer) textadept.events.add_handler('view_new', restore_lexer)
-- Copyright 2007-2009 Mitchell mitchell<att>caladbolg.net. See LICENSE. local textadept = _G.textadept local locale = _G.locale --- -- Handles file-specific settings. module('textadept.mime_types', package.seeall) -- Markdown: -- ## Overview -- -- Files can be recognized and associated with programming language lexers in -- three ways: -- -- * By file extension. -- * By keywords in the file's shebang (`#!/path/to/exe`) line. -- * By a pattern that matches the file's first line. -- -- If a lexer is not associated with a file you open, first make sure the lexer -- exists in `lexers/`. If it does not, you will need to write one. Consult the -- [lexer][lexer] module for a tutorial. -- -- [lexer]: ../modules/lexer.html -- -- ## Configuration File -- -- `core/ext/mime_types.conf` is the configuration file for mime-type detection. -- -- #### Detection by File Extension -- -- file_ext lexer -- -- Note: `file_ext` should not start with a `.` (period). -- -- #### Detection by Shebang Keywords -- -- #shebang_word lexer -- -- Examples of `shebang_word`'s are `lua`, `ruby`, `python`. -- -- #### Detection by Pattern -- -- /pattern lexer -- -- Only the last space, the one separating the pattern from the lexer, is -- significant. No spaces in the pattern need to be escaped. -- -- ## Extras -- -- This module adds an extra function to `buffer`: -- -- * **buffer:set\_lexer** (language)<br /> -- Replacement for [`buffer:set_lexer_language()`][buffer_set_lexer_language].<br /> -- Sets a buffer._lexer field so it can be restored without querying the -- mime-types tables. Also if the user manually sets the lexer, it should be -- restored.<br /> -- Loads the language-specific module if it exists. -- - lang: The string language to set. -- -- [buffer_set_lexer_language]: buffer.html#buffer:set_lexer_language --- -- File extensions with their associated lexers. -- @class table -- @name extensions extensions = {} --- -- Shebang words and their associated lexers. -- @class table -- @name shebangs shebangs = {} --- -- First-line patterns and their associated lexers. -- @class table -- @name patterns patterns = {} -- Load mime-types from mime_types.conf local f = io.open(_HOME..'/core/ext/mime_types.conf', 'rb') if f then for line in f:lines() do if not line:find('^%s*%%') then if line:find('^%s*[^#/]') then -- extension definition local ext, lexer_name = line:match('^%s*(.+)%s+(%S+)$') if ext and lexer_name then extensions[ext] = lexer_name end else -- shebang or pattern local ch, text, lexer_name = line:match('^%s*([#/])(.+)%s+(%S+)$') if ch and text and lexer_name then (ch == '#' and shebangs or patterns)[text] = lexer_name end end end end f:close() end -- -- Replacement for buffer:set_lexer_language(). -- Sets a buffer._lexer field so it can be restored without querying the -- mime-types tables. Also if the user manually sets the lexer, it should be -- restored. -- Loads the language-specific module if it exists. -- @param buffer The buffer to set the lexer language of. -- @param lang The string language to set. -- @usage buffer:set_lexer('language_name') local function set_lexer(buffer, lang) buffer._lexer = lang buffer:set_lexer_language(lang) local ret, err = pcall(require, lang) if ret then _m[lang].set_buffer_properties() elseif not ret and not err:find("^module '"..lang.."' not found:") then error(err) end end textadept.events.add_handler('buffer_new', function() buffer.set_lexer = set_lexer end) -- Scintilla's first buffer doesn't have this if not RESETTING then buffer.set_lexer = set_lexer end -- Performs actions suitable for a new buffer. -- Sets the buffer's lexer language and loads the language module. local function handle_new() local lexer if buffer.filename then lexer = extensions[buffer.filename:match('[^/\\.]+$')] end if not lexer then local line = buffer:get_line(0) if line:find('^#!') then for word in line:gsub('[/\\]', ' '):gmatch('%S+') do lexer = shebangs[word] if lexer then break end end end if not lexer then for patt, lex in pairs(patterns) do if line:find(patt) then lexer = lex break end end end end buffer:set_lexer(lexer or 'container') end -- Sets the buffer's lexer based on filename, shebang words, or -- first line pattern. local function restore_lexer() buffer:set_lexer_language(buffer._lexer or 'container') end textadept.events.add_handler('file_opened', handle_new) textadept.events.add_handler('file_saved_as', handle_new) textadept.events.add_handler('buffer_after_switch', restore_lexer) textadept.events.add_handler('view_new', restore_lexer)
Fixed bug in core/ext/mime_types.lua caused during textadept.reset().
Fixed bug in core/ext/mime_types.lua caused during textadept.reset().
Lua
mit
rgieseke/textadept,rgieseke/textadept
4fedc05339b7f5cecd75a5e37f2519780452de0e
agents/monitoring/tests/schedule/init.lua
agents/monitoring/tests/schedule/init.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 path = require('path') local async = require('async') local utils = require('utils') local timer = require('timer') local StateScanner = require('monitoring/lib/schedule').StateScanner local Scheduler = require('monitoring/lib/schedule').Scheduler local BaseCheck = require('monitoring/lib/check/base').BaseCheck local tmp = path.join('tests', 'tmp') local exports = {} local checks = { BaseCheck:new({id='ch0001', state='OK', period=30, path=path.join(tmp, '0001.chk')}), BaseCheck:new({id='ch0002', state='OK', period=35, path=path.join(tmp, '0002.chk')}), BaseCheck:new({id='ch0003', state='OK', period=40, path=path.join(tmp, '0003.chk')}), BaseCheck:new({id='ch0004', state='OK', period=45, path=path.join(tmp, '0004.chk')}), } exports['test_scheduler_scan'] = function(test, asserts) local s = StateScanner:new(process.cwd()..'/agents/monitoring/tests/data/sample.state') local count = 0 s:on('check_scheduled', function(details) count = count + 1 if count >= 3 then test.done() end end) s:scanStates() end exports['test_scheduler_initialize'] = function(test, asserts) local testFile = path.join(tmp, 'test_scheduler_initialize.state') async.waterfall({ -- write a scan file. the scheduler does this. function(callback) Scheduler:new(testFile, checks, callback) end, -- load with scanner. function(callback) local count = 0 local s = StateScanner:new(testFile) s:on('check_scheduled', function(details) count = count + 1 if count >= #checks then callback() end end) s:scanStates() end }, function(err) asserts.ok(err == nil) test.done() end) end exports['test_scheduler_scans'] = function(test, asserts) local testFile = path.join(tmp, 'test_scheduler_initialize.state') local scheduler async.waterfall({ function(callback) scheduler = Scheduler:new(testFile, checks, callback) end, function(callback) scheduler:start() local timeout = timer.setTimeout(5000, function() -- they all should have run. asserts.equals(scheduler._runCount, #checks) callback() end) end }, function(err) asserts.ok(err == nil) test.done() end) end exports['test_scheduler_adds'] = function(test, asserts) local testFile = path.join(tmp, 'test_scheduler_adds.state') local scheduler local checks2 = { BaseCheck:new({id='ch0001', state='OK', period=1, path=path.join(tmp, '0001.chk')}), } local checks3 = { BaseCheck:new({id='ch0001', state='OK', period=1, path=path.join(tmp, '0001.chk')}), BaseCheck:new({id='ch0002', state='OK', period=1, path=path.join(tmp, '0002.chk')}), } local checks4 = { BaseCheck:new({id='ch0002', state='OK', period=1, path=path.join(tmp, '0002.chk')}), } async.waterfall({ function(callback) scheduler = Scheduler:new(testFile, checks2, callback) end, function(callback) scheduler:rebuild(checks3, callback); end, function(callback) scheduler:start() local timeout = timer.setTimeout(5000, function() -- they all should have run. asserts.equals(scheduler._runCount, 10) print('rebuild'); scheduler:rebuild(checks4, callback); end) end, function(callback) scheduler:start() local timeout = timer.setTimeout(5000, function() -- they all should have run. asserts.ok(scheduler._runCount > 15) asserts.ok(scheduler._runCount < 18) callback() end) end }, function(err) asserts.ok(err == nil) test.done() end) end return exports
--[[ 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 path = require('path') local async = require('async') local utils = require('utils') local timer = require('timer') local StateScanner = require('monitoring/lib/schedule').StateScanner local Scheduler = require('monitoring/lib/schedule').Scheduler local BaseCheck = require('monitoring/lib/check/base').BaseCheck local tmp = path.join('tests', 'tmp') local exports = {} local checks = { BaseCheck:new({id='ch0001', state='OK', period=30, path=path.join(tmp, '0001.chk')}), BaseCheck:new({id='ch0002', state='OK', period=35, path=path.join(tmp, '0002.chk')}), BaseCheck:new({id='ch0003', state='OK', period=40, path=path.join(tmp, '0003.chk')}), BaseCheck:new({id='ch0004', state='OK', period=45, path=path.join(tmp, '0004.chk')}), } exports['test_scheduler_scan'] = function(test, asserts) local s = StateScanner:new(process.cwd()..'/agents/monitoring/tests/data/sample.state') local count = 0 s:on('check_scheduled', function(details) count = count + 1 if count >= 3 then test.done() end end) s:scanStates() end exports['test_scheduler_initialize'] = function(test, asserts) local testFile = path.join(tmp, 'test_scheduler_initialize.state') async.waterfall({ -- write a scan file. the scheduler does this. function(callback) Scheduler:new(testFile, checks, callback) end, -- load with scanner. function(callback) local count = 0 local s = StateScanner:new(testFile) s:on('check_scheduled', function(details) count = count + 1 if count >= #checks then callback() end end) s:scanStates() end }, function(err) asserts.ok(err == nil) test.done() end) end exports['test_scheduler_scans'] = function(test, asserts) local testFile = path.join(tmp, 'test_scheduler_scans.state') local scheduler async.waterfall({ function(callback) scheduler = Scheduler:new(testFile, checks, callback) end, function(callback) scheduler:start() local timeout = timer.setTimeout(5000, function() -- they all should have run. asserts.equals(scheduler._runCount, #checks) callback() end) end }, function(err) asserts.ok(err == nil) test.done() end) end exports['test_scheduler_adds'] = function(test, asserts) local testFile = path.join(tmp, 'test_scheduler_adds.state') local scheduler local checks2 = { BaseCheck:new({id='ch0001', state='OK', period=1, path=path.join(tmp, '0001.chk')}), } local checks3 = { BaseCheck:new({id='ch0001', state='OK', period=1, path=path.join(tmp, '0001.chk')}), BaseCheck:new({id='ch0002', state='OK', period=1, path=path.join(tmp, '0002.chk')}), } local checks4 = { BaseCheck:new({id='ch0002', state='OK', period=1, path=path.join(tmp, '0002.chk')}), } async.waterfall({ function(callback) scheduler = Scheduler:new(testFile, checks2, callback) end, function(callback) scheduler:rebuild(checks3, callback); end, function(callback) scheduler:start() local timeout = timer.setTimeout(5000, function() -- they all should have run. asserts.equals(scheduler._runCount, 10) print('rebuild'); scheduler:rebuild(checks4, callback); end) end, function(callback) scheduler:start() local timeout = timer.setTimeout(5000, function() -- tests are a bit dicey at this point depending on exactly where in the clock we are.. asserts.ok(scheduler._runCount >= 15) asserts.ok(scheduler._runCount <= 18) callback() end) end }, function(err) asserts.ok(err == nil) test.done() end) end return exports
fix race condition in test, improve general test stability
fix race condition in test, improve general test stability
Lua
apache-2.0
kans/zirgo,kans/zirgo,kans/zirgo
af3181f28049721f7445002b5dc84f6de37a9fc7
tests/wow_api.lua
tests/wow_api.lua
local _G = getfenv(0) local donothing = function() end local frames = {} -- Stores globally created frames, and their internal properties. local FrameClass = {} -- A class for creating frames. FrameClass.methods = { "SetScript", "RegisterEvent", "UnregisterEvent", "UnregisterAllEvents", "Show", "Hide", "IsShown" } function FrameClass:New() local frame = {} for i,method in ipairs(self.methods) do frame[method] = self[method] end local frameProps = { events = {}, scripts = {}, timer = GetTime(), isShow = true } return frame, frameProps end function FrameClass:SetScript(script,handler) frames[self].scripts[script] = handler end function FrameClass:RegisterEvent(event) frames[self].events[event] = true end function FrameClass:UnregisterEvent(event) frames[self].events[event] = nil end function FrameClass:UnregisterAllEvents(frame) for event in pairs(frames[self].events) do frames[self].events[event] = nil end end function FrameClass:Show() frames[self].isShow = true end function FrameClass:Hide() frames[self].isShow = false end function FrameClass:IsShown() return frames[self].isShow end function CreateFrame(kind, name, parent) local frame,internal = FrameClass:New() frames[frame] = internal if name then _G[name] = frame end return frame end function UnitName(unit) return unit end function GetRealmName() return "Realm Name" end function UnitClass(unit) return "Warrior", "WARRIOR" end function UnitHealthMax() return 100 end function UnitHealth() return 50 end function GetNumRaidMembers() return 1 end function GetNumPartyMembers() return 1 end FACTION_HORDE = "Horde" FACTION_ALLIANCE = "Alliance" function UnitFactionGroup(unit) return "Horde", "Horde" end function UnitRace(unit) return "Undead", "Scourge" end _time = 0 function GetTime() return _time end function IsAddOnLoaded() return nil end SlashCmdList = {} function __WOW_Input(text) local a,b = string.find(text, "^/%w+") local arg, text = string.sub(text, a,b), string.sub(text, b + 2) for k,handler in pairs(SlashCmdList) do local i = 0 while true do i = i + 1 if not _G["SLASH_" .. k .. i] then break elseif _G["SLASH_" .. k .. i] == arg then handler(text) return end end end; print("No command found:", text) end local ChatFrameTemplate = { AddMessage = function(self, text) print((string.gsub(text, "|c%x%x%x%x%x%x%x%x(.-)|r", "%1"))) end } for i=1,7 do local f = {} for k,v in pairs(ChatFrameTemplate) do f[k] = v end _G["ChatFrame"..i] = f end DEFAULT_CHAT_FRAME = ChatFrame1 debugstack = debug.traceback date = os.date function GetLocale() return "enUS" end function GetAddOnInfo() return end function GetNumAddOns() return 0 end function getglobal(k) return _G[k] end function setglobal(k, v) _G[k] = v end local function _errorhandler(msg) print("--------- geterrorhandler error -------\n"..msg.."\n-----end error-----\n") end function geterrorhandler() return _errorhandler end function InCombatLockdown() return false end function IsLoggedIn() return false end time = os.clock strmatch = string.match function SendAddonMessage(prefix, message, distribution, target) assert(#prefix + #message < 255, string.format("SendAddonMessage: message too long (%d bytes)", #prefix + #message)) -- CHAT_MSG_ADDON(prefix, message, distribution, sender) WoWAPI_FireEvent("CHAT_MSG_ADDON", prefix, message, distribution, "Sender") end function hooksecurefunc(func_name, post_hook_func) local orig_func = _G[func_name] _G[func_name] = function (...) orig_func(...) return post_hook_func(...) end end RED_FONT_COLOR_CODE = "" GREEN_FONT_COLOR_CODE = "" StaticPopupDialogs = {} function WoWAPI_FireEvent(event,...) for frame, props in pairs(frames) do if props.events[event] then if props.scripts["OnEvent"] then props.scripts["OnEvent"](frame,event,...) end end end end function WoWAPI_FireUpdate(forceNow) if forceNow then _time = forceNow end local now = GetTime() for frame,props in pairs(frames) do if props.isShow and props.scripts.OnUpdate then props.scripts.OnUpdate(frame,now-props.timer) props.timer = now end end end -- utility function for "dumping" a number of arguments (return a string representation of them) function dump(...) local t = {} for i=1,select("#", ...) do local v = select(i, ...) if type(v)=="string" then tinsert(t, string.format("%q", v)) else tinsert(t, tostring(v)) end end return "<"..table.concat(t, "> <")..">" end
local _G = getfenv(0) local donothing = function() end local frames = {} -- Stores globally created frames, and their internal properties. local FrameClass = {} -- A class for creating frames. FrameClass.methods = { "SetScript", "RegisterEvent", "UnregisterEvent", "UnregisterAllEvents", "Show", "Hide", "IsShown" } function FrameClass:New() local frame = {} for i,method in ipairs(self.methods) do frame[method] = self[method] end local frameProps = { events = {}, scripts = {}, timer = GetTime(), isShow = true } return frame, frameProps end function FrameClass:SetScript(script,handler) frames[self].scripts[script] = handler end function FrameClass:RegisterEvent(event) frames[self].events[event] = true end function FrameClass:UnregisterEvent(event) frames[self].events[event] = nil end function FrameClass:UnregisterAllEvents(frame) for event in pairs(frames[self].events) do frames[self].events[event] = nil end end function FrameClass:Show() frames[self].isShow = true end function FrameClass:Hide() frames[self].isShow = false end function FrameClass:IsShown() return frames[self].isShow end function CreateFrame(kind, name, parent) local frame,internal = FrameClass:New() frames[frame] = internal if name then _G[name] = frame end return frame end function UnitName(unit) return unit end function GetRealmName() return "Realm Name" end function UnitClass(unit) return "Warrior", "WARRIOR" end function UnitHealthMax() return 100 end function UnitHealth() return 50 end function GetNumRaidMembers() return 1 end function GetNumPartyMembers() return 1 end FACTION_HORDE = "Horde" FACTION_ALLIANCE = "Alliance" function UnitFactionGroup(unit) return "Horde", "Horde" end function UnitRace(unit) return "Undead", "Scourge" end _time = 0 function GetTime() return _time end function IsAddOnLoaded() return nil end SlashCmdList = {} function __WOW_Input(text) local a,b = string.find(text, "^/%w+") local arg, text = string.sub(text, a,b), string.sub(text, b + 2) for k,handler in pairs(SlashCmdList) do local i = 0 while true do i = i + 1 if not _G["SLASH_" .. k .. i] then break elseif _G["SLASH_" .. k .. i] == arg then handler(text) return end end end; print("No command found:", text) end local ChatFrameTemplate = { AddMessage = function(self, text) print((string.gsub(text, "|c%x%x%x%x%x%x%x%x(.-)|r", "%1"))) end } for i=1,7 do local f = {} for k,v in pairs(ChatFrameTemplate) do f[k] = v end _G["ChatFrame"..i] = f end DEFAULT_CHAT_FRAME = ChatFrame1 debugstack = debug.traceback date = os.date function GetLocale() return "enUS" end function GetAddOnInfo() return end function GetNumAddOns() return 0 end function getglobal(k) return _G[k] end function setglobal(k, v) _G[k] = v end local function _errorhandler(msg) print("--------- geterrorhandler error -------\n"..msg.."\n-----end error-----\n") end function geterrorhandler() return _errorhandler end function InCombatLockdown() return false end function IsLoggedIn() return false end function GetFramerate() return 60 end time = os.clock strmatch = string.match function SendAddonMessage(prefix, message, distribution, target) assert(#prefix + #message < 255, string.format("SendAddonMessage: message too long (%d bytes)", #prefix + #message)) -- CHAT_MSG_ADDON(prefix, message, distribution, sender) WoWAPI_FireEvent("CHAT_MSG_ADDON", prefix, message, distribution, "Sender") end function hooksecurefunc(func_name, post_hook_func) local orig_func = _G[func_name] _G[func_name] = function (...) local ret = { orig_func(...) } -- yeahyeah wasteful, see if i care, it's a test framework post_hook_func(...) return unpack(ret) end end RED_FONT_COLOR_CODE = "" GREEN_FONT_COLOR_CODE = "" StaticPopupDialogs = {} function WoWAPI_FireEvent(event,...) for frame, props in pairs(frames) do if props.events[event] then if props.scripts["OnEvent"] then for i=1,select('#',...) do _G["arg"..i] = select(i,...) end _G.event=event props.scripts["OnEvent"](frame,event,...) end end end end function WoWAPI_FireUpdate(forceNow) if forceNow then _time = forceNow end local now = GetTime() for frame,props in pairs(frames) do if props.isShow and props.scripts.OnUpdate then _G.arg1=now-props.timer props.scripts.OnUpdate(frame,now-props.timer) props.timer = now end end end -- utility function for "dumping" a number of arguments (return a string representation of them) function dump(...) local t = {} for i=1,select("#", ...) do local v = select(i, ...) if type(v)=="string" then tinsert(t, string.format("%q", v)) else tinsert(t, tostring(v)) end end return "<"..table.concat(t, "> <")..">" end
Ace3 - tests: wow_api.lua bench fixes/additions: - Add GetFrameRate() - always returns 60 - Make hooksecurefunc() actually return the ORIGINAL return values, not those of the hook - Also set _G.arg1..argn in events - Also set _G.arg1 in OnUpdates
Ace3 - tests: wow_api.lua bench fixes/additions: - Add GetFrameRate() - always returns 60 - Make hooksecurefunc() actually return the ORIGINAL return values, not those of the hook - Also set _G.arg1..argn in events - Also set _G.arg1 in OnUpdates git-svn-id: d324031ee001e5fbb202928c503a4bc65708d41c@320 5debad98-a965-4143-8383-f471b3509dcf
Lua
bsd-3-clause
sarahgerweck/Ace3
3e4abe2e41d8f77fa0c06f7df03291143fd1ade7
SafeLuaAPI/generator.lua
SafeLuaAPI/generator.lua
--- -- ## SafeLuaAPI compiler, generate the C code needed for the library -- -- @author Demi Marie Obenour -- @copyright 2016 -- @license MIT/X11 -- @module generator local generator = {} local require = require local concat = table.concat local assert = assert local sub, find, match = string.sub, string.find, string.match local format = string.format local stdout, stderr = io.stdout, io.stderr local pairs, ipairs, next = pairs, ipairs, next local tostring = tostring local io = io local type, tonumber, tostring = type, tonumber, tostring local string = string local os = os local pcall, xpcall = pcall, xpcall local print, error = print, error local getmetatable, setmetatable = getmetatable, setmetatable if module then module 'generator' end local _ENV = nil local strict, err = pcall(require, 'pl/strict') local err, pretty = pcall(require, 'pl/pretty') pretty = err and pretty local finally = require 'SafeLuaAPI/finally' local parse_prototype = require 'SafeLuaAPI/parse_prototype' local parse_prototypes = parse_prototype.extract_args if pretty then pretty.dump { parse_prototypes('int main(int argc, char **argv)') } end local metatable = { __index = generator, __metatable = nil } local function check_metatable(table_) return getmetatable(table_) == metatable or error('Incorrect type passed to binder API', 2) end function generator:emit_struct(name, arguments) check_metatable(self) local handle = self.handle if #arguments == 1 then return end local x = {} handle:write 'STRUCT_STATIC struct Struct_' handle:write(name) handle:write ' {\n' for i = 2, #arguments do handle:write ' ' handle:write(arguments[i]) handle:write ';\n' end handle:write '};\n' end local function emit_arglist(arguments) local len = #arguments if len == 0 then return '', '', 'L' end local x, y, z = {}, {}, {'L'} for i, j in ipairs(arguments) do if i ~= 1 then -- print('[ARGUMENT] '..j) local argname = match(j, '[_%w]+%s*$') -- print('[ARGNAME] '..argname) y[i-1] = argname z[i] = 'args->'..argname end x[i] = j end return concat(x, ', '), concat(y, ', '), concat(z, ', ') end function generator.check_ident(ident) return find(ident, '^[_%a][_%w]*$') or error(('String %q is not an identifier'):format(ident)) end function generator.check_type(ty) if not (find(ty, '^[%s_%w%b()%*]*$') and find(ty, '^[%s_%w%(%)%*]*$')) then error(('String %q is not a valid C type'):format(ty)) end end local check_ident, check_type = generator.check_ident, generator.check_type function generator:emit_function_prototype(name, prototype) check_metatable(self) local c_source_text = '#ifndef '..name..'\n'..prototype..'\n#endif\n' self.handle:write(c_source_text) end --- Generates a wrapper for API function `name`. -- @tparam string name The function name. -- @tparam string popped The number of arguments popped from the Lua stack. -- @tparam string pushed The number of arguments pushed onto the Lua stack. -- @tparam {string,...} stack_in A list of arguments that name stack slots -- used by the function. -- @tparam string return_type The return type of the function. -- @tparam {string,...} arguments The argument names and types for the function. -- @treturn string The wrapper C code for the function function generator:emit_wrapper(name, popped, pushed, stack_in, return_type, arguments) check_metatable(self) assert(#arguments > 0, 'No Lua API function takes no arguments') -- Consistency checks on the arguments check_type(return_type) check_ident(name) tonumber(popped) tonumber(pushed) self:emit_function_prototype(name, return_type, arguments) -- Get the various lists local prototype_args, initializers, call_string = emit_arglist(arguments) -- C needs different handling of `void` than of other types. Boo. local trampoline_type, retcast_type = 'TRAMPOLINE(', ', RETCAST_VALUE, ' if return_type == 'void' then trampoline_type, retcast_type = 'VOID_TRAMPOLINE(', ', RETCAST_VOID, ' end -- C does not allow empty structs or initializers. Boo. local local_struct = ', DUMMY_LOCAL_STRUCT' if #arguments ~= 1 then -- Actually emit the struct self:emit_struct(name, arguments) -- Use a different macro for the local struct (one that actually -- assigns to thread-local storage) local_struct = ', LOCAL_STRUCT' end -- local args = concat({name, argcount}, ', ') self.handle:write(concat { trampoline_type, return_type, ', ', name, ', ', pushed, ', ', call_string,')\ #define ARGLIST ', prototype_args, '\ EMIT_WRAPPER(', return_type, ', ', name, ', ', popped, local_struct, retcast_type, initializers, ')\n#undef ARGLIST\n\n' }) end function generator:generate(table_) --pretty.dump(table_) check_metatable(self) for i, j in pairs(table_) do assert(type(i) == 'string') self:emit_wrapper(i, j.popped, j.pushed, j.stack_in, j.retval, j.args) end end function generator.new(handle) return setmetatable({ handle = handle }, metatable) end local generate = generator.generate --- Generate C code to a given filename -- @tparam string filename The name of the file to write the C code to. -- @tparam {} table_ The table containing function descriptions function generator.generate_to_file(filename, table_) return finally.with_file(filename, 'w', generate) end return generator
--- -- ## SafeLuaAPI compiler, generate the C code needed for the library -- -- @author Demi Marie Obenour -- @copyright 2016 -- @license MIT/X11 -- @module generator local generator = {} local require = require local concat = table.concat local assert = assert local sub, find, match = string.sub, string.find, string.match local format = string.format local stdout, stderr = io.stdout, io.stderr local pairs, ipairs, next = pairs, ipairs, next local tostring = tostring local io = io local type, tonumber, tostring = type, tonumber, tostring local string = string local os = os local pcall, xpcall = pcall, xpcall local print, error = print, error local getmetatable, setmetatable = getmetatable, setmetatable if module then module 'generator' end local _ENV = nil local strict, err = pcall(require, 'pl/strict') local err, pretty = pcall(require, 'pl/pretty') pretty = err and pretty local finally = require 'SafeLuaAPI/finally' local parse_prototype = require 'SafeLuaAPI/parse_prototype' local parse_prototypes = parse_prototype.extract_args if pretty then pretty.dump { parse_prototypes('int main(int argc, char **argv)') } end local metatable = { __index = generator, __metatable = nil } local function check_metatable(table_) return getmetatable(table_) == metatable or error('Incorrect type passed to binder API', 2) end function generator:emit_struct(name, arguments) check_metatable(self) local handle = self.handle if #arguments == 1 then return end local x = {} handle:write 'STRUCT_STATIC struct Struct_' handle:write(name) handle:write ' {\n' for i = 2, #arguments do handle:write ' ' handle:write(arguments[i]) handle:write ';\n' end handle:write '};\n' end local function emit_arglist(arguments) local len = #arguments if len == 0 then return '', '', 'L' end local x, y, z = {}, {}, {'L'} for i, j in ipairs(arguments) do if i ~= 1 then -- print('[ARGUMENT] '..j) local argname = match(j, '[_%w]+%s*$') -- print('[ARGNAME] '..argname) y[i-1] = argname z[i] = 'args->'..argname end x[i] = j end return concat(x, ', '), concat(y, ', '), concat(z, ', ') end function generator.check_ident(ident) return find(ident, '^[_%a][_%w]*$') or error(('String %q is not an identifier'):format(ident)) end function generator.check_type(ty) if not (find(ty, '^[%s_%w%b()%*]*$') and find(ty, '^[%s_%w%(%)%*]*$')) then error(('String %q is not a valid C type'):format(ty)) end end local check_ident, check_type = generator.check_ident, generator.check_type function generator:emit_function_prototype(name, return_type, argument_list) check_metatable(self) local c_source_text = '#ifndef '..name..'\n'.. return_type..' '..name..'('..concat(argument_list, ', ')..');\n#endif\n' self.handle:write(c_source_text) end --- Generates a wrapper for API function `name`. -- @tparam string name The function name. -- @tparam string popped The number of arguments popped from the Lua stack. -- @tparam string pushed The number of arguments pushed onto the Lua stack. -- @tparam {string,...} stack_in A list of arguments that name stack slots -- used by the function. -- @tparam string return_type The return type of the function. -- @tparam {string,...} arguments The argument names and types for the function. -- @treturn string The wrapper C code for the function function generator:emit_wrapper(name, popped, pushed, stack_in, return_type, arguments) check_metatable(self) assert(#arguments > 0, 'No Lua API function takes no arguments') -- Consistency checks on the arguments check_type(return_type) check_ident(name) tonumber(popped) tonumber(pushed) self:emit_function_prototype(name, return_type, arguments) -- Get the various lists local prototype_args, initializers, call_string = emit_arglist(arguments) -- C needs different handling of `void` than of other types. Boo. local trampoline_type, retcast_type = 'TRAMPOLINE(', ', RETCAST_VALUE, ' if return_type == 'void' then trampoline_type, retcast_type = 'VOID_TRAMPOLINE(', ', RETCAST_VOID, ' end -- C does not allow empty structs or initializers. Boo. local local_struct = ', DUMMY_LOCAL_STRUCT' if #arguments ~= 1 then -- Actually emit the struct self:emit_struct(name, arguments) -- Use a different macro for the local struct (one that actually -- assigns to thread-local storage) local_struct = ', LOCAL_STRUCT' end -- local args = concat({name, argcount}, ', ') self.handle:write(concat { trampoline_type, return_type, ', ', name, ', ', pushed, ', ', call_string,')\ #define ARGLIST ', prototype_args, '\ EMIT_WRAPPER(', return_type, ', ', name, ', ', popped, local_struct, retcast_type, initializers, ')\n#undef ARGLIST\n\n' }) end function generator:generate(table_) --pretty.dump(table_) check_metatable(self) for i, j in pairs(table_) do assert(type(i) == 'string') self:emit_wrapper(i, j.popped, j.pushed, j.stack_in, j.retval, j.args) end end function generator.new(handle) return setmetatable({ handle = handle }, metatable) end local generate = generator.generate --- Generate C code to a given filename -- @tparam string filename The name of the file to write the C code to. -- @tparam {} table_ The table containing function descriptions function generator.generate_to_file(filename, table_) return finally.with_file(filename, 'w', generate) end return generator
Fix C prototype emitter
Fix C prototype emitter Fix the C prototype emitter so that it did not try to read an argument that did not exist.
Lua
apache-2.0
drbo/safer-lua-api,drbo/safer-lua-api
46b0f0d9919ca086bc0b27694af87f569a6a9458
src_trunk/resources/global/chat_globals.lua
src_trunk/resources/global/chat_globals.lua
oocState = 1 function getOOCState() return oocState end function setOOCState(state) oocState = state end function sendMessageToAdmins(message) local players = exports.pool:getPoolElementsByType("player") for k, thePlayer in ipairs(players) do if (exports.global:isPlayerAdmin(thePlayer)) then outputChatBox(tostring(message), thePlayer, 255, 0, 0) end end end function findPlayerByPartialNick(partialNick) local matchNick = nil local matchNickAccuracy=0 local partialNick = string.lower(partialNick) local players = exports.pool:getPoolElementsByType("player") local count = 0 -- IDS if ((tostring(type(tonumber(partialNick)))) == "number") then for key, value in ipairs(players) do local id = getElementData(value, "playerid") if (id) then if (id==tonumber(partialNick)) then matchNick = getPlayerName(value) break end end end elseif not ((tostring(type(tonumber(partialNick)))) == "number") or not (matchNick) then -- Look for player nicks for playerKey, arrayPlayer in ipairs(players) do local playerName = string.lower(getPlayerName(arrayPlayer)) if(string.find(playerName, tostring(partialNick))) then local posStart, posEnd = string.find(playerName, tostring(partialNick)) if posEnd - posStart > matchNickAccuracy then -- better match matchNickAccuracy = posEnd-posStart matchNick = playerName elseif posEnd - posStart == matchNickAccuracy then -- found someone who matches up the same way, so pretend we didnt find any matchNick = nil end end end end if matchNick == nil then return false else local matchPlayer = getPlayerFromName(matchNick) local dbid = getElementData(matchPlayer, "dbid") return matchPlayer, dbid end end function sendLocalMeAction(thePlayer, message) local x, y, z = getElementPosition(thePlayer) local chatSphere = createColSphere(x, y, z, 20) exports.pool:allocateElement(chatSphere) local nearbyPlayers = getElementsWithinColShape(chatSphere, "player") local playerName = string.gsub(getPlayerName(thePlayer), "_", " ") destroyElement(chatSphere) for index, nearbyPlayer in ipairs(nearbyPlayers) do local logged = getElementData(nearbyPlayer, "loggedin") if not isPedDead(nearbyPlayer) and logged==1 and getElementDimension(thePlayer) == getElementDimension(nearbyPlayer) then outputChatBox(" *" .. playerName .. " " .. message, nearbyPlayer, 255, 51, 102) end end end addEvent("sendLocalMeAction", true) addEventHandler("sendLocalMeAction", getRootElement(), sendLocalMeAction) function sendLocalDoAction(thePlayer, message) local x, y, z = getElementPosition(thePlayer) local chatSphere = createColSphere(x, y, z, 20) exports.pool:allocateElement(chatSphere) local nearbyPlayers = getElementsWithinColShape(chatSphere, "player") local playerName = string.gsub(getPlayerName(thePlayer), "_", " ") destroyElement(chatSphere) for index, nearbyPlayer in ipairs(nearbyPlayers) do local logged = getElementData(nearbyPlayer, "loggedin") if not isPedDead(nearbyPlayer) and logged==1 and getElementDimension(thePlayer) == getElementDimension(nearbyPlayer) then outputChatBox(" * " .. message .. " * ((" .. playerName .. "))", nearbyPlayer, 255, 51, 102) end end end
oocState = 1 function getOOCState() return oocState end function setOOCState(state) oocState = state end function sendMessageToAdmins(message) local players = exports.pool:getPoolElementsByType("player") for k, thePlayer in ipairs(players) do if (exports.global:isPlayerAdmin(thePlayer)) then outputChatBox(tostring(message), thePlayer, 255, 0, 0) end end end function findPlayerByPartialNick(partialNick) local matchNick = nil local matchNickAccuracy=0 local partialNick = string.lower(partialNick) local players = exports.pool:getPoolElementsByType("player") local count = 0 -- IDS if tonumber(partialNick) then for key, value in ipairs(players) do if isElement(value) then local id = getElementData(value, "playerid") if id and id == tonumber(partialNick) then matchNick = getPlayerName(value) break end end end else -- Look for player nicks for playerKey, arrayPlayer in ipairs(players) do if isElement(arrayPlayer) then local playerName = string.lower(getPlayerName(arrayPlayer)) if(string.find(playerName, tostring(partialNick))) then local posStart, posEnd = string.find(playerName, tostring(partialNick)) if posEnd - posStart > matchNickAccuracy then -- better match matchNickAccuracy = posEnd-posStart matchNick = playerName elseif posEnd - posStart == matchNickAccuracy then -- found someone who matches up the same way, so pretend we didnt find any matchNick = nil end end end end end if matchNick == nil then return false else local matchPlayer = getPlayerFromName(matchNick) local dbid = getElementData(matchPlayer, "dbid") return matchPlayer, dbid end end function sendLocalMeAction(thePlayer, message) local x, y, z = getElementPosition(thePlayer) local chatSphere = createColSphere(x, y, z, 20) exports.pool:allocateElement(chatSphere) local nearbyPlayers = getElementsWithinColShape(chatSphere, "player") local playerName = string.gsub(getPlayerName(thePlayer), "_", " ") destroyElement(chatSphere) for index, nearbyPlayer in ipairs(nearbyPlayers) do local logged = getElementData(nearbyPlayer, "loggedin") if not isPedDead(nearbyPlayer) and logged==1 and getElementDimension(thePlayer) == getElementDimension(nearbyPlayer) then outputChatBox(" *" .. playerName .. " " .. message, nearbyPlayer, 255, 51, 102) end end end addEvent("sendLocalMeAction", true) addEventHandler("sendLocalMeAction", getRootElement(), sendLocalMeAction) function sendLocalDoAction(thePlayer, message) local x, y, z = getElementPosition(thePlayer) local chatSphere = createColSphere(x, y, z, 20) exports.pool:allocateElement(chatSphere) local nearbyPlayers = getElementsWithinColShape(chatSphere, "player") local playerName = string.gsub(getPlayerName(thePlayer), "_", " ") destroyElement(chatSphere) for index, nearbyPlayer in ipairs(nearbyPlayers) do local logged = getElementData(nearbyPlayer, "loggedin") if not isPedDead(nearbyPlayer) and logged==1 and getElementDimension(thePlayer) == getElementDimension(nearbyPlayer) then outputChatBox(" * " .. message .. " * ((" .. playerName .. "))", nearbyPlayer, 255, 51, 102) end end end
chat fix
chat fix git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1704 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
0511421f2df3d2a015986de292b4e39af65ea298
Module.lua
Module.lua
local Module = torch.class('nn.Module') function Module:__init() self.gradInput = torch.Tensor() self.output = torch.Tensor() end function Module:parameters() if self.weight and self.bias then return {self.weight, self.bias}, {self.gradWeight, self.gradBias} elseif self.weight then return {self.weight}, {self.gradWeight} elseif self.bias then return {self.bias}, {self.gradBias} else return end end function Module:updateOutput(input) return self.output end function Module:forward(input) return self:updateOutput(input) end function Module:backward(input, gradOutput) self:updateGradInput(input, gradOutput) self:accGradParameters(input, gradOutput) return self.gradInput end function Module:backwardUpdate(input, gradOutput, lr) self:updateGradInput(input, gradOutput) self:accUpdateGradParameters(input, gradOutput, lr) return self.gradInput end function Module:updateGradInput(input, gradOutput) return self.gradInput end function Module:accGradParameters(input, gradOutput, scale) end function Module:accUpdateGradParameters(input, gradOutput, lr) local gradWeight = self.gradWeight local gradBias = self.gradBias self.gradWeight = self.weight self.gradBias = self.bias self:accGradParameters(input, gradOutput, -lr) self.gradWeight = gradWeight self.gradBias = gradBias end function Module:sharedAccUpdateGradParameters(input, gradOutput, lr) if self:parameters() then self:zeroGradParameters() self:accGradParameters(input, gradOutput, 1) self:updateParameters(lr) end end function Module:zeroGradParameters() local _,gradParams = self:parameters() if gradParams then for i=1,#gradParams do gradParams[i]:zero() end end end function Module:updateParameters(learningRate) local params, gradParams = self:parameters() if params then for i=1,#params do params[i]:add(-learningRate, gradParams[i]) end end end function Module:share(mlp, ...) local arg = {...} for i,v in ipairs(arg) do if self[v] ~= nil then self[v]:set(mlp[v]) self.accUpdateGradParameters = self.sharedAccUpdateGradParameters mlp.accUpdateGradParameters = mlp.sharedAccUpdateGradParameters end end return self end function Module:clone(...) local f = torch.MemoryFile("rw"):binary() f:writeObject(self) f:seek(1) local clone = f:readObject() f:close() if select('#',...) > 0 then clone:share(self,...) end return clone end function Module:type(type) -- find all tensors and convert them for key,param in pairs(self) do if torch.typename(param) and torch.typename(param):find('torch%..+Tensor') then self[key] = param:type(type) end end -- find submodules in classic containers 'modules' if self.modules then for _,module in ipairs(self.modules) do module:type(type) end end return self end function Module:float() return self:type('torch.FloatTensor') end function Module:double() return self:type('torch.DoubleTensor') end function Module:cuda() return self:type('torch.CudaTensor') end function Module:reset() end function Module:getParameters() -- get parameters local parameters,gradParameters = self:parameters() -- this function flattens arbitrary lists of parameters, -- even complex shared ones local function flatten(parameters) -- already flat ? local flat = true for k = 2,#parameters do if parameters[k]:storage() ~= parameters[k-1]:storage() then flat = false break end end if flat then local nParameters = 0 for k,param in ipairs(parameters) do nParameters = nParameters + param:nElement() end local flatParameters = parameters[1].new(parameters[1]:storage()) if nParameters ~= flatParameters:nElement() then error('flattenParameters(): weird parameters') end return flatParameters end -- compute offsets of each parameter local offsets = {} local sizes = {} local strides = {} local elements = {} local storageOffsets = {} local params = {} local nParameters = 0 for k,param in ipairs(parameters) do table.insert(offsets, nParameters+1) table.insert(sizes, param:size()) table.insert(strides, param:stride()) table.insert(elements, param:nElement()) table.insert(storageOffsets, param:storageOffset()) local isView = false for i = 1,k-1 do if param:storage() == parameters[i]:storage() then offsets[k] = offsets[i] if storageOffsets[k] ~= storageOffsets[i] or elements[k] ~= elements[i] then error('flattenParameters(): cannot flatten shared weights with different structures') end isView = true break end end if not isView then nParameters = nParameters + param:nElement() end end -- create flat vector local flatParameters = parameters[1].new(nParameters) local storage = flatParameters:storage() -- reallocate all parameters in flat vector for i = 1,#parameters do local data = parameters[i]:clone() parameters[i]:set(storage, offsets[i], elements[i]):resize(sizes[i],strides[i]):copy(data) data = nil collectgarbage() end -- cleanup collectgarbage() -- return flat param return flatParameters end -- flatten parameters and gradients local flatParameters = flatten(parameters) local flatGradParameters = flatten(gradParameters) -- return new flat vector that contains all discrete parameters return flatParameters, flatGradParameters end function Module:__call__(input, gradOutput) self:forward(input) if gradOutput then self:backward(input, gradOutput) return self.output, self.gradInput else return self.output end end
local Module = torch.class('nn.Module') function Module:__init() self.gradInput = torch.Tensor() self.output = torch.Tensor() end function Module:parameters() if self.weight and self.bias then return {self.weight, self.bias}, {self.gradWeight, self.gradBias} elseif self.weight then return {self.weight}, {self.gradWeight} elseif self.bias then return {self.bias}, {self.gradBias} else return end end function Module:updateOutput(input) return self.output end function Module:forward(input) return self:updateOutput(input) end function Module:backward(input, gradOutput) self:updateGradInput(input, gradOutput) self:accGradParameters(input, gradOutput) return self.gradInput end function Module:backwardUpdate(input, gradOutput, lr) self:updateGradInput(input, gradOutput) self:accUpdateGradParameters(input, gradOutput, lr) return self.gradInput end function Module:updateGradInput(input, gradOutput) return self.gradInput end function Module:accGradParameters(input, gradOutput, scale) end function Module:accUpdateGradParameters(input, gradOutput, lr) local gradWeight = self.gradWeight local gradBias = self.gradBias self.gradWeight = self.weight self.gradBias = self.bias self:accGradParameters(input, gradOutput, -lr) self.gradWeight = gradWeight self.gradBias = gradBias end function Module:sharedAccUpdateGradParameters(input, gradOutput, lr) if self:parameters() then self:zeroGradParameters() self:accGradParameters(input, gradOutput, 1) self:updateParameters(lr) end end function Module:zeroGradParameters() local _,gradParams = self:parameters() if gradParams then for i=1,#gradParams do gradParams[i]:zero() end end end function Module:updateParameters(learningRate) local params, gradParams = self:parameters() if params then for i=1,#params do params[i]:add(-learningRate, gradParams[i]) end end end function Module:share(mlp, ...) local arg = {...} for i,v in ipairs(arg) do if self[v] ~= nil then self[v]:set(mlp[v]) self.accUpdateGradParameters = self.sharedAccUpdateGradParameters mlp.accUpdateGradParameters = mlp.sharedAccUpdateGradParameters end end return self end function Module:clone(...) local f = torch.MemoryFile("rw"):binary() f:writeObject(self) f:seek(1) local clone = f:readObject() f:close() if select('#',...) > 0 then clone:share(self,...) end return clone end function Module:type(type) -- find all tensors and convert them for key,param in pairs(self) do if torch.typename(param) and torch.typename(param):find('torch%..+Tensor') then self[key] = param:type(type) end end -- find submodules in classic containers 'modules' if self.modules then for _,module in ipairs(self.modules) do module:type(type) end end return self end function Module:float() return self:type('torch.FloatTensor') end function Module:double() return self:type('torch.DoubleTensor') end function Module:cuda() return self:type('torch.CudaTensor') end function Module:reset() end function Module:getParameters() -- get parameters local parameters,gradParameters = self:parameters() local function storageInSet(set, storage) --this is waste of time (need correct hash) for key, val in pairs(set) do if key == storage then return val end end end -- this function flattens arbitrary lists of parameters, -- even complex shared ones local function flatten(parameters) local storages = {} local nParameters = 0 for k = 1,#parameters do if not storageInSet(storages, parameters[k]:storage()) then storages[parameters[k]:storage()] = nParameters nParameters = nParameters + parameters[k]:storage():size() end end local flatParameters = torch.Tensor(nParameters):fill(1) local flatStorage = flatParameters:storage() for k = 1,#parameters do local storageOffset = storageInSet(storages, parameters[k]:storage()) parameters[k]:set(flatStorage, storageOffset + parameters[k]:storageOffset(), parameters[k]:size(), parameters[k]:stride()) parameters[k]:zero() end if (flatParameters:sum() ~= 0) then print("<getParameters()> WARNING: found " .. flatParameters:sum() .. " holes in the parameters vector (i.e. " .. flatParameters:sum() .. " storage elements that are unused, this " .. "might be an issue for your optimization procedure)") end for k, v in pairs(storages) do flatParameters[{{v+1,v+k:size()}}]:copy(torch.Tensor():set(k)) end return flatParameters end -- flatten parameters and gradients local flatParameters = flatten(parameters) local flatGradParameters = flatten(gradParameters) -- return new flat vector that contains all discrete parameters return flatParameters, flatGradParameters end function Module:__call__(input, gradOutput) self:forward(input) if gradOutput then self:backward(input, gradOutput) return self.output, self.gradInput else return self.output end end
Attempt to fix getParameters.
Attempt to fix getParameters.
Lua
bsd-3-clause
EnjoyHacking/nn,sagarwaghmare69/nn,GregSatre/nn,andreaskoepf/nn,diz-vara/nn,elbamos/nn,Djabbz/nn,davidBelanger/nn,kmul00/nn,hughperkins/nn,caldweln/nn,rickyHong/nn_lib_torch,mys007/nn,sbodenstein/nn,ominux/nn,soumith/nn,joeyhng/nn,apaszke/nn,jzbontar/nn,lvdmaaten/nn,adamlerer/nn,nicholas-leonard/nn,hery/nn,bartvm/nn,Aysegul/nn,Jeffyrao/nn,clementfarabet/nn,ivendrov/nn,rotmanmi/nn,aaiijmrtt/nn,jonathantompson/nn,lukasc-ch/nn,zhangxiangxiao/nn,eriche2016/nn,jhjin/nn,PierrotLC/nn,vgire/nn,karpathy/nn,eulerreich/nn,abeschneider/nn,xianjiec/nn,zchengquan/nn,szagoruyko/nn,Moodstocks/nn,forty-2/nn,douwekiela/nn,fmassa/nn,colesbury/nn,PraveerSINGH/nn,boknilev/nn,noa/nn,mlosch/nn,witgo/nn,LinusU/nn
ac4ae88a32ef5028de804dee17de893963e240b6
crop.lua
crop.lua
SILE.require("packages/cropmarks"); if not sheetsize then local papersize = SILE.documentState.paperSize local w = papersize[1] + 57 local h = papersize[2] + 57 sheetsize = w .. "pt x " .. h .. "pt" end local outcounter = 1 SILE.registerCommand("crop:header", function (options, content) SILE.call("meta:surum") SILE.typesetter:typeset(" (" .. outcounter .. ") " .. os.getenv("HOSTNAME") .. " / " .. os.date("%Y-%m-%d, %X")) outcounter = outcounter + 1 end) SILE.call("crop:setup", { papersize = sheetsize })
local bleed = 3 * 2.83465 local trim = 10 * 2.83465 local len = trim - bleed * 2 SILE.require("packages/cropmarks") -- Use our own version of SILE packgage local outcounter = 1 local date = SILE.require("packages.date").exports local outputMarks = function() local page = SILE.getFrame("page") SILE.outputter.rule(page:left() - bleed, page:top(), -len, 0.5) SILE.outputter.rule(page:left(), page:top() - bleed, 0.5, -len) SILE.outputter.rule(page:right() + bleed, page:top(), len, 0.5) SILE.outputter.rule(page:right(), page:top() - bleed, 0.5, -len) SILE.outputter.rule(page:left() - bleed, page:bottom(), -len, 0.5) SILE.outputter.rule(page:left(), page:bottom() + bleed, 0.5, len) SILE.outputter.rule(page:right() + bleed, page:bottom(), len, 0.5) SILE.outputter.rule(page:right(), page:bottom() + bleed, 0.5, len) SILE.call("hbox", {}, function() SILE.settings.temporarily(function() SILE.call("noindent") SILE.call("font", { size="6pt" }) SILE.call("crop:header") end) end) local hbox = SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] = nil SILE.typesetter.frame.state.cursorX = page:left() + bleed SILE.typesetter.frame.state.cursorY = page:top() - bleed - len / 2 + 2 outcounter = outcounter + 1 if hbox then for i=1,#(hbox.value) do hbox.value[i]:outputYourself(SILE.typesetter, {ratio=1}) end end end local function reconstrainFrameset(fs) for n,f in pairs(fs) do if n ~= "page" then if f:isAbsoluteConstraint("right") then f.constraints.right = "left(page) + (" .. f.constraints.right .. ")" end if f:isAbsoluteConstraint("left") then f.constraints.left = "left(page) + (" .. f.constraints.left .. ")" end if f:isAbsoluteConstraint("top") then f.constraints.top = "top(page) + (" .. f.constraints.top .. ")" end if f:isAbsoluteConstraint("bottom") then f.constraints.bottom = "top(page) + (" .. f.constraints.bottom .. ")" end f:invalidate() end end end SILE.registerCommand("crop:setup", function (o,c) local papersize = SU.required(o, "papersize", "setting up crop marks") local size = SILE.paperSizeParser(papersize) local oldsize = SILE.documentState.paperSize SILE.documentState.paperSize = size local offsetx = ( SILE.documentState.paperSize[1] - oldsize[1] ) / 2 local offsety = ( SILE.documentState.paperSize[2] - oldsize[2] ) / 2 local page = SILE.getFrame("page") page:constrain("right", oldsize[1] + offsetx) page:constrain("left", offsetx) page:constrain("bottom", oldsize[2] + offsety) page:constrain("top", offsety) if SILE.scratch.masters then for k,v in pairs(SILE.scratch.masters) do reconstrainFrameset(v.frames) end else reconstrainFrameset(SILE.documentState.documentClass.pageTemplate.frames) end if SILE.typesetter.frame then SILE.typesetter.frame:init() end local oldEndPage = SILE.documentState.documentClass.endPage SILE.documentState.documentClass.endPage = function(self) oldEndPage(self) outputMarks() end end) -- END package override if not sheetsize then local papersize = SILE.documentState.paperSize local w = papersize[1] + (trim * 2) local h = papersize[2] + (trim * 2) sheetsize = w .. "pt x " .. h .. "pt" end local outcounter = 1 SILE.registerCommand("crop:header", function (options, content) SILE.call("meta:surum") SILE.typesetter:typeset(" (" .. outcounter .. ") " .. os.getenv("HOSTNAME") .. " / " .. os.date("%Y-%m-%d, %X")) outcounter = outcounter + 1 end) SILE.call("crop:setup", { papersize = sheetsize })
Add hacked version of SILE's crop marks to dodge math bug
Add hacked version of SILE's crop marks to dodge math bug
Lua
agpl-3.0
alerque/casile,alerque/casile,alerque/casile,alerque/casile,alerque/casile
2a88978e96421c2537e1171eb4b483e778c7e489
kong/resolver/access.lua
kong/resolver/access.lua
local url = require "socket.url" local cache = require "kong.tools.database_cache" local constants = require "kong.constants" local responses = require "kong.tools.responses" local _M = {} local function get_backend_url(api) local result = api.target_url -- Checking if the target url ends with a final slash local len = string.len(result) if string.sub(result, len, len) == "/" then -- Remove one slash to avoid having a double slash -- Because ngx.var.request_uri always starts with a slash result = string.sub(result, 0, len - 1) end return result end local function get_host_from_url(val) local parsed_url = url.parse(val) local port if parsed_url.port then port = parsed_url.port elseif parsed_url.scheme == "https" then port = 443 end return parsed_url.host..(port and ":"..port or "") end -- Find an API from a request made to nginx. Either from one of the Host or X-Host-Override headers -- matching the API's `public_dns`, either from the `request_uri` matching the API's `path`. -- -- To perform this, we need to query _ALL_ APIs in memory. It is the only way to compare the `request_uri` -- as a regex to the values set in DB. We keep APIs in the database cache for a longer time than usual. -- @see https://github.com/Mashape/kong/issues/15 for an improvement on this. -- -- @param `request_uri` The URI for this request. -- @return `err` Any error encountered during the retrieval. -- @return `api` The retrieved API, if any. -- @return `hosts` The list of headers values found in Host and X-Host-Override. -- @return `request_uri` The URI for this request. -- @return `by_path` If the API was retrieved by path, will be true, false if by Host. local function find_api(request_uri) local retrieved_api -- retrieve all APIs local apis_dics, err = cache.get_or_set("ALL_APIS_BY_DIC", function() local apis, err = dao.apis:find_all() if err then return nil, err end -- build dictionnaries of public_dns:api and path:apis for efficient lookup. local dns_dic, path_dic = {}, {} for _, api in ipairs(apis) do if api.public_dns then dns_dic[api.public_dns] = api end if api.path then path_dic[api.path] = api end end return {dns = dns_dic, path = path_dic} end, 60) -- 60 seconds cache if err then return err end -- find by Host header local all_hosts = {} for _, header_name in ipairs({"Host", constants.HEADERS.HOST_OVERRIDE}) do local hosts = ngx.req.get_headers()[header_name] if hosts then if type(hosts) == "string" then hosts = {hosts} end -- for all values of this header, try to find an API using the apis_by_dns dictionnary for _, host in ipairs(hosts) do table.insert(all_hosts, host) if apis_dics.dns[host] then retrieved_api = apis_dics.dns[host] break end end end end -- If it was found by Host, return. if retrieved_api then return nil, retrieved_api, all_hosts end -- Otherwise, we look for it by path. We have to loop over all APIs and compare the requested URI. for path, api in pairs(apis_dics.path) do local m, err = ngx.re.match(request_uri, "^"..path) if err then ngx.log(ngx.ERR, "[resolver] error matching requested path: "..err) elseif m then retrieved_api = api end end -- Return the retrieved_api or nil return nil, retrieved_api, all_hosts, true end -- Retrieve the API from the Host that has been requested function _M.execute(conf) local request_uri = ngx.var.request_uri local err, api, hosts, by_path = find_api(request_uri) if err then return responses.send_HTTP_INTERNAL_SERVER_ERROR(err) elseif not api then return responses.send_HTTP_NOT_FOUND { message = "API not found with these values", public_dns = hosts, path = request_uri } end -- If API was retrieved by path if by_path and api.strip_path then -- All paths are '/path', so let's replace it with a single '/' request_uri = string.gsub(request_uri, api.path, "/") end -- Setting the backend URL for the proxy_pass directive ngx.var.backend_url = get_backend_url(api)..request_uri ngx.req.set_header("Host", get_host_from_url(ngx.var.backend_url)) ngx.ctx.api = api end return _M
local url = require "socket.url" local cache = require "kong.tools.database_cache" local constants = require "kong.constants" local responses = require "kong.tools.responses" local _M = {} local function get_backend_url(api) local result = api.target_url -- Checking if the target url ends with a final slash local len = string.len(result) if string.sub(result, len, len) == "/" then -- Remove one slash to avoid having a double slash -- Because ngx.var.request_uri always starts with a slash result = string.sub(result, 0, len - 1) end return result end local function get_host_from_url(val) local parsed_url = url.parse(val) local port if parsed_url.port then port = parsed_url.port elseif parsed_url.scheme == "https" then port = 443 end return parsed_url.host..(port and ":"..port or "") end -- Find an API from a request made to nginx. Either from one of the Host or X-Host-Override headers -- matching the API's `public_dns`, either from the `request_uri` matching the API's `path`. -- -- To perform this, we need to query _ALL_ APIs in memory. It is the only way to compare the `request_uri` -- as a regex to the values set in DB. We keep APIs in the database cache for a longer time than usual. -- @see https://github.com/Mashape/kong/issues/15 for an improvement on this. -- -- @param `request_uri` The URI for this request. -- @return `err` Any error encountered during the retrieval. -- @return `api` The retrieved API, if any. -- @return `hosts` The list of headers values found in Host and X-Host-Override. -- @return `request_uri` The URI for this request. -- @return `by_path` If the API was retrieved by path, will be true, false if by Host. local function find_api(request_uri) local retrieved_api -- retrieve all APIs local apis_dics, err = cache.get_or_set("ALL_APIS_BY_DIC", function() local apis, err = dao.apis:find_all() if err then return nil, err end -- build dictionnaries of public_dns:api and path:apis for efficient lookup. local dns_dic, path_dic = {}, {} for _, api in ipairs(apis) do if api.public_dns then dns_dic[api.public_dns] = api end if api.path then path_dic[api.path] = api end end return {dns = dns_dic, path = path_dic} end, 60) -- 60 seconds cache if err then return err end -- find by Host header local all_hosts = {} for _, header_name in ipairs({"Host", constants.HEADERS.HOST_OVERRIDE}) do local hosts = ngx.req.get_headers()[header_name] if hosts then if type(hosts) == "string" then hosts = {hosts} end -- for all values of this header, try to find an API using the apis_by_dns dictionnary for _, host in ipairs(hosts) do table.insert(all_hosts, host) if apis_dics.dns[host] then retrieved_api = apis_dics.dns[host] break end end end end -- If it was found by Host, return. if retrieved_api then return nil, retrieved_api, all_hosts end -- Otherwise, we look for it by path. We have to loop over all APIs and compare the requested URI. for path, api in pairs(apis_dics.path) do local m, err = ngx.re.match(request_uri, "^"..path) if err then ngx.log(ngx.ERR, "[resolver] error matching requested path: "..err) elseif m then retrieved_api = api end end -- Return the retrieved_api or nil return nil, retrieved_api, all_hosts, true end -- Retrieve the API from the Host that has been requested function _M.execute(conf) local request_uri = ngx.var.request_uri local err, api, hosts, by_path = find_api(request_uri) if err then return responses.send_HTTP_INTERNAL_SERVER_ERROR(err) elseif not api then return responses.send_HTTP_NOT_FOUND { message = "API not found with these values", public_dns = hosts, path = request_uri } end -- If API was retrieved by path if by_path and api.strip_path then -- Replace `/path` with `path`, and then prefix with a `/` -- Or replace `/path/foo` with `/foo`, and then do not prefix with `/`. request_uri = string.gsub(request_uri, api.path, "") if string.sub(request_uri, 0, 1) ~= "/" then request_uri = "/"..request_uri end end -- Setting the backend URL for the proxy_pass directive ngx.var.backend_url = get_backend_url(api)..request_uri ngx.req.set_header("Host", get_host_from_url(ngx.var.backend_url)) ngx.ctx.api = api end return _M
fix(resolver) handling edgecase resulting in wrong URI
fix(resolver) handling edgecase resulting in wrong URI - If querying `/path/foo` with `strip_path=true`, then the resolver would replace the URI with `//foo`.
Lua
apache-2.0
peterayeni/kong,AnsonSmith/kong,paritoshmmmec/kong,bbalu/kong,ChristopherBiscardi/kong,sbuettner/kong,wakermahmud/kong,Skyscanner/kong,skynet/kong,puug/kong,chourobin/kong,vmercierfr/kong
7f133166ea3345718bc7e2e3ac2e2a92379187cc
orange/utils/headers.lua
orange/utils/headers.lua
-- -- Created by IntelliJ IDEA. -- User: soul11201 <[email protected]> -- Date: 2017/4/26 -- Time: 20:50 -- To change this template use File | Settings | File Templates. -- local handle_util = require("orange.utils.handle") local extractor_util = require("orange.utils.extractor") local _M = {} local function set_header(k,v,overide) local override = overide or false end function _M:set_headers(rule) local extractor,headers_config= rule.extractor,rule.headers if not headers_config or type(headers_config) ~= 'table' then return end local variables = extractor_util.extract_variables(extractor) local req_headers = ngx.req.get_headers(); for _, v in pairs(headers_config) do -- 不存在 || 存在且覆蓋 ngx.log(ngx.ERR,v.name,v.value); if not req_headers[v.name] or v.override == '1' then if v.type == "normal" then ngx.req.set_header(v.name,v.value) ngx.log(ngx.INFO,'[plug header][normal] add headers [',v.name,":",v.value,']') elseif v.type == "extraction" then local value = handle_util.build_uri(extractor.type, v.value, variables) ngx.req.set_header(v.name,value) ngx.log(ngx.INFO,'[plug header][normal] add headers [',v.name,":",value,']') end end end end return _M
-- -- Created by IntelliJ IDEA. -- User: soul11201 <[email protected]> -- Date: 2017/4/26 -- Time: 20:50 -- To change this template use File | Settings | File Templates. -- local handle_util = require("orange.utils.handle") local extractor_util = require("orange.utils.extractor") local _M = {} local function set_header(k,v,overide) local override = overide or false end function _M:set_headers(rule) local extractor,headers_config= rule.extractor,rule.headers if not headers_config or type(headers_config) ~= 'table' then return end local variables = extractor_util.extract_variables(extractor) local req_headers = ngx.req.get_headers(); for _, v in pairs(headers_config) do -- 不存在 || 存在且覆蓋 if not req_headers[v.name] or v.override == '1' then if v.type == "normal" then ngx.req.set_header(v.name,v.value) ngx.log(ngx.INFO,'[plug header][normal] add headers [',v.name,":",v.value,']') elseif v.type == "extraction" then local value = handle_util.build_uri(extractor.type, v.value, variables) ngx.req.set_header(v.name,value) ngx.log(ngx.INFO,'[plug header][expression] add headers [',v.name,":",value,']') end end end end return _M
refactor: headers.lua del log && fix info
refactor: headers.lua del log && fix info
Lua
mit
sumory/orange,sumory/orange,sumory/orange
c62b5524663ea5bccb4a0032ff0ee58bd971648c
src/lua-factory/sources/grl-metrolyrics.lua
src/lua-factory/sources/grl-metrolyrics.lua
--[[ * Copyright (C) 2014 Victor Toso. * * Contact: Victor Toso <[email protected]> * * 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" }, resolve_keys = { ["type"] = "audio", required = { "artist", "title" }, }, } 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 then grl.callback() 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 res = {} local lyrics_body = '<div class="lyrics%-body">(.-)</div>' local lyrics_verse = "<p class='verse'>(.-)</p>" -- from html, get lyrics line by line into table res feed = feed:match(lyrics_body) for verse in feed:gmatch(lyrics_verse) do local start = 1 local e, s = verse:find("<br/>") while (e) do res[#res + 1] = verse:sub(start, e-1) start = s+1 e, s = verse:find("<br/>", start) end res[#res + 1] = verse:sub(start, #verse) .. '\n\n' end -- switch table to string media.lyrics = table.concat(res) return media end
--[[ * Copyright (C) 2014 Victor Toso. * * Contact: Victor Toso <[email protected]> * * 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" }, resolve_keys = { ["type"] = "audio", required = { "artist", "title" }, }, } 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 res = {} local lyrics_body = '<div class="lyrics%-body">(.-)</div>' local lyrics_verse = "<p class='verse'>(.-)</p>" -- from html, get lyrics line by line into table res feed = feed:match(lyrics_body) for verse in feed:gmatch(lyrics_verse) do local start = 1 local e, s = verse:find("<br/>") while (e) do res[#res + 1] = verse:sub(start, e-1) start = s+1 e, s = verse:find("<br/>", start) end res[#res + 1] = verse:sub(start, #verse) .. '\n\n' end -- switch table to string media.lyrics = table.concat(res) return media end
metrolyrics: fix initial check up
metrolyrics: fix initial check up Artist and Title must be non empty strings. Return after callback. https://bugzilla.gnome.org/show_bug.cgi?id=726677
Lua
lgpl-2.1
jasuarez/grilo-plugins,GNOME/grilo-plugins,MikePetullo/grilo-plugins,MathieuDuponchelle/grilo-plugins,vrutkovs/grilo-plugins,vrutkovs/grilo-plugins,MathieuDuponchelle/grilo-plugins,MathieuDuponchelle/grilo-plugins,jasuarez/grilo-plugins,MikePetullo/grilo-plugins,MikePetullo/grilo-plugins,MathieuDuponchelle/grilo-plugins,grilofw/grilo-plugins,grilofw/grilo-plugins,vrutkovs/grilo-plugins,vrutkovs/grilo-plugins,GNOME/grilo-plugins
21f7dd4fad6c053faa4e210b1cdacfef9d516e46
app/views/language_select_box.lua
app/views/language_select_box.lua
local widget = require "widget" local composer = require "composer" local class = require "lib.middleclass" local MessageBox = require "app.views.message_box" local Button = require "app.views.button" local LanguageSelectBox = class("LanguageSelectBox", MessageBox) function LanguageSelectBox:selectLanguage(code) setLanguage(code) local current_scene = composer.getScene(composer.getSceneName("current")) current_scene:redrawScene() self:hide() end function LanguageSelectBox:redrawButtons() if self.buttonGroup then self.buttonGroup:removeSelf() end self.buttonGroup = display.newGroup() self.detailGroup:insert(self.buttonGroup) local offsetY = self.bg.y - self.bg.height / 2 + 80 for code, name in pairs(availableLanguages()) do Button:new( self.buttonGroup, offsetY, name, code == language and "main" or "gray", function() self:selectLanguage(code) end, self.bg.width - 40, nil, { fontSize = 15 } ) offsetY = offsetY + 50 end end function LanguageSelectBox:onCreate() self:newText(T:t('language_select.title'), _W / 2, self.bg.y - self.bg.height / 2 + 25, { fontSize = 17 }) end function LanguageSelectBox:onShow() self:redrawButtons() end return LanguageSelectBox
local widget = require "widget" local composer = require "composer" local class = require "lib.middleclass" local MessageBox = require "app.views.message_box" local Button = require "app.views.button" local LanguageSelectBox = class("LanguageSelectBox", MessageBox) function LanguageSelectBox:selectLanguage(code) setLanguage(code) local current_scene = composer.getScene(composer.getSceneName("current")) current_scene:redrawScene() self:hide() end function LanguageSelectBox:redrawButtons() if self.buttonGroup then self.buttonGroup:removeSelf() end self.buttonGroup = display.newGroup() self.detailGroup:insert(self.buttonGroup) local offsetY = self.bg.y - self.bg.height / 2 + 80 for code, name in pairs(availableLanguages()) do Button:new( self.buttonGroup, offsetY, name, code == language and "main" or "gray", function() self:selectLanguage(code) end, self.bg.width - 40, nil, { fontSize = 15 } ) offsetY = offsetY + 50 end end function LanguageSelectBox:onCreate() self.title = self:newText(T:t('language_select.title'), _W / 2, self.bg.y - self.bg.height / 2 + 25, { fontSize = 17 }) end function LanguageSelectBox:onShow() self:redrawButtons() self.title.text = T:t("language_select.title") end return LanguageSelectBox
Fix: preklad nadpisu volby jazyka
Fix: preklad nadpisu volby jazyka
Lua
mit
jhysek/Minimal-Corona-SDK-Template,jhysek/Minimal-Corona-SDK-Template
f1f5eaccd332c9622ca3387f94ecc7c0b16a009a
interface/flow/init.lua
interface/flow/init.lua
local lfs = require "lfs" local log = require "log" local configenv = require "configenv" local options = require "options" local errors = require "errors" local Flow = require "flow.instance" local Packet = require "flow.packet" local mod = { flows = {} } local env = configenv.env function env.Flow(tbl) if type(tbl) ~= "table" then env.error("Invalid usage of Flow. Try Flow{...)") return end -- check name, disallow for characters that -- - would complicate shell argument parsing ( ;) -- - interfere with flow parameter syntax (/:,) local name = tbl[1] local t = type(name) if t ~= "string" then env.error("Invalid flow name. String expected, got %s.", t) name = nil elseif name == "" then env.error("Flow name cannot be empty.") name = nil elseif string.find(name, "[ ;/:,]") then env.error("Invalid flow name %q. Names cannot include the characters ' ;/:,'.", name) name = nil end -- find instace of parent flow local parent = tbl.parent t = type(parent) if t == "string" then parent = mod.flows[parent] env.error:assert(parent, "Unknown parent %q of flow %q.", parent, name) elseif t ~= "table" and t ~= "nil" then env.error("Invalid value for parent of flow %q. String or flow expected, got %s.", name, t) parent = nil end local packet = tbl[2] if env.error:assert(packet, "Flow %q does not have a valid packet.", name) and parent then packet:inherit(parent.packet) end -- process options tbl[1], tbl[2], tbl.parent = nil, nil, nil for i in pairs(tbl) do env.error:assert(options[i], "Unknown option %q.", i) end local opts, parent_opts = {}, parent and parent.options or {} for i in pairs(options) do opts[i] = tbl[i] or parent_opts[i] end -- ready to assemble flow prototype local flow = { name = name, file = env._FILE, parent = parent, packet = packet, options = opts} -- attempt to add to global flow list if flow.name then local test = mod.flows[name] if test then env.error:assert(not test, 3, "Duplicate flow %q. Also in file %s.", name, test.file) else mod.flows[name] = flow end end return flow end local packetmsg = "Invalid usage of Packet. Try Packet.<Proto>{...}." local function _packet_error() env.error(packetmsg) end env.Packet = setmetatable({}, { __newindex = _packet_error, __call = _packet_error, __index = function(_, proto) if type(proto) ~= "string" then env.error(packetmsg) return function() end end return function(tbl) if type(tbl) ~= "table" then env.error(packetmsg) else return Packet.new(proto, tbl, env.error) end end end }) local function printError(silent, ...) if not silent then log:error(...) end end local function finalizeErrHnd(silent, error, msg, ...) if silent then return end local cnt = error:count() if cnt > 0 then log:error(msg, cnt, ...) error:print(true, log.warn, log) end end function mod.crawlDirectory(baseDir, silent) configenv:setErrHnd() baseDir = baseDir or "flows" for f in lfs.dir(baseDir) do f = baseDir .. "/" .. f if lfs.attributes(f, "mode") == "file" then configenv:parseFile(f) end end finalizeErrHnd(silent, configenv:error(), "%d errors found while processing directory %s:", baseDir) end function mod.crawlFile(filename, silent) configenv:setErrHnd() configenv:parseFile(filename) finalizeErrHnd(silent, configenv:error(), "%d errors found while processing file %s:", filename) end function mod.getInstance(name, file, cli_options, overwrites, properties, silent, final) local error = errors() error.defaultLevel = -1 local flow = { restore = { options = cli_options, overwrites = overwrites }, proto = mod.flows[name], -- packet = proto.packet, results = {}, properties = properties or {} } setmetatable(flow, Flow) -- find flow prototype if file and not flow.proto then configenv:setErrHnd() configenv:parseFile(file) finalizeErrHnd(silent, configenv:error(), "%d errors found while processing extra file %s:", file) flow.proto = mod.flows[name] end if not flow.proto then return printError(silent, "Flow %q not found.", name) end -- find or create packet flow.packet = flow.proto.packet if overwrites and overwrites ~= "" then configenv:setErrHnd(error) flow.packet = configenv:parseString( ("return Packet.%s{%s}"):format(flow.packet.proto, overwrites), ("Overwrites for flow %q."):format(name) ) if not flow.packet then return printError(silent, "Invalid overwrite for flow %q.", name) end flow.packet:inherit(flow.proto.packet) end -- warn about unknown options for i in pairs(cli_options) do error:assert(options[i], "Unknown option %q.", i) end -- process options local results = flow.results for i, opt in pairs(options) do error:setPrefix("Option '%s': ", i) local v = cli_options[i] or flow.proto.options[i] results[i] = opt.parse(flow, v, error) end -- prepare flow error:setPrefix() flow:prepare(error, final) finalizeErrHnd(silent, error, "%d errors found while processing flow %q.", name) if error.valid then return flow end end function mod.restore(flow) local p, r = flow.proto, flow.restore return mod.getInstance(p.name, p.file, r.options, r.overwrites, flow.properties, true, true) end return mod
local lfs = require "lfs" local log = require "log" local configenv = require "configenv" local options = require "options" local errors = require "errors" local Flow = require "flow.instance" local Packet = require "flow.packet" local mod = { flows = {} } local env = configenv.env function env.Flow(tbl) if type(tbl) ~= "table" then env.error("Invalid usage of Flow. Try Flow{...)") return end -- check name, disallow for characters that -- - would complicate shell argument parsing ( ;) -- - interfere with flow parameter syntax (/:,) local name = tbl[1] local t = type(name) if t ~= "string" then env.error("Invalid flow name. String expected, got %s.", t) name = nil elseif name == "" then env.error("Flow name cannot be empty.") name = nil elseif string.find(name, "[ ;/:,]") then env.error("Invalid flow name %q. Names cannot include the characters ' ;/:,'.", name) name = nil end -- find instace of parent flow local parent = tbl.parent t = type(parent) if t == "string" then parent = mod.flows[parent] env.error:assert(parent, "Unknown parent %q of flow %q.", parent, name) elseif t ~= "table" and t ~= "nil" then env.error("Invalid value for parent of flow %q. String or flow expected, got %s.", name, t) parent = nil end local packet = tbl[2] if env.error:assert(packet, "Flow %q does not have a valid packet.", name) and parent then packet:inherit(parent.packet) end -- process options tbl[1], tbl[2], tbl.parent = nil, nil, nil for i in pairs(tbl) do env.error:assert(options[i], "Unknown option %q.", i) end local opts, parent_opts = {}, parent and parent.options or {} for i in pairs(options) do opts[i] = tbl[i] or parent_opts[i] end -- ready to assemble flow prototype local flow = { name = name, file = env._FILE, parent = parent, packet = packet, options = opts} -- attempt to add to global flow list if flow.name then local test = mod.flows[name] if test then env.error:assert(not test, 3, "Duplicate flow %q. Also in file %s.", name, test.file) else mod.flows[name] = flow end end return flow end local packetmsg = "Invalid usage of Packet. Try Packet.<Proto>{...}." local function _packet_error() env.error(packetmsg) end env.Packet = setmetatable({}, { __newindex = _packet_error, __call = _packet_error, __index = function(_, proto) if type(proto) ~= "string" then env.error(packetmsg) return function() end end return function(tbl) if type(tbl) ~= "table" then env.error(packetmsg) else return Packet.new(proto, tbl, env.error) end end end }) local function printError(silent, ...) if not silent then log:error(...) end end local function finalizeErrHnd(silent, error, msg, ...) if silent then return end local cnt = error:count() if cnt > 0 then log:error(msg, cnt, ...) error:print(true, log.warn, log) end end function mod.crawlDirectory(baseDir, silent) configenv:setErrHnd() baseDir = baseDir or "flows" for f in lfs.dir(baseDir) do f = baseDir .. "/" .. f if lfs.attributes(f, "mode") == "file" then configenv:parseFile(f) end end finalizeErrHnd(silent, configenv:error(), "%d errors found while processing directory %s:", baseDir) end function mod.crawlFile(filename, silent) configenv:setErrHnd() configenv:parseFile(filename) finalizeErrHnd(silent, configenv:error(), "%d errors found while processing file %s:", filename) end function mod.getInstance(name, file, cli_options, overwrites, properties, silent, final) local error = errors() error.defaultLevel = -1 local flow = { restore = { options = cli_options, overwrites = overwrites }, proto = mod.flows[name], -- packet = proto.packet, results = {}, properties = properties or {} } setmetatable(flow, Flow) -- find flow prototype if file and not flow.proto then configenv:setErrHnd() configenv:parseFile(file) finalizeErrHnd(silent, configenv:error(), "%d errors found while processing extra file %s:", file) flow.proto = mod.flows[name] end if not flow.proto then return printError(silent, "Flow %q not found.", name) end -- find or create packet flow.packet = flow.proto.packet if overwrites and overwrites ~= "" then configenv:setErrHnd(error) flow.packet = configenv:parseString( ("return Packet.%s{%s}"):format(flow.packet.proto, overwrites), ("Overwrites for flow %q."):format(name) ) else flow.packet = Packet.new(flow.proto.packet.proto, {}) end if not flow.packet then return printError(silent, "Invalid overwrite for flow %q.", name) end flow.packet:inherit(flow.proto.packet) -- warn about unknown options for i in pairs(cli_options) do error:assert(options[i], "Unknown option %q.", i) end -- process options local results = flow.results for i, opt in pairs(options) do error:setPrefix("Option '%s': ", i) local v = cli_options[i] or flow.proto.options[i] results[i] = opt.parse(flow, v, error) end -- prepare flow error:setPrefix() flow:prepare(error, final) finalizeErrHnd(silent, error, "%d errors found while processing flow %q.", name) if error.valid then return flow end end function mod.restore(flow) local p, r = flow.proto, flow.restore return mod.getInstance(p.name, p.file, r.options, r.overwrites, flow.properties, true, true) end return mod
Always inherit instance packet (fixes cloning).
Always inherit instance packet (fixes cloning).
Lua
mit
gallenmu/MoonGen,scholzd/MoonGen,dschoeffm/MoonGen,gallenmu/MoonGen,scholzd/MoonGen,dschoeffm/MoonGen,dschoeffm/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,scholzd/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,emmericp/MoonGen,gallenmu/MoonGen,emmericp/MoonGen,gallenmu/MoonGen,emmericp/MoonGen
9e4b8a91384562e3baee724a52b72e30b1aa006d
modules/luci-mod-admin-full/luasrc/controller/admin/status.lua
modules/luci-mod-admin-full/luasrc/controller/admin/status.lua
-- Copyright 2008 Steven Barth <[email protected]> -- Copyright 2011 Jo-Philipp Wich <[email protected]> -- Licensed to the public under the Apache License 2.0. module("luci.controller.admin.status", package.seeall) function index() entry({"admin", "status"}, alias("admin", "status", "overview"), _("Status"), 20).index = true entry({"admin", "status", "overview"}, template("admin_status/index"), _("Overview"), 1) entry({"admin", "status", "iptables"}, template("admin_status/iptables"), _("Firewall"), 2).leaf = true entry({"admin", "status", "iptables_action"}, post("action_iptables")).leaf = true entry({"admin", "status", "routes"}, template("admin_status/routes"), _("Routes"), 3) entry({"admin", "status", "syslog"}, call("action_syslog"), _("System Log"), 4) entry({"admin", "status", "dmesg"}, call("action_dmesg"), _("Kernel Log"), 5) entry({"admin", "status", "processes"}, cbi("admin_status/processes"), _("Processes"), 6) entry({"admin", "status", "realtime"}, alias("admin", "status", "realtime", "load"), _("Realtime Graphs"), 7) entry({"admin", "status", "realtime", "load"}, template("admin_status/load"), _("Load"), 1).leaf = true entry({"admin", "status", "realtime", "load_status"}, call("action_load")).leaf = true entry({"admin", "status", "realtime", "bandwidth"}, template("admin_status/bandwidth"), _("Traffic"), 2).leaf = true entry({"admin", "status", "realtime", "bandwidth_status"}, call("action_bandwidth")).leaf = true if nixio.fs.access("/etc/config/wireless") then entry({"admin", "status", "realtime", "wireless"}, template("admin_status/wireless"), _("Wireless"), 3).leaf = true entry({"admin", "status", "realtime", "wireless_status"}, call("action_wireless")).leaf = true end entry({"admin", "status", "realtime", "connections"}, template("admin_status/connections"), _("Connections"), 4).leaf = true entry({"admin", "status", "realtime", "connections_status"}, call("action_connections")).leaf = true entry({"admin", "status", "nameinfo"}, call("action_nameinfo")).leaf = true end function action_syslog() local syslog = luci.sys.syslog() luci.template.render("admin_status/syslog", {syslog=syslog}) end function action_dmesg() local dmesg = luci.sys.dmesg() luci.template.render("admin_status/dmesg", {dmesg=dmesg}) end function action_iptables() if luci.http.formvalue("zero") then if luci.http.formvalue("family") == "6" then luci.util.exec("/usr/sbin/ip6tables -Z") else luci.util.exec("/usr/sbin/iptables -Z") end elseif luci.http.formvalue("restart") then luci.util.exec("/etc/init.d/firewall restart") end luci.http.redirect(luci.dispatcher.build_url("admin/status/iptables")) end function action_bandwidth(iface) luci.http.prepare_content("application/json") local bwc = io.popen("luci-bwc -i %q 2>/dev/null" % iface) if bwc then luci.http.write("[") while true do local ln = bwc:read("*l") if not ln then break end luci.http.write(ln) end luci.http.write("]") bwc:close() end end function action_wireless(iface) luci.http.prepare_content("application/json") local bwc = io.popen("luci-bwc -r %q 2>/dev/null" % iface) if bwc then luci.http.write("[") while true do local ln = bwc:read("*l") if not ln then break end luci.http.write(ln) end luci.http.write("]") bwc:close() end end function action_load() luci.http.prepare_content("application/json") local bwc = io.popen("luci-bwc -l 2>/dev/null") if bwc then luci.http.write("[") while true do local ln = bwc:read("*l") if not ln then break end luci.http.write(ln) end luci.http.write("]") bwc:close() end end function action_connections() local sys = require "luci.sys" luci.http.prepare_content("application/json") luci.http.write("{ connections: ") luci.http.write_json(sys.net.conntrack()) local bwc = io.popen("luci-bwc -c 2>/dev/null") if bwc then luci.http.write(", statistics: [") while true do local ln = bwc:read("*l") if not ln then break end luci.http.write(ln) end luci.http.write("]") bwc:close() end luci.http.write(" }") end function action_nameinfo(...) local util = require "luci.util" luci.http.prepare_content("application/json") luci.http.write_json(util.ubus("network.rrdns", "lookup", { addrs = { ... }, timeout = 5000, limit = 1000 }) or { }) end
-- Copyright 2008 Steven Barth <[email protected]> -- Copyright 2011 Jo-Philipp Wich <[email protected]> -- Licensed to the public under the Apache License 2.0. module("luci.controller.admin.status", package.seeall) function index() entry({"admin", "status"}, alias("admin", "status", "overview"), _("Status"), 20).index = true entry({"admin", "status", "overview"}, template("admin_status/index"), _("Overview"), 1) entry({"admin", "status", "iptables"}, template("admin_status/iptables"), _("Firewall"), 2).leaf = true entry({"admin", "status", "iptables_action"}, post("action_iptables")).leaf = true entry({"admin", "status", "routes"}, template("admin_status/routes"), _("Routes"), 3) entry({"admin", "status", "syslog"}, call("action_syslog"), _("System Log"), 4) entry({"admin", "status", "dmesg"}, call("action_dmesg"), _("Kernel Log"), 5) entry({"admin", "status", "processes"}, cbi("admin_status/processes"), _("Processes"), 6) entry({"admin", "status", "realtime"}, alias("admin", "status", "realtime", "load"), _("Realtime Graphs"), 7) entry({"admin", "status", "realtime", "load"}, template("admin_status/load"), _("Load"), 1).leaf = true entry({"admin", "status", "realtime", "load_status"}, call("action_load")).leaf = true entry({"admin", "status", "realtime", "bandwidth"}, template("admin_status/bandwidth"), _("Traffic"), 2).leaf = true entry({"admin", "status", "realtime", "bandwidth_status"}, call("action_bandwidth")).leaf = true if nixio.fs.access("/etc/config/wireless") then entry({"admin", "status", "realtime", "wireless"}, template("admin_status/wireless"), _("Wireless"), 3).leaf = true entry({"admin", "status", "realtime", "wireless_status"}, call("action_wireless")).leaf = true end entry({"admin", "status", "realtime", "connections"}, template("admin_status/connections"), _("Connections"), 4).leaf = true entry({"admin", "status", "realtime", "connections_status"}, call("action_connections")).leaf = true entry({"admin", "status", "nameinfo"}, call("action_nameinfo")).leaf = true end function action_syslog() local syslog = luci.sys.syslog() luci.template.render("admin_status/syslog", {syslog=syslog}) end function action_dmesg() local dmesg = luci.sys.dmesg() luci.template.render("admin_status/dmesg", {dmesg=dmesg}) end function action_iptables() if luci.http.formvalue("zero") then if luci.http.formvalue("family") == "6" then luci.util.exec("/usr/sbin/ip6tables -Z") else luci.util.exec("/usr/sbin/iptables -Z") end elseif luci.http.formvalue("restart") then luci.util.exec("/etc/init.d/firewall restart") end luci.http.redirect(luci.dispatcher.build_url("admin/status/iptables")) end function action_bandwidth(iface) luci.http.prepare_content("application/json") local bwc = io.popen("luci-bwc -i '%s' 2>/dev/null" % iface:gsub("'", "")) if bwc then luci.http.write("[") while true do local ln = bwc:read("*l") if not ln then break end luci.http.write(ln) end luci.http.write("]") bwc:close() end end function action_wireless(iface) luci.http.prepare_content("application/json") local bwc = io.popen("luci-bwc -r '%s' 2>/dev/null" % iface:gsub("'", "")) if bwc then luci.http.write("[") while true do local ln = bwc:read("*l") if not ln then break end luci.http.write(ln) end luci.http.write("]") bwc:close() end end function action_load() luci.http.prepare_content("application/json") local bwc = io.popen("luci-bwc -l 2>/dev/null") if bwc then luci.http.write("[") while true do local ln = bwc:read("*l") if not ln then break end luci.http.write(ln) end luci.http.write("]") bwc:close() end end function action_connections() local sys = require "luci.sys" luci.http.prepare_content("application/json") luci.http.write("{ connections: ") luci.http.write_json(sys.net.conntrack()) local bwc = io.popen("luci-bwc -c 2>/dev/null") if bwc then luci.http.write(", statistics: [") while true do local ln = bwc:read("*l") if not ln then break end luci.http.write(ln) end luci.http.write("]") bwc:close() end luci.http.write(" }") end function action_nameinfo(...) local util = require "luci.util" luci.http.prepare_content("application/json") luci.http.write_json(util.ubus("network.rrdns", "lookup", { addrs = { ... }, timeout = 5000, limit = 1000 }) or { }) end
luci-mod-admin-full: fix possible shell injection in bandwith status
luci-mod-admin-full: fix possible shell injection in bandwith status Signed-off-by: Jo-Philipp Wich <[email protected]>
Lua
apache-2.0
openwrt-es/openwrt-luci,openwrt-es/openwrt-luci,remakeelectric/luci,tobiaswaldvogel/luci,wongsyrone/luci-1,openwrt/luci,artynet/luci,wongsyrone/luci-1,remakeelectric/luci,chris5560/openwrt-luci,hnyman/luci,rogerpueyo/luci,tobiaswaldvogel/luci,nmav/luci,Noltari/luci,openwrt/luci,kuoruan/luci,openwrt-es/openwrt-luci,remakeelectric/luci,chris5560/openwrt-luci,lbthomsen/openwrt-luci,kuoruan/lede-luci,kuoruan/luci,chris5560/openwrt-luci,artynet/luci,wongsyrone/luci-1,Noltari/luci,kuoruan/lede-luci,rogerpueyo/luci,nmav/luci,kuoruan/lede-luci,Noltari/luci,nmav/luci,openwrt/luci,hnyman/luci,nmav/luci,artynet/luci,lbthomsen/openwrt-luci,kuoruan/lede-luci,hnyman/luci,lbthomsen/openwrt-luci,openwrt/luci,artynet/luci,chris5560/openwrt-luci,981213/luci-1,openwrt-es/openwrt-luci,Noltari/luci,openwrt-es/openwrt-luci,Noltari/luci,lbthomsen/openwrt-luci,chris5560/openwrt-luci,rogerpueyo/luci,nmav/luci,nmav/luci,chris5560/openwrt-luci,openwrt-es/openwrt-luci,lbthomsen/openwrt-luci,kuoruan/luci,wongsyrone/luci-1,nmav/luci,hnyman/luci,rogerpueyo/luci,hnyman/luci,rogerpueyo/luci,Noltari/luci,wongsyrone/luci-1,tobiaswaldvogel/luci,hnyman/luci,artynet/luci,hnyman/luci,kuoruan/lede-luci,tobiaswaldvogel/luci,wongsyrone/luci-1,kuoruan/luci,981213/luci-1,981213/luci-1,openwrt-es/openwrt-luci,lbthomsen/openwrt-luci,tobiaswaldvogel/luci,rogerpueyo/luci,remakeelectric/luci,kuoruan/luci,openwrt-es/openwrt-luci,openwrt/luci,wongsyrone/luci-1,981213/luci-1,openwrt/luci,kuoruan/luci,981213/luci-1,openwrt/luci,tobiaswaldvogel/luci,kuoruan/lede-luci,kuoruan/luci,rogerpueyo/luci,kuoruan/lede-luci,981213/luci-1,Noltari/luci,remakeelectric/luci,rogerpueyo/luci,remakeelectric/luci,openwrt/luci,Noltari/luci,hnyman/luci,chris5560/openwrt-luci,kuoruan/lede-luci,artynet/luci,tobiaswaldvogel/luci,artynet/luci,chris5560/openwrt-luci,981213/luci-1,Noltari/luci,lbthomsen/openwrt-luci,nmav/luci,tobiaswaldvogel/luci,artynet/luci,kuoruan/luci,nmav/luci,lbthomsen/openwrt-luci,remakeelectric/luci,artynet/luci,wongsyrone/luci-1,remakeelectric/luci
6e8098106f604b6e4c4d7a094dec737bdda24d9b
kong/cmd/migrations.lua
kong/cmd/migrations.lua
local DB = require "kong.db" local log = require "kong.cmd.utils.log" local tty = require "kong.cmd.utils.tty" local meta = require "kong.meta" local conf_loader = require "kong.conf_loader" local kong_global = require "kong.global" local migrations_utils = require "kong.cmd.utils.migrations" local lapp = [[ Usage: kong migrations COMMAND [OPTIONS] Manage database schema migrations. The available commands are: bootstrap Bootstrap the database and run all migrations. up Run any new migrations. finish Finish running any pending migrations after 'up'. list List executed migrations. reset Reset the database. Options: -y,--yes Assume "yes" to prompts and run non-interactively. -q,--quiet Suppress all output. -f,--force Run migrations even if database reports as already executed. --db-timeout (default 60) Timeout, in seconds, for all database operations (including schema consensus for Cassandra). --lock-timeout (default 60) Timeout, in seconds, for nodes waiting on the leader node to finish running migrations. -c,--conf (optional string) Configuration file. ]] local function confirm_prompt(q) local MAX = 3 local ANSWERS = { y = true, Y = true, yes = true, YES = true, n = false, N = false, no = false, NO = false } while MAX > 0 do io.write("> " .. q .. " [Y/n] ") local a = io.read("*l") if ANSWERS[a] ~= nil then return ANSWERS[a] end MAX = MAX - 1 end end local function execute(args) args.db_timeout = args.db_timeout * 1000 args.lock_timeout = args.lock_timeout if args.quiet then log.disable() end local conf = assert(conf_loader(args.conf)) package.path = conf.lua_package_path .. ";" .. package.path conf.pg_timeout = args.db_timeout -- connect + send + read conf.cassandra_timeout = args.db_timeout -- connect + send + read conf.cassandra_schema_consensus_timeout = args.db_timeout _G.kong = kong_global.new() kong_global.init_pdk(_G.kong, conf, nil) -- nil: latest PDK local db = assert(DB.new(conf)) assert(db:init_connector()) local schema_state = assert(db:schema_state()) if args.command == "list" then if schema_state.needs_bootstrap then log(migrations_utils.NEEDS_BOOTSTRAP_MSG) os.exit(3) end local r = "" if schema_state.executed_migrations then log("Executed migrations:\n%s", schema_state.executed_migrations) r = "\n" end if schema_state.pending_migrations then log("%sPending migrations:\n%s", r, schema_state.pending_migrations) r = "\n" end if schema_state.new_migrations then log("%sNew migrations available:\n%s", r, schema_state.new_migrations) r = "\n" end if schema_state.pending_migrations and schema_state.new_migrations then if r ~= "" then log("") end log.warn("Database has pending migrations from a previous upgrade, " .. "and new migrations from this upgrade (version %s)", tostring(meta._VERSION)) log("\nRun 'kong migrations finish' when ready to complete pending " .. "migrations (%s %s will be incompatible with the previous Kong " .. "version)", db.strategy, db.infos.db_desc) os.exit(4) end if schema_state.pending_migrations then log("\nRun 'kong migrations finish' when ready") os.exit(4) end if schema_state.new_migrations then log("\nRun 'kong migrations up' to proceed") os.exit(5) end -- exit(0) elseif args.command == "bootstrap" then migrations_utils.bootstrap(schema_state, db, args.lock_timeout) elseif args.command == "reset" then if not args.yes then if not tty.isatty() then error("not a tty: invoke 'reset' non-interactively with the --yes flag") end if not confirm_prompt("Are you sure? This operation is irreversible.") then log("cancelled") return end end local ok = migrations_utils.reset(schema_state, db, args.lock_timeout) if not ok then os.exit(1) end os.exit(0) elseif args.command == "up" then migrations_utils.up(schema_state, db, { ttl = args.lock_timeout, force = args.force, abort = true, -- exit the mutex if another node acquired it }) elseif args.command == "finish" then migrations_utils.finish(schema_state, db, { ttl = args.lock_timeout, force = args.force, }) else error("unreachable") end end return { lapp = lapp, execute = execute, sub_commands = { bootstrap = true, up = true, finish = true, list = true, reset = true, } }
local DB = require "kong.db" local log = require "kong.cmd.utils.log" local tty = require "kong.cmd.utils.tty" local meta = require "kong.meta" local conf_loader = require "kong.conf_loader" local kong_global = require "kong.global" local migrations_utils = require "kong.cmd.utils.migrations" local lapp = [[ Usage: kong migrations COMMAND [OPTIONS] Manage database schema migrations. The available commands are: bootstrap Bootstrap the database and run all migrations. up Run any new migrations. finish Finish running any pending migrations after 'up'. list List executed migrations. reset Reset the database. Options: -y,--yes Assume "yes" to prompts and run non-interactively. -q,--quiet Suppress all output. -f,--force Run migrations even if database reports as already executed. --db-timeout (default 60) Timeout, in seconds, for all database operations (including schema consensus for Cassandra). --lock-timeout (default 60) Timeout, in seconds, for nodes waiting on the leader node to finish running migrations. -c,--conf (optional string) Configuration file. ]] local function confirm_prompt(q) local MAX = 3 local ANSWERS = { y = true, Y = true, yes = true, YES = true, n = false, N = false, no = false, NO = false } while MAX > 0 do io.write("> " .. q .. " [Y/n] ") local a = io.read("*l") if ANSWERS[a] ~= nil then return ANSWERS[a] end MAX = MAX - 1 end end local function execute(args) args.db_timeout = args.db_timeout * 1000 args.lock_timeout = args.lock_timeout if args.quiet then log.disable() end local conf = assert(conf_loader(args.conf)) package.path = conf.lua_package_path .. ";" .. package.path conf.pg_timeout = args.db_timeout -- connect + send + read conf.cassandra_timeout = args.db_timeout -- connect + send + read conf.cassandra_schema_consensus_timeout = args.db_timeout _G.kong = kong_global.new() kong_global.init_pdk(_G.kong, conf, nil) -- nil: latest PDK local db = assert(DB.new(conf)) assert(db:init_connector()) local schema_state = assert(db:schema_state()) if args.command == "list" then if schema_state.needs_bootstrap then log(migrations_utils.NEEDS_BOOTSTRAP_MSG) os.exit(3) end local r = "" if schema_state.executed_migrations then log("Executed migrations:\n%s", schema_state.executed_migrations) r = "\n" end if schema_state.pending_migrations then log("%sPending migrations:\n%s", r, schema_state.pending_migrations) r = "\n" end if schema_state.new_migrations then log("%sNew migrations available:\n%s", r, schema_state.new_migrations) r = "\n" end if schema_state.pending_migrations and schema_state.new_migrations then if r ~= "" then log("") end log.warn("Database has pending migrations from a previous upgrade, " .. "and new migrations from this upgrade (version %s)", tostring(meta._VERSION)) log("\nRun 'kong migrations finish' when ready to complete pending " .. "migrations (%s %s will be incompatible with the previous Kong " .. "version)", db.strategy, db.infos.db_desc) os.exit(4) end if schema_state.pending_migrations then log("\nRun 'kong migrations finish' when ready") os.exit(4) end if schema_state.new_migrations then log("\nRun 'kong migrations up' to proceed") os.exit(5) end -- exit(0) elseif args.command == "bootstrap" then migrations_utils.bootstrap(schema_state, db, args.lock_timeout) elseif args.command == "reset" then if not args.yes then if not tty.isatty() then error("not a tty: invoke 'reset' non-interactively with the --yes flag") end if not schema_state.needs_bootstrap and not confirm_prompt("Are you sure? This operation is irreversible.") then log("cancelled") return end end local ok = migrations_utils.reset(schema_state, db, args.lock_timeout) if not ok then os.exit(1) end os.exit(0) elseif args.command == "up" then migrations_utils.up(schema_state, db, { ttl = args.lock_timeout, force = args.force, abort = true, -- exit the mutex if another node acquired it }) elseif args.command == "finish" then migrations_utils.finish(schema_state, db, { ttl = args.lock_timeout, force = args.force, }) else error("unreachable") end end return { lapp = lapp, execute = execute, sub_commands = { bootstrap = true, up = true, finish = true, list = true, reset = true, } }
fix(cli) do not ask for confirmation if nothing to reset
fix(cli) do not ask for confirmation if nothing to reset
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
05ceb9c0260c5019c59efc52a5d47fe8cb137d73
hash.lua
hash.lua
local ffi = require 'ffi' local tds = require 'tds.env' local elem = require 'tds.elem' local C = tds.C local hash = {} function hash.__new() local self = C.tds_hash_new() if self == nil then error('unable to allocate hash') end self = ffi.cast('tds_hash&', self) ffi.gc(self, C.tds_hash_free) return self end local function findkey(self, lkey) local obj if type(lkey) == 'string' then obj = C.tds_hash_search_string(self, lkey, #lkey) elseif type(lkey) == 'number' then obj = C.tds_hash_search_number(self, lkey) else error('string or number key expected') end return obj end function hash:__newindex(lkey, lval) assert(self) local obj = findkey(self, lkey) if obj ~= nil then if lval then local val = C.tds_hash_object_value(obj) C.tds_elem_free_content(val) elem.set(val, lval) else C.tds_hash_remove(self, obj) C.tds_hash_object_free(obj) end else if lval then local obj = C.tds_hash_object_new() local key = C.tds_hash_object_key(obj) local val = C.tds_hash_object_value(obj) elem.set(val, lval) elem.set(key, lkey) C.tds_hash_insert(self, obj) end end end function hash:__index(lkey) assert(self) local obj = findkey(self, lkey) if obj ~= nil then local val = elem.get(C.tds_hash_object_value(obj)) return val else return rawget(hash, lkey) end end function hash:__len() assert(self) return tonumber(C.tds_hash_size(self)) end function hash:__pairs() assert(self) local iterator = C.tds_hash_iterator_new(self) ffi.gc(iterator, C.tds_hash_iterator_free) return function() local obj = C.tds_hash_iterator_next(iterator) if obj ~= nil then local key = elem.get(C.tds_hash_object_key(obj)) local val = elem.get(C.tds_hash_object_value(obj)) return key, val end end end hash.pairs = hash.__pairs ffi.metatype('tds_hash', hash) if pcall(require, 'torch') and torch.metatype then function hash:write(f) f:writeLong(self:__len()) for k,v in pairs(self) do f:writeObject(k) f:writeObject(v) end end function hash:read(f) local n = f:readLong() for i=1,n do local k = f:readObject() local v = f:readObject() self[k] = v end end hash.__factory = hash.__new hash.__version = 0 torch.metatype('tds_hash', hash, 'tds_hash&') end -- table constructor local hash_ctr = {} setmetatable( hash_ctr, { __index = hash, __newindex = hash, __call = hash.__new } ) tds.hash = hash_ctr return hash_ctr
local ffi = require 'ffi' local tds = require 'tds.env' local elem = require 'tds.elem' local C = tds.C local hash = {} function hash.__new() local self = C.tds_hash_new() if self == nil then error('unable to allocate hash') end self = ffi.cast('tds_hash&', self) ffi.gc(self, C.tds_hash_free) return self end local function findkey(self, lkey) local obj if type(lkey) == 'string' then obj = C.tds_hash_search_string(self, lkey, #lkey) elseif type(lkey) == 'number' then obj = C.tds_hash_search_number(self, lkey) else error('string or number key expected') end return obj end function hash:__newindex(lkey, lval) assert(self) local obj = findkey(self, lkey) if obj ~= nil then if lval then local val = C.tds_hash_object_value(obj) C.tds_elem_free_content(val) elem.set(val, lval) else C.tds_hash_remove(self, obj) C.tds_hash_object_free(obj) end else if lval then local obj = C.tds_hash_object_new() local key = C.tds_hash_object_key(obj) local val = C.tds_hash_object_value(obj) elem.set(val, lval) elem.set(key, lkey) C.tds_hash_insert(self, obj) end end end function hash:__index(lkey) assert(self) local obj = findkey(self, lkey) if obj ~= nil then local val = elem.get(C.tds_hash_object_value(obj)) return val end end function hash:__len() assert(self) return tonumber(C.tds_hash_size(self)) end function hash:__pairs() assert(self) local iterator = C.tds_hash_iterator_new(self) ffi.gc(iterator, C.tds_hash_iterator_free) return function() local obj = C.tds_hash_iterator_next(iterator) if obj ~= nil then local key = elem.get(C.tds_hash_object_key(obj)) local val = elem.get(C.tds_hash_object_value(obj)) return key, val end end end ffi.metatype('tds_hash', hash) if pcall(require, 'torch') and torch.metatype then function hash:__write(f) f:writeLong(#self) for k,v in pairs(self) do f:writeObject(k) f:writeObject(v) end end function hash:__read(f) local n = f:readLong() for i=1,n do local k = f:readObject() local v = f:readObject() self[k] = v end end hash.__factory = hash.__new hash.__version = 0 torch.metatype('tds_hash', hash, 'tds_hash&') end -- table constructor local hash_ctr = {} setmetatable( hash_ctr, { __index = hash, __newindex = hash, __call = hash.__new } ) tds.hash = hash_ctr return hash_ctr
hash: fixed issue of <pairs> (or other metatable members) seen as key values
hash: fixed issue of <pairs> (or other metatable members) seen as key values
Lua
bsd-3-clause
torch/tds,jakezhaojb/tds,Moodstocks/tds,jakezhaojb/tds,jakezhaojb/tds,jakezhaojb/tds
1a9fe9cd77e70674270101c9566efea6fd7c11bb
libs/web/luasrc/http.lua
libs/web/luasrc/http.lua
--[[ LuCI - HTTP-Interaction Description: HTTP-Header manipulator and form variable preprocessor FileId: $Id$ ToDo: - Cookie handling License: Copyright 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 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. ]]-- module("luci.http", package.seeall) require("ltn12") require("luci.http.protocol") require("luci.util") context = luci.util.threadlocal() Request = luci.util.class() function Request.__init__(self, env, sourcein, sinkerr) self.input = sourcein self.error = sinkerr -- File handler self.filehandler = function() end -- HTTP-Message table self.message = { env = env, headers = {}, params = luci.http.protocol.urldecode_params(env.QUERY_STRING or ""), } setmetatable(self.message.params, {__index = function(tbl, key) setmetatable(tbl, nil) luci.http.protocol.parse_message_body( self.input, self.message, self.filehandler ) return rawget(tbl, key) end }) end function Request.formvalue(self, name, default) if name then return self.message.params[name] and tostring(self.message.params[name]) or default else return self.message.params end end function Request.formvaluetable(self, prefix) local vals = {} prefix = prefix and prefix .. "." or "." local void = self.message.params[nil] for k, v in pairs(self.message.params) do if k:find(prefix, 1, true) == 1 then vals[k:sub(#prefix + 1)] = tostring(v) end end return vals end function Request.getenv(self, name) return name and self.message.env[name] or self.message.env end function Request.setfilehandler(self, callback) self.filehandler = callback end function close() if not context.eoh then context.eoh = true coroutine.yield(3) end if not context.closed then context.closed = true coroutine.yield(5) end end function formvalue(...) return context.request:formvalue(...) end function formvaluetable(...) return context.request:formvaluetable(...) end function getvalue(...) return context.request:getvalue(...) end function postvalue(...) return context.request:postvalue(...) end function getenv(...) return context.request:getenv(...) end function setfilehandler(...) return context.request:setfilehandler(...) end function header(key, value) if not context.status then status() end if not context.headers then context.headers = {} end context.headers[key:lower()] = value coroutine.yield(2, key, value) end function prepare_content(mime) header("Content-Type", mime) end function status(code, message) code = code or 200 message = message or "OK" context.status = code coroutine.yield(1, code, message) end function write(content) if not content or #content == 0 then return end if not context.eoh then if not context.status then status() end if not context.headers or not context.headers["content-type"] then header("Content-Type", "text/html; charset=utf-8") end context.eoh = true coroutine.yield(3) end coroutine.yield(4, content) end function basic_auth(realm, errorpage) header("Status", "401 Unauthorized") header("WWW-Authenticate", string.format('Basic realm="%s"', realm or "")) if errorpage then errorpage() end close() end function redirect(url) header("Status", "302 Found") header("Location", url) close() end function build_querystring(table) local s="?" for k, v in pairs(table) do s = s .. urlencode(k) .. "=" .. urlencode(v) .. "&" end return s end urldecode = luci.http.protocol.urldecode urlencode = luci.http.protocol.urlencode
--[[ LuCI - HTTP-Interaction Description: HTTP-Header manipulator and form variable preprocessor FileId: $Id$ ToDo: - Cookie handling License: Copyright 2008 Steven Barth <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 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. ]]-- module("luci.http", package.seeall) require("ltn12") require("luci.http.protocol") require("luci.util") context = luci.util.threadlocal() Request = luci.util.class() function Request.__init__(self, env, sourcein, sinkerr) self.input = sourcein self.error = sinkerr -- File handler self.filehandler = function() end -- HTTP-Message table self.message = { env = env, headers = {}, params = luci.http.protocol.urldecode_params(env.QUERY_STRING or ""), } setmetatable(self.message.params, {__index = function(tbl, key) setmetatable(tbl, nil) luci.http.protocol.parse_message_body( self.input, self.message, self.filehandler ) return rawget(tbl, key) end }) end function Request.formvalue(self, name, default) if name then return self.message.params[name] and tostring(self.message.params[name]) or default else return self.message.params end end function Request.formvaluetable(self, prefix) local vals = {} prefix = prefix and prefix .. "." or "." local void = self.message.params[nil] for k, v in pairs(self.message.params) do if k:find(prefix, 1, true) == 1 then vals[k:sub(#prefix + 1)] = tostring(v) end end return vals end function Request.getenv(self, name) if name then return self.message.env[name] else return self.message.env end end function Request.setfilehandler(self, callback) self.filehandler = callback end function close() if not context.eoh then context.eoh = true coroutine.yield(3) end if not context.closed then context.closed = true coroutine.yield(5) end end function formvalue(...) return context.request:formvalue(...) end function formvaluetable(...) return context.request:formvaluetable(...) end function getvalue(...) return context.request:getvalue(...) end function postvalue(...) return context.request:postvalue(...) end function getenv(...) return context.request:getenv(...) end function setfilehandler(...) return context.request:setfilehandler(...) end function header(key, value) if not context.status then status() end if not context.headers then context.headers = {} end context.headers[key:lower()] = value coroutine.yield(2, key, value) end function prepare_content(mime) header("Content-Type", mime) end function status(code, message) code = code or 200 message = message or "OK" context.status = code coroutine.yield(1, code, message) end function write(content) if not content or #content == 0 then return end if not context.eoh then if not context.status then status() end if not context.headers or not context.headers["content-type"] then header("Content-Type", "text/html; charset=utf-8") end context.eoh = true coroutine.yield(3) end coroutine.yield(4, content) end function basic_auth(realm, errorpage) header("Status", "401 Unauthorized") header("WWW-Authenticate", string.format('Basic realm="%s"', realm or "")) if errorpage then errorpage() end close() end function redirect(url) header("Status", "302 Found") header("Location", url) close() end function build_querystring(table) local s="?" for k, v in pairs(table) do s = s .. urlencode(k) .. "=" .. urlencode(v) .. "&" end return s end urldecode = luci.http.protocol.urldecode urlencode = luci.http.protocol.urlencode
libs/web: Fixed bug where the environment table gets returned in case of an undefined variable
libs/web: Fixed bug where the environment table gets returned in case of an undefined variable
Lua
apache-2.0
Noltari/luci,db260179/openwrt-bpi-r1-luci,RedSnake64/openwrt-luci-packages,remakeelectric/luci,981213/luci-1,palmettos/cnLuCI,fkooman/luci,thesabbir/luci,shangjiyu/luci-with-extra,male-puppies/luci,Wedmer/luci,rogerpueyo/luci,oneru/luci,jorgifumi/luci,oyido/luci,oneru/luci,urueedi/luci,openwrt/luci,Wedmer/luci,remakeelectric/luci,florian-shellfire/luci,forward619/luci,tcatm/luci,keyidadi/luci,palmettos/cnLuCI,RedSnake64/openwrt-luci-packages,joaofvieira/luci,nmav/luci,david-xiao/luci,RedSnake64/openwrt-luci-packages,NeoRaider/luci,ff94315/luci-1,ollie27/openwrt_luci,thess/OpenWrt-luci,chris5560/openwrt-luci,jchuang1977/luci-1,MinFu/luci,shangjiyu/luci-with-extra,oneru/luci,fkooman/luci,chris5560/openwrt-luci,dismantl/luci-0.12,ff94315/luci-1,hnyman/luci,fkooman/luci,rogerpueyo/luci,fkooman/luci,wongsyrone/luci-1,RedSnake64/openwrt-luci-packages,bright-things/ionic-luci,mumuqz/luci,keyidadi/luci,aa65535/luci,opentechinstitute/luci,rogerpueyo/luci,Noltari/luci,nwf/openwrt-luci,zhaoxx063/luci,MinFu/luci,harveyhu2012/luci,urueedi/luci,male-puppies/luci,zhaoxx063/luci,cshore/luci,NeoRaider/luci,LuttyYang/luci,hnyman/luci,RuiChen1113/luci,nwf/openwrt-luci,oneru/luci,obsy/luci,remakeelectric/luci,deepak78/new-luci,obsy/luci,MinFu/luci,chris5560/openwrt-luci,openwrt-es/openwrt-luci,oyido/luci,taiha/luci,palmettos/test,Wedmer/luci,openwrt-es/openwrt-luci,db260179/openwrt-bpi-r1-luci,remakeelectric/luci,palmettos/cnLuCI,sujeet14108/luci,schidler/ionic-luci,tcatm/luci,Hostle/openwrt-luci-multi-user,jchuang1977/luci-1,fkooman/luci,Hostle/openwrt-luci-multi-user,NeoRaider/luci,david-xiao/luci,rogerpueyo/luci,ReclaimYourPrivacy/cloak-luci,NeoRaider/luci,tcatm/luci,lbthomsen/openwrt-luci,zhaoxx063/luci,aircross/OpenWrt-Firefly-LuCI,oyido/luci,hnyman/luci,tcatm/luci,tobiaswaldvogel/luci,Noltari/luci,kuoruan/luci,ReclaimYourPrivacy/cloak-luci,cshore-firmware/openwrt-luci,dismantl/luci-0.12,bright-things/ionic-luci,palmettos/test,cshore/luci,Kyklas/luci-proto-hso,Hostle/luci,ReclaimYourPrivacy/cloak-luci,Sakura-Winkey/LuCI,marcel-sch/luci,hnyman/luci,shangjiyu/luci-with-extra,maxrio/luci981213,palmettos/test,RedSnake64/openwrt-luci-packages,cshore-firmware/openwrt-luci,oyido/luci,jchuang1977/luci-1,schidler/ionic-luci,Noltari/luci,opentechinstitute/luci,LuttyYang/luci,Hostle/luci,NeoRaider/luci,chris5560/openwrt-luci,slayerrensky/luci,nmav/luci,cappiewu/luci,ollie27/openwrt_luci,fkooman/luci,forward619/luci,marcel-sch/luci,forward619/luci,RuiChen1113/luci,jlopenwrtluci/luci,jorgifumi/luci,kuoruan/luci,cshore-firmware/openwrt-luci,sujeet14108/luci,artynet/luci,jlopenwrtluci/luci,zhaoxx063/luci,tobiaswaldvogel/luci,openwrt-es/openwrt-luci,slayerrensky/luci,mumuqz/luci,nwf/openwrt-luci,joaofvieira/luci,bittorf/luci,ollie27/openwrt_luci,bittorf/luci,RuiChen1113/luci,opentechinstitute/luci,jchuang1977/luci-1,daofeng2015/luci,cshore-firmware/openwrt-luci,maxrio/luci981213,schidler/ionic-luci,LazyZhu/openwrt-luci-trunk-mod,981213/luci-1,nmav/luci,Kyklas/luci-proto-hso,kuoruan/lede-luci,taiha/luci,opentechinstitute/luci,artynet/luci,db260179/openwrt-bpi-r1-luci,dismantl/luci-0.12,shangjiyu/luci-with-extra,Sakura-Winkey/LuCI,kuoruan/lede-luci,bittorf/luci,Hostle/luci,david-xiao/luci,thess/OpenWrt-luci,bright-things/ionic-luci,teslamint/luci,MinFu/luci,RuiChen1113/luci,taiha/luci,jorgifumi/luci,opentechinstitute/luci,kuoruan/luci,harveyhu2012/luci,bright-things/ionic-luci,aircross/OpenWrt-Firefly-LuCI,remakeelectric/luci,aa65535/luci,slayerrensky/luci,cshore/luci,wongsyrone/luci-1,artynet/luci,joaofvieira/luci,NeoRaider/luci,tobiaswaldvogel/luci,jchuang1977/luci-1,lcf258/openwrtcn,981213/luci-1,cshore/luci,mumuqz/luci,male-puppies/luci,bright-things/ionic-luci,kuoruan/luci,lcf258/openwrtcn,openwrt/luci,tobiaswaldvogel/luci,LazyZhu/openwrt-luci-trunk-mod,ReclaimYourPrivacy/cloak-luci,deepak78/new-luci,ff94315/luci-1,urueedi/luci,nwf/openwrt-luci,sujeet14108/luci,RuiChen1113/luci,jlopenwrtluci/luci,MinFu/luci,thesabbir/luci,palmettos/test,oyido/luci,sujeet14108/luci,zhaoxx063/luci,maxrio/luci981213,kuoruan/lede-luci,dismantl/luci-0.12,urueedi/luci,Hostle/luci,male-puppies/luci,urueedi/luci,cshore-firmware/openwrt-luci,sujeet14108/luci,deepak78/new-luci,daofeng2015/luci,bittorf/luci,cappiewu/luci,wongsyrone/luci-1,db260179/openwrt-bpi-r1-luci,artynet/luci,keyidadi/luci,aa65535/luci,chris5560/openwrt-luci,Hostle/openwrt-luci-multi-user,oyido/luci,keyidadi/luci,maxrio/luci981213,nwf/openwrt-luci,lbthomsen/openwrt-luci,joaofvieira/luci,openwrt/luci,aircross/OpenWrt-Firefly-LuCI,openwrt-es/openwrt-luci,teslamint/luci,maxrio/luci981213,wongsyrone/luci-1,Hostle/luci,mumuqz/luci,Kyklas/luci-proto-hso,remakeelectric/luci,cshore-firmware/openwrt-luci,shangjiyu/luci-with-extra,teslamint/luci,oneru/luci,teslamint/luci,joaofvieira/luci,mumuqz/luci,thess/OpenWrt-luci,mumuqz/luci,nwf/openwrt-luci,Kyklas/luci-proto-hso,LuttyYang/luci,Kyklas/luci-proto-hso,obsy/luci,aircross/OpenWrt-Firefly-LuCI,keyidadi/luci,Wedmer/luci,obsy/luci,LazyZhu/openwrt-luci-trunk-mod,palmettos/cnLuCI,jorgifumi/luci,nmav/luci,male-puppies/luci,Sakura-Winkey/LuCI,lbthomsen/openwrt-luci,lcf258/openwrtcn,Hostle/openwrt-luci-multi-user,lcf258/openwrtcn,Sakura-Winkey/LuCI,joaofvieira/luci,chris5560/openwrt-luci,openwrt/luci,teslamint/luci,Kyklas/luci-proto-hso,taiha/luci,opentechinstitute/luci,Noltari/luci,thess/OpenWrt-luci,jlopenwrtluci/luci,ollie27/openwrt_luci,aa65535/luci,db260179/openwrt-bpi-r1-luci,zhaoxx063/luci,dwmw2/luci,david-xiao/luci,male-puppies/luci,palmettos/test,obsy/luci,thesabbir/luci,Sakura-Winkey/LuCI,oneru/luci,thess/OpenWrt-luci,marcel-sch/luci,openwrt/luci,chris5560/openwrt-luci,ff94315/luci-1,rogerpueyo/luci,deepak78/new-luci,taiha/luci,lbthomsen/openwrt-luci,teslamint/luci,artynet/luci,jlopenwrtluci/luci,aa65535/luci,Hostle/luci,shangjiyu/luci-with-extra,harveyhu2012/luci,MinFu/luci,LazyZhu/openwrt-luci-trunk-mod,nmav/luci,ff94315/luci-1,lbthomsen/openwrt-luci,bittorf/luci,thesabbir/luci,florian-shellfire/luci,schidler/ionic-luci,deepak78/new-luci,wongsyrone/luci-1,bright-things/ionic-luci,slayerrensky/luci,NeoRaider/luci,daofeng2015/luci,ollie27/openwrt_luci,david-xiao/luci,ollie27/openwrt_luci,openwrt-es/openwrt-luci,artynet/luci,oneru/luci,taiha/luci,wongsyrone/luci-1,sujeet14108/luci,cshore/luci,ReclaimYourPrivacy/cloak-luci,tobiaswaldvogel/luci,harveyhu2012/luci,artynet/luci,openwrt/luci,Noltari/luci,artynet/luci,jlopenwrtluci/luci,schidler/ionic-luci,nwf/openwrt-luci,jorgifumi/luci,dwmw2/luci,RedSnake64/openwrt-luci-packages,jlopenwrtluci/luci,hnyman/luci,nmav/luci,schidler/ionic-luci,Hostle/luci,Hostle/openwrt-luci-multi-user,florian-shellfire/luci,dwmw2/luci,ReclaimYourPrivacy/cloak-luci,david-xiao/luci,male-puppies/luci,artynet/luci,LuttyYang/luci,nwf/openwrt-luci,db260179/openwrt-bpi-r1-luci,thess/OpenWrt-luci,Kyklas/luci-proto-hso,nmav/luci,openwrt-es/openwrt-luci,tcatm/luci,cappiewu/luci,forward619/luci,Wedmer/luci,aa65535/luci,kuoruan/lede-luci,lcf258/openwrtcn,slayerrensky/luci,taiha/luci,bittorf/luci,jchuang1977/luci-1,thesabbir/luci,thess/OpenWrt-luci,Hostle/openwrt-luci-multi-user,thesabbir/luci,openwrt-es/openwrt-luci,forward619/luci,urueedi/luci,obsy/luci,teslamint/luci,Noltari/luci,lcf258/openwrtcn,palmettos/cnLuCI,daofeng2015/luci,deepak78/new-luci,daofeng2015/luci,tobiaswaldvogel/luci,jorgifumi/luci,sujeet14108/luci,thesabbir/luci,kuoruan/luci,forward619/luci,florian-shellfire/luci,slayerrensky/luci,oneru/luci,kuoruan/lede-luci,bright-things/ionic-luci,nmav/luci,urueedi/luci,RuiChen1113/luci,openwrt/luci,kuoruan/lede-luci,hnyman/luci,hnyman/luci,florian-shellfire/luci,dwmw2/luci,mumuqz/luci,schidler/ionic-luci,daofeng2015/luci,palmettos/test,Hostle/openwrt-luci-multi-user,Wedmer/luci,aa65535/luci,RuiChen1113/luci,aircross/OpenWrt-Firefly-LuCI,marcel-sch/luci,jlopenwrtluci/luci,ff94315/luci-1,sujeet14108/luci,maxrio/luci981213,dwmw2/luci,marcel-sch/luci,jorgifumi/luci,Sakura-Winkey/LuCI,cshore-firmware/openwrt-luci,lbthomsen/openwrt-luci,keyidadi/luci,LuttyYang/luci,dismantl/luci-0.12,LuttyYang/luci,kuoruan/lede-luci,tcatm/luci,tobiaswaldvogel/luci,urueedi/luci,lbthomsen/openwrt-luci,ff94315/luci-1,LazyZhu/openwrt-luci-trunk-mod,lcf258/openwrtcn,palmettos/cnLuCI,maxrio/luci981213,kuoruan/luci,male-puppies/luci,cappiewu/luci,harveyhu2012/luci,lbthomsen/openwrt-luci,NeoRaider/luci,tcatm/luci,981213/luci-1,dwmw2/luci,dismantl/luci-0.12,cshore/luci,Wedmer/luci,cshore/luci,thess/OpenWrt-luci,shangjiyu/luci-with-extra,taiha/luci,marcel-sch/luci,LuttyYang/luci,Wedmer/luci,zhaoxx063/luci,florian-shellfire/luci,jorgifumi/luci,981213/luci-1,MinFu/luci,wongsyrone/luci-1,MinFu/luci,slayerrensky/luci,palmettos/cnLuCI,deepak78/new-luci,Sakura-Winkey/LuCI,opentechinstitute/luci,kuoruan/luci,LuttyYang/luci,aa65535/luci,aircross/OpenWrt-Firefly-LuCI,shangjiyu/luci-with-extra,rogerpueyo/luci,daofeng2015/luci,deepak78/new-luci,cappiewu/luci,teslamint/luci,zhaoxx063/luci,981213/luci-1,hnyman/luci,Hostle/openwrt-luci-multi-user,LazyZhu/openwrt-luci-trunk-mod,Noltari/luci,harveyhu2012/luci,forward619/luci,schidler/ionic-luci,dwmw2/luci,lcf258/openwrtcn,wongsyrone/luci-1,joaofvieira/luci,kuoruan/lede-luci,obsy/luci,palmettos/cnLuCI,LazyZhu/openwrt-luci-trunk-mod,florian-shellfire/luci,openwrt-es/openwrt-luci,ollie27/openwrt_luci,marcel-sch/luci,db260179/openwrt-bpi-r1-luci,tcatm/luci,rogerpueyo/luci,cshore/luci,fkooman/luci,mumuqz/luci,harveyhu2012/luci,aircross/OpenWrt-Firefly-LuCI,maxrio/luci981213,ollie27/openwrt_luci,cappiewu/luci,remakeelectric/luci,remakeelectric/luci,bittorf/luci,ff94315/luci-1,jchuang1977/luci-1,palmettos/test,RuiChen1113/luci,slayerrensky/luci,chris5560/openwrt-luci,lcf258/openwrtcn,jchuang1977/luci-1,bright-things/ionic-luci,thesabbir/luci,oyido/luci,Sakura-Winkey/LuCI,981213/luci-1,fkooman/luci,lcf258/openwrtcn,palmettos/test,daofeng2015/luci,dismantl/luci-0.12,florian-shellfire/luci,keyidadi/luci,tobiaswaldvogel/luci,openwrt/luci,nmav/luci,joaofvieira/luci,ReclaimYourPrivacy/cloak-luci,rogerpueyo/luci,forward619/luci,Hostle/luci,keyidadi/luci,oyido/luci,ReclaimYourPrivacy/cloak-luci,LazyZhu/openwrt-luci-trunk-mod,RedSnake64/openwrt-luci-packages,marcel-sch/luci,dwmw2/luci,cappiewu/luci,cappiewu/luci,cshore-firmware/openwrt-luci,opentechinstitute/luci,obsy/luci,Noltari/luci,david-xiao/luci,db260179/openwrt-bpi-r1-luci,kuoruan/luci,bittorf/luci,david-xiao/luci
ab3b4404048aee45c5175ffd7be8a64a9ec6a167
boss.lua
boss.lua
local mod = EPGP:NewModule("boss", "AceEvent-3.0", "AceTimer-3.0") local Debug = LibStub("LibDebug-1.0") local L = LibStub("AceLocale-3.0"):GetLocale("EPGP") local BOSSES = { -- The Obsidian Sanctum [28860] = "Sartharion", -- Eye of Eternity [28859] = "Malygos", -- Naxxramas [15956] = "Anub'Rekhan", [15953] = "Grand Widow Faerlina", [15952] = "Maexxna", [16028] = "Patchwerk", [15931] = "Grobbulus", [15932] = "Gluth", [15928] = "Thaddius", [16061] = "Instructor Razuvious", [16060] = "Gothik the Harvester", -- TODO(alkis): Add Four Horsemen [15954] = "Noth the Plaguebringer", [15936] = "Heigan the Unclean", [16011] = "Loatheb", [15989] = "Sapphiron", [15990] = "Kel'Thuzad", -- Vault of Archavon [31125] = "Archavon the Stone Watcher", } local function IsRLorML() if UnitInRaid("player") then local loot_method, ml_party_id, ml_raid_id = GetLootMethod() if loot_method == "master" and ml_party_id == 0 then return true end if loot_method ~= "master" and IsRaidLeader() then return true end end return false end function mod:COMBAT_LOG_EVENT_UNFILTERED(event_name, timestamp, event, source, source_name, source_flags, dest, dest_name, dest_flags, ...) -- bitlib does not support 64 bit integers so we are going to do some -- string hacking to get what we want. For an NPC: -- guid & 0x00F0000000000000 == 3 -- and the NPC id is: -- (guid & 0x0000FFFFFF000000) >> 24 if event == "UNIT_DIED" and dest:sub(5, 5) == "3" then local npc_id = tonumber(string.sub(dest, -12, -7), 16) if BOSSES[npc_id] then self:SendMessage("BossKilled", dest_name) end end end local in_combat = false local award_queue = {} local timer local function IsRLorML() if UnitInRaid("player") then local loot_method, ml_party_id, ml_raid_id = GetLootMethod() if loot_method == "master" and ml_party_id == 0 then return true end if loot_method ~= "master" and IsRaidLeader() then return true end end return false end function mod:PopAwardQueue() if in_combat then return end if #award_queue == 0 then if timer then self:CancelTimer(timer, true) timer = nil end return end if StaticPopup_Visible("EPGP_BOSS_DEAD") then return end local boss_name = table.remove(award_queue, 1) local dialog = StaticPopup_Show("EPGP_BOSS_DEAD", boss_name) if dialog then dialog.reason = boss_name end end local function BossKilled(event_name, boss_name) Debug("Boss killed: %s", boss_name) -- Temporary fix since we cannot unregister DBM callbacks if not mod:IsEnabled() then return end if CanEditOfficerNote() and IsRLorML() then tinsert(award_queue, boss_name) if not timer then timer = mod:ScheduleRepeatingTimer("PopAwardQueue", 1) end end end function mod:PLAYER_REGEN_DISABLED() in_combat = true end function mod:PLAYER_REGEN_ENABLED() in_combat = false end function mod:DebugTest() BossKilled("BossKilled", "Sapphiron") end mod.dbDefaults = { profile = { enabled = false, }, } mod.optionsName = L["Boss"] mod.optionsDesc = L["Automatic boss tracking"] mod.optionsArgs = { help = { order = 1, type = "description", name = L["Automatic boss tracking by means of a popup to mass award EP to the raid and standby when a boss is killed."] }, } function mod:OnEnable() self:RegisterEvent("PLAYER_REGEN_DISABLED") self:RegisterEvent("PLAYER_REGEN_ENABLED") if DBM then EPGP:Print(L["Using DBM for boss kill tracking"]) DBM:RegisterCallback("kill", function (mod) BossKilled("kill", mod.combatInfo.name) end) else self:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED") self:RegisterMessage("BossKilled", BossKilled) end end
local mod = EPGP:NewModule("boss", "AceEvent-3.0", "AceTimer-3.0") local Debug = LibStub("LibDebug-1.0") local L = LibStub("AceLocale-3.0"):GetLocale("EPGP") local BOSSES = { -- The Obsidian Sanctum [28860] = "Sartharion", -- Eye of Eternity [28859] = "Malygos", -- Naxxramas [15956] = "Anub'Rekhan", [15953] = "Grand Widow Faerlina", [15952] = "Maexxna", [16028] = "Patchwerk", [15931] = "Grobbulus", [15932] = "Gluth", [15928] = "Thaddius", [16061] = "Instructor Razuvious", [16060] = "Gothik the Harvester", -- TODO(alkis): Add Four Horsemen [15954] = "Noth the Plaguebringer", [15936] = "Heigan the Unclean", [16011] = "Loatheb", [15989] = "Sapphiron", [15990] = "Kel'Thuzad", -- Vault of Archavon [31125] = "Archavon the Stone Watcher", [33993] = "Emalon the Storm Watcher", -- Ulduar [33113] = "Flame Leviathan", [33118] = "Ignis the Furnace Master", [33186] = "Razorscale", [33293] = "XT-002 Deconstructor", -- TODO(alkis): Add Assembly of Iron [32930] = "Kologarn", [33515] = "Auriaya", [33412] = "Mimiron", [32845] = "Hodir", [32865] = "Thorim", [32906] = "Freya", [33271] = "General Vezax", [33288] = "Yogg-Saron", -- TODO(alkis): Add Algalon the Observer } local function IsRLorML() if UnitInRaid("player") then local loot_method, ml_party_id, ml_raid_id = GetLootMethod() if loot_method == "master" and ml_party_id == 0 then return true end if loot_method ~= "master" and IsRaidLeader() then return true end end return false end function mod:COMBAT_LOG_EVENT_UNFILTERED(event_name, timestamp, event, source, source_name, source_flags, dest, dest_name, dest_flags, ...) -- bitlib does not support 64 bit integers so we are going to do some -- string hacking to get what we want. For an NPC: -- guid & 0x00F0000000000000 == 3 -- and the NPC id is: -- (guid & 0x0000FFFFFF000000) >> 24 if event == "UNIT_DIED" and dest:sub(5, 5) == "3" then local npc_id = tonumber(string.sub(dest, -12, -7), 16) if BOSSES[npc_id] then self:SendMessage("BossKilled", dest_name) end end end local in_combat = false local award_queue = {} local timer local function IsRLorML() if UnitInRaid("player") then local loot_method, ml_party_id, ml_raid_id = GetLootMethod() if loot_method == "master" and ml_party_id == 0 then return true end if loot_method ~= "master" and IsRaidLeader() then return true end end return false end function mod:PopAwardQueue() if in_combat then return end if #award_queue == 0 then if timer then self:CancelTimer(timer, true) timer = nil end return end if StaticPopup_Visible("EPGP_BOSS_DEAD") then return end local boss_name = table.remove(award_queue, 1) local dialog = StaticPopup_Show("EPGP_BOSS_DEAD", boss_name) if dialog then dialog.reason = boss_name end end local function BossKilled(event_name, boss_name) Debug("Boss killed: %s", boss_name) -- Temporary fix since we cannot unregister DBM callbacks if not mod:IsEnabled() then return end if CanEditOfficerNote() and IsRLorML() then tinsert(award_queue, boss_name) if not timer then timer = mod:ScheduleRepeatingTimer("PopAwardQueue", 1) end end end function mod:PLAYER_REGEN_DISABLED() in_combat = true end function mod:PLAYER_REGEN_ENABLED() in_combat = false end function mod:DebugTest() BossKilled("BossKilled", "Sapphiron") end mod.dbDefaults = { profile = { enabled = false, }, } mod.optionsName = L["Boss"] mod.optionsDesc = L["Automatic boss tracking"] mod.optionsArgs = { help = { order = 1, type = "description", name = L["Automatic boss tracking by means of a popup to mass award EP to the raid and standby when a boss is killed."] }, } function mod:OnEnable() self:RegisterEvent("PLAYER_REGEN_DISABLED") self:RegisterEvent("PLAYER_REGEN_ENABLED") if DBM then EPGP:Print(L["Using DBM for boss kill tracking"]) DBM:RegisterCallback("kill", function (mod) BossKilled("kill", mod.combatInfo.name) end) else self:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED") self:RegisterMessage("BossKilled", BossKilled) end end
Add Ulduar bosses and new Vault of Archavon boss. This fixes issue 408.
Add Ulduar bosses and new Vault of Archavon boss. This fixes issue 408.
Lua
bsd-3-clause
ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,ceason/epgp-tfatf,sheldon/epgp,protomech/epgp-dkp-reloaded,hayword/tfatf_epgp,sheldon/epgp,hayword/tfatf_epgp
a4d515aea8df2c3d9eef11e75d7588f8140bcbc7
LibGuildStorage-1.0.lua
LibGuildStorage-1.0.lua
-- This library handles storing information in officer notes. It -- streamlines and optimizes access to these notes. The API is as -- follows: -- -- GetNote(name): Returns the officer note of member 'name' -- -- SetNote(name, note): Sets the officer note of member 'name' to -- 'note' -- -- GetGuildInfo(): Returns the guild info text -- -- -- The library also fires the following messages, which you can -- register for through RegisterCallback and unregister through -- UnregisterCallback. You can also unregister all messages through -- UnregisterAllCallbacks. -- -- GuildInfoChanged(info): Fired when guild info has changed since its -- previous state. The info is the new guild info. -- -- GuildNoteChanged(name, note): Fired when a guild note changes. The -- name is the name of the member of which the note changed and the -- note is the new note. local MAJOR_VERSION = "LibGuildStorage-1.0" local MINOR_VERSION = tonumber(("$Revision$"):match("%d+")) or 0 local lib, oldMinor = LibStub:NewLibrary(MAJOR_VERSION, MINOR_VERSION) if not lib then return end local function debug(...) ChatFrame1:AddMessage(table.concat({...}, "")) end local CallbackHandler = LibStub:GetLibrary("CallbackHandler-1.0") if not lib.callbacks then lib.callbacks = CallbackHandler:New(lib) end local callbacks = lib.callbacks if lib.frame then lib.frame:UnregisterAllEvents() lib.frame:SetScript("OnEvent", nil) lib.frame:SetScript("OnUpdate", nil) else lib.frame = CreateFrame("Frame", MAJOR_VERSION .. "_Frame") end local frame = lib.frame frame:SetScript("OnEvent", function(this, event, ...) lib[event](lib, ...) end) -- Cache is indexed by name and a table with index, class and note local cache = {} local guild_info = "" local next_index = 1 local function UpdateGuildRoster() debug("Calling UpdateGuildRoster next_index=", next_index, " #members=", GetNumGuildMembers(true)) if next_index == 1 then local new_guild_info = GetGuildInfoText() or "" if new_guild_info ~= guild_info then guild_info = new_guild_info callbacks:Fire("GuildInfoChanged", guild_info) end end -- Read up to 100 members at a time. local e = math.min(next_index + 99, GetNumGuildMembers(true)) for i = next_index, e do local name, _, _, _, _, _, _, note, _, _, class = GetGuildRosterInfo(i) local t = cache[name] if not t then t = {} cache[name] = t end t.index = i t.class = class if t.note ~= note then t.note = note debug("name=", name, " note=", note) callbacks:Fire("GuildNoteChanged", name, note) end end next_index = e + 1 if next_index > GetNumGuildMembers(true) then frame:Hide() end end frame:SetScript("OnUpdate", UpdateGuildRoster) frame:RegisterEvent("PLAYER_GUILD_UPDATE") frame:RegisterEvent("GUILD_ROSTER_UPDATE") function lib:PLAYER_GUILD_UPDATE(unit) debug("Got PLAYER_GUILD_UPDATE unit=", unit) -- Hide the frame to stop OnUpdate from reading guild information if frame:IsShown() then frame:Hide() end GuildRoster() end function lib:GUILD_ROSTER_UPDATE(loc) if loc then GuildRoster() return end -- Show the frame to make the OnUpdate handler to be called debug("Got GUILD_ROSTER_UPDATE") next_index = 1 frame:Show() end function lib:GetNote(name) local entry = cache[name] if not entry then return nil end return entry.note end function lib:SetNote(name, note) local entry = cache[name] if not entry then return end -- We do not update the note here. We are going to wait until the -- next GUILD_ROSTER_UPDATE and fire a GuildNoteChanged callback. debug("Setting officer note for ", name, "(", entry.index, ") to ", note) -- TODO(alkis): Investigate performance issues in case we want to -- verify if this is the right index or not. GuildRosterSetOfficerNote(entry.index, note) end function lib:GetGuildInfo() return guild_info end GuildRoster() frame:Hide()
-- This library handles storing information in officer notes. It -- streamlines and optimizes access to these notes. The API is as -- follows: -- -- GetNote(name): Returns the officer note of member 'name' -- -- SetNote(name, note): Sets the officer note of member 'name' to -- 'note' -- -- GetGuildInfo(): Returns the guild info text -- -- -- The library also fires the following messages, which you can -- register for through RegisterCallback and unregister through -- UnregisterCallback. You can also unregister all messages through -- UnregisterAllCallbacks. -- -- GuildInfoChanged(info): Fired when guild info has changed since its -- previous state. The info is the new guild info. -- -- GuildNoteChanged(name, note): Fired when a guild note changes. The -- name is the name of the member of which the note changed and the -- note is the new note. local MAJOR_VERSION = "LibGuildStorage-1.0" local MINOR_VERSION = tonumber(("$Revision$"):match("%d+")) or 0 local lib, oldMinor = LibStub:NewLibrary(MAJOR_VERSION, MINOR_VERSION) if not lib then return end local function debug(...) ChatFrame1:AddMessage(table.concat({...}, "")) end local CallbackHandler = LibStub:GetLibrary("CallbackHandler-1.0") if not lib.callbacks then lib.callbacks = CallbackHandler:New(lib) end local callbacks = lib.callbacks if lib.frame then lib.frame:UnregisterAllEvents() lib.frame:SetScript("OnEvent", nil) lib.frame:SetScript("OnUpdate", nil) else lib.frame = CreateFrame("Frame", MAJOR_VERSION .. "_Frame") end local frame = lib.frame frame:SetScript("OnEvent", function(this, event, ...) lib[event](lib, ...) end) -- Cache is indexed by name and a table with index, class and note local cache = {} local guild_info = "" local next_index = 1 local function UpdateGuildRoster() debug("Calling UpdateGuildRoster next_index=", next_index, " #members=", GetNumGuildMembers(true)) if next_index == 1 then local new_guild_info = GetGuildInfoText() or "" if new_guild_info ~= guild_info then guild_info = new_guild_info callbacks:Fire("GuildInfoChanged", guild_info) end end -- Read up to 100 members at a time. local e = math.min(next_index + 99, GetNumGuildMembers(true)) for i = next_index, e do local name, _, _, _, _, _, _, note, _, _, class = GetGuildRosterInfo(i) local t = cache[name] if not t then t = {} cache[name] = t end t.index = i t.class = class if t.note ~= note then t.note = note debug("name=", name, " note=", note) callbacks:Fire("GuildNoteChanged", name, note) end end next_index = e + 1 if next_index > GetNumGuildMembers(true) then frame:Hide() end end frame:SetScript("OnUpdate", UpdateGuildRoster) frame:RegisterEvent("PLAYER_GUILD_UPDATE") frame:RegisterEvent("GUILD_ROSTER_UPDATE") function lib:PLAYER_GUILD_UPDATE() debug("Got PLAYER_GUILD_UPDATE") -- Hide the frame to stop OnUpdate from reading guild information if frame:IsShown() and not IsInGuild() then frame:Hide() end GuildRoster() end function lib:GUILD_ROSTER_UPDATE(loc) if loc then GuildRoster() return end -- Show the frame to make the OnUpdate handler to be called debug("Got GUILD_ROSTER_UPDATE") next_index = 1 frame:Show() end function lib:GetNote(name) local entry = cache[name] if not entry then return nil end return entry.note end function lib:SetNote(name, note) local entry = cache[name] if not entry then return end -- We do not update the note here. We are going to wait until the -- next GUILD_ROSTER_UPDATE and fire a GuildNoteChanged callback. debug("Setting officer note for ", name, "(", entry.index, ") to ", note) -- TODO(alkis): Investigate performance issues in case we want to -- verify if this is the right index or not. GuildRosterSetOfficerNote(entry.index, note) end function lib:GetGuildInfo() return guild_info end GuildRoster() frame:Hide()
Small bug fix for PLAYER_GUILD_UPDATE event. We do not want to stop updating the cache when we get this event unless we left the guild.
Small bug fix for PLAYER_GUILD_UPDATE event. We do not want to stop updating the cache when we get this event unless we left the guild.
Lua
bsd-3-clause
protomech/epgp-dkp-reloaded,hayword/tfatf_epgp,sheldon/epgp,ceason/epgp-tfatf,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded,hayword/tfatf_epgp,sheldon/epgp
faec0ac3165fcf6d59586dcf7d166606acaaf247
nyagos.d/suffix.lua
nyagos.d/suffix.lua
share._suffixes={} share._setsuffix = function(suffix,cmdline) local suffix=string.lower(suffix) if string.sub(suffix,1,1)=='.' then suffix = string.sub(suffix,2) end if not share._suffixes[suffix] then local orgpathext = nyagos.getenv("PATHEXT") local newext="."..suffix if not string.find(";"..orgpathext..";",";"..newext..";",1,true) then nyagos.setenv("PATHEXT",orgpathext..";"..newext) end end local table = share._suffixes table[suffix]=cmdline share._suffixes = table end suffix = setmetatable({},{ __call = function(t,k,v) share._setsuffix(k,v) return end, __newindex = function(t,k,v) share._setsuffix(k,v) return end, __index = function(t,k) return share._suffixes[k] end }) share._org_suffix_argsfilter=nyagos.argsfilter nyagos.argsfilter = function(args) if share._org_suffix_argsfilter then local args_ = share._org_suffix_argsfilter(args) if args_ then args = args_ end end local path=nyagos.which(args[0]) if not path then return end local m = string.match(path,"%.(%w+)$") if not m then return end local cmdline = share._suffixes[ string.lower(m) ] if not cmdline then return end local newargs={} if type(cmdline) == 'table' then for i=1,#cmdline do newargs[i-1]=cmdline[i] end elseif type(cmdline) == 'string' then newargs[0] = cmdline end newargs[#newargs+1] = path for i=1,#args do newargs[#newargs+1] = args[i] end return newargs end nyagos.alias.suffix = function(args) if #args < 2 then print "Usage: suffix SUFFIX COMMAND" else local cmdline={} for i=2,#args do cmdline[#cmdline+1]=args[i] end suffix(args[1],cmdline) end end suffix.pl="perl" if nyagos.which("ipy") then suffix.py="ipy" elseif nyagos.which("py") then suffix.py="py" else suffix.py="python" end suffix.rb="ruby" suffix.lua="lua" suffix.awk={"awk","-f"} suffix.js={"cscript","//nologo"} suffix.vbs={"cscript","//nologo"} suffix.ps1={"powershell","-file"}
share._suffixes={} share._setsuffix = function(suffix,cmdline) local suffix=string.lower(suffix) if string.sub(suffix,1,1)=='.' then suffix = string.sub(suffix,2) end if not share._suffixes[suffix] then local orgpathext = nyagos.getenv("PATHEXT") local newext="."..suffix if not string.find(";"..orgpathext..";",";"..newext..";",1,true) then nyagos.setenv("PATHEXT",orgpathext..";"..newext) end end local table = share._suffixes table[suffix]=cmdline share._suffixes = table end suffix = setmetatable({},{ __call = function(t,k,v) share._setsuffix(k,v) return end, __newindex = function(t,k,v) share._setsuffix(k,v) return end, __index = function(t,k) return share._suffixes[k] end }) share._org_suffix_argsfilter=nyagos.argsfilter nyagos.argsfilter = function(args) if share._org_suffix_argsfilter then local args_ = share._org_suffix_argsfilter(args) if args_ then args = args_ end end local path=nyagos.which(args[0]) if not path then return end local m = string.match(path,"%.(%w+)$") if not m then return end local cmdline = share._suffixes[ string.lower(m) ] if not cmdline then return end local newargs={} if type(cmdline) == 'table' then for i=1,#cmdline do newargs[i-1]=cmdline[i] end elseif type(cmdline) == 'string' then newargs[0] = cmdline end newargs[#newargs+1] = path for i=1,#args do newargs[#newargs+1] = args[i] end return newargs end nyagos.alias.suffix = function(args) if #args < 2 then print "Usage: suffix SUFFIX COMMAND" else local cmdline={} for i=2,#args do cmdline[#cmdline+1]=args[i] end suffix(args[1],cmdline) end end suffix.pl="perl" if nyagos.which("ipy") then suffix.py="ipy" elseif nyagos.which("py") then suffix.py="py" else suffix.py="python" end suffix.rb="ruby" suffix.lua="lua" suffix.awk={"awk","-f"} suffix.js={"cscript","//nologo"} suffix.vbs={"cscript","//nologo"} suffix.wsf={"cscript","//nologo"} suffix.ps1={"powershell","-file"}
suffix.lua supports .wsf
suffix.lua supports .wsf
Lua
bsd-3-clause
hattya/nyagos,hattya/nyagos,tyochiai/nyagos,tsuyoshicho/nyagos,nocd5/nyagos,hattya/nyagos,zetamatta/nyagos
d3cee5b5fec48a8261c2811e41a7f3d41a71fec1
test/unit/worksheet/test_write_dimension.lua
test/unit/worksheet/test_write_dimension.lua
---- -- Tests for the xlsxwriter.lua worksheet class. -- -- Copyright 2014, John McNamara, [email protected] -- require "Test.More" plan(10) ---- -- Tests setup. -- local expected local got local caption local Worksheet = require "xlsxwriter.worksheet" local worksheet local cell_ref ---- -- 1. Test the _write_dimension() method with no dimensions set. -- caption = " \tWorksheet: _write_dimension()" expected = '<dimension ref="A1"/>' worksheet = Worksheet:new() worksheet:_set_filehandle(io.tmpfile()) worksheet:_write_dimension() got = worksheet:_get_data() is(got, expected, caption) ---- -- 2. Test the _write_dimension() method with dimensions set. -- cell_ref = 'A1' caption = string.format(" \tWorksheet: _write_dimension('%s')", cell_ref) expected = string.format('<dimension ref="%s"/>', cell_ref) worksheet = Worksheet:new() worksheet:_set_filehandle(io.tmpfile()) worksheet:write(cell_ref, 'some string') worksheet:_write_dimension() got = worksheet:_get_data() is(got, expected, caption) ---- -- 3. Test the _write_dimension() method with dimensions set. -- cell_ref = 'A1048576' caption = string.format(" \tWorksheet: _write_dimension('%s')", cell_ref) expected = string.format('<dimension ref="%s"/>', cell_ref) worksheet = Worksheet:new() worksheet:_set_filehandle(io.tmpfile()) worksheet:write(cell_ref, 'some string') worksheet:_write_dimension() got = worksheet:_get_data() is(got, expected, caption) ---- -- 4. Test the _write_dimension() method with dimensions set. -- cell_ref = 'XFD1' caption = string.format(" \tWorksheet: _write_dimension('%s')", cell_ref) expected = string.format('<dimension ref="%s"/>', cell_ref) worksheet = Worksheet:new() worksheet:_set_filehandle(io.tmpfile()) worksheet:write(cell_ref, 'some string') worksheet:_write_dimension() got = worksheet:_get_data() is(got, expected, caption) ---- -- 5. Test the _write_dimension() method with dimensions set. -- cell_ref = 'XFD1048576' caption = string.format(" \tWorksheet: _write_dimension('%s')", cell_ref) expected = string.format('<dimension ref="%s"/>', cell_ref) worksheet = Worksheet:new() worksheet:_set_filehandle(io.tmpfile()) worksheet:write(cell_ref, 'some string') worksheet:_write_dimension() got = worksheet:_get_data() is(got, expected, caption) ---- -- 6. Test the _write_dimension() method with dimensions set. -- cell_ref = 'A1' caption = string.format(" \tWorksheet: _write_dimension('%s')", cell_ref) expected = string.format('<dimension ref="%s"/>', cell_ref) worksheet = Worksheet:new() worksheet:_set_filehandle(io.tmpfile()) worksheet:write(cell_ref, 'some string') worksheet:_write_dimension() got = worksheet:_get_data() is(got, expected, caption) ---- -- 7. Test the _write_dimension() method with dimensions set. -- cell_ref = 'A1:B2' caption = string.format(" \tWorksheet: _write_dimension('%s')", cell_ref) expected = string.format('<dimension ref="%s"/>', cell_ref) worksheet = Worksheet:new() worksheet:_set_filehandle(io.tmpfile()) worksheet:write('A1', 'some string') worksheet:write('B2', 'some string') worksheet:_write_dimension() got = worksheet:_get_data() is(got, expected, caption) ---- -- 8. Test the _write_dimension() method with dimensions set. -- cell_ref = 'A1:B2' caption = string.format(" \tWorksheet: _write_dimension('%s')", cell_ref) expected = string.format('<dimension ref="%s"/>', cell_ref) worksheet = Worksheet:new() worksheet:_set_filehandle(io.tmpfile()) worksheet:write('B2', 'some string') worksheet:write('A1', 'some string') worksheet:_write_dimension() got = worksheet:_get_data() is(got, expected, caption) ---- -- 9. Test the _write_dimension() method with dimensions set. -- cell_ref = 'B2:H11' caption = string.format(" \tWorksheet: _write_dimension('%s')", cell_ref) expected = string.format('<dimension ref="%s"/>', cell_ref) worksheet = Worksheet:new() worksheet:_set_filehandle(io.tmpfile()) worksheet:write('B2', 'some string') worksheet:write('H11', 'some string') worksheet:_write_dimension() got = worksheet:_get_data() is(got, expected, caption) ---- -- 10. Test the _write_dimension() method with dimensions set. -- cell_ref = 'A1:XFD1048576' caption = string.format(" \tWorksheet: _write_dimension('%s')", cell_ref) expected = string.format('<dimension ref="%s"/>', cell_ref) worksheet = Worksheet:new() worksheet:_set_filehandle(io.tmpfile()) worksheet:write('A1', 'some string') worksheet:write('XFD1048576', 'some string') worksheet:_write_dimension() got = worksheet:_get_data() is(got, expected, caption)
---- -- Tests for the xlsxwriter.lua worksheet class. -- -- Copyright 2014, John McNamara, [email protected] -- require "Test.More" plan(10) ---- -- Tests setup. -- local expected local got local caption local Worksheet = require "xlsxwriter.worksheet" local Sharedstrings = require "xlsxwriter.sharedstrings" local worksheet local cell_ref ---- -- 1. Test the _write_dimension() method with no dimensions set. -- caption = " \tWorksheet: _write_dimension()" expected = '<dimension ref="A1"/>' worksheet = Worksheet:new() worksheet:_set_filehandle(io.tmpfile()) worksheet:_write_dimension() got = worksheet:_get_data() is(got, expected, caption) ---- -- 2. Test the _write_dimension() method with dimensions set. -- cell_ref = 'A1' caption = string.format(" \tWorksheet: _write_dimension('%s')", cell_ref) expected = string.format('<dimension ref="%s"/>', cell_ref) worksheet = Worksheet:new() worksheet.str_table = Sharedstrings:new() worksheet:_set_filehandle(io.tmpfile()) worksheet:write(cell_ref, 'some string') worksheet:_write_dimension() got = worksheet:_get_data() is(got, expected, caption) ---- -- 3. Test the _write_dimension() method with dimensions set. -- cell_ref = 'A1048576' caption = string.format(" \tWorksheet: _write_dimension('%s')", cell_ref) expected = string.format('<dimension ref="%s"/>', cell_ref) worksheet = Worksheet:new() worksheet.str_table = Sharedstrings:new() worksheet:_set_filehandle(io.tmpfile()) worksheet:write(cell_ref, 'some string') worksheet:_write_dimension() got = worksheet:_get_data() is(got, expected, caption) ---- -- 4. Test the _write_dimension() method with dimensions set. -- cell_ref = 'XFD1' caption = string.format(" \tWorksheet: _write_dimension('%s')", cell_ref) expected = string.format('<dimension ref="%s"/>', cell_ref) worksheet = Worksheet:new() worksheet.str_table = Sharedstrings:new() worksheet:_set_filehandle(io.tmpfile()) worksheet:write(cell_ref, 'some string') worksheet:_write_dimension() got = worksheet:_get_data() is(got, expected, caption) ---- -- 5. Test the _write_dimension() method with dimensions set. -- cell_ref = 'XFD1048576' caption = string.format(" \tWorksheet: _write_dimension('%s')", cell_ref) expected = string.format('<dimension ref="%s"/>', cell_ref) worksheet = Worksheet:new() worksheet.str_table = Sharedstrings:new() worksheet:_set_filehandle(io.tmpfile()) worksheet:write(cell_ref, 'some string') worksheet:_write_dimension() got = worksheet:_get_data() is(got, expected, caption) ---- -- 6. Test the _write_dimension() method with dimensions set. -- cell_ref = 'A1' caption = string.format(" \tWorksheet: _write_dimension('%s')", cell_ref) expected = string.format('<dimension ref="%s"/>', cell_ref) worksheet = Worksheet:new() worksheet.str_table = Sharedstrings:new() worksheet:_set_filehandle(io.tmpfile()) worksheet:write(cell_ref, 'some string') worksheet:_write_dimension() got = worksheet:_get_data() is(got, expected, caption) ---- -- 7. Test the _write_dimension() method with dimensions set. -- cell_ref = 'A1:B2' caption = string.format(" \tWorksheet: _write_dimension('%s')", cell_ref) expected = string.format('<dimension ref="%s"/>', cell_ref) worksheet = Worksheet:new() worksheet.str_table = Sharedstrings:new() worksheet:_set_filehandle(io.tmpfile()) worksheet:write('A1', 'some string') worksheet:write('B2', 'some string') worksheet:_write_dimension() got = worksheet:_get_data() is(got, expected, caption) ---- -- 8. Test the _write_dimension() method with dimensions set. -- cell_ref = 'A1:B2' caption = string.format(" \tWorksheet: _write_dimension('%s')", cell_ref) expected = string.format('<dimension ref="%s"/>', cell_ref) worksheet = Worksheet:new() worksheet.str_table = Sharedstrings:new() worksheet:_set_filehandle(io.tmpfile()) worksheet:write('B2', 'some string') worksheet:write('A1', 'some string') worksheet:_write_dimension() got = worksheet:_get_data() is(got, expected, caption) ---- -- 9. Test the _write_dimension() method with dimensions set. -- cell_ref = 'B2:H11' caption = string.format(" \tWorksheet: _write_dimension('%s')", cell_ref) expected = string.format('<dimension ref="%s"/>', cell_ref) worksheet = Worksheet:new() worksheet.str_table = Sharedstrings:new() worksheet:_set_filehandle(io.tmpfile()) worksheet:write('B2', 'some string') worksheet:write('H11', 'some string') worksheet:_write_dimension() got = worksheet:_get_data() is(got, expected, caption) ---- -- 10. Test the _write_dimension() method with dimensions set. -- cell_ref = 'A1:XFD1048576' caption = string.format(" \tWorksheet: _write_dimension('%s')", cell_ref) expected = string.format('<dimension ref="%s"/>', cell_ref) worksheet = Worksheet:new() worksheet.str_table = Sharedstrings:new() worksheet:_set_filehandle(io.tmpfile()) worksheet:write('A1', 'some string') worksheet:write('XFD1048576', 'some string') worksheet:_write_dimension() got = worksheet:_get_data() is(got, expected, caption)
Fix tests with string table.
Fix tests with string table.
Lua
mit
moteus/xlsxwriter.lua,moteus/xlsxwriter.lua,moteus/xlsxwriter.lua,moteus/xlsxwriter.lua
ae70b6bf21b0a159f442b9ec035db51a38428940
mumbledj/mumbledj.lua
mumbledj/mumbledj.lua
------------------------- -- MumbleDJ -- -- By Matthieu Grieger -- ------------------------------------------------------------------ -- mumbledj.lua -- -- The main file which defines most of MumbleDJ's behavior. All -- -- commands are found here, and most of their implementation. -- ------------------------------------------------------------------ local config = require("config") local song_queue = require("song_queue") -- Connects to Mumble server. function piepan.onConnect() print(piepan.me.name .. " has connected to the server!") local user = piepan.users[piepan.me.name] local channel = user.channel(config.DEFAULT_CHANNEL) piepan.me:moveTo(channel) end -- Function that is called when a new message is posted to the channel. function piepan.onMessage(message) if message.user == nil then return end if string.sub(message.text, 0, 1) == config.COMMAND_PREFIX then parse_command(message) end end -- Parses commands and its arguments (if they exist), and calls the appropriate -- functions for doing the requested task. function parse_command(message) local command = "" local argument = "" if string.find(message.text, " ") then command = string.sub(message.text, 2, string.find(message.text, ' ') - 1) argument = string.sub(message.text, string.find(message.text, ' ') + 1) else command = string.sub(message.text, 2) end -- Add command if command == config.ADD_ALIAS then local has_permission = check_permissions(config.ADMIN_ADD, message.user.name) if has_permission then if config.OUTPUT then print(message.user.name .. " has told the bot to add the following URL to the queue: " .. argument .. ".") if not song_queue.add_song(argument, message.user.name) then message.user:send(config.INVALID_URL_MSG) end end else message.user:send(config.NO_PERMISSION_MSG) end -- Skip command elseif command == config.SKIP_ALIAS then local has_permission = check_permissions(config.ADMIN_SKIP, message.user.name) if has_permission then if config.OUTPUT then print(message.user.name .. " has voted to skip the current song.") end skip(message.user.name) else message.user:send(config.NO_PERMISSION_MSG) end -- Volume command elseif command == config.VOLUME_ALIAS then local has_permission = check_permissions(config.ADMIN_VOLUME, message.user.name) if has_permission then if config.OUTPUT then print(message.user.name .. " has changed the volume to the following: " .. argument .. ".") if argument ~= nil then if config.LOWEST_VOLUME < argument < config.HIGHEST_VOLUME then config.VOLUME = argument else message.user:send(config.NOT_IN_VOLUME_RANGE) end else message.user:send(config.NO_ARGUMENT) end end end -- Move command elseif command == config.MOVE_ALIAS then local has_permission = check_permissions(config.ADMIN_MOVE, message.user.name) if has_permission then if config.OUTPUT then print(message.user.name .. " has told the bot to move to the following channel: " .. argument .. ".") end if not move(argument) then message.user:send(config.CHANNEL_DOES_NOT_EXIST_MSG) end else message.user:send(config.NO_PERMISSION_MSG) end -- Kill command elseif command == config.KILL_ALIAS then local has_permission = check_permissions(config.ADMIN_KILL, message.user.name) if has_permission then if config.OUTPUT then print(message.user.name .. " has told the bot to kill itself.") end kill() else message.user:send(config.NO_PERMISSION_MSG) end else message.user:send("The command you have entered is not valid.") end end -- Handles a skip request through the use of helper functions found within -- song_queue.lua. Once done processing, it will compare the skip ratio with -- the one defined in the settings and decide whether to skip the current song -- or not. function skip(username) if song_queue:add_skip(username) then local skip_ratio = song_queue:count_skippers() / count_users() if skip_ratio > config.SKIP_RATIO then piepan.me.channel:send(config.SONG_SKIPPED_HTML) piepan.Audio:stop() next_song() else piepan.me.channel:send(string.format(config.USER_SKIP_HTML, username)) end else message.user:send("You have already voted to skip this song.") end end -- Moves the bot to the channel specified by the "chan" argument. -- NOTE: This only supports moving to a sibling channel at the moment. function move(chan) local user = piepan.users[piepan.me.name] local channel = user.channel("../" .. chan) if channel == nil then return false else piepan.me:moveTo(channel) return true end end -- Performs functions that allow the bot to safely exit. function kill() os.remove("song.ogg") os.remove("song-converted.ogg") os.remove(".video_fail") piepan.disconnect() os.exit(0) end -- Checks the permissions of a user against the config to see if they are -- allowed to execute a certain command. function check_permissions(ADMIN_COMMAND, username) if config.ENABLE_ADMINS and ADMIN_COMMAND then return is_admin(username) end return true end -- Checks if a user is an admin, as specified in config.lua. function is_admin(username) for _,user in pairs(config.ADMINS) do if user == username then return true end end return false end -- Switches to the next song. function next_song() song_queue:reset_skips() if song_queue:get_length() ~= 0 then local success = song_queue:get_next_song() if not success then piepan.me.channel:send("An error occurred while preparing the next track. Skipping...") end end end -- Checks if a file exists. function file_exists(file) local f=io.open(file,"r") if f~=nil then io.close(f) return true else return false end end -- Returns the number of users in the Mumble server. function count_users() local user_count = -1 -- Set to -1 to account for the bot for name,_ in pairs(piepan.users) do user_count = user_count + 1 end return user_count end
------------------------- -- MumbleDJ -- -- By Matthieu Grieger -- ------------------------------------------------------------------ -- mumbledj.lua -- -- The main file which defines most of MumbleDJ's behavior. All -- -- commands are found here, and most of their implementation. -- ------------------------------------------------------------------ local config = require("config") local song_queue = require("song_queue") -- Connects to Mumble server. function piepan.onConnect() print(piepan.me.name .. " has connected to the server!") local user = piepan.users[piepan.me.name] local channel = user.channel(config.DEFAULT_CHANNEL) piepan.me:moveTo(channel) end -- Function that is called when a new message is posted to the channel. function piepan.onMessage(message) if message.user == nil then return end if string.sub(message.text, 0, 1) == config.COMMAND_PREFIX then parse_command(message) end end -- Parses commands and its arguments (if they exist), and calls the appropriate -- functions for doing the requested task. function parse_command(message) local command = "" local argument = "" if string.find(message.text, " ") then command = string.sub(message.text, 2, string.find(message.text, ' ') - 1) argument = string.sub(message.text, string.find(message.text, ' ') + 1) else command = string.sub(message.text, 2) end -- Add command if command == config.ADD_ALIAS then local has_permission = check_permissions(config.ADMIN_ADD, message.user.name) if has_permission then if config.OUTPUT then print(message.user.name .. " has told the bot to add the following URL to the queue: " .. argument .. ".") if not song_queue.add_song(argument, message.user.name) then message.user:send(config.INVALID_URL_MSG) end end else message.user:send(config.NO_PERMISSION_MSG) end -- Skip command elseif command == config.SKIP_ALIAS then local has_permission = check_permissions(config.ADMIN_SKIP, message.user.name) if has_permission then if config.OUTPUT then print(message.user.name .. " has voted to skip the current song.") end skip(message.user.name) else message.user:send(config.NO_PERMISSION_MSG) end -- Volume command elseif command == config.VOLUME_ALIAS then local has_permission = check_permissions(config.ADMIN_VOLUME, message.user.name) if has_permission then if config.OUTPUT then print(message.user.name .. " has changed the volume to the following: " .. argument .. ".") if argument ~= nil then if config.LOWEST_VOLUME < argument < config.HIGHEST_VOLUME then config.VOLUME = argument else message.user:send(config.NOT_IN_VOLUME_RANGE) end else message.user:send(config.NO_ARGUMENT) end end end -- Move command elseif command == config.MOVE_ALIAS then local has_permission = check_permissions(config.ADMIN_MOVE, message.user.name) if has_permission then if config.OUTPUT then print(message.user.name .. " has told the bot to move to the following channel: " .. argument .. ".") end if not move(argument) then message.user:send(config.CHANNEL_DOES_NOT_EXIST_MSG) end else message.user:send(config.NO_PERMISSION_MSG) end -- Kill command elseif command == config.KILL_ALIAS then local has_permission = check_permissions(config.ADMIN_KILL, message.user.name) if has_permission then if config.OUTPUT then print(message.user.name .. " has told the bot to kill itself.") end kill() else message.user:send(config.NO_PERMISSION_MSG) end else message.user:send("The command you have entered is not valid.") end end -- Handles a skip request through the use of helper functions found within -- song_queue.lua. Once done processing, it will compare the skip ratio with -- the one defined in the settings and decide whether to skip the current song -- or not. function skip(username) if song_queue:add_skip(username) then local skip_ratio = song_queue:count_skippers() / count_users() if skip_ratio > config.SKIP_RATIO then piepan.me.channel:send(config.SONG_SKIPPED_HTML) piepan.Audio:stop() next_song() else piepan.me.channel:send(string.format(config.USER_SKIP_HTML, username)) end end end -- Moves the bot to the channel specified by the "chan" argument. -- NOTE: This only supports moving to a sibling channel at the moment. function move(chan) local user = piepan.users[piepan.me.name] local channel = user.channel("../" .. chan) if channel == nil then return false else piepan.me:moveTo(channel) return true end end -- Performs functions that allow the bot to safely exit. function kill() os.remove("song.ogg") os.remove("song-converted.ogg") os.remove(".video_fail") piepan.disconnect() os.exit(0) end -- Checks the permissions of a user against the config to see if they are -- allowed to execute a certain command. function check_permissions(ADMIN_COMMAND, username) if config.ENABLE_ADMINS and ADMIN_COMMAND then return is_admin(username) end return true end -- Checks if a user is an admin, as specified in config.lua. function is_admin(username) for _,user in pairs(config.ADMINS) do if user == username then return true end end return false end -- Switches to the next song. function next_song() song_queue:reset_skips() if song_queue:get_length() ~= 0 then local success = song_queue:get_next_song() if not success then piepan.me.channel:send("An error occurred while preparing the next track. Skipping...") end end end -- Checks if a file exists. function file_exists(file) local f=io.open(file,"r") if f~=nil then io.close(f) return true else return false end end -- Returns the number of users in the Mumble server. function count_users() local user_count = -1 -- Set to -1 to account for the bot for name,_ in pairs(piepan.users) do user_count = user_count + 1 end return user_count end
Fixed a crash related to messages
Fixed a crash related to messages
Lua
mit
fiveofeight/mumbledj,pzduniak/mumbledj,RichardNysater/mumbledj,Gamah/mumbledj,MrKrucible/mumbledj,r3valkyrie/mumbledj,GabrielPlassard/mumbledj,matthieugrieger/mumbledj
28a7334f5c02ea1468ebd75254bb03cd38abcec2
src/xenia/gpu/vulkan/premake5.lua
src/xenia/gpu/vulkan/premake5.lua
project_root = "../../../.." include(project_root.."/tools/build") group("src") project("xenia-gpu-vulkan") uuid("717590b4-f579-4162-8f23-0624e87d6cca") kind("StaticLib") language("C++") links({ "volk", "xenia-base", "xenia-gpu", "xenia-ui", "xenia-ui-spirv", "xenia-ui-vulkan", "xxhash", }) defines({ }) includedirs({ project_root.."/third_party/gflags/src", }) local_platform_files() files({ "shaders/bin/*.h", }) -- TODO(benvanik): kill this and move to the debugger UI. group("src") project("xenia-gpu-vulkan-trace-viewer") uuid("86a1dddc-a26a-4885-8c55-cf745225d93e") kind("WindowedApp") language("C++") links({ "capstone", "gflags", "glslang-spirv", "imgui", "libavcodec", "libavutil", "mspack", "snappy", "spirv-tools", "volk", "xenia-apu", "xenia-apu-nop", "xenia-base", "xenia-core", "xenia-cpu", "xenia-cpu-backend-x64", "xenia-gpu", "xenia-gpu-vulkan", "xenia-hid", "xenia-hid-nop", "xenia-kernel", "xenia-ui", "xenia-ui-spirv", "xenia-ui-vulkan", "xenia-vfs", "xxhash", }) defines({ }) includedirs({ project_root.."/third_party/gflags/src", }) files({ "vulkan_trace_viewer_main.cc", "../../base/main_"..platform_suffix..".cc", }) filter("platforms:Linux") links({ "X11", "xcb", "X11-xcb", "GL", "vulkan", }) filter("platforms:Windows") links({ "xenia-apu-xaudio2", "xenia-hid-winkey", "xenia-hid-xinput", }) -- Only create the .user file if it doesn't already exist. local user_file = project_root.."/build/xenia-gpu-vulkan-trace-viewer.vcxproj.user" if not os.isfile(user_file) then debugdir(project_root) debugargs({ "--flagfile=scratch/flags.txt", "2>&1", "1>scratch/stdout-trace-viewer.txt", }) end group("src") project("xenia-gpu-vulkan-trace-dump") uuid("0dd0dd1c-b321-494d-ab9a-6c062f0c65cc") kind("ConsoleApp") language("C++") links({ "capstone", "gflags", "glslang-spirv", "imgui", "libavcodec", "libavutil", "mspack", "snappy", "spirv-tools", "volk", "xenia-apu", "xenia-apu-nop", "xenia-base", "xenia-core", "xenia-cpu", "xenia-cpu-backend-x64", "xenia-gpu", "xenia-gpu-vulkan", "xenia-hid", "xenia-hid-nop", "xenia-kernel", "xenia-ui", "xenia-ui-spirv", "xenia-ui-vulkan", "xenia-vfs", "xxhash", }) defines({ }) includedirs({ project_root.."/third_party/gflags/src", }) files({ "vulkan_trace_dump_main.cc", "../../base/main_"..platform_suffix..".cc", }) filter("platforms:Linux") links({ "X11", "xcb", "X11-xcb", "GL", "vulkan", }) filter("platforms:Windows") -- Only create the .user file if it doesn't already exist. local user_file = project_root.."/build/xenia-gpu-vulkan-trace-dump.vcxproj.user" if not os.isfile(user_file) then debugdir(project_root) debugargs({ "--flagfile=scratch/flags.txt", "2>&1", "1>scratch/stdout-trace-dump.txt", }) end
project_root = "../../../.." include(project_root.."/tools/build") group("src") project("xenia-gpu-vulkan") uuid("717590b4-f579-4162-8f23-0624e87d6cca") kind("StaticLib") language("C++") links({ "volk", "xenia-base", "xenia-gpu", "xenia-ui", "xenia-ui-spirv", "xenia-ui-vulkan", "xxhash", }) defines({ }) includedirs({ project_root.."/third_party/gflags/src", }) local_platform_files() files({ "shaders/bin/*.h", }) -- TODO(benvanik): kill this and move to the debugger UI. group("src") project("xenia-gpu-vulkan-trace-viewer") uuid("86a1dddc-a26a-4885-8c55-cf745225d93e") kind("WindowedApp") language("C++") links({ "aes_128", "capstone", "gflags", "glslang-spirv", "imgui", "libavcodec", "libavutil", "mspack", "snappy", "spirv-tools", "volk", "xenia-apu", "xenia-apu-nop", "xenia-base", "xenia-core", "xenia-cpu", "xenia-cpu-backend-x64", "xenia-gpu", "xenia-gpu-vulkan", "xenia-hid", "xenia-hid-nop", "xenia-kernel", "xenia-ui", "xenia-ui-spirv", "xenia-ui-vulkan", "xenia-vfs", "xxhash", }) defines({ }) includedirs({ project_root.."/third_party/gflags/src", }) files({ "vulkan_trace_viewer_main.cc", "../../base/main_"..platform_suffix..".cc", }) filter("platforms:Linux") links({ "X11", "xcb", "X11-xcb", "GL", "vulkan", }) filter("platforms:Windows") links({ "xenia-apu-xaudio2", "xenia-hid-winkey", "xenia-hid-xinput", }) -- Only create the .user file if it doesn't already exist. local user_file = project_root.."/build/xenia-gpu-vulkan-trace-viewer.vcxproj.user" if not os.isfile(user_file) then debugdir(project_root) debugargs({ "--flagfile=scratch/flags.txt", "2>&1", "1>scratch/stdout-trace-viewer.txt", }) end group("src") project("xenia-gpu-vulkan-trace-dump") uuid("0dd0dd1c-b321-494d-ab9a-6c062f0c65cc") kind("ConsoleApp") language("C++") links({ "aes_128", "capstone", "gflags", "glslang-spirv", "imgui", "libavcodec", "libavutil", "mspack", "snappy", "spirv-tools", "volk", "xenia-apu", "xenia-apu-nop", "xenia-base", "xenia-core", "xenia-cpu", "xenia-cpu-backend-x64", "xenia-gpu", "xenia-gpu-vulkan", "xenia-hid", "xenia-hid-nop", "xenia-kernel", "xenia-ui", "xenia-ui-spirv", "xenia-ui-vulkan", "xenia-vfs", "xxhash", }) defines({ }) includedirs({ project_root.."/third_party/gflags/src", }) files({ "vulkan_trace_dump_main.cc", "../../base/main_"..platform_suffix..".cc", }) filter("platforms:Linux") links({ "X11", "xcb", "X11-xcb", "GL", "vulkan", }) filter("platforms:Windows") -- Only create the .user file if it doesn't already exist. local user_file = project_root.."/build/xenia-gpu-vulkan-trace-dump.vcxproj.user" if not os.isfile(user_file) then debugdir(project_root) debugargs({ "--flagfile=scratch/flags.txt", "2>&1", "1>scratch/stdout-trace-dump.txt", }) end
[Vulkan] Fix missing aes_128 link for trace viewer/dumper.
[Vulkan] Fix missing aes_128 link for trace viewer/dumper.
Lua
bsd-3-clause
sephiroth99/xenia,sephiroth99/xenia,sephiroth99/xenia
6b73779b6a6c1d35b8b22d79bedc8f13390c5d44
extensions/battery/init.lua
extensions/battery/init.lua
--- === hs.battery === --- --- Battery/power information --- All functions here may return nil, if the information requested is not available. --- --- This module is based primarily on code from the previous incarnation of Mjolnir by [Steven Degutis](https://github.com/sdegutis/). local module = require("hs.battery.internal") local fnutils = require("hs.fnutils") -- private variables and methods ----------------------------------------- local check_list = {} for i,v in pairs(module) do check_list[#check_list + 1] = i end local __tostring_for_tables = function(self) local result = "" local width = 0 for i,v in fnutils.sortByKeys(self) do if type(i) == "string" and width < i:len() then width = i:len() end end for i,v in fnutils.sortByKeys(self) do if type(i) == "string" then result = result..string.format("%-"..tostring(width).."s %s\n", i, tostring(v)) end end return result end -- Public interface ------------------------------------------------------ module.watcher = require("hs.battery.watcher") --- hs.battery.getAll() -> table --- Function --- Get all available battery information --- --- Parameters: --- * None --- --- Returns: --- * A table containing all the information provided by the separate functions in hs.battery --- --- Notes: --- * If you require multiple pieces of information about a battery, this function may be more efficient than calling several other functions separately module.getAll = function() local t = {} for i, v in ipairs(check_list) do t[v] = module[v]() if t[v] == nil then t[v] = "n/a" end end return setmetatable(t, {__tostring = __tostring_for_tables }) end -- Return Module Object -------------------------------------------------- return module
--- === hs.battery === --- --- Battery/power information --- All functions here may return nil, if the information requested is not available. --- --- This module is based primarily on code from the previous incarnation of Mjolnir by [Steven Degutis](https://github.com/sdegutis/). local module = require("hs.battery.internal") local fnutils = require("hs.fnutils") -- private variables and methods ----------------------------------------- local check_list = {} for i,v in pairs(module) do if type(v) == "function" then check_list[#check_list + 1] = i end end local __tostring_for_tables = function(self) local result = "" local width = 0 for i,v in fnutils.sortByKeys(self) do if type(i) == "string" and width < i:len() then width = i:len() end end for i,v in fnutils.sortByKeys(self) do if type(i) == "string" then result = result..string.format("%-"..tostring(width).."s %s\n", i, tostring(v)) end end return result end -- Public interface ------------------------------------------------------ module.watcher = require("hs.battery.watcher") --- hs.battery.getAll() -> table --- Function --- Get all available battery information --- --- Parameters: --- * None --- --- Returns: --- * A table containing all the information provided by the separate functions in hs.battery --- --- Notes: --- * If you require multiple pieces of information about a battery, this function may be more efficient than calling several other functions separately module.getAll = function() local t = {} for i, v in ipairs(check_list) do t[v] = module[v]() if t[v] == nil then t[v] = "n/a" end end return setmetatable(t, {__tostring = __tostring_for_tables }) end -- Return Module Object -------------------------------------------------- return module
CL: *BugFix* - getAll should ignore non-functions
CL: *BugFix* - getAll should ignore non-functions
Lua
mit
CommandPost/CommandPost-App,Hammerspoon/hammerspoon,cmsj/hammerspoon,Habbie/hammerspoon,cmsj/hammerspoon,Habbie/hammerspoon,asmagill/hammerspoon,cmsj/hammerspoon,cmsj/hammerspoon,Habbie/hammerspoon,Habbie/hammerspoon,Hammerspoon/hammerspoon,asmagill/hammerspoon,CommandPost/CommandPost-App,asmagill/hammerspoon,bradparks/hammerspoon,Hammerspoon/hammerspoon,latenitefilms/hammerspoon,Hammerspoon/hammerspoon,Hammerspoon/hammerspoon,cmsj/hammerspoon,asmagill/hammerspoon,bradparks/hammerspoon,bradparks/hammerspoon,latenitefilms/hammerspoon,latenitefilms/hammerspoon,latenitefilms/hammerspoon,CommandPost/CommandPost-App,asmagill/hammerspoon,CommandPost/CommandPost-App,bradparks/hammerspoon,CommandPost/CommandPost-App,Habbie/hammerspoon,latenitefilms/hammerspoon,Hammerspoon/hammerspoon,Habbie/hammerspoon,latenitefilms/hammerspoon,bradparks/hammerspoon,asmagill/hammerspoon,CommandPost/CommandPost-App,cmsj/hammerspoon
6ba38be621a44599c85a79940fc9ec1895aa32b9
PPAndroid/assets/Core.lua
PPAndroid/assets/Core.lua
cfuns = require("ffi") cfuns.cdef[[ typedef struct { float x; float y; } vec2f; typedef struct { float x; float y; float z; } vec3f; typedef void (*touchHandler) (int x, int y, int pointerIndex); typedef void (*tapHandler) (int x, int y); typedef struct { vec3f acceleration; vec3f gyroscope; } SensorState; typedef struct { uint64_t _totalTime, _lastTime, _elapsedTime; bool _isPaused, _isStopped; } Clock; typedef struct { uint8_t* base; uint8_t* ptr; uint32_t length; } Buffer; typedef struct { Buffer* in_; Buffer* out; } Network; typedef struct { uint32_t width, height; } Screen; typedef struct Renderer Renderer; typedef struct Content Content; typedef struct { Clock* clock; Network* network; SensorState* sensor; Renderer* renderer; Screen* screen; Content* content; bool paused; char* name; } Game; extern Game* gGame; uint32_t loadFrame(const char* name); uint32_t loadFont(const char* fontName); void unloadFrame(uint32_t frame); void unloadFont(uint32_t font); //clock.h float clockElapsed(Clock* clock); float clockTotal(Clock* clock); vec2f measureString(uint32_t font, const char* str); void addFrame(uint32_t frame, vec2f pos, vec2f dim, unsigned int color); void addFrame2(uint32_t frame, vec2f pos, vec2f dim, unsigned int color, vec2f origin, float rotation, int mirrored); void addText(uint32_t font, const char* str, vec2f pos, unsigned int color); //buffer.h uint32_t bufferBytesRemaining(Buffer* buffer); void bufferWriteBytes(Buffer* buffer, uint8_t* data, size_t length); void bufferWriteByte(Buffer* buffer, uint8_t data); void bufferWriteShort(Buffer* buffer, uint16_t data); void bufferWriteInt(Buffer* buffer, uint32_t data); void bufferWriteLong(Buffer* buffer, uint64_t data); void bufferWriteUTF8(Buffer* buffer, const char* data); void bufferWriteFloat(Buffer* buffer, float data); void bufferWriteDouble(Buffer* buffer,double data); void bufferReadBytes(Buffer* buffer, uint8_t* dest, size_t numBytes); void bufferReadUTF8(Buffer* buffer, const char* dest); uint8_t bufferReadByte(Buffer* buffer); uint16_t bufferReadShort(Buffer* buffer); uint32_t bufferReadInt(Buffer* buffer); uint64_t bufferReadLong(Buffer* buffer); float bufferReadFloat(Buffer* buffer); double bufferReadDouble(Buffer* buffer); const char* bufferReadLuaString(Buffer* buffer); const char* testStr(); //network.h int networkConnect(Network* network); int networkReconnect(Network* network); int networkDisconnect(Network* network); int networkSend(Network* network); int networkReceive(Network* network); int networkIsAlive(Network* network); int networkShutdown(Network* network); ]] local C = cfuns.C function log(s) Out.writeShort(#s + 3); Out.writeByte(5); Out.writeUTF8(s); end Loader = {} Loader.loadFrame = C.loadFrame Loader.loadFont = C.loadFont Loader.unloadFont = C.unloadFont Loader.unloadFrame = C.unloadFrame Renderer = {} Renderer.addFrame = C.addFrame Renderer.addFrame2 = C.addFrame2 Renderer.addText = C.addText Font = {} Font.measure = C.measureString; Network = { messages = { sensor = 1, transition = 6 }, send = function() cfuns.C.networkSend(C.gGame.network) end, isAlive = function() cfuns.C.networkIsAlive(C.gGame.network) end } Time = {} Time.total = 0 Time.elapsed = 0 Out = { } function Out.writeByte(byte) C.bufferWriteByte(C.gGame.network.out, byte) end function Out.writeShort(short) C.bufferWriteShort(C.gGame.network.out, short) end function Out.writeInt(int) C.bufferWriteInt(C.gGame.network.out, int) end function Out.writeLong(long) C.bufferWriteShort(C.gGame.network.out, long) end function Out.writeFloat(float) C.bufferWriteFloat(C.gGame.network.out, float) end function Out.writeDouble(double) C.bufferWriteDouble(C.gGame.network.out, double) end function Out.writeVec2(v) Out.writeFloat(v.x) Out.writeFloat(v.y) end function Out.writeVec3(v) Out.writeFloat(v.x) Out.writeFloat(v.y) Out.writeFloat(v.z) end function Out.writeUTF8(s) C.bufferWriteUTF8(C.gGame.network.out, s); end In = { } In.readByte = function() return C.bufferReadByte(C.gGame.network.in_) end In.readShort = function() return C.bufferReadShort(C.gGame.network.in_) end In.readInt = function() return C.bufferReadInt(C.gGame.network.in_) end In.readLong = function() return C.bufferReadLong(C.gGame.network.in_) end In.readFloat = function() return C.bufferReadFloat(C.gGame.network.in_) end In.readDouble = function() return C.bufferReadDouble(C.gGame.network.in_) end In.readVec2 = function() return vec2(In.readFloat(), In.readFloat()) end In.readVec3 = function() return vec3(In.readFloat(), In.readFloat(), In.readFloat()) end In.readUTF8 = function() return cfuns.string(C.bufferReadLuaString(C.gGame.network.in_)) end In.readByteArray = function() local len = In.readShort() local array = {} for i=0, len-1, 1 do array[i] = In.readByte() end return array end Sensors = C.gGame.sensor Screen = C.gGame.screen; vec2 = cfuns.typeof("vec2f") local function updateTime() Time.total = C.clockTotal(C.gGame.clock) Time.elapsed = C.clockElapsed(C.gGame.clock) end function coreUpdate() Sensors = C.gGame.sensor Screen = C.gGame.screen updateTime(); end
cfuns = require("ffi") cfuns.cdef[[ typedef struct { float x; float y; } vec2f; typedef struct { float x; float y; float z; } vec3f; typedef void (*touchHandler) (int x, int y, int pointerIndex); typedef void (*tapHandler) (int x, int y); typedef struct { vec3f acceleration; vec3f gyroscope; } SensorState; typedef struct { uint64_t _totalTime, _lastTime, _elapsedTime; bool _isPaused, _isStopped; } Clock; typedef struct { uint8_t* base; uint8_t* ptr; uint32_t length; } Buffer; typedef struct { Buffer* in_; Buffer* out; } Network; typedef struct { uint32_t width, height; } Screen; typedef struct Renderer Renderer; typedef struct Content Content; typedef struct { Clock* clock; Network* network; SensorState* sensor; Renderer* renderer; Screen* screen; Content* content; bool paused; char* name; } Game; extern Game* gGame; uint32_t loadFrame(const char* name); uint32_t loadFont(const char* fontName); void unloadFrame(uint32_t frame); void unloadFont(uint32_t font); //clock.h float clockElapsed(Clock* clock); float clockTotal(Clock* clock); vec2f measureString(uint32_t font, const char* str); void addFrame(uint32_t frame, vec2f pos, vec2f dim, unsigned int color); void addFrame2(uint32_t frame, vec2f pos, vec2f dim, unsigned int color, vec2f origin, float rotation, int mirrored); void addText(uint32_t font, const char* str, vec2f pos, unsigned int color); //buffer.h uint32_t bufferBytesRemaining(Buffer* buffer); void bufferWriteBytes(Buffer* buffer, uint8_t* data, size_t length); void bufferWriteByte(Buffer* buffer, uint8_t data); void bufferWriteShort(Buffer* buffer, uint16_t data); void bufferWriteInt(Buffer* buffer, uint32_t data); void bufferWriteLong(Buffer* buffer, uint64_t data); void bufferWriteUTF8(Buffer* buffer, const char* data); void bufferWriteFloat(Buffer* buffer, float data); void bufferWriteDouble(Buffer* buffer,double data); void bufferReadBytes(Buffer* buffer, uint8_t* dest, size_t numBytes); void bufferReadUTF8(Buffer* buffer, const char* dest); uint8_t bufferReadByte(Buffer* buffer); uint16_t bufferReadShort(Buffer* buffer); uint32_t bufferReadInt(Buffer* buffer); uint64_t bufferReadLong(Buffer* buffer); float bufferReadFloat(Buffer* buffer); double bufferReadDouble(Buffer* buffer); const char* bufferReadLuaString(Buffer* buffer); const char* testStr(); //network.h int networkConnect(Network* network); int networkReconnect(Network* network); int networkDisconnect(Network* network); int networkSend(Network* network); int networkReceive(Network* network); int networkIsAlive(Network* network); int networkShutdown(Network* network); ]] local C = cfuns.C function log(s) Out.writeShort(#s + 3); Out.writeByte(5); Out.writeUTF8(s); end Loader = {} Loader.loadFrame = C.loadFrame Loader.loadFont = C.loadFont Loader.unloadFont = C.unloadFont Loader.unloadFrame = C.unloadFrame Renderer = {} Renderer.addFrame = C.addFrame Renderer.addFrame2 = C.addFrame2 Renderer.addText = C.addText Font = {} Font.measure = C.measureString; Network = { messages = { sensor = 1, transition = 6 }, send = function() cfuns.C.networkSend(C.gGame.network) end, isAlive = function() cfuns.C.networkIsAlive(C.gGame.network) end } Time = {} Time.total = 0 Time.elapsed = 0 Out = { } function Out.writeByte(byte) C.bufferWriteByte(C.gGame.network.out, byte) end function Out.writeShort(short) C.bufferWriteShort(C.gGame.network.out, short) end function Out.writeInt(int) C.bufferWriteInt(C.gGame.network.out, int) end function Out.writeLong(long) C.bufferWriteShort(C.gGame.network.out, long) end function Out.writeFloat(float) C.bufferWriteFloat(C.gGame.network.out, float) end function Out.writeDouble(double) C.bufferWriteDouble(C.gGame.network.out, double) end function Out.writeVec2(v) Out.writeFloat(v.x) Out.writeFloat(v.y) end function Out.writeVec3(v) Out.writeFloat(v.x) Out.writeFloat(v.y) Out.writeFloat(v.z) end function Out.writeUTF8(s) C.bufferWriteUTF8(C.gGame.network.out, s); end In = { } In.readByte = function() return C.bufferReadByte(C.gGame.network.in_) end In.readShort = function() return C.bufferReadShort(C.gGame.network.in_) end In.readInt = function() return C.bufferReadInt(C.gGame.network.in_) end In.readLong = function() return C.bufferReadLong(C.gGame.network.in_) end In.readFloat = function() return C.bufferReadFloat(C.gGame.network.in_) end In.readDouble = function() return C.bufferReadDouble(C.gGame.network.in_) end In.readVec2 = function() return vec2(In.readFloat(), In.readFloat()) end In.readVec3 = function() return vec3(In.readFloat(), In.readFloat(), In.readFloat()) end In.readUTF8 = function() return cfuns.string(C.bufferReadLuaString(C.gGame.network.in_)) end In.readByteArray = function() local len = In.readShort() local array = {} for i=0, len-1, 1 do array[i] = In.readByte() end return array end Sensors = C.gGame.sensor Screen = C.gGame.screen vec2_MT = { __add = function (v0, v1) return vec2(v0.x + v1.x, v0.y + v1.y) end, __sub = function (v0, v1) return vec2(v0.x - v1.x, v0.y - v1.y) end, __mul = function (v0, scalar) return vec2(v0.x * scalar, v0.y * scalar) end, __div = function (v0, scalar) return vec2(v0.x / scalar, v0.y / scalar) end } vec2 = cfuns.metatype("vec2f", vec2_MT) local function updateTime() Time.total = C.clockTotal(C.gGame.clock) Time.elapsed = C.clockElapsed(C.gGame.clock) end function coreUpdate() Sensors = C.gGame.sensor Screen = C.gGame.screen updateTime(); end
Fix for vector math
Fix for vector math
Lua
apache-2.0
ponpal/ProjectParty-for-Android,ponpal/ProjectParty-for-Android,ponpal/ProjectParty-for-Android
36c2e212f4e5aa3f6fda901a0ee20b8da44a73cd
otherplatforms/emscripten-webgl/premake4.lua
otherplatforms/emscripten-webgl/premake4.lua
------------------------------------------------------------------ -- premake 4 Pyros3D solution ------------------------------------------------------------------ solution "Pyros3D" -- Make Directories os.mkdir("bin"); os.mkdir("build"); os.mkdir("include"); os.mkdir("libs"); newoption { trigger = "jsnative", description = "Build Engine to be used from Javascript - Proof of Concept" } newoption { trigger = "examples", description = "Build Demos Examples" } newoption { trigger = "log", value = "OUTPUT", description = "Log Output", allowed = { { "none", "No log - Default" }, { "console", "Log to Console"}, { "file", "Log to File"} } } if _OPTIONS['jsnative'] then excludes { "**/SDL/**" } else framework = "_SDL"; libsToLink = { "SDL" } end excludes { "**/SFML/**", "**/SDL2/**" } premake.gcc.cc = "emcc"; premake.gcc.cxx = "em++"; ------------------------------------------------------------------ -- setup common settings ------------------------------------------------------------------ configurations { "Debug", "Release" } platforms { "x32" } location "build" rootdir = "." libName = "PyrosEngine" project "PyrosEngine" targetdir "libs" if _OPTIONS["jsnative"] then kind "ConsoleApp" else kind "SharedLib" end language "C++" files { "../../src/**.h", "../../src/**.cpp" } if _OPTIONS["jsnative"] then files { "src/JSNative/JSNative_Wrapper.h", "src/JSNative/JSNative_Wrapper.cpp" } end includedirs { "../../include/", "include/" } defines({"UNICODE", "LODEPNG", "GLES2", "EMSCRIPTEN"}) if _OPTIONS["jsnative"]==nil then defines({framework}) end if _OPTIONS["log"]=="console" then defines({"LOG_TO_CONSOLE"}) else if _OPTIONS["log"]=="file" then defines({"LOG_TO_FILE"}) else defines({"LOG_DISABLE"}) end end if _OPTIONS["jsnative"] then configuration "Debug" targetname(libName.."d.js") defines({"_DEBUG"}) flags { "Symbols" } targetdir ("bin") links { "BulletDynamics", "BulletCollision", "LinearMath", "freetype" } linkoptions { "-L../libs", "--post-js ../src/JSNative/glue.js" } configuration "Release" flags { "Optimize" } targetname(libName..".js") targetdir ("bin") links { "BulletDynamics", "BulletCollision", "LinearMath", "freetype" } linkoptions { "-L../libs", "--post-js ../src/JSNative/glue.js" } else configuration "Debug" targetname(libName.."d") defines({"_DEBUG"}) flags { "Symbols" } configuration "Release" flags { "Optimize" } targetname(libName) end function BuildDemo(demoPath, demoName) project (demoName) kind "ConsoleApp" language "C++" targetname(demoName..".html") files { demoPath.."/**.h", demoPath.."/**.cpp", demoPath.."/../WindowManagers/**.cpp", demoPath.."/../WindowManagers/**.h", demoPath.."/../MainProgram.cpp" } excludes { demoPath.."/../WindowManagers/SDL2/**" } excludes { demoPath.."/../WindowManagers/SFML/**" } includedirs { "../../include/", "include/", "../../src/" } defines({"UNICODE", "GLEW_STATIC", "GLES2", "EMSCRIPTEN"}) defines({framework}); defines({"DEMO_NAME="..demoName, "_"..demoName}) configuration "Debug" defines({"_DEBUG"}) targetdir ("bin") links { libName.."d", "BulletDynamics", "BulletCollision", "LinearMath", "freetype" } linkoptions { "-L../libs" } flags { "Symbols" } linkoptions { "--preload-file ../"..demoPath.."/assets@../../"..demoPath.."/assets" } configuration "Release" targetdir ("bin") links { libName, "BulletDynamics", "BulletCollision", "LinearMath", "freetype" } linkoptions { "-L../libs" } flags { "Optimize" } linkoptions { "--preload-file ../"..demoPath.."/assets@../../"..demoPath.."/assets" } end; if _OPTIONS["examples"] and _OPTIONS["jsnative"]==nil then BuildDemo("examples/RotatingCube", "RotatingCube"); BuildDemo("examples/RotatingTexturedCube", "RotatingTexturedCube"); BuildDemo("examples/RotatingTextureAnimatedCube", "RotatingTextureAnimatedCube"); BuildDemo("examples/RotatingCubeWithLighting", "RotatingCubeWithLighting"); BuildDemo("examples/RotatingCubeWithLightingAndShadow", "RotatingCubeWithLightingAndShadow"); BuildDemo("examples/SimplePhysics", "SimplePhysics"); BuildDemo("examples/TextRendering", "TextRendering"); BuildDemo("examples/CustomMaterial", "CustomMaterial"); BuildDemo("examples/PickingPainterMethod", "PickingPainterMethod"); BuildDemo("examples/SkeletonAnimationExample", "SkeletonAnimationExample"); BuildDemo("examples/DepthOfField", "DepthOfField"); BuildDemo("examples/SSAOExample", "SSAOExample"); BuildDemo("examples/DeferredRendering", "DeferredRendering"); BuildDemo("examples/LOD_example", "LOD_example"); BuildDemo("examples/Decals", "Decals"); BuildDemo("examples/IslandDemo", "IslandDemo"); BuildDemo("examples/ParallaxMapping", "ParallaxMapping"); end
------------------------------------------------------------------ -- premake 4 Pyros3D solution ------------------------------------------------------------------ solution "Pyros3D" -- Make Directories os.mkdir("bin"); os.mkdir("build"); os.mkdir("include"); os.mkdir("libs"); newoption { trigger = "jsnative", description = "Build Engine to be used from Javascript - Proof of Concept" } newoption { trigger = "examples", description = "Build Demos Examples" } newoption { trigger = "log", value = "OUTPUT", description = "Log Output", allowed = { { "none", "No log - Default" }, { "console", "Log to Console"}, { "file", "Log to File"} } } if _OPTIONS['jsnative'] then excludes { "**/SDL/**" } else framework = "_SDL"; libsToLink = { "SDL" } end excludes { "**/SFML/**", "**/SDL2/**" } premake.gcc.cc = "emcc"; premake.gcc.cxx = "em++"; ------------------------------------------------------------------ -- setup common settings ------------------------------------------------------------------ configurations { "Debug", "Release" } platforms { "x32" } location "build" rootdir = "." libName = "PyrosEngine" project "PyrosEngine" targetdir "libs" if _OPTIONS["jsnative"] then kind "ConsoleApp" else kind "SharedLib" end language "C++" files { "../../src/**.h", "../../src/**.cpp" } if _OPTIONS["jsnative"] then files { "src/JSNative/JSNative_Wrapper.h", "src/JSNative/JSNative_Wrapper.cpp" } end includedirs { "../../include/", "include/" } defines({"UNICODE", "LODEPNG", "GLES2", "EMSCRIPTEN"}) if _OPTIONS["jsnative"]==nil then defines({framework}) end if _OPTIONS["log"]=="console" then defines({"LOG_TO_CONSOLE"}) else if _OPTIONS["log"]=="file" then defines({"LOG_TO_FILE"}) else defines({"LOG_DISABLE"}) end end if _OPTIONS["jsnative"] then configuration "Debug" targetname(libName.."d.js") defines({"_DEBUG"}) flags { "Symbols" } targetdir ("bin") links { "BulletDynamics", "BulletCollision", "LinearMath", "freetype" } linkoptions { "-L../libs", "--post-js ../src/JSNative/glue.js" } configuration "Release" flags { "Optimize" } targetname(libName..".js") targetdir ("bin") links { "BulletDynamics", "BulletCollision", "LinearMath", "freetype" } linkoptions { "-L../libs", "--post-js ../src/JSNative/glue.js" } else configuration "Debug" targetname(libName.."d") defines({"_DEBUG"}) flags { "Symbols" } configuration "Release" flags { "Optimize" } targetname(libName) end function BuildDemo(demoPath, demoName) project (demoName) kind "ConsoleApp" language "C++" targetname(demoName..".html") files { demoPath.."/**.h", demoPath.."/**.cpp", demoPath.."/../WindowManagers/**.cpp", demoPath.."/../WindowManagers/**.h", demoPath.."/../MainProgram.cpp" } excludes { demoPath.."/../WindowManagers/SDL2/**" } excludes { demoPath.."/../WindowManagers/SFML/**" } includedirs { "../../include/", "include/", "../../src/" } defines({"UNICODE", "GLEW_STATIC", "GLES2", "EMSCRIPTEN"}) defines({framework}); defines({"DEMO_NAME="..demoName, "_"..demoName}) configuration "Debug" defines({"_DEBUG"}) targetdir ("bin") links { libName.."d", "BulletDynamics", "BulletCollision", "LinearMath", "freetype" } linkoptions { "-L../libs" } flags { "Symbols" } linkoptions { "--preload-file ../"..demoPath.."/assets@../../"..demoPath.."/assets" } configuration "Release" targetdir ("bin") links { libName, "BulletDynamics", "BulletCollision", "LinearMath", "freetype" } linkoptions { "-L../libs" } flags { "Optimize" } linkoptions { "--preload-file ../"..demoPath.."/assets@../../"..demoPath.."/assets" } end; if _OPTIONS["examples"] and _OPTIONS["jsnative"]==nil then BuildDemo("../../examples/RotatingCube", "RotatingCube"); BuildDemo("../../examples/RotatingTexturedCube", "RotatingTexturedCube"); BuildDemo("../../examples/RotatingTextureAnimatedCube", "RotatingTextureAnimatedCube"); BuildDemo("../../examples/RotatingCubeWithLighting", "RotatingCubeWithLighting"); BuildDemo("../../examples/RotatingCubeWithLightingAndShadow", "RotatingCubeWithLightingAndShadow"); BuildDemo("../../examples/SimplePhysics", "SimplePhysics"); BuildDemo("../../examples/TextRendering", "TextRendering"); BuildDemo("../../examples/CustomMaterial", "CustomMaterial"); BuildDemo("../../examples/PickingPainterMethod", "PickingPainterMethod"); BuildDemo("../../examples/SkeletonAnimationExample", "SkeletonAnimationExample"); BuildDemo("../../examples/DepthOfField", "DepthOfField"); BuildDemo("../../examples/SSAOExample", "SSAOExample"); BuildDemo("../../examples/DeferredRendering", "DeferredRendering"); BuildDemo("../../examples/LOD_example", "LOD_example"); BuildDemo("../../examples/Decals", "Decals"); BuildDemo("../../examples/IslandDemo", "IslandDemo"); BuildDemo("../../examples/ParallaxMapping", "ParallaxMapping"); end
Fixed emscripten premake file
Fixed emscripten premake file
Lua
mit
Peixinho/Pyros3D,Peixinho/Pyros3D,Peixinho/Pyros3D
e30b563a3b75604cb111a98ecdde8b0f29201885
Peripherals/Keyboard.lua
Peripherals/Keyboard.lua
local events = require("Engine.events") return function(config) --A function that creates a new Keyboard peripheral. local OSX = (love.system.getOS() == "OS X") if config._SpaceWalkthrough then events.register("love:keypressed",function(key,sc,isrepeat) if key == "space" then events.trigger("love:textinput"," ") end end) end if config._Android then events.register("love:textinput",function(t) events.trigger("love:keypressed",string.lower(t),string.lower(t)) events.trigger("love:keyreleased",string.lower(t),string.lower(t)) end) end if config.CPUKit then --Register Keyboard events local cpukit = config.CPUKit events.register("love:keypressed", function(k,...) if OSX then if k == "lgui" then cpukit.triggerEvent("keypressed","lctrl",...) elseif k == "rgui" then cpukit.triggerEvent("keypressed","rctrl",...) elseif love.keyboard.isDown("lalt","ralt") and love.keyboard.isDown("backspace") then cpukit.triggerEvent("keyreleased", "delete",...) end end cpukit.triggerEvent("keypressed",k,...) end) events.register("love:keyreleased", function(k,...) if OSX then if k == "lgui" then cpukit.triggerEvent("keyreleased","lctrl",...) elseif k == "rgui" then cpukit.triggerEvent("keyreleased","rctrl",...) elseif love.keyboard.isDown("lalt","ralt") and love.keyboard.isDown("backspace") then cpukit.triggerEvent("keyreleased", "delete",...) end end cpukit.triggerEvent("keyreleased",k,...) end) local gpukit = config.GPUKit --The hook the textinput for feltering characters not in the font events.register("love:textinput",function(text) local text_escaped = text:gsub("[%(%)%.%%%+%-%*%?%[%]%^%$]", "%%%1") if #text == 1 and ((not gpukit) or gpukit._FontChars:find(text_escaped)) then cpukit.triggerEvent("textinput",text) end end) end --The api starts here-- local KB = {} function KB.textinput(state) if type(state) ~= "nil" then love.keyboard.setTextInput(state or config._EXKB) else return love.keyboard.getTextInput() end end function KB.keyrepeat(state) if type(state) ~= "nil" then love.keyboard.setKeyRepeat(state) else return love.keyboard.getKeyRepeat() end end function KB.keytoscancode(key) if type(key) ~= "string" then return false, "Key must be a string, provided: "..type(key) end --Error local ok, err = pcall(love.keyboard.getScancodeFromKey, key) if ok then return err else return error(err) end end function KB.scancodetokey(scancode) if type(scancode) ~= "string" then return false, "Scancode must be a string, provided: "..type(scancode) end --Error local ok, err = pcall(love.keyboard.getKeyFromScancode, scancode) if ok then return err else return error(err) end end function KB.isKDown(...) if love.keyboard.isDown(...) then return true end if OSX then for i=1, select("#", ...) do if select(i, ...) == "lctrl" and love.keyboard.isDown("lgui") then return true elseif select(i, ...) == "rctrl" and love.keyboard.isDown("rgui") then return true elseif select(i, ...) == "delete" and love.keyboard.isDown("ralt", "lalt") and love.keyboard.isDown("backspace") then return true end end end return false end return KB end
local events = require("Engine.events") return function(config) --A function that creates a new Keyboard peripheral. local OSX = (love.system.getOS() == "OS X") if config._SpaceWalkthrough then events.register("love:keypressed",function(key,sc,isrepeat) if key == "space" then events.trigger("love:textinput"," ") end end) end if config._Android then events.register("love:textinput",function(t) events.trigger("love:keypressed",string.lower(t),string.lower(t)) events.trigger("love:keyreleased",string.lower(t),string.lower(t)) end) end if config.CPUKit then --Register Keyboard events local cpukit = config.CPUKit events.register("love:keypressed", function(k,...) if OSX then if k == "lgui" then cpukit.triggerEvent("keypressed","lctrl",...) elseif k == "rgui" then cpukit.triggerEvent("keypressed","rctrl",...) elseif love.keyboard.isDown("lalt","ralt") and k == "backspace" then cpukit.triggerEvent("keyreleased", "delete",...) end end cpukit.triggerEvent("keypressed",k,...) end) events.register("love:keyreleased", function(k,...) if OSX then if k == "lgui" then cpukit.triggerEvent("keyreleased","lctrl",...) elseif k == "rgui" then cpukit.triggerEvent("keyreleased","rctrl",...) elseif love.keyboard.isDown("lalt","ralt") and k == "backspace" then cpukit.triggerEvent("keyreleased", "delete",...) end end cpukit.triggerEvent("keyreleased",k,...) end) local gpukit = config.GPUKit --The hook the textinput for feltering characters not in the font events.register("love:textinput",function(text) local text_escaped = text:gsub("[%(%)%.%%%+%-%*%?%[%]%^%$]", "%%%1") if #text == 1 and ((not gpukit) or gpukit._FontChars:find(text_escaped)) then cpukit.triggerEvent("textinput",text) end end) end --The api starts here-- local KB = {} function KB.textinput(state) if type(state) ~= "nil" then love.keyboard.setTextInput(state or config._EXKB) else return love.keyboard.getTextInput() end end function KB.keyrepeat(state) if type(state) ~= "nil" then love.keyboard.setKeyRepeat(state) else return love.keyboard.getKeyRepeat() end end function KB.keytoscancode(key) if type(key) ~= "string" then return false, "Key must be a string, provided: "..type(key) end --Error local ok, err = pcall(love.keyboard.getScancodeFromKey, key) if ok then return err else return error(err) end end function KB.scancodetokey(scancode) if type(scancode) ~= "string" then return false, "Scancode must be a string, provided: "..type(scancode) end --Error local ok, err = pcall(love.keyboard.getKeyFromScancode, scancode) if ok then return err else return error(err) end end function KB.isKDown(...) if love.keyboard.isDown(...) then return true end if OSX then for i=1, select("#", ...) do if select(i, ...) == "lctrl" and love.keyboard.isDown("lgui") then return true elseif select(i, ...) == "rctrl" and love.keyboard.isDown("rgui") then return true elseif select(i, ...) == "delete" and love.keyboard.isDown("ralt", "lalt") and k == "backspace" then return true end end end return false end return KB end
fixed if conditions
fixed if conditions
Lua
mit
RamiLego4Game/LIKO-12
98973775e85db5fd2a49ddeb1bcbce949a35f43b
src/rxbinderutils/src/Shared/RxBinderUtils.lua
src/rxbinderutils/src/Shared/RxBinderUtils.lua
--[=[ Utility methods to observe bound objects on instances. This is what makes the Rx library with binders really good. :::info Using this API, you can query most game-state in very efficient ways, and react to the world changing in real-time. This makes programming streaming and other APIs really nice. ::: @class RxBinderUtils ]=] local require = require(script.Parent.loader).load(script) local Binder = require("Binder") local Brio = require("Brio") local Maid = require("Maid") local Observable = require("Observable") local Rx = require("Rx") local RxBrioUtils = require("RxBrioUtils") local RxInstanceUtils = require("RxInstanceUtils") local RxLinkUtils = require("RxLinkUtils") local RxBinderUtils = {} --[=[ Observes a structure where a parent has object values with linked objects (for example), maybe an AI has a list of linked objectvalue tasks to execute. @param linkName string @param parent Instance @param binder Binder<T> @return Observable<Brio<T>> ]=] function RxBinderUtils.observeLinkedBoundClassBrio(linkName, parent, binder) assert(type(linkName) == "string", "Bad linkName") assert(typeof(parent) == "Instance", "Bad parent") assert(Binder.isBinder(binder), "Bad binder") return RxLinkUtils.observeValidLinksBrio(linkName, parent) :Pipe({ RxBrioUtils.flatMapBrio(function(_, linkValue) return RxBinderUtils.observeBoundClassBrio(binder, linkValue) end); }); end --[=[ Observes bound children classes. @param binder Binder<T> @param instance Instance @return Observable<Brio<T>> ]=] function RxBinderUtils.observeBoundChildClassBrio(binder, instance) assert(Binder.isBinder(binder), "Bad binder") assert(typeof(instance) == "Instance", "Bad instance") return RxInstanceUtils.observeChildrenBrio(instance) :Pipe({ RxBrioUtils.flatMapBrio(function(child) return RxBinderUtils.observeBoundClassBrio(binder, child) end); }) end --[=[ Observes ainstance's parent class that is bound. @param binder Binder<T> @param instance Instance @return Observable<Brio<T>> ]=] function RxBinderUtils.observeBoundParentClassBrio(binder, instance) assert(Binder.isBinder(binder), "Bad binder") assert(typeof(instance) == "Instance", "Bad instance") return RxInstanceUtils.observePropertyBrio(instance, "Parent") :Pipe({ RxBrioUtils.switchMapBrio(function(child) if child then return RxBinderUtils.observeBoundClassBrio(binder, child) else return Rx.EMPTY end end); }) end --[=[ Observes all bound classes that hit that list of binders @param binders { Binder<T> } @param instance Instance @return Observable<Brio<T>> ]=] function RxBinderUtils.observeBoundChildClassesBrio(binders, instance) assert(type(binders) == "table", "Bad binders") assert(typeof(instance) == "Instance", "Bad instance") return RxInstanceUtils.observeChildrenBrio(instance) :Pipe({ RxBrioUtils.flatMapBrio(function(child) return RxBinderUtils.observeBoundClassesBrio(binders, child) end); }) end --[=[ Observes a bound class on a given instance. @param binder Binder<T> @param instance Instance @return Observable<T?> ]=] function RxBinderUtils.observeBoundClass(binder, instance) assert(type(binder) == "table", "Bad binder") assert(typeof(instance) == "Instance", "Bad instance") return Observable.new(function(sub) local maid = Maid.new() maid:GiveTask(binder:ObserveInstance(instance, function(...) sub:Fire(...) end)) sub:Fire(binder:Get(instance)) return maid end) end --[=[ Observes a bound class on a given instance. @param binder Binder<T> @param instance Instance @return Observable<Brio<T>> ]=] function RxBinderUtils.observeBoundClassBrio(binder, instance) assert(type(binder) == "table", "Bad binder") assert(typeof(instance) == "Instance", "Bad instance") return Observable.new(function(sub) local maid = Maid.new() local function handleClassChanged(class) if class then local brio = Brio.new(class) maid._lastBrio = brio sub:Fire(brio) else maid._lastBrio = nil end end maid:GiveTask(binder:ObserveInstance(instance, handleClassChanged)) handleClassChanged(binder:Get(instance)) return maid end) end --[=[ Observes all bound classes for a given binder. @param binders { Binder<T> } @param instance Instance @return Observable<Brio<T>> ]=] function RxBinderUtils.observeBoundClassesBrio(binders, instance) assert(type(binders) == "table", "Bad binders") assert(typeof(instance) == "Instance", "Bad instance") local observables = {} for _, binder in pairs(binders) do table.insert(observables, RxBinderUtils.observeBoundClassBrio(binder, instance)) end return Rx.of(unpack(observables)):Pipe({ Rx.mergeAll(); }) end --[=[ Observes all instances bound to a given binder. @param binder Binder @return Observable<Brio<T>> ]=] function RxBinderUtils.observeAllBrio(binder) assert(Binder.isBinder(binder), "Bad binder") return Observable.new(function(sub) local maid = Maid.new() local function handleNewClass(class) local brio = Brio.new(class) maid[class] = brio sub:Fire(brio) end maid:GiveTask(binder:GetClassAddedSignal():Connect(handleNewClass)) maid:GiveTask(binder:GetClassRemovingSignal():Connect(function(class) maid[class] = nil end)) for class, _ in pairs(binder:GetAllSet()) do handleNewClass(class) end return maid end) end return RxBinderUtils
--[=[ Utility methods to observe bound objects on instances. This is what makes the Rx library with binders really good. :::info Using this API, you can query most game-state in very efficient ways, and react to the world changing in real-time. This makes programming streaming and other APIs really nice. ::: @class RxBinderUtils ]=] local require = require(script.Parent.loader).load(script) local Binder = require("Binder") local Brio = require("Brio") local Maid = require("Maid") local Observable = require("Observable") local Rx = require("Rx") local RxBrioUtils = require("RxBrioUtils") local RxInstanceUtils = require("RxInstanceUtils") local RxLinkUtils = require("RxLinkUtils") local RxBinderUtils = {} --[=[ Observes a structure where a parent has object values with linked objects (for example), maybe an AI has a list of linked objectvalue tasks to execute. @param linkName string @param parent Instance @param binder Binder<T> @return Observable<Brio<T>> ]=] function RxBinderUtils.observeLinkedBoundClassBrio(linkName, parent, binder) assert(type(linkName) == "string", "Bad linkName") assert(typeof(parent) == "Instance", "Bad parent") assert(Binder.isBinder(binder), "Bad binder") return RxLinkUtils.observeValidLinksBrio(linkName, parent) :Pipe({ RxBrioUtils.flatMapBrio(function(_, linkValue) return RxBinderUtils.observeBoundClassBrio(binder, linkValue) end); }); end --[=[ Observes bound children classes. @param binder Binder<T> @param instance Instance @return Observable<Brio<T>> ]=] function RxBinderUtils.observeBoundChildClassBrio(binder, instance) assert(Binder.isBinder(binder), "Bad binder") assert(typeof(instance) == "Instance", "Bad instance") return RxInstanceUtils.observeChildrenBrio(instance) :Pipe({ RxBrioUtils.flatMapBrio(function(child) return RxBinderUtils.observeBoundClassBrio(binder, child) end); }) end --[=[ Observes ainstance's parent class that is bound. @param binder Binder<T> @param instance Instance @return Observable<Brio<T>> ]=] function RxBinderUtils.observeBoundParentClassBrio(binder, instance) assert(Binder.isBinder(binder), "Bad binder") assert(typeof(instance) == "Instance", "Bad instance") return RxInstanceUtils.observePropertyBrio(instance, "Parent") :Pipe({ RxBrioUtils.switchMapBrio(function(child) if child then return RxBinderUtils.observeBoundClassBrio(binder, child) else return Rx.EMPTY end end); }) end --[=[ Observes all bound classes that hit that list of binders @param binders { Binder<T> } @param instance Instance @return Observable<Brio<T>> ]=] function RxBinderUtils.observeBoundChildClassesBrio(binders, instance) assert(type(binders) == "table", "Bad binders") assert(typeof(instance) == "Instance", "Bad instance") return RxInstanceUtils.observeChildrenBrio(instance) :Pipe({ RxBrioUtils.flatMapBrio(function(child) return RxBinderUtils.observeBoundClassesBrio(binders, child) end); }) end --[=[ Observes a bound class on a given instance. @param binder Binder<T> @param instance Instance @return Observable<T?> ]=] function RxBinderUtils.observeBoundClass(binder, instance) assert(Binder.isBinder(binder), "Bad binder") assert(typeof(instance) == "Instance", "Bad instance") return Observable.new(function(sub) local maid = Maid.new() maid:GiveTask(binder:ObserveInstance(instance, function(...) sub:Fire(...) end)) sub:Fire(binder:Get(instance)) return maid end) end --[=[ Observes a bound class on a given instance. @param binder Binder<T> @param instance Instance @return Observable<Brio<T>> ]=] function RxBinderUtils.observeBoundClassBrio(binder, instance) assert(Binder.isBinder(binder), "Bad binder") assert(typeof(instance) == "Instance", "Bad instance") return Observable.new(function(sub) local maid = Maid.new() local function handleClassChanged(class) if class then local brio = Brio.new(class) maid._lastBrio = brio sub:Fire(brio) else maid._lastBrio = nil end end maid:GiveTask(binder:ObserveInstance(instance, handleClassChanged)) handleClassChanged(binder:Get(instance)) return maid end) end --[=[ Observes all bound classes for a given binder. @param binders { Binder<T> } @param instance Instance @return Observable<Brio<T>> ]=] function RxBinderUtils.observeBoundClassesBrio(binders, instance) assert(type(binders) == "table", "Bad binders") assert(typeof(instance) == "Instance", "Bad instance") local observables = {} for _, binder in pairs(binders) do table.insert(observables, RxBinderUtils.observeBoundClassBrio(binder, instance)) end return Rx.of(unpack(observables)):Pipe({ Rx.mergeAll(); }) end --[=[ Observes all instances bound to a given binder. @param binder Binder @return Observable<Brio<T>> ]=] function RxBinderUtils.observeAllBrio(binder) assert(Binder.isBinder(binder), "Bad binder") return Observable.new(function(sub) local maid = Maid.new() local function handleNewClass(class) local brio = Brio.new(class) maid[class] = brio sub:Fire(brio) end maid:GiveTask(binder:GetClassAddedSignal():Connect(handleNewClass)) maid:GiveTask(binder:GetClassRemovingSignal():Connect(function(class) maid[class] = nil end)) for class, _ in pairs(binder:GetAllSet()) do handleNewClass(class) end return maid end) end return RxBinderUtils
fix: Better errors when not passing a binder into RxBinderUtils
fix: Better errors when not passing a binder into RxBinderUtils
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
035b3b770a0e1d2e3dcad40ddadd04a15d81dce7
src/lunajson/encode.lua
src/lunajson/encode.lua
local byte = string.byte local find = string.find local format = string.format local gsub = string.gsub local match = string.match local rawequal = rawequal local tostring = tostring local pairs = pairs local type = type local function encode(v, nullv) local i = 1 local builder = {} local visited = {} local function f_tostring(v) builder[i] = tostring(v) i = i+1 end local radixmark = match(tostring(0.5), '[^0-9]') local delimmark = match(tostring(123456789.123456789), '[^0-9' .. radixmark .. ']') if radixmark == '.' then radixmark = nil end local f_number = function(n) builder[i] = format("%.17g", n) i = i+1 end if radixmark or delimmark then if radixmark and find(radixmark, '%W') then radixmark = '%' .. radixmark end if delimmark and find(selimmark, '%W') then delimmark = '%' .. delimmark end f_number = function(n) local s = format("%.17g", n) if delimmark then s = gsub(s, delimmark, '') end if radixmark then s = gsub(s, radixmark, '.') end builder[i] = s i = i+1 end end local dodecode local f_string_subst = { ['"'] = '\\"', ['\\'] = '\\\\', ['\b'] = '\\b', ['\f'] = '\\f', ['\n'] = '\\n', ['\r'] = '\\r', ['\t'] = '\\t', __index = function(_, c) return format('\\u00%02X', tostring(byte(c))) end } setmetatable(f_string_subst, f_string_subst) local function f_string(s) -- use the cluttered pattern because lua 5.1 does not handle \0 in a pattern correctly local pat = '[^\32-\33\35-\91\93-\255]' builder[i] = '"' if find(s, pat) then s = gsub(s, pat, f_string_subst) end builder[i+1] = s builder[i+2] = '"' i = i+3 end local function f_table(o) if visited[o] then error("loop detected") end visited[o] = true local alen = o[0] if type(alen) == 'number' then builder[i] = '[' i = i+1 for j = 1, alen do dodecode(o[j]) builder[i] = ',' i = i+1 end if alen > 0 then i = i-1 end builder[i] = ']' i = i+1 return end local v = o[1] if v ~= nil then builder[i] = '[' i = i+1 local j = 2 repeat dodecode(v) v = o[j] if v == nil then break end j = j+1 builder[i] = ',' i = i+1 until false builder[i] = ']' i = i+1 return end builder[i] = '{' i = i+1 local oldi = i for k, v in pairs(o) do if type(k) ~= 'string' then error("non-string key") end f_string(k) builder[i] = ':' i = i+1 dodecode(v) builder[i] = ',' i = i+1 end if i > oldi then i = i-1 end builder[i] = '}' i = i+1 end local dispatcher = { boolean = f_tostring, number = f_tostring, string = f_string, table = arraylen and f_table_arraylen or f_table, __index = function() error("invalid type value") end } setmetatable(dispatcher, dispatcher) function dodecode(v) if rawequal(v, nullv) then builder[i] = 'null' i = i+1 return end dispatcher[type(v)](v) end -- exec dodecode(v) return table.concat(builder) end return { encode = encode }
local byte = string.byte local find = string.find local format = string.format local gsub = string.gsub local match = string.match local rawequal = rawequal local tostring = tostring local pairs = pairs local type = type local function encode(v, nullv) local i = 1 local builder = {} local visited = {} local function f_tostring(v) builder[i] = tostring(v) i = i+1 end local radixmark = match(tostring(0.5), '[^0-9]') local delimmark = match(tostring(123456789.123456789), '[^0-9' .. radixmark .. ']') if radixmark == '.' then radixmark = nil end local f_number = function(n) builder[i] = format("%.17g", n) i = i+1 end if radixmark or delimmark then if radixmark and find(radixmark, '%W') then radixmark = '%' .. radixmark end if delimmark and find(selimmark, '%W') then delimmark = '%' .. delimmark end f_number = function(n) local s = format("%.17g", n) if delimmark then s = gsub(s, delimmark, '') end if radixmark then s = gsub(s, radixmark, '.') end builder[i] = s i = i+1 end end local dodecode local f_string_subst = { ['"'] = '\\"', ['\\'] = '\\\\', ['\b'] = '\\b', ['\f'] = '\\f', ['\n'] = '\\n', ['\r'] = '\\r', ['\t'] = '\\t', __index = function(_, c) return format('\\u00%02X', tostring(byte(c))) end } setmetatable(f_string_subst, f_string_subst) local function f_string(s) -- use the cluttered pattern because lua 5.1 does not handle \0 in a pattern correctly local pat = '[^\32-\33\35-\91\93-\255]' builder[i] = '"' if find(s, pat) then s = gsub(s, pat, f_string_subst) end builder[i+1] = s builder[i+2] = '"' i = i+3 end local function f_table(o) if visited[o] then error("loop detected") end visited[o] = true local tmp = o[0] if type(tmp) == 'number' then -- arraylen available builder[i] = '[' i = i+1 for j = 1, tmp do dodecode(o[j]) builder[i] = ',' i = i+1 end if tmp > 0 then i = i-1 end builder[i] = ']' else tmp = o[1] if tmp ~= nil then -- detected as array builder[i] = '[' i = i+1 local j = 2 repeat dodecode(tmp) tmp = o[j] if tmp == nil then break end j = j+1 builder[i] = ',' i = i+1 until false builder[i] = ']' else -- detected as object builder[i] = '{' i = i+1 local tmp = i for k, v in pairs(o) do if type(k) ~= 'string' then error("non-string key") end f_string(k) builder[i] = ':' i = i+1 dodecode(v) builder[i] = ',' i = i+1 end if i > tmp then i = i-1 end builder[i] = '}' end end i = i+1 visited[o] = nil end local dispatcher = { boolean = f_tostring, number = f_tostring, string = f_string, table = arraylen and f_table_arraylen or f_table, __index = function() error("invalid type value") end } setmetatable(dispatcher, dispatcher) function dodecode(v) if rawequal(v, nullv) then builder[i] = 'null' i = i+1 return end dispatcher[type(v)](v) end -- exec dodecode(v) return table.concat(builder) end return { encode = encode }
fix loop detection
fix loop detection
Lua
mit
bigcrush/lunajson,tst2005/lunajson,csteddy/lunajson,csteddy/lunajson,grafi-tt/lunajson,tst2005/lunajson,grafi-tt/lunajson,grafi-tt/lunajson,bigcrush/lunajson
41dcd79c05c611f95d5cb0bd8af8882f49ef735a
applications/luci-vnstat/luasrc/model/cbi/vnstat.lua
applications/luci-vnstat/luasrc/model/cbi/vnstat.lua
--[[ LuCI - Lua Configuration Interface Copyright 2010-2011 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local utl = require "luci.util" local sys = require "luci.sys" local fs = require "nixio.fs" local nw = require "luci.model.network" local dbdir, line for line in io.lines("/etc/vnstat.conf") do dbdir = line:match("^%s*DatabaseDir%s+[\"'](%S-)[\"']") if dbdir then break end end dbdir = dbdir or "/var/lib/vnstat" m = Map("vnstat", translate("VnStat"), translate("VnStat is a network traffic monitor for Linux that keeps a log of network traffic for the selected interface(s).")) m.submit = translate("Restart VnStat") m.reset = false nw.init(luci.model.uci.cursor_state()) local ifaces = { } local enabled = { } local iface for iface in fs.dir(dbdir) do if iface:sub(1,1) ~= '.' then ifaces[iface] = iface enabled[iface] = iface end end for _, iface in ipairs(sys.net.devices()) do ifaces[iface] = iface end local s = m:section(TypedSection, "vnstat") s.anonymous = true s.addremove = false mon_ifaces = s:option(Value, "interface", translate("Monitor selected interfaces")) mon_ifaces.template = "cbi/network_ifacelist" mon_ifaces.widget = "checkbox" mon_ifaces.cast = "table" function mon_ifaces.write(self, section, val) local i local s = { } if val then for _, i in ipairs(type(val) == "table" and val or { val }) do s[i] = true end end for i, _ in pairs(ifaces) do if not s[i] then fs.unlink(dbdir .. "/" .. i) fs.unlink(dbdir .. "/." .. i) end end if next(s) then m.uci:set_list("vnstat", section, "interface", utl.keys(s)) else m.uci:delete("vnstat", section, "interface") end end mon_ifaces.remove = mon_ifaces.write return m
--[[ LuCI - Lua Configuration Interface Copyright 2010-2011 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local utl = require "luci.util" local sys = require "luci.sys" local fs = require "nixio.fs" local nw = require "luci.model.network" local dbdir, line for line in io.lines("/etc/vnstat.conf") do dbdir = line:match("^%s*DatabaseDir%s+[\"'](%S-)[\"']") if dbdir then break end end dbdir = dbdir or "/var/lib/vnstat" m = Map("vnstat", translate("VnStat"), translate("VnStat is a network traffic monitor for Linux that keeps a log of network traffic for the selected interface(s).")) m.submit = translate("Restart VnStat") m.reset = false nw.init(luci.model.uci.cursor_state()) local ifaces = { } local enabled = { } local iface if fs.access(dbdir) then for iface in fs.dir(dbdir) do if iface:sub(1,1) ~= '.' then ifaces[iface] = iface enabled[iface] = iface end end end for _, iface in ipairs(sys.net.devices()) do ifaces[iface] = iface end local s = m:section(TypedSection, "vnstat") s.anonymous = true s.addremove = false mon_ifaces = s:option(Value, "interface", translate("Monitor selected interfaces")) mon_ifaces.template = "cbi/network_ifacelist" mon_ifaces.widget = "checkbox" mon_ifaces.cast = "table" function mon_ifaces.write(self, section, val) local i local s = { } if val then for _, i in ipairs(type(val) == "table" and val or { val }) do s[i] = true end end for i, _ in pairs(ifaces) do if not s[i] then fs.unlink(dbdir .. "/" .. i) fs.unlink(dbdir .. "/." .. i) end end if next(s) then m.uci:set_list("vnstat", section, "interface", utl.keys(s)) else m.uci:delete("vnstat", section, "interface") end end mon_ifaces.remove = mon_ifaces.write return m
applications/luci-vnstat: fix crash if dbdir is defined but not existing yet
applications/luci-vnstat: fix crash if dbdir is defined but not existing yet
Lua
apache-2.0
deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,8devices/luci,deepak78/luci
b0d1f6bb0d2fe3164f412cfdbc792e8798063c93
app/object.lua
app/object.lua
--[[ file: app/object.lua desc: Manage object storage ]] --localize luawa local database, user = luawa.database, luawa.user --oxy.object local object = { cache = {} } --new object 'factory' function object:new( type ) if not oxy.config.objects[type] then return false end --create new object, set type local object = { type = type, module = oxy.config.objects[type].module, cache = {} } --if custom fields for lists, load default (id, owners, name) object.fields = oxy.config.objects[type].fields or '*' --make object use self as index self.__index = self setmetatable( object, self ) --this + above essentially makes object inherit self's methods --return the new object class w/ type set return object end --fetch an object as lua object (NO permission checks - ie internal) function object:fetch( id, prepare, fields ) if self.cache[id] then return self.cache[id] end --cache cleared at end of every request? fields = fields or 'id, name' --get object from mysql (get all fields - assume need all on fetch) local object, err = database:select( self.module .. '_' .. self.type, fields, { id = id }, order, limit, offset ) --if we got none back if #object ~= 1 then err = 'No ' .. self.type .. ' found' return false, err end object = object[1] --load the object 'class' according to type local type = require( oxy.config.root .. 'modules/' .. self.module .. '/object/' .. self.type ) --set our new objects index to that of the type type.__index = type setmetatable( object, type ) --this + above essentially makes object inherit type's methods --run any prepare function if prepare and object.prepare then object:prepare() end --add to our cache self.cache[id] = object return object end --get an object w/ permission check on active user function object:get( id, permission ) --permission permission = permission or 'view' --not logged in? if not user:checkLogin() then return false, 'You need to be logged in' end --we got permission? if not self:permission( id, permission ) then return false, 'You do not have permission to ' .. permission .. ' this ' .. self.type end --fetch! return self:fetch( id, true, '*' ) end --check current user permissions on object (Admin, View, Edit) function object:permission( id, permission ) --not logged in? if not user:checkLogin() then return false end --permission to any if user:checkPermission( permission .. 'Any' .. self.type ) then return true end --permission to owned if user:checkPermission( permission .. 'Own' .. self.type ) then local test = database:select( self.module .. '_' .. self.type, 'id', { id = id, { user_id = user:getData().id, group_id = user:getData().group } }, 'id ASC', 1 ) if #test == 1 then return true end end --default response return false end --get all objects (mysql list only) function object:getAll( wheres, order, limit, offset ) return self:getList( wheres, order, limit, offset, true ) end --get all owned objects (mysql list only) function object:getOwned( wheres, order, limit, offset ) return self:getList( wheres, order, limit, offset ) end --get list of objects from mysql (DRY, see above) function object:getList( wheres, order, limit, offset, all ) --not logged in? if not user:checkLogin() then return false, 'You need to be logged in' end --type edit/delete permissions local type, edit, delete, ownedit, owndelete = self.type, false, false, false, false wheres = wheres or {} --are we looking for all objects, or just owned if all then --do we have permission to ViewAny<Object> if not user:checkPermission( 'ViewAny' .. type ) then return false, 'You do not have permission view all ' .. type .. 's' end if user:checkPermission( 'EditAny' .. type ) then edit = true end if user:checkPermission( 'EditOwn' .. type ) then ownedit = true end if user:checkPermission( 'DeleteAny' .. type ) then delete = true end if user:checkPermission( 'DeleteOwn' .. type ) then owndelete = true end else --do we have permission to ViewOwn<Object> if not user:checkPermission( 'ViewOwn' .. type ) then return false, 'You do not have permission view owned ' .. type .. 's' end if user:checkPermission( 'EditOwn' .. type ) then edit = true end if user:checkPermission( 'DeleteOwn' .. type ) then delete = true end --make sure we match user or group id table.insert( wheres, { user_id = user:getData().id, group_id = user:getData().group } ) end --get objects from mysql (only get fields needed for lists) local objects = database:select( self.module .. '_' .. self.type, self.fields, wheres, order, limit, offset ) --assign edit & delete permissions for k, object in pairs( objects ) do object.permissions = { edit = edit, delete = delete } if all and ( object.user_id == user:getData().id or object.group_id == user:getData().group ) then if not delete then object.permissions.delete = owndelete end if not edit then object.permissions.edit = ownedit end end end return objects end return object
--[[ file: app/object.lua desc: Manage object storage ]] --localize luawa local database, user = luawa.database, luawa.user --oxy.object local object = {} --new object 'factory' function object:new( type ) if not oxy.config.objects[type] then return false end --create new object, set type local object = { type = type, module = oxy.config.objects[type].module, cache = {} } --if custom fields for lists object.fields = oxy.config.objects[type].fields or '*' --make object use self as index self.__index = self setmetatable( object, self ) --this + above essentially makes object inherit self/object's methods --return the new object class w/ type set return object end --fetch an object as lua object (NO permission checks - ie internal) function object:fetch( id, prepare, fields ) fields = fields or 'id, name' --get object from mysql (get all fields - assume need all on fetch) local object, err = database:select( self.module .. '_' .. self.type, fields, { id = id }, order, limit, offset ) --if we got none back if #object ~= 1 then err = 'No ' .. self.type .. ' found' return false, err end object = object[1] --load the object 'class' according to type local type = require( oxy.config.root .. 'modules/' .. self.module .. '/object/' .. self.type ) --set our new objects index to that of the type type.__index = type setmetatable( object, type ) --this + above essentially makes object inherit type's methods --helper functions local this = self --edit object details in database & as object object._edit = function( self, data ) if not this:permission( self.id, 'edit' ) then return false, 'You do not have permission to edit this ' .. this.type end for key, value in pairs( data ) do self[key] = value end --update database local update, err = database:update( this.module .. '_' .. this.type, data, { id = self.id } ) return update, err end --delete the object object._delete = function( self ) return this:delete( self.id ) end --run any prepare function if prepare and object.prepare then object:prepare() end return object end --get an object w/ permission check on active user function object:get( id, permission ) --permission permission = permission or 'view' --not logged in? if not user:checkLogin() then return false, 'You need to be logged in' end --we got permission? if not self:permission( id, permission ) then return false, 'You do not have permission to ' .. permission .. ' this ' .. self.type end --fetch! return self:fetch( id, true, '*' ) end --check current user permissions on object (Admin, View, Edit) function object:permission( id, permission ) --not logged in? if not user:checkLogin() then return false end --permission to any if user:checkPermission( permission .. 'Any' .. self.type ) then return true end --permission to owned if user:checkPermission( permission .. 'Own' .. self.type ) then local test = database:select( self.module .. '_' .. self.type, 'id', { id = id, { user_id = user:getData().id, group_id = user:getData().group } }, 'id ASC', 1 ) if #test == 1 then return true end end --default response return false end --delete (mysql only) function object:delete( id ) --we got permission? if not self:permission( id, 'delete' ) then return false, 'You do not have permission to delete this ' .. self.type end --delete local delete, err = database:delete( self.module .. '_' .. self.type, { id = id }, 1 ) return delete, err end --get all objects (mysql list only) function object:getAll( wheres, order, limit, offset ) return self:getList( wheres, order, limit, offset, true ) end --get all owned objects (mysql list only) function object:getOwned( wheres, order, limit, offset ) return self:getList( wheres, order, limit, offset ) end --get list of objects from mysql (DRY, see above) function object:getList( wheres, order, limit, offset, all ) --not logged in? if not user:checkLogin() then return false, 'You need to be logged in' end --type edit/delete permissions local type, edit, delete, ownedit, owndelete = self.type, false, false, false, false wheres = wheres or {} --are we looking for all objects, or just owned if all then --do we have permission to ViewAny<Object> if not user:checkPermission( 'ViewAny' .. type ) then return false, 'You do not have permission view all ' .. type .. 's' end if user:checkPermission( 'EditAny' .. type ) then edit = true end if user:checkPermission( 'EditOwn' .. type ) then ownedit = true end if user:checkPermission( 'DeleteAny' .. type ) then delete = true end if user:checkPermission( 'DeleteOwn' .. type ) then owndelete = true end else --do we have permission to ViewOwn<Object> if not user:checkPermission( 'ViewOwn' .. type ) then return false, 'You do not have permission view owned ' .. type .. 's' end if user:checkPermission( 'EditOwn' .. type ) then edit = true end if user:checkPermission( 'DeleteOwn' .. type ) then delete = true end --make sure we match user or group id table.insert( wheres, { user_id = user:getData().id, group_id = user:getData().group } ) end --get objects from mysql (only get fields needed for lists) local objects = database:select( self.module .. '_' .. self.type, self.fields, wheres, order, limit, offset ) --assign edit & delete permissions for k, object in pairs( objects ) do object.permissions = { edit = edit, delete = delete } if all and ( object.user_id == user:getData().id or object.group_id == user:getData().group ) then if not delete then object.permissions.delete = owndelete end if not edit then object.permissions.edit = ownedit end end end return objects end return object
Add object:_edit and object:_delete helper functions, remove object cache (bug on updates as not shared between workers)
Add object:_edit and object:_delete helper functions, remove object cache (bug on updates as not shared between workers)
Lua
mit
Oxygem/Oxycore,Oxygem/Oxycore,Oxygem/Oxycore
7446da88a7f9e0feb5d21f55e061673d26cbd701
spec/area/surface_spec.lua
spec/area/surface_spec.lua
require 'spec/defines' require 'stdlib/area/surface' describe('Surface Spec', function() describe('Surface lookups', function() it('should work with no parameters', function() assert.same({ }, Surface.lookup()) end) it('should work with string parameters', function() _G["game"] = { surfaces = { nauvis = { __self = 0, name = 'nauvis' } } } assert.same({ game.surfaces['nauvis'] }, Surface.lookup('nauvis')) assert.same({ }, Surface.lookup('foo')) end) it('should work with object parameters', function() _G["game"] = { surfaces = { nauvis = { __self = 0, name = 'nauvis' } } } assert.same({ game.surfaces['nauvis'] }, Surface.lookup(game.surfaces['nauvis'])) end) it('should work with table parameters', function() _G["game"] = { surfaces = { nauvis = { __self = 0, name = 'nauvis' } } } assert.same({ }, Surface.lookup({})) assert.same({ game.surfaces['nauvis'] }, Surface.lookup({ 'nauvis' })) assert.same({ game.surfaces['nauvis'] }, Surface.lookup({ 'nauvis', 'foo', 'bar' })) assert.same({ game.surfaces['nauvis'] }, Surface.lookup({ game.surfaces['nauvis'] })) end) end) end)
require 'spec/defines' require 'stdlib/area/surface' describe('Surface Spec', function() describe('Surface lookups', function() it('should work with no parameters', function() assert.same({ }, Surface.lookup()) end) it('should work with string parameters', function() _G["game"] = { surfaces = { nauvis = { __self = 0 } } } setmetatable(game.surfaces['nauvis'], { __index = { name = 'nauvis'}}) assert.same({ game.surfaces['nauvis'] }, Surface.lookup('nauvis')) assert.same({ }, Surface.lookup('foo')) end) it('should work with object parameters', function() _G["game"] = { surfaces = { nauvis = { __self = 0 } } } setmetatable(game.surfaces['nauvis'], { __index = { name = 'nauvis'}}) assert.same({ game.surfaces['nauvis'] }, Surface.lookup(game.surfaces['nauvis'])) end) it('should work with table parameters', function() _G["game"] = { surfaces = { nauvis = { __self = 0 } } } setmetatable(game.surfaces['nauvis'], { __index = { name = 'nauvis'}}) assert.same({ }, Surface.lookup({})) assert.same({ game.surfaces['nauvis'] }, Surface.lookup({ 'nauvis' })) assert.same({ game.surfaces['nauvis'] }, Surface.lookup({ 'nauvis', 'foo', 'bar' })) assert.same({ game.surfaces['nauvis'] }, Surface.lookup({ game.surfaces['nauvis'] })) end) end) end)
Fix surface spec test to correctly mock factorio objects
Fix surface spec test to correctly mock factorio objects
Lua
isc
Afforess/Factorio-Stdlib
76ff4b7dcdbd0ee9300fffc179af50d992b59b01
deployment_scripts/puppet/modules/lma_collector/files/plugins/filters/influxdb_accumulator.lua
deployment_scripts/puppet/modules/lma_collector/files/plugins/filters/influxdb_accumulator.lua
-- Copyright 2015 Mirantis, Inc. -- -- 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. require 'cjson' require 'os' require 'string' require 'table' local field_util = require 'field_util' local utils = require 'lma_utils' local l = require 'lpeg' l.locale(l) local flush_count = read_config('flush_count') or 100 local flush_interval = read_config('flush_interval') or 5 local default_tenant_id = read_config("default_tenant_id") local default_user_id = read_config("default_user_id") local time_precision = read_config("time_precision") -- the tag_fields parameter is a list of tags separated by spaces local tag_grammar = l.Ct((l.C((l.P(1) - l.P" ")^1) * l.P" "^0)^0) local tag_fields = tag_grammar:match(read_config("tag_fields") or "") local defaults = { tenant_id=default_tenant_id, user_id=default_user_id, } local last_flush = os.time() local datapoints = {} function escape_string(str) return tostring(str):gsub("([ ,])", "\\%1") end -- Flush the datapoints to InfluxDB if enough items are present or if the -- timeout has expired function flush () local now = os.time() if #datapoints > 0 and (#datapoints > flush_count or now - last_flush > flush_interval) then datapoints[#datapoints+1] = '' utils.safe_inject_payload("txt", "influxdb", table.concat(datapoints, "\n")) datapoints = {} last_flush = now end end -- Return the Payload field decoded as JSON data, nil if the payload isn't a -- valid JSON string function decode_json_payload() local ok, data = pcall(cjson.decode, read_message("Payload")) if not ok then return end return data end function process_single_metric() local tags = {} local name = read_message("Fields[name]") local value if not name then return 'Fields[name] is missing' end if read_message('Type'):match('multivalue_metric$') then value = decode_json_payload() if not value then return 'Invalid payload value' end else value = read_message("Fields[value]") if not value then return 'Fields[value] is missing' end end -- collect Fields[tag_fields] local i = 0 while true do local t = read_message("Fields[tag_fields]", 0, i) if not t then break end tags[t] = read_message(string.format('Fields[%s]', t)) i = i + 1 end encode_datapoint(name, value, tags) end function process_bulk_metric() -- The payload contains a list of datapoints, each point being formatted -- like this: {name='foo',value=1,tags={k1=v1,...}} local datapoints = decode_json_payload() if not datapoints then return 'Invalid payload value' end for _, point in ipairs(datapoints) do encode_datapoint(point.name, point.value, point.tags or {}) end end function encode_scalar_value(value) if type(value) == "number" then -- Always send numbers as formatted floats, so InfluxDB will accept -- them if they happen to change from ints to floats between -- points in time. Forcing them to always be floats avoids this. return string.format("%.6f", value) elseif type(value) == "string" then -- string values need to be double quoted return '"' .. value:gsub('"', '\\"') .. '"' elseif type(value) == "boolean" then return '"' .. tostring(value) .. '"' end end function encode_value(value) if type(value) == "table" then local values = {} for k,v in pairs(value) do table.insert( values, string.format("%s=%s", escape_string(k), encode_scalar_value(v)) ) end return table.concat(values, ',') else return "value=" .. encode_scalar_value(value) end end -- encode a single datapoint using the InfluxDB line protocol -- -- name: the measurement's name -- value: a scalar value or a list of key-value pairs -- tags: a table of tags -- -- Timestamp is taken from the Heka message function encode_datapoint(name, value, tags) if type(name) ~= 'string' or value == nil or type(tags) ~= 'table' then -- fail silently if any input parameter is invalid return end local ts if time_precision and time_precision ~= 'ns' then ts = field_util.message_timestamp(time_precision) else ts = read_message('Timestamp') end -- Add the common tags for _, t in ipairs(tag_fields) do tags[t] = read_message(string.format('Fields[%s]', t)) or defaults[t] end local tags_array = {} for k,v in pairs(tags) do table.insert(tags_array, escape_string(k) .. '=' .. escape_string(v)) end -- for performance reasons, it is recommended to always send the tags -- in the same order. table.sort(tags_array) if #tags_array > 0 then point = string.format("%s,%s %s %d", escape_string(name), table.concat(tags_array, ','), encode_value(value), ts) else point = string.format("%s %s %d", escape_string(name), encode_value(value), ts) end datapoints[#datapoints+1] = point end function process_message() local err_msg local msg_type = read_message("Type") if msg_type:match('bulk_metric$') then err_msg = process_bulk_metric() else err_msg = process_single_metric() end flush() if err_msg then return -1, err_msg else return 0 end end function timer_event(ns) flush() end
-- Copyright 2015 Mirantis, Inc. -- -- 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. require 'cjson' require 'os' require 'string' require 'table' local field_util = require 'field_util' local utils = require 'lma_utils' local l = require 'lpeg' l.locale(l) local flush_count = read_config('flush_count') or 100 local flush_interval = read_config('flush_interval') or 5 local default_tenant_id = read_config("default_tenant_id") local default_user_id = read_config("default_user_id") local time_precision = read_config("time_precision") -- the tag_fields parameter is a list of tags separated by spaces local tag_grammar = l.Ct((l.C((l.P(1) - l.P" ")^1) * l.P" "^0)^0) local tag_fields = tag_grammar:match(read_config("tag_fields") or "") local defaults = { tenant_id=default_tenant_id, user_id=default_user_id, } local last_flush = os.time() local datapoints = {} function escape_string(str) return tostring(str):gsub("([ ,])", "\\%1") end -- Flush the datapoints to InfluxDB if enough items are present or if the -- timeout has expired function flush () local now = os.time() if #datapoints > 0 and (#datapoints > flush_count or now - last_flush > flush_interval) then datapoints[#datapoints+1] = '' utils.safe_inject_payload("txt", "influxdb", table.concat(datapoints, "\n")) datapoints = {} last_flush = now end end -- Return the Payload field decoded as JSON data, nil if the payload isn't a -- valid JSON string function decode_json_payload() local ok, data = pcall(cjson.decode, read_message("Payload")) if not ok then return end return data end function process_single_metric() local tags = {} local name = read_message("Fields[name]") local value if not name then return 'Fields[name] is missing' end if read_message('Type'):match('multivalue_metric$') then value = decode_json_payload() if not value then return 'Invalid payload value' end else value = read_message("Fields[value]") if not value then return 'Fields[value] is missing' end end -- collect Fields[tag_fields] local i = 0 while true do local t = read_message("Fields[tag_fields]", 0, i) if not t then break end tags[t] = read_message(string.format('Fields[%s]', t)) i = i + 1 end encode_datapoint(name, value, tags) end function process_bulk_metric() -- The payload contains a list of datapoints, each point being formatted -- like this: {name='foo',value=1,tags={k1=v1,...}} local datapoints = decode_json_payload() if not datapoints then return 'Invalid payload value' end for _, point in ipairs(datapoints) do encode_datapoint(point.name, point.value, point.tags or {}) end end function encode_scalar_value(value) if type(value) == "number" then -- Always send numbers as formatted floats, so InfluxDB will accept -- them if they happen to change from ints to floats between -- points in time. Forcing them to always be floats avoids this. return string.format("%.6f", value) elseif type(value) == "string" then -- string values need to be double quoted return '"' .. value:gsub('"', '\\"') .. '"' elseif type(value) == "boolean" then return '"' .. tostring(value) .. '"' end end function encode_value(value) if type(value) == "table" then local values = {} for k,v in pairs(value) do table.insert( values, string.format("%s=%s", escape_string(k), encode_scalar_value(v)) ) end return table.concat(values, ',') else return "value=" .. encode_scalar_value(value) end end -- encode a single datapoint using the InfluxDB line protocol -- -- name: the measurement's name -- value: a scalar value or a list of key-value pairs -- tags: a table of tags -- -- Timestamp is taken from the Heka message function encode_datapoint(name, value, tags) if type(name) ~= 'string' or value == nil or type(tags) ~= 'table' then -- fail silently if any input parameter is invalid return end local ts if time_precision and time_precision ~= 'ns' then ts = field_util.message_timestamp(time_precision) else ts = read_message('Timestamp') end -- Add the common tags for _, t in ipairs(tag_fields) do tags[t] = read_message(string.format('Fields[%s]', t)) or defaults[t] end local tags_array = {} for k,v in pairs(tags) do if k ~= '' and v ~= '' then -- empty tag name and value aren't allowed table.insert(tags_array, escape_string(k) .. '=' .. escape_string(v)) end end -- for performance reasons, it is recommended to always send the tags -- in the same order. table.sort(tags_array) if #tags_array > 0 then point = string.format("%s,%s %s %d", escape_string(name), table.concat(tags_array, ','), encode_value(value), ts) else point = string.format("%s %s %d", escape_string(name), encode_value(value), ts) end datapoints[#datapoints+1] = point end function process_message() local err_msg local msg_type = read_message("Type") if msg_type:match('bulk_metric$') then err_msg = process_bulk_metric() else err_msg = process_single_metric() end flush() if err_msg then return -1, err_msg else return 0 end end function timer_event(ns) flush() end
Prevent empty tag names and values for InfluxDB
Prevent empty tag names and values for InfluxDB Change-Id: Ide0a52d63f5e6385997455e81899f76f8b5a0829 Closes-Bug: #1572631
Lua
apache-2.0
stackforge/fuel-plugin-lma-collector,stackforge/fuel-plugin-lma-collector,stackforge/fuel-plugin-lma-collector,stackforge/fuel-plugin-lma-collector,stackforge/fuel-plugin-lma-collector
7207dfe4aa31ed3396789a48f516e27fc70c703e
lua/entities/gmod_wire_expression2/core/http.lua
lua/entities/gmod_wire_expression2/core/http.lua
/* Simple HTTP Extension (McLovin) */ E2Lib.RegisterExtension( "http", true ) local cvar_delay = CreateConVar( "wire_expression2_http_delay", "3", FCVAR_ARCHIVE ) local cvar_timeout = CreateConVar( "wire_expression2_http_timeout", "15", FCVAR_ARCHIVE ) local requests = {} local run_on = { clk = 0, ents = {} } local function player_can_request( ply ) local preq = requests[ply] return !preq or (preq.in_progress and preq.t_start and (CurTime() - preq.t_start) >= cvar_timeout:GetInt()) or (!preq.in_progress and preq.t_end and (CurTime() - preq.t_end) >= cvar_delay:GetInt()) end __e2setcost( 20 ) e2function void httpRequest( string url ) if !player_can_request( self.player ) or url == "" then return end requests[self.player] = { in_progress = true, t_start = CurTime(), t_end = 0, url = url } http.Get( url, "", function( args, contents, size ) local ply = args[1] if !validEntity( ply ) or !ply:IsPlayer() or !requests[ply] then return end local preq = requests[ply] preq.t_end = CurTime() preq.in_progress = false preq.data = contents or "" run_on.clk = 1 for ent,eply in pairs( run_on.ents ) do if validEntity( ent ) and ent.Execute and eply == ply then ent:Execute() end end run_on.clk = 0 end, self.player ) end __e2setcost( 5 ) e2function number httpCanRequest() return ( player_can_request( self.player ) ) and 1 or 0 end e2function number httpClk() return run_on.clk end e2function string httpData() local preq = requests[self.player] return preq.data or "" end e2function string httpRequestUrl() local preq = requests[self.player] return preq.url or "" end e2function string httpUrlEncode(string data) local ndata = string.gsub( data, "[^%w _~%.%-]", function( str ) local nstr = string.format( "%X", string.byte( str ) ) return "%" .. ( ( string.len( nstr ) == 1 ) and "0" or "" ) .. nstr end ) return string.gsub( ndata, " ", "+" ) end e2function string httpUrlDecode(string data) local ndata = string.gsub( data, "+", " " ) return string.gsub( ndata, "(%%%x%x)", function( str ) return string.char( tonumber( string.Right( str, 2 ), 16 ) ) end ) end e2function void runOnHTTP( number rohttp ) run_on.ents[self.entity] = ( rohttp != 0 ) and self.player or nil end registerCallback( "destruct", function( self ) run_on.ents[self.entity] = nil end )
/* Simple HTTP Extension (McLovin) */ E2Lib.RegisterExtension( "http", true ) local cvar_delay = CreateConVar( "wire_expression2_http_delay", "3", FCVAR_ARCHIVE ) local cvar_timeout = CreateConVar( "wire_expression2_http_timeout", "15", FCVAR_ARCHIVE ) local requests = {} local run_on = { clk = 0, ents = {} } local function player_can_request( ply ) local preq = requests[ply] return !preq or (preq.in_progress and preq.t_start and (CurTime() - preq.t_start) >= cvar_timeout:GetInt()) or (!preq.in_progress and preq.t_end and (CurTime() - preq.t_end) >= cvar_delay:GetInt()) end __e2setcost( 20 ) e2function void httpRequest( string url ) if !player_can_request( self.player ) or url == "" then return end requests[self.player] = { in_progress = true, t_start = CurTime(), t_end = 0, url = url } http.Get( url, "", function( args, contents, size ) local ply = args[1] if !validEntity( ply ) or !ply:IsPlayer() or !requests[ply] then return end local preq = requests[ply] preq.t_end = CurTime() preq.in_progress = false preq.data = contents or "" preq.data = string.gsub( preq.data, string.char( 13 ) .. string.char( 10 ), "\n" ) run_on.clk = 1 for ent,eply in pairs( run_on.ents ) do if validEntity( ent ) and ent.Execute and eply == ply then ent:Execute() end end run_on.clk = 0 end, self.player ) end __e2setcost( 5 ) e2function number httpCanRequest() return ( player_can_request( self.player ) ) and 1 or 0 end e2function number httpClk() return run_on.clk end e2function string httpData() local preq = requests[self.player] return preq.data or "" end e2function string httpRequestUrl() local preq = requests[self.player] return preq.url or "" end e2function string httpUrlEncode(string data) local ndata = string.gsub( data, "[^%w _~%.%-]", function( str ) local nstr = string.format( "%X", string.byte( str ) ) return "%" .. ( ( string.len( nstr ) == 1 ) and "0" or "" ) .. nstr end ) return string.gsub( ndata, " ", "+" ) end e2function string httpUrlDecode(string data) local ndata = string.gsub( data, "+", " " ) return string.gsub( ndata, "(%%%x%x)", function( str ) return string.char( tonumber( string.Right( str, 2 ), 16 ) ) end ) end e2function void runOnHTTP( number rohttp ) run_on.ents[self.entity] = ( rohttp != 0 ) and self.player or nil end registerCallback( "destruct", function( self ) run_on.ents[self.entity] = nil end )
[E2] http.lua: Fixed the new line character to be compatible with lua in order to prevent future problems with fileWrite().
[E2] http.lua: Fixed the new line character to be compatible with lua in order to prevent future problems with fileWrite().
Lua
apache-2.0
mitterdoo/wire,thegrb93/wire,rafradek/wire,dvdvideo1234/wire,CaptainPRICE/wire,bigdogmat/wire,notcake/wire,NezzKryptic/Wire,immibis/wiremod,mms92/wire,Grocel/wire,Python1320/wire,garrysmodlua/wire,plinkopenguin/wiremod,sammyt291/wire,wiremod/wire
4c4935d32c28267f6a7a10853d32a8e76055445f
helper.lua
helper.lua
-- Helper Module -- local setup = require "setup" local dbmodule = require "dbmodule" local config = require "config" scriptdb = config.scriptdb local helper = {} helper.mainMenu = {"Help (h)", "Initial Setup (i)", "Search by Name of Script (s)", "Search by Category (c)", "Create script.db backup (b)", "Exit (q)"} function helper.banner() banner=[[ _ _ _____ _____ _ | \ | |/ ___|| ___| | | | \| |\ `--. | |__ __ _ _ __ ___ | |__ | . ` | `--. \| __| / _` || '__| / __|| '_ \ | |\ |/\__/ /| |___ | (_| || | | (__ | | | | \_| \_/\____/ \____/ \__,_||_| \___||_| |_| ]] return banner end function getScirptDesc( nse ) io.write('\nDo yo want more info about any script, choose the script using id [1-'..#nse..'] or quit (0) ') local option = io.read("*n") if nse[option] then print("\n") local file = config.scriptsPath..nse[option] local lines = lines_from(file) for k,v in pairs(lines) do local i = string.find(v, "license") if not i then print('\27[96m'..v..'\27[0m') else getScirptDesc(nse) end end elseif option == 0 then os.execute("clear") print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m') helper.searchConsole() else os.execute("clear") helper.menu(helper.mainMenu) helper.Main() end end function resultList(nse) if #nse > 0 then print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m') print("\nTotal Scripts Found "..#nse.."\n") for k,v in ipairs(nse) do print('\27[92m'..k.." "..v..'\27[0m') end getScirptDesc(nse) else print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m') print("\nNot Results Found\n") io.write("Do you want search again? [y/n]: ") local action = io.read() if action == 'y' then os.execute("clear") print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m') helper.searchConsole() else os.execute("clear") helper.menu(helper.mainMenu) helper.Main() end end end function resultListaCat(scripts,catName) if #scripts > 0 then print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m') print("\nTotal Scripts Found "..#scripts.." into "..catName.." Category\n") for k,v in ipairs(scripts) do print('\27[92m'..k.." "..v..'\27[0m') end getScirptDesc(scripts) else print("Not Results Found\n") print("=== These are the enabled Categories ===\n") dbmodule.findAll("categories") end end function helper.menu(menulist) print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m') for key,value in ipairs(menulist) do print(key.." "..value) end return menulist end function helper.searchConsole() io.write('\nnsearch> ') local command = io.read() if command == "help" or command == nil then os.execute("clear") print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m') print("name : search by script's name ") print("category : search by category") print("exit : close the console") print("back : returns to the main menu") print("\n Usage:") print("\n name:http") print("\n category:exploit") helper.searchConsole() elseif string.find(command,"name:") then string = command:gsub("name:","") os.execute("clear") resultList(dbmodule.findScript(string,helper.banner())) elseif string.find(command,"exit") then os.exit() elseif string.find(command,"back") then os.execute("clear") helper.menu(helper.mainMenu) helper.Main() elseif string.find(command,"category:") then string = command:gsub("category:","") print(string) os.execute("clear") resultListaCat(dbmodule.SearchByCat(string),string) else helper.searchConsole() end end function helper.Main() io.write('\n What do you want to do? : ') local action = io.read() if action == "q" or action == "6" then os.exit() elseif action == "i" or action == "2" then os.execute( "clear" ) setup.install(helper.banner()) elseif action == "s" or action == "3" then os.execute( "clear" ) print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m') helper.searchConsole() elseif action == "b" or action == "4" then setup.createBackup(helper.banner()) os.execute( "clear" ) helper.menu(mainMenu) helper.Main() else os.exit() end end return helper
-- Helper Module -- local setup = require "setup" local dbmodule = require "dbmodule" local config = require "config" scriptdb = config.scriptdb local helper = {} helper.mainMenu = {"Help (h)", "Initial Setup (i)", "Search by Name of Script (s)", "Search by Category (c)", "Create script.db backup (b)", "Exit (q)"} function helper.banner() banner=[[ _ _ _____ _____ _ | \ | |/ ___|| ___| | | | \| |\ `--. | |__ __ _ _ __ ___ | |__ | . ` | `--. \| __| / _` || '__| / __|| '_ \ | |\ |/\__/ /| |___ | (_| || | | (__ | | | | \_| \_/\____/ \____/ \__,_||_| \___||_| |_| ]] return banner end function getScirptDesc( nse ) io.write('\nDo yo want more info about any script, choose the script using id [1-'..#nse..'] or quit (0)') local option = io.read() key = tonumber(option) if nse[key] then print("\n") local file = config.scriptsPath..nse[key] local lines = lines_from(file) for k,v in pairs(lines) do local i = string.find(v, "license") if not i then print('\27[96m'..v..'\27[0m') else getScirptDesc(nse) end end elseif option == "0" then os.execute("clear") print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m') helper.searchConsole() else os.execute("clear") helper.menu(helper.mainMenu) helper.Main() end end function resultList(nse) if #nse > 0 then print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m') print("\nTotal Scripts Found "..#nse.."\n") for k,v in ipairs(nse) do print('\27[92m'..k.." "..v..'\27[0m') end getScirptDesc(nse) else print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m') print("\nNot Results Found\n") io.write("Do you want search again? [y/n]: ") local action = io.read() if action == 'y' then os.execute("clear") print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m') helper.searchConsole() else os.execute("clear") helper.menu(helper.mainMenu) helper.Main() end end end function resultListaCat(scripts,catName) if #scripts > 0 then print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m') print("\nTotal Scripts Found "..#scripts.." into "..catName.." Category\n") for k,v in ipairs(scripts) do print('\27[92m'..k.." "..v..'\27[0m') end getScirptDesc(scripts) else print("Not Results Found\n") print("=== These are the enabled Categories ===\n") dbmodule.findAll("categories") end end function helper.menu(menulist) print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m') for key,value in ipairs(menulist) do print(key.." "..value) end return menulist end function helper.searchConsole() io.write('nsearch> ') local command = io.read() print(string.len(command)) if command == "help" then os.execute("clear") print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m') print("name : search by script's name ") print("category : search by category") print("exit : close the console") print("back : returns to the main menu") print("\n Usage:") print("\n name:http") print("\n category:exploit") helper.searchConsole() elseif string.find(command,"name:") then string = command:gsub("name:","") os.execute("clear") resultList(dbmodule.findScript(string,helper.banner())) elseif string.find(command,"exit") then os.exit() elseif string.find(command,"back") then os.execute("clear") helper.menu(helper.mainMenu) helper.Main() elseif string.find(command,"category:") then string = command:gsub("category:","") os.execute("clear") resultListaCat(dbmodule.SearchByCat(string),string) else helper.searchConsole() end end function helper.Main() io.write('\n What do you want to do? : ') local action = io.read() if action == "q" or action == "6" then os.exit() elseif action == "i" or action == "2" then os.execute( "clear" ) setup.install(helper.banner()) elseif action == "s" or action == "3" then os.execute( "clear" ) print('\27[1m \27[36m'..helper.banner()..'\27[21m \27[0m') helper.searchConsole() elseif action == "b" or action == "4" then setup.createBackup(helper.banner()) os.execute( "clear" ) helper.menu(helper.mainMenu) helper.Main() else os.execute("clear") helper.menu(helper.mainMenu) helper.Main() end end return helper
Fixing double string
Fixing double string
Lua
apache-2.0
JKO/nsearch,JKO/nsearch
a56be783deb188f24590a104038ccef9e0472e8d
tests/base/test_http.lua
tests/base/test_http.lua
-- -- tests/base/test_http.lua -- Tests the http API -- Copyright (c) 2016 Jason Perkins and the Premake project -- local p = premake -- only declare the suite as a test if http.get is an existing method. local suite = {} if http.get ~= nil then suite = test.declare("premake_http") end function suite.http_get() local result, err = http.get("http://httpbin.org/user-agent") if result then p.out(result) test.capture( '{"user-agent": "Premake/' .. _PREMAKE_VERSION .. '"}' ) else test.fail(err); end end function suite.https_get() -- sslverifypeer = 0, so we can test from within companies like here at Blizzard where all HTTPS traffic goes through -- some strange black box that re-signs all traffic with a custom ssl certificate. local result, err = http.get("https://httpbin.org/user-agent", { sslverifypeer = 0 }) if result then p.out(result) test.capture( '{"user-agent": "Premake/' .. _PREMAKE_VERSION .. '"}' ) else test.fail(err); end end function suite.https_get_verify_peer() local result, err = http.get("https://httpbin.org/user-agent") if result then p.out(result) test.capture( '{"user-agent": "Premake/' .. _PREMAKE_VERSION .. '"}' ) else test.fail(err); end end function suite.http_responsecode() local result, err, responseCode = http.get("http://httpbin.org/status/418") test.isequal(responseCode, 418) end function suite.http_redirect() local result, err, responseCode = http.get("http://httpbin.org/redirect/3") if result then test.isequal(responseCode, 200) else test.fail(err); end end function suite.http_headers() local result, err, responseCode = http.get("http://httpbin.org/headers", { headers = { 'X-Premake: premake' } }) if result then if (not result:find('X-Premake')) then test.fail("response doens't contain header") test.print(result) end else test.fail(err); end end
-- -- tests/base/test_http.lua -- Tests the http API -- Copyright (c) 2016 Jason Perkins and the Premake project -- local p = premake -- only declare the suite as a test if http.get is an existing method. local suite = {} if http.get ~= nil then suite = test.declare("premake_http") end function suite.http_get() local result, err = http.get("http://httpbin.org/user-agent") if result then p.out(result) test.capture( '{"user-agent": "Premake/' .. _PREMAKE_VERSION .. '"}' ) else test.fail(err); end end function suite.https_get() -- sslverifypeer = 0, so we can test from within companies like here at Blizzard where all HTTPS traffic goes through -- some strange black box that re-signs all traffic with a custom ssl certificate. local result, err = http.get("https://httpbin.org/user-agent", { sslverifypeer = 0 }) if result then p.out(result) test.capture( '{"user-agent": "Premake/' .. _PREMAKE_VERSION .. '"}' ) else test.fail(err); end end function suite.https_get_verify_peer() local result, err = http.get("https://httpbin.org/user-agent") if result then p.out(result) test.capture( '{"user-agent": "Premake/' .. _PREMAKE_VERSION .. '"}' ) else test.fail(err); end end function suite.http_responsecode() local result, err, responseCode = http.get("http://httpbin.org/status/418") test.isequal(responseCode, 418) end -- Disable as httpbin.org returns 404 on this endpoint --[[ function suite.http_redirect() local result, err, responseCode = http.get("http://httpbin.org/redirect/3") if result then test.isequal(responseCode, 200) else test.fail(err); end end ]] function suite.http_headers() local result, err, responseCode = http.get("http://httpbin.org/headers", { headers = { 'X-Premake: premake' } }) if result then if (not result:find('X-Premake')) then test.fail("response doens't contain header") test.print(result) end else test.fail(err); end end
Disable redirect test until HTTP endpoint is fixed
Disable redirect test until HTTP endpoint is fixed
Lua
bsd-3-clause
starkos/premake-core,premake/premake-core,starkos/premake-core,noresources/premake-core,dcourtois/premake-core,dcourtois/premake-core,premake/premake-core,starkos/premake-core,dcourtois/premake-core,premake/premake-core,noresources/premake-core,starkos/premake-core,starkos/premake-core,noresources/premake-core,starkos/premake-core,premake/premake-core,noresources/premake-core,dcourtois/premake-core,premake/premake-core,noresources/premake-core,premake/premake-core,starkos/premake-core,noresources/premake-core,dcourtois/premake-core,dcourtois/premake-core,premake/premake-core,noresources/premake-core,dcourtois/premake-core
9fcb71c3db72495966e5ad305e81b8ef2b2ecbef
lua/zbe/keyfix.lua
lua/zbe/keyfix.lua
return { name = "Home/End modified", description = "Modified Ctrl-Left and Ctrl-right to behave as Home/End.", author = "Paul Kulchenko", version = 0.1, onRegister = function() end, onEditorCharAdded = function(self, editor, event) end, onEditorFocusSet = function(self, editor, event) end, --[[ This page is helpful for commands http://wxlua.sourceforge.net/docs/wxluaref.html -- mac ctrl == 16, raw_control -- mac option == 1 -- mac cmd == 2 --]] onEditorKeyDown = function(self, editor, event) local keycode = event:GetKeyCode() local mod = event:GetModifiers() -- DisplayOutputLn("key code:", keycode) -- DisplayOutputLn("modifier:", mod) -- DisplayOutputLn("alt:", wx.wxMOD_ALT) -- DisplayOutputLn("D:", tostring(('D'):byte())) if mod == wx.wxMOD_CMD + wx.wxMOD_SHIFT then if keycode == ('['):byte() then local nb = ide.frame.notebook nb:AdvanceSelection(false) return false elseif keycode == (']'):byte() then local nb = ide.frame.notebook nb:AdvanceSelection(true) return false end end if mod == wx.wxMOD_ALT then -- DisplayOutputLn("in1") -- if keycode == ('D'):byte() then -- DisplayOutputLn("in2") -- editor:DeleteWordRight() -- return false -- end end if mod == wx.wxMOD_RAW_CONTROL then if keycode == ('E'):byte() then editor:LineEnd() return false end if keycode == ('A'):byte() then editor:VCHome() return false end if keycode == ('P'):byte() then editor:LineUp() return false end if keycode == ('N'):byte() then editor:LineDown() return false end if keycode == ('F'):byte() then editor:CharRight() return false end if keycode == ('B'):byte() then editor:CharLeft() return false end if keycode == ('K'):byte() then --[[ emacs deletes to the end of the line and if at the beginning and line is empty then delete the whole line --]] local line = editor:GetCurrentLine() local lineBegin = editor:PositionFromLine(line) local lineEnd = editor:GetLineEndPosition(line) if lineBegin == lineEnd then editor:LineDelete() else editor:DelLineRight() end return false end end end, }
return { name = "Zemacsy", description = "Xcode and Emacs type keybindings", author = "Sean Levin", version = 0.1, onRegister = function() end, onEditorCharAdded = function(self, editor, event) end, onEditorFocusSet = function(self, editor, event) end, --[[ This page is helpful for commands http://wxlua.sourceforge.net/docs/wxluaref.html -- mac ctrl == 16, raw_control -- mac option == 1 -- mac cmd == 2 --]] onEditorKeyDown = function(self, editor, event) local keycode = event:GetKeyCode() local mod = event:GetModifiers() -- DisplayOutputLn("key code:", keycode) -- DisplayOutputLn("modifier:", mod) -- DisplayOutputLn("alt:", wx.wxMOD_ALT) -- DisplayOutputLn("D:", tostring(('D'):byte())) if mod == wx.wxMOD_CMD + wx.wxMOD_SHIFT then if keycode == ('['):byte() then local nb = ide.frame.notebook nb:AdvanceSelection(false) return false elseif keycode == (']'):byte() then local nb = ide.frame.notebook nb:AdvanceSelection(true) return false end end if mod == wx.wxMOD_ALT then -- DisplayOutputLn("in1") -- if keycode == ('D'):byte() then -- DisplayOutputLn("in2") -- editor:DeleteWordRight() -- return false -- end end if mod == wx.wxMOD_RAW_CONTROL then if keycode == ('E'):byte() then editor:LineEnd() return false end if keycode == ('A'):byte() then editor:VCHome() return false end if keycode == ('P'):byte() then editor:LineUp() return false end if keycode == ('N'):byte() then editor:LineDown() return false end if keycode == ('F'):byte() then editor:CharRight() return false end if keycode == ('B'):byte() then editor:CharLeft() return false end if keycode == ('K'):byte() then --[[ emacs deletes to the end of the line and if at the beginning and line is empty then delete the whole line --]] local line = editor:GetCurrentLine() local lineBegin = editor:PositionFromLine(line) local lineEnd = editor:GetLineEndPosition(line) if lineBegin == lineEnd then editor:LineDelete() else editor:DelLineRight() end return false end end end, }
fix version info
fix version info
Lua
unlicense
slevin/experiements,slevin/experiements,slevin/experiements,slevin/experiements,slevin/experiements,slevin/experiements,slevin/experiements,slevin/experiements,slevin/experiements
ea385663779cd523c0921b230a4b7056a8b82e50
scripts/ovale_items.lua
scripts/ovale_items.lua
local _, Ovale = ... local OvaleScripts = Ovale.OvaleScripts do local name = "ovale_items" local desc = "[5.4.7] Ovale: Items & Trinkets" local code = [[ ### ### Potions (Mists of Pandaria only) ### Define(jade_serpent_potion 76093) Define(jade_serpent_potion_buff 105702) SpellInfo(jade_serpent_potion_buff duration=25) Define(mogu_power_potion 76095) Define(mogu_power_potion_buff 105706) SpellInfo(mogu_power_potion_buff duration=25) Define(virmens_bite_potion 76089) Define(virmens_bite_potion_buff 105697) SpellInfo(virmens_bite_potion_buff duration=25) AddCheckBox(potions "Use potions" default) AddFunction UsePotionAgility { if CheckBoxOn(potions) and target.Classification(worldboss) Item(virmens_bite_potion usable=1) } AddFunction UsePotionIntellect { if CheckBoxOn(potions) and target.Classification(worldboss) Item(jade_serpent_potion usable=1) } AddFunction UsePotionStrength { if CheckBoxOn(potions) and target.Classification(worldboss) Item(mogu_power_potion usable=1) } ### ### Trinkets (Mists of Pandaria only) ### # Agility SpellList(trinket_proc_agility_buff 126554 126690 126707 128984 138699 138938 146308 146310 148896 148903) SpellList(trinket_stacking_proc_agility_buff 138756) SpellList(trinket_stat_agility_buff 126554 126690 126707 128984 138699 138938 146308 146310 148896 148903) SpellList(trinket_stacking_stat_agility_buff 138756) # Intellect SpellList(trinket_proc_intellect_buff 126554 126690 126707 128984 138699 138938 146308 146310 148896 148903) SpellList(trinket_stacking_proc_intellect_buff 138756) # Strength SpellList(trinket_proc_strength_buff 126554 126690 126707 128984 138699 138938 146308 146310 148896 148903) # Critical Strike SpellList(trinket_stacking_stat_crit_buff 138756) AddCheckBox(opt_use_trinket0 "Use trinket 0" default) AddCheckBox(opt_use_trinket1 "Use trinket 1" default) AddFunction UseItemActions { Item(HandsSlot usable=1) if CheckBoxOn(opt_use_trinket0) Item(Trinket0Slot usable=1) if CheckBoxOn(opt_use_trinket1) Item(Trinket1Slot usable=1) } ### ### Legendary Meta Gem ### Define(lucidity_druid_buff 137247) SpellInfo(lucidity_druid_buff duration=4) Define(lucidity_monk_buff 137331) SpellInfo(lucidity_monk_buff duration=4) Define(lucidity_paladin_buff 137288) SpellInfo(lucidity_paladin_buff duration=4) Define(lucidity_priest_buff 137323) SpellInfo(lucidity_priest_buff duration=4) Define(lucidity_shaman_buff 137326) SpellInfo(lucidity_shaman_buff duration=4) ]] OvaleScripts:RegisterScript(nil, name, desc, code, "include") end
local _, Ovale = ... local OvaleScripts = Ovale.OvaleScripts do local name = "ovale_items" local desc = "[5.4.7] Ovale: Items & Trinkets" local code = [[ ### ### Potions (Mists of Pandaria only) ### Define(jade_serpent_potion 76093) Define(jade_serpent_potion_buff 105702) SpellInfo(jade_serpent_potion_buff duration=25) Define(mogu_power_potion 76095) Define(mogu_power_potion_buff 105706) SpellInfo(mogu_power_potion_buff duration=25) Define(virmens_bite_potion 76089) Define(virmens_bite_potion_buff 105697) SpellInfo(virmens_bite_potion_buff duration=25) AddCheckBox(potions "Use potions" default) AddFunction UsePotionAgility { if CheckBoxOn(potions) and target.Classification(worldboss) Item(virmens_bite_potion usable=1) } AddFunction UsePotionIntellect { if CheckBoxOn(potions) and target.Classification(worldboss) Item(jade_serpent_potion usable=1) } AddFunction UsePotionStrength { if CheckBoxOn(potions) and target.Classification(worldboss) Item(mogu_power_potion usable=1) } ### ### Trinkets (Mists of Pandaria only) ### # Agility SpellList(trinket_proc_agility_buff 126554 126690 126707 128984 138699 138938 146308 146310 148896 148903) SpellList(trinket_stacking_proc_agility_buff 138756) SpellList(trinket_stat_agility_buff 126554 126690 126707 128984 138699 138938 146308 146310 148896 148903) SpellList(trinket_stacking_stat_agility_buff 138756) # Intellect SpellList(trinket_proc_intellect_buff 126577 126683 126705 128985 136082 138898 138963 139133 146046 148897 148906) SpellList(trinket_stacking_proc_intellect_buff 138786 146184) # Strength SpellList(trinket_proc_strength_buff 126582 126679 126700 128986 138702 146245 146250 148899) SpellList(trinket_stacking_proc_strength_buff 138759 138870) # Critical Strike SpellList(trinket_stacking_stat_crit_buff 146285) AddCheckBox(opt_use_trinket0 "Use trinket 0" default) AddCheckBox(opt_use_trinket1 "Use trinket 1" default) AddFunction UseItemActions { Item(HandsSlot usable=1) if CheckBoxOn(opt_use_trinket0) Item(Trinket0Slot usable=1) if CheckBoxOn(opt_use_trinket1) Item(Trinket1Slot usable=1) } ### ### Legendary Meta Gem ### Define(lucidity_druid_buff 137247) SpellInfo(lucidity_druid_buff duration=4) Define(lucidity_monk_buff 137331) SpellInfo(lucidity_monk_buff duration=4) Define(lucidity_paladin_buff 137288) SpellInfo(lucidity_paladin_buff duration=4) Define(lucidity_priest_buff 137323) SpellInfo(lucidity_priest_buff duration=4) Define(lucidity_shaman_buff 137326) SpellInfo(lucidity_shaman_buff duration=4) ]] OvaleScripts:RegisterScript(nil, name, desc, code, "include") end
Fix spell IDs for trinket proc buffs.
Fix spell IDs for trinket proc buffs. This corrects the lists for intellect, strength and crit rating. git-svn-id: b2bb544abab4b09d60f88077ac82407cb244c9c9@1349 d5049fe3-3747-40f7-a4b5-f36d6801af5f
Lua
mit
Xeltor/ovale,eXhausted/Ovale,ultijlam/ovale,ultijlam/ovale,ultijlam/ovale,eXhausted/Ovale,eXhausted/Ovale
9aa765434d87037ed872ce0db8ce342af4589c1a
extensions/image/init.lua
extensions/image/init.lua
local module = { --- === hs.image === --- --- A module for capturing and manipulating image objects from other modules for use with hs.drawing. --- } local fnutils = require("hs.fnutils") local module = require("hs.image.internal") local objectMT = hs.getObjectMetatable("hs.image") require("hs.drawing.color") -- make sure that the conversion helpers required to support color are loaded -- local __tostring_for_arrays = function(self) -- local result = "" -- for i,v in fnutils.sortByKeyValues(self) do -- result = result..v.."\n" -- end -- return result -- end -- -- local __tostring_for_tables = function(self) -- local result = "" -- local width = 0 -- for i,v in fnutils.sortByKeys(self) do -- if type(i) == "string" and width < i:len() then width = i:len() end -- end -- for i,v in fnutils.sortByKeys(self) do -- if type(i) == "string" then -- result = result..string.format("%-"..tostring(width).."s \"%s\"\n", i, v) -- end -- end -- return result -- end -- -- module.systemImageNames = setmetatable(module.systemImageNames, { __tostring = __tostring_for_tables -- }) module.systemImageNames = ls.makeConstantsTable(module.systemImageNames) module.additionalImageNames = ls.makeConstantsTable(module.additionalImageNames) --- hs.image:setName(Name) -> boolean --- Method --- Assigns the name assigned to the hs.image object. --- --- Parameters: --- * Name - the name to assign to the hs.image object. --- --- Returns: --- * Status - a boolean value indicating success (true) or failure (false) when assigning the specified name. --- --- Notes: --- * This method is included for backwards compatibility and is considered deprecated. It is equivalent to `hs.image:name(name) and true or false`. objectMT.setName = function(self, ...) return self:name(...) and true or false end --- hs.image:setSize(size [, absolute]) -> object --- Method --- Returns a copy of the image resized to the height and width specified in the size table. --- --- Parameters: --- * size - a table with 'h' and 'w' keys specifying the size for the new image. --- * absolute - an optional boolean specifying whether or not the copied image should be resized to the height and width specified (true), or whether the copied image should be scaled proportionally to fit within the height and width specified (false). Defaults to false. --- --- Returns: --- * a copy of the image object at the new size --- --- Notes: --- * This method is included for backwards compatibility and is considered deprecated. It is equivalent to `hs.image:copy():size(size, [absolute])`. objectMT.setSize = function(self, ...) return self:copy():size(...) end return module
--- === hs.image === --- --- A module for capturing and manipulating image objects from other modules for use with hs.drawing. --- local module = require("hs.image.internal") local objectMT = hs.getObjectMetatable("hs.image") require("hs.drawing.color") -- make sure that the conversion helpers required to support color are loaded -- local __tostring_for_arrays = function(self) -- local result = "" -- for i,v in fnutils.sortByKeyValues(self) do -- result = result..v.."\n" -- end -- return result -- end -- -- local __tostring_for_tables = function(self) -- local result = "" -- local width = 0 -- for i,v in fnutils.sortByKeys(self) do -- if type(i) == "string" and width < i:len() then width = i:len() end -- end -- for i,v in fnutils.sortByKeys(self) do -- if type(i) == "string" then -- result = result..string.format("%-"..tostring(width).."s \"%s\"\n", i, v) -- end -- end -- return result -- end -- -- module.systemImageNames = setmetatable(module.systemImageNames, { __tostring = __tostring_for_tables -- }) module.systemImageNames = ls.makeConstantsTable(module.systemImageNames) module.additionalImageNames = ls.makeConstantsTable(module.additionalImageNames) --- hs.image:setName(Name) -> boolean --- Method --- Assigns the name assigned to the hs.image object. --- --- Parameters: --- * Name - the name to assign to the hs.image object. --- --- Returns: --- * Status - a boolean value indicating success (true) or failure (false) when assigning the specified name. --- --- Notes: --- * This method is included for backwards compatibility and is considered deprecated. It is equivalent to `hs.image:name(name) and true or false`. objectMT.setName = function(self, ...) return self:name(...) and true or false end --- hs.image:setSize(size [, absolute]) -> object --- Method --- Returns a copy of the image resized to the height and width specified in the size table. --- --- Parameters: --- * size - a table with 'h' and 'w' keys specifying the size for the new image. --- * absolute - an optional boolean specifying whether or not the copied image should be resized to the height and width specified (true), or whether the copied image should be scaled proportionally to fit within the height and width specified (false). Defaults to false. --- --- Returns: --- * a copy of the image object at the new size --- --- Notes: --- * This method is included for backwards compatibility and is considered deprecated. It is equivalent to `hs.image:copy():size(size, [absolute])`. objectMT.setSize = function(self, ...) return self:copy():size(...) end return module
Cleanup hs.image
Cleanup hs.image - Fixed @stickler-ci errors
Lua
mit
cmsj/hammerspoon,CommandPost/CommandPost-App,asmagill/hammerspoon,Hammerspoon/hammerspoon,CommandPost/CommandPost-App,Habbie/hammerspoon,Hammerspoon/hammerspoon,Habbie/hammerspoon,Habbie/hammerspoon,Habbie/hammerspoon,CommandPost/CommandPost-App,asmagill/hammerspoon,asmagill/hammerspoon,cmsj/hammerspoon,Hammerspoon/hammerspoon,CommandPost/CommandPost-App,asmagill/hammerspoon,Hammerspoon/hammerspoon,cmsj/hammerspoon,CommandPost/CommandPost-App,Hammerspoon/hammerspoon,cmsj/hammerspoon,latenitefilms/hammerspoon,asmagill/hammerspoon,Hammerspoon/hammerspoon,latenitefilms/hammerspoon,latenitefilms/hammerspoon,cmsj/hammerspoon,asmagill/hammerspoon,latenitefilms/hammerspoon,cmsj/hammerspoon,Habbie/hammerspoon,latenitefilms/hammerspoon,CommandPost/CommandPost-App,latenitefilms/hammerspoon,Habbie/hammerspoon
f2e878dbe784a0f81bca5ae4d9b51c62a16f6b2e
tests/lua/res1.lua
tests/lua/res1.lua
-- Create names for commonly used constants local Or = Const("or") local Not = Const("not") local False = Const("false") function init_env(env) -- Populate environment when declarations used by resolve_macro. -- This is a 'fake' environment used only for testing. local a = Local("a", Prop) local b = Local("b", Prop) local c = Local("c", Prop) local Ha = Local("Ha", a) local Hb = Local("Hb", b) env = add_decl(env, mk_constant_assumption("or", mk_arrow(Prop, Prop, Prop))) env = add_decl(env, mk_constant_assumption("not", mk_arrow(Prop, Prop))) env = add_decl(env, mk_constant_assumption("false", Prop)) env = add_decl(env, mk_axiom({"or", "elim"}, Pi(a, b, c, mk_arrow(Or(a, b), mk_arrow(a, c), mk_arrow(b, c), c)))) env = add_decl(env, mk_axiom({"or", "intro_left"}, Pi(a, Ha, b, Or(a, b)))) env = add_decl(env, mk_axiom({"or", "intro_right"}, Pi(b, a, Hb, Or(a, b)))) env = add_decl(env, mk_axiom("absurd_elim", Pi(a, b, mk_arrow(a, Not(a), b)))) return env end function decl_bools(env, ls) for i = 1, #ls do env = add_decl(env, mk_constant_assumption(ls[i]:data(), Prop)) end return env end function Consts(s) -- Auxiliary function for creating multiple constants local r = {} local i = 1 for c in string.gmatch(s, '[^ ,;\t\n]+') do r[i] = Const(c) i = i + 1 end return unpack(r) end function OR(...) -- Nary Or local arg = {...} if #arg == 0 then return False elseif #arg == 1 then return arg[1] else local r = arg[#arg] for i = #arg-1, 1, -1 do r = Or(arg[i], r) end return r end end function print_types(env, ...) local arg = {...} local tc = type_checker(env) for i = 1, #arg do print(tostring(arg[i]) .. " : " .. tostring(tc:check(arg[i]))) end end function assert_some_axioms(env) -- Assert some clauses local l1, l2, l3, l4, l5, l6 = Consts("l1 l2 l3 l4 l5 l6") env = decl_bools(env, {l1, l2, l3, l4, l5}) env = add_decl(env, mk_definition("l6", Prop, l3, {opaque=false})) -- l6 is alias for l3 env = add_decl(env, mk_axiom("H1", OR(l1, l2, Not(l3)))) env = add_decl(env, mk_axiom("H2", OR(l2, l3, l4))) env = add_decl(env, mk_axiom("H3", OR(Not(l1), l2, l4, l5))) env = add_decl(env, mk_axiom("H4", OR(l4, l6, Not(l5)))) env = add_decl(env, mk_axiom("H5", OR(Not(l4), l3))) env = add_decl(env, mk_axiom("H6", Not(l3))) env = add_decl(env, mk_axiom("H7", Not(l2))) return env end local env = bare_environment({trust_lvl=1}) env = init_env(env) env = assert_some_axioms(env) local l1, l2, l3, l4, l5, l6 = Consts("l1 l2 l3 l4 l5 l6") local H1, H2, H3, H4, H5, H6, H7 = Consts("H1 H2 H3 H4 H5 H6 H7") local tc = type_checker(env) print(tc:check(Or)) print(tc:check(Const("absurd_elim"))) print(tc:check(H4)) local Pr1 = resolve_macro(l6, H2, H1) local Pr2 = resolve_macro(l1, Pr1, H3) assert(Pr1:is_macro()) assert(Pr1:macro_num_args() == 3) assert(Pr1:macro_arg(0) == l6) assert(Pr1:macro_def() == Pr2:macro_def()) assert(Pr1:data() == Pr1:macro_def()) assert(Pr1 == mk_macro(Pr1:macro_def(), {Pr1:macro_arg(0), Pr1:macro_arg(1), Pr1:macro_arg(2)})) assert(Pr1:macro_def():name() == name("resolve")) assert(Pr1:macro_def():trust_level() >= 0) print(Pr1:macro_def():hash()) print(Pr1:macro_def()) print("-----------") print(tc:check(H2)) print(tc:check(H1)) print(tc:check(Pr1)) print(tc:check(H3)) print(tc:check(Pr2)) local Pr3 = resolve_macro(l4, resolve_macro(l5, Pr2, H4), H5) print(tc:check(Pr3)) local Pr4 = resolve_macro(l2, resolve_macro(l3, Pr3, H6), H7) print("-----------") print("proof for false: ") print_types(env, H1, H2, H3, H4, H5, H6, H7) print(tostring(Pr4) .. " : " .. tostring(tc:check(Pr4))) print("----------------") print("Type checking again, but using trust_lvl=0, macros will be expanded during type checking") local env = bare_environment({trust_lvl=0}) env = init_env(env) env = assert_some_axioms(env) local tc = type_checker(env) -- Since the trust_lvl is 0, the macro will be expanded during type checking print(tc:whnf(Pr1)) print(tc:check(Pr1)) print(tc:check(Pr4)) print(env:normalize(Pr4)) local a = Const("a") assert(not pcall(function() a:macro_num_args() end)) assert(not pcall(function() a:let_name() end)) assert(not pcall(function() mk_arrow(a) end))
-- Create names for commonly used constants local Or = Const("or") local Not = Const("not") local False = Const("false") function init_env(env) -- Populate environment when declarations used by resolve_macro. -- This is a 'fake' environment used only for testing. local a = Local("a", Prop) local b = Local("b", Prop) local c = Local("c", Prop) local Ha = Local("Ha", a) local Hb = Local("Hb", b) env = add_decl(env, mk_constant_assumption("or", mk_arrow(Prop, Prop, Prop))) env = add_decl(env, mk_constant_assumption("not", mk_arrow(Prop, Prop))) env = add_decl(env, mk_constant_assumption("false", Prop)) env = add_decl(env, mk_axiom({"or", "elim"}, Pi(a, b, c, mk_arrow(Or(a, b), mk_arrow(a, c), mk_arrow(b, c), c)))) env = add_decl(env, mk_axiom({"or", "intro_left"}, Pi(a, Ha, b, Or(a, b)))) env = add_decl(env, mk_axiom({"or", "intro_right"}, Pi(b, a, Hb, Or(a, b)))) env = add_decl(env, mk_axiom("absurd_elim", Pi(a, b, mk_arrow(a, Not(a), b)))) return env end function decl_bools(env, ls) for i = 1, #ls do env = add_decl(env, mk_constant_assumption(ls[i]:data(), Prop)) end return env end function Consts(s) -- Auxiliary function for creating multiple constants local r = {} local i = 1 for c in string.gmatch(s, '[^ ,;\t\n]+') do r[i] = Const(c) i = i + 1 end return unpack(r) end function OR(...) -- Nary Or local arg = {...} if #arg == 0 then return False elseif #arg == 1 then return arg[1] else local r = arg[#arg] for i = #arg-1, 1, -1 do r = Or(arg[i], r) end return r end end function print_types(env, ...) local arg = {...} local tc = type_checker(env) for i = 1, #arg do print(tostring(arg[i]) .. " : " .. tostring(tc:check(arg[i]))) end end function assert_some_axioms(env) -- Assert some clauses local l1, l2, l3, l4, l5, l6 = Consts("l1 l2 l3 l4 l5 l6") env = decl_bools(env, {l1, l2, l3, l4, l5}) env = add_decl(env, mk_definition("l6", Prop, l3, {opaque=false})) -- l6 is alias for l3 env = add_decl(env, mk_axiom("H1", OR(l1, l2, Not(l3)))) env = add_decl(env, mk_axiom("H2", OR(l2, l3, l4))) env = add_decl(env, mk_axiom("H3", OR(Not(l1), l2, l4, l5))) env = add_decl(env, mk_axiom("H4", OR(l4, l6, Not(l5)))) env = add_decl(env, mk_axiom("H5", OR(Not(l4), l3))) env = add_decl(env, mk_axiom("H6", Not(l3))) env = add_decl(env, mk_axiom("H7", Not(l2))) return env end local env = bare_environment({trust_lvl=1}) env = init_env(env) env = assert_some_axioms(env) local l1, l2, l3, l4, l5, l6 = Consts("l1 l2 l3 l4 l5 l6") local H1, H2, H3, H4, H5, H6, H7 = Consts("H1 H2 H3 H4 H5 H6 H7") local tc = type_checker(env) print(tc:check(Or)) print(tc:check(Const("absurd_elim"))) print(tc:check(H4)) local Pr1 = resolve_macro(l6, H2, H1) local Pr2 = resolve_macro(l1, Pr1, H3) assert(Pr1:is_macro()) assert(Pr1:macro_num_args() == 3) assert(Pr1:macro_arg(0) == l6) assert(Pr1:macro_def() == Pr2:macro_def()) assert(Pr1:data() == Pr1:macro_def()) assert(Pr1 == mk_macro(Pr1:macro_def(), {Pr1:macro_arg(0), Pr1:macro_arg(1), Pr1:macro_arg(2)})) assert(Pr1:macro_def():name() == name("resolve")) assert(Pr1:macro_def():trust_level() >= 0) print(Pr1:macro_def():hash()) print(Pr1:macro_def()) print("-----------") print(tc:check(H2)) print(tc:check(H1)) print(tc:check(Pr1)) print(tc:check(H3)) print(tc:check(Pr2)) local Pr3 = resolve_macro(l4, resolve_macro(l5, Pr2, H4), H5) print(tc:check(Pr3)) local Pr4 = resolve_macro(l2, resolve_macro(l3, Pr3, H6), H7) print("-----------") print("proof for false: ") print_types(env, H1, H2, H3, H4, H5, H6, H7) print(tostring(Pr4) .. " : " .. tostring(tc:check(Pr4))) print("----------------") local env = bare_environment({trust_lvl=1}) env = init_env(env) env = assert_some_axioms(env) local tc = type_checker(env) -- Since the trust_lvl is 0, the macro will be expanded during type checking print(tc:whnf(Pr1)) print(tc:check(Pr1)) print(tc:check(Pr4)) print(env:normalize(Pr4)) local a = Const("a") assert(not pcall(function() a:macro_num_args() end)) assert(not pcall(function() a:let_name() end)) assert(not pcall(function() mk_arrow(a) end))
fix(tests/lua/res1): adjust test to recent modifications
fix(tests/lua/res1): adjust test to recent modifications
Lua
apache-2.0
fpvandoorn/lean,leodemoura/lean,sp3ctum/lean,fgdorais/lean,soonhokong/lean-windows,fpvandoorn/lean2,soonhokong/lean-osx,c-cube/lean,leanprover-community/lean,johoelzl/lean,fgdorais/lean,eigengrau/lean,avigad/lean,leanprover-community/lean,eigengrau/lean,digama0/lean,sp3ctum/lean,johoelzl/lean,soonhokong/lean-osx,eigengrau/lean,avigad/lean,eigengrau/lean,c-cube/lean,dselsam/lean,soonhokong/lean-osx,leanprover/lean,leodemoura/lean,dselsam/lean,dselsam/lean,dselsam/lean,UlrikBuchholtz/lean,levnach/lean,avigad/lean,leanprover-community/lean,avigad/lean,leanprover-community/lean,javra/lean,johoelzl/lean,leanprover/lean,johoelzl/lean,leanprover-community/lean,leanprover/lean,soonhokong/lean-windows,soonhokong/lean-windows,levnach/lean,UlrikBuchholtz/lean,fpvandoorn/lean,digama0/lean,rlewis1988/lean,sp3ctum/lean,leanprover/lean,fpvandoorn/lean2,digama0/lean,Kha/lean,fgdorais/lean,johoelzl/lean,rlewis1988/lean,digama0/lean,fpvandoorn/lean,dselsam/lean,UlrikBuchholtz/lean,javra/lean,sp3ctum/lean,Kha/lean,avigad/lean,leodemoura/lean,rlewis1988/lean,javra/lean,rlewis1988/lean,levnach/lean,dselsam/lean,digama0/lean,leodemoura/lean,sp3ctum/lean,eigengrau/lean,leanprover/lean,c-cube/lean,fpvandoorn/lean2,rlewis1988/lean,Kha/lean,Kha/lean,htzh/lean,fpvandoorn/lean,soonhokong/lean,soonhokong/lean-osx,c-cube/lean,avigad/lean,fpvandoorn/lean,fpvandoorn/lean,javra/lean,rlewis1988/lean,htzh/lean,fpvandoorn/lean2,soonhokong/lean-windows,soonhokong/lean-windows,leanprover-community/lean,htzh/lean,soonhokong/lean,c-cube/lean,fgdorais/lean,fpvandoorn/lean2,UlrikBuchholtz/lean,soonhokong/lean,UlrikBuchholtz/lean,levnach/lean,htzh/lean,soonhokong/lean,Kha/lean,htzh/lean,soonhokong/lean,digama0/lean,fgdorais/lean,fgdorais/lean,levnach/lean,leanprover/lean,leodemoura/lean,soonhokong/lean-osx,johoelzl/lean,leodemoura/lean,Kha/lean,javra/lean
7a7ce8947895423b0e7456e335c9a55a912023bb
src/extensions/cp/apple/finalcutpro/browser/Columns.lua
src/extensions/cp/apple/finalcutpro/browser/Columns.lua
--- === cp.apple.finalcutpro.browser.Columns === --- --- Final Cut Pro Browser List View Columns local require = require --local log = require("hs.logger").new("Columns") local ax = require("hs._asm.axuielement") local geometry = require("hs.geometry") local axutils = require("cp.ui.axutils") local tools = require("cp.tools") local Element = require("cp.ui.Element") local Menu = require("cp.ui.Menu") local systemElementAtPosition = ax.systemElementAtPosition local childWithRole = axutils.childWithRole -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local Columns = Element:subclass("cp.apple.finalcutpro.browser.Columns") --- cp.apple.finalcutpro.browser.Columns(parent) -> Columns --- Constructor --- Constructs a new Columns object. --- --- Parameters: --- * parent - The parent object --- --- Returns: --- * The new `Columns` instance. function Columns:initialize(parent) local UI = parent.UI:mutate(function(original) return childWithRole(original(), "AXScrollArea") end) Element.initialize(self, parent, UI) end --- cp.apple.finalcutpro.browser.Columns:show() -> self --- Method --- Shows the Browser List View columns menu popup. --- --- Parameters: --- * None --- --- Returns: --- * Self function Columns:show() local ui = self:UI() if ui then local scrollAreaFrame = ui:attributeValue("AXFrame") local outlineUI = axutils.childWithRole(ui, "AXOutline") local outlineFrame = outlineUI and outlineUI:attributeValue("AXFrame") if scrollAreaFrame and outlineFrame then local headerHeight = (scrollAreaFrame.h - outlineFrame.h) / 2 local point = geometry.point(scrollAreaFrame.x+headerHeight, scrollAreaFrame.y+headerHeight) local element = point and systemElementAtPosition(point) if element and element:attributeValue("AXParent"):attributeValue("AXParent") == outlineUI then --cp.dev.highlightPoint(point) tools.ninjaRightMouseClick(point) end end end return self end --- cp.apple.finalcutpro.browser.Columns:isMenuShowing() -> boolean --- Method --- Is the Columns menu popup showing? --- --- Parameters: --- * None --- --- Returns: --- * `true` if the columns menu popup is showing, otherwise `false` function Columns:isMenuShowing() return self:menu():isShowing() end --- cp.apple.finalcutpro.browser.Columns:menu() -> cp.ui.Menu --- Method --- Gets the Columns menu object. --- --- Parameters: --- * None --- --- Returns: --- * A `Menu` object. function Columns.lazy.method:menu() return Menu(self, self.UI:mutate(function(original) return childWithRole(childWithRole(childWithRole(original(), "AXOutline"), "AXGroup"), "AXMenu") end)) end return Columns
--- === cp.apple.finalcutpro.browser.Columns === --- --- Final Cut Pro Browser List View Columns local require = require --local log = require("hs.logger").new("Columns") local ax = require("hs._asm.axuielement") local geometry = require("hs.geometry") local axutils = require("cp.ui.axutils") local tools = require("cp.tools") local Element = require("cp.ui.Element") local Menu = require("cp.ui.Menu") local systemElementAtPosition = ax.systemElementAtPosition local childWithRole = axutils.childWithRole -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local Columns = Element:subclass("cp.apple.finalcutpro.browser.Columns") --- cp.apple.finalcutpro.browser.Columns(parent) -> Columns --- Constructor --- Constructs a new Columns object. --- --- Parameters: --- * parent - The parent object --- --- Returns: --- * The new `Columns` instance. function Columns:initialize(parent) local UI = parent.UI:mutate(function(original) return childWithRole(original(), "AXScrollArea") end) Element.initialize(self, parent, UI) end --- getVisibleHeightOfAXOutline(ui) -> number | nil --- Constructor --- Gets the visible height of an `AXOutline` object. --- --- Parameters: --- * ui - The `AXOutline` object to check. --- --- Returns: --- * The height of the visible area of the `AXOutline` or `nil` if something goes wrong. local function getVisibleHeightOfAXOutline(ui) if ui then local visibleRows = ui:attributeValue("AXVisibleRows") if visibleRows and #visibleRows >= 1 then local firstRowUI = ui:attributeValue("AXChildren")[1] local lastRowUI = ui:attributeValue("AXChildren")[#visibleRows] if firstRowUI and lastRowUI then local firstFrame = firstRowUI:attributeValue("AXFrame") local lastFrame = lastRowUI:attributeValue("AXFrame") local top = firstFrame and firstFrame.y local bottom = lastFrame and lastFrame.y + lastFrame.h if top and bottom then return bottom - top end end end end end --- cp.apple.finalcutpro.browser.Columns:show() -> self --- Method --- Shows the Browser List View columns menu popup. --- --- Parameters: --- * None --- --- Returns: --- * Self function Columns:show() local ui = self:UI() if ui then local scrollAreaFrame = ui:attributeValue("AXFrame") local outlineUI = childWithRole(ui, "AXOutline") local visibleHeight = getVisibleHeightOfAXOutline(outlineUI) local outlineFrame = outlineUI and outlineUI:attributeValue("AXFrame") if scrollAreaFrame and outlineFrame and visibleHeight then local headerHeight = (scrollAreaFrame.h - visibleHeight) / 2 local point = geometry.point(scrollAreaFrame.x+headerHeight, scrollAreaFrame.y+headerHeight) local element = point and systemElementAtPosition(point) if element and element:attributeValue("AXParent"):attributeValue("AXParent") == outlineUI then --cp.dev.highlightPoint(point) tools.ninjaRightMouseClick(point) end end end return self end --- cp.apple.finalcutpro.browser.Columns:isMenuShowing() -> boolean --- Method --- Is the Columns menu popup showing? --- --- Parameters: --- * None --- --- Returns: --- * `true` if the columns menu popup is showing, otherwise `false` function Columns:isMenuShowing() return self:menu():isShowing() end --- cp.apple.finalcutpro.browser.Columns:menu() -> cp.ui.Menu --- Method --- Gets the Columns menu object. --- --- Parameters: --- * None --- --- Returns: --- * A `Menu` object. function Columns.lazy.method:menu() return Menu(self, self.UI:mutate(function(original) return childWithRole(childWithRole(childWithRole(original(), "AXOutline"), "AXGroup"), "AXMenu") end)) end return Columns
#1701
#1701 - Fixed a bug where `cp.apple.finalcutpro.browser.Columns:show()` would fail if you had a really massive amount of content in list view. - Closes #1701
Lua
mit
fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks
68ea2078c736761a3e58de8bc71dd5c0ba690f27
share/lua/website/spiegel.lua
share/lua/website/spiegel.lua
-- libquvi-scripts -- Copyright (C) 2010-2011,2013 Toni Gundogdu <[email protected]> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- 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; either -- 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 Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- -- -- NOTE: mp4s do not appear to be available (404) even if listed. -- local Spiegel = {} -- Utility functions unique to this script -- Identify the script. function ident(self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "spiegel%.de" r.formats = "default|best" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/video/"}) return r end -- Query available formats. function query_formats(self) Spiegel.get_media_id(self) local config = Spiegel.get_config(self) local formats = Spiegel.iter_formats(config) local t = {} for _,v in pairs(formats) do table.insert(t, Spiegel.to_s(v)) end table.sort(t) self.formats = table.concat(t, "¦") return self end -- Parse media URL. function parse(self) self.host_id = "spiegel" local p = quvi.fetch(self.page_url) self.title = p:match('"spVideoTitle">(.-)<') or error('no match: media title') self.thumbnail_url = p:match('"og:image" content="(.-)"') or '' Spiegel.get_media_id(self) local config = Spiegel.get_config(self) local formats = Spiegel.iter_formats(config) local U = require 'quvi/util' local format = U.choose_format(self, formats, Spiegel.choose_best, Spiegel.choose_default, Spiegel.to_s) or error("unable to choose format") self.duration = (format.duration or 0) * 1000 -- to msec self.url = {format.url or error("no match: media url")} return self end -- -- Utility functions -- function Spiegel.get_media_id(self) self.id = self.page_url:match("/video/.-video%-(.-)%.") or error ("no match: media id") end function Spiegel.get_config(self) local fmt_s = "http://video.spiegel.de/flash/%s.xml" local config_url = string.format(fmt_s, self.id) return quvi.fetch(config_url, {fetch_type = 'config'}) end function Spiegel.iter_formats(config) local p = '<filename>(.-)<' .. '.-<codec>(.-)<' .. '.-<totalbitrate>(%d+)' .. '.-<width>(%d+)' .. '.-<height>(%d+)' .. '.-<duration>(%d+)' local t = {} for fn,c,b,w,h,d in config:gmatch(p) do local cn = fn:match('%.(%w+)$') or error('no match: container') local u = 'http://video.spiegel.de/flash/' .. fn -- print(u,c,b,w,h,cn,d) table.insert(t, {codec=string.lower(c), url=u, width=tonumber(w), height=tonumber(h), bitrate=tonumber(b), duration=tonumber(d), container=cn}) end return t end function Spiegel.choose_best(formats) -- Highest quality available local r = {width=0, height=0, bitrate=0, url=nil} local U = require 'quvi/util' for _,v in pairs(formats) do if U.is_higher_quality(v,r) then r = v end end return r end function Spiegel.choose_default(formats) -- Lowest quality available local r = {width=0xffff, height=0xffff, bitrate=0xffff, url=nil} local U = require 'quvi/util' for _,v in pairs(formats) do if U.is_lower_quality(v,r) then r = v end end return r end function Spiegel.to_s(t) return string.format('%s_%s_%sk_%sp', t.container, t.codec, t.bitrate, t.height) end -- vim: set ts=4 sw=4 tw=72 expandtab:
-- libquvi-scripts -- Copyright (C) 2010-2011,2013 Toni Gundogdu <[email protected]> -- -- This file is part of libquvi-scripts <http://quvi.sourceforge.net/>. -- -- 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; either -- 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 Street, Fifth Floor, Boston, MA -- 02110-1301 USA -- -- -- NOTE: mp4s do not appear to be available (404) even if listed. -- local Spiegel = {} -- Utility functions unique to this script -- Identify the script. function ident(self) package.path = self.script_dir .. '/?.lua' local C = require 'quvi/const' local r = {} r.domain = "spiegel%.de" r.formats = "default|best" r.categories = C.proto_http local U = require 'quvi/util' r.handles = U.handles(self.page_url, {r.domain}, {"/video/"}) return r end -- Query available formats. function query_formats(self) Spiegel.get_media_id(self) local config = Spiegel.get_config(self) local formats = Spiegel.iter_formats(config) local t = {} for _,v in pairs(formats) do table.insert(t, Spiegel.to_s(v)) end table.sort(t) self.formats = table.concat(t, "¦") return self end -- Parse media URL. function parse(self) self.host_id = "spiegel" local p = quvi.fetch(self.page_url) self.title = p:match('"spVideoTitle">(.-)<') or error('no match: media title') self.thumbnail_url = p:match('"og:image" content="(.-)"') or '' Spiegel.get_media_id(self) local config = Spiegel.get_config(self) local formats = Spiegel.iter_formats(config) local U = require 'quvi/util' local format = U.choose_format(self, formats, Spiegel.choose_best, Spiegel.choose_default, Spiegel.to_s) or error("unable to choose format") self.duration = (format.duration or 0) * 1000 -- to msec self.url = {format.url or error("no match: media url")} return self end -- -- Utility functions -- function Spiegel.get_media_id(self) self.id = self.page_url:match("/video/.-video%-(.-)%.") or error ("no match: media id") end function Spiegel.get_config(self) local fmt_s = "http://video.spiegel.de/flash/%s.xml" local config_url = string.format(fmt_s, self.id) return quvi.fetch(config_url, {fetch_type = 'config'}) end function Spiegel.iter_formats(config) local p = '<filename>(.-)<' .. '.-<codec>(.-)<' .. '.-<totalbitrate>(%d+)' .. '.-<width>(%d+)' .. '.-<height>(%d+)' .. '.-<duration>(%d+)' local t = {} for fn,c,b,w,h,d in config:gmatch(p) do local cn = fn:match('%.(%w+)$') or error('no match: container') local u = 'http://video.spiegel.de/flash/' .. fn -- print(u,c,b,w,h,cn,d) table.insert(t, {codec=string.lower(c), url=u, width=tonumber(w), height=tonumber(h), bitrate=tonumber(b), duration=tonumber(d), container=cn}) end return t end function Spiegel.choose_best(formats) -- Highest quality available local r = {width=0, height=0, bitrate=0, url=nil} local U = require 'quvi/util' for _,v in pairs(formats) do if U.is_higher_quality(v,r) then r = v end end return r end function Spiegel.choose_default(formats) return formats[1] end function Spiegel.to_s(t) return string.format('%s_%s_%sk_%sp', t.container, t.codec, t.bitrate, t.height) end -- vim: set ts=4 sw=4 tw=72 expandtab:
FIX: website/spiegel.lua: choose_default
FIX: website/spiegel.lua: choose_default Choosing to use the "lowest quality" stream (3gp) as the 'default' stream would cause HTTP/404 when the stream was accessed. Although this stream is listed among those available ones, it appears to be missing for most videos (if not all). Spiegel.choose_default: Return the first available stream as the new 'default' stream. Signed-off-by: Toni Gundogdu <[email protected]>
Lua
agpl-3.0
legatvs/libquvi-scripts,alech/libquvi-scripts,alech/libquvi-scripts,legatvs/libquvi-scripts
615b4b66575a5b74a0608864f97c9a0f34ce3979
Modules/Utility/os.lua
Modules/Utility/os.lua
-- to use: local os = require(this_script) -- @author Narrev -- Please message Narrev (on Roblox) for any functionality you would like added --[[ This adds os.date back to Roblox! It functions just like Lua's built-in os.date, but with a few additions. Note: Padding can be toggled by inserting a '_' like so: os.date("%_x", os.time()) Note: tick() is the default unix time used for os.date() os.date("*t") returns a table with the following indices: hour 14 min 36 wday 1 year 2003 yday 124 month 5 sec 33 day 4 String reference: %a abbreviated weekday name (e.g., Wed) %A full weekday name (e.g., Wednesday) %b abbreviated month name (e.g., Sep) %B full month name (e.g., September) %c date and time (e.g., 09/16/98 23:48:10) %d day of the month (16) [01-31] %H hour, using a 24-hour clock (23) [00-23] %I hour, using a 12-hour clock (11) [01-12] %j day of year [01-365] %M minute (48) [00-59] %m month (09) [01-12] %n New-line character ('\n') %p either "am" or "pm" ('_' makes it uppercase) %r 12-hour clock time * 02:55:02 pm %R 24-hour HH:MM time, equivalent to %H:%M 14:55 %s day suffix %S second (10) [00-61] %t Horizontal-tab character ('\t') %T Basically %r but without seconds (HH:MM AM), equivalent to %I:%M %p 2:55 pm %u ISO 8601 weekday as number with Monday as 1 (1-7) 4 %w weekday (3) [0-6 = Sunday-Saturday] %x date (e.g., 09/16/98) %X time (e.g., 23:48:10) %Y full year (1998) %y two-digit year (98) [00-99] %% the character `%´ os.clock() returns how long the server has been active, or more realistically, how long since when you required this module os.UTCToTick returns your time in seconds given @param UTC time in seconds --]] local firstRequired = os.time() --local overflow = (require(game:GetService("ReplicatedStorage"):WaitForChild("NevermoreEngine")).LoadLibrary)("table").overflow return { date = function(optString, unix) local stringPassed = false if not (optString == nil and unix == nil) then -- This adds compatibility for Roblox JSON and MarketPlace format, and the different ways this function accepts parameters if type(optString) == "number" or optString:match("/Date%((%d+)") or optString:match("%d+\-%d+\-%d+T%d+:%d+:[%d%.]+.+") then -- if they didn't pass a non unix time unix, optString = optString elseif type(optString) == "string" then assert(optString:find("*t") or optString:find("%%"), "Invalid string passed to os.date") unix, optString = optString:find("^!") and os.time() or unix, optString:find("^!") and optString:sub(2) or optString stringPassed = true end if type(unix) == "string" then if unix:match("/Date%((%d+)") then -- This is for a certain JSON compatibility. It works the same even if you don't need it unix = unix:match("/Date%((%d+)") / 1000 elseif unix:match("%d+\-%d+\-%d+T%d+:%d+:[%d%.]+.+") then -- Untested MarketPlaceService compatibility -- This part of the script is untested local year, month, day, hour, minute, second = unix:match("(%d+)\-(%d+)\-(%d+)T(%d+):(%d+):([%d%.]+).+") unix = os.time{year = year, month = month, day = day, hour = hour, minute = minute, second = second} end end end local floor, ceil = math.floor, math.ceil local overflow = function(tab, seed) for i, value in ipairs(tab) do if seed - value <= 0 then return i, seed end seed = seed - value end end local getLeaps = function(yr) local yr = yr - 1 return floor(yr/4) - floor(yr/100) + floor(yr/400) end local dayAlign = unix == 0 and 1 or 0 -- fixes calculation for unix == 0 local unix = type(unix) == "number" and unix + dayAlign or tick() local days, month, year = ceil(unix / 86400) + 719527 local wday = (days + 6) % 7 local _4Years = floor(days % 146097 / 1461) * 4 + floor(days / 146097) * 400 year, days = overflow({366,365,365,365}, days - 365*_4Years - getLeaps(_4Years)) -- [0-1461] year, _4Years = year + _4Years - 1 local yDay = days month, days = overflow({31,(year%4==0 and(year%100~=0 or year%400==0))and 29 or 28,31,30,31,30,31,31,30,31,30,31}, days) local hours = floor(unix / 3600 % 24) local minutes = floor(unix / 60 % 60) local seconds = floor(unix % 60) - dayAlign local dayNamesAbbr = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"} -- Consider using dayNames[wday + 1]:sub(1,3) local dayNames = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"} local months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"} local suffixes = {"st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "st"} if stringPassed then local padded = function(num) return string.format("%02d", num) end return ( optString :gsub("%%c", "%%x %%X") :gsub("%%_c", "%%_x %%_X") :gsub("%%x", "%%m/%%d/%%y") :gsub("%%_x", "%%_m/%%_d/%%y") :gsub("%%X", "%%H:%%M:%%S") :gsub("%%_X", "%%_H:%%M:%%S") :gsub("%%T", "%%I:%%M %%p") :gsub("%%_T", "%%_I:%%M %%p") :gsub("%%r", "%%I:%%M:%%S %%p") :gsub("%%_r", "%%_I:%%M:%%S %%p") :gsub("%%R", "%%H:%%M") :gsub("%%_R", "%%_H:%%M") :gsub("%%a", dayNamesAbbr[wday + 1]) :gsub("%%A", dayNames[wday + 1]) :gsub("%%b", months[month]:sub(1,3)) :gsub("%%B", months[month]) :gsub("%%d", padded(days)) :gsub("%%_d", days) :gsub("%%H", padded(hours)) :gsub("%%_H", hours) :gsub("%%I", padded(hours > 12 and hours - 12 or hours == 0 and 12 or hours)) :gsub("%%_I", hours > 12 and hours - 12 or hours == 0 and 12 or hours) :gsub("%%j", padded(yDay)) :gsub("%%_j", yDay) :gsub("%%M", padded(minutes)) :gsub("%%_M", minutes) :gsub("%%m", padded(month)) :gsub("%%_m", month) :gsub("%%n","\n") :gsub("%%p", hours >= 12 and "pm" or "am") :gsub("%%_p", hours >= 12 and "PM" or "AM") :gsub("%%s", suffixes[days]) :gsub("%%S", padded(seconds)) :gsub("%%_S", seconds) :gsub("%%t", "\t") :gsub("%%u", wday == 0 and 7 or wday) :gsub("%%w", wday) :gsub("%%Y", year) :gsub("%%y", padded(year % 100)) :gsub("%%_y", year % 100) :gsub("%%%%", "%%") ) end return {year = year, month = month, day = days, yday = yDay, wday = wday, hour = hours, min = minutes, sec = seconds} end; UTCToTick = function(time) -- UTC time in seconds to your time in seconds -- This is for scheduling Roblox events across timezones return time + math.ceil(tick()) - os.time() end; time = function(...) return os.time(...) end; difftime = function(...) return os.difftime(...) end; clock = function(...) return os.difftime(os.time(), firstRequired) end; }
-- to use: local os = require(this_script) -- @author Narrev -- Please message Narrev (on Roblox) for any functionality you would like added --[[ This adds os.date back to Roblox! It functions just like Lua's built-in os.date, but with a few additions. Note: Padding can be toggled by inserting a '_' like so: os.date("%_x", os.time()) Note: tick() is the default unix time used for os.date() os.date("*t") returns a table with the following indices: hour 14 min 36 wday 1 year 2003 yday 124 month 5 sec 33 day 4 String reference: %a abbreviated weekday name (e.g., Wed) %A full weekday name (e.g., Wednesday) %b abbreviated month name (e.g., Sep) %B full month name (e.g., September) %c date and time (e.g., 09/16/98 23:48:10) %d day of the month (16) [01-31] %H hour, using a 24-hour clock (23) [00-23] %I hour, using a 12-hour clock (11) [01-12] %j day of year [01-365] %M minute (48) [00-59] %m month (09) [01-12] %n New-line character ('\n') %p either "am" or "pm" ('_' makes it uppercase) %r 12-hour clock time * 02:55:02 pm %R 24-hour HH:MM time, equivalent to %H:%M 14:55 %s day suffix %S second (10) [00-61] %t Horizontal-tab character ('\t') %T Basically %r but without seconds (HH:MM AM), equivalent to %I:%M %p 2:55 pm %u ISO 8601 weekday as number with Monday as 1 (1-7) 4 %w weekday (3) [0-6 = Sunday-Saturday] %x date (e.g., 09/16/98) %X time (e.g., 23:48:10) %Y full year (1998) %y two-digit year (98) [00-99] %% the character `%´ os.clock() returns how long the server has been active, or more realistically, how long since when you required this module os.UTCToTick returns your time in seconds given @param UTC time in seconds --]] local firstRequired = os.time() --local overflow = (require(game:GetService("ReplicatedStorage"):WaitForChild("NevermoreEngine")).LoadLibrary)("table").overflow return { date = function(optString, unix) local stringPassed = false if not (optString == nil and unix == nil) then -- This adds compatibility for Roblox JSON and MarketPlace format, and the different ways this function accepts parameters if type(optString) == "number" or optString:match("/Date%((%d+)") or optString:match("%d+\-%d+\-%d+T%d+:%d+:[%d%.]+.+") then -- if they didn't pass a non unix time unix, optString = optString elseif type(optString) == "string" and optString ~= "*t" then assert(optString:find("%%[_cxXTrRaAbBdHIjMmnpsStuwyY]"), "Invalid string passed to os.date") unix, optString = optString:find("^!") and os.time() or unix, optString:find("^!") and optString:sub(2) or optString stringPassed = true end if type(unix) == "string" then -- If it is a unix time, but in a Roblox format if unix:match("/Date%((%d+)") then -- This is for a certain JSON compatibility. It works the same even if you don't need it unix = unix:match("/Date%((%d+)") / 1000 elseif unix:match("%d+\-%d+\-%d+T%d+:%d+:[%d%.]+.+") then -- Untested MarketPlaceService compatibility -- This part of the script is untested local year, month, day, hour, minute, second = unix:match("(%d+)\-(%d+)\-(%d+)T(%d+):(%d+):([%d%.]+).+") unix = os.time{year = year, month = month, day = day, hour = hour, minute = minute, second = second} end end else optString, stringPassed = "%c", true end local floor, ceil = math.floor, math.ceil local overflow = function(tab, seed) for i, value in ipairs(tab) do if seed - value <= 0 then return i, seed end seed = seed - value end end local getLeaps = function(yr) local yr = yr - 1 return floor(yr/4) - floor(yr/100) + floor(yr/400) end local dayAlign = unix == 0 and 1 or 0 -- fixes calculation for unix == 0 local unix = type(unix) == "number" and unix + dayAlign or tick() local days, month, year = ceil(unix / 86400) + 719527 local wday = (days + 6) % 7 local _4Years = floor(days % 146097 / 1461) * 4 + floor(days / 146097) * 400 year, days = overflow({366,365,365,365}, days - 365*_4Years - getLeaps(_4Years)) -- [0-1461] year, _4Years = year + _4Years - 1 local yDay = days month, days = overflow({31,(year%4==0 and(year%100~=0 or year%400==0))and 29 or 28,31,30,31,30,31,31,30,31,30,31}, days) local hours = floor(unix / 3600 % 24) local minutes = floor(unix / 60 % 60) local seconds = floor(unix % 60) - dayAlign local dayNamesAbbr = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"} -- Consider using dayNames[wday + 1]:sub(1,3) local dayNames = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"} local months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"} local suffixes = {"st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th", "th", "st"} if stringPassed then local padded = function(num) return string.format("%02d", num) end return ( optString :gsub("%%c", "%%x %%X") :gsub("%%_c", "%%_x %%_X") :gsub("%%x", "%%m/%%d/%%y") :gsub("%%_x", "%%_m/%%_d/%%y") :gsub("%%X", "%%H:%%M:%%S") :gsub("%%_X", "%%_H:%%M:%%S") :gsub("%%T", "%%I:%%M %%p") :gsub("%%_T", "%%_I:%%M %%p") :gsub("%%r", "%%I:%%M:%%S %%p") :gsub("%%_r", "%%_I:%%M:%%S %%p") :gsub("%%R", "%%H:%%M") :gsub("%%_R", "%%_H:%%M") :gsub("%%a", dayNamesAbbr[wday + 1]) :gsub("%%A", dayNames[wday + 1]) :gsub("%%b", months[month]:sub(1,3)) :gsub("%%B", months[month]) :gsub("%%d", padded(days)) :gsub("%%_d", days) :gsub("%%H", padded(hours)) :gsub("%%_H", hours) :gsub("%%I", padded(hours > 12 and hours - 12 or hours == 0 and 12 or hours)) :gsub("%%_I", hours > 12 and hours - 12 or hours == 0 and 12 or hours) :gsub("%%j", padded(yDay)) :gsub("%%_j", yDay) :gsub("%%M", padded(minutes)) :gsub("%%_M", minutes) :gsub("%%m", padded(month)) :gsub("%%_m", month) :gsub("%%n","\n") :gsub("%%p", hours >= 12 and "pm" or "am") :gsub("%%_p", hours >= 12 and "PM" or "AM") :gsub("%%s", suffixes[days]) :gsub("%%S", padded(seconds)) :gsub("%%_S", seconds) :gsub("%%t", "\t") :gsub("%%u", wday == 0 and 7 or wday) :gsub("%%w", wday) :gsub("%%Y", year) :gsub("%%y", padded(year % 100)) :gsub("%%_y", year % 100) :gsub("%%%%", "%%") ) end return {year = year, month = month, day = days, yday = yDay, wday = wday, hour = hours, min = minutes, sec = seconds} end; UTCToTick = function(time) -- UTC time in seconds to your time in seconds -- This is for scheduling Roblox events across timezones return time + math.ceil(tick()) - os.time() end; time = function(...) return os.time(...) end; difftime = function(...) return os.difftime(...) end; clock = function(...) return os.difftime(os.time(), firstRequired) end; }
Re-added compatibility to "*t" and no arguments
Re-added compatibility to "*t" and no arguments Also fixed erroring for invalid strings
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
495ae59c054c7f62fff84abcc3504cac2f2d0c66
OS/CartOS/terminal.lua
OS/CartOS/terminal.lua
--The terminal !-- local PATH = "C://Programs/;" local curdrive, curdir, curpath = "C", "/", "C://" local function nextPath(p) if p:sub(-1)~=";" then p=p..";" end return p:gmatch("(.-);") end printCursor(1,1,1) color(9) print("LIKO-12 V0.6.0 DEV") color(8) print("CartOS DEV B1") flip() sleep(0.5) color(7) print("\nA PICO-8 CLONE OS WITH EXTRA ABILITIES") flip() sleep(0.25) color(10) print("TYPE HELP FOR HELP") flip() sleep(0.25) local history = {} local btimer, btime, blink = 0, 0.5, true local function checkCursor() local cx, cy = printCursor() local tw, th = termsize() if cx > tw+1 then cx = tw+1 end if cx < 1 then cx = 1 end if cy > th+1 then cy = th+1 end if cy < 1 then cy = 1 end printCursor(cx,cy) cy = cy-1 rect(cx*4-2,cy*8+2,4,5,false,blink and 5 or 1) end local function split(str) local t = {} for val in str:gmatch("%S+") do table.insert(t, val) end return unpack(t) end local term = {} function term.setdrive(d) if type(d) ~= "string" then return error("DriveLetter must be a string, provided: "..type(d)) end if not fs.drives()[d] then return error("Drive '"..d.."' doesn't exists !") end curdrive = d curpath = cudrive..":/"..curdir end function term.setdirectory(d) if type(d) ~= "string" then return error("Directory must be a string, provided: "..type(d)) end if not fs.exists(curdrive..":/"..d) then return error("Directory doesn't exists !") end if not fs.isDirectory(curdrive..":/"..d) then return error("It must be a directory, not a file") end curdir = d curpath = curdrive..":/"..d end function term.setpath(p) if type(p) ~= "string" then return error("Patj must be a string, provided: "..type(p)) end local dv, d = p:match("(.+)://(.+)") if (not dv) or (not d) then return error("Invalied path: "..p) end if not fs.drives()[dv] then return error("Drive '"..dv.."' doesn't exists !") end if d:sub(0,1) ~= "/" then d = "/"..d end if not fs.exists(dv..":/"..d) then return error("Directory doesn't exists !") end if not fs.isDirectory(dv..":/"..d) then return error("It must be a directory, not a file") end curdrive, curdir, curpath = dv, d, dv..":/"..d end function term.getpath() return curpath end function term.getdrive() return curdrive end function term.getdirectory() return curdir end function term.setPATH(p) PATH = p end function term.getPATH() return PATH end function term.execute(command,...) if not command then print("") return false, "No command" end if fs.exists(curpath..command..".lua") then local chunk, err = fs.load(curpath..command..".lua") if not chunk then color(9) print("\nL-ERR:"..tostring(err)) color(8) return false, tostring(err) end local ok, err = pcall(chunk,...) if not ok then color(9) print("ERR: "..tostring(err)) color(8) return false, tostring(err) end color(8) return true end for path in nextPath(PATH) do local files = fs.directoryItems(path) for _,file in ipairs(files) do if file == command..".lua" then local chunk, err = fs.load(path..file) if not chunk then color(9) print("\nL-ERR:"..tostring(err)) color(8) return false, tostring(err) end local ok, err = pcall(chunk,...) if not ok then color(9) print("\nERR: "..tostring(err)) color(8) return false, tostring(err) end color(8) return true end end end color(10) print("\nFile not found") color(8) return false, "File not found" end function term.loop() --Enter the while loop of the terminal clearEStack() color(8) checkCursor() print(curdir.."> ",false) local buffer = "" while true do checkCursor() local event, a, b, c, d, e, f = pullEvent() if event == "textinput" then buffer = buffer..a print(a,false) elseif event == "keypressed" then if a == "return" then table.insert(history, buffer) blink = false; checkCursor() term.execute(split(buffer)) buffer = "" color(8) checkCursor() print(curdir.."> ",false) blink = true end elseif event == "touchpressed" then textinput(true) keyrepeat(true) elseif event == "update" then btimer = btimer + a if btimer > btime then btimer = btimer-btime blink = not blink end end end end return term
--The terminal !-- local PATH = "C://Programs/;" local curdrive, curdir, curpath = "C", "/", "C:///" local function nextPath(p) if p:sub(-1)~=";" then p=p..";" end return p:gmatch("(.-);") end printCursor(1,1,1) color(9) print("LIKO-12 V0.6.0 DEV") color(8) print("CartOS DEV B1") flip() sleep(0.5) color(7) print("\nA PICO-8 CLONE OS WITH EXTRA ABILITIES") flip() sleep(0.25) color(10) print("TYPE HELP FOR HELP") flip() sleep(0.25) local history = {} local btimer, btime, blink = 0, 0.5, true local function checkCursor() local cx, cy = printCursor() local tw, th = termsize() if cx > tw+1 then cx = tw+1 end if cx < 1 then cx = 1 end if cy > th+1 then cy = th+1 end if cy < 1 then cy = 1 end printCursor(cx,cy) cy = cy-1 rect(cx*4-2,cy*8+2,4,5,false,blink and 5 or 1) end local function split(str) local t = {} for val in str:gmatch("%S+") do table.insert(t, val) end return unpack(t) end local term = {} function term.setdrive(d) if type(d) ~= "string" then return error("DriveLetter must be a string, provided: "..type(d)) end if not fs.drives()[d] then return error("Drive '"..d.."' doesn't exists !") end curdrive = d curpath = curdrive.."://"..curdir end function term.setdirectory(d) if type(d) ~= "string" then return error("Directory must be a string, provided: "..type(d)) end if not fs.exists(curdrive.."://"..d) then return error("Directory doesn't exists !") end if not fs.isDirectory(curdrive.."://"..d) then return error("It must be a directory, not a file") end if d:sub(0,1) ~= "/" then d = "/"..d end if d:sub(-2,-1) ~= "/" then d = d.."/" end d = d:gsub("//","/") curdir = d curpath = curdrive.."://"..d end function term.setpath(p) if type(p) ~= "string" then return error("Path must be a string, provided: "..type(p)) end local dv, d = p:match("(.+)://(.+)") if (not dv) or (not d) then return error("Invalied path: "..p) end if not fs.drives()[dv] then return error("Drive '"..dv.."' doesn't exists !") end if d:sub(0,1) ~= "/" then d = "/"..d end if d:sub(-2,-1) ~= "/" then d = d.."/" end if not fs.exists(dv.."://"..d) then return error("Directory doesn't exists !") end if not fs.isDirectory(dv.."://"..d) then return error("It must be a directory, not a file") end d = d:gsub("//","/") curdrive, curdir, curpath = dv, d, dv.."://"..d end function term.getpath() return curpath end function term.getdrive() return curdrive end function term.getdirectory() return curdir end function term.setPATH(p) PATH = p end function term.getPATH() return PATH end function term.execute(command,...) if not command then print("") return false, "No command" end if fs.exists(curpath..command..".lua") then local chunk, err = fs.load(curpath..command..".lua") if not chunk then color(9) print("\nL-ERR:"..tostring(err)) color(8) return false, tostring(err) end local ok, err = pcall(chunk,...) if not ok then color(9) print("ERR: "..tostring(err)) color(8) return false, tostring(err) end color(8) return true end for path in nextPath(PATH) do local files = fs.directoryItems(path) for _,file in ipairs(files) do if file == command..".lua" then local chunk, err = fs.load(path..file) if not chunk then color(9) print("\nL-ERR:"..tostring(err)) color(8) return false, tostring(err) end local ok, err = pcall(chunk,...) if not ok then color(9) print("\nERR: "..tostring(err)) color(8) return false, tostring(err) end color(8) return true end end end color(10) print("\nFile not found") color(8) return false, "File not found" end function term.loop() --Enter the while loop of the terminal clearEStack() color(8) checkCursor() print(term.getpath().."> ",false) local buffer = "" while true do checkCursor() local event, a, b, c, d, e, f = pullEvent() if event == "textinput" then buffer = buffer..a print(a,false) elseif event == "keypressed" then if a == "return" then table.insert(history, buffer) blink = false; checkCursor() term.execute(split(buffer)) buffer = "" color(8) checkCursor() print(term.getpath().."> ",false) blink = true end elseif event == "touchpressed" then textinput(true) keyrepeat(true) elseif event == "update" then btimer = btimer + a if btimer > btime then btimer = btimer-btime blink = not blink end end end end return term
Bugfix
Bugfix
Lua
mit
RamiLego4Game/LIKO-12
ca6d5134983a1f60e89cc11cfe49506773051956
check/plugin.lua
check/plugin.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. --]] --[[ Module for running custom agent plugins written in an arbitrary programing / scripting language. This module is backward compatibile with Cloudkick agent plugins (https://support.cloudkick.com/Creating_a_plugin). All the plugins must output information to the standard output in the format defined bellow: status <status string> metric <name 1> <type> <value> [<unit>] metric <name 2> <type> <value> [<unit>] metric <name 3> <type> <value> [<unit>] * <status string> - A status string which includes a summary of the results. * <name> Name of the metric. No spaces are allowed. If a name contains a dot, string before the dot is considered to be a metric dimension. * <type> - Metric type which can be one of: * string * gauge * float * int * [<unit>] - Metric unit, optional. A string representing the units of the metric measurement. Units may only be provided on non-string metrics, and may not contain any spaces. Examples: 'bytes', 'milliseconds', 'percent'. --]] local table = require('table') local childprocess = require('childprocess') local timer = require('timer') local path = require('path') local string = require('string') local fmt = string.format local readdir = require('fs').readdir local logging = require('logging') local LineEmitter = require('line-emitter').LineEmitter local ChildCheck = require('./base').ChildCheck local CheckResult = require('./base').CheckResult local Metric = require('./base').Metric local split = require('/base/util/misc').split local tableContains = require('/base/util/misc').tableContains local lastIndexOf = require('/base/util/misc').lastIndexOf local constants = require('/constants') local loggingUtil = require('/base/util/logging') local windowsConvertCmd = require('virgo_utils').windowsConvertCmd local toString = require('/base/util/misc').toString local PluginCheck = ChildCheck:extend() --[[ Constructor. params.details - Table with the following keys: - file (string) - Name of the plugin file. - args (table) - Command-line arguments which get passed to the plugin. - timeout (number) - Plugin execution timeout in milliseconds. --]] function PluginCheck:initialize(params) ChildCheck.initialize(self, params) if params.details.file == nil then params.details.file = '' end local file = path.basename(params.details.file) local args = params.details.args and params.details.args or {} local timeout = params.details.timeout and params.details.timeout or constants:get('DEFAULT_PLUGIN_TIMEOUT') self._full_path = params.details.file or '' self._file = file self._pluginPath = path.join(constants:get('DEFAULT_CUSTOM_PLUGINS_PATH'), file) self._pluginArgs = args self._timeout = timeout self._log = loggingUtil.makeLogger(fmt('(plugin=%s, id=%s, iid=%s)', file, self.id, self._iid)) end function PluginCheck:getType() return 'agent.plugin' end function PluginCheck:getTargets(callback) readdir(constants:get('DEFAULT_CUSTOM_PLUGINS_PATH'), function(err, files) if err then callback(err, {}) return end local i, x for i, x in ipairs(files) do if x == '.' or x == '..' then table.remove(files, i) end end callback(nil, files) end) end function PluginCheck:run(callback) local exePath local exeArgs local closeStdin exePath, exeArgs, closeStdin = windowsConvertCmd(self._pluginPath, self._pluginArgs) local cenv = self:_childEnv() -- Ruby 1.9.1p0 crashes when stdin is closed, so we let luvit take care of -- closing the pipe after the process runs. local child = self:_runChild(exePath, exeArgs, cenv, callback) if closeStdin then child.stdin:close() end end local exports = {} exports.PluginCheck = PluginCheck return exports
--[[ 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. --]] --[[ Module for running custom agent plugins written in an arbitrary programing / scripting language. This module is backward compatibile with Cloudkick agent plugins (https://support.cloudkick.com/Creating_a_plugin). All the plugins must output information to the standard output in the format defined bellow: status <status string> metric <name 1> <type> <value> [<unit>] metric <name 2> <type> <value> [<unit>] metric <name 3> <type> <value> [<unit>] * <status string> - A status string which includes a summary of the results. * <name> Name of the metric. No spaces are allowed. If a name contains a dot, string before the dot is considered to be a metric dimension. * <type> - Metric type which can be one of: * string * gauge * float * int * [<unit>] - Metric unit, optional. A string representing the units of the metric measurement. Units may only be provided on non-string metrics, and may not contain any spaces. Examples: 'bytes', 'milliseconds', 'percent'. --]] local table = require('table') local childprocess = require('childprocess') local timer = require('timer') local path = require('path') local string = require('string') local fmt = string.format local readdir = require('fs').readdir local stat = require('fs').stat local bit = require('bit') local os = require('os') local async = require('async') local logging = require('logging') local LineEmitter = require('line-emitter').LineEmitter local ChildCheck = require('./base').ChildCheck local CheckResult = require('./base').CheckResult local Metric = require('./base').Metric local split = require('/base/util/misc').split local tableContains = require('/base/util/misc').tableContains local lastIndexOf = require('/base/util/misc').lastIndexOf local constants = require('/constants') local loggingUtil = require('/base/util/logging') local windowsConvertCmd = require('virgo_utils').windowsConvertCmd local toString = require('/base/util/misc').toString local PluginCheck = ChildCheck:extend() local octal = function(s) return tonumber(s, 8) end --[[ Constructor. params.details - Table with the following keys: - file (string) - Name of the plugin file. - args (table) - Command-line arguments which get passed to the plugin. - timeout (number) - Plugin execution timeout in milliseconds. --]] function PluginCheck:initialize(params) ChildCheck.initialize(self, params) if params.details.file == nil then params.details.file = '' end local file = path.basename(params.details.file) local args = params.details.args and params.details.args or {} local timeout = params.details.timeout and params.details.timeout or constants:get('DEFAULT_PLUGIN_TIMEOUT') self._full_path = params.details.file or '' self._file = file self._pluginPath = path.join(constants:get('DEFAULT_CUSTOM_PLUGINS_PATH'), file) self._pluginArgs = args self._timeout = timeout self._log = loggingUtil.makeLogger(fmt('(plugin=%s, id=%s, iid=%s)', file, self.id, self._iid)) end function PluginCheck:getType() return 'agent.plugin' end function PluginCheck:getTargets(callback) local targets = {} local root = constants:get('DEFAULT_CUSTOM_PLUGINS_PATH') local function executeCheck(file, callback) stat(path.join(root, file), function(err, s) if err then return callback() end if not s.is_file or not s.mode then return callback() end if os.type() == 'win32' then table.insert(targets, file) else local executable = bit.bor( bit.band(s.mode, octal(1)), bit.band(s.mode, octal(10)), bit.band(s.mode, octal(100)) ) if executable ~= 0 then table.insert(targets, file) end end callback() end) end -- readdir(, function(err, files) readdir(root, function(err, files) if err then local msg if err.code == 'ENOENT' then msg = fmt('Plugin Directory, %s, does not exist', root) else msg = fmt('Error Reading Directory, %s', root, err.message) end return callback(err, { msg }) end async.forEachLimit(files, 5, executeCheck, function(err) callback(err, targets) end) end) end function PluginCheck:run(callback) local exePath local exeArgs local closeStdin exePath, exeArgs, closeStdin = windowsConvertCmd(self._pluginPath, self._pluginArgs) local cenv = self:_childEnv() -- Ruby 1.9.1p0 crashes when stdin is closed, so we let luvit take care of -- closing the pipe after the process runs. local child = self:_runChild(exePath, exeArgs, cenv, callback) if closeStdin then child.stdin:close() end end local exports = {} exports.PluginCheck = PluginCheck return exports
Fix: add unix executable filter to agent.plugin targets
Fix: add unix executable filter to agent.plugin targets Only return agent.plugin files available that match: * files only * executable on unix
Lua
apache-2.0
kaustavha/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent
9dd10787dc56c2a01d8ded687f5b94855e13b646
apicast/src/module.lua
apicast/src/module.lua
local setmetatable = setmetatable local pcall = pcall local require = require local pairs = pairs local _M = { _VERSION = '0.1' } local mt = { __index = _M } function _M.new(name) name = name or os.getenv('APICAST_MODULE') or 'apicast' ngx.log(ngx.DEBUG, 'init plugin ', name) return setmetatable({ name = name }, mt) end function _M.call(self, phase, ...) -- shortcut for requre('module').call() if not self and not phase then return _M.new():call() end -- normal instance interface local name = self.name if not name then return nil, 'not initialized' end phase = phase or ngx.get_phase() local fun = _M.load(name, phase) if fun then ngx.log(ngx.DEBUG, 'plugin ', name, ' calling phase ', phase) return fun(...) else ngx.log(ngx.DEBUG, 'plugin ', name, ' skipping phase ', phase) return nil, 'plugin does not have ' .. phase end end local prequire = function(file) return pcall(require, file) end function _M.load(name, phase) local files = { [ name .. '.' .. phase ] = 'call', -- like apicast.init exposing .call [ name ] = phase -- like apicast exposing .init } for file, method in pairs(files) do local ok, ret = prequire(file) if ok then ngx.log(ngx.DEBUG, 'plugin loaded: ', file) local f = ret[method] if f then return f else ngx.log(ngx.ERR, 'plugin ', file, ' missing function ', method) end else ngx.log(ngx.DEBUG, 'plugin not loaded: ', file) end end return nil, 'could not load plugin' end return _M
local setmetatable = setmetatable local pcall = pcall local require = require local pairs = pairs local _M = { _VERSION = '0.1' } local mt = { __index = _M } function _M.new(name) name = name or os.getenv('APICAST_MODULE') or 'apicast' ngx.log(ngx.DEBUG, 'init plugin ', name) return setmetatable({ name = name }, mt) end function _M.call(self, phase, ...) -- shortcut for requre('module').call() if not self and not phase then return _M.new():call() end -- normal instance interface local name = self.name if not name then return nil, 'not initialized' end phase = phase or ngx.get_phase() local fun = _M.load(name, phase) if fun then ngx.log(ngx.DEBUG, 'plugin ', name, ' calling phase ', phase) return fun(...) else ngx.log(ngx.DEBUG, 'plugin ', name, ' skipping phase ', phase) return nil, 'plugin does not have ' .. phase end end local cache = {} local prequire = function(file) if cache[file] then return true, cache[file] end local ok, mod = pcall(require, file) if ok then cache[file] = mod end return ok, mod end function _M.load(name, phase) local files = { [ name .. '.' .. phase ] = 'call', -- like apicast.init exposing .call [ name ] = phase -- like apicast exposing .init } for file, method in pairs(files) do local ok, ret = prequire(file) if ok and ret then ngx.log(ngx.DEBUG, 'plugin loaded: ', file) local f = ret[method] if f then return f else ngx.log(ngx.ERR, 'plugin ', file, ' missing function ', method) end elseif ok and not ret then ngx.log(ngx.ERR, 'plugin ', file, ' wasnt loaded ', method) else ngx.log(ngx.DEBUG, 'plugin not loaded: ', file) end end return nil, 'could not load plugin' end return _M
cache modules
cache modules prevents weird bug when require would not return proper module
Lua
mit
3scale/apicast,3scale/apicast,3scale/docker-gateway,3scale/apicast,3scale/docker-gateway,3scale/apicast
a2cbd72c3cda553a3bbafb0f20f2e676cb3cac3a
onmt/Model.lua
onmt/Model.lua
--[[ Generic Model class. ]] local Model = torch.class('Model') local options = { { '-model_type', 'seq2seq', [[Type of model to train. This option impacts all options choices.]], { enum = {'lm', 'seq2seq', 'seqtagger'}, structural = 0 } }, { '-param_init', 0.1, [[Parameters are initialized over uniform distribution with support (-`param_init`, `param_init`).]], { valid = onmt.utils.ExtendedCmdLine.isFloat(0), init_only = true } } } function Model.declareOpts(cmd) cmd:setCmdLineOptions(options, 'Model') end function Model:__init(args) self.args = onmt.utils.ExtendedCmdLine.getModuleOpts(args, options) self.models = {} end -- Dynamically change parameters in the graph. function Model:changeParameters(changes) _G.logger:info('Applying new parameters:') for k, v in pairs(changes) do _G.logger:info(' * %s = ' .. tostring(v), k) for _, model in pairs(self.models) do model:apply(function(m) if k == 'dropout' and torch.typename(m) == 'nn.Dropout' then m:setp(v) elseif k:find('fix_word_vecs') and torch.typename(m) == 'onmt.WordEmbedding' then local enc = k == 'fix_word_vecs_enc' and torch.typename(model):find('Encoder') local dec = k == 'fix_word_vecs_dec' and torch.typename(model):find('Decoder') if enc or dec then m:fixEmbeddings(v) end end end) end end end function Model:getInputLabelsCount(batch) return batch.sourceInput:ne(onmt.Constants.PAD):sum() end function Model:getOutputLabelsCount(batch) return self:getOutput(batch):ne(onmt.Constants.PAD):sum() end function Model:evaluate() for _, m in pairs(self.models) do m:evaluate() end end function Model:training() for _, m in pairs(self.models) do m:training() end end function Model:initParams() _G.logger:info('Initializing parameters...') local params, gradParams, orderedIndex = self:getParams() local numParams = 0 for i, key in ipairs(orderedIndex) do if params[i]:dim() > 0 then params[i]:uniform(-self.args.param_init, self.args.param_init) self.models[key]:apply(function (m) if m.postParametersInitialization then m:postParametersInitialization() end end) numParams = numParams + params[i]:size(1) end end _G.logger:info(' * number of parameters: ' .. numParams) return params, gradParams end function Model:getParams() -- Order the model table because we need all replicas to have the same order. local orderedIndex = {} for key in pairs(self.models) do table.insert(orderedIndex, key) end table.sort(orderedIndex) local params = {} local gradParams = {} for i, key in ipairs(orderedIndex) do params[i], gradParams[i] = self.models[key]:getParameters() end return params, gradParams, orderedIndex end return Model
--[[ Generic Model class. ]] local Model = torch.class('Model') local options = { { '-model_type', 'seq2seq', [[Type of model to train. This option impacts all options choices.]], { enum = {'lm', 'seq2seq', 'seqtagger'}, structural = 0 } }, { '-param_init', 0.1, [[Parameters are initialized over uniform distribution with support (-`param_init`, `param_init`).]], { valid = onmt.utils.ExtendedCmdLine.isFloat(0), init_only = true } } } function Model.declareOpts(cmd) cmd:setCmdLineOptions(options, 'Model') end function Model:__init(args) self.args = onmt.utils.ExtendedCmdLine.getModuleOpts(args, options) self.models = {} end -- Dynamically change parameters in the graph. function Model:changeParameters(changes) _G.logger:info('Applying new parameters:') for k, v in pairs(changes) do _G.logger:info(' * %s = ' .. tostring(v), k) for _, model in pairs(self.models) do model:apply(function(m) if k == 'dropout' and torch.typename(m) == 'nn.Dropout' then m:setp(v) elseif k:find('fix_word_vecs') and torch.typename(m) == 'onmt.WordEmbedding' then local enc = k == 'fix_word_vecs_enc' and torch.typename(model):find('Encoder') local dec = k == 'fix_word_vecs_dec' and torch.typename(model):find('Decoder') if enc or dec then m:fixEmbeddings(v) end end end) end end end function Model:getInputLabelsCount(batch) return batch.sourceInput:ne(onmt.Constants.PAD):sum() end function Model:getOutputLabelsCount(batch) return self:getOutput(batch):ne(onmt.Constants.PAD):sum() end function Model:evaluate() for _, m in pairs(self.models) do m:evaluate() end end function Model:training() for _, m in pairs(self.models) do m:training() end end function Model:initParams() _G.logger:info('Initializing parameters...') local params, gradParams, modelMap = self:getParams() local numParams = 0 for i = 1, #params do local name = modelMap[i] params[i]:uniform(-self.args.param_init, self.args.param_init) self.models[name]:apply(function (m) if m.postParametersInitialization then m:postParametersInitialization() end end) numParams = numParams + params[i]:size(1) end _G.logger:info(' * number of parameters: ' .. numParams) return params, gradParams end function Model:getParams() -- Order the model table because we need all replicas to have the same order. local orderedIndex = {} for key in pairs(self.models) do table.insert(orderedIndex, key) end table.sort(orderedIndex) local params = {} local gradParams = {} local modelMap = {} for i, key in ipairs(orderedIndex) do local p, gp = self.models[key]:getParameters() if p:dim() > 0 then table.insert(params, p) table.insert(gradParams, gp) table.insert(modelMap, key) end end return params, gradParams, modelMap end return Model
Do not store empty parameters set
Do not store empty parameters set Fixes #248.
Lua
mit
da03/OpenNMT,jsenellart/OpenNMT,da03/OpenNMT,OpenNMT/OpenNMT,monsieurzhang/OpenNMT,da03/OpenNMT,jungikim/OpenNMT,OpenNMT/OpenNMT,OpenNMT/OpenNMT,jungikim/OpenNMT,jsenellart-systran/OpenNMT,jsenellart/OpenNMT,jsenellart-systran/OpenNMT,jungikim/OpenNMT,monsieurzhang/OpenNMT,monsieurzhang/OpenNMT,jsenellart/OpenNMT,jsenellart-systran/OpenNMT
40cee997006a976acdf89dc610d8ac15232c3645
worldedit_commands/cuboid.lua
worldedit_commands/cuboid.lua
dofile(minetest.get_modpath("worldedit_commands") .. "/cuboidapi.lua") minetest.register_chatcommand("/outset", { params = "<amount> [h|v]", description = "outset the selection", privs = {worldedit=true}, func = function(name, param) local find, _, amount, dir = param:find("^(%d+)[%s+]?([hv]?)$") if find == nil then return false, "invalid usage: " .. param end local pos1 = worldedit.pos1[name] local pos2 = worldedit.pos2[name] if pos1 == nil or pos2 == nil then return false, "Undefined region. Region must be defined beforehand." end if dir == "" then assert(worldedit.cuboid_volumetric_expand(name, amount)) elseif dir == "h" then assert(worldedit.cuboid_linear_expand(name, 'x', 1, amount)) assert(worldedit.cuboid_linear_expand(name, 'x', -1, amount)) assert(worldedit.cuboid_linear_expand(name, 'z', 1, amount)) assert(worldedit.cuboid_linear_expand(name, 'z', -1, amount)) elseif dir == "v" then assert(worldedit.cuboid_linear_expand(name, 'y', 1, amount)) assert(worldedit.cuboid_linear_expand(name, 'y', -1, amount)) else return false, "Unknown error" end worldedit.marker_update(name) return true, "Region outset by " .. amount .. " blocks" end, } ) minetest.register_chatcommand("/inset", { params = "<amount> [h|v]", description = "inset the selection", privs = {worldedit=true}, func = function(name, param) local find, _, amount, dir = param:find("^(%d+)[%s+]?([hv]?)$") if find == nil then return false, "invalid usage: " .. param end local pos1 = worldedit.pos1[name] local pos2 = worldedit.pos2[name] if pos1 == nil or pos2 == nil then return false, "Undefined region. Region must be defined beforehand." end if dir == "" then assert(worldedit.cuboid_volumetric_expand(name, -amount)) elseif dir == "h" then assert(worldedit.cuboid_linear_expand(name, 'x', 1, -amount)) assert(worldedit.cuboid_linear_expand(name, 'x', -1, -amount)) assert(worldedit.cuboid_linear_expand(name, 'z', 1, -amount)) assert(worldedit.cuboid_linear_expand(name, 'z', -1, -amount)) elseif dir == "v" then assert(worldedit.cuboid_linear_expand(name, 'y', 1, -amount)) assert(worldedit.cuboid_linear_expand(name, 'y', -1, -amount)) else return false, "Unknown error" end worldedit.marker_update(name) return true, "Region inset by " .. amount .. " blocks" end, } ) minetest.register_chatcommand("/shift", { params = "<amount> [up|down|left|right|front|back]", description = "Moves the selection region. Does not move contents.", privs = {worldedit=true}, func = function(name, param) local pos1 = worldedit.pos1[name] local pos2 = worldedit.pos2[name] local find, _, amount, direction = param:find("(%d+)%s*(%l*)") if find == nil then worldedit.player_notify(name, "invalid usage: " .. param) return end if pos1 == nil or pos2 == nil then worldedit.player_notify(name, "Undefined region. Region must be defined beforehand.") return end local axis, dir if direction ~= "" then axis, dir = worldedit.translate_direction(name, direction) else axis, dir = worldedit.player_axis(name) end assert(worldedit.cuboid_shift(name, axis, amount * dir)) worldedit.marker_update(name) return true, "region shifted by " .. amount .. " nodes" end, } ) minetest.register_chatcommand("/expand", { params = "<amount> [reverse-amount] [up|down|left|right|front|back]", description = "expand the selection in one or two directions at once", privs = {worldedit=true}, func = function(name, param) local find, _, amount, arg2, arg3 = param:find("(%d+)%s*(%w*)%s*(%l*)") if find == nil then worldedit.player_notify(name, "invalid use: " .. param) return end if worldedit.pos1[name] == nil or worldedit.pos2[name] == nil then worldedit.player_notify(name, "Undefined region. Region must be defined beforehand.") return end local tmp = tonumber(arg2) local axis, dir local reverse_amount = 0 axis,dir = worldedit.player_axis(name) if arg2 ~= "" then if tmp == nil then axis, dir = worldedit.translate_direction(name, arg2) else reverse_amount = tmp end end if arg3 ~= "" then axis, dir = worldedit.translate_direction(name, arg3) end worldedit.cuboid_linear_expand(name, axis, dir, amount) worldedit.cuboid_linear_expand(name, axis, -dir, reverse_amount) worldedit.marker_update(name) end, } ) minetest.register_chatcommand("/contract", { params = "<amount> [reverse-amount] [up|down|left|right|front|back]", description = "contract the selection in one or two directions at once", privs = {worldedit=true}, func = function(name, param) local find, _, amount, arg2, arg3 = param:find("(%d+)%s*(%w*)%s*(%l*)") if find == nil then worldedit.player_notify(name, "invalid use: " .. param) return end if worldedit.pos1[name] == nil or worldedit.pos2[name] == nil then worldedit.player_notify(name, "Undefined region. Region must be defined beforehand.") return end local tmp = tonumber(arg2) local axis, dir local reverse_amount = 0 axis,dir = worldedit.player_axis(name) if arg2 ~= "" then if tmp == nil then axis, dir = worldedit.translate_direction(name, arg2) else reverse_amount = tmp end end if arg3 ~= "" then axis, dir = worldedit.translate_direction(name, arg3) end worldedit.cuboid_linear_expand(name, axis, dir, -amount) worldedit.cuboid_linear_expand(name, axis, -dir, -reverse_amount) worldedit.marker_update(name) end, } )
dofile(minetest.get_modpath("worldedit_commands") .. "/cuboidapi.lua") minetest.register_chatcommand("/outset", { params = "<amount> [h|v]", description = "outset the selection", privs = {worldedit=true}, func = function(name, param) local find, _, amount, dir = param:find("^(%d+)[%s+]?([hv]?)$") if find == nil then return false, "invalid usage: " .. param end local pos1 = worldedit.pos1[name] local pos2 = worldedit.pos2[name] if pos1 == nil or pos2 == nil then return false, "Undefined region. Region must be defined beforehand." end if dir == "" then assert(worldedit.cuboid_volumetric_expand(name, amount)) elseif dir == "h" then assert(worldedit.cuboid_linear_expand(name, 'x', 1, amount)) assert(worldedit.cuboid_linear_expand(name, 'x', -1, amount)) assert(worldedit.cuboid_linear_expand(name, 'z', 1, amount)) assert(worldedit.cuboid_linear_expand(name, 'z', -1, amount)) elseif dir == "v" then assert(worldedit.cuboid_linear_expand(name, 'y', 1, amount)) assert(worldedit.cuboid_linear_expand(name, 'y', -1, amount)) else return false, "Unknown error" end worldedit.marker_update(name) return true, "Region outset by " .. amount .. " blocks" end, } ) minetest.register_chatcommand("/inset", { params = "<amount> [h|v]", description = "inset the selection", privs = {worldedit=true}, func = function(name, param) local find, _, amount, dir = param:find("^(%d+)[%s+]?([hv]?)$") if find == nil then return false, "invalid usage: " .. param end local pos1 = worldedit.pos1[name] local pos2 = worldedit.pos2[name] if pos1 == nil or pos2 == nil then return false, "Undefined region. Region must be defined beforehand." end if dir == "" then assert(worldedit.cuboid_volumetric_expand(name, -amount)) elseif dir == "h" then assert(worldedit.cuboid_linear_expand(name, 'x', 1, -amount)) assert(worldedit.cuboid_linear_expand(name, 'x', -1, -amount)) assert(worldedit.cuboid_linear_expand(name, 'z', 1, -amount)) assert(worldedit.cuboid_linear_expand(name, 'z', -1, -amount)) elseif dir == "v" then assert(worldedit.cuboid_linear_expand(name, 'y', 1, -amount)) assert(worldedit.cuboid_linear_expand(name, 'y', -1, -amount)) else return false, "Unknown error" end worldedit.marker_update(name) return true, "Region inset by " .. amount .. " blocks" end, } ) minetest.register_chatcommand("/shift", { params = "<amount> [up|down|left|right|front|back]", description = "Moves the selection region. Does not move contents.", privs = {worldedit=true}, func = function(name, param) local pos1 = worldedit.pos1[name] local pos2 = worldedit.pos2[name] local find, _, amount, direction = param:find("(%d+)%s*(%l*)") if find == nil then worldedit.player_notify(name, "invalid usage: " .. param) return end if pos1 == nil or pos2 == nil then worldedit.player_notify(name, "Undefined region. Region must be defined beforehand.") return end local axis, dir if direction ~= "" then axis, dir = worldedit.translate_direction(name, direction) else axis, dir = worldedit.player_axis(name) end if axis == nil or dir == nil then return false, "Invalid if looking up or down" end assert(worldedit.cuboid_shift(name, axis, amount * dir)) worldedit.marker_update(name) return true, "region shifted by " .. amount .. " nodes" end, } ) minetest.register_chatcommand("/expand", { params = "<amount> [reverse-amount] [up|down|left|right|front|back]", description = "expand the selection in one or two directions at once", privs = {worldedit=true}, func = function(name, param) local find, _, amount, arg2, arg3 = param:find("(%d+)%s*(%w*)%s*(%l*)") if find == nil then worldedit.player_notify(name, "invalid use: " .. param) return end if worldedit.pos1[name] == nil or worldedit.pos2[name] == nil then worldedit.player_notify(name, "Undefined region. Region must be defined beforehand.") return end local tmp = tonumber(arg2) local axis, dir local reverse_amount = 0 axis,dir = worldedit.player_axis(name) if arg2 ~= "" then if tmp == nil then axis, dir = worldedit.translate_direction(name, arg2) else reverse_amount = tmp end end if arg3 ~= "" then axis, dir = worldedit.translate_direction(name, arg3) end worldedit.cuboid_linear_expand(name, axis, dir, amount) worldedit.cuboid_linear_expand(name, axis, -dir, reverse_amount) worldedit.marker_update(name) end, } ) minetest.register_chatcommand("/contract", { params = "<amount> [reverse-amount] [up|down|left|right|front|back]", description = "contract the selection in one or two directions at once", privs = {worldedit=true}, func = function(name, param) local find, _, amount, arg2, arg3 = param:find("(%d+)%s*(%w*)%s*(%l*)") if find == nil then worldedit.player_notify(name, "invalid use: " .. param) return end if worldedit.pos1[name] == nil or worldedit.pos2[name] == nil then worldedit.player_notify(name, "Undefined region. Region must be defined beforehand.") return end local tmp = tonumber(arg2) local axis, dir local reverse_amount = 0 axis,dir = worldedit.player_axis(name) if arg2 ~= "" then if tmp == nil then axis, dir = worldedit.translate_direction(name, arg2) else reverse_amount = tmp end end if arg3 ~= "" then axis, dir = worldedit.translate_direction(name, arg3) end worldedit.cuboid_linear_expand(name, axis, dir, -amount) worldedit.cuboid_linear_expand(name, axis, -dir, -reverse_amount) worldedit.marker_update(name) end, } )
Fix a crash that happened when trying to shift the cuboid using relative direction while looking straight up or down
Fix a crash that happened when trying to shift the cuboid using relative direction while looking straight up or down
Lua
agpl-3.0
Uberi/Minetest-WorldEdit
27c1e6d2d8cc6f291ae9e7852d6dd9a712f33dae
src/lib/hardware/pci.lua
src/lib/hardware/pci.lua
module(...,package.seeall) local ffi = require("ffi") local C = ffi.C local lib = require("core.lib") require("lib.hardware.pci_h") --- ### Hardware device information devices = {} --- Array of all supported hardware devices. --- --- Each entry is a "device info" table with these attributes: --- --- * `pciaddress` e.g. `"0000:83:00.1"` --- * `vendor` id hex string e.g. `"0x8086"` for Intel. --- * `device` id hex string e.g. `"0x10fb"` for 82599 chip. --- * `interface` name of Linux interface using this device e.g. `"eth0"`. --- * `status` string Linux operational status, or `nil` if not known. --- * `driver` Lua module that supports this hardware e.g. `"intel10g"`. --- * `usable` device was suitable to use when scanned? `yes` or `no` --- Initialize (or re-initialize) the `devices` table. function scan_devices () for _,device in ipairs(lib.files_in_directory("/sys/bus/pci/devices")) do local info = device_info(device) if info.driver then table.insert(devices, info) end end end function device_info (pciaddress) local info = {} local p = path(pciaddress) info.pciaddress = pciaddress info.vendor = lib.firstline(p.."/vendor") info.device = lib.firstline(p.."/device") info.model = which_model(info.vendor, info.device) info.driver = which_driver(info.vendor, info.device) if info.driver then info.interface = lib.firstfile(p.."/net") if info.interface then info.status = lib.firstline(p.."/net/"..info.interface.."/operstate") end end info.usable = lib.yesno(is_usable(info)) return info end --- Return the path to the sysfs directory for `pcidev`. function path(pcidev) return "/sys/bus/pci/devices/"..pcidev end model = { ["82599_SFP"] = 'Intel 82599 SFP', ["82574L"] = 'Intel 82574L', ["82571"] = 'Intel 82571', ["82599_T3"] = 'Intel 82599 T3', ["X540"] = 'Intel X540', } -- Supported cards indexed by vendor and device id. local cards = { ["0x8086"] = { ["0x10fb"] = {model = model["82599_SFP"], driver = 'apps.intel.intel_app'}, ["0x10d3"] = {model = model["82574L"], driver = 'apps.intel.intel_app'}, ["0x105e"] = {model = model["82571"], driver = 'apps.intel.intel_app'}, ["0x151c"] = {model = model["82599_T3"], driver = 'apps.intel.intel_app'}, ["0x1528"] = {model = model["X540"], driver = 'apps.intel.intel_app'}, }, ["0x1924"] = { ["0x0903"] = {model = 'SFN7122F', driver = 'apps.solarflare.solarflare'} }, } -- Return the name of the Lua module that implements support for this device. function which_driver (vendor, device) local card = cards[vendor] and cards[vendor][device] return card and card.driver end function which_model (vendor, device) local card = cards[vendor] and cards[vendor][device] return card and card.model end --- ### Device manipulation. --- Return true if `device` is safely available for use, or false if --- the operating systems to be using it. function is_usable (info) return info.driver and (info.interface == nil or info.status == 'down') end --- Force Linux to release the device with `pciaddress`. --- The corresponding network interface (e.g. `eth0`) will disappear. function unbind_device_from_linux (pciaddress) root_check() local p = path(pciaddress).."/driver/unbind" if lib.can_write(p) then lib.writefile(path(pciaddress).."/driver/unbind", pciaddress) end end -- Memory map PCI device configuration space. -- Return two values: -- Pointer for memory-mapped access. -- File descriptor for the open sysfs resource file. function map_pci_memory (device, n) root_check() local filepath = path(device).."/resource"..n local fd = C.open_pci_resource(filepath) assert(fd >= 0) local addr = C.map_pci_resource(fd) assert( addr ~= 0 ) return addr, fd end -- Close a file descriptor opened by map_pci_memory(). function close_pci_resource (fd, base) C.close_pci_resource(fd, base) end --- Enable or disable PCI bus mastering. DMA only works when bus --- mastering is enabled. function set_bus_master (device, enable) root_check() local fd = C.open_pcie_config(path(device).."/config") local value = ffi.new("uint16_t[1]") assert(C.pread(fd, value, 2, 0x4) == 2) if enable then value[0] = bit.bor(value[0], lib.bits({Master=2})) else value[0] = bit.band(value[0], bit.bnot(lib.bits({Master=2}))) end assert(C.pwrite(fd, value, 2, 0x4) == 2) C.close(fd) end function root_check () lib.root_check("error: must run as root to access PCI devices") end --- ### Selftest --- --- PCI selftest scans for available devices and performs our driver's --- self-test on each of them. function selftest () print("selftest: pci") scan_devices() print_device_summary() end function print_device_summary () local attrs = {"pciaddress", "vendor", "device", "interface", "status", "driver", "usable"} local fmt = "%-13s %-7s %-7s %-10s %-9s %-11s %s" print(fmt:format(unpack(attrs))) for _,info in ipairs(devices) do local values = {} for _,attr in ipairs(attrs) do table.insert(values, info[attr] or "-") end print(fmt:format(unpack(values))) end end
module(...,package.seeall) local ffi = require("ffi") local C = ffi.C local lib = require("core.lib") require("lib.hardware.pci_h") --- ### Hardware device information devices = {} --- Array of all supported hardware devices. --- --- Each entry is a "device info" table with these attributes: --- --- * `pciaddress` e.g. `"0000:83:00.1"` --- * `vendor` id hex string e.g. `"0x8086"` for Intel. --- * `device` id hex string e.g. `"0x10fb"` for 82599 chip. --- * `interface` name of Linux interface using this device e.g. `"eth0"`. --- * `status` string Linux operational status, or `nil` if not known. --- * `driver` Lua module that supports this hardware e.g. `"intel10g"`. --- * `usable` device was suitable to use when scanned? `yes` or `no` --- Initialize (or re-initialize) the `devices` table. function scan_devices () for _,device in ipairs(lib.files_in_directory("/sys/bus/pci/devices")) do local info = device_info(device) if info.driver then table.insert(devices, info) end end end function device_info (pciaddress) local info = {} local p = path(pciaddress) info.pciaddress = canonical(pciaddress) info.vendor = lib.firstline(p.."/vendor") info.device = lib.firstline(p.."/device") info.model = which_model(info.vendor, info.device) info.driver = which_driver(info.vendor, info.device) if info.driver then info.interface = lib.firstfile(p.."/net") if info.interface then info.status = lib.firstline(p.."/net/"..info.interface.."/operstate") end end info.usable = lib.yesno(is_usable(info)) return info end --- Return the path to the sysfs directory for `pcidev`. function path(pcidev) return "/sys/bus/pci/devices/"..qualified(pcidev) end model = { ["82599_SFP"] = 'Intel 82599 SFP', ["82574L"] = 'Intel 82574L', ["82571"] = 'Intel 82571', ["82599_T3"] = 'Intel 82599 T3', ["X540"] = 'Intel X540', } -- Supported cards indexed by vendor and device id. local cards = { ["0x8086"] = { ["0x10fb"] = {model = model["82599_SFP"], driver = 'apps.intel.intel_app'}, ["0x10d3"] = {model = model["82574L"], driver = 'apps.intel.intel_app'}, ["0x105e"] = {model = model["82571"], driver = 'apps.intel.intel_app'}, ["0x151c"] = {model = model["82599_T3"], driver = 'apps.intel.intel_app'}, ["0x1528"] = {model = model["X540"], driver = 'apps.intel.intel_app'}, }, ["0x1924"] = { ["0x0903"] = {model = 'SFN7122F', driver = 'apps.solarflare.solarflare'} }, } -- Return the name of the Lua module that implements support for this device. function which_driver (vendor, device) local card = cards[vendor] and cards[vendor][device] return card and card.driver end function which_model (vendor, device) local card = cards[vendor] and cards[vendor][device] return card and card.model end --- ### Device manipulation. --- Return true if `device` is safely available for use, or false if --- the operating systems to be using it. function is_usable (info) return info.driver and (info.interface == nil or info.status == 'down') end --- Force Linux to release the device with `pciaddress`. --- The corresponding network interface (e.g. `eth0`) will disappear. function unbind_device_from_linux (pciaddress) root_check() local p = path(pciaddress).."/driver/unbind" if lib.can_write(p) then lib.writefile(path(pciaddress).."/driver/unbind", qualified(pciaddress)) end end -- Memory map PCI device configuration space. -- Return two values: -- Pointer for memory-mapped access. -- File descriptor for the open sysfs resource file. function map_pci_memory (device, n) root_check() local filepath = path(device).."/resource"..n local fd = C.open_pci_resource(filepath) assert(fd >= 0) local addr = C.map_pci_resource(fd) assert( addr ~= 0 ) return addr, fd end -- Close a file descriptor opened by map_pci_memory(). function close_pci_resource (fd, base) C.close_pci_resource(fd, base) end --- Enable or disable PCI bus mastering. DMA only works when bus --- mastering is enabled. function set_bus_master (device, enable) root_check() local fd = C.open_pcie_config(path(device).."/config") local value = ffi.new("uint16_t[1]") assert(C.pread(fd, value, 2, 0x4) == 2) if enable then value[0] = bit.bor(value[0], lib.bits({Master=2})) else value[0] = bit.band(value[0], bit.bnot(lib.bits({Master=2}))) end assert(C.pwrite(fd, value, 2, 0x4) == 2) C.close(fd) end function root_check () lib.root_check("error: must run as root to access PCI devices") end -- Return the canonical (abbreviated) representation of the PCI address. -- -- example: canonical("0000:01:00.0") -> "01:00.0" function canonical (address) return address:gsub("^0000:", "") end -- Return the fully-qualified representation of a PCI address. -- -- example: qualified("01:00.0") -> "0000:01:00.0" function qualified (address) return address:gsub("^%d%d:%d%d[.]%d+$", "0000:%1") end --- ### Selftest --- --- PCI selftest scans for available devices and performs our driver's --- self-test on each of them. function selftest () print("selftest: pci") assert(qualified("0000:01:00.0") == "0000:01:00.0", "qualified 1") assert(qualified( "01:00.0") == "0000:01:00.0", "qualified 2") assert(canonical("0000:01:00.0") == "01:00.0", "canonical 1") assert(canonical( "01:00.0") == "01:00.0", "canonical 2") scan_devices() print_device_summary() end function print_device_summary () local attrs = {"pciaddress", "vendor", "device", "interface", "status", "driver", "usable"} local fmt = "%-13s %-7s %-7s %-10s %-9s %-11s %s" print(fmt:format(unpack(attrs))) for _,info in ipairs(devices) do local values = {} for _,attr in ipairs(attrs) do table.insert(values, info[attr] or "-") end print(fmt:format(unpack(values))) end end
lib.pci: Support short/canonical ("01:00.0") addresses
lib.pci: Support short/canonical ("01:00.0") addresses Adds these two functions: pci.canonical(address) => returns address in short canonical format pci.qualified(address) => returns address in fully qualified format with the intention that users can specify either format and Snabb Switch will prefer the canonical format internally but expand to the qualified format when needed (e.g. for resolving sysfs paths). This is a user visible change. The PCI selftest now shows canonical addresses: $ sudo ./snabb snsh -t lib.hardware.pci selftest: pci pciaddress vendor device interface status driver usable 01:00.0 0x8086 0x10fb p1p1 down apps.intel.intel_app yes 01:00.1 0x8086 0x10fb p1p2 down apps.intel.intel_app yes 02:00.0 0x8086 0x10fb p2p1 down apps.intel.intel_app yes 02:00.1 0x8086 0x10fb p2p2 down apps.intel.intel_app yes 03:00.0 0x8086 0x10fb p3p1 down apps.intel.intel_app yes 03:00.1 0x8086 0x10fb - - apps.intel.intel_app yes 81:00.0 0x8086 0x10fb p5p1 down apps.intel.intel_app yes 81:00.1 0x8086 0x10fb p5p2 down apps.intel.intel_app yes 82:00.0 0x8086 0x10fb p6p1 down apps.intel.intel_app yes 82:00.1 0x8086 0x10fb p6p2 down apps.intel.intel_app yes and software now accepts either format in parameters: $ sudo SNABB_PCI0=01:00.0 SNABB_PCI1=0000:01:00.1 ./snabb snsh -t apps.intel.intel_app selftest: intel_app 100 VF initializations: Running iterated VMDq test... test # 1: VMDq VLAN=101; 100ms burst. packet sent: 628,830 test # 2: VMDq VLAN=102; 100ms burst. packet sent: 1,745,985 test # 3: VMDq VLAN=103; 100ms burst. packet sent: 2,891,700 This change can potentially break software that depends on always having qualified paths: that would now be considered a bug.
Lua
apache-2.0
Igalia/snabb,wingo/snabb,hb9cwp/snabbswitch,aperezdc/snabbswitch,mixflowtech/logsensor,snabbnfv-goodies/snabbswitch,kbara/snabb,andywingo/snabbswitch,dpino/snabb,mixflowtech/logsensor,alexandergall/snabbswitch,snabbco/snabb,Igalia/snabbswitch,Igalia/snabb,dpino/snabb,wingo/snabb,aperezdc/snabbswitch,eugeneia/snabb,wingo/snabbswitch,Igalia/snabb,lukego/snabbswitch,snabbco/snabb,andywingo/snabbswitch,kbara/snabb,kbara/snabb,snabbco/snabb,eugeneia/snabbswitch,heryii/snabb,snabbco/snabb,lukego/snabb,alexandergall/snabbswitch,snabbco/snabb,mixflowtech/logsensor,eugeneia/snabb,hb9cwp/snabbswitch,heryii/snabb,dpino/snabbswitch,kbara/snabb,wingo/snabbswitch,snabbnfv-goodies/snabbswitch,andywingo/snabbswitch,snabbco/snabb,snabbco/snabb,eugeneia/snabb,wingo/snabb,alexandergall/snabbswitch,Igalia/snabb,SnabbCo/snabbswitch,SnabbCo/snabbswitch,lukego/snabbswitch,plajjan/snabbswitch,justincormack/snabbswitch,aperezdc/snabbswitch,snabbco/snabb,dpino/snabb,dpino/snabb,plajjan/snabbswitch,wingo/snabb,alexandergall/snabbswitch,aperezdc/snabbswitch,lukego/snabb,plajjan/snabbswitch,mixflowtech/logsensor,eugeneia/snabb,Igalia/snabbswitch,hb9cwp/snabbswitch,wingo/snabb,eugeneia/snabbswitch,heryii/snabb,alexandergall/snabbswitch,dpino/snabbswitch,kbara/snabb,dpino/snabb,alexandergall/snabbswitch,wingo/snabbswitch,mixflowtech/logsensor,alexandergall/snabbswitch,Igalia/snabbswitch,dpino/snabbswitch,heryii/snabb,andywingo/snabbswitch,Igalia/snabb,hb9cwp/snabbswitch,lukego/snabbswitch,dpino/snabbswitch,SnabbCo/snabbswitch,lukego/snabbswitch,SnabbCo/snabbswitch,eugeneia/snabb,lukego/snabb,snabbnfv-goodies/snabbswitch,snabbnfv-goodies/snabbswitch,Igalia/snabb,wingo/snabbswitch,heryii/snabb,plajjan/snabbswitch,lukego/snabb,justincormack/snabbswitch,dpino/snabb,kbara/snabb,eugeneia/snabb,eugeneia/snabbswitch,eugeneia/snabb,Igalia/snabb,eugeneia/snabbswitch,Igalia/snabbswitch,Igalia/snabbswitch,eugeneia/snabb,alexandergall/snabbswitch,heryii/snabb,dpino/snabb,Igalia/snabb,wingo/snabb,justincormack/snabbswitch,justincormack/snabbswitch
cd45b48e8b9ff3e30fa13ea9b17b6d5a01a4b9d5
src/luarocks/fs/unix.lua
src/luarocks/fs/unix.lua
local assert, type, table, io, package, math, os, ipairs = assert, type, table, io, package, math, os, ipairs --- Unix implementation of filesystem and platform abstractions. module("luarocks.fs.unix", package.seeall) local fs = require("luarocks.fs") local cfg = require("luarocks.cfg") local dir = require("luarocks.dir") local fs = require("luarocks.fs") math.randomseed(os.time()) --- Return an absolute pathname from a potentially relative one. -- @param pathname string: pathname to convert. -- @param relative_to string or nil: path to prepend when making -- pathname absolute, or the current dir in the dir stack if -- not given. -- @return string: The pathname converted to absolute. function absolute_name(pathname, relative_to) assert(type(pathname) == "string") assert(type(relative_to) == "string" or not relative_to) relative_to = relative_to or fs.current_dir() if pathname:sub(1,1) == "/" then return pathname else return relative_to .. "/" .. pathname end end --- Create a wrapper to make a script executable from the command-line. -- @param file string: Pathname of script to be made executable. -- @param dest string: Directory where to put the wrapper. -- @return boolean or (nil, string): True if succeeded, or nil and -- an error message. function wrap_script(file, dest) assert(type(file) == "string") assert(type(dest) == "string") local base = dir.base_name(file) local wrapname = fs.is_dir(dest) and dest.."/"..base or dest local wrapper = io.open(wrapname, "w") if not wrapper then return nil, "Could not open "..wrapname.." for writing." end wrapper:write("#!/bin/sh\n\n") wrapper:write('LUA_PATH="'..package.path..';$LUA_PATH"\n') wrapper:write('LUA_CPATH="'..package.cpath..';$LUA_CPATH"\n') wrapper:write('export LUA_PATH LUA_CPATH\n') wrapper:write('exec "'..dir.path(cfg.variables["LUA_BINDIR"], cfg.lua_interpreter)..'" -lluarocks.loader "'..file..'" "$@"\n') wrapper:close() if fs.execute("chmod +x",wrapname) then return true else return nil, "Could not make "..wrapname.." executable." end end --- Check if a file (typically inside path.bin_dir) is an actual binary -- or a Lua wrapper. -- @param filename string: the file name with full path. -- @return boolean: returns true if file is an actual binary -- (or if it couldn't check) or false if it is a Lua wrapper. function is_actual_binary(filename) if filename:match("%.lua$") then return false end local file = io.open(filename) if file then local found = false local first = file:read() if first:match("#!.*lua") then found = true elseif first:match("#!/bin/sh") then local line = file:read() line = file:read() if not(line and line:match("LUA_PATH")) then found = true end end file:close() if found then return false else return true end else return true end return false end function is_actual_binary(filename) if filename:match("%.lua$") then return false end local file = io.open(filename) if file then local found = false local first = file:read() if first:match("#!.*lua") then file:close() return true elseif first:match("#!/bin/sh") then local line = file:read() line = file:read() if not(line and line:match("LUA_PATH")) then file:close() return true end end file:close() else return true end return false end function copy_binary(filename, dest) return fs.copy(filename, dest) end
local assert, type, table, io, package, math, os, ipairs = assert, type, table, io, package, math, os, ipairs --- Unix implementation of filesystem and platform abstractions. module("luarocks.fs.unix", package.seeall) local fs = require("luarocks.fs") local cfg = require("luarocks.cfg") local dir = require("luarocks.dir") local fs = require("luarocks.fs") math.randomseed(os.time()) --- Return an absolute pathname from a potentially relative one. -- @param pathname string: pathname to convert. -- @param relative_to string or nil: path to prepend when making -- pathname absolute, or the current dir in the dir stack if -- not given. -- @return string: The pathname converted to absolute. function absolute_name(pathname, relative_to) assert(type(pathname) == "string") assert(type(relative_to) == "string" or not relative_to) relative_to = relative_to or fs.current_dir() if pathname:sub(1,1) == "/" then return pathname else return relative_to .. "/" .. pathname end end --- Create a wrapper to make a script executable from the command-line. -- @param file string: Pathname of script to be made executable. -- @param dest string: Directory where to put the wrapper. -- @return boolean or (nil, string): True if succeeded, or nil and -- an error message. function wrap_script(file, dest) assert(type(file) == "string") assert(type(dest) == "string") local base = dir.base_name(file) local wrapname = fs.is_dir(dest) and dest.."/"..base or dest local wrapper = io.open(wrapname, "w") if not wrapper then return nil, "Could not open "..wrapname.." for writing." end wrapper:write("#!/bin/sh\n\n") wrapper:write('LUA_PATH="'..package.path..';$LUA_PATH"\n') wrapper:write('LUA_CPATH="'..package.cpath..';$LUA_CPATH"\n') wrapper:write('export LUA_PATH LUA_CPATH\n') wrapper:write('exec "'..dir.path(cfg.variables["LUA_BINDIR"], cfg.lua_interpreter)..'" -lluarocks.loader "'..file..'" "$@"\n') wrapper:close() if fs.execute("chmod +x",wrapname) then return true else return nil, "Could not make "..wrapname.." executable." end end --- Check if a file (typically inside path.bin_dir) is an actual binary -- or a Lua wrapper. -- @param filename string: the file name with full path. -- @return boolean: returns true if file is an actual binary -- (or if it couldn't check) or false if it is a Lua wrapper. function is_actual_binary(filename) if filename:match("%.lua$") then return false end local file = io.open(filename) if file then local found = false local first = file:read() if first:match("#!.*lua") then found = true elseif first:match("#!/bin/sh") then local line = file:read() line = file:read() if not(line and line:match("LUA_PATH")) then found = true end end file:close() if found then return false else return true end else return true end return false end function is_actual_binary(filename) if filename:match("%.lua$") then return false end local file = io.open(filename) if file then local found = false local first = file:read() if not first then file:close() print("Warning: could not read "..filename) return false end if first:match("#!.*lua") then file:close() return true elseif first:match("#!/bin/sh") then local line = file:read() line = file:read() if not(line and line:match("LUA_PATH")) then file:close() return true end end file:close() else return true end return false end function copy_binary(filename, dest) return fs.copy(filename, dest) end
Add sanity check to is_actual_binary. Should fix crash in 'luarocks pack' reported by Alexander Gladysh, or at least give better diagnostics.
Add sanity check to is_actual_binary. Should fix crash in 'luarocks pack' reported by Alexander Gladysh, or at least give better diagnostics.
Lua
mit
tst2005/luarocks,xpol/luainstaller,robooo/luarocks,coderstudy/luarocks,xpol/luavm,rrthomas/luarocks,starius/luarocks,xpol/luainstaller,xpol/luavm,xiaq/luarocks,leafo/luarocks,aryajur/luarocks,xpol/luarocks,xpol/luavm,tst2005/luarocks,xiaq/luarocks,tarantool/luarocks,luarocks/luarocks,tst2005/luarocks,usstwxy/luarocks,xpol/luarocks,tarantool/luarocks,xpol/luainstaller,ignacio/luarocks,ignacio/luarocks,xpol/luavm,tst2005/luarocks,robooo/luarocks,robooo/luarocks,tarantool/luarocks,luarocks/luarocks,aryajur/luarocks,xpol/luainstaller,xiaq/luarocks,leafo/luarocks,lxbgit/luarocks,lxbgit/luarocks,xiaq/luarocks,ignacio/luarocks,starius/luarocks,rrthomas/luarocks,keplerproject/luarocks,xpol/luavm,aryajur/luarocks,starius/luarocks,luarocks/luarocks,keplerproject/luarocks,lxbgit/luarocks,coderstudy/luarocks,xpol/luarocks,leafo/luarocks,keplerproject/luarocks,usstwxy/luarocks,ignacio/luarocks,aryajur/luarocks,usstwxy/luarocks,keplerproject/luarocks,xpol/luarocks,rrthomas/luarocks,coderstudy/luarocks,usstwxy/luarocks,robooo/luarocks,lxbgit/luarocks,rrthomas/luarocks,coderstudy/luarocks,starius/luarocks
df1ab2901904d7cbfea59ef3533c6f502dacb8fa
utils.lua
utils.lua
-- UTILS function trim(s) local from = s:match"^%s*()" return s:match"^%s*()" > #s and "" or s:match(".*%S", s:match"^%s*()") end function trim_table_strings(t) assert(type(t) == 'table', "You must provide a table") for index,value in pairs(t) do if(type(value) == 'string') then t[index] = trim(value) end end return t end -- See https://stackoverflow.com/questions/20325332/how-to-check-if-two-tablesobjects-have-the-same-value-in-lua function tables_equals(o1, o2, ignore_mt) if o1 == o2 then return true end local o1Type = type(o1) local o2Type = type(o2) if o1Type ~= o2Type then return false end if o1Type ~= 'table' then return false end if not ignore_mt then local mt1 = getmetatable(o1) if mt1 and mt1.__eq then --compare using built in method return o1 == o2 end end local keySet = {} for key1, value1 in pairs(o1) do local value2 = o2[key1] if value2 == nil or tables_equals(value1, value2, ignore_mt) == false then return false end keySet[key1] = true end for key2, _ in pairs(o2) do if not keySet[key2] then return false end end return true end function clone(t) -- shallow-copy a table if type(t) ~= "table" then return t end local meta = getmetatable(t) local target = {} for k, v in pairs(t) do target[k] = v end setmetatable(target, meta) return target end table.exact_length = function(tbl) if (type(tbl) ~= 'table') then return 1 end local i = 0 for k,v in pairs(tbl) do i = i + 1 end return i end function isint(n) if (torch.isTensor(n)) then return torch.eq(n, torch.floor(n)) else return n == math.floor(n) end end function isnan(n) return n ~= n end table.get_key_string = function(tbl) local ret = "" for key,_ in pairs(tbl) do if (ret ~= "") then ret = ret .. ", " end ret = ret .. ("'%s'"):format(key) end return ret end table.collapse_to_string = function(tbl, indent, start) assert(type(tbl) == "table", "The object isn't of type table: " .. type(tbl)) indent = indent or "" start = start or indent local ret = start if(tbl == nil) then ret = "No table provided" elseif(table.exact_length(tbl) == 0) then ret = "Empty table" else for k,v in pairs(tbl) do if (ret ~= start) then ret = ret .. ", " -- If deeper structure then the description should be dense if (indent:len() <= 2*1) then ret = ret .. "\n" .. indent end end if (type(v) == "table") then v = ("[\n%s%s\n%s]"): format(indent .. " ", table.collapse_to_string(v, indent .. " ", ""), indent) end if (isnan(v)) then ret = ret .. "'" .. k .. "'=>nan" else ret = ret .. "'" .. k .. "'=>'" .. tostring(v) .. "'" end end end return ret end table.has_element = function(haystack, needle) for _,value in pairs(haystack) do if (value == needle) then return true end end return false end -- maxn is deprecated for lua version >=5.3 table.maxn = table.maxn or function(t) local maxn=0 for i in pairs(t) do maxn=type(i)=='number'and i>maxn and i or maxn end return maxn end -- Util for debugging purpose table._dump = function(tbl) print(("\n-[ Table dump ]-\n%s"):format(table.collapse_to_string(tbl))) end if (itorch ~= nil) then -- The itorch has a strange handling of tables that generate huge outputs for -- large dataframe objects. This may hang the notebook as it tries to print -- thousands of entries. This snippet overloads if we seem to be in an itorch environement print_itorch = print print_df = function(...) for i = 1,select('#',...) do local obj = select(i,...) if torch.isTypeOf(obj, Dataframe) then print_itorch(tostring(obj)) else print_itorch(obj) end end if select('#',...) == 0 then print_itorch() end end print = print_df end -- END UTILS
-- UTILS function trim(s) local from = s:match"^%s*()" return s:match"^%s*()" > #s and "" or s:match(".*%S", s:match"^%s*()") end function trim_table_strings(t) assert(type(t) == 'table', "You must provide a table") for index,value in pairs(t) do if(type(value) == 'string') then t[index] = trim(value) end end return t end -- See https://stackoverflow.com/questions/20325332/how-to-check-if-two-tablesobjects-have-the-same-value-in-lua function tables_equals(o1, o2, ignore_mt) if o1 == o2 then return true end local o1Type = type(o1) local o2Type = type(o2) if o1Type ~= o2Type then return false end if o1Type ~= 'table' then return false end if not ignore_mt then local mt1 = getmetatable(o1) if mt1 and mt1.__eq then --compare using built in method return o1 == o2 end end local keySet = {} for key1, value1 in pairs(o1) do local value2 = o2[key1] if value2 == nil or tables_equals(value1, value2, ignore_mt) == false then return false end keySet[key1] = true end for key2, _ in pairs(o2) do if not keySet[key2] then return false end end return true end function clone(t) -- shallow-copy a table if type(t) ~= "table" then return t end local meta = getmetatable(t) local target = {} for k, v in pairs(t) do target[k] = v end setmetatable(target, meta) return target end table.exact_length = function(tbl) if (type(tbl) ~= 'table') then return 1 end local i = 0 for k,v in pairs(tbl) do i = i + 1 end return i end function isint(n) if (torch.isTensor(n)) then return torch.eq(n, torch.floor(n)) else return n == math.floor(n) end end function isnan(n) return n ~= n end table.get_key_string = function(tbl) local ret = "" for key,_ in pairs(tbl) do if (ret ~= "") then ret = ret .. ", " end ret = ret .. ("'%s'"):format(key) end return ret end table.collapse_to_string = function(tbl, indent, start) assert(type(tbl) == "table", "The object isn't of type table: " .. type(tbl)) indent = indent or "" start = start or indent local ret = start if(tbl == nil) then ret = "No table provided" elseif(table.exact_length(tbl) == 0) then ret = "Empty table" else for k,v in pairs(tbl) do if (ret ~= start) then ret = ret .. ", " -- If deeper structure then the description should be dense if (indent:len() <= 2*1) then ret = ret .. "\n" .. indent end end if (type(v) == "table") then v = ("[\n%s%s\n%s]"): format(indent .. " ", table.collapse_to_string(v, indent .. " ", ""), indent) end if (isnan(v)) then ret = ret .. "'" .. k .. "'=>nan" else ret = ret .. "'" .. k .. "'=>'" .. tostring(v) .. "'" end end end return ret end table.has_element = function(haystack, needle) for _,value in pairs(haystack) do if (value == needle) then return true end end return false end -- maxn is deprecated for lua version >=5.3 table.maxn = table.maxn or function(t) local maxn=0 for i in pairs(t) do maxn=type(i)=='number'and i>maxn and i or maxn end return maxn end -- Util for debugging purpose table._dump = function(tbl) print(("\n-[ Table dump ]-\n%s"):format(table.collapse_to_string(tbl))) end if (itorch ~= nil) then -- The itorch has a strange handling of tables that generate huge outputs for -- large dataframe objects. This may hang the notebook as it tries to print -- thousands of entries. This snippet overloads if we seem to be in an itorch environement print_itorch = print print_df = function(...) for i = 1,select('#',...) do local obj = select(i,...) if torch.isTypeOf(obj, Dataframe) then print_itorch(tostring(obj)) else print_itorch(obj) end end if select('#',...) == 0 then print_itorch() end end print = print_df end -- END UTILS
Indentation fixes
Indentation fixes
Lua
mit
AlexMili/torch-dataframe
b470ddf3d3723a700a97f73f8599696d21198bfb
xmake/modules/detect/tools/link/has_flags.lua
xmake/modules/detect/tools/link/has_flags.lua
--!The Make-like Build Utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you 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. -- -- Copyright (C) 2015 - 2017, TBOOX Open Source Group. -- -- @author ruki -- @file has_flags.lua -- -- imports import("lib.detect.cache") -- attempt to check it from the argument list function _check_from_arglist(flags, opt) -- only one flag? if #flags > 1 then return end -- make cache key local key = "detect.tools.link.has_flags" -- make allflags key local flagskey = opt.program .. "_" .. (opt.programver or "") -- load cache local cacheinfo = cache.load(key) -- get all allflags from argument list local allflags = cacheinfo[flagskey] if not allflags then -- get argument list allflags = {} local arglist = nil try { function () os.runv(opt.program, {"-?"}) end, catch { function (errors) arglist = errors end } } if arglist then for arg in arglist:gmatch("(/[%-%a%d]+)%s+") do allflags[arg:gsub("/", "-"):lower()] = true end end -- save cache cacheinfo[flagskey] = allflags cache.save(key, cacheinfo) end -- ok? return allflags[flags[1]:gsub("/", "-"):lower()] end -- try running to check flags function _check_try_running(flags, opt) -- make an stub source file local winmain = flags:lower():find("subsystem:windows") local sourcefile = path.join(os.tmpdir(), "detect", ifelse(winmain, "winmain_", "") .. "link_has_flags.c") if not os.isfile(sourcefile) then if winmain then io.writefile(sourcefile, "int WinMain(void* instance, void* previnst, char** argv, int argc)\n{return 0;}") else io.writefile(sourcefile, "int main(int argc, char** argv)\n{return 0;}") end end -- compile the source file local objectfile = os.tmpfile() .. ".obj" local binaryfile = os.tmpfile() .. ".exe" os.iorunv("cl", {"-c", "-nologo", "-Fo" .. objectfile, sourcefile}) -- try link it local ok = try { function () os.execv(opt.program, table.join(flags, "-nologo", "-out:" .. binaryfile, objectfile)); return true end } -- remove files os.tryrm(objectfile) os.tryrm(binaryfile) -- ok? return ok end -- has_flags(flags)? -- -- @param opt the argument options, .e.g {toolname = "", program = "", programver = "", toolkind = "[cc|cxx|ld|ar|sh|gc|rc|dc|mm|mxx]"} -- -- @return true or false -- function main(flags, opt) -- attempt to check it from the argument list if _check_from_arglist(flags, opt) then return true end -- try running to check it return _check_try_running(flags, opt) end
--!The Make-like Build Utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you 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. -- -- Copyright (C) 2015 - 2017, TBOOX Open Source Group. -- -- @author ruki -- @file has_flags.lua -- -- imports import("lib.detect.cache") -- attempt to check it from the argument list function _check_from_arglist(flags, opt) -- only one flag? if #flags > 1 then return end -- make cache key local key = "detect.tools.link.has_flags" -- make allflags key local flagskey = opt.program .. "_" .. (opt.programver or "") -- load cache local cacheinfo = cache.load(key) -- get all allflags from argument list local allflags = cacheinfo[flagskey] if not allflags then -- get argument list allflags = {} local arglist = nil try { function () os.runv(opt.program, {"-?"}) end, catch { function (errors) arglist = errors end } } if arglist then for arg in arglist:gmatch("(/[%-%a%d]+)%s+") do allflags[arg:gsub("/", "-"):lower()] = true end end -- save cache cacheinfo[flagskey] = allflags cache.save(key, cacheinfo) end -- ok? return allflags[flags[1]:gsub("/", "-"):lower()] end -- try running to check flags function _check_try_running(flags, opt) -- make an stub source file local flags_str = table.concat(flags, " "):lower() local winmain = flags_str:find("subsystem:windows") local sourcefile = path.join(os.tmpdir(), "detect", ifelse(winmain, "winmain_", "") .. "link_has_flags.c") if not os.isfile(sourcefile) then if winmain then io.writefile(sourcefile, "int WinMain(void* instance, void* previnst, char** argv, int argc)\n{return 0;}") else io.writefile(sourcefile, "int main(int argc, char** argv)\n{return 0;}") end end -- compile the source file local objectfile = os.tmpfile() .. ".obj" local binaryfile = os.tmpfile() .. ".exe" os.iorunv("cl", {"-c", "-nologo", "-Fo" .. objectfile, sourcefile}) -- try link it local ok = try { function () os.execv(opt.program, table.join(flags, "-nologo", "-out:" .. binaryfile, objectfile)); return true end } -- remove files os.tryrm(objectfile) os.tryrm(binaryfile) -- ok? return ok end -- has_flags(flags)? -- -- @param opt the argument options, .e.g {toolname = "", program = "", programver = "", toolkind = "[cc|cxx|ld|ar|sh|gc|rc|dc|mm|mxx]"} -- -- @return true or false -- function main(flags, opt) -- attempt to check it from the argument list if _check_from_arglist(flags, opt) then return true end -- try running to check it return _check_try_running(flags, opt) end
fix link.has_flags
fix link.has_flags
Lua
apache-2.0
tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake
11c4a7964ee509ae7aa96f39d80b46cc6939d3ff
tools/utils/unicode.lua
tools/utils/unicode.lua
-- for lua < 5.3 compatibility local bit32 = nil if not bit32 then bit32 = require 'bit32' end local unidata = require './unidata' local unicode = {} -- convert the next utf8 character to ucs -- returns codepoint and utf-8 character function unicode._utf8_to_cp(s, idx) if idx > #s then return end idx = idx or 1 local c = string.byte(s, idx) local l = (c < 0x80 and 1) or (c < 0xE0 and 2) or (c < 0xF0 and 3) or (c < 0xF8 and 4) if not l then error("invalid utf-8 sequence") end local val = 0 if l == 1 then return c, string.sub(s, idx, idx) end for i = 1, l do c = string.byte(s, idx+i-1) if i > 1 then assert(bit32.band(c, 0xC0) == 0x80) val = bit32.lshift(val, 6) val = bit32.bor(val, bit32.band(c, 0x3F)) else val = bit32.band(c,bit32.rshift(0xff,l)) end end return val, string.sub(s, idx, idx+l-1) end -- convert unicode codepoint to utf8 function unicode._cp_to_utf8(u) assert(u>=0 and u<=0x10FFFF) if u <= 0x7F then return string.char(u) elseif u <= 0x7FF then local b0 = 0xC0 + bit32.rshift(u, 6) local b1 = 0x80 + bit32.band(u, 0x3F) return string.char(b0, b1) elseif u <= 0xFFFF then local b0 = 0xE0 + bit32.rshift(u, 12) local b1 = 0x80 + bit32.band(bit32.rshift(u, 6), 0x3f) local b2 = 0x80 + bit32.band(u, 0x3f) return string.char(b0, b1, b2) end local b0 = 0xF0 + bit32.rshift(u, 18) local b1 = 0x80 + bit32.band(bit32.rshift(u, 12), 0x3f) local b2 = 0x80 + bit32.band(bit32.rshift(u, 6), 0x3f) local b3 = 0x80 + bit32.band(u, 0x3f) return string.char(b0, b1, b2, b3) end function unicode.utf8_iter(s) local L = #s local nextv, nextc = unicode._utf8_to_cp(s, 1) local p = 1 if nextc then p = p + #nextc end return function() local v,c = nextv, nextc if p > L then if nextc then nextc = nil return v, c, nil end return end nextv, nextc = unicode._utf8_to_cp(s, p) p = p + #nextc return v, c, nextv end end local function _find_codepoint(u, utable) for i,v in pairs(utable) do if u >= i then local idx = bit32.rshift(u-i,4) + 1 local p = (u-i) % 16 if v[idx] then return not(bit32.band(bit32.lshift(v[idx], p), 0x8000) == 0) end end end return false end function unicode.isSeparator(u) if not u then return false end -- control character or separator return (u >= 9 and u <= 13) or _find_codepoint(u, unidata.Separator) end -- returns if letter and case "lower", "upper", "other" function unicode.isLetter(u) if not u then return false end -- unicode letter or CJK Unified Ideograph if ((u>=0x4E00 and u<=0x9FD5) -- CJK Unified Ideograph or (u>=0x2F00 and u<=0x2FD5) -- Kangxi Radicals or (u>=0x2E80 and u<=0x2EFF) -- CJK Radicals Supplement or (u>=0x3040 and u<=0x319F) -- Hiragana, Katakana, Bopomofo, Hangul, Kanbun or _find_codepoint(u, unidata.LetterOther) ) then return true, "other" end if _find_codepoint(u, unidata.LetterLower) then return true, "lower" end if _find_codepoint(u, unidata.LetterUpper) then return true, "upper" end return false end -- convert unicode character to lowercase form if defined in unicodedata function unicode.getLower(u) local l = unidata.maplower[u] if l then return l, unicode._cp_to_utf8(l) end return end -- convert unicode character to uppercase form if defined in unicodedata -- dynamically reverse maplower if necessary function unicode.getUpper(l) if not unicode.mapupper then unidata.mapupper = {} for uidx,lidx in pairs(unidata.maplower) do unidata.mapupper[lidx] = uidx end end local u = unidata.mapupper[l] if u then return u, unicode._cp_to_utf8(u) end return end function unicode.isNumber(u) if not u then return false end return _find_codepoint(u, unidata.Number) end function unicode.isAlnum(u) return unicode.isLetter(u) or unicode.isNumber(u) or u=='_' end return unicode
-- for lua < 5.3 compatibility local bit32 = nil if not bit32 then bit32 = require 'bit32' end local unidata = require './unidata' local unicode = {} -- convert the next utf8 character to ucs -- returns codepoint and utf-8 character function unicode._utf8_to_cp(s, idx) if idx > #s then return end idx = idx or 1 local c = string.byte(s, idx) local l = (c < 0x80 and 1) or (c < 0xE0 and 2) or (c < 0xF0 and 3) or (c < 0xF8 and 4) if not l then error("invalid utf-8 sequence") end local val = 0 if l == 1 then return c, string.sub(s, idx, idx) end for i = 1, l do c = string.byte(s, idx+i-1) if i > 1 then assert(bit32.band(c, 0xC0) == 0x80) val = bit32.lshift(val, 6) val = bit32.bor(val, bit32.band(c, 0x3F)) else val = bit32.band(c,bit32.rshift(0xff,l)) end end return val, string.sub(s, idx, idx+l-1) end -- convert unicode codepoint to utf8 function unicode._cp_to_utf8(u) assert(u>=0 and u<=0x10FFFF) if u <= 0x7F then return string.char(u) elseif u <= 0x7FF then local b0 = 0xC0 + bit32.rshift(u, 6) local b1 = 0x80 + bit32.band(u, 0x3F) return string.char(b0, b1) elseif u <= 0xFFFF then local b0 = 0xE0 + bit32.rshift(u, 12) local b1 = 0x80 + bit32.band(bit32.rshift(u, 6), 0x3f) local b2 = 0x80 + bit32.band(u, 0x3f) return string.char(b0, b1, b2) end local b0 = 0xF0 + bit32.rshift(u, 18) local b1 = 0x80 + bit32.band(bit32.rshift(u, 12), 0x3f) local b2 = 0x80 + bit32.band(bit32.rshift(u, 6), 0x3f) local b3 = 0x80 + bit32.band(u, 0x3f) return string.char(b0, b1, b2, b3) end function unicode.utf8_iter(s) local L = #s local nextv, nextc = unicode._utf8_to_cp(s, 1) local p = 1 if nextc then p = p + #nextc end return function() local v,c = nextv, nextc if p > L then if nextc then nextc = nil return v, c, nil end return end nextv, nextc = unicode._utf8_to_cp(s, p) p = p + #nextc return v, c, nextv end end local function _find_codepoint(u, utable) for i,v in pairs(utable) do if u >= i then local idx = bit32.rshift(u-i,4) + 1 local p = (u-i) % 16 if v[idx] then return not(bit32.band(bit32.lshift(v[idx], p), 0x8000) == 0) end end end return false end function unicode.isSeparator(u) if not u then return false end -- control character or separator return (u >= 9 and u <= 13) or _find_codepoint(u, unidata.Separator) end -- returns if letter and case "lower", "upper", "other" function unicode.isLetter(u) if not u then return false end -- unicode letter or CJK Unified Ideograph if ((u>=0x4E00 and u<=0x9FD5) -- CJK Unified Ideograph or (u>=0x2F00 and u<=0x2FD5) -- Kangxi Radicals or (u>=0x2E80 and u<=0x2EFF) -- CJK Radicals Supplement or (u>=0x3040 and u<=0x319F) -- Hiragana, Katakana, Bopomofo, Hangul, Kanbun or _find_codepoint(u, unidata.LetterOther) ) then return true, "other" end if _find_codepoint(u, unidata.LetterLower) then return true, "lower" end if _find_codepoint(u, unidata.LetterUpper) then return true, "upper" end return false end -- convert unicode character to lowercase form if defined in unicodedata function unicode.getLower(u) local l = unidata.maplower[u] if l then return l, unicode._cp_to_utf8(l) end return end -- convert unicode character to uppercase form if defined in unicodedata -- dynamically reverse maplower if necessary function unicode.getUpper(l) if not unicode.mapupper then -- make sure that reversing, we keep the smallest codepoint because we have İ>i, and I>i unidata.mapupper = {} for uidx,lidx in pairs(unidata.maplower) do if not unidata.mapupper[lidx] or unidata.mapupper[lidx] > uidx then unidata.mapupper[lidx] = uidx end end end local u = unidata.mapupper[l] if u then return u, unicode._cp_to_utf8(u) end return end function unicode.isNumber(u) if not u then return false end return _find_codepoint(u, unidata.Number) end function unicode.isAlnum(u) return unicode.isLetter(u) or unicode.isNumber(u) or u=='_' end return unicode
fix unicode lower table reverse
fix unicode lower table reverse
Lua
mit
jungikim/OpenNMT,OpenNMT/OpenNMT,da03/OpenNMT,OpenNMT/OpenNMT,da03/OpenNMT,da03/OpenNMT,jsenellart-systran/OpenNMT,jsenellart-systran/OpenNMT,OpenNMT/OpenNMT,monsieurzhang/OpenNMT,jsenellart/OpenNMT,monsieurzhang/OpenNMT,jsenellart-systran/OpenNMT,jsenellart/OpenNMT,jungikim/OpenNMT,srush/OpenNMT,jungikim/OpenNMT,monsieurzhang/OpenNMT,jsenellart/OpenNMT,cservan/OpenNMT_scores_0.2.0
6c0029df469e89ce809ff833a3fa631eee14f77e
core/libtexpdf-output.lua
core/libtexpdf-output.lua
local pdf = require("justenoughlibtexpdf") if (not SILE.outputters) then SILE.outputters = {} end local cursorX = 0 local cursorY = 0 local font = 0 local started = false local lastkey local function ensureInit () if not started then pdf.init(SILE.outputFilename, SILE.documentState.paperSize[1], SILE.documentState.paperSize[2]) pdf.beginpage() started = true end end SILE.outputters.libtexpdf = { init = function () -- We don't do anything yet because this commits us to a page size. end, _init = ensureInit, newPage = function () ensureInit() pdf.endpage() pdf.beginpage() end, finish = function () if not started then return end pdf.endpage() pdf.finish() started = false lastkey = nil end, setColor = function (_, color) ensureInit() if color.r then pdf.setcolor_rgb(color.r, color.g, color.b) end if color.c then pdf.setcolor_cmyk(color.c, color.m, color.y, color.k) end if color.l then pdf.setcolor_gray(color.l) end end, pushColor = function (_, color) ensureInit() if color.r then pdf.colorpush_rgb(color.r, color.g, color.b) end if color.c then pdf.colorpush_cmyk(color.c, color.m, color.y, color.k) end if color.l then pdf.colorpush_gray(color.l) end end, popColor = function (_) ensureInit() pdf.colorpop() end, cursor = function (_) return cursorX, cursorY end, outputHbox = function (value, width) width = SU.cast("number", width) ensureInit() if not value.glyphString then return end -- Nodes which require kerning or have offsets to the glyph -- position should be output a glyph at a time. We pass the -- glyph advance from the htmx table, so that libtexpdf knows -- how wide each glyph is. It uses this to then compute the -- relative position between the pen after the glyph has been -- painted (cursorX + glyphAdvance) and the next painting -- position (cursorX + width - remember that the box's "width" -- is actually the shaped x_advance). if value.complex then for i = 1, #(value.items) do local glyph = value.items[i].gid local buf = string.char(math.floor(glyph % 2^32 / 2^8)) .. string.char(glyph % 0x100) pdf.setstring(cursorX + (value.items[i].x_offset or 0), cursorY + (value.items[i].y_offset or 0), buf, string.len(buf), font, value.items[i].glyphAdvance) cursorX = cursorX + value.items[i].width end return end local buf = {} for i = 1, #(value.glyphString) do local glyph = value.glyphString[i] buf[#buf+1] = string.char(math.floor(glyph % 2^32 / 2^8)) buf[#buf+1] = string.char(glyph % 0x100) end buf = table.concat(buf, "") pdf.setstring(cursorX, cursorY, buf, string.len(buf), font, width) end, setFont = function (options) ensureInit() if SILE.font._key(options) == lastkey then return end lastkey = SILE.font._key(options) font = SILE.font.cache(options, SILE.shaper.getFace) if options.direction == "TTB" then font.layout_dir = 1 end if SILE.typesetter.frame and SILE.typesetter.frame:writingDirection() == "TTB" then pdf.setdirmode(1) else pdf.setdirmode(0) end local pdffont = pdf.loadfont(font) if pdffont < 0 then SU.error("Font loading error for "..options) end font = pdffont end, drawImage = function (src, x, y, width, height) x = SU.cast("number", x) y = SU.cast("number", y) width = SU.cast("number", width) height = SU.cast("number", height) ensureInit() pdf.drawimage(src, x, y, width, height) end, imageSize = function (src) ensureInit() -- in case it's a PDF file local llx, lly, urx, ury = pdf.imagebbox(src) return (urx-llx), (ury-lly) end, moveTo = function (x, y) x = SU.cast("number", x) y = SU.cast("number", y) cursorX = x cursorY = SILE.documentState.paperSize[2] - y end, rule = function (x, y, width, depth) x = SU.cast("number", x) y = SU.cast("number", y) width = SU.cast("number", width) depth = SU.cast("number", depth) ensureInit() pdf.setrule(x, SILE.documentState.paperSize[2] - y - depth, width, depth) end, debugFrame = function (self, frame) ensureInit() pdf.colorpush_rgb(0.8, 0, 0) self.rule(frame:left(), frame:top(), frame:width(), 0.5) self.rule(frame:left(), frame:top(), 0.5, frame:height()) self.rule(frame:right(), frame:top(), 0.5, frame:height()) self.rule(frame:left(), frame:bottom(), frame:width(), 0.5) --self.rule(frame:left() + frame:width()/2 - 5, (frame:top() + frame:bottom())/2+5, 10, 10) local gentium = SILE.font.loadDefaults({family="Gentium Plus", language="en"}) local stuff = SILE.shaper:createNnodes(frame.id, gentium) stuff = stuff[1].nodes[1].value.glyphString -- Horrible hack local buf = {} for i = 1, #stuff do local glyph = stuff[i] buf[#buf+1] = string.char(math.floor(glyph % 2^32 / 2^8)) buf[#buf+1] = string.char(glyph % 0x100) end buf = table.concat(buf, "") local oldfont = font SILE.outputter.setFont(gentium) pdf.setstring(frame:left():tonumber(), (SILE.documentState.paperSize[2] - frame:top()):tonumber(), buf, string.len(buf), font, 0) if oldfont then pdf.loadfont(oldfont) font = oldfont end pdf.colorpop() end, debugHbox = function (hbox, scaledWidth) ensureInit() pdf.colorpush_rgb(0.8, 0.3, 0.3) pdf.setrule(cursorX, cursorY+(hbox.height), scaledWidth+0.5, 0.5) pdf.setrule(cursorX, cursorY, 0.5, hbox.height) pdf.setrule(cursorX, cursorY, scaledWidth+0.5, 0.5) pdf.setrule(cursorX+scaledWidth, cursorY, 0.5, hbox.height) if hbox.depth then pdf.setrule(cursorX, cursorY-(hbox.depth), scaledWidth, 0.5) pdf.setrule(cursorX+scaledWidth, cursorY-(hbox.depth), 0.5, hbox.depth) pdf.setrule(cursorX, cursorY-(hbox.depth), 0.5, hbox.depth) end pdf.colorpop() end } SILE.outputter = SILE.outputters.libtexpdf if not SILE.outputFilename and SILE.masterFilename then SILE.outputFilename = SILE.masterFilename..".pdf" end
local pdf = require("justenoughlibtexpdf") if (not SILE.outputters) then SILE.outputters = {} end local cursorX = 0 local cursorY = 0 local font = 0 local started = false local lastkey local function ensureInit () if not started then pdf.init(SILE.outputFilename, SILE.documentState.paperSize[1], SILE.documentState.paperSize[2]) pdf.beginpage() started = true end end SILE.outputters.libtexpdf = { init = function () -- We don't do anything yet because this commits us to a page size. end, _init = ensureInit, newPage = function () ensureInit() pdf.endpage() pdf.beginpage() end, finish = function () if not started then return end pdf.endpage() pdf.finish() started = false lastkey = nil end, setColor = function (_, color) ensureInit() if color.r then pdf.setcolor_rgb(color.r, color.g, color.b) end if color.c then pdf.setcolor_cmyk(color.c, color.m, color.y, color.k) end if color.l then pdf.setcolor_gray(color.l) end end, pushColor = function (_, color) ensureInit() if color.r then pdf.colorpush_rgb(color.r, color.g, color.b) end if color.c then pdf.colorpush_cmyk(color.c, color.m, color.y, color.k) end if color.l then pdf.colorpush_gray(color.l) end end, popColor = function (_) ensureInit() pdf.colorpop() end, cursor = function (_) return cursorX, cursorY end, outputHbox = function (value, width) width = SU.cast("number", width) ensureInit() if not value.glyphString then return end -- Nodes which require kerning or have offsets to the glyph -- position should be output a glyph at a time. We pass the -- glyph advance from the htmx table, so that libtexpdf knows -- how wide each glyph is. It uses this to then compute the -- relative position between the pen after the glyph has been -- painted (cursorX + glyphAdvance) and the next painting -- position (cursorX + width - remember that the box's "width" -- is actually the shaped x_advance). if value.complex then for i = 1, #(value.items) do local glyph = value.items[i].gid local buf = string.char(math.floor(glyph % 2^32 / 2^8)) .. string.char(glyph % 0x100) pdf.setstring(cursorX + (value.items[i].x_offset or 0), cursorY + (value.items[i].y_offset or 0), buf, string.len(buf), font, value.items[i].glyphAdvance) cursorX = cursorX + value.items[i].width end return end local buf = {} for i = 1, #(value.glyphString) do local glyph = value.glyphString[i] buf[#buf+1] = string.char(math.floor(glyph % 2^32 / 2^8)) buf[#buf+1] = string.char(glyph % 0x100) end buf = table.concat(buf, "") pdf.setstring(cursorX, cursorY, buf, string.len(buf), font, width) end, setFont = function (options) ensureInit() if SILE.font._key(options) == lastkey then return end lastkey = SILE.font._key(options) font = SILE.font.cache(options, SILE.shaper.getFace) if options.direction == "TTB" then font.layout_dir = 1 end if SILE.typesetter.frame and SILE.typesetter.frame:writingDirection() == "TTB" then pdf.setdirmode(1) else pdf.setdirmode(0) end local pdffont = pdf.loadfont(font) if pdffont < 0 then SU.error("Font loading error for "..options) end font = pdffont end, drawImage = function (src, x, y, width, height) x = SU.cast("number", x) y = SU.cast("number", y) width = SU.cast("number", width) height = SU.cast("number", height) ensureInit() pdf.drawimage(src, x, y, width, height) end, imageSize = function (src) ensureInit() -- in case it's a PDF file local llx, lly, urx, ury = pdf.imagebbox(src) return (urx-llx), (ury-lly) end, moveTo = function (x, y) x = SU.cast("number", x) y = SU.cast("number", y) cursorX = x cursorY = SILE.documentState.paperSize[2] - y end, rule = function (x, y, width, depth) x = SU.cast("number", x) y = SU.cast("number", y) width = SU.cast("number", width) depth = SU.cast("number", depth) ensureInit() pdf.setrule(x, SILE.documentState.paperSize[2] - y - depth, width, depth) end, debugFrame = function (self, frame) ensureInit() pdf.colorpush_rgb(0.8, 0, 0) self.rule(frame:left(), frame:top(), frame:width(), 0.5) self.rule(frame:left(), frame:top(), 0.5, frame:height()) self.rule(frame:right(), frame:top(), 0.5, frame:height()) self.rule(frame:left(), frame:bottom(), frame:width(), 0.5) --self.rule(frame:left() + frame:width()/2 - 5, (frame:top() + frame:bottom())/2+5, 10, 10) local gentium = SILE.font.loadDefaults({family="Gentium Plus", language="en"}) local stuff = SILE.shaper:createNnodes(frame.id, gentium) stuff = stuff[1].nodes[1].value.glyphString -- Horrible hack local buf = {} for i = 1, #stuff do local glyph = stuff[i] buf[#buf+1] = string.char(math.floor(glyph % 2^32 / 2^8)) buf[#buf+1] = string.char(glyph % 0x100) end buf = table.concat(buf, "") local oldfont = font SILE.outputter.setFont(gentium) pdf.setstring(frame:left():tonumber(), (SILE.documentState.paperSize[2] - frame:top()):tonumber(), buf, string.len(buf), font, 0) if oldfont then pdf.loadfont(oldfont) font = oldfont end pdf.colorpop() end, debugHbox = function (hbox, scaledWidth) ensureInit() pdf.colorpush_rgb(0.8, 0.3, 0.3) pdf.setrule(cursorX, cursorY+(hbox.height:tonumber()), scaledWidth:tonumber()+0.5, 0.5) pdf.setrule(cursorX, cursorY, 0.5, hbox.height:tonumber()) pdf.setrule(cursorX, cursorY, scaledWidth:tonumber()+0.5, 0.5) pdf.setrule(cursorX+scaledWidth:tonumber(), cursorY, 0.5, hbox.height:tonumber()) if hbox.depth then pdf.setrule(cursorX, cursorY-(hbox.depth:tonumber()), scaledWidth:tonumber(), 0.5) pdf.setrule(cursorX+scaledWidth:tonumber(), cursorY-(hbox.depth:tonumber()), 0.5, hbox.depth:tonumber()) pdf.setrule(cursorX, cursorY-(hbox.depth:tonumber()), 0.5, hbox.depth:tonumber()) end pdf.colorpop() end } SILE.outputter = SILE.outputters.libtexpdf if not SILE.outputFilename and SILE.masterFilename then SILE.outputFilename = SILE.masterFilename..".pdf" end
fix(debug): Fix math in hbox debugging
fix(debug): Fix math in hbox debugging
Lua
mit
alerque/sile,alerque/sile,alerque/sile,alerque/sile
4b294d2588b098c70cdd316838806dd32c647dc8
src_trunk/resources/lvpd-system/s_backup.lua
src_trunk/resources/lvpd-system/s_backup.lua
backupBlip = false backupPlayer = nil function removeBackup(thePlayer, commandName) if (exports.global:isPlayerAdmin(thePlayer)) then if (backupPlayer~=nil) then for k,v in ipairs(getPlayersInTeam ( getTeamFromName("Los Santos Police Department") )) do triggerClientEvent(v, "destroyBackupBlip", backupBlip) end removeEventHandler("onPlayerQuit", backupPlayer, destroyBlip) removeEventHandler("savePlayer", backupPlayer, destroyBlip) backupPlayer = nil backupBlip = false outputChatBox("Backup system reset!", thePlayer, 255, 194, 14) else outputChatBox("Backup system did not need reset.", thePlayer, 255, 194, 14) end end end addCommandHandler("resetbackup", removeBackup, false, false) function backup(thePlayer, commandName) local duty = tonumber(getElementData(thePlayer, "duty")) local theTeam = getPlayerTeam(thePlayer) local factionType = getElementData(theTeam, "type") if (factionType==2) and (duty>0) then if (backupBlip == true) and (backupPlayer~=thePlayer) then -- in use outputChatBox("There is already a backup beacon in use.", thePlayer, 255, 194, 14) elseif (backupBlip == false) then -- make backup blip backupBlip = true backupPlayer = thePlayer for k,v in ipairs(getPlayersInTeam ( getTeamFromName("Los Santos Police Department") )) do local duty = tonumber(getElementData(v, "duty")) if (duty>0) then triggerClientEvent(v, "createBackupBlip", thePlayer) outputChatBox("A unit needs urgent assistance! Please respond ASAP!", v, 255, 194, 14) end end addEventHandler("onPlayerQuit", thePlayer, destroyBlip) addEventHandler("savePlayer", thePlayer, destroyBlip) elseif (backupBlip == true) and (backupPlayer==thePlayer) then -- in use by this player for key, v in ipairs(getPlayersInTeam(theTeam)) do local duty = tonumber(getElementData(v, "duty")) if (duty>0) then triggerClientEvent(v, "destroyBackupBlip", getRootElement()) outputChatBox("The unit no longer requires assistance. Resume normal patrol", v, 255, 194, 14) end end removeEventHandler("onPlayerQuit", thePlayer, destroyBlip) removeEventHandler("savePlayer", thePlayer, destroyBlip) backupPlayer = nil backupBlip = false end end end addCommandHandler("backup", backup, false, false) function destroyBlip() local theTeam = getPlayerTeam(source) for key, value in ipairs(getPlayersInTeam(theTeam)) do outputChatBox("The unit no longer requires assistance. Resume normal patrol", value, 255, 194, 14) end for k,v in ipairs(getPlayersInTeam ( getTeamFromName("Los Santos Police Department") )) do triggerClientEvent(v, "destroyBackupBlip", backupBlip) end removeEventHandler("onPlayerQuit", thePlayer, destroyBlip) removeEventHandler("savePlayer", thePlayer, destroyBlip) backupPlayer = nil backupBlip = false end
backupBlip = false backupPlayer = nil function removeBackup(thePlayer, commandName) if (exports.global:isPlayerAdmin(thePlayer)) then if (backupPlayer~=nil) then for k,v in ipairs(getPlayersInTeam ( getTeamFromName("Los Santos Police Department") )) do triggerClientEvent(v, "destroyBackupBlip", getRootElement()) end removeEventHandler("onPlayerQuit", backupPlayer, destroyBlip) removeEventHandler("savePlayer", backupPlayer, destroyBlip) backupPlayer = nil backupBlip = false outputChatBox("Backup system reset!", thePlayer, 255, 194, 14) else outputChatBox("Backup system did not need reset.", thePlayer, 255, 194, 14) end end end addCommandHandler("resetbackup", removeBackup, false, false) function backup(thePlayer, commandName) local duty = tonumber(getElementData(thePlayer, "duty")) local theTeam = getPlayerTeam(thePlayer) local factionType = getElementData(theTeam, "type") if (factionType==2) and (duty>0) then if (backupBlip == true) and (backupPlayer~=thePlayer) then -- in use outputChatBox("There is already a backup beacon in use.", thePlayer, 255, 194, 14) elseif (backupBlip == false) then -- make backup blip backupBlip = true backupPlayer = thePlayer for k,v in ipairs(getPlayersInTeam ( getTeamFromName("Los Santos Police Department") )) do local duty = tonumber(getElementData(v, "duty")) if (duty>0) then triggerClientEvent(v, "createBackupBlip", thePlayer) outputChatBox("A unit needs urgent assistance! Please respond ASAP!", v, 255, 194, 14) end end addEventHandler("onPlayerQuit", thePlayer, destroyBlip) addEventHandler("savePlayer", thePlayer, destroyBlip) elseif (backupBlip == true) and (backupPlayer==thePlayer) then -- in use by this player for key, v in ipairs(getPlayersInTeam(theTeam)) do local duty = tonumber(getElementData(v, "duty")) if (duty>0) then triggerClientEvent(v, "destroyBackupBlip", getRootElement()) outputChatBox("The unit no longer requires assistance. Resume normal patrol", v, 255, 194, 14) end end removeEventHandler("onPlayerQuit", thePlayer, destroyBlip) removeEventHandler("savePlayer", thePlayer, destroyBlip) backupPlayer = nil backupBlip = false end end end addCommandHandler("backup", backup, false, false) function destroyBlip() local theTeam = getPlayerTeam(source) for key, value in ipairs(getPlayersInTeam(theTeam)) do outputChatBox("The unit no longer requires assistance. Resume normal patrol", value, 255, 194, 14) triggerClientEvent(value, "destroyBackupBlip", getRootElement()) end removeEventHandler("onPlayerQuit", thePlayer, destroyBlip) removeEventHandler("savePlayer", thePlayer, destroyBlip) backupPlayer = nil backupBlip = false end
Fixed backup
Fixed backup git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1210 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
cee1083cbbb1f98a3156e6c0a410148296e0177e
src/lua-factory/sources/grl-spotify-cover.lua
src/lua-factory/sources/grl-spotify-cover.lua
--[[ * Copyright (C) 2015 Bastien Nocera. * * Contact: Bastien Nocera <[email protected]> * * 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-spotify-cover", name = "Spotify Cover", description = "a source for music covers", supported_keys = { 'thumbnail' }, supported_media = { 'audio' }, resolve_keys = { ["type"] = "audio", required = { "artist", "album" }, }, tags = { 'music', 'net:internet' }, } ------------------ -- Source utils -- ------------------ SPOTIFY_SEARCH_ALBUM = 'https://api.spotify.com/v1/search?q=album:%s+artist:%s&type=album&limit=1' --------------------------------- -- 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.album or #media.artist == 0 or #media.album == 0 then callback() return end -- Prepare artist and title strings to the url artist = grl.encode(media.artist) album = grl.encode(media.album) url = string.format(SPOTIFY_SEARCH_ALBUM, album, artist) local userdata = {callback = callback, media = media} grl.fetch(url, fetch_page_cb, userdata) end --------------- -- Utilities -- --------------- function fetch_page_cb(result, userdata) local json = {} if not result then userdata.callback() return end json = grl.lua.json.string_to_table(result) if not json or not json.albums or json.albums.total == 0 or not json.albums.items or not #json.albums.items or not json.albums.items[1].images then userdata.callback() return end userdata.media.thumbnail = {} for i, item in ipairs(json.albums.items[1].images) do table.insert(userdata.media.thumbnail, item.url) end userdata.callback(userdata.media, 0) end
--[[ * Copyright (C) 2015 Bastien Nocera. * * Contact: Bastien Nocera <[email protected]> * * 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-spotify-cover", name = "Spotify Cover", description = "a source for music covers", supported_keys = { 'thumbnail' }, supported_media = { 'audio' }, resolve_keys = { ["type"] = "audio", required = { "artist", "album" }, }, tags = { 'music', 'net:internet' }, } ------------------ -- Source utils -- ------------------ SPOTIFY_SEARCH_ALBUM = 'https://api.spotify.com/v1/search?q=album:%s+artist:%s&type=album&limit=1' --------------------------------- -- 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.album or #req.artist == 0 or #req.album == 0 then grl.callback() return end -- Prepare artist and title strings to the url artist = grl.encode(req.artist) album = grl.encode(req.album) url = string.format(SPOTIFY_SEARCH_ALBUM, album, artist) grl.fetch(url, fetch_page_cb) end --------------- -- Utilities -- --------------- function fetch_page_cb(result) local json = {} if not result then grl.callback() return end json = grl.lua.json.string_to_table(result) if not json or not json.albums or json.albums.total == 0 or not json.albums.items or not #json.albums.items or not json.albums.items[1].images then grl.callback() return end local media = {} media.thumbnail = {} for i, item in ipairs(json.albums.items[1].images) do table.insert(media.thumbnail, item.url) end grl.callback(media, 0) end
Revert "lua-factory: port grl-spotify-cover.lua to the new lua system"
Revert "lua-factory: port grl-spotify-cover.lua to the new lua system" This reverts commit 9b329f3e5246477f039a1fb2b129706370237c89. But keeps grl.fetch callback as function instead of string https://bugzilla.gnome.org/show_bug.cgi?id=763046
Lua
lgpl-2.1
MikePetullo/grilo-plugins,GNOME/grilo-plugins,GNOME/grilo-plugins,MikePetullo/grilo-plugins,jasuarez/grilo-plugins,MikePetullo/grilo-plugins,grilofw/grilo-plugins,grilofw/grilo-plugins,jasuarez/grilo-plugins
c2c491ab4bedea3be7b1a6aca8bb4e65a9d763db
xmake/modules/detect/tools/nvcc/has_flags.lua
xmake/modules/detect/tools/nvcc/has_flags.lua
--!A cross-platform build utility based on Lua -- -- 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. -- -- Copyright (C) 2015 - 2019, TBOOX Open Source Group. -- -- @author ruki -- @file has_flags.lua -- -- imports import("lib.detect.cache") import("core.language.language") -- is linker? function _islinker(flags, opt) -- the flags is "-Wl,<arg>" or "-Xlinker <arg>"? local flags_str = table.concat(flags, " ") if flags_str:startswith("-Wl,") or flags_str:startswith("-Xlinker ") then return true end -- the tool kind is ld or sh? local toolkind = opt.toolkind or "" return toolkind == "ld" or toolkind == "sh" or toolkind:endswith("-ld") or toolkind:endswith("-sh") end -- try running function _try_running(...) local argv = {...} local errors = nil return try { function () os.runv(unpack(argv)); return true end, catch { function (errs) errors = (errs or ""):trim() end }}, errors end -- attempt to check it from the argument list function _check_from_arglist(flags, opt, islinker) -- check for the builtin flags local builtin_flags = {["-code"] = true, ["--gpu-code"] = true, ["-gencode"] = true, ["--generate-code"] = true, ["-arch"] = true, ["--gpu-architecture"] = true} if builtin_flags[flags[1]] then return true end -- check from the `--help` menu, only for linker if islinker or #flags > 1 then return end -- make cache key local key = "detect.tools.nvcc.has_flags" -- make flags key local flagskey = opt.program .. "_" .. (opt.programver or "") -- load cache local cacheinfo = cache.load(key) -- get all flags from argument list local allflags = cacheinfo[flagskey] if not allflags then -- get argument list allflags = {} local arglist = os.iorunv(opt.program, {"--help"}) if arglist then for arg in arglist:gmatch("%s+(%-[%-%a%d]+)%s+") do allflags[arg] = true end end -- save cache cacheinfo[flagskey] = allflags cache.save(key, cacheinfo) end -- ok? return allflags[flags[1]] end -- try running to check flags function _check_try_running(flags, opt, islinker) -- make an stub source file local sourcefile = path.join(os.tmpdir(), "detect", "nvcc_has_flags.cu") if not os.isfile(sourcefile) then io.writefile(sourcefile, "int main(int argc, char** argv)\n{return 0;}") end -- check flags local objectfile = is_plat("windows") and sourcefile .. ".o" or os.nuldev() if islinker then return _try_running(opt.program, table.join(flags, "-o", objectfile, sourcefile)) else return _try_running(opt.program, table.join(flags, "-c", "-o", objectfile, sourcefile)) end end -- has_flags(flags)? -- -- @param opt the argument options, .e.g {toolname = "", program = "", programver = "", toolkind = "cu"} -- -- @return true or false -- function main(flags, opt) -- is linker? local islinker = _islinker(flags, opt) -- attempt to check it from the argument list if _check_from_arglist(flags, opt, islinker) then return true end -- try running to check it return _check_try_running(flags, opt, islinker) end
--!A cross-platform build utility based on Lua -- -- 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. -- -- Copyright (C) 2015 - 2019, TBOOX Open Source Group. -- -- @author ruki -- @file has_flags.lua -- -- imports import("lib.detect.cache") import("core.language.language") -- is linker? function _islinker(flags, opt) -- the flags is "-Wl,<arg>" or "-Xlinker <arg>"? local flags_str = table.concat(flags, " ") if flags_str:startswith("-Wl,") or flags_str:startswith("-Xlinker ") then return true end -- the tool kind is ld or sh? local toolkind = opt.toolkind or "" return toolkind == "ld" or toolkind == "sh" or toolkind:endswith("-ld") or toolkind:endswith("-sh") end -- try running function _try_running(...) local argv = {...} local errors = nil return try { function () os.runv(unpack(argv)); return true end, catch { function (errs) errors = (errs or ""):trim() end }}, errors end -- attempt to check it from the argument list function _check_from_arglist(flags, opt, islinker) -- check for the builtin flags local builtin_flags = {["-code"] = true, ["--gpu-code"] = true, ["-gencode"] = true, ["--generate-code"] = true, ["-arch"] = true, ["--gpu-architecture"] = true, ["-cudart=none"] = true, ["--cudart=none"] = true} if builtin_flags[flags[1]] then return true end local cudart_flags = {["none"] = true, ["shared"] = true, ["static"] = true} local builtin_flags_pair = {["-cudart"] = cudart_flags, ["--cudart"] = cudart_flags} if #flags > 1 and builtin_flags_pair[flags[1]] and builtin_flags_pair[flags[1]][flags[2]] then return true end -- check from the `--help` menu, only for linker if islinker or #flags > 1 then return end -- make cache key local key = "detect.tools.nvcc.has_flags" -- make flags key local flagskey = opt.program .. "_" .. (opt.programver or "") -- load cache local cacheinfo = cache.load(key) -- get all flags from argument list local allflags = cacheinfo[flagskey] if not allflags then -- get argument list allflags = {} local arglist = os.iorunv(opt.program, {"--help"}) if arglist then for arg in arglist:gmatch("%s+(%-[%-%a%d]+)%s+") do allflags[arg] = true end end -- save cache cacheinfo[flagskey] = allflags cache.save(key, cacheinfo) end -- ok? return allflags[flags[1]] end -- try running to check flags function _check_try_running(flags, opt, islinker) -- make an stub source file local sourcefile = path.join(os.tmpdir(), "detect", "nvcc_has_flags.cu") if not os.isfile(sourcefile) then io.writefile(sourcefile, "int main(int argc, char** argv)\n{return 0;}") end -- check flags local objectfile = is_plat("windows") and sourcefile .. ".o" or os.nuldev() if islinker then return _try_running(opt.program, table.join(flags, "-o", objectfile, sourcefile)) else return _try_running(opt.program, table.join(flags, "-c", "-o", objectfile, sourcefile)) end end -- has_flags(flags)? -- -- @param opt the argument options, .e.g {toolname = "", program = "", programver = "", toolkind = "cu"} -- -- @return true or false -- function main(flags, opt) -- is linker? local islinker = _islinker(flags, opt) -- attempt to check it from the argument list if _check_from_arglist(flags, opt, islinker) then return true end -- try running to check it return _check_try_running(flags, opt, islinker) end
Support cudart flags
Support cudart flags Fix check failed of "-cudart none" ``` checking for the flags (-cudart none ) ... no > nvcc -cudart none -m64 -LC:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\lib checkinfo: C:\Program Files (x86)\xmake/core/base/os.lua:715: nvcc_has_flags.cu tmpxft_00003f20_00000000-18_nvcc_has_flags.obj : error LNK2019: 无法解析的外部符号 __cudaRegisterFatBinary,该符号在函数 "void __cdecl __nv_cudaEntityRegisterCallback(void * *)" (?__nv_cudaEntityRegisterCallback@@YAXPEAPEAX@Z) 中被引用 tmpxft_00003f20_00000000-18_nvcc_has_flags.obj : error LNK2019: 无法解析的外部符号 __cudaRegisterFatBinaryEnd,该符号在函数 "void __cdecl __nv_cudaEntityRegisterCallback(void * *)" (?__nv_cudaEntityRegisterCallback@@YAXPEAPEAX@Z) 中被引用 tmpxft_00003f20_00000000-18_nvcc_has_flags.obj : error LNK2019: 无法解析的外部符号 __cudaUnregisterFatBinary,该符号在函数 "void __cdecl __cudaUnregisterBinaryUtil(void)" (?__cudaUnregisterBinaryUtil@@YAXXZ) 中被引用 C:\Users\lzy\AppData\Local\Temp\.xmake\190520\detect\nvcc_has_flags.cu.o : fatal error LNK1120: 3 个无法解析的外部命令 stack traceback: [C]: in function 'error' [C:\Program Files (x86)\xmake/core/base/os.lua:715]: in function 'raise' [C:\Program Files (x86)\xmake\core\sandbox\modules\os.lua:309]: in function 'runv' [...iles (x86)\xmake\modules\detect\tools\nvcc\has_flags.lua:44]: ```
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
e3316c4e1086e75aa24d73d2f28175fb57abbc33
build/scripts/common.lua
build/scripts/common.lua
-- Configuration gnrale configurations { -- "DebugStatic", -- "ReleaseStatic", "DebugDLL", "ReleaseDLL" } defines "NAZARA_BUILD" language "C++" location(_ACTION) includedirs { "../include", "../src/", "../extlibs/include" } libdirs "../lib" if (_OPTIONS["x64"]) then libdirs "../extlibs/lib/x64" end libdirs "../extlibs/lib/x86" targetdir "../lib" configuration "Debug*" defines "NAZARA_DEBUG" flags "Symbols" configuration "Release*" flags { "EnableSSE", "EnableSSE2", "Optimize", "OptimizeSpeed", "NoFramePointer", "NoRTTI" } configuration "*Static" defines "NAZARA_STATIC" kind "StaticLib" configuration "*DLL" kind "SharedLib" configuration "DebugStatic" targetsuffix "-s-d" configuration "ReleaseStatic" targetsuffix "-s" configuration "DebugDLL" targetsuffix "-d" configuration "codeblocks or codelite or gmake or xcode3*" buildoptions { "-mfpmath=sse", "-std=c++11" } configuration { "linux or bsd or macosx", "gmake" } buildoptions "-fvisibility=hidden"
-- Configuration gnrale configurations { -- "DebugStatic", -- "ReleaseStatic", "DebugDLL", "ReleaseDLL" } defines "NAZARA_BUILD" language "C++" location(_ACTION) includedirs { "../include", "../src/", "../extlibs/include" } libdirs "../lib" if (_OPTIONS["x64"]) then libdirs "../extlibs/lib/x64" end libdirs "../extlibs/lib/x86" targetdir "../lib" configuration "Debug*" defines "NAZARA_DEBUG" flags "Symbols" configuration "Release*" flags { "EnableSSE", "EnableSSE2", "Optimize", "OptimizeSpeed", "NoFramePointer", "NoRTTI" } -- Activation du SSE ct GCC configuration { "Release*", "codeblocks or codelite or gmake or xcode3*" } buildoptions "-mfpmath=sse" configuration "*Static" defines "NAZARA_STATIC" kind "StaticLib" configuration "*DLL" kind "SharedLib" configuration "DebugStatic" targetsuffix "-s-d" configuration "ReleaseStatic" targetsuffix "-s" configuration "DebugDLL" targetsuffix "-d" configuration "codeblocks or codelite or gmake or xcode3*" buildoptions "-std=c++11" configuration { "linux or bsd or macosx", "gmake" } buildoptions "-fvisibility=hidden"
Fixed SSE warning in debug with GCC
Fixed SSE warning in debug with GCC Former-commit-id: 3632988311795547ccf59a66606b3faccff1a1b1
Lua
mit
DigitalPulseSoftware/NazaraEngine
665dfcbab6ee25cab99b103afdbc1a952c650ce2
busted/outputHandlers/base.lua
busted/outputHandlers/base.lua
return function(busted) local handler = { successes = {}, successesCount = 0, pendings = {}, pendingsCount = 0, failures = {}, failuresCount = 0, errors = {}, errorsCount = 0, inProgress = {} } handler.subscribe = function(handler, options) require('busted.languages.en') if options.language ~= 'en' then require('busted.languages.' .. options.language) end busted.subscribe({ 'suite', 'start' }, handler.baseSuiteStart) busted.subscribe({ 'suite', 'end' }, handler.baseSuiteEnd) busted.subscribe({ 'test', 'start' }, handler.baseTestStart) busted.subscribe({ 'test', 'end' }, handler.baseTestEnd) busted.subscribe({ 'error', 'it' }, handler.baseError) busted.subscribe({ 'error', 'file' }, handler.baseError) busted.subscribe({ 'error', 'pending' }, handler.baseError) end handler.getFullName = function(context) local parent = busted.context.parent(context) local names = { (context.name or context.descriptor) } while parent and (parent.name or parent.descriptor) and parent.descriptor ~= 'file' do current_context = context.parent table.insert(names, 1, parent.name or parent.descriptor) parent = busted.context.parent(parent) end return table.concat(names, ' ') end handler.format = function(element, parent, message, debug, isError) local formatted = { trace = element.trace or debug, name = handler.getFullName(element), message = message, isError = isError } return formatted end handler.getDuration = function() if not handler.endTime or not handler.startTime then return 0 end return handler.endTime - handler.startTime end handler.baseSuiteStart = function(name, parent) handler.startTime = os.clock() return nil, true end handler.baseSuiteEnd = function(name, parent) handler.endTime = os.clock() return nil, true end handler.baseTestStart = function(element, parent) handler.inProgress[tostring(element)] = {} return nil, true end handler.baseTestEnd = function(element, parent, status, debug) local insertTable local id = tostring(element) if status == 'success' then insertTable = handler.successes handler.successesCount = handler.successesCount + 1 elseif status == 'pending' then insertTable = handler.pendings handler.pendingsCount = handler.pendingsCount + 1 elseif status == 'failure' then insertTable = handler.failures handler.failuresCount = handler.failuresCount + 1 end insertTable[id] = handler.format(element, parent, nil, debug) if handler.inProgress[id] then for k, v in pairs(handler.inProgress[id]) do insertTable[id][k] = v end handler.inProgress[id] = nil end return nil, true end handler.baseError = function(element, parent, message, debug) if element.descriptor == 'it' then handler.inProgress[tostring(element)].message = message else handler.errorsCount = handler.errorsCount + 1 table.insert(handler.errors, handler.format(element, parent, message, debug, true)) end return nil, true end return handler end
return function(busted) local handler = { successes = {}, successesCount = 0, pendings = {}, pendingsCount = 0, failures = {}, failuresCount = 0, errors = {}, errorsCount = 0, inProgress = {} } handler.subscribe = function(handler, options) require('busted.languages.en') if options.language ~= 'en' then require('busted.languages.' .. options.language) end busted.subscribe({ 'suite', 'start' }, handler.baseSuiteStart) busted.subscribe({ 'suite', 'end' }, handler.baseSuiteEnd) busted.subscribe({ 'test', 'start' }, handler.baseTestStart) busted.subscribe({ 'test', 'end' }, handler.baseTestEnd) busted.subscribe({ 'error', 'describe' }, handler.baseError) busted.subscribe({ 'error', 'it' }, handler.baseError) busted.subscribe({ 'error', 'file' }, handler.baseError) busted.subscribe({ 'error', 'pending' }, handler.baseError) end handler.getFullName = function(context) local parent = busted.context.parent(context) local names = { (context.name or context.descriptor) } while parent and (parent.name or parent.descriptor) and parent.descriptor ~= 'file' do current_context = context.parent table.insert(names, 1, parent.name or parent.descriptor) parent = busted.context.parent(parent) end return table.concat(names, ' ') end handler.format = function(element, parent, message, debug, isError) local formatted = { trace = element.trace or debug, name = handler.getFullName(element), message = message, isError = isError } return formatted end handler.getDuration = function() if not handler.endTime or not handler.startTime then return 0 end return handler.endTime - handler.startTime end handler.baseSuiteStart = function(name, parent) handler.startTime = os.clock() return nil, true end handler.baseSuiteEnd = function(name, parent) handler.endTime = os.clock() return nil, true end handler.baseTestStart = function(element, parent) handler.inProgress[tostring(element)] = {} return nil, true end handler.baseTestEnd = function(element, parent, status, debug) local insertTable local id = tostring(element) if status == 'success' then insertTable = handler.successes handler.successesCount = handler.successesCount + 1 elseif status == 'pending' then insertTable = handler.pendings handler.pendingsCount = handler.pendingsCount + 1 elseif status == 'failure' then insertTable = handler.failures handler.failuresCount = handler.failuresCount + 1 end insertTable[id] = handler.format(element, parent, nil, debug) if handler.inProgress[id] then for k, v in pairs(handler.inProgress[id]) do insertTable[id][k] = v end handler.inProgress[id] = nil end return nil, true end handler.baseError = function(element, parent, message, debug) if element.descriptor == 'it' then handler.inProgress[tostring(element)].message = message else handler.errorsCount = handler.errorsCount + 1 table.insert(handler.errors, handler.format(element, parent, message, debug, true)) end return nil, true end return handler end
Handle errors in describe blocks
Handle errors in describe blocks Fixes part of #260 Also, cc @kbambz :P
Lua
mit
sobrinho/busted,DorianGray/busted,Olivine-Labs/busted,leafo/busted,xyliuke/busted,ryanplusplus/busted,o-lim/busted,mpeterv/busted,istr/busted,nehz/busted
a37128f891bca7336f4dff2809d18cf3304e50b2
mods/farming/melon.lua
mods/farming/melon.lua
local S = farming.intllib -- melon minetest.register_craftitem("farming:melon_slice", { description = S("Melon Slice"), inventory_image = "farming_melon_slice.png", on_place = function(itemstack, placer, pointed_thing) return farming.place_seed(itemstack, placer, pointed_thing, "farming:melon_1") end, on_use = minetest.item_eat(2), }) minetest.register_craft({ output = "farming:melon_8", recipe = { {"farming:melon_slice", "farming:melon_slice", "farming:melon_slice"}, {"farming:melon_slice", "farming:melon_slice", "farming:melon_slice"}, {"farming:melon_slice", "farming:melon_slice", "farming:melon_slice"}, } }) minetest.register_craft({ output = "farming:melon_slice 9", recipe = { {"", "farming:melon_8", ""}, } }) -- melon definition local crop_def = { drawtype = "plantlike", tiles = {"farming_melon_1.png"}, paramtype = "light", sunlight_propagates = true, walkable = false, buildable_to = true, drop = "", selection_box = farming.select, groups = { snappy = 3, flammable = 2, plant = 1, attached_node = 1, not_in_creative_inventory = 1, growing = 1 }, sounds = default.node_sound_leaves_defaults() } -- stage 1 minetest.register_node("farming:melon_1", table.copy(crop_def)) -- stage 2 crop_def.tiles = {"farming_melon_2.png"} minetest.register_node("farming:melon_2", table.copy(crop_def)) -- stage 3 crop_def.tiles = {"farming_melon_3.png"} minetest.register_node("farming:melon_3", table.copy(crop_def)) -- stage 4 crop_def.tiles = {"farming_melon_4.png"} minetest.register_node("farming:melon_4", table.copy(crop_def)) -- stage 5 crop_def.tiles = {"farming_melon_5.png"} minetest.register_node("farming:melon_5", table.copy(crop_def)) -- stage 6 crop_def.tiles = {"farming_melon_6.png"} minetest.register_node("farming:melon_6", table.copy(crop_def)) -- stage 7 crop_def.tiles = {"farming_melon_7.png"} minetest.register_node("farming:melon_7", table.copy(crop_def)) -- stage 8 (final) crop_def.drawtype = "nodebox" crop_def.description = S("Melon") crop_def.tiles = {"farming_melon_top.png", "farming_melon_top.png", "farming_melon_side.png"} crop_def.selection_box = {-.5, -.5, -.5, .5, .5, .5} crop_def.walkable = true crop_def.groups = {snappy = 1, oddly_breakable_by_hand = 1, flammable = 2, plant = 1} crop_def.drop = "farming:melon_slice 9" minetest.register_node("farming:melon_8", table.copy(crop_def))
local S = farming.intllib -- melon minetest.register_craftitem("farming:melon_slice", { description = S("Melon Slice"), inventory_image = "farming_melon_slice.png", on_place = function(itemstack, placer, pointed_thing) return farming.place_seed(itemstack, placer, pointed_thing, "farming:melon_1") end, on_use = minetest.item_eat(2), }) minetest.register_craft({ output = "farming:melon_8", recipe = { {"farming:melon_slice", "farming:melon_slice", "farming:melon_slice"}, {"farming:melon_slice", "farming:melon_slice", "farming:melon_slice"}, {"farming:melon_slice", "farming:melon_slice", "farming:melon_slice"}, } }) minetest.register_craft({ output = "farming:melon_slice 9", recipe = { {"", "farming:melon_8", ""}, } }) -- melon definition local crop_def = { drawtype = "plantlike", tiles = {"farming_melon_1.png"}, paramtype = "light", sunlight_propagates = true, walkable = false, buildable_to = true, drop = "", selection_box = farming.select, groups = { snappy = 3, flammable = 2, plant = 1, attached_node = 1, not_in_creative_inventory = 1, growing = 1 }, sounds = default.node_sound_leaves_defaults() } -- stage 1 minetest.register_node("farming:melon_1", table.copy(crop_def)) -- stage 2 crop_def.tiles = {"farming_melon_2.png"} minetest.register_node("farming:melon_2", table.copy(crop_def)) -- stage 3 crop_def.tiles = {"farming_melon_3.png"} minetest.register_node("farming:melon_3", table.copy(crop_def)) -- stage 4 crop_def.tiles = {"farming_melon_4.png"} minetest.register_node("farming:melon_4", table.copy(crop_def)) -- stage 5 crop_def.tiles = {"farming_melon_5.png"} minetest.register_node("farming:melon_5", table.copy(crop_def)) -- stage 6 crop_def.tiles = {"farming_melon_6.png"} minetest.register_node("farming:melon_6", table.copy(crop_def)) -- stage 7 crop_def.tiles = {"farming_melon_7.png"} minetest.register_node("farming:melon_7", table.copy(crop_def)) -- stage 8 (final) crop_def.drawtype = "nodebox" crop_def.description = S("Melon") crop_def.tiles = {"farming_melon_top.png", "farming_melon_top.png", "farming_melon_side.png", "farming_melon_side.png", "farming_melon_side.png", "farming_melon_side.png"} crop_def.selection_box = {-.5, -.5, -.5, .5, .5, .5} crop_def.walkable = true crop_def.groups = {snappy = 1, oddly_breakable_by_hand = 1, flammable = 2, plant = 1} crop_def.drop = "farming:melon_slice 9" minetest.register_node("farming:melon_8", table.copy(crop_def))
fix melon textures
fix melon textures
Lua
lgpl-2.1
maikerumine/grieftest
36380b29167900162880718b54682f65549242be
aspects/vim/files/.vim/lua/wincent/init.lua
aspects/vim/files/.vim/lua/wincent/init.lua
local wincent = {} -- +0,+1,+2, ... +254 local focused_colorcolumn = '+' .. table.concat({ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100', '101', '102', '103', '104', '105', '106', '107', '108', '109', '110', '111', '112', '113', '114', '115', '116', '117', '118', '119', '120', '121', '122', '123', '124', '125', '126', '127', '128', '129', '130', '131', '132', '133', '134', '135', '136', '137', '138', '139', '140', '141', '142', '143', '144', '145', '146', '147', '148', '149', '150', '151', '152', '153', '154', '155', '156', '157', '158', '159', '160', '161', '162', '163', '164', '165', '166', '167', '168', '169', '170', '171', '172', '173', '174', '175', '176', '177', '178', '179', '180', '181', '182', '183', '184', '185', '186', '187', '188', '189', '190', '191', '192', '193', '194', '195', '196', '197', '198', '199', '200', '201', '202', '203', '204', '205', '206', '207', '208', '209', '210', '211', '212', '213', '214', '215', '216', '217', '218', '219', '220', '221', '222', '223', '224', '225', '226', '227', '228', '229', '230', '231', '232', '233', '234', '235', '236', '237', '238', '239', '240', '241', '242', '243', '244', '245', '246', '247', '248', '249', '250', '251', '252', '253', '254' }, ',+') local winhighlight_blurred = table.concat({ 'CursorLineNr:LineNr', 'EndOfBuffer:ColorColumn', 'IncSearch:ColorColumn', 'Normal:ColorColumn', 'NormalNC:ColorColumn', 'SignColumn:ColorColumn' }, ',') local with_spell_settings = function(callback) local spell = vim.api.nvim_win_get_option(0, 'spell') local spellcapcheck = vim.api.nvim_buf_get_option(0, 'spellcapcheck') local spellfile = vim.api.nvim_buf_get_option(0, 'spellfile') local spelllang = vim.api.nvim_buf_get_option(0, 'spelllang') callback() vim.api.nvim_win_set_option(0, 'spell', spell) vim.api.nvim_buf_set_option(0, 'spellcapcheck', spellcapcheck) vim.api.nvim_buf_set_option(0, 'spellfile', spellfile) vim.api.nvim_buf_set_option(0, 'spelllang', spelllang) end local when_supports_blur_and_focus = function(callback) local filetype = vim.api.nvim_buf_get_option(0, 'filetype') local listed = vim.api.nvim_buf_get_option(0, 'buflisted') if wincent.colorcolumn_filetype_blacklist[filetype] ~= true and listed then callback() end end local focus_window = function() vim.api.nvim_win_set_option(0, 'winhighlight', '') when_supports_blur_and_focus(function() vim.api.nvim_win_set_option(0, 'colorcolumn', focused_colorcolumn) if filetype ~= '' then with_spell_settings(function () vim.cmd('ownsyntax on') vim.api.nvim_win_set_option(0, 'list', true) vim.api.nvim_win_set_option(0, 'conceallevel', 1) end) end end) end local blur_window = function() vim.api.nvim_win_set_option(0, 'winhighlight', winhighlight_blurred) when_supports_blur_and_focus(function() with_spell_settings(function() vim.cmd('ownsyntax off') vim.api.nvim_win_set_option(0, 'list', false) vim.api.nvim_win_set_option(0, 'conceallevel', 0) end) end) end local set_cursorline = function(active) local filetype = vim.api.nvim_buf_get_option(0, 'filetype') if wincent.cursorline_blacklist[filetype] ~= true then vim.api.nvim_win_set_option(0, 'cursorline', active) end end -- TODO: maybe move this into an autocmds.lua file, or possibly even more granular than that wincent.buf_enter = function() focus_window() end wincent.focus_gained = function() focus_window() end wincent.focus_lost = function() blur_window() end wincent.insert_enter = function() set_cursorline(false) end wincent.insert_leave = function() set_cursorline(true) end wincent.vim_enter = function() set_cursorline(true) focus_window() end wincent.win_enter = function() set_cursorline(true) focus_window() end wincent.win_leave = function() set_cursorline(false) blur_window() end wincent.colorcolumn_filetype_blacklist = { ['command-t'] = true, ['diff'] = true, ['dirvish'] = true, ['fugitiveblame']= true, ['undotree'] = true, ['qf'] = true, } wincent.cursorline_blacklist = { ['command-t'] = true, } return wincent
local wincent = {} -- +0,+1,+2, ... +254 local focused_colorcolumn = '+' .. table.concat({ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '100', '101', '102', '103', '104', '105', '106', '107', '108', '109', '110', '111', '112', '113', '114', '115', '116', '117', '118', '119', '120', '121', '122', '123', '124', '125', '126', '127', '128', '129', '130', '131', '132', '133', '134', '135', '136', '137', '138', '139', '140', '141', '142', '143', '144', '145', '146', '147', '148', '149', '150', '151', '152', '153', '154', '155', '156', '157', '158', '159', '160', '161', '162', '163', '164', '165', '166', '167', '168', '169', '170', '171', '172', '173', '174', '175', '176', '177', '178', '179', '180', '181', '182', '183', '184', '185', '186', '187', '188', '189', '190', '191', '192', '193', '194', '195', '196', '197', '198', '199', '200', '201', '202', '203', '204', '205', '206', '207', '208', '209', '210', '211', '212', '213', '214', '215', '216', '217', '218', '219', '220', '221', '222', '223', '224', '225', '226', '227', '228', '229', '230', '231', '232', '233', '234', '235', '236', '237', '238', '239', '240', '241', '242', '243', '244', '245', '246', '247', '248', '249', '250', '251', '252', '253', '254' }, ',+') local winhighlight_blurred = table.concat({ 'CursorLineNr:LineNr', 'EndOfBuffer:ColorColumn', 'IncSearch:ColorColumn', 'Normal:ColorColumn', 'NormalNC:ColorColumn', 'SignColumn:ColorColumn' }, ',') -- "Safe" version of `nvim_win_get_var()` that returns `nil` if the -- variable is not set. local win_get_var = function(handle, name) local result pcall(function () result = vim.api.nvim_win_get_var(handle, name) end) return result end -- As described in a7e4d8b8383a375d124, `ownsyntax` resets spelling -- settings, so we capture and restore them. Note that there is some trickiness -- here because multiple autocmds can trigger "focus" or "blur" operations; this -- means that we can't just naively save and restore: we have to use a flag to -- make sure that we only capture the initial state. local ownsyntax = function(active) if active and win_get_var(0, 'ownsyntax') == false then -- We are focussing; restore previous settings. vim.cmd('ownsyntax on') vim.api.nvim_win_set_option(0, 'spell', win_get_var(0, 'spell') or false) vim.api.nvim_buf_set_option(0, 'spellcapcheck', win_get_var(0, 'spellcapcheck') or '') vim.api.nvim_buf_set_option(0, 'spellfile', win_get_var(0, 'spellfile') or '') vim.api.nvim_buf_set_option(0, 'spelllang', win_get_var(0, 'spelllang') or 'en') -- Set flag to show that we have restored the captured options. vim.api.nvim_win_set_var(0, 'ownsyntax', true) elseif not active and win_get_var(0, 'ownsyntax') ~= false then -- We are blurring; save settings for later restoration. vim.api.nvim_win_set_var(0, 'spell', vim.api.nvim_win_get_option(0, 'spell')) vim.api.nvim_win_set_var(0, 'spellcapcheck', vim.api.nvim_buf_get_option(0, 'spellcapcheck')) vim.api.nvim_win_set_var(0, 'spellfile', vim.api.nvim_buf_get_option(0, 'spellfile')) vim.api.nvim_win_set_var(0, 'spelllang', vim.api.nvim_buf_get_option(0, 'spelllang')) vim.cmd('ownsyntax off') -- Suppress spelling in blurred buffer. vim.api.nvim_win_set_option(0, 'spell', false) -- Set flag to show that we have captured options. vim.api.nvim_win_set_var(0, 'ownsyntax', false) end return spell end local when_supports_blur_and_focus = function(callback) local filetype = vim.api.nvim_buf_get_option(0, 'filetype') local listed = vim.api.nvim_buf_get_option(0, 'buflisted') if wincent.colorcolumn_filetype_blacklist[filetype] ~= true and listed then callback() end end local focus_window = function() vim.api.nvim_win_set_option(0, 'winhighlight', '') when_supports_blur_and_focus(function() vim.api.nvim_win_set_option(0, 'colorcolumn', focused_colorcolumn) if filetype ~= '' then ownsyntax(true) vim.api.nvim_win_set_option(0, 'list', true) vim.api.nvim_win_set_option(0, 'conceallevel', 1) end end) end local blur_window = function() vim.api.nvim_win_set_option(0, 'winhighlight', winhighlight_blurred) when_supports_blur_and_focus(function() ownsyntax(false) vim.api.nvim_win_set_option(0, 'list', false) vim.api.nvim_win_set_option(0, 'conceallevel', 0) end) end local set_cursorline = function(active) local filetype = vim.api.nvim_buf_get_option(0, 'filetype') if wincent.cursorline_blacklist[filetype] ~= true then vim.api.nvim_win_set_option(0, 'cursorline', active) end end -- TODO: maybe move this into an autocmds.lua file, or possibly even more granular than that wincent.buf_enter = function() focus_window() end wincent.focus_gained = function() focus_window() end wincent.focus_lost = function() blur_window() end wincent.insert_enter = function() set_cursorline(false) end wincent.insert_leave = function() set_cursorline(true) end wincent.vim_enter = function() set_cursorline(true) focus_window() end wincent.win_enter = function() set_cursorline(true) focus_window() end wincent.win_leave = function() set_cursorline(false) blur_window() end wincent.colorcolumn_filetype_blacklist = { ['command-t'] = true, ['diff'] = true, ['dirvish'] = true, ['fugitiveblame']= true, ['undotree'] = true, ['qf'] = true, } wincent.cursorline_blacklist = { ['command-t'] = true, } return wincent
fix(vim): make sure spell settings are correctly saved/restored
fix(vim): make sure spell settings are correctly saved/restored I couldn't remember what all this stuff was for when I was porting from Vimscript to Lua in 0cc3b34b, but I noticed that spelling mistakes were being highlighted in blurred Markdown windows. So, I did a bit of digging and I am not sure this was working before. As it says in a7e4d8b8383a375d124, calling `:ownsyntax` resets the spelling settings. You could see the old code saving and restoring the settings after the `:ownsyntax` invocations, but nowhere do I see it setting `'nospell'` on blurred windows and `'spell'` (if applicable) on focussed windows. It's all made more complicated by the fact that we register multiple autocmds that end up going through the same path eg. `VimEnter`, `WinEnter`, `BufEnter` and `FocusGained` all call `focus_window()`, and both `FocusLost` and `WinLeave` call `blur_window()`. So when you start up Vim, you are going to hit sometimes multiple of those in a row. So, that's why we have all the delicate state management in there: if we are blurring, we take a snapshot of the settings, but only once; and if we are focussing, we do the opposite, and restore the settings, but only once. The tricky bits are the `== false` and `~= false` comparisons in `ownsyntax()`: - At startup our flag is going to be `nil`. - If focusing and we have a settings snapshot (ie. flag `== false`), we restore. Set flag to `true` to avoid doing this again if we get called again. - If blurring (ie. flag `~= false`), save. Set flag to `false` to avoid doing this again if we get called.
Lua
unlicense
wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent,wincent/wincent
177b1cbc8127d0916f8c847ca4a8dfe515aaa43d
plugins/mod_roster.lua
plugins/mod_roster.lua
local st = require "util.stanza" local send = require "core.sessionmanager".send_to_session add_iq_handler("c2s", "jabber:iq:roster", function (session, stanza) if stanza.attr.type == "get" then local roster = st.reply(stanza) :query("jabber:iq:roster"); for jid in pairs(session.roster) do roster:tag("item", { jid = jid, subscription = "none" }):up(); end send(session, roster); return true; end end);
local st = require "util.stanza" local send = require "core.sessionmanager".send_to_session add_iq_handler("c2s", "jabber:iq:roster", function (session, stanza) if stanza.attr.type == "get" then local roster = st.reply(stanza) :query("jabber:iq:roster"); for jid in pairs(session.roster) do local item = st.stanza("item", { jid = jid, subscription = session.roster[jid].subscription, name = session.roster[jid].name, }); for group in pairs(session.roster[jid].groups) do item:tag("group"):text(group):up(); end roster:add_child(item); end send(session, roster); return true; end end);
Fixed: mod_roster now outputs all roster data (instead of just the JIDs)
Fixed: mod_roster now outputs all roster data (instead of just the JIDs)
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
64a7a23d9df6133e0f17a40de5f0d6cc79774fba
lua/encoders/signalfx.lua
lua/encoders/signalfx.lua
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. --[=[ Extracts data from message fields in messages. Generates JSON suitable for send to datapoint SignalFx API. (Currently only supports writing data points, NOT events.) Config: - metric_name (string, required) String to use as the `metric` name in SignalFX. Supports interpolation of field values from the processed message, using `%{fieldname}`. Any `fieldname` values of "Type", "Payload", "Hostname", "Pid", "Logger", "Severity", or "EnvVersion" will be extracted from the the base message schema, any other values will be assumed to refer to a dynamic message field. Only the first value of the first instance of a dynamic message field can be used for series name interpolation. If the dynamic field doesn't exist, the uninterpolated value will be left in the series name. Note that it is not possible to interpolate either the "Timestamp" or the "Uuid" message fields into the series name, those values will be interpreted as referring to dynamic message fields. - value_field (string, optional, defaults to "value") The `fieldname` to use as the value for the metric in signalfx. If the `value` field is not present this encoder will set one as the value for counters: `1`. A value of `0` will be used for `gauges`. - stat_type (string, optional, defaults to "counter") A metric can be of type "counter" or "gauge". *Example Heka Configuration* .. code-block:: ini [signalfx-encoder] type = "SandboxEncoder" filename = "lua_encoders/signalfx.lua" [signalfx-encoder.config] metric_name = "test-metric.%{title}.%{Hostname}" value_field = "metric_value" stat_type = "gauge" [signalfx] type = "HttpOutput" message_matcher = "Type == 'json'" address = "https://ingest.signalfx.com/v2/datapoint" encoder = "signalfx-encoder" [signalfx.headers] content-type = ["application/json"] X-SF-Token = "<YOUR-SIGNALFX-API-TOKEN>" --]=] require "cjson" require "string" require "table" local metric_name = read_config("metric_name") local value_field = read_config("value_field") or "value" local use_subs if string.find(metric_name, "%%{[%w%p]-}") then use_subs = true end local base_fields_map = { Type = true, Payload = true, Hostname = true, Pid = true, Logger = true, Severity = true, EnvVersion = true } -- Used for interpolating message fields into series name. local function sub_func(key) if base_fields_map[key] then return read_message(key) else local val = read_message("Fields["..key.."]") if val then return val end return "%{"..key.."}" end end function process_message() local ts = read_message("Timestamp") / 1e9 if not ts then return -1 end local value = read_message("Fields["..value_field.."]") -- assume stat_type is a counter unless gauge is specified local stat_type = read_message("Fields[type]") if stat_type == "gauge" then if not value then return -1 end else stat_type = "counter" if not value then value = 1 end -- default counter to 1 end -- only process name if everything looks good local name = "" if use_subs then name = string.gsub(metric_name, "%%{([%w%p]-)}", sub_func) else name = metric_name end if not name or name == "" then return -1 end local output = { -- array of data points [stat_type] = { { metric=name, value=value, timestamp=ts, dimensions={ hostname=Hostname } } } } inject_payload("json", "signalfx", cjson.encode(output)) return 0 end
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. --[=[ Extracts data from message fields in messages. Generates JSON suitable for send to datapoint SignalFx API. (Currently only supports writing data points, NOT events.) Config: - metric_name (string, required) String to use as the `metric` name in SignalFX. Supports interpolation of field values from the processed message, using `%{fieldname}`. Any `fieldname` values of "Type", "Payload", "Hostname", "Pid", "Logger", "Severity", or "EnvVersion" will be extracted from the the base message schema, any other values will be assumed to refer to a dynamic message field. Only the first value of the first instance of a dynamic message field can be used for series name interpolation. If the dynamic field doesn't exist, the uninterpolated value will be left in the series name. Note that it is not possible to interpolate either the "Timestamp" or the "Uuid" message fields into the series name, those values will be interpreted as referring to dynamic message fields. - value_field (string, optional, defaults to "value") The `fieldname` to use as the value for the metric in signalfx. If the `value` field is not present this encoder will set one as the value for counters: `1`. A value of `0` will be used for `gauges`. - stat_type (string, optional, defaults to "counter") A metric can be of type "counter" or "gauge". *Example Heka Configuration* .. code-block:: ini [signalfx-encoder] type = "SandboxEncoder" filename = "lua_encoders/signalfx.lua" [signalfx-encoder.config] metric_name = "test-metric.%{title}.%{Hostname}" value_field = "metric_value" stat_type = "gauge" [signalfx] type = "HttpOutput" message_matcher = "Type == 'json'" address = "https://ingest.signalfx.com/v2/datapoint" encoder = "signalfx-encoder" [signalfx.headers] content-type = ["application/json"] X-SF-Token = "<YOUR-SIGNALFX-API-TOKEN>" --]=] require "cjson" require "string" require "table" local metric_name = read_config("metric_name") local value_field = read_config("value_field") or "value" local use_subs if string.find(metric_name, "%%{[%w%p]-}") then use_subs = true end local base_fields_map = { Type = true, Payload = true, Hostname = true, Pid = true, Logger = true, Severity = true, EnvVersion = true } -- Used for interpolating message fields into series name. local function sub_func(key) if base_fields_map[key] then return read_message(key) else local val = read_message("Fields["..key.."]") if val then return val end return "%{"..key.."}" end end function process_message() local ts = tonumber(read_message("Timestamp")) if not ts then return -1 end ts = ts / 1e6 -- Convert nanoseconds to milliseconds local value = read_message("Fields["..value_field.."]") -- assume stat_type is a counter unless gauge is specified local stat_type = read_message("Fields[type]") if stat_type == "gauge" then if not value then return -1 end else stat_type = "counter" if not value then value = 1 end -- default counter to 1 end -- only process name if everything looks good local name = "" if use_subs then name = string.gsub(metric_name, "%%{([%w%p]-)}", sub_func) else name = metric_name end if not name or name == "" then return -1 end local output = { -- array of data points [stat_type] = { { metric=name, value=value, timestamp=ts, dimensions={ hostname=Hostname } } } } inject_payload("json", "signalfx", cjson.encode(output)) return 0 end
signalfx encoder (bugfix): timestamp in milliseconds
signalfx encoder (bugfix): timestamp in milliseconds
Lua
apache-2.0
wxdublin/heka-clever-plugins
22e77171f0bbad871250d7d3ac40cf97b84c6c91
Nncache.lua
Nncache.lua
-- Nncache.lua -- nearest neighbors cache -- API overview if false then -- construction nnc = Nncache() -- setter and getter nnc:setLine(obsIndex, tensor1D) tensor1D = nnc:getLine(obsIndex) -- may return null -- apply a function to each key-value pair local function f(key,value) end nnc:apply(f) -- saving to a file and restoring from one -- the suffix is determined by the class Nncachebuilder nnc:save(filePath) nnc = nnc.load(filePath) nnc = nnc.loadUsingPrefix(filePathPrefix) end -------------------------------------------------------------------------------- -- CONSTRUCTION -------------------------------------------------------------------------------- torch.class('Nncache') function Nncache:__init() self._table = {} self._lastValuesSize = nil end -------------------------------------------------------------------------------- -- PUBLIC CLASS METHODS -------------------------------------------------------------------------------- function Nncache.load(filePath) -- return an nnc; error if there is no saved Nncache at the filePath local v, isVerbose = makeVerbose(false, 'Nncache.read') verify(v, isVerbose, {{filePath, 'filePath', 'isString'}}) local nnc = torch.load(filePath, Nncachebuilder.format()) v('nnc', nnc) v('typename', torch.typename(nnc)) assert(torch.typename(nnc) == 'Nncache', 'bad typename = ' .. tostring(torch.typename(nnc))) -- NOTE: cannot test if each table entry has 256 rows, because the -- original allXs may have had fewer than 256 observations return nnc end -- read function Nncache.loadUsingPrefix(filePathPrefix) return Nncache.load(Nncache._filePath(filePathPrefix)) end -- loadUsingPrefix -------------------------------------------------------------------------------- -- PRIVATE CLASS METHODS -------------------------------------------------------------------------------- function Nncache._filePath(filePathPrefix) return filePathPrefix .. Nncachebuilder.mergedFileSuffix() end -- _filePath -------------------------------------------------------------------------------- -- PUBLIC INSTANCE METHODS -------------------------------------------------------------------------------- function Nncache:apply(f) -- apply a function to each key-value pair for key, value in pairs(self._table) do f(key, value) end end -- apply function Nncache:getLine(obsIndex) -- return line at key or null local v, isVerbose = makeVerbose(false, 'Nncache:getline') verify(v, isVerbose, {{obsIndex, 'obsIndex', 'isIntegerPositive'}}) return self._table[obsIndex] end -- getline function Nncache:setLine(obsIndex, values) -- set the line, checking that it is not already set local v, isVerbose = makeVerbose(false, 'Nncache:setLine') verify(v, isVerbose, {{obsIndex, 'obsIndex', 'isIntegerPositive'}, {values, 'values', 'isTensor1D'}}) v('self', self) -- check that size of values is same on every call if self._lastValuesSize then local newSize = values:size(1) assert(self._lastValuesSize == newSize, string.format('cannot change size of values; \n was %s; \n is %s', tostring(self._lastValuesSize), tostring(newSize))) self._lastValuesSize = newSize else self._lastValuesSize = values:size(1) end -- check that the obsIndex slot has not already been filled assert(self._table[obsIndex] == nil, string.format('attempt to set cache line already filled; \nobsIndex ', tostring(obsIndex))) self._table[obsIndex] = values end -- setLine function Nncache:save(filePath) -- write to disk by serializing -- NOTE: if the name of this method were 'write', then the call below -- to torch.save would call this function recursively. Hence the name -- of this function. local v, isVerbose = makeVerbose(false, 'Nncache:write') v('self', self) verify(v, isVerbose, {{filePath, 'filePath', 'isString'}}) v('filePath', filePath) v('Nncachebuilder.format()', Nncachebuilder.format()) torch.save(filePath, self, Nncachebuilder.format()) end -- write
-- Nncache.lua -- nearest neighbors cache -- API overview if false then -- construction nnc = Nncache() -- setter and getter nnc:setLine(obsIndex, tensor1D) tensor1D = nnc:getLine(obsIndex) -- may return null -- apply a function to each key-value pair local function f(key,value) end nnc:apply(f) -- saving to a file and restoring from one -- the suffix is determined by the class Nncachebuilder nnc:save(filePath) nnc = nnc.load(filePath) nnc = nnc.loadUsingPrefix(filePathPrefix) end -------------------------------------------------------------------------------- -- CONSTRUCTION -------------------------------------------------------------------------------- torch.class('Nncache') function Nncache:__init() self._table = {} self._lastValuesSize = nil end -------------------------------------------------------------------------------- -- PUBLIC CLASS METHODS -------------------------------------------------------------------------------- function Nncache.load(filePath) -- return an nnc; error if there is no saved Nncache at the filePath local v, isVerbose = makeVerbose(true, 'Nncache.load') verify(v, isVerbose, {{filePath, 'filePath', 'isString'}}) local nnc = torch.load(filePath, Nncachebuilder.format()) --v('nnc', nnc) v('nnc:size()', nnc:size()) v('typename', torch.typename(nnc)) assert(torch.typename(nnc) == 'Nncache', 'bad typename = ' .. tostring(torch.typename(nnc))) -- NOTE: cannot test if each table entry has 256 rows, because the -- original allXs may have had fewer than 256 observations return nnc end -- read function Nncache.loadUsingPrefix(filePathPrefix) return Nncache.load(Nncache._filePath(filePathPrefix)) end -- loadUsingPrefix -------------------------------------------------------------------------------- -- PRIVATE CLASS METHODS -------------------------------------------------------------------------------- function Nncache._filePath(filePathPrefix) return filePathPrefix .. Nncachebuilder.mergedFileSuffix() end -- _filePath -------------------------------------------------------------------------------- -- PUBLIC INSTANCE METHODS -------------------------------------------------------------------------------- function Nncache:apply(f) -- apply a function to each key-value pair for key, value in pairs(self._table) do f(key, value) end end -- apply function Nncache:getLine(obsIndex) -- return line at key or null local v, isVerbose = makeVerbose(false, 'Nncache:getline') verify(v, isVerbose, {{obsIndex, 'obsIndex', 'isIntegerPositive'}}) return self._table[obsIndex] end -- getline function Nncache:setLine(obsIndex, values) -- set the line, checking that it is not already set local v, isVerbose = makeVerbose(false, 'Nncache:setLine') verify(v, isVerbose, {{obsIndex, 'obsIndex', 'isIntegerPositive'}, {values, 'values', 'isTensor1D'}}) v('self', self) -- check that size of values is same on every call if self._lastValuesSize then local newSize = values:size(1) assert(self._lastValuesSize == newSize, string.format('cannot change size of values; \n was %s; \n is %s', tostring(self._lastValuesSize), tostring(newSize))) self._lastValuesSize = newSize else self._lastValuesSize = values:size(1) end -- check that the obsIndex slot has not already been filled assert(self._table[obsIndex] == nil, string.format('attempt to set cache line already filled; \nobsIndex ', tostring(obsIndex))) self._table[obsIndex] = values end -- setLine function Nncache:save(filePath) -- write to disk by serializing -- NOTE: if the name of this method were 'write', then the call below -- to torch.save would call this function recursively. Hence the name -- of this function. local v, isVerbose = makeVerbose(false, 'Nncache:write') v('self', self) verify(v, isVerbose, {{filePath, 'filePath', 'isString'}}) v('filePath', filePath) v('Nncachebuilder.format()', Nncachebuilder.format()) torch.save(filePath, self, Nncachebuilder.format()) end -- write
Fix verbose code
Fix verbose code
Lua
bsd-3-clause
rlowrance/kernel-smoothers
283f486676eb62394dd060b13e277f83c77fa2f9
deps/coro-wrapper.lua
deps/coro-wrapper.lua
--[[lit-meta name = "creationix/coro-wrapper" version = "3.0.1" homepage = "https://github.com/luvit/lit/blob/master/deps/coro-wrapper.lua" description = "An adapter for applying decoders to coro-streams." tags = {"coro", "decoder", "adapter"} license = "MIT" author = { name = "Tim Caswell" } ]] local concat = table.concat local sub = string.sub -- Merger allows for effecient merging of many chunks. -- The scan function returns truthy when the chunk contains a useful delimeter -- Or in other words, when there is enough data to flush to the decoder. -- merger(read, scan) -> read, updateScan -- read() -> chunk or nil -- scan(chunk) -> should_flush -- updateScan(scan) local function merger(read, scan) local parts = {} -- Return a new read function that combines chunks smartly return function () while true do -- Read the next event from upstream. local chunk = read() -- We got an EOS (end of stream) if not chunk then -- If there is nothing left to flush, emit EOS here. if #parts == 0 then return end -- Flush the buffer chunk = concat(parts) parts = {} return chunk end -- Accumulate the chunk parts[#parts + 1] = chunk -- Flush the buffer if scan tells us to. if scan(chunk) then chunk = concat(parts) parts = {} return chunk end end end, -- This is used to update or disable the scan function. It's useful for -- protocols that change mid-stream (like HTTP upgrades in websockets) function (newScan) scan = newScan end end -- Decoder takes in a read function and a decode function and returns a new -- read function that emits decoded events. When decode returns `nil` it means -- that it needs more data before it can parse. The index output in decode is -- the index to start the next decode. If output index if nil it means nothing -- is leftover and next decode starts fresh. -- decoder(read, decode) -> read, updateDecode -- read() -> chunk or nil -- decode(chunk, index) -> nil or (data, index) -- updateDecode(Decode) local function decoder(read, decode) local buffer, index local want = true return function () while true do -- If there isn't enough data to decode then get more data. if want then local chunk = read() if buffer then -- If we had leftover data in the old buffer, trim it down. if index > 1 then buffer = sub(buffer, index) index = 1 end if chunk then -- Concatenate the chunk with the old data buffer = buffer .. chunk end else -- If there was no leftover data, set new data in the buffer if chunk then buffer = chunk index = 1 else buffer = nil index = nil end end end -- If we have data, lets try to decode it local item, newIndex = decode(buffer, index) want = not newIndex if item or newIndex then -- There was enough data to emit an event! if newIndex then assert(type(newIndex) == "number", "index must be a number if set") -- There was leftover data index = newIndex else want = true -- There was no leftover data buffer = nil index = nil end -- Emit the event return item end end end, function (newDecode) decode = newDecode end end local function encoder(write, encode) return function (item) if not item then return write() end return write(encode(item)) end, function (newEncode) encode = newEncode end end return { merger = merger, decoder = decoder, encoder = encoder, }
--[[lit-meta name = "creationix/coro-wrapper" version = "3.0.1" homepage = "https://github.com/luvit/lit/blob/master/deps/coro-wrapper.lua" description = "An adapter for applying decoders to coro-streams." tags = {"coro", "decoder", "adapter"} license = "MIT" author = { name = "Tim Caswell" } ]] local concat = table.concat local sub = string.sub -- Merger allows for effecient merging of many chunks. -- The scan function returns truthy when the chunk contains a useful delimeter -- Or in other words, when there is enough data to flush to the decoder. -- merger(read, scan) -> read, updateScan -- read() -> chunk or nil -- scan(chunk) -> should_flush -- updateScan(scan) local function merger(read, scan) local parts = {} -- Return a new read function that combines chunks smartly return function () while true do -- Read the next event from upstream. local chunk = read() -- We got an EOS (end of stream) if not chunk then -- If there is nothing left to flush, emit EOS here. if #parts == 0 then return end -- Flush the buffer chunk = concat(parts) parts = {} return chunk end -- Accumulate the chunk parts[#parts + 1] = chunk -- Flush the buffer if scan tells us to. if scan(chunk) then chunk = concat(parts) parts = {} return chunk end end end, -- This is used to update or disable the scan function. It's useful for -- protocols that change mid-stream (like HTTP upgrades in websockets) function (newScan) scan = newScan end end -- Decoder takes in a read function and a decode function and returns a new -- read function that emits decoded events. When decode returns `nil` it means -- that it needs more data before it can parse. The index output in decode is -- the index to start the next decode. If output index if nil it means nothing -- is leftover and next decode starts fresh. -- decoder(read, decode) -> read, updateDecode -- read() -> chunk or nil -- decode(chunk, index) -> nil or (data, index) -- updateDecode(Decode) local function decoder(read, decode) local buffer, index local want = true return function () while true do -- If there isn't enough data to decode then get more data. if want then local chunk = read() if buffer then -- If we had leftover data in the old buffer, trim it down. if index > 1 then buffer = sub(buffer, index) index = 1 end if chunk then -- Concatenate the chunk with the old data buffer = buffer .. chunk end else -- If there was no leftover data, set new data in the buffer if chunk then buffer = chunk index = 1 else buffer = nil index = nil end end end -- Return nil if the buffer is empty if buffer == '' or buffer == nil then return nil end -- If we have data, lets try to decode it local item, newIndex = decode(buffer, index) want = not newIndex if item or newIndex then -- There was enough data to emit an event! if newIndex then assert(type(newIndex) == "number", "index must be a number if set") -- There was leftover data index = newIndex else want = true -- There was no leftover data buffer = nil index = nil end -- Emit the event return item end end end, function (newDecode) decode = newDecode end end local function encoder(write, encode) return function (item) if not item then return write() end return write(encode(item)) end, function (newEncode) encode = newEncode end end return { merger = merger, decoder = decoder, encoder = encoder, }
Fixed infinite loop in coro-wrapper decoder - If the buffer is empty, nil is returned to signal the end of the loop
Fixed infinite loop in coro-wrapper decoder - If the buffer is empty, nil is returned to signal the end of the loop
Lua
apache-2.0
luvit/lit,zhaozg/lit
cb8a7c5094f37d94638974b67dc92256aaef70c5
plugins/webshot.lua
plugins/webshot.lua
local helpers = require "OAuth.helpers" local base = 'https://screenshotmachine.com/' local url = base .. 'processor.php' local function get_webshot_url(param, psize) local response_body = { } local request_constructor = { url = url, method = "GET", sink = ltn12.sink.table(response_body), headers = { referer = base, dnt = "1", origin = base, ["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36" }, redirect = false } local arguments = { urlparam = param, size = psize } request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments) local ok, response_code, response_headers, response_status_line = https.request(request_constructor) if not ok or response_code ~= 200 then return nil end local response = table.concat(response_body) return string.match(response, "href='(.-)'") end local function run(msg, matches) if is_momod(msg) then local size = 'X' if matches[2] then if (matches[2] == 'Fmob' or matches[2] == 'F') and is_admin1(msg) then size = matches[2] else size = matches[2] end end local find = get_webshot_url(matches[1], size) if find then local imgurl = base .. find local receiver = get_receiver(msg) send_photo_from_url(receiver, imgurl) end else return lang_text('require_mod') end end return { description = "WEBSHOT", usage = { "MOD", "[#]|[sasha] webshot <url> [<size>]: Sasha fa uno screenshot del sito e lo manda, se <size> specificato lo manda con quella dimensione altrimenti con dimensione X.", "La dimensione pu essere:", "'T': (120 x 90px) - molto grande", "'S': (200 x 150px) - piccola", "'E': (320 x 240px) - seminormale", "'N': (400 x 300px) - normale", "'M': (640 x 480px) - media", "'L': (800 x 600px) - grande", "'X': (1024 x 768px) - molto grande", "'Nmob': (480 x 800px) - normale", "ADMIN", "'F': Pagina intera (pu essere un processo molto lungo)", "'Fmob': Pagina intera (pu essere un processo lungo)", }, patterns = { "^[#!/][Ww][Ee][Bb][Ss][Hh][Oo][Tt] ([Hh][Tt][Tt][Pp][Ss]?://[%w-_%.%?%.:/%+=&]+) (.*)$", "^[#!/][Ww][Ee][Bb][Ss][Hh][Oo][Tt] ([Hh][Tt][Tt][Pp][Ss]?://[%w-_%.%?%.:/%+=&]+)$", "^[#!/][Ww][Ee][Bb][Ss][Hh][Oo][Tt] ([%w-_%.%?%.:/%+=&]+) (.*)$", "^[#!/][Ww][Ee][Bb][Ss][Hh][Oo][Tt] ([%w-_%.%?%.:/%+=&]+)$", -- webshot "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt][Tt][Aa] ([Hh][Tt][Tt][Pp][Ss]?://[%w-_%.%?%.:/%+=&]+) (.*)$", "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt][Tt][Aa] ([Hh][Tt][Tt][Pp][Ss]?://[%w-_%.%?%.:/%+=&]+)$", "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt][Tt][Aa] ([%w-_%.%?%.:/%+=&]+) (.*)$", "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt][Tt][Aa] ([%w-_%.%?%.:/%+=&]+)$", "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt] ([Hh][Tt][Tt][Pp][Ss]?://[%w-_%.%?%.:/%+=&]+) (.*)$", "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt] ([Hh][Tt][Tt][Pp][Ss]?://[%w-_%.%?%.:/%+=&]+)$", "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt] ([%w-_%.%?%.:/%+=&]+) (.*)$", "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt] ([%w-_%.%?%.:/%+=&]+)$", }, run = run, min_rank = 1 }
local helpers = require "OAuth.helpers" local base = 'https://screenshotmachine.com/' local url = base .. 'processor.php' local function get_webshot_url(param, psize) local response_body = { } local request_constructor = { url = url, method = "GET", sink = ltn12.sink.table(response_body), headers = { referer = base, dnt = "1", origin = base, ["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36" }, redirect = false } local arguments = { urlparam = param, size = psize } request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments) local ok, response_code, response_headers, response_status_line = https.request(request_constructor) if not ok or response_code ~= 200 then return nil end local response = table.concat(response_body) return string.match(response, "href='(.-)'") end local function run(msg, matches) if is_momod(msg) then local size = 'X' if matches[2] then if matches[2] == 'Fmob' or matches[2] == 'F' then if is_admin1(msg) then size = matches[2] else return lang_text('require_admin') end else size = matches[2] end end local find = get_webshot_url(matches[1], size) if find then local imgurl = base .. find local receiver = get_receiver(msg) send_photo_from_url(receiver, imgurl) end else return lang_text('require_mod') end end return { description = "WEBSHOT", usage = { "MOD", "[#]|[sasha] webshot <url> [<size>]: Sasha fa uno screenshot del sito e lo manda, se <size> specificato lo manda con quella dimensione altrimenti con dimensione X.", "La dimensione pu essere:", "'T': (120 x 90px) - molto grande", "'S': (200 x 150px) - piccola", "'E': (320 x 240px) - seminormale", "'N': (400 x 300px) - normale", "'M': (640 x 480px) - media", "'L': (800 x 600px) - grande", "'X': (1024 x 768px) - molto grande", "'Nmob': (480 x 800px) - normale", "ADMIN", "'F': Pagina intera (pu essere un processo molto lungo)", "'Fmob': Pagina intera (pu essere un processo lungo)", }, patterns = { "^[#!/][Ww][Ee][Bb][Ss][Hh][Oo][Tt] ([Hh][Tt][Tt][Pp][Ss]?://[%w-_%.%?%.:/%+=&]+) (.*)$", "^[#!/][Ww][Ee][Bb][Ss][Hh][Oo][Tt] ([Hh][Tt][Tt][Pp][Ss]?://[%w-_%.%?%.:/%+=&]+)$", "^[#!/][Ww][Ee][Bb][Ss][Hh][Oo][Tt] ([%w-_%.%?%.:/%+=&]+) (.*)$", "^[#!/][Ww][Ee][Bb][Ss][Hh][Oo][Tt] ([%w-_%.%?%.:/%+=&]+)$", -- webshot "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt][Tt][Aa] ([Hh][Tt][Tt][Pp][Ss]?://[%w-_%.%?%.:/%+=&]+) (.*)$", "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt][Tt][Aa] ([Hh][Tt][Tt][Pp][Ss]?://[%w-_%.%?%.:/%+=&]+)$", "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt][Tt][Aa] ([%w-_%.%?%.:/%+=&]+) (.*)$", "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt][Tt][Aa] ([%w-_%.%?%.:/%+=&]+)$", "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt] ([Hh][Tt][Tt][Pp][Ss]?://[%w-_%.%?%.:/%+=&]+) (.*)$", "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt] ([Hh][Tt][Tt][Pp][Ss]?://[%w-_%.%?%.:/%+=&]+)$", "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt] ([%w-_%.%?%.:/%+=&]+) (.*)$", "^[Ss][Aa][Ss][Hh][Aa] [Ww][Ee][Bb][Ss][Hh][Oo][Tt] ([%w-_%.%?%.:/%+=&]+)$", }, run = run, min_rank = 1 }
fix full page
fix full page
Lua
agpl-3.0
xsolinsx/AISasha
3f090656ff810a7c87c334978f49790e109846aa
src_trunk/resources/phone-system/c_phone_system.lua
src_trunk/resources/phone-system/c_phone_system.lua
local wPhoneMenu, gRingtones, ePhoneNumber, bCall, bOK, bCancel local sx, sy = guiGetScreenSize() local p_Sound = {} local stopTimer = {} function showPhoneGui(itemValue) wPhoneMenu = guiCreateWindow(sx/2 - 125,sy/2 - 175,250,310,"Phone Menu",false) bCall = guiCreateButton(0.0424,0.0831,0.2966,0.0855,"Call",true,wPhoneMenu) ePhoneNumber = guiCreateEdit(0.3559,0.0831,0.5975,0.0855,"",true,wPhoneMenu) gRingtones = guiCreateGridList(0.0381,0.1977,0.9153,0.6706,true,wPhoneMenu) guiGridListAddColumn(gRingtones,"ringtones",0.85) for i, filename in ipairs(ringtones) do guiGridListSetItemText(gRingtones, guiGridListAddRow(gRingtones), 1, filename:sub(1,-5), false, false) end guiGridListSetSelectedItem(gRingtones, itemValue - 1, 1) bOK = guiCreateButton(0.0381,0.8821,0.4492,0.0742,"OK",true,wPhoneMenu) bCancel = guiCreateButton(0.5212,0.8821,0.4322,0.0742,"Cancel",true,wPhoneMenu) addEventHandler("onClientGUIClick", getRootElement(), onGuiClick) showCursor(true) end addEvent("showPhoneGUI", true) addEventHandler("showPhoneGUI", getRootElement(), showPhoneGui) function onGuiClick(button) if button == "left" then if p_Sound["playing"] then stopSound(p_Sound["playing"]) end if source == bCall then local phoneNumber = guiGetText(wPhoneMenu) triggerServerEvent("remoteCall", getLocalPlayer(), getLocalPlayer(), "call", phoneNumber) hidePhoneGUI() elseif source == gRingtones then if guiGridListGetSelectedItem(gRingtones) ~= -1 then local filename = guiGridListGetItemText(gRingtones, guiGridListGetSelectedItem(gRingtones), 1) p_Sound["playing"] = playSound(filename..".mp3") end elseif source == bCancel then hidePhoneGUI() elseif source == bOK then if guiGridListGetSelectedItem(gRingtones) ~= -1 then triggerServerEvent("saveRingtone", getLocalPlayer(), guiGridListGetSelectedItem(gRingtones) + 1) end hidePhoneGUI() end end end function hidePhoneGUI() if wPhoneMenu then destroyElement(wPhoneMenu) end removeEventHandler("onClientGUIClick", getRootElement(), onGuiClick) showCursor(false) end function startPhoneRinging(ringType) if ringType == 1 then -- phone call local x, y, z = getElementPosition(source) local _,_, itemValue = exports.global:cdoesPlayerHaveItem(getLocalPlayer(), 2, -1) if not itemValue then itemValue = 1 end p_Sound[source] = playSound3D(ringtones[itemValue], x, y, z, true) getSoundLength(p_Sound[source]) stopTimer[source] = setTimer(triggerEvent, 10000, 1, "stopRinging", source) elseif ringType == 2 then -- sms p_Sound[source] = playSound3D("sms.mp3",getElementPosition(source)) else outputDebugString("Ring type "..tostring(ringType).. " doesn't exist!", 2) end attachElements(p_Sound[source], source) end addEvent("startRinging", true) addEventHandler("startRinging", getRootElement(), startPhoneRinging) function stopPhoneRinging() if p_Sound[source] then stopSound(p_Sound[source]) p_Sound[source] = nil end if stopTimer[source] then killTimer(stopTimer[source]) stopTimer[source] = nil end end addEvent("stopRinging", true) addEventHandler("stopRinging", getRootElement(), stopPhoneRinging)
local wPhoneMenu, gRingtones, ePhoneNumber, bCall, bOK, bCancel local sx, sy = guiGetScreenSize() local p_Sound = {} local stopTimer = {} function showPhoneGui(itemValue) wPhoneMenu = guiCreateWindow(sx/2 - 125,sy/2 - 175,250,310,"Phone Menu",false) bCall = guiCreateButton(0.0424,0.0831,0.2966,0.0855,"Call",true,wPhoneMenu) ePhoneNumber = guiCreateEdit(0.3559,0.0831,0.5975,0.0855,"",true,wPhoneMenu) gRingtones = guiCreateGridList(0.0381,0.1977,0.9153,0.6706,true,wPhoneMenu) guiGridListAddColumn(gRingtones,"ringtones",0.85) for i, filename in ipairs(ringtones) do guiGridListSetItemText(gRingtones, guiGridListAddRow(gRingtones), 1, filename:sub(1,-5), false, false) end guiGridListSetSelectedItem(gRingtones, itemValue - 1, 1) bOK = guiCreateButton(0.0381,0.8821,0.4492,0.0742,"OK",true,wPhoneMenu) bCancel = guiCreateButton(0.5212,0.8821,0.4322,0.0742,"Cancel",true,wPhoneMenu) addEventHandler("onClientGUIClick", getRootElement(), onGuiClick) showCursor(true) end addEvent("showPhoneGUI", true) addEventHandler("showPhoneGUI", getRootElement(), showPhoneGui) function onGuiClick(button) if button == "left" then if p_Sound["playing"] then stopSound(p_Sound["playing"]) end if source == bCall then local phoneNumber = guiGetText(wPhoneMenu) triggerServerEvent("remoteCall", getLocalPlayer(), getLocalPlayer(), "call", phoneNumber) hidePhoneGUI() elseif source == gRingtones then if guiGridListGetSelectedItem(gRingtones) ~= -1 then local filename = guiGridListGetItemText(gRingtones, guiGridListGetSelectedItem(gRingtones), 1) p_Sound["playing"] = playSound(filename..".mp3") end elseif source == bCancel then hidePhoneGUI() elseif source == bOK then if guiGridListGetSelectedItem(gRingtones) ~= -1 then triggerServerEvent("saveRingtone", getLocalPlayer(), guiGridListGetSelectedItem(gRingtones) + 1) end hidePhoneGUI() end end end function hidePhoneGUI() if wPhoneMenu then destroyElement(wPhoneMenu) end removeEventHandler("onClientGUIClick", getRootElement(), onGuiClick) showCursor(false) end function startPhoneRinging(ringType) if ringType == 1 then -- phone call local x, y, z = getElementPosition(source) local _,_, itemValue = exports.global:cdoesPlayerHaveItem(getLocalPlayer(), 2, -1) if not itemValue then itemValue = 1 end p_Sound[source] = playSound3D(ringtones[itemValue], x, y, z, true) setSoundVolume(p_Sound[source], 0.4) setSoundMaxDistance(p_Sound[source], 20) getSoundLength(p_Sound[source]) stopTimer[source] = setTimer(triggerEvent, 10000, 1, "stopRinging", source) elseif ringType == 2 then -- sms p_Sound[source] = playSound3D("sms.mp3",getElementPosition(source)) else outputDebugString("Ring type "..tostring(ringType).. " doesn't exist!", 2) end attachElements(p_Sound[source], source) end addEvent("startRinging", true) addEventHandler("startRinging", getRootElement(), startPhoneRinging) function stopPhoneRinging() if p_Sound[source] then stopSound(p_Sound[source]) p_Sound[source] = nil end if stopTimer[source] then killTimer(stopTimer[source]) stopTimer[source] = nil end end addEvent("stopRinging", true) addEventHandler("stopRinging", getRootElement(), stopPhoneRinging)
fixed #1006: Ringtone - Too Loud
fixed #1006: Ringtone - Too Loud git-svn-id: 8769cb08482c9977c94b72b8e184ec7d2197f4f7@1216 64450a49-1f69-0410-a0a2-f5ebb52c4f5b
Lua
bsd-3-clause
valhallaGaming/uno,valhallaGaming/uno,valhallaGaming/uno
02d68d1d8fbba5b9685c29c503520796c55fa3fa
src/camera/src/Client/CameraStackService.lua
src/camera/src/Client/CameraStackService.lua
--[=[ Holds camera states and allows for the last camera state to be retrieved. Also initializes an impulse and default camera as the bottom of the stack. Is a singleton. @class CameraStackService ]=] local require = require(script.Parent.loader).load(script) local RunService = game:GetService("RunService") local Workspace = game:GetService("Workspace") local HttpService = game:GetService("HttpService") local CustomCameraEffect = require("CustomCameraEffect") local DefaultCamera = require("DefaultCamera") local ImpulseCamera = require("ImpulseCamera") local ServiceBag = require("ServiceBag") assert(RunService:IsClient(), "[CameraStackService] - Only require CameraStackService on client") local CameraStackService = {} --[=[ Initializes a new camera stack. Should be done via the ServiceBag. @param serviceBag ServiceBag ]=] function CameraStackService:Init(serviceBag) assert(ServiceBag.isServiceBag(serviceBag), "Not a valid service bag") self._stack = {} self._disabledSet = {} -- Initialize default cameras self._rawDefaultCamera = DefaultCamera.new() self._impulseCamera = ImpulseCamera.new() self._defaultCamera = (self._rawDefaultCamera + self._impulseCamera):SetMode("Relative") if self._doNotUseDefaultCamera then Workspace.CurrentCamera.CameraType = Enum.CameraType.Scriptable -- TODO: Handle camera deleted too! Workspace.CurrentCamera:GetPropertyChangedSignal("CameraType"):Connect(function() Workspace.CurrentCamera.CameraType = Enum.CameraType.Scriptable end) else self._rawDefaultCamera:BindToRenderStep() end -- Add camera to stack self:Add(self._defaultCamera) RunService:BindToRenderStep("CameraStackUpdateInternal", Enum.RenderPriority.Camera.Value + 75, function() debug.profilebegin("CameraStackUpdate") if next(self._disabledSet) then return end local state = self:GetTopState() if state then state:Set(Workspace.CurrentCamera) end debug.profileend() end) end --[=[ Prevents the default camera from being used @param doNotUseDefaultCamera boolean ]=] function CameraStackService:SetDoNotUseDefaultCamera(doNotUseDefaultCamera) assert(not self._stack, "Already initialized") self._doNotUseDefaultCamera = doNotUseDefaultCamera end --[=[ Pushes a disable state onto the camera stack @return function -- Function to cancel disable ]=] function CameraStackService:PushDisable() assert(self._stack, "Not initialized") local disabledKey = HttpService:GenerateGUID(false) self._disabledSet[disabledKey] = true return function() self._disabledSet[disabledKey] = nil end end --[=[ Outputs the camera stack. Intended for diagnostics. ]=] function CameraStackService:PrintCameraStack() assert(self._stack, "Stack is not initialized yet") for _, value in pairs(self._stack) do print(tostring(type(value) == "table" and value.ClassName or tostring(value))) end end --[=[ Returns the default camera @return SummedCamera -- DefaultCamera + ImpulseCamera ]=] function CameraStackService:GetDefaultCamera() assert(self._defaultCamera, "Not initialized") return self._defaultCamera end --[=[ Returns the impulse camera. Useful for adding camera shake. Shaking the camera: ```lua self._cameraStackService:GetImpulseCamera():Impulse(Vector3.new(0.25, 0, 0.25*(math.random()-0.5))) ``` You can also sum the impulse camera into another effect to layer the shake on top of the effect as desired. ```lua -- Adding global custom camera shake to a custom camera effect local customCameraEffect = ... return (customCameraEffect + self._cameraStackService:GetImpulseCamera()):SetMode("Relative") ``` @return ImpulseCamera ]=] function CameraStackService:GetImpulseCamera() assert(self._impulseCamera, "Not initialized") return self._impulseCamera end --[=[ Returns the default camera without any impulse cameras @return DefaultCamera ]=] function CameraStackService:GetRawDefaultCamera() assert(self._rawDefaultCamera, "Not initialized") return self._rawDefaultCamera end --[=[ Gets the camera current on the top of the stack @return CameraEffect ]=] function CameraStackService:GetTopCamera() assert(self._stack, "Not initialized") return self._stack[#self._stack] end --[=[ Retrieves the top state off the stack at this time @return CameraState? ]=] function CameraStackService:GetTopState() assert(self._stack, "Stack is not initialized yet") if #self._stack > 10 then warn(("[CameraStackService] - Stack is bigger than 10 in camerastackService (%d)"):format(#self._stack)) end local topState = self._stack[#self._stack] if type(topState) == "table" then local state = topState.CameraState or topState if state then return state else warn("[CameraStackService] - No top state!") end else warn("[CameraStackService] - Bad type on top of stack") end end --[=[ Returns a new camera state that retrieves the state below its set state. @return CustomCameraEffect -- Effect below @return (CameraState) -> () -- Function to set the state ]=] function CameraStackService:GetNewStateBelow() assert(self._stack, "Stack is not initialized yet") local _stateToUse = nil return CustomCameraEffect.new(function() local index = self:GetIndex(_stateToUse) if index then local below = self._stack[index-1] if below then return below.CameraState or below else warn("[CameraStackService] - Could not get state below, found current state. Returning default.") return self._stack[1].CameraState end else warn(("[CameraStackService] - Could not get state from %q, returning default"):format(tostring(_stateToUse))) return self._stack[1].CameraState end end), function(newStateToUse) _stateToUse = newStateToUse end end --[=[ Retrieves the index of a state @param state CameraEffect @return number? -- index ]=] function CameraStackService:GetIndex(state) assert(self._stack, "Stack is not initialized yet") for index, value in pairs(self._stack) do if value == state then return index end end end --[=[ Returns the current stack. :::warning Do not modify this stack, this is the raw memory of the stack ::: @return { CameraState<T> } ]=] function CameraStackService:GetStack() assert(self._stack, "Not initialized") return self._stack end --[=[ Removes the state from the stack @param state CameraState ]=] function CameraStackService:Remove(state) assert(self._stack, "Stack is not initialized yet") local index = self:GetIndex(state) if index then table.remove(self._stack, index) end end --[=[ Adds the state from the stack @param state CameraState ]=] function CameraStackService:Add(state) assert(self._stack, "Stack is not initialized yet") table.insert(self._stack, state) end return CameraStackService
--[=[ Holds camera states and allows for the last camera state to be retrieved. Also initializes an impulse and default camera as the bottom of the stack. Is a singleton. @class CameraStackService ]=] local require = require(script.Parent.loader).load(script) local RunService = game:GetService("RunService") local Workspace = game:GetService("Workspace") local HttpService = game:GetService("HttpService") local CustomCameraEffect = require("CustomCameraEffect") local DefaultCamera = require("DefaultCamera") local ImpulseCamera = require("ImpulseCamera") local ServiceBag = require("ServiceBag") assert(RunService:IsClient(), "[CameraStackService] - Only require CameraStackService on client") local CameraStackService = {} --[=[ Initializes a new camera stack. Should be done via the ServiceBag. @param serviceBag ServiceBag ]=] function CameraStackService:Init(serviceBag) assert(ServiceBag.isServiceBag(serviceBag), "Not a valid service bag") self._stack = {} self._disabledSet = {} -- Initialize default cameras self._rawDefaultCamera = DefaultCamera.new() self._impulseCamera = ImpulseCamera.new() self._defaultCamera = (self._rawDefaultCamera + self._impulseCamera):SetMode("Relative") -- Add camera to stack self:Add(self._defaultCamera) RunService:BindToRenderStep("CameraStackUpdateInternal", Enum.RenderPriority.Camera.Value + 75, function() debug.profilebegin("CameraStackUpdate") if next(self._disabledSet) then return end local state = self:GetTopState() if state then state:Set(Workspace.CurrentCamera) end debug.profileend() end) end function CameraStackService:Start() self._started = true -- TODO: Allow rebinding if self._doNotUseDefaultCamera then Workspace.CurrentCamera.CameraType = Enum.CameraType.Scriptable -- TODO: Handle camera deleted too! Workspace.CurrentCamera:GetPropertyChangedSignal("CameraType"):Connect(function() Workspace.CurrentCamera.CameraType = Enum.CameraType.Scriptable end) else self._rawDefaultCamera:BindToRenderStep() end end --[=[ Prevents the default camera from being used @param doNotUseDefaultCamera boolean ]=] function CameraStackService:SetDoNotUseDefaultCamera(doNotUseDefaultCamera) assert(not self._started, "Already started") self._doNotUseDefaultCamera = doNotUseDefaultCamera end --[=[ Pushes a disable state onto the camera stack @return function -- Function to cancel disable ]=] function CameraStackService:PushDisable() assert(self._stack, "Not initialized") local disabledKey = HttpService:GenerateGUID(false) self._disabledSet[disabledKey] = true return function() self._disabledSet[disabledKey] = nil end end --[=[ Outputs the camera stack. Intended for diagnostics. ]=] function CameraStackService:PrintCameraStack() assert(self._stack, "Stack is not initialized yet") for _, value in pairs(self._stack) do print(tostring(type(value) == "table" and value.ClassName or tostring(value))) end end --[=[ Returns the default camera @return SummedCamera -- DefaultCamera + ImpulseCamera ]=] function CameraStackService:GetDefaultCamera() assert(self._defaultCamera, "Not initialized") return self._defaultCamera end --[=[ Returns the impulse camera. Useful for adding camera shake. Shaking the camera: ```lua self._cameraStackService:GetImpulseCamera():Impulse(Vector3.new(0.25, 0, 0.25*(math.random()-0.5))) ``` You can also sum the impulse camera into another effect to layer the shake on top of the effect as desired. ```lua -- Adding global custom camera shake to a custom camera effect local customCameraEffect = ... return (customCameraEffect + self._cameraStackService:GetImpulseCamera()):SetMode("Relative") ``` @return ImpulseCamera ]=] function CameraStackService:GetImpulseCamera() assert(self._impulseCamera, "Not initialized") return self._impulseCamera end --[=[ Returns the default camera without any impulse cameras @return DefaultCamera ]=] function CameraStackService:GetRawDefaultCamera() assert(self._rawDefaultCamera, "Not initialized") return self._rawDefaultCamera end --[=[ Gets the camera current on the top of the stack @return CameraEffect ]=] function CameraStackService:GetTopCamera() assert(self._stack, "Not initialized") return self._stack[#self._stack] end --[=[ Retrieves the top state off the stack at this time @return CameraState? ]=] function CameraStackService:GetTopState() assert(self._stack, "Stack is not initialized yet") if #self._stack > 10 then warn(("[CameraStackService] - Stack is bigger than 10 in camerastackService (%d)"):format(#self._stack)) end local topState = self._stack[#self._stack] if type(topState) == "table" then local state = topState.CameraState or topState if state then return state else warn("[CameraStackService] - No top state!") end else warn("[CameraStackService] - Bad type on top of stack") end end --[=[ Returns a new camera state that retrieves the state below its set state. @return CustomCameraEffect -- Effect below @return (CameraState) -> () -- Function to set the state ]=] function CameraStackService:GetNewStateBelow() assert(self._stack, "Stack is not initialized yet") local _stateToUse = nil return CustomCameraEffect.new(function() local index = self:GetIndex(_stateToUse) if index then local below = self._stack[index-1] if below then return below.CameraState or below else warn("[CameraStackService] - Could not get state below, found current state. Returning default.") return self._stack[1].CameraState end else warn(("[CameraStackService] - Could not get state from %q, returning default"):format(tostring(_stateToUse))) return self._stack[1].CameraState end end), function(newStateToUse) _stateToUse = newStateToUse end end --[=[ Retrieves the index of a state @param state CameraEffect @return number? -- index ]=] function CameraStackService:GetIndex(state) assert(self._stack, "Stack is not initialized yet") for index, value in pairs(self._stack) do if value == state then return index end end end --[=[ Returns the current stack. :::warning Do not modify this stack, this is the raw memory of the stack ::: @return { CameraState<T> } ]=] function CameraStackService:GetStack() assert(self._stack, "Not initialized") return self._stack end --[=[ Removes the state from the stack @param state CameraState ]=] function CameraStackService:Remove(state) assert(self._stack, "Stack is not initialized yet") local index = self:GetIndex(state) if index then table.remove(self._stack, index) end end --[=[ Adds the state from the stack @param state CameraState ]=] function CameraStackService:Add(state) assert(self._stack, "Stack is not initialized yet") table.insert(self._stack, state) end return CameraStackService
fix: Delay CameraStackService starting until start method so that configuration has time to be set
fix: Delay CameraStackService starting until start method so that configuration has time to be set
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
ca543dec8306c2c32ed5956539061d5cfae7f680
includes/server/nginx.lua
includes/server/nginx.lua
local time, ngx_print, ngx_var, ngx_req = os.time, ngx.print, ngx.var, ngx.req local explode, unescape = seawolf.text.explode, socket.url.unescape local trim = seawolf.text.trim env._SERVER = function (v) if v == 'QUERY_STRING' then return ngx_var.args elseif v == 'SCRIPT_NAME' then return ngx_var.uri elseif v == 'HTTP_HOST' then return ngx_req.get_headers()["Host"] elseif v == 'SERVER_NAME' then return ngx_var[v:lower()] else return ngx_var[v] end end local cookies, parsed, tmp, key, value = ngx_req.get_headers()['Cookie'] or '', {} cookies = explode(';', cookies) for _, v in pairs(cookies) do v = trim(v) if #v > 0 then tmp = explode('=', v) key = unescape((tmp[1] or ''):gsub('+', ' ')) value = unescape((tmp[2] or ''):gsub('+', ' ')) parsed[key] = value end end ophal.cookies = parsed function write(s) ngx.print(s) end io.write = write function headerCookieSetString(name, value, expires, path, domain) return ('%s=%s; domain=%s; expires=%s; path=%s'):format(name, value, domain, ngx.cookie_time(expires+time()), path) end function header(n, v) if n == 'status' then ngx.status = v else if type(v) == 'function' then v = v() end ngx.header[n] = v end end --[[ Redirect to raw destination URL. ]] function redirect(dest_url, http_response_code) shutdown_ophal() ngx.redirect(dest_url, http_response_code or ngx.HTTP_MOVED_TEMPORARILY) end do local body function request_get_body() local file = {} if body == nil then ngx.req.read_body() -- try from memory body = ngx.req.get_body_data() if body == nil then file.name = ngx.req.get_body_file() if file.name then file.handle = io.open(file.name) body = file.handle:read '*a' else body = '' end end end return body end end function server_exit() ngx.exit(ngx.HTTP_OK) end
local seawolf = require 'seawolf'.__build('text') local time, ngx_print, ngx_var, ngx_req = os.time, ngx.print, ngx.var, ngx.req local explode, unescape = seawolf.text.explode, socket.url.unescape local trim = seawolf.text.trim env._SERVER = function (v) if v == 'QUERY_STRING' then return ngx_var.args elseif v == 'SCRIPT_NAME' then return ngx_var.uri elseif v == 'HTTP_HOST' then return ngx_req.get_headers()["Host"] elseif v == 'SERVER_NAME' then return ngx_var[v:lower()] else return ngx_var[v] end end local cookies, parsed, tmp, key, value = ngx_req.get_headers()['Cookie'] or '', {} cookies = explode(';', cookies) for _, v in pairs(cookies) do v = trim(v) if #v > 0 then tmp = explode('=', v) key = unescape((tmp[1] or ''):gsub('+', ' ')) value = unescape((tmp[2] or ''):gsub('+', ' ')) parsed[key] = value end end ophal.cookies = parsed function write(s) ngx.print(s) end io.write = write function headerCookieSetString(name, value, expires, path, domain) return ('%s=%s; domain=%s; expires=%s; path=%s'):format(name, value, domain, ngx.cookie_time(expires+time()), path) end function header(n, v) if n == 'status' then ngx.status = v else if type(v) == 'function' then v = v() end ngx.header[n] = v end end --[[ Redirect to raw destination URL. ]] function redirect(dest_url, http_response_code) shutdown_ophal() ngx.redirect(dest_url, http_response_code or ngx.HTTP_MOVED_TEMPORARILY) end do local body function request_get_body() local file = {} if body == nil then ngx.req.read_body() -- try from memory body = ngx.req.get_body_data() if body == nil then file.name = ngx.req.get_body_file() if file.name then file.handle = io.open(file.name) body = file.handle:read '*a' else body = '' end end end return body end end function server_exit() ngx.exit(ngx.HTTP_OK) end
Bug fix: 505 when calling explode() on nginx.
Bug fix: 505 when calling explode() on nginx.
Lua
agpl-3.0
ophal/core,coinzen/coinage,ophal/core,coinzen/coinage,coinzen/coinage,ophal/core
05b0bb2e6a6589092084615e9a961ea45a75d8c0
access.lua
access.lua
-- import requirements -- allow either cjson, or th-LuaJSON local has_cjson, jsonmod = pcall(require, "cjson") if not has_cjson then jsonmod = require "json" end -- Ubuntu broke the install. Puts the source in /usr/share/lua/5.1/https.lua, -- but since the source defines itself as the module "ssl.https", after we -- load the source, we need to grab the actual thing. pcall(require,"https") local https = require "ssl.https" -- /usr/share/lua/5.1/https.lua local ltn12 = require("ltn12") local uri = ngx.var.uri local uri_args = ngx.req.get_uri_args() local scheme = ngx.var.scheme local server_name = ngx.var.server_name -- setup some app-level vars local client_id = ngx.var.ngo_client_id local client_secret = ngx.var.ngo_client_secret local domain = ngx.var.ngo_domain local cb_scheme = ngx.var.ngo_callback_scheme or scheme local cb_server_name = ngx.var.ngo_callback_host or server_name local cb_uri = ngx.var.ngo_callback_uri or "/_oauth" local cb_url = cb_scheme.."://"..cb_server_name..cb_uri local redir_url = cb_scheme.."://"..cb_server_name..uri local signout_uri = ngx.var.ngo_signout_uri or "/_signout" local debug = ngx.var.ngo_debug local whitelist = ngx.var.ngo_whitelist local blacklist = ngx.var.ngo_blacklist local secure_cookies = ngx.var.ngo_secure_cookies local token_secret = ngx.var.ngo_token_secret or "UNSET" local set_user = ngx.var.ngo_user local email_as_user = ngx.var.ngo_email_as_user -- Force the user to set a token secret if token_secret == "UNSET" then ngx.log(ngx.ERR, "$ngo_token_secret must be set in Nginx config!") return ngx.exit(ngx.HTTP_UNAUTHORIZED) end -- See https://developers.google.com/accounts/docs/OAuth2WebServer if uri == signout_uri then ngx.header["Set-Cookie"] = "OauthAccessToken==deleted; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT" return ngx.redirect(cb_scheme.."://"..server_name) end -- Enforce token security and expiration local oauth_expires = tonumber(ngx.var.cookie_OauthExpires) or 0 local oauth_email = ngx.unescape_uri(ngx.var.cookie_OauthEmail or "") local oauth_access_token = ngx.unescape_uri(ngx.var.cookie_OauthAccessToken or "") local expected_token = ngx.encode_base64(ngx.hmac_sha1(token_secret, cb_server_name .. oauth_email .. oauth_expires)) if oauth_access_token == expected_token and oauth_expires and oauth_expires > ngx.time() then -- Populate the nginx 'ngo_user' variable with our Oauth username, if requested if set_user then local oauth_user, oauth_domain = oauth_email:match("([^@]+)@(.+)") if email_as_user then ngx.var.ngo_user = email else ngx.var.ngo_user = oauth_user end end return else -- If no access token and this isn't the callback URI, redirect to oauth if uri ~= cb_uri then -- Redirect to the /oauth endpoint, request access to ALL scopes return ngx.redirect("https://accounts.google.com/o/oauth2/auth?client_id="..client_id.."&scope=email&response_type=code&redirect_uri="..ngx.escape_uri(cb_url).."&state="..ngx.escape_uri(redir_url).."&login_hint="..ngx.escape_uri(domain)) end -- Fetch teh authorization code from the parameters local auth_code = uri_args["code"] local auth_error = uri_args["error"] if auth_error then ngx.log(ngx.ERR, "received "..auth_error.." from https://accounts.google.com/o/oauth2/auth") return ngx.exit(ngx.HTTP_UNAUTHORIZED) end if debug then ngx.log(ngx.ERR, "DEBUG: fetching token for auth code "..auth_code) end -- TODO: Switch to NBIO sockets -- If I get around to working luasec, this says how to pass a function which -- can generate a socket, needed for NBIO using nginx cosocket -- http://lua-users.org/lists/lua-l/2009-02/msg00251.html local res, code, headers, status = https.request( "https://accounts.google.com/o/oauth2/token", "code="..ngx.escape_uri(auth_code).."&client_id="..client_id.."&client_secret="..client_secret.."&redirect_uri="..ngx.escape_uri(cb_url).."&grant_type=authorization_code" ) if debug then ngx.log(ngx.ERR, "DEBUG: token response "..res..code..status) end if code~=200 then ngx.log(ngx.ERR, "received "..code.." from https://accounts.google.com/o/oauth2/token") return ngx.exit(ngx.HTTP_UNAUTHORIZED) end -- use version 1 cookies so we don't have to encode. MSIE-old beware local json = jsonmod.decode( res ) local access_token = json["access_token"] local expires = ngx.time() + json["expires_in"] local cookie_tail = ";version=1;path=/;Max-Age="..json["expires_in"] if secure_cookies then cookie_tail = cookie_tail..";secure" end local send_headers = { Authorization = "Bearer "..access_token, } local result_table = {} local res2, code2, headers2, status2 = https.request({ url = "https://www.googleapis.com/oauth2/v2/userinfo", method = "GET", headers = send_headers, sink = ltn12.sink.table(result_table), }) if code2~=200 then ngx.log(ngx.ERR, "received "..code2.." from https://www.googleapis.com/oauth2/v2/userinfo") return ngx.exit(ngx.HTTP_UNAUTHORIZED) end if debug then ngx.log(ngx.ERR, "DEBUG: userinfo response "..res2..code2..status2..table.concat(result_table)) end json = jsonmod.decode( table.concat(result_table) ) local name = json["name"] local email = json["email"] local picture = json["picture"] local token = ngx.encode_base64(ngx.hmac_sha1(token_secret, cb_server_name .. email .. expires)) local oauth_user, oauth_domain = email:match("([^@]+)@(.+)") -- If no whitelist or blacklist, match on domain if not whitelist and not blacklist and domain then if oauth_domain ~= domain then if debug then ngx.log(ngx.ERR, "DEBUG: "..email.." not in "..domain) end return ngx.exit(ngx.HTTP_UNAUTHORIZED) end end if whitelist then if not string.find(" " .. whitelist .. " ", " " .. email .. " ") then if debug then ngx.log(ngx.ERR, "DEBUG: "..email.." not in whitelist") end return ngx.exit(ngx.HTTP_UNAUTHORIZED) end end if blacklist then if string.find(" " .. blacklist .. " ", " " .. email .. " ") then if debug then ngx.log(ngx.ERR, "DEBUG: "..email.." in blacklist") end return ngx.exit(ngx.HTTP_UNAUTHORIZED) end end ngx.header["Set-Cookie"] = { "OauthAccessToken="..ngx.escape_uri(token)..cookie_tail, "OauthExpires="..expires..cookie_tail, "OauthName="..ngx.escape_uri(name)..cookie_tail, "OauthEmail="..ngx.escape_uri(email)..cookie_tail, "OauthPicture="..ngx.escape_uri(picture)..cookie_tail } -- Poplate our ngo_user variable if set_user then if email_as_user then ngx.var.ngo_user = email else ngx.var.ngo_user = oauth_user end end -- Redirect if debug then ngx.log(ngx.ERR, "DEBUG: authorized "..json["email"]..", redirecting to "..uri_args["state"]) end return ngx.redirect(uri_args["state"]) end
-- import requirements -- allow either cjson, or th-LuaJSON local has_cjson, jsonmod = pcall(require, "cjson") if not has_cjson then jsonmod = require "json" end -- Ubuntu broke the install. Puts the source in /usr/share/lua/5.1/https.lua, -- but since the source defines itself as the module "ssl.https", after we -- load the source, we need to grab the actual thing. pcall(require,"https") local https = require "ssl.https" -- /usr/share/lua/5.1/https.lua local ltn12 = require("ltn12") local uri = ngx.var.uri local uri_args = ngx.req.get_uri_args() local scheme = ngx.var.scheme local server_name = ngx.var.server_name -- setup some app-level vars local client_id = ngx.var.ngo_client_id local client_secret = ngx.var.ngo_client_secret local domain = ngx.var.ngo_domain local cb_scheme = ngx.var.ngo_callback_scheme or scheme local cb_server_name = ngx.var.ngo_callback_host or server_name local cb_uri = ngx.var.ngo_callback_uri or "/_oauth" local cb_url = cb_scheme.."://"..cb_server_name..cb_uri local redir_url = cb_scheme.."://"..cb_server_name..uri local signout_uri = ngx.var.ngo_signout_uri or "/_signout" local debug = ngx.var.ngo_debug local whitelist = ngx.var.ngo_whitelist local blacklist = ngx.var.ngo_blacklist local secure_cookies = ngx.var.ngo_secure_cookies local token_secret = ngx.var.ngo_token_secret or "UNSET" local set_user = ngx.var.ngo_user local email_as_user = ngx.var.ngo_email_as_user -- Force the user to set a token secret if token_secret == "UNSET" then ngx.log(ngx.ERR, "$ngo_token_secret must be set in Nginx config!") return ngx.exit(ngx.HTTP_UNAUTHORIZED) end -- See https://developers.google.com/accounts/docs/OAuth2WebServer if uri == signout_uri then ngx.header["Set-Cookie"] = "OauthAccessToken==deleted; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT" return ngx.redirect(cb_scheme.."://"..server_name) end -- Enforce token security and expiration local oauth_expires = tonumber(ngx.var.cookie_OauthExpires) or 0 local oauth_email = ngx.unescape_uri(ngx.var.cookie_OauthEmail or "") local oauth_access_token = ngx.unescape_uri(ngx.var.cookie_OauthAccessToken or "") local expected_token = ngx.encode_base64(ngx.hmac_sha1(token_secret, cb_server_name .. oauth_email .. oauth_expires)) -- Prevent timing attacks -- https://github.com/agoragames/nginx-google-oauth/issues/5 local token_match = true for i=0,#expected_token do token_match = token_match and (expected_token:sub(i,i)==oauth_access_token:sub(i,i)) end if token_match and oauth_expires and oauth_expires > ngx.time() then -- Populate the nginx 'ngo_user' variable with our Oauth username, if requested if set_user then local oauth_user, oauth_domain = oauth_email:match("([^@]+)@(.+)") if email_as_user then ngx.var.ngo_user = email else ngx.var.ngo_user = oauth_user end end return else -- If no access token and this isn't the callback URI, redirect to oauth if uri ~= cb_uri then -- Redirect to the /oauth endpoint, request access to ALL scopes return ngx.redirect("https://accounts.google.com/o/oauth2/auth?client_id="..client_id.."&scope=email&response_type=code&redirect_uri="..ngx.escape_uri(cb_url).."&state="..ngx.escape_uri(redir_url).."&login_hint="..ngx.escape_uri(domain)) end -- Fetch teh authorization code from the parameters local auth_code = uri_args["code"] local auth_error = uri_args["error"] if auth_error then ngx.log(ngx.ERR, "received "..auth_error.." from https://accounts.google.com/o/oauth2/auth") return ngx.exit(ngx.HTTP_UNAUTHORIZED) end if debug then ngx.log(ngx.ERR, "DEBUG: fetching token for auth code "..auth_code) end -- TODO: Switch to NBIO sockets -- If I get around to working luasec, this says how to pass a function which -- can generate a socket, needed for NBIO using nginx cosocket -- http://lua-users.org/lists/lua-l/2009-02/msg00251.html local res, code, headers, status = https.request( "https://accounts.google.com/o/oauth2/token", "code="..ngx.escape_uri(auth_code).."&client_id="..client_id.."&client_secret="..client_secret.."&redirect_uri="..ngx.escape_uri(cb_url).."&grant_type=authorization_code" ) if debug then ngx.log(ngx.ERR, "DEBUG: token response "..res..code..status) end if code~=200 then ngx.log(ngx.ERR, "received "..code.." from https://accounts.google.com/o/oauth2/token") return ngx.exit(ngx.HTTP_UNAUTHORIZED) end -- use version 1 cookies so we don't have to encode. MSIE-old beware local json = jsonmod.decode( res ) local access_token = json["access_token"] local expires = ngx.time() + json["expires_in"] local cookie_tail = ";version=1;path=/;Max-Age="..json["expires_in"] if secure_cookies then cookie_tail = cookie_tail..";secure" end local send_headers = { Authorization = "Bearer "..access_token, } local result_table = {} local res2, code2, headers2, status2 = https.request({ url = "https://www.googleapis.com/oauth2/v2/userinfo", method = "GET", headers = send_headers, sink = ltn12.sink.table(result_table), }) if code2~=200 then ngx.log(ngx.ERR, "received "..code2.." from https://www.googleapis.com/oauth2/v2/userinfo") return ngx.exit(ngx.HTTP_UNAUTHORIZED) end if debug then ngx.log(ngx.ERR, "DEBUG: userinfo response "..res2..code2..status2..table.concat(result_table)) end json = jsonmod.decode( table.concat(result_table) ) local name = json["name"] local email = json["email"] local picture = json["picture"] local token = ngx.encode_base64(ngx.hmac_sha1(token_secret, cb_server_name .. email .. expires)) local oauth_user, oauth_domain = email:match("([^@]+)@(.+)") -- If no whitelist or blacklist, match on domain if not whitelist and not blacklist and domain then if oauth_domain ~= domain then if debug then ngx.log(ngx.ERR, "DEBUG: "..email.." not in "..domain) end return ngx.exit(ngx.HTTP_UNAUTHORIZED) end end if whitelist then if not string.find(" " .. whitelist .. " ", " " .. email .. " ") then if debug then ngx.log(ngx.ERR, "DEBUG: "..email.." not in whitelist") end return ngx.exit(ngx.HTTP_UNAUTHORIZED) end end if blacklist then if string.find(" " .. blacklist .. " ", " " .. email .. " ") then if debug then ngx.log(ngx.ERR, "DEBUG: "..email.." in blacklist") end return ngx.exit(ngx.HTTP_UNAUTHORIZED) end end ngx.header["Set-Cookie"] = { "OauthAccessToken="..ngx.escape_uri(token)..cookie_tail, "OauthExpires="..expires..cookie_tail, "OauthName="..ngx.escape_uri(name)..cookie_tail, "OauthEmail="..ngx.escape_uri(email)..cookie_tail, "OauthPicture="..ngx.escape_uri(picture)..cookie_tail } -- Poplate our ngo_user variable if set_user then if email_as_user then ngx.var.ngo_user = email else ngx.var.ngo_user = oauth_user end end -- Redirect if debug then ngx.log(ngx.ERR, "DEBUG: authorized "..json["email"]..", redirecting to "..uri_args["state"]) end return ngx.redirect(uri_args["state"]) end
WIP prevent timing attacks on access token verification. Fixes #5
WIP prevent timing attacks on access token verification. Fixes #5
Lua
mit
agoragames/nginx-google-oauth,agoragames/nginx-google-oauth
58ab17704dc56dbcd02e0af5bb6c00dbf5becfff
test_scripts/Polices/Policy_Table_Update/029_ATF_P_TC_Notifying_HMI_via_OnAppPermissionChanged.lua
test_scripts/Polices/Policy_Table_Update/029_ATF_P_TC_Notifying_HMI_via_OnAppPermissionChanged.lua
--------------------------------------------------------------------------------------------- -- Requirement summary: -- [PolicyTableUpdate] Notifying HMI via OnAppPermissionChanged about the affected application -- -- Description: -- PoliciesManager must initiate sending SDL.OnAppPermissionChanged{appID} notification to HMI IN CASE the Updated PT resulted any changes in the appID app`s policies. -- Preconditions: -- 1.SDL and HMI are running -- 2.AppID_1 is connected to SDL. -- 3.The device the app is running on is consented -- 4.Policy Table Update procedure is on stage waiting for: -- HMI->SDL: SDL.OnReceivedPolicyUpdate (policyfile) -- 'policyfile' corresponds to PTU validation rules -- Steps: -- Request policy update via HMI: -- HMI->SDL: SDL.OnReceivedPolicyUpdate (policyfile) -- Expected result: -- 1.PoliciesManager validates the updated PT (policyFile) e.i. verifyes, saves the updated fields and everything that is defined with related requirements) -- 2.On validation success: -- SDL->HMI:OnStatusUpdate("UP_TO_DATE") -- 3.SDL replaces the following sections of the Local Policy Table with the corresponding sections from PTU: -- module_config, -- functional_groupings, -- app_policies -- 4.SDL removes 'policyfile' from the directory -- 5.SDL->app: onPermissionChange(<permisssionItem>) -- 6.SDL->HMI: SDL.OnAppPermissionChanged(<appID_1>, params) --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --ToDo: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed config.defaultProtocolVersion = 2 --[[ Required Shared libraries ]] local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require('user_modules/shared_testcases/commonFunctions') local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable') local json = require('json') --[[ Local Variables ]] local basic_ptu_file = "files/ptu.json" local ptu_app_registered = "files/ptu_app.json" -- Prepare parameters for app to save it in json file local function PrepareJsonPTU1(name, new_ptufile) local json_app = [[ { "keep_context": false, "steal_focus": false, "priority": "NONE", "default_hmi": "NONE", "groups": [ "Location-1" ], "RequestType":[ "TRAFFIC_MESSAGE_CHANNEL", "PROPRIETARY", "HTTP", "QUERY_APPS" ] }]] local app = json.decode(json_app) testCasesForPolicyTable:AddApplicationToPTJsonFile(basic_ptu_file, new_ptufile, name, app) end --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() --[[ General Settings for configuration ]] Test = require('connecttest') local mobile_session = require('mobile_session') require('cardinalities') require('user_modules/AppTypes') --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test.Precondition_StopSDL() StopSDL() end function Test.Precondition_Delete_LogsAndPT() commonSteps:DeleteLogsFiles() commonSteps:DeletePolicyTable() end function Test.Precondition_StartSDL() StartSDL(config.pathToSDL, config.ExitOnCrash) end function Test:Precondition_initHMI() self:initHMI() end function Test:Precondition_initHMI_onReady() self:initHMI_onReady() end function Test:Precondition_ConnectMobile() self:connectMobile() end function Test:Precondition_StartSession() self.mobileSession = mobile_session.MobileSession(self, self.mobileConnection) end function Test.Precondition_PreparePTData() PrepareJsonPTU1(config.application1.registerAppInterfaceParams.appID, ptu_app_registered) end function Test:Precondition_RegisterApp() self.mobileSession:StartService(7) :Do(function () local correlationId = self.mobileSession:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered") :Do(function(_, data) local RequestIdActivateApp = self.hmiConnection:SendRequest("SDL.ActivateApp", {appID = data.params.application.appID}) EXPECT_HMIRESPONSE(RequestIdActivateApp, {result = {code = 0, isSDLAllowed = false}, method = "SDL.ActivateApp"}) :Do(function(_,_) local RequestIdGetUserFriendlyMessage = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage", {language = "EN-US", messageCodes = {"DataConsent"}}) EXPECT_HMIRESPONSE(RequestIdGetUserFriendlyMessage,{result = {code = 0, method = "SDL.GetUserFriendlyMessage"}}) :Do(function(_,_) self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality", {allowed = true, source = "GUI", device = {id = config.deviceMAC, name = "127.0.0.1"}}) EXPECT_HMICALL("BasicCommunication.ActivateApp") :Do(function(_,data1) self.hmiConnection:SendResponse(data1.id,"BasicCommunication.ActivateApp", "SUCCESS", {}) end) EXPECT_NOTIFICATION("OnHMIStatus", {hmiLevel = "FULL", systemContext = "MAIN"}) end) end) end) EXPECT_RESPONSE(correlationId, { success = true }) EXPECT_NOTIFICATION("OnPermissionsChange") end) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:UpdatePolicy_ExpectOnAppPermissionChangedWithAppID() EXPECT_HMICALL("BasicCommunication.PolicyUpdate") testCasesForPolicyTable:updatePolicyInDifferentSessions(Test, ptu_app_registered, config.application1.registerAppInterfaceParams.appName, self.mobileSession) EXPECT_HMINOTIFICATION("SDL.OnAppPermissionChanged") :ValidIf(function (_, data) if data.params.appID~=nil then return true else print("OnAppPermissionChanged came without appID") return false end end) end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_RemovePTUfiles() os.remove(ptu_app_registered) end function Test.Postcondition_Stop_SDL() StopSDL() end return Test
--------------------------------------------------------------------------------------------- -- Requirement summary: -- [PolicyTableUpdate] Notifying HMI via OnAppPermissionChanged about the affected application -- -- Description: -- PoliciesManager must initiate sending SDL.OnAppPermissionChanged{appID} notification to HMI IN CASE the Updated PT resulted any changes in the appID app`s policies. -- Preconditions: -- 1.SDL and HMI are running -- 2.AppID_1 is connected to SDL. -- 3.The device the app is running on is consented -- 4.Policy Table Update procedure is on stage waiting for: -- HMI->SDL: SDL.OnReceivedPolicyUpdate (policyfile) -- 'policyfile' corresponds to PTU validation rules -- Steps: -- Request policy update via HMI: -- HMI->SDL: SDL.OnReceivedPolicyUpdate (policyfile) -- Expected result: -- 1.PoliciesManager validates the updated PT (policyFile) e.i. verifyes, saves the updated fields and everything that is defined with related requirements) -- 2.On validation success: -- SDL->HMI:OnStatusUpdate("UP_TO_DATE") -- 3.SDL replaces the following sections of the Local Policy Table with the corresponding sections from PTU: -- module_config, -- functional_groupings, -- app_policies -- 4.SDL removes 'policyfile' from the directory -- 5.SDL->app: onPermissionChange(<permisssionItem>) -- 6.SDL->HMI: SDL.OnAppPermissionChanged(<appID_1>, params) --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --ToDo: shall be removed when issue: "ATF does not stop HB timers by closing session and connection" is fixed config.defaultProtocolVersion = 2 --[[ Required Shared libraries ]] local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonFunctions = require('user_modules/shared_testcases/commonFunctions') local testCasesForPolicyTable = require('user_modules/shared_testcases/testCasesForPolicyTable') local json = require('json') --[[ Local Variables ]] local basic_ptu_file = "files/ptu.json" local ptu_app_registered = "files/ptu_app.json" --[[ General Precondition before ATF start ]] commonFunctions:SDLForceStop() commonSteps:DeleteLogsFileAndPolicyTable() --[[ General Settings for configuration ]] Test = require('connecttest') -- local mobile_session = require('mobile_session') require('cardinalities') require('user_modules/AppTypes') --[[ Preconditions ]] commonFunctions:newTestCasesGroup("Preconditions") function Test.Precondition_PreparePTData() local json_app = [[ { "keep_context": false, "steal_focus": false, "priority": "NONE", "default_hmi": "NONE", "groups": [ "Base-4", "Location-1" ], "RequestType":[ "TRAFFIC_MESSAGE_CHANNEL", "PROPRIETARY", "HTTP", "QUERY_APPS" ] }]] local app = json.decode(json_app) testCasesForPolicyTable:AddApplicationToPTJsonFile(basic_ptu_file, ptu_app_registered, config.application1.registerAppInterfaceParams.appID, app) end function Test:Precondition_ActivateApp() local RequestIdActivateApp = self.hmiConnection:SendRequest("SDL.ActivateApp", {appID = self.applications[config.application1.registerAppInterfaceParams.appName]}) EXPECT_HMIRESPONSE(RequestIdActivateApp, {result = {code = 0, isSDLAllowed = false}, method = "SDL.ActivateApp"}) :Do(function(_,_) local RequestIdGetUserFriendlyMessage = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage", {language = "EN-US", messageCodes = {"DataConsent"}}) EXPECT_HMIRESPONSE(RequestIdGetUserFriendlyMessage,{result = {code = 0, method = "SDL.GetUserFriendlyMessage"}}) :Do(function(_,_) self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality", {allowed = true, source = "GUI", device = {id = config.deviceMAC, name = "127.0.0.1"}}) EXPECT_HMICALL("BasicCommunication.ActivateApp") :Do(function(_,data1) self.hmiConnection:SendResponse(data1.id,"BasicCommunication.ActivateApp", "SUCCESS", {}) end) EXPECT_NOTIFICATION("OnHMIStatus", {hmiLevel = "FULL", systemContext = "MAIN"}) end) end) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:UpdatePolicy_ExpectOnAppPermissionChangedWithAppID() testCasesForPolicyTable:updatePolicyInDifferentSessions(Test, ptu_app_registered, config.application1.registerAppInterfaceParams.appName, self.mobileSession) EXPECT_HMINOTIFICATION("SDL.OnAppPermissionChanged") :ValidIf(function (_, data) if data.params.appID~=nil then return true else print("OnAppPermissionChanged came without appID") return false end end) :Times(AtLeast(1)) end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_RemovePTUfiles() os.remove(ptu_app_registered) end function Test.Postcondition_Stop_SDL() StopSDL() end return Test
Fix issues
Fix issues
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
bbc0cb555ed4787b2016000df4eb418a4e898aeb
lua/plugins/telescope.lua
lua/plugins/telescope.lua
local nvim = require'nvim' local utils = require'utils' local executable = require'utils.files'.executable local load_module = require'utils.helpers'.load_module local set_autocmd = require'nvim.autocmds'.set_autocmd local set_mapping = require'nvim.mappings'.set_mapping local set_command = require'nvim.commands'.set_command local telescope = load_module'telescope' if not telescope then return false end -- local lsp_langs = require'plugins.lsp' local ts_langs = require'plugins.treesitter' local actions = require'telescope.actions' telescope.setup{ defaults = { vimgrep_arguments = require'utils.helpers'.select_grep(false, 'grepprg', true), mappings = { i = { ["<ESC>"] = actions.close, -- ["<CR>"] = actions.goto_file_selection_edit + actions.center, ["<C-j>"] = actions.move_selection_next, ["<C-k>"] = actions.move_selection_previous, }, n = { ["<ESC>"] = actions.close, }, }, prompt_position = "bottom", prompt_prefix = ">", selection_strategy = "reset", sorting_strategy = "descending", layout_strategy = "horizontal", -- file_ignore_patterns = {}, file_sorter = require'telescope.sorters'.get_fzy_sorter , generic_sorter = require'telescope.sorters'.get_fzy_sorter, -- shorten_path = true, winblend = 0, -- width = 0.75, -- preview_cutoff = 120, -- results_height = 1, -- results_width = 0.8, -- border = {}, -- borderchars = { '─', '│', '─', '│', '╭', '╮', '╯', '╰'}, -- color_devicons = true, -- use_less = true, set_env = { ['COLORTERM'] = 'truecolor' }, -- file_previewer = require'telescope.previewers'.cat.new, -- grep_previewer = require'telescope.previewers'.vimgrep.new, -- qflist_previewer = require'telescope.previewers'.qflist.new, -- Developer configurations: Not meant for general override -- buffer_previewer_maker = require'telescope.previewers'.buffer_previewer_maker }, } -- *** Builtins *** -- builtin.planets -- builtin.builtin -- builtin.find_files -- builtin.git_files -- builtin.buffers -- builtin.oldfiles -- builtin.commands -- builtin.tags -- builtin.command_history -- builtin.help_tags -- builtin.man_pages -- builtin.marks -- builtin.colorscheme -- builtin.treesitter -- builtin.live_grep -- builtin.current_buffer_fuzzy_find -- builtin.current_buffer_tags -- builtin.grep_string -- builtin.quickfix -- builtin.loclist -- builtin.reloader -- builtin.vim_options -- builtin.registers -- builtin.keymaps -- builtin.filetypes -- builtin.highlights -- builtin.git_commits -- builtin.git_bcommits -- builtin.git_branches -- builtin.git_status local noremap = {noremap = true} set_command{ lhs = 'LuaReloaded', rhs = [[lua require'telescope.builtin'.reloader()]], args = {force=true} } set_command{ lhs = 'HelpTags', rhs = function() require'telescope.builtin'.help_tags{} end, args = {force=true} } set_mapping{ mode = 'n', lhs = '<C-p>', rhs = function() local is_git = vim.b.project_root and vim.b.project_root.is_git or false require'telescope.builtin'.find_files { find_command = require'utils.helpers'.select_filelist(is_git, true) } end, args = {noremap = true} } set_mapping{ mode = 'n', lhs = '<C-b>', rhs = [[<cmd>lua require'telescope.builtin'.current_buffer_fuzzy_find{}<CR>]], args = noremap, } set_mapping{ mode = 'n', lhs = '<leader>g', rhs = [[<cmd>lua require'telescope.builtin'.live_grep{}<CR>]], args = noremap, } set_mapping{ mode = 'n', lhs = '<C-q>', rhs = [[<cmd>lua require'telescope.builtin'.quickfix{}<CR>]], args = noremap, } set_command{ lhs = 'Oldfiles', rhs = [[lua require'telescope.builtin'.oldfiles{}]], args = {force=true} } set_command{ lhs = 'Registers', rhs = [[lua require'telescope.builtin'.registers{}]], args = {force=true} } set_command{ lhs = 'Marks', rhs = [[lua require'telescope.builtin'.marks{}]], args = {force=true} } set_command{ lhs = 'Manpages', rhs = [[lua require'telescope.builtin'.man_pages{}]], args = {force=true} } set_command{ lhs = 'GetVimFiles', rhs = function() require'telescope.builtin'.find_files{ cwd = require'sys'.base, find_command = require'utils.helpers'.select_filelist(false, true) } end, args = {force=true} } if executable('git') then -- set_mapping{ -- mode = 'n', -- lhs = '<leader>s', -- rhs = [[<cmd>lua require'telescope.builtin'.git_status{}<CR>]], -- args = noremap, -- } set_mapping{ mode = 'n', lhs = '<leader>c', rhs = [[<cmd>lua require'telescope.builtin'.git_bcommits{}<CR>]], args = noremap, } set_mapping{ mode = 'n', lhs = '<leader>C', rhs = [[<cmd>lua require'telescope.builtin'.git_commits{}<CR>]], args = noremap, } set_mapping{ mode = 'n', lhs = '<leader>b', rhs = [[<cmd>lua require'telescope.builtin'.git_branches{}<CR>]], args = noremap, } end if ts_langs then set_autocmd{ event = 'FileType', pattern = ts_langs, cmd = [[nnoremap <A-s> <cmd>lua require'telescope.builtin'.treesitter{}<CR>]], group = 'TreesitterAutocmds' } set_autocmd{ event = 'FileType', pattern = ts_langs, cmd = [[command! -buffer TSSymbols lua require'telescope.builtin'.treesitter{}]], group = 'TreesitterAutocmds' } end return true
local nvim = require'nvim' local utils = require'utils' local executable = require'utils.files'.executable local load_module = require'utils.helpers'.load_module local set_autocmd = require'nvim.autocmds'.set_autocmd local set_mapping = require'nvim.mappings'.set_mapping local set_command = require'nvim.commands'.set_command local telescope = load_module'telescope' if not telescope then return false end -- local lsp_langs = require'plugins.lsp' local ts_langs = require'plugins.treesitter' local actions = require'telescope.actions' telescope.setup{ layout_config = { prompt_position = "bottom", prompt_prefix = ">", }, defaults = { vimgrep_arguments = require'utils.helpers'.select_grep(false, 'grepprg', true), mappings = { i = { ["<ESC>"] = actions.close, -- ["<CR>"] = actions.goto_file_selection_edit + actions.center, ["<C-j>"] = actions.move_selection_next, ["<C-k>"] = actions.move_selection_previous, }, n = { ["<ESC>"] = actions.close, }, }, selection_strategy = "reset", sorting_strategy = "descending", layout_strategy = "horizontal", -- file_ignore_patterns = {}, file_sorter = require'telescope.sorters'.get_fzy_sorter , generic_sorter = require'telescope.sorters'.get_fzy_sorter, -- shorten_path = true, winblend = 0, set_env = { ['COLORTERM'] = 'truecolor' }, }, } -- *** Builtins *** -- builtin.planets -- builtin.builtin -- builtin.find_files -- builtin.git_files -- builtin.buffers -- builtin.oldfiles -- builtin.commands -- builtin.tags -- builtin.command_history -- builtin.help_tags -- builtin.man_pages -- builtin.marks -- builtin.colorscheme -- builtin.treesitter -- builtin.live_grep -- builtin.current_buffer_fuzzy_find -- builtin.current_buffer_tags -- builtin.grep_string -- builtin.quickfix -- builtin.loclist -- builtin.reloader -- builtin.vim_options -- builtin.registers -- builtin.keymaps -- builtin.filetypes -- builtin.highlights -- builtin.git_commits -- builtin.git_bcommits -- builtin.git_branches -- builtin.git_status local noremap = {noremap = true} set_command{ lhs = 'LuaReloaded', rhs = [[lua require'telescope.builtin'.reloader()]], args = {force=true} } set_command{ lhs = 'HelpTags', rhs = function() require'telescope.builtin'.help_tags{} end, args = {force=true} } set_mapping{ mode = 'n', lhs = '<C-p>', rhs = function() local is_git = vim.b.project_root and vim.b.project_root.is_git or false require'telescope.builtin'.find_files { find_command = require'utils.helpers'.select_filelist(is_git, true) } end, args = {noremap = true} } set_mapping{ mode = 'n', lhs = '<C-b>', rhs = [[<cmd>lua require'telescope.builtin'.current_buffer_fuzzy_find{}<CR>]], args = noremap, } set_mapping{ mode = 'n', lhs = '<leader>g', rhs = [[<cmd>lua require'telescope.builtin'.live_grep{}<CR>]], args = noremap, } set_mapping{ mode = 'n', lhs = '<C-q>', rhs = [[<cmd>lua require'telescope.builtin'.quickfix{}<CR>]], args = noremap, } set_command{ lhs = 'Oldfiles', rhs = [[lua require'telescope.builtin'.oldfiles{}]], args = {force=true} } set_command{ lhs = 'Registers', rhs = [[lua require'telescope.builtin'.registers{}]], args = {force=true} } set_command{ lhs = 'Marks', rhs = [[lua require'telescope.builtin'.marks{}]], args = {force=true} } set_command{ lhs = 'Manpages', rhs = [[lua require'telescope.builtin'.man_pages{}]], args = {force=true} } set_command{ lhs = 'GetVimFiles', rhs = function() require'telescope.builtin'.find_files{ cwd = require'sys'.base, find_command = require'utils.helpers'.select_filelist(false, true) } end, args = {force=true} } if executable('git') then -- set_mapping{ -- mode = 'n', -- lhs = '<leader>s', -- rhs = [[<cmd>lua require'telescope.builtin'.git_status{}<CR>]], -- args = noremap, -- } set_mapping{ mode = 'n', lhs = '<leader>c', rhs = [[<cmd>lua require'telescope.builtin'.git_bcommits{}<CR>]], args = noremap, } set_mapping{ mode = 'n', lhs = '<leader>C', rhs = [[<cmd>lua require'telescope.builtin'.git_commits{}<CR>]], args = noremap, } set_mapping{ mode = 'n', lhs = '<leader>b', rhs = [[<cmd>lua require'telescope.builtin'.git_branches{}<CR>]], args = noremap, } end if ts_langs then set_autocmd{ event = 'FileType', pattern = ts_langs, cmd = [[nnoremap <A-s> <cmd>lua require'telescope.builtin'.treesitter{}<CR>]], group = 'TreesitterAutocmds' } set_autocmd{ event = 'FileType', pattern = ts_langs, cmd = [[command! -buffer TSSymbols lua require'telescope.builtin'.treesitter{}]], group = 'TreesitterAutocmds' } end return true
fix: Update telescope settings
fix: Update telescope settings
Lua
mit
Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim
780b34fc9ff915305921de551016032a71e049ef
lua/entities/gmod_wire_freezer.lua
lua/entities/gmod_wire_freezer.lua
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Freezer" ENT.WireDebugName = "Freezer" if CLIENT then return end -- No more client function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.State = false self.CollisionState = 0 self.Marks = {} self.Inputs = WireLib.CreateInputs(self, {"Activate", "Disable Collisions"}) self:UpdateOutputs() end function ENT:TriggerInput(name, value) if name == "Activate" then self.State = value ~= 0 for _, ent in pairs(self.Marks) do if IsValid(ent) and IsValid(ent:GetPhysicsObject()) then ent:GetPhysicsObject():EnableMotion(not self.State) if not self.State then ent:GetPhysicsObject():Wake() end end end elseif name == "Disable Collisions" then self.CollisionState = math.Clamp(math.Round(value), 0, 4) for _, ent in pairs(self.Marks) do if IsValid(ent) and IsValid(ent:GetPhysicsObject()) then if self.CollisionState == 0 then ent:SetCollisionGroup( COLLISION_GROUP_NONE ) ent:GetPhysicsObject():EnableCollisions(true) elseif self.CollisionState == 1 then ent:SetCollisionGroup( COLLISION_GROUP_WORLD ) ent:GetPhysicsObject():EnableCollisions(true) elseif self.CollisionState == 2 then ent:SetCollisionGroup( COLLISION_GROUP_NONE ) ent:GetPhysicsObject():EnableCollisions(false) elseif self.CollisionState == 3 then ent:SetCollisionGroup( COLLISION_GROUP_WEAPON ) ent:GetPhysicsObject():EnableCollisions(true) elseif self.CollisionState == 4 then ent:SetCollisionGroup( COLLISION_GROUP_WEAPON ) ent:GetPhysicsObject():EnableCollisions(false) end end end end self:UpdateOverlay() end local collisionDescriptions = { [0] = "Normal Collisions", [1] = "Disabled prop/player Collisions", [2] = "Disabled prop/world Collisions", [3] = "Disabled player Collisions", [4] = "Disabled prop/world/player Collisions" } function ENT:UpdateOverlay() self:SetOverlayText( (self.State and "Frozen" or "Unfrozen") .. "\n" .. collisionDescriptions[self.CollisionState] .. "\n" .. "Linked Entities: " .. #self.Marks) end function ENT:UpdateOutputs() self:UpdateOverlay() WireLib.SendMarks(self) -- Stool's yellow lines end function ENT:CheckEnt( ent ) if IsValid(ent) then for index, e in pairs( self.Marks ) do if (e == ent) then return true, index end end end return false, 0 end function ENT:LinkEnt( ent ) if (self:CheckEnt( ent )) then return false end self.Marks[#self.Marks+1] = ent ent:CallOnRemove("AdvEMarker.Unlink", function(ent) if IsValid(self) then self:UnlinkEnt(ent) end end) self:UpdateOutputs() return true end function ENT:UnlinkEnt( ent ) local bool, index = self:CheckEnt( ent ) if (bool) then table.remove( self.Marks, index ) self:UpdateOutputs() end return bool end function ENT:ClearEntities() self.Marks = {} self:UpdateOutputs() end duplicator.RegisterEntityClass( "gmod_wire_freezer", WireLib.MakeWireEnt, "Data" ) function ENT:BuildDupeInfo() local info = self.BaseClass.BuildDupeInfo(self) or {} if next(self.Marks) then local tbl = {} for index, e in pairs( self.Marks ) do tbl[index] = e:EntIndex() end info.marks = tbl end return info end function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) if info.Ent1 then -- Old wire-extras dupe support table.insert(self.Marks, GetEntByID(info.Ent1)) end if info.marks then for index, entindex in pairs(info.marks) do self.Marks[index] = GetEntByID(entindex) end end self:TriggerInput("Disable Collisions", self.Inputs["Disable Collisions"].Value) self:UpdateOutputs() end
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Freezer" ENT.WireDebugName = "Freezer" if CLIENT then return end -- No more client function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.State = false self.CollisionState = 0 self.Marks = {} self.Inputs = WireLib.CreateInputs(self, {"Activate", "Disable Collisions"}) self:UpdateOutputs() end function ENT:TriggerInput(name, value) if name == "Activate" then self.State = value ~= 0 for _, ent in pairs(self.Marks) do if IsValid(ent) and IsValid(ent:GetPhysicsObject()) then if self.State then -- Garry's Mod provides an OnPhysgunFreeze hook, which will -- unfreeze the object if prop protection allows it... gamemode.Call("OnPhysgunFreeze", self, ent:GetPhysicsObject(), ent, self:GetPlayer()) else -- ...and a CanPlayerUnfreeze hook, which will return whether -- prop protection allows it, but won't unfreeze do the unfreezing. if not gamemode.Call("CanPlayerUnfreeze", self:GetPlayer(), ent, ent:GetPhysicsObject()) then return end ent:GetPhysicsObject():EnableMotion(true) ent:GetPhysicsObject():Wake() end end end elseif name == "Disable Collisions" then self.CollisionState = math.Clamp(math.Round(value), 0, 4) for _, ent in pairs(self.Marks) do if IsValid(ent) and IsValid(ent:GetPhysicsObject()) and gamemode.Call("CanTool", self:GetPlayer(), WireLib.dummytrace(ent), "nocollide") then if self.CollisionState == 0 then ent:SetCollisionGroup( COLLISION_GROUP_NONE ) ent:GetPhysicsObject():EnableCollisions(true) elseif self.CollisionState == 1 then ent:SetCollisionGroup( COLLISION_GROUP_WORLD ) ent:GetPhysicsObject():EnableCollisions(true) elseif self.CollisionState == 2 then ent:SetCollisionGroup( COLLISION_GROUP_NONE ) ent:GetPhysicsObject():EnableCollisions(false) elseif self.CollisionState == 3 then ent:SetCollisionGroup( COLLISION_GROUP_WEAPON ) ent:GetPhysicsObject():EnableCollisions(true) elseif self.CollisionState == 4 then ent:SetCollisionGroup( COLLISION_GROUP_WEAPON ) ent:GetPhysicsObject():EnableCollisions(false) end end end end self:UpdateOverlay() end local collisionDescriptions = { [0] = "Normal Collisions", [1] = "Disabled prop/player Collisions", [2] = "Disabled prop/world Collisions", [3] = "Disabled player Collisions", [4] = "Disabled prop/world/player Collisions" } function ENT:UpdateOverlay() self:SetOverlayText( (self.State and "Frozen" or "Unfrozen") .. "\n" .. collisionDescriptions[self.CollisionState] .. "\n" .. "Linked Entities: " .. #self.Marks) end function ENT:UpdateOutputs() self:UpdateOverlay() WireLib.SendMarks(self) -- Stool's yellow lines end function ENT:CheckEnt( ent ) if IsValid(ent) then for index, e in pairs( self.Marks ) do if (e == ent) then return true, index end end end return false, 0 end function ENT:LinkEnt( ent ) if (self:CheckEnt( ent )) then return false end self.Marks[#self.Marks+1] = ent ent:CallOnRemove("AdvEMarker.Unlink", function(ent) if IsValid(self) then self:UnlinkEnt(ent) end end) self:UpdateOutputs() return true end function ENT:UnlinkEnt( ent ) local bool, index = self:CheckEnt( ent ) if (bool) then table.remove( self.Marks, index ) self:UpdateOutputs() end return bool end function ENT:ClearEntities() self.Marks = {} self:UpdateOutputs() end duplicator.RegisterEntityClass( "gmod_wire_freezer", WireLib.MakeWireEnt, "Data" ) function ENT:BuildDupeInfo() local info = self.BaseClass.BuildDupeInfo(self) or {} if next(self.Marks) then local tbl = {} for index, e in pairs( self.Marks ) do tbl[index] = e:EntIndex() end info.marks = tbl end return info end function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) if info.Ent1 then -- Old wire-extras dupe support table.insert(self.Marks, GetEntByID(info.Ent1)) end if info.marks then for index, entindex in pairs(info.marks) do self.Marks[index] = GetEntByID(entindex) end end self:TriggerInput("Disable Collisions", self.Inputs["Disable Collisions"].Value) self:UpdateOutputs() end
Fix #545. Freezer now obeys prop protection.
Fix #545. Freezer now obeys prop protection.
Lua
apache-2.0
NezzKryptic/Wire,notcake/wire,plinkopenguin/wiremod,CaptainPRICE/wire,Python1320/wire,rafradek/wire,immibis/wiremod,wiremod/wire,mitterdoo/wire,thegrb93/wire,dvdvideo1234/wire,bigdogmat/wire,garrysmodlua/wire,mms92/wire,Grocel/wire,sammyt291/wire
8899bd346f29636ffaf508a889df8ef059dd31d3
mods/00_bt_armor/throwing/init.lua
mods/00_bt_armor/throwing/init.lua
arrows = { {"throwing:arrow", "throwing:arrow_entity"}, {"throwing:arrow_mithril", "throwing:arrow_mithril_entity"}, {"throwing:arrow_fire", "throwing:arrow_fire_entity"}, {"throwing:arrow_teleport", "throwing:arrow_teleport_entity"}, {"throwing:arrow_dig", "throwing:arrow_dig_entity"}, {"throwing:arrow_build", "throwing:arrow_build_entity"} } local throwing_shoot_arrow = function(itemstack, player) for _,arrow in ipairs(arrows) do if player:get_inventory():get_stack("main", player:get_wield_index()+1):get_name() == arrow[1] then if not minetest.setting_getbool("creative_mode") then player:get_inventory():remove_item("main", arrow[1]) end local playerpos = player:getpos() local obj = minetest.env:add_entity({x=playerpos.x,y=playerpos.y+1.5,z=playerpos.z}, arrow[2]) local dir = player:get_look_dir() obj:setvelocity({x=dir.x*19, y=dir.y*19, z=dir.z*19}) obj:setacceleration({x=dir.x*-3, y=-10, z=dir.z*-3}) obj:setyaw(player:get_look_yaw()+math.pi) minetest.sound_play("throwing_sound", {pos=playerpos}) if obj:get_luaentity().player == "" then obj:get_luaentity().player = player end obj:get_luaentity().node = player:get_inventory():get_stack("main", 1):get_name() return true end end return false end minetest.register_tool("throwing:bow_wood", { description = "Wood Bow", inventory_image = "throwing_bow_wood.png", stack_max = 1, on_use = function(itemstack, user, pointed_thing) if throwing_shoot_arrow(itemstack, user, pointed_thing) then if not minetest.setting_getbool("creative_mode") then itemstack:add_wear(65535/50) end end return itemstack end, }) minetest.register_craft({ output = 'throwing:bow_wood', recipe = { {'farming:string', 'default:wood', ''}, {'farming:string', '', 'default:wood'}, {'farming:string', 'default:wood', ''}, } }) minetest.register_tool("throwing:bow_stone", { description = "Stone Bow", inventory_image = "throwing_bow_stone.png", stack_max = 1, on_use = function(itemstack, user, pointed_thing) if throwing_shoot_arrow(item, user, pointed_thing) then if not minetest.setting_getbool("creative_mode") then itemstack:add_wear(65535/100) end end return itemstack end, }) minetest.register_craft({ output = 'throwing:bow_stone', recipe = { {'farming:string', 'default:cobble', ''}, {'farming:string', '', 'default:cobble'}, {'farming:string', 'default:cobble', ''}, } }) minetest.register_tool("throwing:bow_steel", { description = "Steel Bow", inventory_image = "throwing_bow_steel.png", stack_max = 1, on_use = function(itemstack, user, pointed_thing) if throwing_shoot_arrow(item, user, pointed_thing) then if not minetest.setting_getbool("creative_mode") then itemstack:add_wear(65535/200) end end return itemstack end, }) minetest.register_craft({ output = 'throwing:bow_steel', recipe = { {'farming:string', 'default:steel_ingot', ''}, {'farming:string', '', 'default:steel_ingot'}, {'farming:string', 'default:steel_ingot', ''}, } }) minetest.register_tool("throwing:bow_mithril", { description = "Mithril Bow", inventory_image = "throwing_bow_mithril.png", stack_max = 1, on_use = function(itemstack, user, pointed_thing) if throwing_shoot_arrow(item, user, pointed_thing) then if not minetest.setting_getbool("creative_mode") then itemstack:add_wear(65535/1000) end end return itemstack end, }) minetest.register_craft({ output = 'throwing:bow_mithril', recipe = { {'farming:string', 'moreores:mithril_ingot', ''}, {'farming:string', 'moreores:silver_ingot', 'moreores:mithril_ingot'}, {'farming:string', 'moreores:mithril_ingot', ''}, } }) dofile(minetest.get_modpath("throwing").."/arrow.lua") dofile(minetest.get_modpath("throwing").."/mithril_arrow.lua") dofile(minetest.get_modpath("throwing").."/fire_arrow.lua") dofile(minetest.get_modpath("throwing").."/teleport_arrow.lua") dofile(minetest.get_modpath("throwing").."/dig_arrow.lua") dofile(minetest.get_modpath("throwing").."/build_arrow.lua") if minetest.setting_get("log_mods") then minetest.log("action", "throwing loaded") end
local playerCooldown = {} minetest.register_on_joinplayer(function(player) playerCooldown[player:get_player_name()] = 0.0 end) minetest.register_on_leaveplayer(function(player) playerCooldown[player:get_player_name()] = nil end) arrows = { {"throwing:arrow", "throwing:arrow_entity"}, {"throwing:arrow_mithril", "throwing:arrow_mithril_entity"}, {"throwing:arrow_fire", "throwing:arrow_fire_entity"}, {"throwing:arrow_teleport", "throwing:arrow_teleport_entity"}, {"throwing:arrow_dig", "throwing:arrow_dig_entity"}, {"throwing:arrow_build", "throwing:arrow_build_entity"} } local cooldowns = {} cooldowns["throwing:bow_wood"] = 2.5 cooldowns["throwing:bow_stone"] = 1.5 cooldowns["throwing:bow_steel"] = 0.5 cooldowns["throwing:bow_mithril"] = 0.2 cooldowns["throwing:arrow"] = 0.5 cooldowns["throwing:arrow_mithril"] = 0.2 cooldowns["throwing:arrow_fire"] = 5.0 cooldowns["throwing:arrow_teleport"] = 2.0 cooldowns["throwing:arrow_dig"] = 0.5 cooldowns["throwing:arrow_build"] = 1.0 local throwing_shoot_arrow = function(itemstack, player) if playerCooldown[player:get_player_name()] == 0.0 then local playerpos = player:getpos() if playerpos.x < -31000 or 31000 < playerpos.x or playerpos.y < -31000 or 31000 < playerpos.y or playerpos.x < -31000 or 31000 < playerpos.x then minetest.log("error", "[throwing] "..player:get_player_name().." position out of bounds "..minetest.pos_to_string(playerpos)) return false end for _,arrow in ipairs(arrows) do if player:get_inventory():get_stack("main", player:get_wield_index()+1):get_name() == arrow[1] then if not minetest.setting_getbool("creative_mode") then player:get_inventory():remove_item("main", arrow[1]) end local obj = minetest.env:add_entity({x=playerpos.x,y=playerpos.y+1.5,z=playerpos.z}, arrow[2]) local dir = player:get_look_dir() obj:setvelocity({x=dir.x*19, y=dir.y*19, z=dir.z*19}) obj:setacceleration({x=dir.x*-3, y=-10, z=dir.z*-3}) obj:setyaw(player:get_look_yaw()+math.pi) minetest.sound_play("throwing_sound", {pos=playerpos}) if obj:get_luaentity().player == "" then obj:get_luaentity().player = player end obj:get_luaentity().node = player:get_inventory():get_stack("main", 1):get_name() local bowCooldown = cooldowns[player:get_inventory():get_stack("main", player:get_wield_index()):get_name()] local arrowCooldown = cooldowns[player:get_inventory():get_stack("main", player:get_wield_index()+1):get_name()] local totalCooldown = bowCooldown + arrowCooldown local playername = player:get_player_name() playerCooldown[playername] = totalCooldown minetest.after(totalCooldown, function(playername) if playerCooldown[playername] then playerCooldown[playername] = 0.0 end end, playername) return true end end end return false end minetest.register_tool("throwing:bow_wood", { description = "Wood Bow", inventory_image = "throwing_bow_wood.png", stack_max = 1, on_use = function(itemstack, user, pointed_thing) if throwing_shoot_arrow(itemstack, user, pointed_thing) then if not minetest.setting_getbool("creative_mode") then itemstack:add_wear(65535/50) end end return itemstack end, }) minetest.register_craft({ output = 'throwing:bow_wood', recipe = { {'farming:string', 'default:wood', ''}, {'farming:string', '', 'default:wood'}, {'farming:string', 'default:wood', ''}, } }) minetest.register_tool("throwing:bow_stone", { description = "Stone Bow", inventory_image = "throwing_bow_stone.png", stack_max = 1, on_use = function(itemstack, user, pointed_thing) if throwing_shoot_arrow(item, user, pointed_thing) then if not minetest.setting_getbool("creative_mode") then itemstack:add_wear(65535/100) end end return itemstack end, }) minetest.register_craft({ output = 'throwing:bow_stone', recipe = { {'farming:string', 'default:cobble', ''}, {'farming:string', '', 'default:cobble'}, {'farming:string', 'default:cobble', ''}, } }) minetest.register_tool("throwing:bow_steel", { description = "Steel Bow", inventory_image = "throwing_bow_steel.png", stack_max = 1, on_use = function(itemstack, user, pointed_thing) if throwing_shoot_arrow(item, user, pointed_thing) then if not minetest.setting_getbool("creative_mode") then itemstack:add_wear(65535/200) end end return itemstack end, }) minetest.register_craft({ output = 'throwing:bow_steel', recipe = { {'farming:string', 'default:steel_ingot', ''}, {'farming:string', '', 'default:steel_ingot'}, {'farming:string', 'default:steel_ingot', ''}, } }) minetest.register_tool("throwing:bow_mithril", { description = "Mithril Bow", inventory_image = "throwing_bow_mithril.png", stack_max = 1, on_use = function(itemstack, user, pointed_thing) if throwing_shoot_arrow(item, user, pointed_thing) then if not minetest.setting_getbool("creative_mode") then itemstack:add_wear(65535/1000) end end return itemstack end, }) minetest.register_craft({ output = 'throwing:bow_mithril', recipe = { {'farming:string', 'moreores:mithril_ingot', ''}, {'farming:string', 'moreores:silver_ingot', 'moreores:mithril_ingot'}, {'farming:string', 'moreores:mithril_ingot', ''}, } }) dofile(minetest.get_modpath("throwing").."/arrow.lua") dofile(minetest.get_modpath("throwing").."/mithril_arrow.lua") dofile(minetest.get_modpath("throwing").."/fire_arrow.lua") dofile(minetest.get_modpath("throwing").."/teleport_arrow.lua") dofile(minetest.get_modpath("throwing").."/dig_arrow.lua") dofile(minetest.get_modpath("throwing").."/build_arrow.lua") if minetest.setting_get("log_mods") then minetest.log("action", "throwing loaded") end
Fixed out of bounds bug and added a cooldown so you can no longer spam fire arrows
Fixed out of bounds bug and added a cooldown so you can no longer spam fire arrows
Lua
lgpl-2.1
evrooije/beerarchy,evrooije/beerarchy,evrooije/beerarchy
625567775e43677b305df3da0fbbe6c7361a2b3e
nvim/lua/lsp.lua
nvim/lua/lsp.lua
vim.api.nvim_command('echo "Hello, Nvim!"') local nvim_lsp = require('lspconfig') local on_attach = function(client, bufnr) local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(bufnr, ...) end local function buf_set_option(...) vim.api.nvim_buf_set_option(bufnr, ...) end buf_set_option('omnifunc', 'v:lua.vim.lsp.omnifunc') -- Mappings. local opts = { noremap=true, silent=true } buf_set_keymap('n', 'gD', '<Cmd>lua vim.lsp.buf.declaration()<CR>', opts) buf_set_keymap('n', 'gd', '<Cmd>lua vim.lsp.buf.definition()<CR>', opts) buf_set_keymap('n', 'K', '<Cmd>lua vim.lsp.buf.hover()<CR>', opts) buf_set_keymap('n', 'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', opts) buf_set_keymap('n', '<C-k>', '<cmd>lua vim.lsp.buf.signature_help()<CR>', opts) buf_set_keymap('n', '<space>wa', '<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>', opts) buf_set_keymap('n', '<space>wr', '<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>', opts) buf_set_keymap('n', '<space>wl', '<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>', opts) buf_set_keymap('n', '<space>D', '<cmd>lua vim.lsp.buf.type_definition()<CR>', opts) buf_set_keymap('n', '<space>rn', '<cmd>lua vim.lsp.buf.rename()<CR>', opts) buf_set_keymap('n', 'gr', '<cmd>lua vim.lsp.buf.references()<CR>', opts) buf_set_keymap('n', '<space>e', '<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>', opts) buf_set_keymap('n', '[d', '<cmd>lua vim.lsp.diagnostic.goto_prev()<CR>', opts) buf_set_keymap('n', ']d', '<cmd>lua vim.lsp.diagnostic.goto_next()<CR>', opts) buf_set_keymap('n', '<space>q', '<cmd>lua vim.lsp.diagnostic.set_loclist()<CR>', opts) -- Set some keybinds conditional on server capabilities if client.resolved_capabilities.document_formatting then buf_set_keymap("n", "<space>f", "<cmd>lua vim.lsp.buf.formatting()<CR>", opts) elseif client.resolved_capabilities.document_range_formatting then buf_set_keymap("n", "<space>f", "<cmd>lua vim.lsp.buf.formatting()<CR>", opts) end -- Set autocommands conditional on server_capabilities if client.resolved_capabilities.document_highlight then vim.api.nvim_exec([[ hi LspReferenceRead cterm=bold ctermbg=red guibg=LightYellow hi LspReferenceText cterm=bold ctermbg=red guibg=LightYellow hi LspReferenceWrite cterm=bold ctermbg=red guibg=LightYellow augroup lsp_document_highlight autocmd! autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight() autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references() augroup END ]], false) end end -- Use a loop to conveniently both setup defined servers -- and map buffer local keybindings when the language server attaches local servers = { "solargraph" } for _, lsp in ipairs(servers) do nvim_lsp[lsp].setup { on_attach = on_attach } end vim.cmd [[autocmd CursorHold,CursorHoldI * lua require'nvim-lightbulb'.update_lightbulb()]]
vim.api.nvim_command('echo "Hello, Nvim!"') local nvim_lsp = require('lspconfig') local on_attach = function(client, bufnr) local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(bufnr, ...) end local function buf_set_option(...) vim.api.nvim_buf_set_option(bufnr, ...) end buf_set_option('omnifunc', 'v:lua.vim.lsp.omnifunc') -- Mappings. local opts = { noremap=true, silent=true } buf_set_keymap('n', 'gD', '<Cmd>lua vim.lsp.buf.declaration()<CR>', opts) buf_set_keymap('n', 'gd', '<Cmd>lua vim.lsp.buf.definition()<CR>', opts) buf_set_keymap('n', 'K', '<Cmd>lua vim.lsp.buf.hover()<CR>', opts) buf_set_keymap('n', 'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', opts) buf_set_keymap('n', '<C-k>', '<cmd>lua vim.lsp.buf.signature_help()<CR>', opts) buf_set_keymap('n', '<space>wa', '<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>', opts) buf_set_keymap('n', '<space>wr', '<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>', opts) -- I don't use this one and it interferes with the use I give it (navigating splits) -- buf_set_keymap('n', '<space>wl', '<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>', opts) buf_set_keymap('n', '<space>D', '<cmd>lua vim.lsp.buf.type_definition()<CR>', opts) buf_set_keymap('n', '<space>rn', '<cmd>lua vim.lsp.buf.rename()<CR>', opts) buf_set_keymap('n', 'gr', '<cmd>lua vim.lsp.buf.references()<CR>', opts) buf_set_keymap('n', '<space>e', '<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>', opts) buf_set_keymap('n', '[d', '<cmd>lua vim.lsp.diagnostic.goto_prev()<CR>', opts) buf_set_keymap('n', ']d', '<cmd>lua vim.lsp.diagnostic.goto_next()<CR>', opts) buf_set_keymap('n', '<space>q', '<cmd>lua vim.lsp.diagnostic.set_loclist()<CR>', opts) -- Set some keybinds conditional on server capabilities if client.resolved_capabilities.document_formatting then buf_set_keymap("n", "<space>f", "<cmd>lua vim.lsp.buf.formatting()<CR>", opts) elseif client.resolved_capabilities.document_range_formatting then buf_set_keymap("n", "<space>f", "<cmd>lua vim.lsp.buf.formatting()<CR>", opts) end -- I don't want auto highlighting -- -- Set autocommands conditional on server_capabilities -- if client.resolved_capabilities.document_highlight then -- vim.api.nvim_exec([[ -- hi LspReferenceRead cterm=bold ctermbg=red guibg=LightYellow -- hi LspReferenceText cterm=bold ctermbg=red guibg=LightYellow -- hi LspReferenceWrite cterm=bold ctermbg=red guibg=LightYellow -- augroup lsp_document_highlight -- autocmd! -- autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight() -- autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references() -- augroup END -- ]], false) -- end end -- Use a loop to conveniently both setup defined servers -- and map buffer local keybindings when the language server attaches local servers = { "solargraph", "flow" } nvim_lsp["solargraph"].setup { on_attach = on_attach } nvim_lsp["flow"].setup { on_attach = on_attach, cmd = { "./node_modules/.bin/flow", "lsp" } } vim.cmd [[autocmd CursorHold,CursorHoldI * lua require'nvim-lightbulb'.update_lightbulb()]]
+fix: improve LSP config a bit
+fix: improve LSP config a bit Add flow and remove some stuff that was more annoying than helpful
Lua
mit
franciscoj/dot-files,franciscoj/dot-files,franciscoj/dot-files
35eec07d55e7ed36e05f894bf6f7f65162841ff9
modules/title/post/olds.lua
modules/title/post/olds.lua
local sql = require'lsqlite3' local date = require'date' local patterns = { -- X://Y url "^(https?://%S+)", "^<(https?://%S+)>", "%f[%S](https?://%S+)", -- www.X.Y url "^(www%.[%w_-%%]+%.%S+)", "%f[%S](www%.[%w_-%%]+%.%S+)", } local openDB = function() local dbfilename = string.format("cache/urls.%s.sql", ivar2.network) local db = sql.open(dbfilename) db:exec([[ CREATE TABLE IF NOT EXISTS urls ( nick text, timestamp integer, url text, channel text ); ]]) return db end -- check for existing url local checkOld = function(source, destination, url) local db = openDB() -- create a select handle local sth = db:prepare([[ SELECT nick, timestamp FROM urls WHERE url=? AND channel=? ORDER BY timestamp ASC ]]) -- execute select with a url bound to variable sth:bind_values(url, destination) local count, first = 0 while(sth:step() == sql.ROW) do count = count + 1 if(count == 1) then first = sth:get_named_values() end end sth:finalize() db:close() if(count > 0) then local age = date.relativeTimeShort(first.timestamp) return first.nick, count, age end end local updateDB = function(source, destination, url) local db = openDB() local sth = db:prepare[[ INSERT INTO urls(nick, channel, url, timestamp) values(?, ?, ?, ?) ]] sth:bind_values(source.nick, destination, url, os.time()) sth:step() sth:finalize() end do return function(source, destination, queue) local nick, count, age = checkOld(source, destination, queue.url) updateDB(source, destination, queue.url) -- relativeTimeShort() returns nil if it gets fed os.time(). if(not age) then return end local prepend if(count > 1) then prepend = string.format("Old! %s times, first by %s %s ago", count, nick, age) else prepend = string.format("Old! Linked by %s %s ago", nick, age) end if(queue.output) then queue.output = string.format("%s - %s", prepend, queue.output) else queue.output = prepend end end end
local sql = require'lsqlite3' local date = require'date' local uri = require"handler.uri" local uri_parse = uri.parse local patterns = { -- X://Y url "^(https?://%S+)", "^<(https?://%S+)>", "%f[%S](https?://%S+)", -- www.X.Y url "^(www%.[%w_-%%]+%.%S+)", "%f[%S](www%.[%w_-%%]+%.%S+)", } local openDB = function() local dbfilename = string.format("cache/urls.%s.sql", ivar2.network) local db = sql.open(dbfilename) db:exec([[ CREATE TABLE IF NOT EXISTS urls ( nick text, timestamp integer, url text, channel text ); ]]) return db end -- check for existing url local checkOld = function(source, destination, url) -- Don't lookup root path URLs. local info = uri_parse(url) if(info.path == '' or info.path == '/') then return end local db = openDB() -- create a select handle local sth = db:prepare([[ SELECT nick, timestamp FROM urls WHERE url=? AND channel=? ORDER BY timestamp ASC ]]) -- execute select with a url bound to variable sth:bind_values(url, destination) local count, first = 0 while(sth:step() == sql.ROW) do count = count + 1 if(count == 1) then first = sth:get_named_values() end end sth:finalize() db:close() if(count > 0) then local age = date.relativeTimeShort(first.timestamp) return first.nick, count, age end end local updateDB = function(source, destination, url) local db = openDB() local sth = db:prepare[[ INSERT INTO urls(nick, channel, url, timestamp) values(?, ?, ?, ?) ]] sth:bind_values(source.nick, destination, url, os.time()) sth:step() sth:finalize() end do return function(source, destination, queue) local nick, count, age = checkOld(source, destination, queue.url) updateDB(source, destination, queue.url) -- relativeTimeShort() returns nil if it gets fed os.time(). if(not age) then return end local prepend if(count > 1) then prepend = string.format("Old! %s times, first by %s %s ago", count, nick, age) else prepend = string.format("Old! Linked by %s %s ago", nick, age) end if(queue.output) then queue.output = string.format("%s - %s", prepend, queue.output) else queue.output = prepend end end end
title/olds: Don't lookup rooth path URLs.
title/olds: Don't lookup rooth path URLs. Fixes #46.
Lua
mit
torhve/ivar2,torhve/ivar2,haste/ivar2,torhve/ivar2
0a9a0bc02ee2133b440920a475c88a4f2c64c483
fbtorch.lua
fbtorch.lua
-- Copyright 2004-present Facebook. All Rights Reserved. -- Always line-buffer stdout because we want our logs not to be slow, even -- if they are redirected. io.stdout:setvbuf('line') local pl = require('pl.import_into')() local util = require('fb.util') require 'totem' -- Compatibility stuff, LuaJIT in 5.2 compat mode has renamed string.gfind -- to string.gmatch if string.gfind == nil then string.gfind = string.gmatch end -- sys.clock is broken, broken, broken! local sys = require('sys') sys.clock = util.time local timer_start local function tic() timer_start = util.monotonic_clock() end sys.tic = tic local function toc(verbose) local duration = util.monotonic_clock() - timer_start if verbose then print(duration) end return duration end sys.toc = toc -- Load C extension which loads torch and sets up error handlers local torch = require('fbtorch_ext') -- OMP tends to badly hurt performance on our multi-die multi-core NUMA -- machines, so it's off by default. Turn it on with extreme care, and -- benchmark, benchmark, benchmark -- check "user time", not just "wall -- time", since you might be inadvertently wasting a ton of CPU for a -- negligible wall-clock speedup. For context, read this thread: -- https://fb.facebook.com/groups/709562465759038/874071175974832 local env_threads = os.getenv('OMP_NUM_THREADS') if env_threads == nil or env_threads == '' then torch.setnumthreads(1) end if LuaUnit then -- modify torch.Tester and totem.Tester to use our own flavor of LuaUnit torch.Tester.assert_sub = function(self, condition, message) if not condition then error(message) end end torch.Tester.run = function(self, run_tests) local tests, testnames tests = self.tests testnames = self.testnames if type(run_tests) == 'string' then run_tests = {run_tests} end if type(run_tests) == 'table' then tests = {} testnames = {} for i,fun in ipairs(self.tests) do for j,name in ipairs(run_tests) do if self.testnames[i] == name then tests[#tests+1] = self.tests[i] testnames[#testnames+1] = self.testnames[i] end end end end -- global TestTorch = {} for i,fun in ipairs(tests) do local name = testnames[i] TestTorch['test_' .. name] = fun end -- LuaUnit will run tests (functions whose names start with 'test') -- from all globals whose names start with 'Test' LuaUnit:run() end totem.Tester._assert_sub = torch.Tester.assert_sub totem.Tester._success = function() end totem.Tester._failure = function() end totem.Tester.run = function(self, run_tests) local tests = self.tests if type(run_tests) == 'string' then run_tests = {run_tests} end if type(run_tests) == 'table' then tests = {} for j, name in ipairs(run_tests) do if self.tests[name] then tests[name] = self.tests[name] end end end -- global TestTotem = tests -- LuaUnit will run tests (functions whose names start with 'test') -- from all globals whose names start with 'Test' LuaUnit:run() end end if os.getenv('LUA_DEBUG') then require('fb.debugger').enter() end -- reload: unload a module and re-require it local function reload(mod, ...) package.loaded[mod] = nil return require(mod, ...) end torch.reload = reload return torch
-- Copyright 2004-present Facebook. All Rights Reserved. -- Always line-buffer stdout because we want our logs not to be slow, even -- if they are redirected. io.stdout:setvbuf('line') local pl = require('pl.import_into')() local util = require('fb.util') require 'totem' -- Compatibility stuff, LuaJIT in 5.2 compat mode has renamed string.gfind -- to string.gmatch if string.gfind == nil then string.gfind = string.gmatch end -- sys.clock is broken, broken, broken! local sys = require('sys') sys.clock = util.time local timer_start local function tic() timer_start = util.monotonic_clock() end sys.tic = tic local function toc(verbose) local duration = util.monotonic_clock() - timer_start if verbose then print(duration) end return duration end sys.toc = toc -- Load C extension which loads torch and sets up error handlers local torch = require('fbtorch_ext') -- OMP tends to badly hurt performance on our multi-die multi-core NUMA -- machines, so it's off by default. Turn it on with extreme care, and -- benchmark, benchmark, benchmark -- check "user time", not just "wall -- time", since you might be inadvertently wasting a ton of CPU for a -- negligible wall-clock speedup. For context, read this thread: -- https://fb.facebook.com/groups/709562465759038/874071175974832 local env_threads = os.getenv('OMP_NUM_THREADS') if env_threads == nil or env_threads == '' then torch.setnumthreads(1) end if LuaUnit then -- modify torch.Tester and totem.Tester to use our own flavor of LuaUnit torch.Tester._assert_sub = function(self, condition, message) if not condition then error(message) end end torch.Tester.run = function(self, run_tests) local tests, testnames tests = self.tests testnames = self.testnames if type(run_tests) == 'string' then run_tests = {run_tests} end if type(run_tests) == 'table' then tests = {} testnames = {} for i,fun in ipairs(self.tests) do for j,name in ipairs(run_tests) do if self.testnames[i] == name then tests[#tests+1] = self.tests[i] testnames[#testnames+1] = self.testnames[i] end end end end -- global TestTorch = {} for name,fun in pairs(tests) do TestTorch['test_' .. name] = fun end -- LuaUnit will run tests (functions whose names start with 'test') -- from all globals whose names start with 'Test' LuaUnit:run() end totem.Tester._assert_sub = torch.Tester._assert_sub totem.Tester._success = function() end totem.Tester._failure = function(message) error(message) end totem.Tester.run = function(self, run_tests) local tests = self.tests if type(run_tests) == 'string' then run_tests = {run_tests} end if type(run_tests) == 'table' then tests = {} for j, name in ipairs(run_tests) do if self.tests[name] then tests[name] = self.tests[name] end end end -- global TestTotem = tests -- LuaUnit will run tests (functions whose names start with 'test') -- from all globals whose names start with 'Test' LuaUnit:run() end end if os.getenv('LUA_DEBUG') then require('fb.debugger').enter() end -- reload: unload a module and re-require it local function reload(mod, ...) package.loaded[mod] = nil return require(mod, ...) end torch.reload = reload return torch
fix torch Tester integration with fbtorch/luaunit (which OSS pull broke)
fix torch Tester integration with fbtorch/luaunit (which OSS pull broke) Summary:torch.Tester was rewritten; needed to fix fbtorch integration. FYI I think the new torch Tester regressed my changes that put tests in alphabetical order; need to fix in OSS. Reviewed By: soumith Differential Revision: D3121559 fb-gh-sync-id: 322ca881f3e95b85e051e023340ca58427945548 fbshipit-source-id: 322ca881f3e95b85e051e023340ca58427945548
Lua
bsd-3-clause
facebook/fbtorch
00b7d21f165195ecc556ebd3524b67939b85aed3
spec/util/fromFasta_spec.lua
spec/util/fromFasta_spec.lua
-- lua-npge, Nucleotide PanGenome explorer (Lua module) -- Copyright (C) 2014-2015 Boris Nagaev -- See the LICENSE file for terms of use. describe("npge.util.fromFasta", function() it("parses fasta representation", function() local fromFasta = require 'npge.util.fromFasta' local fasta = [[ >foo descr ATGC >bar several words AAA TTT]] local textToIt = require 'npge.util.textToIt' local lines = textToIt(fasta) local parser = fromFasta(lines) local foo_name, foo_descr, foo_text = parser() assert.truthy(foo_name, "foo") assert.truthy(foo_descr, "descr") assert.truthy(foo_text, "ATGC") local bar_name, bar_descr, bar_text = parser() assert.truthy(bar_name, "bar") assert.truthy(bar_descr, "several words") assert.truthy(bar_text, "AAATTT") end) end)
-- lua-npge, Nucleotide PanGenome explorer (Lua module) -- Copyright (C) 2014-2015 Boris Nagaev -- See the LICENSE file for terms of use. describe("npge.util.fromFasta", function() it("parses fasta representation", function() local fromFasta = require 'npge.util.fromFasta' local fasta = [[ >foo descr ATGC >bar several words AAA TTT]] local textToIt = require 'npge.util.textToIt' local lines = textToIt(fasta) local parser = fromFasta(lines) local foo_name, foo_descr, foo_text = parser() assert.equal(foo_name, "foo") assert.equal(foo_descr, "descr") assert.equal(foo_text, "ATGC") local bar_name, bar_descr, bar_text = parser() assert.equal(bar_name, "bar") assert.equal(bar_descr, "several words") assert.equal(bar_text, "AAATTT") end) end)
fix test (assert.equal instead of asset.truthy)
fix test (assert.equal instead of asset.truthy)
Lua
mit
npge/lua-npge,npge/lua-npge,starius/lua-npge,npge/lua-npge,starius/lua-npge,starius/lua-npge
2c446cbe7da4bda4cd5913daaa06b0dd99b6a90e
packages/pirania/files/usr/lib/lua/voucher/vouchera.lua
packages/pirania/files/usr/lib/lua/voucher/vouchera.lua
#!/bin/lua local store = require('voucher.store') local config = require('voucher.config') local utils = require('voucher.utils') local vouchera = {} local ID_SIZE = 6 --! Simplify the comparison of vouchers using a metatable for the == operator local voucher_metatable = { __eq = function(self, value) return self.tostring() == value.tostring() end } --! obj attrs id, name, code, mac, expiration_date, duration_m, mod_counter function voucher_init(obj) local voucher = {} if not obj.id then obj.id = utils.random_string(ID_SIZE) end voucher.id = obj.id if type(obj.id) ~= "string" then return nil, "id must be a string" end voucher.name = obj.name if type(obj.code) ~= "string" then return nil, "code must be a string" end voucher.code = obj.code if type(obj.mac) == "string" and #obj.mac ~= 17 then return nil, "invalid mac" end voucher.mac = obj.mac if obj.expiration_date == nil and obj.duration_m == nil then return nil elseif obj.expiration_date ~= nil then voucher.expiration_date = obj.expiration_date elseif obj.duration_m ~= nil then voucher.duration_m = obj.duration_m end voucher.mod_counter = obj.mod_counter or 1 --! tostring must reflect all the state of a voucher (so vouchers can be compared reliably using tostring) voucher.tostring = function() local v = voucher return(string.format('%s\t%s\t%s\t%s\t%s\t%s\t%s', v.id, v.name, v.code, v.mac or 'xx:xx:xx:xx:xx:xx', os.date("%c", v.expiration_date) or '', tostring(v.duration_m), v.mod_counter)) end setmetatable(voucher, voucher_metatable) return voucher end function vouchera.init(cfg) if cfg ~= nil then config = cfg end vouchera.config = config vouchera.PRUNE_OLDER_THAN_S = tonumber(config.prune_expired_for_days) * 60 * 60 * 24 vouchera.vouchers = store.load_db(config.db_path, voucher_init) --! Automatic voucher pruning for _, voucher in pairs(vouchera.vouchers) do if vouchera.should_be_pruned(voucher) then vouchera.remove_locally(voucher.id) end end end function vouchera.add(obj) local voucher = voucher_init(obj) if vouchera.vouchers[obj.id] ~= nil then return nil, "voucher with same id already exists" end if voucher and store.add_voucher(config.db_path, voucher, voucher_init) then vouchera.vouchers[obj.id] = voucher return voucher end return nil, "can't create voucher" end --! Remove a voucher from the local db. This won't trigger a remove in the shared db. function vouchera.remove_locally(id) if vouchera.vouchers[id] ~= nil then if store.remove_voucher(config.db_path, vouchera.vouchers[id]) then vouchera.vouchers[id] = nil return true else return nil, "can't remove voucher" end end return nil, "can't find voucher to remove" end --! Remove a voucher from the shared db. --! Deactivates the voucher, sets the expiration_date to the current time and increment the mod_counter. --! This will eventualy prune the voucher in all the dbs after PRUNE_OLDER_THAN_S seconds. --! It is important to maintain the "removed" (deactivated) voucher in the shared db for some time --! so that all nodes (even nodes that are offline when this is executed) have time to update locally --! and eventualy prune the voucher. function vouchera.remove_globally(name) local voucher = vouchera.vouchers[name] if voucher then voucher.expiration_date = os.time() voucher.mac = nil voucher.mod_counter = voucher.mod_counter + 1 return store.add_voucher(config.db_path, voucher, voucher_init) end return voucher end --! Activate a voucher returning true or false depending on the status of the operation. function vouchera.activate(code, mac) local voucher = vouchera.is_activable(code) if voucher then voucher.mac = mac --! If the voucher has a duration then create the expiration_date from it if voucher.duration_m then voucher.expiration_date = os.time() + duration_m * 60 end voucher.mod_counter = voucher.mod_counter + 1 store.add_voucher(config.db_path, voucher, voucher_init) end return voucher end function vouchera.deactivate(id) local voucher = vouchera.vouchers[id] if voucher then voucher.mac = nil voucher.mod_counter = voucher.mod_counter + 1 return store.add_voucher(config.db_path, voucher, voucher_init) end return voucher end --! updates the database with the new voucher information function vouchera.update_with(voucher) vouchera.vouchers[voucher.id] = voucher return store.add_voucher(config.db_path, voucher, voucher_init) end --! Return true if there is an activated voucher that grants a access to the specified MAC function vouchera.is_mac_authorized(mac) if mac ~= nil then for k, v in pairs(vouchera.vouchers) do if v.mac == mac and vouchera.is_active(v) then return true end end end return false end --! Check if a code would be good to be activated but without activating it right away. function vouchera.is_activable(code) for k, v in pairs(vouchera.vouchers) do if v.code == code and v.mac == nil then if v.expiration_date ~= nil and v.expiration_date > os.time() then return v end return v end end return false end function vouchera.is_active(voucher) return voucher.mac ~= nil and voucher.expiration_date > os.time() end function vouchera.should_be_pruned(voucher) return voucher.expiration_date >= (os.time() + vouchera.PRUNE_OLDER_THAN_S) end function vouchera.update_expiration_date(id, new_date) local voucher = vouchera.vouchers[id] if voucher then voucher.expiration_date = new_date voucher.mod_counter = voucher.mod_counter + 1 return store.add_voucher(config.db_path, voucher, voucher_init) end return voucher end vouchera.voucher = voucher_init return vouchera
#!/bin/lua local store = require('voucher.store') local config = require('voucher.config') local utils = require('voucher.utils') local vouchera = {} local ID_SIZE = 6 --! Simplify the comparison of vouchers using a metatable for the == operator local voucher_metatable = { __eq = function(self, value) return self.tostring() == value.tostring() end } --! obj attrs id, name, code, mac, expiration_date, duration_m, mod_counter function voucher_init(obj) local voucher = {} if not obj.id then obj.id = utils.random_string(ID_SIZE) end voucher.id = obj.id if type(obj.id) ~= "string" then return nil, "id must be a string" end voucher.name = obj.name if type(obj.code) ~= "string" then return nil, "code must be a string" end voucher.code = obj.code if type(obj.mac) == "string" and #obj.mac ~= 17 then return nil, "invalid mac" end voucher.mac = obj.mac if obj.expiration_date == nil and obj.duration_m == nil then return nil elseif obj.expiration_date ~= nil then voucher.expiration_date = obj.expiration_date elseif obj.duration_m ~= nil then voucher.duration_m = obj.duration_m end voucher.mod_counter = obj.mod_counter or 1 --! tostring must reflect all the state of a voucher (so vouchers can be compared reliably using tostring) voucher.tostring = function() local v = voucher return(string.format('%s\t%s\t%s\t%s\t%s\t%s\t%s', v.id, v.name, v.code, v.mac or 'xx:xx:xx:xx:xx:xx', os.date("%c", v.expiration_date) or '', tostring(v.duration_m), v.mod_counter)) end setmetatable(voucher, voucher_metatable) return voucher end function vouchera.init(cfg) if cfg ~= nil then config = cfg end vouchera.config = config vouchera.PRUNE_OLDER_THAN_S = tonumber(config.prune_expired_for_days) * 60 * 60 * 24 vouchera.vouchers = store.load_db(config.db_path, voucher_init) --! Automatic voucher pruning for _, voucher in pairs(vouchera.vouchers) do if vouchera.should_be_pruned(voucher) then vouchera.remove_locally(voucher.id) end end end function vouchera.add(obj) local voucher = voucher_init(obj) if vouchera.vouchers[obj.id] ~= nil then return nil, "voucher with same id already exists" end if voucher and store.add_voucher(config.db_path, voucher, voucher_init) then vouchera.vouchers[obj.id] = voucher return voucher end return nil, "can't create voucher" end --! Remove a voucher from the local db. This won't trigger a remove in the shared db. function vouchera.remove_locally(id) if vouchera.vouchers[id] ~= nil then if store.remove_voucher(config.db_path, vouchera.vouchers[id]) then vouchera.vouchers[id] = nil return true else return nil, "can't remove voucher" end end return nil, "can't find voucher to remove" end --! Remove a voucher from the shared db. --! Deactivates the voucher, sets the expiration_date to the current time and increment the mod_counter. --! This will eventualy prune the voucher in all the dbs after PRUNE_OLDER_THAN_S seconds. --! It is important to maintain the "removed" (deactivated) voucher in the shared db for some time --! so that all nodes (even nodes that are offline when this is executed) have time to update locally --! and eventualy prune the voucher. function vouchera.remove_globally(name) local voucher = vouchera.vouchers[name] if voucher then voucher.expiration_date = os.time() voucher.mac = nil voucher.mod_counter = voucher.mod_counter + 1 return store.add_voucher(config.db_path, voucher, voucher_init) end return voucher end --! Activate a voucher returning true or false depending on the status of the operation. function vouchera.activate(code, mac) local voucher = vouchera.is_activable(code) if voucher then voucher.mac = mac --! If the voucher has a duration then create the expiration_date from it if voucher.duration_m then voucher.expiration_date = os.time() + voucher.duration_m * 60 end voucher.mod_counter = voucher.mod_counter + 1 store.add_voucher(config.db_path, voucher, voucher_init) end return voucher end function vouchera.deactivate(id) local voucher = vouchera.vouchers[id] if voucher then voucher.mac = nil voucher.mod_counter = voucher.mod_counter + 1 return store.add_voucher(config.db_path, voucher, voucher_init) end return voucher end --! updates the database with the new voucher information function vouchera.update_with(voucher) vouchera.vouchers[voucher.id] = voucher return store.add_voucher(config.db_path, voucher, voucher_init) end --! Return true if there is an activated voucher that grants a access to the specified MAC function vouchera.is_mac_authorized(mac) if mac ~= nil then for k, v in pairs(vouchera.vouchers) do if v.mac == mac and vouchera.is_active(v) then return true end end end return false end --! Check if a code would be good to be activated but without activating it right away. function vouchera.is_activable(code) for k, v in pairs(vouchera.vouchers) do if v.code == code and v.mac == nil then if v.expiration_date ~= nil and v.expiration_date > os.time() then return v end return v end end return false end function vouchera.is_active(voucher) return voucher.mac ~= nil and voucher.expiration_date > os.time() end function vouchera.should_be_pruned(voucher) return type(voucher.expiration_date) == "number" and ( voucher.expiration_date <= (os.time() - vouchera.PRUNE_OLDER_THAN_S)) end function vouchera.update_expiration_date(id, new_date) local voucher = vouchera.vouchers[id] if voucher then voucher.expiration_date = new_date voucher.mod_counter = voucher.mod_counter + 1 return store.add_voucher(config.db_path, voucher, voucher_init) end return voucher end vouchera.voucher = voucher_init return vouchera
pirania: fix pruning
pirania: fix pruning
Lua
agpl-3.0
libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages
6aaefa0f24d4a44b6e8a37e3dba76876d24879f3
tweak/scripts/rweichler/include/icon_random.lua
tweak/scripts/rweichler/include/icon_random.lua
local rand = nil local view_order = nil local function randomize(tbl) --use the same random seed every time if not rand then rand = math.random(1, 8297094) end for i=1,#tbl-1 do local rand_index = i + rand % (#tbl - i + 1) local tmp = tbl[i] tbl[i] = tbl[rand_index] tbl[rand_index] = tmp end end local function init(len) if not view_order or len > #view_order then view_order = {} for i=1,len do table.insert(view_order, i) end randomize(view_order) end end local function make_progress_table(mag, max) if mag < 1/max then mag = 1/max end if mag > 1 then mag = 1 end local inc = (1 - mag)/(max - 1) local first = mag/2 local tbl = {} for i=0,max-1 do table.insert(tbl, first + inc*i) end return tbl end return function(page, percent, mag, callback) init(#page) local max = #view_order local negative = percent < 0 if negative then percent = -percent end local progress_table = make_progress_table(mag, max) for i, prog in ipairs(progress_table) do if negative then i = #progress_table - i + 1 end local icon = page[view_order[i]] if not icon then elseif percent < prog - mag/2 then callback(icon, 0) elseif percent > prog + mag/2 then callback(icon, negative and -1 or 1) else local p = (percent - prog + mag/2)/mag if negative then p = -p end callback(icon, p) end end end
local rand = nil local view_order = nil local function randomize(tbl) --use the same random seed every time if not rand then rand = math.random(1, 8297094) end for i=1,#tbl-1 do local rand_index = i + rand % (#tbl - i + 1) local tmp = tbl[i] tbl[i] = tbl[rand_index] tbl[rand_index] = tmp end end local function init(len) if not view_order or len > #view_order then view_order = {} for i=1,len do table.insert(view_order, i) end randomize(view_order) end end local function make_progress_table(mag, max) local inc = (1 - mag)/(max - 1) local first = mag/2 local tbl = {} for i=0,max-1 do table.insert(tbl, first + inc*i) end return tbl end return function(page, percent, mag, callback) init(#page) local max = #view_order if mag < 1/max then mag = 1/max end if mag > 1 then mag = 1 end local negative = percent < 0 if negative then percent = -percent end local progress_table = make_progress_table(mag, max) for i, prog in ipairs(progress_table) do if negative then i = #progress_table - i + 1 end local icon = page[view_order[i]] if not icon then elseif percent < prog - mag/2 then callback(icon, 0) elseif percent > prog + mag/2 then callback(icon, negative and -1 or 1) else local p = (percent - prog + mag/2)/mag if negative then p = -p end callback(icon, p) end end end
small bugfix for icon_random
small bugfix for icon_random
Lua
mit
rweichler/cylinder,rweichler/cylinder,rweichler/cylinder
68611204180b92c046a93b17dc217a8dff9211a6
nvim/nvim/lua/_/statusline.lua
nvim/nvim/lua/_/statusline.lua
local utils = require '_.utils' local M = {} --------------------------------------------------------------------------------- -- Helpers --------------------------------------------------------------------------------- -- display lineNoIndicator (from drzel/vim-line-no-indicator) local function line_no_indicator() local line_no_indicator_chars = { ' ', '▁', '▂', '▃', '▄', '▅', '▆', '▇', '█' } local current_line = vim.fn.line('.') local total_lines = vim.fn.line('$') local index = current_line if current_line == 1 then index = 1 elseif current_line == total_lines then index = #line_no_indicator_chars else local line_no_fraction = math.floor(current_line) / math.floor(total_lines) index = math.ceil(line_no_fraction * #line_no_indicator_chars) end return line_no_indicator_chars[index] end --------------------------------------------------------------------------------- -- Main functions --------------------------------------------------------------------------------- function M.lsp_status() if not vim.tbl_isempty(vim.lsp.buf_get_clients()) then local line = [[%5*%{luaeval("require'lsp-status'.status_errors()")}]] line = line .. [[ %6*%{luaeval("require'lsp-status'.status_warnings()")}]] line = line .. [[ %7*%{luaeval("require'lsp-status'.status_hints()")}]] line = line .. [[ %8*%{luaeval("require'lsp-status'.status_info()")}]] return line end return '' end function M.git_info() if not vim.g.loaded_fugitive then return '' end local out = vim.fn.FugitiveHead(10) if out ~= '' then out = utils.get_icon('branch') .. ' ' .. out end return out end function M.update_filepath_highlights() if vim.bo.modified then vim.cmd('hi! link StatusLineFilePath DiffChange') vim.cmd('hi! link StatusLineNewFilePath DiffChange') else vim.cmd('hi! link StatusLineFilePath User6') vim.cmd('hi! link StatusLineNewFilePath User4') end return '' end function M.get_filepath_parts() local base = vim.fn.expand('%:~:.:h') local filename = vim.fn.expand('%:~:.:t') local prefix = (vim.fn.empty(base) == 1 or base == '.') and '' or base .. '/' return {base, filename, prefix} end function M.filepath() local parts = M.get_filepath_parts() local prefix = parts[3] local filename = parts[2] local line = [[%{luaeval("require'_.statusline'.get_filepath_parts()[3]")}]] line = line .. '%*' line = line .. [[%{luaeval("require'_.statusline'.update_filepath_highlights()")}]] line = line .. '%#StatusLineFilePath#' line = line .. [[%{luaeval("require'_.statusline'.get_filepath_parts()[2]")}]] if vim.fn.empty(prefix) == 1 and vim.fn.empty(filename) == 1 then line = [[%{luaeval("require'_.statusline'.update_filepath_highlights()")}]] line = line .. '%#StatusLineNewFilePath#' line = line .. '%f' line = line .. '%*' end return line end function M.readonly() local is_modifiable = vim.bo.modifiable == true local is_readonly = vim.bo.readonly == true if not is_modifiable and is_readonly then return utils.get_icon('lock') .. ' RO' end if is_modifiable and is_readonly then return 'RO' end if not is_modifiable and not is_readonly then return utils.get_icon('lock') end return '' end local mode_table = { no='N-Operator Pending', v='V.', V='V·Line', ['']='V·Block', -- this is not ^V, but it's , they're different s='S.', S='S·Line', ['']='S·Block', i='I.', ic='I·Compl', ix='I·X-Compl', R='R.', Rc='Compl·Replace', Rx='V·Replace', Rv='X-Compl·Replace', c='Command', cv='Vim Ex', ce='Ex', r='Propmt', rm='More', ['r?']='Confirm', ['!']='Sh', t='T.' } function M.mode() return mode_table[vim.fn.mode()] or (vim.fn.mode() == 'n' and '' or 'NOT IN MAP') end function M.rhs() return vim.fn.winwidth(0) > 80 and ('%s %02d/%02d:%02d'):format(line_no_indicator(), vim.fn.line('.'), vim.fn.line('$'), vim.fn.col('.')) or line_no_indicator() end function M.spell() if vim.wo.spell then return utils.get_icon('spell') end return '' end function M.paste() if vim.o.paste then return utils.get_icon('paste') end return '' end function M.file_info() local line = vim.bo.filetype if vim.bo.fileformat ~= 'unix' then return line .. ' ' .. vim.bo.fileformat end if vim.bo.fileencoding ~= 'utf-8' then return line .. ' ' .. vim.bo.fileencoding end return line end function M.word_count() if vim.bo.filetype == 'markdown' or vim.bo.filetype == 'text' then return vim.fn.wordcount()['words'] .. ' words' end return '' end function M.filetype() return vim.bo.filetype end --------------------------------------------------------------------------------- -- Statusline --------------------------------------------------------------------------------- function M.active() local line = [[%6*%{luaeval("require'_.statusline'.git_info()")} %*]] line = line .. '%<' line = line .. '%4*' .. M.filepath() .. '%*' line = line .. [[%4* %{luaeval("require'_.statusline'.word_count()")} %*]] line = line .. [[%5* %{luaeval("require'_.statusline'.readonly()")} %w %*]] line = line .. '%9*%=%*' line = line .. M.lsp_status() .. '%*' line = line .. [[ %{luaeval("require'_.statusline'.mode()")} %*]] line = line .. [[%#ErrorMsg#%{luaeval("require'_.statusline'.paste()")}%*]] line = line .. [[%#WarningMsg#%{luaeval("require'_.statusline'.spell()")}%*]] line = line .. [[%4* %{luaeval("require'_.statusline'.file_info()")} %*]] line = line .. [[%4* %{luaeval("require'_.statusline'.rhs()")} %*]] if vim.bo.filetype == 'help' or vim.bo.filetype == 'man' then line = [[%#StatusLineNC# %{luaeval("require'_.statusline'.filetype()")} %f]] line = line .. [[%5* %{luaeval("require'_.statusline'.readonly()")} %w %*]] end vim.api.nvim_win_set_option(0, 'statusline', line) end function M.inactive() local line = '%#StatusLineNC#%f%*' vim.api.nvim_win_set_option(0, 'statusline', line) end function M.activate() vim.cmd( ('hi! StatusLine gui=NONE cterm=NONE guibg=NONE ctermbg=NONE guifg=%s ctermfg=%d'):format( utils.get_color('Identifier', 'fg', 'gui'), utils.get_color('Identifier', 'fg', 'cterm'))) utils.augroup('MyStatusLine', function() vim.cmd('autocmd WinEnter,BufEnter * lua require\'_.statusline\'.active()') vim.cmd('autocmd WinLeave,BufLeave * lua require\'_.statusline\'.inactive()') end) end return M
local utils = require '_.utils' local M = {} --------------------------------------------------------------------------------- -- Helpers --------------------------------------------------------------------------------- -- display lineNoIndicator (from drzel/vim-line-no-indicator) local function line_no_indicator() local line_no_indicator_chars = { ' ', '▁', '▂', '▃', '▄', '▅', '▆', '▇', '█' } local current_line = vim.fn.line('.') local total_lines = vim.fn.line('$') local index = current_line if current_line == 1 then index = 1 elseif current_line == total_lines then index = #line_no_indicator_chars else local line_no_fraction = math.floor(current_line) / math.floor(total_lines) index = math.ceil(line_no_fraction * #line_no_indicator_chars) end return line_no_indicator_chars[index] end --------------------------------------------------------------------------------- -- Main functions --------------------------------------------------------------------------------- function M.lsp_status() if not vim.tbl_isempty(vim.lsp.buf_get_clients()) then local line = [[%5*%{luaeval("require'lsp-status'.status_errors()")}]] line = line .. [[ %6*%{luaeval("require'lsp-status'.status_warnings()")}]] line = line .. [[ %7*%{luaeval("require'lsp-status'.status_hints()")}]] line = line .. [[ %8*%{luaeval("require'lsp-status'.status_info()")}]] return line end return '' end function M.git_info() if not vim.g.loaded_fugitive then return '' end local out = vim.fn.FugitiveHead(10) if out ~= '' then out = utils.get_icon('branch') .. ' ' .. out end return out end function M.update_filepath_highlights() if vim.bo.modified then vim.cmd('hi! link StatusLineFilePath DiffChange') vim.cmd('hi! link StatusLineNewFilePath DiffChange') else vim.cmd('hi! link StatusLineFilePath User6') vim.cmd('hi! link StatusLineNewFilePath User4') end return '' end function M.get_filepath_parts() local base = vim.fn.expand('%:~:.:h') local filename = vim.fn.expand('%:~:.:t') local prefix = (vim.fn.empty(base) == 1 or base == '.') and '' or base .. '/' return {base, filename, prefix} end function M.filepath() local parts = M.get_filepath_parts() local prefix = parts[3] local filename = parts[2] local line = [[%{luaeval("require'_.statusline'.get_filepath_parts()[3]")}]] line = line .. '%*' line = line .. [[%{luaeval("require'_.statusline'.update_filepath_highlights()")}]] line = line .. '%#StatusLineFilePath#' line = line .. [[%{luaeval("require'_.statusline'.get_filepath_parts()[2]")}]] if vim.fn.empty(prefix) == 1 and vim.fn.empty(filename) == 1 then line = [[%{luaeval("require'_.statusline'.update_filepath_highlights()")}]] line = line .. '%#StatusLineNewFilePath#' line = line .. '%f' line = line .. '%*' end return line end function M.readonly() local is_modifiable = vim.bo.modifiable == true local is_readonly = vim.bo.readonly == true if not is_modifiable and is_readonly then return utils.get_icon('lock') .. ' RO' end if is_modifiable and is_readonly then return 'RO' end if not is_modifiable and not is_readonly then return utils.get_icon('lock') end return '' end local mode_table = { no='N-Operator Pending', v='V.', V='V·Line', ['']='V·Block', -- this is not ^V, but it's , they're different s='S.', S='S·Line', ['']='S·Block', i='I.', ic='I·Compl', ix='I·X-Compl', R='R.', Rc='Compl·Replace', Rx='V·Replace', Rv='X-Compl·Replace', c='Command', cv='Vim Ex', ce='Ex', r='Propmt', rm='More', ['r?']='Confirm', ['!']='Sh', t='T.' } function M.mode() return mode_table[vim.fn.mode()] or (vim.fn.mode() == 'n' and '' or 'NOT IN MAP') end function M.rhs() return vim.fn.winwidth(0) > 80 and ('%s %02d/%02d:%02d'):format(line_no_indicator(), vim.fn.line('.'), vim.fn.line('$'), vim.fn.col('.')) or line_no_indicator() end function M.spell() if vim.wo.spell then return utils.get_icon('spell') end return '' end function M.paste() if vim.o.paste then return utils.get_icon('paste') end return '' end function M.file_info() local line = vim.bo.filetype if vim.bo.fileformat ~= 'unix' then return line .. ' ' .. vim.bo.fileformat end if vim.bo.fileencoding ~= 'utf-8' then return line .. ' ' .. vim.bo.fileencoding end return line end function M.word_count() if vim.bo.filetype == 'markdown' or vim.bo.filetype == 'text' then return vim.fn.wordcount()['words'] .. ' words' end return '' end function M.filetype() return vim.bo.filetype end --------------------------------------------------------------------------------- -- Statusline --------------------------------------------------------------------------------- function M.active() local line = M.lsp_status() .. ' %*' line = line .. [[%6*%{luaeval("require'_.statusline'.git_info()")} %*]] line = line .. '%<' line = line .. '%4*' .. M.filepath() .. '%*' line = line .. [[%4* %{luaeval("require'_.statusline'.word_count()")} %*]] line = line .. [[%5* %{luaeval("require'_.statusline'.readonly()")} %w %*]] line = line .. '%9*%=%*' line = line .. [[ %{luaeval("require'_.statusline'.mode()")} %*]] line = line .. [[%#ErrorMsg#%{luaeval("require'_.statusline'.paste()")}%*]] line = line .. [[%#WarningMsg#%{luaeval("require'_.statusline'.spell()")}%*]] line = line .. [[%4* %{luaeval("require'_.statusline'.file_info()")} %*]] line = line .. [[%4* %{luaeval("require'_.statusline'.rhs()")} %*]] if vim.bo.filetype == 'help' or vim.bo.filetype == 'man' then line = [[%#StatusLineNC# %{luaeval("require'_.statusline'.filetype()")} %f]] line = line .. [[%5* %{luaeval("require'_.statusline'.readonly()")} %w %*]] end vim.api.nvim_win_set_option(0, 'statusline', line) end function M.inactive() local line = '%#StatusLineNC#%f%*' vim.api.nvim_win_set_option(0, 'statusline', line) end function M.activate() vim.cmd( ('hi! StatusLine gui=NONE cterm=NONE guibg=NONE ctermbg=NONE guifg=%s ctermfg=%d'):format( utils.get_color('Identifier', 'fg', 'gui'), utils.get_color('Identifier', 'fg', 'cterm'))) utils.augroup('MyStatusLine', function() vim.cmd('autocmd WinEnter,BufEnter * lua require\'_.statusline\'.active()') vim.cmd('autocmd WinLeave,BufLeave * lua require\'_.statusline\'.inactive()') end) end return M
fix(nvim): lsp status info position
fix(nvim): lsp status info position
Lua
mit
skyuplam/dotfiles,skyuplam/dotfiles
8dde1203348ff4408ced269a307ece98705a3a29
core/servermanager.lua
core/servermanager.lua
local st = require "util.stanza"; local send = require "core.sessionmanager".send_to_session; local xmlns_stanzas ='urn:ietf:params:xml:ns:xmpp-stanzas'; require "modulemanager" -- Handle stanzas that were addressed to the server (whether they came from c2s, s2s, etc.) function handle_stanza(origin, stanza) -- Use plugins if not modulemanager.handle_stanza(origin, stanza) then if stanza.name == "iq" then local reply = st.reply(stanza); reply.attr.type = "error"; reply:tag("error", { type = "cancel" }) :tag("service-unavailable", { xmlns = xmlns_stanzas }); send(origin, reply); end end end
local st = require "util.stanza"; local send = require "core.sessionmanager".send_to_session; local xmlns_stanzas ='urn:ietf:params:xml:ns:xmpp-stanzas'; require "modulemanager" -- Handle stanzas that were addressed to the server (whether they came from c2s, s2s, etc.) function handle_stanza(origin, stanza) -- Use plugins if not modulemanager.handle_stanza(origin, stanza) then if stanza.name == "iq" then if stanza.attr.type ~= "result" and stanza.attr.type ~= "error" then send(origin, st.error_reply(stanza, "cancel", "service-unavailable")); end elseif stanza.name == "message" then send(origin, st.error_reply(stanza, "cancel", "service-unavailable")); elseif stanza.name ~= "presence" then error("Unknown stanza"); end end end
Fixed: Unhandled stanza handling
Fixed: Unhandled stanza handling
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
84c5f57efab1b75a591ccbfb8db4fb71dbe8c17f
lua/entities/gmod_wire_expression2/core/sound.lua
lua/entities/gmod_wire_expression2/core/sound.lua
/******************************************************************************\ Built-in Sound support v1.18 \******************************************************************************/ E2Lib.RegisterExtension("sound", true) local wire_expression2_maxsounds = CreateConVar( "wire_expression2_maxsounds", 16 ) local wire_expression2_sound_burst_max = CreateConVar( "wire_expression2_sound_burst_max", 8 ) local wire_expression2_sound_burst_rate = CreateConVar( "wire_expression2_sound_burst_rate", 0.1 ) --------------------------------------------------------------- -- Helper functions --------------------------------------------------------------- local function isAllowed( self ) local data = self.data.sound_data local count = data.count if count == wire_expression2_maxsounds:GetInt() then return false end if data.burst == 0 then return false end data.burst = data.burst - 1 local timerid = "E2_sound_burst_count_" .. self.entity:EntIndex() if not timer.Exists( timerid ) then timer.Create( timerid, wire_expression2_sound_burst_rate:GetFloat(), 0, function() if not IsValid( self.entity ) then timer.Remove( timerid ) return end data.burst = data.burst + 1 if data.burst == wire_expression2_sound_burst_max:GetInt() then timer.Remove( timerid ) end end) end return true end local function getSound( self, index ) if isnumber( index ) then index = math.floor( index ) end return self.data.sound_data.sounds[index] end local function soundStop(self, index, fade) local sound = getSound( self, index ) if not sound then return end fade = math.abs( fade ) if fade == 0 then sound:Stop() else sound:FadeOut( fade ) end if isnumber( index ) then index = math.floor( index ) end self.data.sound_data.sounds[index] = nil self.data.sound_data.count = self.data.sound_data.count - 1 timer.Remove( "E2_sound_stop_" .. self.entity:EntIndex() .. "_" .. index ) end local function soundCreate(self, entity, index, time, path, fade) if path:match('["?]') then return end local data = self.data.sound_data if not isAllowed( self ) then return end path = path:Trim() path = path:gsub( "\\", "/" ) if isnumber( index ) then index = math.floor( index ) end local timerid = "E2_sound_stop_" .. self.entity:EntIndex() .. "_" .. index local sound = getSound( self, index ) if sound then sound:Stop() timer.Remove( timerid ) else data.count = data.count + 1 end local sound = CreateSound( entity, path ) data.sounds[index] = sound sound:Play() entity:CallOnRemove( "E2_stopsound", function() soundStop( self, index, 0 ) end ) if time == 0 and fade == 0 then return end time = math.abs( time ) timer.Create( timerid, time, 1, function() if not self or not IsValid( self.entity ) or not IsValid( entity ) then return end soundStop( self, index, fade ) end) end local function soundPurge( self ) local sound_data = self.data.sound_data if sound_data.sounds then for k,v in pairs( sound_data.sounds ) do v:Stop() timer.Remove( "E2_sound_stop_" .. self.entity:EntIndex() .. "_" .. k ) end end sound_data.sounds = {} sound_data.count = 0 end --------------------------------------------------------------- -- Play functions --------------------------------------------------------------- __e2setcost(25) e2function void soundPlay( index, duration, string path ) soundCreate(self,self.entity,index,duration,path,0) end e2function void entity:soundPlay( index, duration, string path) if not IsValid(this) or not isOwner(self, this) then return end soundCreate(self,this,index,duration,path,0) end e2function void soundPlay( index, duration, string path, fade ) soundCreate(self,self.entity,index,duration,path,fade) end e2function void entity:soundPlay( index, duration, string path, fade ) if not IsValid(this) or not isOwner(self, this) then return end soundCreate(self,this,index,duration,path,fade) end e2function void soundPlay( string index, duration, string path ) = e2function void soundPlay( index, duration, string path ) e2function void entity:soundPlay( string index, duration, string path ) = e2function void entity:soundPlay( index, duration, string path ) e2function void soundPlay( string index, duration, string path, fade ) = e2function void soundPlay( index, duration, string path, fade ) e2function void entity:soundPlay( string index, duration, string path, fade ) = e2function void entity:soundPlay( index, duration, string path, fade ) --------------------------------------------------------------- -- Modifier functions --------------------------------------------------------------- __e2setcost(5) e2function void soundStop( index ) soundStop(self, index, 0) end e2function void soundStop( index, fadetime ) soundStop(self, index, fadetime) end e2function void soundVolume( index, volume ) local sound = getSound( self, index ) if not sound then return end sound:ChangeVolume( math.Clamp( volume, 0, 1 ), 0 ) end e2function void soundVolume( index, volume, fadetime ) local sound = getSound( self, index ) if not sound then return end sound:ChangeVolume( math.Clamp( volume, 0, 1 ), math.abs( fadetime ) ) end e2function void soundPitch( index, pitch ) local sound = getSound( self, index ) if not sound then return end sound:ChangePitch( math.Clamp( pitch, 0, 255 ), 0 ) end e2function void soundPitch( index, pitch, fadetime ) local sound = getSound( self, index ) if not sound then return end sound:ChangePitch( math.Clamp( pitch, 0, 255 ), math.abs( fadetime ) ) end e2function void soundStop( string index ) = e2function void soundStop( index ) e2function void soundStop( string index, fadetime ) = e2function void soundStop( index, fadetime ) e2function void soundVolume( string index, volume ) = e2function void soundVolume( index, volume ) e2function void soundVolume( string index, volume, fadetime ) = e2function void soundVolume( index, volume, fadetime ) e2function void soundPitch( string index, pitch ) = e2function void soundPitch( index, pitch ) e2function void soundPitch( string index, pitch, fadetime ) = e2function void soundPitch( index, pitch, fadetime ) --------------------------------------------------------------- -- Other --------------------------------------------------------------- e2function void soundPurge() soundPurge( self ) end e2function number soundDuration(string sound) return SoundDuration(sound) or 0 end --------------------------------------------------------------- registerCallback("construct", function(self) self.data.sound_data = {} self.data.sound_data.burst = wire_expression2_sound_burst_max:GetInt() self.data.sound_data.sounds = {} self.data.sound_data.count = 0 end) registerCallback("destruct", function(self) soundPurge( self ) end)
/******************************************************************************\ Built-in Sound support v1.18 \******************************************************************************/ E2Lib.RegisterExtension("sound", true) local wire_expression2_maxsounds = CreateConVar( "wire_expression2_maxsounds", 16 ) local wire_expression2_sound_burst_max = CreateConVar( "wire_expression2_sound_burst_max", 8 ) local wire_expression2_sound_burst_rate = CreateConVar( "wire_expression2_sound_burst_rate", 0.1 ) --------------------------------------------------------------- -- Helper functions --------------------------------------------------------------- local function isAllowed( self ) local data = self.data.sound_data local count = data.count if count == wire_expression2_maxsounds:GetInt() then return false end if data.burst == 0 then return false end data.burst = data.burst - 1 local timerid = "E2_sound_burst_count_" .. self.entity:EntIndex() if not timer.Exists( timerid ) then timer.Create( timerid, wire_expression2_sound_burst_rate:GetFloat(), 0, function() if not IsValid( self.entity ) then timer.Remove( timerid ) return end data.burst = data.burst + 1 if data.burst == wire_expression2_sound_burst_max:GetInt() then timer.Remove( timerid ) end end) end return true end local function getSound( self, index ) if isnumber( index ) then index = math.floor( index ) end return self.data.sound_data.sounds[index] end local function soundStop(self, index, fade) local sound = getSound( self, index ) if not sound then return end fade = math.abs( fade ) if fade == 0 then sound:Stop() if isnumber( index ) then index = math.floor( index ) end self.data.sound_data.sounds[index] = nil self.data.sound_data.count = self.data.sound_data.count - 1 else sound:FadeOut( fade ) timer.Simple( fade, function() soundStop( self, index, 0 ) end) end timer.Remove( "E2_sound_stop_" .. self.entity:EntIndex() .. "_" .. index ) end local function soundCreate(self, entity, index, time, path, fade) if path:match('["?]') then return end local data = self.data.sound_data if not isAllowed( self ) then return end path = path:Trim() path = path:gsub( "\\", "/" ) if isnumber( index ) then index = math.floor( index ) end local timerid = "E2_sound_stop_" .. self.entity:EntIndex() .. "_" .. index local sound = getSound( self, index ) if sound then sound:Stop() timer.Remove( timerid ) else data.count = data.count + 1 end local sound = CreateSound( entity, path ) data.sounds[index] = sound sound:Play() entity:CallOnRemove( "E2_stopsound", function() soundStop( self, index, 0 ) end ) if time == 0 and fade == 0 then return end time = math.abs( time ) timer.Create( timerid, time, 1, function() if not self or not IsValid( self.entity ) or not IsValid( entity ) then return end soundStop( self, index, fade ) end) end local function soundPurge( self ) local sound_data = self.data.sound_data if sound_data.sounds then for k,v in pairs( sound_data.sounds ) do v:Stop() timer.Remove( "E2_sound_stop_" .. self.entity:EntIndex() .. "_" .. k ) end end sound_data.sounds = {} sound_data.count = 0 end --------------------------------------------------------------- -- Play functions --------------------------------------------------------------- __e2setcost(25) e2function void soundPlay( index, duration, string path ) soundCreate(self,self.entity,index,duration,path,0) end e2function void entity:soundPlay( index, duration, string path) if not IsValid(this) or not isOwner(self, this) then return end soundCreate(self,this,index,duration,path,0) end e2function void soundPlay( index, duration, string path, fade ) soundCreate(self,self.entity,index,duration,path,fade) end e2function void entity:soundPlay( index, duration, string path, fade ) if not IsValid(this) or not isOwner(self, this) then return end soundCreate(self,this,index,duration,path,fade) end e2function void soundPlay( string index, duration, string path ) = e2function void soundPlay( index, duration, string path ) e2function void entity:soundPlay( string index, duration, string path ) = e2function void entity:soundPlay( index, duration, string path ) e2function void soundPlay( string index, duration, string path, fade ) = e2function void soundPlay( index, duration, string path, fade ) e2function void entity:soundPlay( string index, duration, string path, fade ) = e2function void entity:soundPlay( index, duration, string path, fade ) --------------------------------------------------------------- -- Modifier functions --------------------------------------------------------------- __e2setcost(5) e2function void soundStop( index ) soundStop(self, index, 0) end e2function void soundStop( index, fadetime ) soundStop(self, index, fadetime) end e2function void soundVolume( index, volume ) local sound = getSound( self, index ) if not sound then return end sound:ChangeVolume( math.Clamp( volume, 0, 1 ), 0 ) end e2function void soundVolume( index, volume, fadetime ) local sound = getSound( self, index ) if not sound then return end sound:ChangeVolume( math.Clamp( volume, 0, 1 ), math.abs( fadetime ) ) end e2function void soundPitch( index, pitch ) local sound = getSound( self, index ) if not sound then return end sound:ChangePitch( math.Clamp( pitch, 0, 255 ), 0 ) end e2function void soundPitch( index, pitch, fadetime ) local sound = getSound( self, index ) if not sound then return end sound:ChangePitch( math.Clamp( pitch, 0, 255 ), math.abs( fadetime ) ) end e2function void soundStop( string index ) = e2function void soundStop( index ) e2function void soundStop( string index, fadetime ) = e2function void soundStop( index, fadetime ) e2function void soundVolume( string index, volume ) = e2function void soundVolume( index, volume ) e2function void soundVolume( string index, volume, fadetime ) = e2function void soundVolume( index, volume, fadetime ) e2function void soundPitch( string index, pitch ) = e2function void soundPitch( index, pitch ) e2function void soundPitch( string index, pitch, fadetime ) = e2function void soundPitch( index, pitch, fadetime ) --------------------------------------------------------------- -- Other --------------------------------------------------------------- e2function void soundPurge() soundPurge( self ) end e2function number soundDuration(string sound) return SoundDuration(sound) or 0 end --------------------------------------------------------------- registerCallback("construct", function(self) self.data.sound_data = {} self.data.sound_data.burst = wire_expression2_sound_burst_max:GetInt() self.data.sound_data.sounds = {} self.data.sound_data.count = 0 end) registerCallback("destruct", function(self) soundPurge( self ) end)
Fixed sounds not stopping
Fixed sounds not stopping Fixed sounds not stopping if you remove the entity while the sound is fading
Lua
apache-2.0
plinkopenguin/wiremod,Python1320/wire,bigdogmat/wire,mms92/wire,Grocel/wire,garrysmodlua/wire,wiremod/wire,mitterdoo/wire,thegrb93/wire,dvdvideo1234/wire,sammyt291/wire,immibis/wiremod,CaptainPRICE/wire,NezzKryptic/Wire,notcake/wire,rafradek/wire
e406a527593379df572b203b4299ffa5d21c446e
applications/luci-siitwizard/luasrc/model/cbi/siitwizard.lua
applications/luci-siitwizard/luasrc/model/cbi/siitwizard.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2008 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local uci = require "luci.model.uci".cursor() -------------------- View -------------------- f = SimpleForm("siitwizward", "4over6-Assistent", "Dieser Assistent unterstüzt bei der Einrichtung von IPv4-over-IPv6 Translation.") mode = f:field(ListValue, "mode", "Betriebsmodus") mode:value("gateway", "Gateway") mode:value("client", "Client") dev = f:field(ListValue, "device", "WLAN-Gerät") uci:foreach("wireless", "wifi-device", function(section) dev:value(section[".name"]) end) lanip = f:field(Value, "ipaddr", "LAN IP Adresse") lanip.value = "127.23.1.1" lanmsk = f:field(Value, "netmask", "LAN Netzmaske") lanmsk.value = "255.255.0.0" -------------------- Control -------------------- LL_PREFIX = luci.ip.IPv6("fe80::/64") -- -- find link-local address -- function find_ll() for _, r in ipairs(luci.sys.net.routes6()) do if LL_PREFIX:contains(r.dest) and r.dest:higher(LL_PREFIX) then return r.dest:sub(LL_PREFIX) end end return luci.ip.IPv6("::") end function f.handle(self, state, data) if state == FORM_VALID then luci.http.redirect(luci.dispatcher.build_url("admin", "uci", "changes")) return false elseif state == FORM_INVALID then self.errmessage = "Ungültige Eingabe: Bitte die Formularfelder auf Fehler prüfen." end return true end function mode.write(self, section, value) -- -- Configure wifi device -- local wifi_device = dev:formvalue(section) local wifi_essid = uci:get("siit", "wifi", "essid") or "6mesh.freifunk.net" local wifi_bssid = uci:get("siit", "wifi", "bssid") or "02:ca:ff:ee:ba:be" local wifi_channel = uci:get("siit", "wifi", "channel") or "1" -- nuke old device definition uci:delete_all("wireless", "wifi-iface", function(s) return s.device == wifi_device end ) uci:delete_all("network", "interface", function(s) return s['.name'] == wifi_device end ) -- create wifi device definition uci:tset("wireless", wifi_device, { disabled = 0, channel = wifi_channel, -- txantenna = 1, -- rxantenna = 1, -- diversity = 0 }) uci:section("wireless", "wifi-iface", nil, { encryption = "none", mode = "adhoc", network = wifi_device, device = wifi_device, ssid = wifi_essid, bssid = wifi_bssid, }) -- -- Determine defaults -- local ula_prefix = uci:get("siit", "ipv6", "ula_prefix") or "fd00::" local ula_global = uci:get("siit", "ipv6", "ula_global") or "00ca:ffee:babe::" -- = Freifunk local ula_subnet = uci:get("siit", "ipv6", "ula_subnet") or "0000:0000:0000:4223::" -- = Berlin local siit_prefix = uci:get("siit", "ipv6", "siit_prefix") or "::ffff:0000:0000" -- Find wifi interface local device = dev:formvalue(section) -- -- Generate ULA -- local ula = luci.ip.IPv6("::/64") for _, prefix in ipairs({ ula_prefix, ula_global, ula_subnet }) do ula = ula:add(luci.ip.IPv6(prefix)) end ula = ula:add(find_ll()) -- -- Gateway mode -- -- * wan port is dhcp, lan port is 172.23.1.1/24 -- * siit0 gets a dummy address: 169.254.42.42 -- * wl0 gets an ipv6 address, in this case the fdca:ffee:babe::1:1/64 -- * we do a ::ffff:ffff:0/96 route into siit0, so everything from 6mesh goes into translation. -- * an HNA6 of ::ffff:ffff:0:0/96 announces the mapped 0.0.0.0/0 ipv4 space. -- * MTU on WAN, LAN down to 1400, ipv6 headers are slighly larger. if value == "gateway" then uci:set("network", "wan", "mtu", 1400) -- use full siit subnet siit_route = luci.ip.IPv6(siit_prefix .. "/96") -- -- Client mode -- -- * 172.23.2.1/24 on its lan, fdca:ffee:babe::1:2 on wl0 and the usual dummy address on siit0. -- * we do a ::ffff:ffff:172.13.2.0/120 to siit0, because in this case, only traffic directed to clients needs to go into translation. -- * same route as HNA6 announcement to catch the traffic out of the mesh. -- * Also, MTU on LAN reduced to 1400. else -- lan interface local lan_net = luci.ip.IPv4( lanip:formvalue(section) or "192.168.1.1", lanmsk:formvalue(section) or "255.255.255.0" ) uci:tset("network", "lan", { mtu = 1400, ipaddr = lan_net:host():string(), netmask = lan_net:mask():string() }) -- derive siit subnet from lan config siit_route = luci.ip.IPv6( siit_prefix .. "/" .. (96 + lan_net:prefix()) ):add(lan_net[2]) end -- siit0 interface uci:delete_all("network", "interface", function(s) return ( s.ifname == "siit0" ) end) uci:section("network", "interface", "siit0", { ifname = "siit0", proto = "static", ipaddr = "169.254.42.42", netmask = "255.255.255.0" }) -- siit0 route uci:delete_all("network", "route6", function(s) return siit_route:contains(luci.ip.IPv6(s.target)) end) uci:section("network", "route6", nil, { interface = "siit0", target = siit_route:string() }) -- create wifi network interface uci:section("network", "interface", wifi_device, { proto = "static", mtu = 1400, ip6addr = ula:string() }) -- nuke old olsrd interfaces uci:delete_all("olsrd", "Interface", function(s) return s.interface == wifi_device end) -- configure olsrd interface uci:foreach("olsrd", "olsrd", function(s) uci:set("olsrd", s['.name'], "IpVersion", 6) end) uci:section("olsrd", "Interface", nil, { ignore = 0, interface = wifi_device, Ip6AddrType = "global" }) -- hna6 uci:delete_all("olsrd", "Hna6", function(s) if s.netaddr and s.prefix then return siit_route:contains(luci.ip.IPv6(s.netaddr.."/"..s.prefix)) end end) uci:section("olsrd", "Hna6", nil, { netaddr = siit_route:host():string(), prefix = siit_route:prefix() }) uci:save("wireless") uci:save("network") uci:save("olsrd") end return f
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2008 Jo-Philipp Wich <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local uci = require "luci.model.uci".cursor() -------------------- View -------------------- f = SimpleForm("siitwizward", "4over6-Assistent", "Dieser Assistent unterstüzt bei der Einrichtung von IPv4-over-IPv6 Translation.") mode = f:field(ListValue, "mode", "Betriebsmodus") mode:value("gateway", "Gateway") mode:value("client", "Client") dev = f:field(ListValue, "device", "WLAN-Gerät") uci:foreach("wireless", "wifi-device", function(section) dev:value(section[".name"]) end) lanip = f:field(Value, "ipaddr", "LAN IP Adresse") lanip.value = "172.23.1.1" lanip:depends("mode", "client") lanmsk = f:field(Value, "netmask", "LAN Netzmaske") lanmsk.value = "255.255.0.0" lanmsk:depends("mode", "client") -------------------- Control -------------------- LL_PREFIX = luci.ip.IPv6("fe80::/64") -- -- find link-local address -- function find_ll() for _, r in ipairs(luci.sys.net.routes6()) do if LL_PREFIX:contains(r.dest) and r.dest:higher(LL_PREFIX) then return r.dest:sub(LL_PREFIX) end end return luci.ip.IPv6("::") end function f.handle(self, state, data) if state == FORM_VALID then luci.http.redirect(luci.dispatcher.build_url("admin", "uci", "changes")) return false elseif state == FORM_INVALID then self.errmessage = "Ungültige Eingabe: Bitte die Formularfelder auf Fehler prüfen." end return true end function mode.write(self, section, value) -- -- Configure wifi device -- local wifi_device = dev:formvalue(section) local wifi_essid = uci:get("siit", "wifi", "essid") or "6mesh.freifunk.net" local wifi_bssid = uci:get("siit", "wifi", "bssid") or "02:ca:ff:ee:ba:be" local wifi_channel = uci:get("siit", "wifi", "channel") or "1" -- nuke old device definition uci:delete_all("wireless", "wifi-iface", function(s) return s.device == wifi_device end ) uci:delete_all("network", "interface", function(s) return s['.name'] == wifi_device end ) -- create wifi device definition uci:tset("wireless", wifi_device, { disabled = 0, channel = wifi_channel, -- txantenna = 1, -- rxantenna = 1, -- diversity = 0 }) uci:section("wireless", "wifi-iface", nil, { encryption = "none", mode = "adhoc", network = wifi_device, device = wifi_device, ssid = wifi_essid, bssid = wifi_bssid, }) -- -- Determine defaults -- local ula_prefix = uci:get("siit", "ipv6", "ula_prefix") or "fd00::" local ula_global = uci:get("siit", "ipv6", "ula_global") or "00ca:ffee:babe::" -- = Freifunk local ula_subnet = uci:get("siit", "ipv6", "ula_subnet") or "0000:0000:0000:4223::" -- = Berlin local siit_prefix = uci:get("siit", "ipv6", "siit_prefix") or "::ffff:0000:0000" -- Find wifi interface local device = dev:formvalue(section) -- -- Generate ULA -- local ula = luci.ip.IPv6("::/64") for _, prefix in ipairs({ ula_prefix, ula_global, ula_subnet }) do ula = ula:add(luci.ip.IPv6(prefix)) end ula = ula:add(find_ll()) -- -- Gateway mode -- -- * wan port is dhcp, lan port is 172.23.1.1/24 -- * siit0 gets a dummy address: 169.254.42.42 -- * wl0 gets an ipv6 address, in this case the fdca:ffee:babe::1:1/64 -- * we do a ::ffff:ffff:0/96 route into siit0, so everything from 6mesh goes into translation. -- * an HNA6 of ::ffff:ffff:0:0/96 announces the mapped 0.0.0.0/0 ipv4 space. -- * MTU on WAN, LAN down to 1400, ipv6 headers are slighly larger. if value == "gateway" then uci:set("network", "wan", "mtu", 1400) -- use full siit subnet siit_route = luci.ip.IPv6(siit_prefix .. "/96") -- -- Client mode -- -- * 172.23.2.1/24 on its lan, fdca:ffee:babe::1:2 on wl0 and the usual dummy address on siit0. -- * we do a ::ffff:ffff:172.13.2.0/120 to siit0, because in this case, only traffic directed to clients needs to go into translation. -- * same route as HNA6 announcement to catch the traffic out of the mesh. -- * Also, MTU on LAN reduced to 1400. else -- lan interface local lan_net = luci.ip.IPv4( lanip:formvalue(section) or "192.168.1.1", lanmsk:formvalue(section) or "255.255.255.0" ) uci:tset("network", "lan", { mtu = 1400, ipaddr = lan_net:host():string(), netmask = lan_net:mask():string() }) -- derive siit subnet from lan config siit_route = luci.ip.IPv6( siit_prefix .. "/" .. (96 + lan_net:prefix()) ):add(lan_net[2]) end -- siit0 interface uci:delete_all("network", "interface", function(s) return ( s.ifname == "siit0" ) end) uci:section("network", "interface", "siit0", { ifname = "siit0", proto = "static", ipaddr = "169.254.42.42", netmask = "255.255.255.0" }) -- siit0 route uci:delete_all("network", "route6", function(s) return siit_route:contains(luci.ip.IPv6(s.target)) end) uci:section("network", "route6", nil, { interface = "siit0", target = siit_route:string() }) -- create wifi network interface uci:section("network", "interface", wifi_device, { proto = "static", mtu = 1400, ip6addr = ula:string() }) -- nuke old olsrd interfaces uci:delete_all("olsrd", "Interface", function(s) return s.interface == wifi_device end) -- configure olsrd interface uci:foreach("olsrd", "olsrd", function(s) uci:set("olsrd", s['.name'], "IpVersion", 6) end) uci:section("olsrd", "Interface", nil, { ignore = 0, interface = wifi_device, Ip6AddrType = "global" }) -- hna6 uci:delete_all("olsrd", "Hna6", function(s) if s.netaddr and s.prefix then return siit_route:contains(luci.ip.IPv6(s.netaddr.."/"..s.prefix)) end end) uci:section("olsrd", "Hna6", nil, { netaddr = siit_route:host():string(), prefix = siit_route:prefix() }) uci:save("wireless") uci:save("network") uci:save("olsrd") end return f
applications/siitwizard: - fix default lan ip - make ip and netmask depend on client mode
applications/siitwizard: - fix default lan ip - make ip and netmask depend on client mode
Lua
apache-2.0
deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci
e8ce4657ee558e7d59ee1228aa947704b91a4b36
nyagos.d/catalog/git.lua
nyagos.d/catalog/git.lua
if not nyagos then print("This is a script for nyagos not lua.exe") os.exit() end -- hub exists, replace git command local hubpath=nyagos.which("hub.exe") if hubpath then nyagos.alias.git = "hub.exe" end share.git = {} local getcommits = function(args) local fd=io.popen("git log --format=\"%h\" -n 20 2>nul","r") if not fd then return {} end local result={} for line in fd:lines() do result[#result+1] = line end fd:close() return result end -- setup local branch listup local branchlist = function(args) if string.find(args[#args],"[/\\\\]") then return nil end local gitbranches = getcommits() local gitbranch_tmp = nyagos.eval('git for-each-ref --format="%(refname:short)" refs/heads/ 2> nul') for line in gitbranch_tmp:gmatch('[^\n]+') do table.insert(gitbranches,line) end return gitbranches end local unquote = function(s) s = string.gsub(s,'"','') return string.gsub(s,'\\[0-7][0-7][0-7]',function(t) return string.char(tonumber(string.sub(t,2),8)) end) end local addlist = function(args) local fd = io.popen("git status -s 2>nul","r") if not fd then return nil end local files = {} for line in fd:lines() do files[#files+1] = unquote(string.sub(line,4)) end fd:close() return files end local checkoutlist = function(args) local result = branchlist(args) or {} local fd = io.popen("git status -s 2>nul","r") if fd then for line in fd:lines() do if string.sub(line,1,2) == " M" then result[1+#result] = unquote(string.sub(line,4)) end end fd:close() end return result end --setup current branch string local currentbranch = function() return nyagos.eval('git rev-parse --abbrev-ref HEAD 2> nul') end -- subcommands local gitsubcommands={} -- keyword gitsubcommands["bisect"]={"start", "bad", "good", "skip", "reset", "visualize", "replay", "log", "run"} gitsubcommands["notes"]={"add", "append", "copy", "edit", "list", "prune", "remove", "show"} gitsubcommands["reflog"]={"show", "delete", "expire"} gitsubcommands["rerere"]={"clear", "forget", "diff", "remaining", "status", "gc"} gitsubcommands["stash"]={"save", "list", "show", "apply", "clear", "drop", "pop", "create", "branch"} gitsubcommands["submodule"]={"add", "status", "init", "deinit", "update", "summary", "foreach", "sync"} gitsubcommands["svn"]={"init", "fetch", "clone", "rebase", "dcommit", "log", "find-rev", "set-tree", "commit-diff", "info", "create-ignore", "propget", "proplist", "show-ignore", "show-externals", "branch", "tag", "blame", "migrate", "mkdirs", "reset", "gc"} gitsubcommands["worktree"]={"add", "list", "lock", "prune", "unlock"} -- branch gitsubcommands["checkout"]=checkoutlist gitsubcommands["reset"]=branchlist gitsubcommands["merge"]=branchlist gitsubcommands["rebase"]=branchlist gitsubcommands["revert"]=branchlist gitsubcommands["show"]=getcommits gitsubcommands["add"]=addlist local gitvar=share.git gitvar.subcommand=gitsubcommands gitvar.branch=branchlist gitvar.currentbranch=currentbranch share.git=gitvar if not share.maincmds then use "subcomplete.lua" end if share.maincmds and share.maincmds["git"] then -- git command complementation exists. nyagos.complete_for.git = function(args) while #args > 2 and args[2]:sub(1,1) == "-" do table.remove(args,2) end if #args == 2 then return share.maincmds.git end local subcmd = table.remove(args,2) while #args > 2 and args[2]:sub(1,1) == "-" do table.remove(args,2) end local t = share.git.subcommand[subcmd] if type(t) == "function" then return t(args) elseif type(t) == "table" and #args == 2 then return t end end end -- EOF
if not nyagos then print("This is a script for nyagos not lua.exe") os.exit() end -- hub exists, replace git command local hubpath=nyagos.which("hub.exe") if hubpath then nyagos.alias.git = "hub.exe" end share.git = {} local getcommits = function(args) local fd=io.popen("git log --format=\"%h\" -n 20 2>nul","r") if not fd then return {} end local result={} for line in fd:lines() do result[#result+1] = line end fd:close() return result end -- setup local branch listup local branchlist = function(args) if string.find(args[#args],"[/\\\\]") then return nil end local gitbranches = getcommits() local gitbranch_tmp = nyagos.eval('git for-each-ref --format="%(refname:short)" refs/heads/ 2> nul') for line in gitbranch_tmp:gmatch('[^\n]+') do table.insert(gitbranches,line) end return gitbranches end local unquote = function(s) s = string.gsub(s,'"','') return string.gsub(s,'\\[0-7][0-7][0-7]',function(t) return string.char(tonumber(string.sub(t,2),8)) end) end local addlist = function(args) local fd = io.popen("git status -s 2>nul","r") if not fd then return nil end local files = {} for line in fd:lines() do local arrowStart,arrowEnd = string.find(line," -> ",1,true) if arrowStart then files[#files+1] = unquote(string.sub(line,4,arrowStart-1)) files[#files+1] = unquote(string.sub(line,arrowEnd+1)) else files[#files+1] = unquote(string.sub(line,4)) end end fd:close() return files end local checkoutlist = function(args) local result = branchlist(args) or {} local fd = io.popen("git status -s 2>nul","r") if fd then for line in fd:lines() do if string.sub(line,1,2) == " M" then result[1+#result] = unquote(string.sub(line,4)) end end fd:close() end return result end --setup current branch string local currentbranch = function() return nyagos.eval('git rev-parse --abbrev-ref HEAD 2> nul') end -- subcommands local gitsubcommands={} -- keyword gitsubcommands["bisect"]={"start", "bad", "good", "skip", "reset", "visualize", "replay", "log", "run"} gitsubcommands["notes"]={"add", "append", "copy", "edit", "list", "prune", "remove", "show"} gitsubcommands["reflog"]={"show", "delete", "expire"} gitsubcommands["rerere"]={"clear", "forget", "diff", "remaining", "status", "gc"} gitsubcommands["stash"]={"save", "list", "show", "apply", "clear", "drop", "pop", "create", "branch"} gitsubcommands["submodule"]={"add", "status", "init", "deinit", "update", "summary", "foreach", "sync"} gitsubcommands["svn"]={"init", "fetch", "clone", "rebase", "dcommit", "log", "find-rev", "set-tree", "commit-diff", "info", "create-ignore", "propget", "proplist", "show-ignore", "show-externals", "branch", "tag", "blame", "migrate", "mkdirs", "reset", "gc"} gitsubcommands["worktree"]={"add", "list", "lock", "prune", "unlock"} -- branch gitsubcommands["checkout"]=checkoutlist gitsubcommands["reset"]=branchlist gitsubcommands["merge"]=branchlist gitsubcommands["rebase"]=branchlist gitsubcommands["revert"]=branchlist gitsubcommands["show"]=getcommits gitsubcommands["add"]=addlist local gitvar=share.git gitvar.subcommand=gitsubcommands gitvar.branch=branchlist gitvar.currentbranch=currentbranch share.git=gitvar if not share.maincmds then use "subcomplete.lua" end if share.maincmds and share.maincmds["git"] then -- git command complementation exists. nyagos.complete_for.git = function(args) while #args > 2 and args[2]:sub(1,1) == "-" do table.remove(args,2) end if #args == 2 then return share.maincmds.git end local subcmd = table.remove(args,2) while #args > 2 and args[2]:sub(1,1) == "-" do table.remove(args,2) end local t = share.git.subcommand[subcmd] if type(t) == "function" then return t(args) elseif type(t) == "table" and #args == 2 then return t end end end -- EOF
Fix: git.lua: `git add` could not complete files when git status is `file1 -> file2`
Fix: git.lua: `git add` could not complete files when git status is `file1 -> file2`
Lua
bsd-3-clause
zetamatta/nyagos,tsuyoshicho/nyagos
10f2ef7935908e98d17577c0635561685d7e262f
covers.lua
covers.lua
local color = "#FFFFFF" SILE.registerCommand("frontcover", function () local options = {} options["first-content-frame"] = "front" SILE.call("pagetemplate", options, function () SILE.call("frame", { id = "front", top = "0", bottom = "100%ph", left = "15%pw", right = "85%pw" }) end) SILE.call("color", { color = color }, function () SILE.call("center", {}, function () SILE.call("hbox") SILE.call("vfill") SILE.call("cabook:font:title", { size = "7%pmed" }, function () SILE.call("wraptitle", {}, { CASILE.metadata.title }) end) SILE.call("skip", { height = "7%pmin" }) SILE.call("cabook:font:subtitle", { size = "5%pmed" }, function () SILE.call("wrapsubtitle", {}, { CASILE.metadata.subtitle }) end) SILE.call("vfill") SILE.call("vfill") if CASILE.metadata.creator then SILE.call("cabook:font:author", { size = "6%pmed", weight = 300 }, { CASILE.metadata.creator[1].text }) end end) SILE.call("par") SILE.call("vfill") SILE.call("break") end) end) SILE.registerCommand("backcover", function () local options = {} options["first-content-frame"] = "front" SILE.call("pagetemplate", options, function () SILE.call("frame", { id = "front", top = "15%pw", bottom = "100%ph - 15%pw", left = "15%pw", right = "85%pw" }) end) SILE.call("noindent") SILE.call("color", { color = color }, function () SILE.settings.set("linebreak.emergencyStretch", SILE.length("2spc")) SILE.settings.temporarily(function () SILE.call("font", { size = "5.2%fw", language = "tr", weight = "600" }) SILE.settings.set("linespacing.method", "fit-font") SILE.settings.set("linespacing.fit-font.extra-space", SILE.length("0.6ex")) CASILE.dropcapNextLetter() SILE.process({ CASILE.metadata.abstract }) SILE.call("par") if CASILE.metadata.creator then SILE.call("raggedleft", {}, function () SILE.call("em", {}, { CASILE.metadata.creator[1].text }) end) end end) SILE.call("skip", { height = "8%pmin" }) SILE.call("par") SILE.settings.temporarily(function () SILE.settings.set("linespacing.method", "fit-font") SILE.settings.set("linespacing.fit-font.extra-space", SILE.length("0.32ex")) SILE.call("cabook:font:sans", { size = "3.4%fw", language = "tr", weight = 600 }) SILE.settings.set("document.lskip", SILE.nodefactory.glue("82pt")) if CASILE.metadata.creator then SILE.process({ CASILE.metadata.creator[1].about }) end SILE.call("par") end) SILE.call("skip", { height = "1cm" }) SILE.call("break") end) end) SILE.registerCommand("spine", function (options) options["first-content-frame"] = "spine1" SILE.call("pagetemplate", options, function () -- luacheck: ignore spine SILE.call("frame", { id = "spine1", top = "-" .. spine, height = spine, left = spine, width = "46%ph", next = "spine2", rotate = 90 }) SILE.call("frame", { id = "spine2", top = "-50%ph-" .. spine, height = spine, left = spine, width = "30%ph", rotate = 90 }) end) SILE.call("noindent") SILE.call("color", { color = color }, function () SILE.call("center", {}, function () SILE.call("topfill") SILE.call("skip", { height = "-10%fh" }) SILE.call("cabook:font:title", { size = "60%fh" }, { CASILE.metadata.title }) SILE.call("par") end) end) SILE.call("framebreak") SILE.call("color", { color = color }, function () SILE.call("center", {}, function () SILE.call("topfill") SILE.call("skip", { height = "10%fh" }) if CASILE.metadata.creator then SILE.call("cabook:font:author", { size = "30%fh" }, { CASILE.metadata.creator[1].text }) end SILE.call("par") end) end) end)
local color = "#FFFFFF" SILE.registerCommand("frontcover", function () local options = {} options["first-content-frame"] = "front" SILE.call("pagetemplate", options, function () SILE.call("frame", { id = "front", top = "0", bottom = "100%ph", left = "15%pw", right = "85%pw" }) end) SILE.call("color", { color = color }, function () SILE.call("center", {}, function () SILE.call("hbox") SILE.call("vfill") SILE.call("cabook:font:title", { size = "7%pmed" }, function () SILE.call("wraptitle", {}, { CASILE.metadata.title }) end) SILE.call("skip", { height = "7%pmin" }) SILE.call("cabook:font:subtitle", { size = "5%pmed" }, function () SILE.call("wrapsubtitle", {}, { CASILE.metadata.subtitle }) end) SILE.call("vfill") SILE.call("vfill") if CASILE.metadata.creator then SILE.call("cabook:font:author", { size = "6%pmed", weight = 300 }, { CASILE.metadata.creator[1].text }) end end) SILE.call("par") SILE.call("vfill") SILE.call("break") end) end) SILE.registerCommand("backcover", function () local options = {} options["first-content-frame"] = "front" SILE.call("pagetemplate", options, function () SILE.call("frame", { id = "front", top = "15%pw", bottom = "100%ph - 15%pw", left = "15%pw", right = "85%pw" }) end) SILE.call("noindent") SILE.call("color", { color = color }, function () SILE.settings.set("linebreak.emergencyStretch", SILE.length("2spc")) SILE.settings.temporarily(function () SILE.call("font", { size = "5.2%fw", weight = "600" }) SILE.settings.set("linespacing.method", "fit-font") SILE.settings.set("linespacing.fit-font.extra-space", SILE.length("0.6ex")) CASILE.dropcapNextLetter() SILE.process({ CASILE.metadata.abstract }) SILE.call("par") if CASILE.metadata.creator then SILE.call("raggedleft", {}, function () SILE.call("em", {}, { CASILE.metadata.creator[1].text }) end) end end) SILE.call("skip", { height = "8%pmin" }) SILE.call("par") SILE.settings.temporarily(function () SILE.settings.set("linespacing.method", "fit-font") SILE.settings.set("linespacing.fit-font.extra-space", SILE.length("0.32ex")) SILE.call("cabook:font:sans", { size = "3.4%fw", weight = 600 }) SILE.settings.set("document.lskip", SILE.nodefactory.glue("82pt")) if CASILE.metadata.creator then SILE.process({ CASILE.metadata.creator[1].about }) end SILE.call("par") end) SILE.call("skip", { height = "1cm" }) SILE.call("break") end) end) SILE.registerCommand("spine", function (options) options["first-content-frame"] = "spine1" SILE.call("pagetemplate", options, function () -- luacheck: ignore spine SILE.call("frame", { id = "spine1", top = "-" .. spine, height = spine, left = spine, width = "46%ph", next = "spine2", rotate = 90 }) SILE.call("frame", { id = "spine2", top = "-50%ph-" .. spine, height = spine, left = spine, width = "30%ph", rotate = 90 }) end) SILE.call("noindent") SILE.call("color", { color = color }, function () SILE.call("center", {}, function () SILE.call("topfill") SILE.call("skip", { height = "-10%fh" }) SILE.call("cabook:font:title", { size = "60%fh" }, { CASILE.metadata.title }) SILE.call("par") end) end) SILE.call("framebreak") SILE.call("color", { color = color }, function () SILE.call("center", {}, function () SILE.call("topfill") SILE.call("skip", { height = "10%fh" }) if CASILE.metadata.creator then SILE.call("cabook:font:author", { size = "30%fh" }, { CASILE.metadata.creator[1].text }) end SILE.call("par") end) end) end)
fix: Remove hard coded TR language tag from back cover template
fix: Remove hard coded TR language tag from back cover template
Lua
agpl-3.0
alerque/casile,alerque/casile,alerque/casile,alerque/casile,alerque/casile
a2cf7eb3d84544c0f9e3e2d22b1a41ef4f8ce36b
cpaste.lua
cpaste.lua
-- CPaste, micro pastebin running on Carbon print("Morning, Ladies and Gentlemen, CPaste here.") -- Settings: ret = assert(loadfile("settings.lua")()) -- Web Paste webpaste = assert(loadfile("webpaste.lua")(ret)) -- Load css local css = "" local f = io.open("thirdparty/highlight.css") if f then print("Read thirdparty/highlight.css") css = f:read("*a") f:close() end -- Actual Code: srv.Use(mw.Logger()) -- Activate logger. getplain = mw.new(function() -- Main Retrieval of Pastes. local seg1 = params("seg1") local seg2 = params("seg2") local id = seg2 local method = "pretty" if id == nil then id = seg1 else method = seg1 id = seg2 if id == nil then content("No such paste.", 404, "text/plain") return end id = id:sub(2, -1) end if seg1 == "paste" then content(webpaste) elseif #id ~= 8 or id == nil then content("No such paste.", 404, "text/plain") else local con, err = redis.connectTimeout(redis_addr, 10) -- Connect to Redis if err ~= nil then error(err) end local res,err = con.Cmd("get", "cpaste:"..id).String() -- Get cpaste:<ID> if err ~= nil then error(err) end local cpastemdata, err = con.Cmd("get", "cpastemdata:"..id).String() if err ~= nil then error(err) end if res == "<nil>" then content(doctype()( tag"head"( tag"title" "CPaste" ), tag"body"( "No such paste." ) )) else if method == "raw" then content(res, 200, "text/plain") elseif method == "pretty" or method == "hl" then if cpastemdata == "html" then content(res) elseif cpastemdata == "plain" then content(syntaxhl(res, hlcss), 200) else content(res, 200, cpastemdata) end else content("No such action. (Try 'raw' or 'pretty')", 404) end end con.Close() end end, {redis_addr=ret.redis, url=ret.url, webpaste=webpaste, hlcss=css}) srv.GET("/:seg1", getplain) srv.GET("/:seg1/*seg2", getplain) srv.GET("/", mw.echo(ret.mainpage)) -- Main page. srv.POST("/", mw.new(function() -- Putting up pastes local data = form("c") or form("f") local type = form("type") or "plain" local expire = tonumber(form("expire")) or expiretime local giveraw = false local giverawform = form("raw") if giverawform == "true" or giverawform == "yes" or giverawform == "y" then giveraw = true else giveraw = false end expire = expire * 60 --Convert the expiration time from seconds to minutes if expire > expiretime then --Prevent the expiration time getting too high expire = expiretime end if data then if #data <= maxpastesize then math.randomseed(unixtime()) local id = "" local stringtable={} for i=1,8 do local n = math.random(48, 122) if (n < 58 or n > 64) and (n < 91 or n > 96) then id = id .. string.char(n) else id = id .. string.char(math.random(97, 122)) end end local con, err = redis.connectTimeout(redis_addr, 10) -- Connect to Redis if err ~= nil then error(err) end local r, err = con.Cmd("set", "cpaste:"..id, data) -- Set cpaste:<randomid> to data if err ~= nil then error(err) end local r, err = con.Cmd("set", "cpastemdata:"..id, type) -- Set cpastemdata:<randomid> to the metadata if err ~= nil then error(err) end local r, err = con.Cmd("expire", "cpaste:"..id, expire) -- Make it expire if err ~= nil then error(err) end local r, err = con.Cmd("expire", "cpastemdata:"..id, expire) -- Make it expire if err ~= nil then error(err) end con.Close() if giveraw then content(url.."raw/"..id.."\n", 200, "text/plain") else content(url..id.."\n", 200, "text/plain") end else content("Content too big. Max is "..tostring(maxpastesize).." Bytes, given "..tostring(#data).." Bytes.", 400, "text/plain") end else content("No content given.", 400, "text/plain") end end, {url=ret.url, expiretime=ret.expiresecs, redis_addr=ret.redis, maxpastesize=ret.maxpastesize})) print("Ready for action!")
-- CPaste, micro pastebin running on Carbon print("Morning, Ladies and Gentlemen, CPaste here.") -- Settings: ret = assert(loadfile("settings.lua")()) -- Web Paste webpaste_f, err = loadfile("webpaste.lua") if not err then webpaste = webpaste_f(ret) else error(err) end -- Load css local css = "" local f = io.open("thirdparty/highlight.css") if f then print("Read thirdparty/highlight.css") css = f:read("*a") f:close() end -- Actual Code: srv.Use(mw.Logger()) -- Activate logger. getplain = mw.new(function() -- Main Retrieval of Pastes. local seg1 = params("seg1") local seg2 = params("seg2") local id = seg2 local method = "pretty" if id == nil then id = seg1 else method = seg1 id = seg2 if id == nil then content("No such paste.", 404, "text/plain") return end id = id:sub(2, -1) end if seg1 == "paste" then content(webpaste) elseif #id ~= 8 or id == nil then content("No such paste.", 404, "text/plain") else local con, err = redis.connectTimeout(redis_addr, 10) -- Connect to Redis if err ~= nil then error(err) end local res,err = con.Cmd("get", "cpaste:"..id).String() -- Get cpaste:<ID> if err ~= nil then error(err) end local cpastemdata, err = con.Cmd("get", "cpastemdata:"..id).String() if err ~= nil then error(err) end if res == "<nil>" then content(doctype()( tag"head"( tag"title" "CPaste" ), tag"body"( "No such paste." ) )) else if method == "raw" then content(res, 200, "text/plain") elseif method == "pretty" or method == "hl" then if cpastemdata == "html" then content(res) elseif cpastemdata == "plain" then content(syntaxhl(res, hlcss), 200) else content(res, 200, cpastemdata) end else content("No such action. (Try 'raw' or 'pretty')", 404) end end con.Close() end end, {redis_addr=ret.redis, url=ret.url, webpaste=webpaste, hlcss=css}) srv.GET("/:seg1", getplain) srv.GET("/:seg1/*seg2", getplain) srv.GET("/", mw.echo(ret.mainpage)) -- Main page. srv.POST("/", mw.new(function() -- Putting up pastes local data = form("c") or form("f") local type = form("type") or "plain" local expire = tonumber(form("expire")) or expiretime local giveraw = false local giverawform = form("raw") if giverawform == "true" or giverawform == "yes" or giverawform == "y" then giveraw = true else giveraw = false end expire = expire * 60 --Convert the expiration time from seconds to minutes if expire > expiretime then --Prevent the expiration time getting too high expire = expiretime end if data then if #data <= maxpastesize then math.randomseed(unixtime()) local id = "" local stringtable={} for i=1,8 do local n = math.random(48, 122) if (n < 58 or n > 64) and (n < 91 or n > 96) then id = id .. string.char(n) else id = id .. string.char(math.random(97, 122)) end end local con, err = redis.connectTimeout(redis_addr, 10) -- Connect to Redis if err ~= nil then error(err) end local r, err = con.Cmd("set", "cpaste:"..id, data) -- Set cpaste:<randomid> to data if err ~= nil then error(err) end local r, err = con.Cmd("set", "cpastemdata:"..id, type) -- Set cpastemdata:<randomid> to the metadata if err ~= nil then error(err) end local r, err = con.Cmd("expire", "cpaste:"..id, expire) -- Make it expire if err ~= nil then error(err) end local r, err = con.Cmd("expire", "cpastemdata:"..id, expire) -- Make it expire if err ~= nil then error(err) end con.Close() if giveraw then content(url.."raw/"..id.."\n", 200, "text/plain") else content(url..id.."\n", 200, "text/plain") end else content("Content too big. Max is "..tostring(maxpastesize).." Bytes, given "..tostring(#data).." Bytes.", 400, "text/plain") end else content("No content given.", 400, "text/plain") end end, {url=ret.url, expiretime=ret.expiresecs, redis_addr=ret.redis, maxpastesize=ret.maxpastesize})) print("Ready for action!")
Fixing error message if the error was in webpaste.lua
Fixing error message if the error was in webpaste.lua
Lua
mit
vifino/cpaste,carbonsrv/cpaste
0a9456826bdd9d0a25dc8d4311e8b5faa9522607
config/wezterm/wezterm.lua
config/wezterm/wezterm.lua
local wezterm = require 'wezterm' local sys = require 'sys' require 'patch_runtime' wezterm.on('update-right-status', function(window, _) -- "Wed Mar 3 08:14" local date = wezterm.strftime '%a %b %-d %H:%M ' local bat = '' for _, b in ipairs(wezterm.battery_info()) do bat = '🔋 ' .. string.format('%.0f%%', b.state_of_charge * 100) end window:set_right_status(wezterm.format { { Text = bat .. ' ' .. date }, }) end) local default_prog if sys.name == 'windows' then -- Use OSC 7 as per the above example -- set_environment_variables['prompt'] = '$E]7;file://localhost/$P$E\\$E[32m$T$E[0m $E[35m$P$E[36m$_$G$E[0m ' -- use a more ls-like output format for dir -- set_environment_variables['DIRCMD'] = '/d' -- And inject clink into the command prompt default_prog = { 'powershell.exe', '-NoLogo', -- '-NoProfile', '-ExecutionPolicy', 'RemoteSigned', -- '-Command', -- '[Console]::InputEncoding=[Console]::OutputEncoding=[System.Text.Encoding]::UTF8;', } end local firacode = sys.name == 'windows' and 'FiraCode NF' or 'FiraCode Nerd Font' local keys = { { key = 'z', mods = 'LEADER', action = 'TogglePaneZoomState' }, { key = 'v', mods = 'LEADER', action = wezterm.action { SplitHorizontal = { domain = 'CurrentPaneDomain' } } }, { key = 's', mods = 'LEADER', action = wezterm.action { SplitVertical = { domain = 'CurrentPaneDomain' } } }, { key = 'n', mods = 'LEADER', action = wezterm.action { SpawnCommandInNewTab = { domain = 'CurrentPaneDomain' } }, }, { key = 'h', mods = 'LEADER', action = wezterm.action { ActivatePaneDirection = 'Left' } }, { key = 'l', mods = 'LEADER', action = wezterm.action { ActivatePaneDirection = 'Right' } }, { key = 'k', mods = 'LEADER', action = wezterm.action { ActivatePaneDirection = 'Up' } }, { key = 'j', mods = 'LEADER', action = wezterm.action { ActivatePaneDirection = 'Down' } }, { key = 'n', mods = 'CTRL|ALT', action = wezterm.action { ActivatePaneDirection = 'Next' } }, { key = 'p', mods = 'CTRL|ALT', action = wezterm.action { ActivatePaneDirection = 'Prev' } }, { key = 'f', mods = 'LEADER', action = wezterm.action { ActivateKeyTable = { name = 'font_size', one_shot = false, }, }, }, { key = 'r', mods = 'LEADER', action = wezterm.action { ActivateKeyTable = { name = 'resize_pane', one_shot = false, }, }, }, { key = 'c', mods = 'LEADER', action = 'ActivateCopyMode' }, { key = 'Insert', mods = 'SHIFT', action = wezterm.action { PasteFrom = 'Clipboard' } }, { key = 'Insert', mods = 'CTRL', action = wezterm.action { CopyTo = 'ClipboardAndPrimarySelection' } }, { key = 'Paste', action = wezterm.action { PasteFrom = 'Clipboard' } }, { key = 'Copy', action = wezterm.action { CopyTo = 'ClipboardAndPrimarySelection' } }, { key = 'q', mods = 'LEADER', action = wezterm.action { CloseCurrentTab = { confirm = false } } }, { key = 'x', mods = 'LEADER', action = wezterm.action { CloseCurrentPane = { confirm = false } } }, } for i = 1, 8 do -- CTRL+ALT + number to activate that tab table.insert(keys, { key = tostring(i), mods = 'LEADER', action = wezterm.action { ActivateTab = i - 1 }, }) -- -- F1 through F8 to activate that tab -- table.insert(tabkeys, { -- key = 'F' .. tostring(i), -- action = wezterm.action { ActivateTab = i - 1 }, -- }) end return { disable_default_key_bindings = true, default_prog = default_prog, font = wezterm.font_with_fallback { { family = firacode, weight = 'Regular', stretch = 'Normal', style = 'Normal', }, 'JetBrains Mono', 'Noto Color Emoji', 'Symbols Nerd Font Mono', 'Last Resort High-Efficiency', }, scrollback_lines = 10000, font_size = 11.0, harfbuzz_features = { 'zero' }, -- use_dead_keys = false, window_close_confirmation = 'NeverPrompt', -- initial_cols = 232, -- initial_rows = 59, hide_tab_bar_if_only_one_tab = true, leader = { key = '\\', mods = 'CTRL', timeout_milliseconds = 1000 }, keys = keys, key_tables = { font_size = { { key = '+', mods = 'SHIFT', action = 'IncreaseFontSize' }, { key = '-', action = 'DecreaseFontSize' }, { key = '=', action = 'ResetFontSize' }, { key = 'Escape', action = 'PopKeyTable' }, { key = 'q', action = 'PopKeyTable' }, { key = 'c', mods = 'CTRL', action = 'PopKeyTable' }, }, resize_pane = { { key = 'LeftArrow', action = wezterm.action { AdjustPaneSize = { 'Left', 1 } } }, { key = 'h', action = wezterm.action { AdjustPaneSize = { 'Left', 1 } } }, { key = 'RightArrow', action = wezterm.action { AdjustPaneSize = { 'Right', 1 } } }, { key = 'l', action = wezterm.action { AdjustPaneSize = { 'Right', 1 } } }, { key = 'UpArrow', action = wezterm.action { AdjustPaneSize = { 'Up', 1 } } }, { key = 'k', action = wezterm.action { AdjustPaneSize = { 'Up', 1 } } }, { key = 'DownArrow', action = wezterm.action { AdjustPaneSize = { 'Down', 1 } } }, { key = 'j', action = wezterm.action { AdjustPaneSize = { 'Down', 1 } } }, { key = 'Escape', action = 'PopKeyTable' }, { key = 'q', action = 'PopKeyTable' }, { key = 'c', mods = 'CTRL', action = 'PopKeyTable' }, }, }, mouse_bindings = { { event = { Up = { streak = 1, button = 'Left' } }, mods = 'CTRL', action = 'OpenLinkAtMouseCursor', }, }, }
require 'patch_runtime' local wezterm = require 'wezterm' local sys = require 'sys' -- local split = require('utils.strings').split -- local list_extend = require('utils.tables').list_extend -- local version_date = tonumber(split(wezterm.version, '-')[1]) wezterm.on('update-right-status', function(window, _) -- "Wed Mar 3 08:14" local date = wezterm.strftime '%a %b %-d %H:%M ' local bat = '' for _, b in ipairs(wezterm.battery_info()) do bat = '🔋 ' .. string.format('%.0f%%', b.state_of_charge * 100) end window:set_right_status(wezterm.format { { Text = bat .. ' ' .. date }, }) end) local default_prog if sys.name == 'windows' then -- Use OSC 7 as per the above example -- set_environment_variables['prompt'] = '$E]7;file://localhost/$P$E\\$E[32m$T$E[0m $E[35m$P$E[36m$_$G$E[0m ' -- use a more ls-like output format for dir -- set_environment_variables['DIRCMD'] = '/d' -- And inject clink into the command prompt default_prog = { 'powershell.exe', '-NoLogo', -- '-NoProfile', '-ExecutionPolicy', 'RemoteSigned', -- '-Command', -- '[Console]::InputEncoding=[Console]::OutputEncoding=[System.Text.Encoding]::UTF8;', } end local firacode = sys.name == 'windows' and 'FiraCode NF' or 'FiraCode Nerd Font' local keys = { { key = 'z', mods = 'LEADER', action = 'TogglePaneZoomState' }, { key = 'R', mods = 'LEADER', action = wezterm.action.ReloadConfiguration }, { key = 'v', mods = 'LEADER', action = wezterm.action { SplitHorizontal = { domain = 'CurrentPaneDomain' } } }, { key = 's', mods = 'LEADER', action = wezterm.action { SplitVertical = { domain = 'CurrentPaneDomain' } } }, { key = 'n', mods = 'LEADER', action = wezterm.action { SpawnCommandInNewTab = { domain = 'CurrentPaneDomain' } }, }, { key = 'h', mods = 'LEADER', action = wezterm.action { ActivatePaneDirection = 'Left' } }, { key = 'l', mods = 'LEADER', action = wezterm.action { ActivatePaneDirection = 'Right' } }, { key = 'k', mods = 'LEADER', action = wezterm.action { ActivatePaneDirection = 'Up' } }, { key = 'j', mods = 'LEADER', action = wezterm.action { ActivatePaneDirection = 'Down' } }, { key = 'n', mods = 'CTRL|ALT', action = wezterm.action { ActivatePaneDirection = 'Next' } }, { key = 'p', mods = 'CTRL|ALT', action = wezterm.action { ActivatePaneDirection = 'Prev' } }, { key = 'f', mods = 'LEADER', action = wezterm.action { ActivateKeyTable = { name = 'font_size', one_shot = false, replace_current = false, }, }, }, { key = 'r', mods = 'LEADER', action = wezterm.action { ActivateKeyTable = { name = 'resize_pane', one_shot = false, replace_current = false, }, }, }, { key = 'c', mods = 'LEADER', action = 'ActivateCopyMode' }, { key = 'Insert', mods = 'SHIFT', action = wezterm.action { PasteFrom = 'Clipboard' } }, { key = 'Insert', mods = 'CTRL', action = wezterm.action { CopyTo = 'ClipboardAndPrimarySelection' } }, { key = 'Paste', action = wezterm.action { PasteFrom = 'Clipboard' } }, { key = 'Copy', action = wezterm.action { CopyTo = 'ClipboardAndPrimarySelection' } }, { key = 'q', mods = 'LEADER', action = wezterm.action { CloseCurrentTab = { confirm = false } } }, { key = 'x', mods = 'LEADER', action = wezterm.action { CloseCurrentPane = { confirm = false } } }, } for i = 1, 8 do -- CTRL+ALT + number to activate that tab table.insert(keys, { key = tostring(i), mods = 'LEADER', action = wezterm.action { ActivateTab = i - 1 }, }) -- -- F1 through F8 to activate that tab -- table.insert(tabkeys, { -- key = 'F' .. tostring(i), -- action = wezterm.action { ActivateTab = i - 1 }, -- }) end return { disable_default_key_bindings = true, default_prog = default_prog, font = wezterm.font_with_fallback { { family = firacode, weight = 'Regular', stretch = 'Normal', style = 'Normal', }, 'JetBrains Mono', 'Noto Color Emoji', 'Symbols Nerd Font Mono', 'Last Resort High-Efficiency', }, color_scheme = 'tokyonight', window_background_opacity = 0.9, scrollback_lines = 10000, font_size = 11.0, harfbuzz_features = { 'zero' }, -- use_dead_keys = false, window_close_confirmation = 'NeverPrompt', -- initial_cols = 232, -- initial_rows = 59, hide_tab_bar_if_only_one_tab = true, leader = { key = '\\', mods = 'CTRL', timeout_milliseconds = 1000 }, keys = keys, key_tables = { font_size = { { key = '+', mods = 'SHIFT', action = 'IncreaseFontSize' }, { key = '-', action = 'DecreaseFontSize' }, { key = '_', mods = 'SHIFT', action = 'DecreaseFontSize' }, { key = '=', action = 'ResetFontSize' }, { key = 'Escape', action = 'PopKeyTable' }, { key = 'q', action = 'PopKeyTable' }, { key = 'c', mods = 'CTRL', action = 'PopKeyTable' }, }, resize_pane = { { key = 'LeftArrow', action = wezterm.action { AdjustPaneSize = { 'Left', 1 } } }, { key = 'h', action = wezterm.action { AdjustPaneSize = { 'Left', 1 } } }, { key = 'RightArrow', action = wezterm.action { AdjustPaneSize = { 'Right', 1 } } }, { key = 'l', action = wezterm.action { AdjustPaneSize = { 'Right', 1 } } }, { key = 'UpArrow', action = wezterm.action { AdjustPaneSize = { 'Up', 1 } } }, { key = 'k', action = wezterm.action { AdjustPaneSize = { 'Up', 1 } } }, { key = 'DownArrow', action = wezterm.action { AdjustPaneSize = { 'Down', 1 } } }, { key = 'j', action = wezterm.action { AdjustPaneSize = { 'Down', 1 } } }, { key = 'Escape', action = 'PopKeyTable' }, { key = 'q', action = 'PopKeyTable' }, { key = 'c', mods = 'CTRL', action = 'PopKeyTable' }, }, }, mouse_bindings = { { event = { Up = { streak = 1, button = 'Left' } }, mods = 'CTRL', action = 'OpenLinkAtMouseCursor', }, }, }
feat: Add new mappings, options and fix windows error
feat: Add new mappings, options and fix windows error Add replace_current option for key_table mappings, missing this option in windows caused startup errors Add color_scheme = 'tokyonight' and set opacity to 0.1 Add new <S-_> font reduction mapping New Reload mapping
Lua
mit
Mike325/dotfiles,Mike325/dotfiles
81d33d33bb519dcbcbfde92e851c2786f6233dbc
core/hyphenator-liang.lua
core/hyphenator-liang.lua
local function addPattern(hyphenator, pattern) local trie = hyphenator.trie local bits = SU.splitUtf8(pattern) for i = 1, #bits do local char = bits[i] if not char:find("%d") then if not(trie[char]) then trie[char] = {} end trie = trie[char] end end trie["_"] = {} local lastWasDigit = 0 for i = 1, #bits do local char = bits[i] if char:find("%d") then lastWasDigit = 1 table.insert(trie["_"], tonumber(char)) elseif lastWasDigit == 1 then lastWasDigit = 0 else table.insert(trie["_"], 0) end end end local function registerException(hyphenator, exception) local text = exception:gsub("-", "") local bits = SU.splitUtf8(exception) hyphenator.exceptions[text] = { } local j = 1 for _, bit in ipairs(bits) do j = j + 1 if bit == "-" then j = j - 1 hyphenator.exceptions[text][j] = 1 else hyphenator.exceptions[text][j] = 0 end end end local function loadPatterns(hyphenator, language) SILE.languageSupport.loadLanguage(language) local languageset = SILE.hyphenator.languages[language] if not (languageset) then print("No patterns for language "..language) return end for _, pattern in pairs(languageset.patterns) do addPattern(hyphenator, pattern) end if not languageset.exceptions then languageset.exceptions = {} end for _, exception in pairs(languageset.exceptions) do registerException(hyphenator, exception) end end SILE._hyphenate = function (self, text) if string.len(text) < self.minWord then return { text } end local points = self.exceptions[text:lower()] local word = SU.splitUtf8(text) if not points then points = SU.map(function ()return 0 end, word) local work = SU.map(string.lower, word) table.insert(work, ".") table.insert(work, 1, ".") table.insert(points, 1, 0) for i = 1, #work do local trie = self.trie for j = i, #work do if not trie[work[j]] then break end trie = trie[work[j]] local p = trie["_"] if p then for k = 1, #p do if points[i + k - 2] and points[i + k - 2] < p[k] then points[i + k - 2] = p[k] end end end end end -- Still inside the no-exceptions case for i = 1, self.leftmin do points[i] = 0 end for i = #points-self.rightmin, #points do points[i] = 0 end end local pieces = {""} for i = 1, #word do pieces[#pieces] = pieces[#pieces] .. word[i] if points[1+i] and 1 == (points[1+i] % 2) then table.insert(pieces, "") end end return pieces end SILE.hyphenator = {} SILE.hyphenator.languages = {} SILE._hyphenators = {} local initHyphenator = function (lang) if not SILE._hyphenators[lang] then SILE._hyphenators[lang] = {minWord = 5, leftmin = 2, rightmin = 2, trie = {}, exceptions = {} } loadPatterns(SILE._hyphenators[lang], lang) end end local hyphenateNode = function (node) if not node:isNnode() or not node.text then return {node} end if node.language and (type(SILE.hyphenator.languages[node.language]) == "function") then return SILE.hyphenator.languages[node.language](node) end initHyphenator(node.language) local breaks = SILE._hyphenate(SILE._hyphenators[node.language], node.text) if #breaks > 1 then local newnodes = {} for j, brk in ipairs(breaks) do if not(brk == "") then for _, newNode in pairs(SILE.shaper:createNnodes(brk, node.options)) do if newNode:isNnode() then newNode.parent = node table.insert(newnodes, newNode) end end if not (j == #breaks) then local discretionary = SILE.nodefactory.newDiscretionary({ prebreak = SILE.shaper:createNnodes(SILE.settings.get("font.hyphenchar"), node.options) }) discretionary.parent = node table.insert(newnodes, discretionary) --table.insert(newnodes, SILE.nodefactory.newPenalty({ value = SILE.settings.get("typesetter.hyphenpenalty") })) end end end node.children = newnodes node.hyphenated = false node.done = false return newnodes end return {node} end SILE.showHyphenationPoints = function (word, language) language = language or "en" initHyphenator(language) return SU.concat(SILE._hyphenate(SILE._hyphenators[language], word), SILE.settings.get("font.hyphenchar")) end SILE.hyphenate = function (nodelist) local newlist = {} for i = 1, #nodelist do local node = nodelist[i] local newnodes = hyphenateNode(node) for j = 1, #newnodes do newlist[#newlist+1] = newnodes[j] end end return newlist end SILE.registerCommand("hyphenator:add-exceptions", function (options, content) local language = options.lang or SILE.settings.get("document.language") SILE.languageSupport.loadLanguage(language) initHyphenator(language) for token in SU.gtoke(content[1]) do if token.string then registerException(SILE._hyphenators[language], token.string) end end end)
local function addPattern(hyphenator, pattern) local trie = hyphenator.trie local bits = SU.splitUtf8(pattern) for i = 1, #bits do local char = bits[i] if not char:find("%d") then if not(trie[char]) then trie[char] = {} end trie = trie[char] end end trie["_"] = {} local lastWasDigit = 0 for i = 1, #bits do local char = bits[i] if char:find("%d") then lastWasDigit = 1 table.insert(trie["_"], tonumber(char)) elseif lastWasDigit == 1 then lastWasDigit = 0 else table.insert(trie["_"], 0) end end end local function registerException(hyphenator, exception) local text = exception:gsub("-", "") local bits = SU.splitUtf8(exception) hyphenator.exceptions[text] = { } local j = 1 for _, bit in ipairs(bits) do j = j + 1 if bit == "-" then j = j - 1 hyphenator.exceptions[text][j] = 1 else hyphenator.exceptions[text][j] = 0 end end end local function loadPatterns(hyphenator, language) SILE.languageSupport.loadLanguage(language) local languageset = SILE.hyphenator.languages[language] if not (languageset) then print("No patterns for language "..language) return end for _, pattern in pairs(languageset.patterns) do addPattern(hyphenator, pattern) end if not languageset.exceptions then languageset.exceptions = {} end for _, exception in pairs(languageset.exceptions) do registerException(hyphenator, exception) end end SILE._hyphenate = function (self, text) if string.len(text) < self.minWord then return { text } end local points = self.exceptions[text:lower()] local word = SU.splitUtf8(text) if not points then points = SU.map(function ()return 0 end, word) local work = SU.map(string.lower, word) table.insert(work, ".") table.insert(work, 1, ".") table.insert(points, 1, 0) for i = 1, #work do local trie = self.trie for j = i, #work do if not trie[work[j]] then break end trie = trie[work[j]] local p = trie["_"] if p then for k = 1, #p do if points[i + k - 2] and points[i + k - 2] < p[k] then points[i + k - 2] = p[k] end end end end end -- Still inside the no-exceptions case for i = 1, self.leftmin do points[i] = 0 end for i = #points-self.rightmin, #points do points[i] = 0 end end local pieces = {""} for i = 1, #word do pieces[#pieces] = pieces[#pieces] .. word[i] if points[1+i] and 1 == (points[1+i] % 2) then table.insert(pieces, "") end end return pieces end SILE.hyphenator = {} SILE.hyphenator.languages = {} SILE._hyphenators = {} local initHyphenator = function (lang) if not SILE._hyphenators[lang] then SILE._hyphenators[lang] = { minWord = 5, leftmin = 2, rightmin = 2, trie = {}, exceptions = {} } loadPatterns(SILE._hyphenators[lang], lang) end end local hyphenateNode = function (node) if not node.language then return { node } end if not node:isNnode() or not node.text then return { node } end if node.language and (type(SILE.hyphenator.languages[node.language]) == "function") then return SILE.hyphenator.languages[node.language](node) end initHyphenator(node.language) local breaks = SILE._hyphenate(SILE._hyphenators[node.language], node.text) if #breaks > 1 then local newnodes = {} for j, brk in ipairs(breaks) do if not(brk == "") then for _, newNode in pairs(SILE.shaper:createNnodes(brk, node.options)) do if newNode:isNnode() then newNode.parent = node table.insert(newnodes, newNode) end end if not (j == #breaks) then local discretionary = SILE.nodefactory.newDiscretionary({ prebreak = SILE.shaper:createNnodes(SILE.settings.get("font.hyphenchar"), node.options) }) discretionary.parent = node table.insert(newnodes, discretionary) --table.insert(newnodes, SILE.nodefactory.newPenalty({ value = SILE.settings.get("typesetter.hyphenpenalty") })) end end end node.children = newnodes node.hyphenated = false node.done = false return newnodes end return { node } end SILE.showHyphenationPoints = function (word, language) language = language or "en" initHyphenator(language) return SU.concat(SILE._hyphenate(SILE._hyphenators[language], word), SILE.settings.get("font.hyphenchar")) end SILE.hyphenate = function (nodelist) local newlist = {} for _, node in ipairs(nodelist) do local newnodes = hyphenateNode(node) if newnodes then for _, n in ipairs(newnodes) do table.insert(newlist, n) end end end return newlist end SILE.registerCommand("hyphenator:add-exceptions", function (options, content) local language = options.lang or SILE.settings.get("document.language") or "und" SILE.languageSupport.loadLanguage(language) initHyphenator(language) for token in SU.gtoke(content[1]) do if token.string then registerException(SILE._hyphenators[language], token.string) end end end)
fix(languages): Make sure hyphenator doesn't ever think language is nil
fix(languages): Make sure hyphenator doesn't ever think language is nil
Lua
mit
alerque/sile,alerque/sile,alerque/sile,alerque/sile
b4e8d5229543b1c945f2e0fe3efd8ea558deaaf5
src/azk/cli/shell.lua
src/azk/cli/shell.lua
local io = require('io') local colors = require('ansicolors') local S = require('syscall') local tablex = require('pl.tablex') local shell = {} local logs_format="%%{reset}%%{%s}azk %s%%{reset}: %s%%{reset}" local logs_type = { ['error'] = "red", info = "blue", warning = "yellow" } local _, err, our, ouw = S.pipe() local _, err, oer, oew = S.pipe() local inb = S.dup(0) local oub = S.dup(1) local oeb = S.dup(2) function shell.capture_io(input, func) local _, err, inr, inw = S.pipe() if func == nil then func, input = input, nil end -- Clear before data io.stdout:flush() io.stderr:flush() -- Fake input if input ~= nil then inw:write(input .. "\n") end -- Replace defaults assert(S.dup2(inr, 0)) assert(S.dup2(ouw, 1)) assert(S.dup2(oew, 2)) -- Run code with print and read func(inw, our) ouw:write("\n") oew:write("\n") -- Restore and reset default S.dup2(inb, 0) S.dup2(oub, 1) S.dup2(oeb, 2) io.stdout:flush() io.stderr:flush() io.stdout:setvbuf("no") io.stderr:setvbuf("no") -- Return capture return { ['stdout'] = our:read():gsub("\n$", ""), ['stderr'] = oer:read():gsub("\n$", "") } end function shell.format(data, ...) return colors.noReset(data):format(...) end function shell.write(...) io.stdout:write(shell.format(...)) end function shell.print(...) shell.write(...) io.stdout:write("\n") end function shell.capture(...) shell.write(...) return io.stdin:read() end tablex.foreach(logs_type, function(color, log) shell[log] = function(msgs, ...) msgs = logs_format:format(color, log, msgs) shell.print(msgs, ...) end end) return shell
local io = require('io') local colors = require('ansicolors') local S = require('syscall') local tablex = require('pl.tablex') local shell = {} local logs_format="%%{reset}%%{%s}azk %s%%{reset}: %s%%{reset}" local logs_type = { ['error'] = "red", info = "blue", warning = "yellow" } local _, err, our, ouw = S.pipe() local _, err, oer, oew = S.pipe() local inb = S.dup(0) local oub = S.dup(1) local oeb = S.dup(2) function shell.capture_io(input, func) local _, err, inr, inw = S.pipe() if func == nil then func, input = input, nil end -- Clear before data io.stdout:flush() io.stderr:flush() -- Fake input if input ~= nil then inw:write(input .. "\n") end -- Replace defaults assert(S.dup2(inr, 0)) assert(S.dup2(ouw, 1)) assert(S.dup2(oew, 2)) -- Run code with print and read local _, err = pcall(func, inw, our) ouw:write("\n") oew:write("\n") -- Restore and reset default S.dup2(inb, 0) S.dup2(oub, 1) S.dup2(oeb, 2) io.stdout:flush() io.stderr:flush() io.stdout:setvbuf("no") io.stderr:setvbuf("no") if err then error(err) end -- Return capture return { ['stdout'] = our:read():gsub("\n$", ""), ['stderr'] = oer:read():gsub("\n$", "") } end --function shell.capture_io(input, func) --return {} --end function shell.format(data, ...) return colors.noReset(data):format(...) end function shell.write(...) io.stdout:write(shell.format(...)) end function shell.print(...) shell.write(...) io.stdout:write("\n") end function shell.capture(...) shell.write(...) return io.stdin:read() end tablex.foreach(logs_type, function(color, log) shell[log] = function(msgs, ...) msgs = logs_format:format(color, log, msgs) shell.print(msgs, ...) end end) return shell
Fixing shell.capture_io to guard of raise errors and propagate then.
Fixing shell.capture_io to guard of raise errors and propagate then.
Lua
apache-2.0
azukiapp/azk,heitortsergent/azk,saitodisse/azk-travis-test,marcusgadbem/azk,nuxlli/azk,teodor-pripoae/azk,agendor/azk,slobo/azk,nuxlli/azk,renanmpimentel/azk,saitodisse/azk,agendor/azk,Klaudit/azk,renanmpimentel/azk,marcusgadbem/azk,fearenales/azk,slobo/azk,Klaudit/azk,teodor-pripoae/azk,azukiapp/azk,juniorribeiro/azk,gullitmiranda/azk,saitodisse/azk,saitodisse/azk-travis-test,fearenales/azk,juniorribeiro/azk,heitortsergent/azk,gullitmiranda/azk
a4b360074654140afa7aa85474197b56ffa30ba3
ios-icons/icons.lua
ios-icons/icons.lua
local icons_mt = {} icons_mt.__tostring = function(i) local result = "Icon Set\n\n" for _, p in ipairs(i) do result = result .. tostring(p) end result = result .. "\n" return result end local icons = {} icons.__meta = icons_mt icons.flatten = function(tab) local insert = table.insert local result = {} local function isEntry(e) return (type(e) == 'table' and e.id) end local function flatten(tab) for _,v in ipairs(tab) do if isEntry(v) then insert(result, v) else flatten(v) end end end flatten(tab) return result end icons.dock = function(tab) return tab[1] end icons.find_all = function(tab, pat) local strfind = string.find local insert = table.insert local result = {} local all_icons = tab:flatten() for _,v in pairs(all_icons) do if strfind(v.name or '', pat) then insert(result, v) end end return result end icons.find = function(tab, pat) local strfind = string.find local all_icons = tab:flatten() for _,v in pairs(all_icons) do if strfind(v.name or '', pat) then return v end end return nil end icons.find_id = function(tab, pat) local strfind = string.find local all_icons = tab:flatten() for _,v in pairs(all_icons) do if strfind(v.id or '', pat) then return v end end return nil end icons.visit = function(tab, visitor) assert(type(visitor) == 'function', 'visitor must be a function') for _,v in pairs(tab) do visitor(v) end end local dockMax = 4 local pageMax = 9 -- TODO: handle fillPercent -- TODO: pass in page size as a parameter with a default (x = x or default) icons.reshape = function(tab, fillPercent) local result = {} local page = {} local count = 1 local insert = table.insert for i,v in ipairs(tab) do if i < dockMax then insert(page, v) elseif i == dockMax then insert(page, v) insert(result, page) page = {} count = 1 elseif count % pageMax ~= 0 then insert(page, v) count = count + 1 else insert(page, v) insert(result, page) page = {} count = 1 end end return result end return icons
local icons_mt = {} icons_mt.__tostring = function(i) local result = "Icon Set\n\n" for _, p in ipairs(i) do result = result .. tostring(p) end result = result .. "\n" return result end local icons = {} icons.__meta = icons_mt icons.flatten = function(tab) local insert = table.insert local result = {} local function isEntry(e) return (type(e) == 'table' and e.id) end local function flatten(tab) for _,v in pairs(tab) do if isEntry(v) then insert(result, v) else if type(v) == 'table' then flatten(v) end end end end flatten(tab) return result end icons.dock = function(tab) return tab[1] end icons.find_all = function(tab, pat) local strfind = string.find local insert = table.insert local result = {} local all_icons = tab:flatten() for _,v in pairs(all_icons) do if strfind(v.name or '', pat) then insert(result, v) end end return result end icons.find = function(tab, pat) local strfind = string.find local all_icons = tab:flatten() for _,v in pairs(all_icons) do if strfind(v.name or '', pat) then return v end end return nil end icons.find_id = function(tab, pat) local strfind = string.find local all_icons = tab:flatten() for _,v in pairs(all_icons) do if strfind(v.id or '', pat) then return v end end return nil end icons.visit = function(tab, visitor) assert(type(visitor) == 'function', 'visitor must be a function') for _,v in pairs(tab) do visitor(v) end end local dockMax = 4 local pageMax = 9 -- TODO: handle fillPercent -- TODO: pass in page size as a parameter with a default (x = x or default) icons.reshape = function(tab, fillPercent) local result = {} local page = {} local count = 1 local insert = table.insert for i,v in ipairs(tab) do if i < dockMax then insert(page, v) elseif i == dockMax then insert(page, v) insert(result, page) page = {} count = 1 elseif count % pageMax ~= 0 then insert(page, v) count = count + 1 else insert(page, v) insert(result, page) page = {} count = 1 end end return result end return icons
fixed flatten function to handle folders
fixed flatten function to handle folders
Lua
mit
profburke/ios-icons,profburke/ios-icons,profburke/ios-icons
a8039b2e0e34c1c48e129b3b815fb62da9a0ccb3
scheduled/spawnpoint.lua
scheduled/spawnpoint.lua
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] require("base.common") module("scheduled.spawnpoint", package.seeall) -- INSERT INTO scheduledscripts VALUES('scheduled.spawnpoint', 5, 5, 'startSpawnpoint'); -- This script is used for character independet events lasting over some time -- conatining all center points SPAWNDATAS = {} gmSpawnpointSettings = {} gmMonsters = {} -- get active bomb information by center position SPAWNDATA = {} function startSpawnpoint() spawnGM() end function spawnGM() local mon; if gmSpawnpointSettings[1] == nil then return end for i=1, #gmSpawnpointSettings do local monsterIds = gmSpawnpointSettings[i][1]; local position = gmSpawnpointSettings[i][2]; local amount = gmSpawnpointSettings[i][3]; local intervals = gmSpawnpointSettings[i][4]; local endurance = gmSpawnpointSettings[i][5]; local gfxId = gmSpawnpointSettings[i][6]; local sfxId = gmSpawnpointSettings[i][7]; local pause = gmSpawnpointSettings[i][9]; --sets/checks 8 array pos as counter if checkValue(pause) == false then if gmSpawnpointSettings[i][8] == nil then gmSpawnpointSettings[i][8] = 0; else gmSpawnpointSettings[i][8] = gmSpawnpointSettings[i][8]+1; end if checkValue(intervals) == false then intervals = 1 end if gmSpawnpointSettings[i][8] % intervals == 0 then --keeps counter from overflow if checkValue(endurance) == false then gmSpawnpointSettings[i][8] = 0 end if #gmMonsters[i]-1 < amount then updateMonsters(gmMonsters,i); mon = world:createMonster(monsterIds[Random.uniform(1,#monsterIds)], position,10); if isValidChar(mon) then table.insert(gmMonsters[i],mon); --does GFX with spawn if checkValue(gfxId) == true then world:gfx(gfxId,position) end --Does SFX with spawn if checkValue(sfxId) == true then world:makeSound(sfxId,position) end end else updateMonsters(gmMonsters,i); end end --Removes spawnpoint if he reaches the maximum number of cycles if checkValue(endurance) == true then if gmSpawnpointSettings[i][8] >= endurance then table.remove(gmSpawnpointSettings, i) table.remove(gmMonsters, i) end end end end end function checkValue(input) if input == 0 then return false else return true end end function updateMonsters(array,number) for i=2, #array[number] do local mon = array[number][i] if not isValidChar(mon) then table.remove(array[number], i) end end end
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] require("base.common") module("scheduled.spawnpoint", package.seeall) -- INSERT INTO scheduledscripts VALUES('scheduled.spawnpoint', 5, 5, 'startSpawnpoint'); -- This script is used for character independet events lasting over some time -- conatining all center points SPAWNDATAS = {} gmSpawnpointSettings = {} gmMonsters = {} -- get active bomb information by center position SPAWNDATA = {} function startSpawnpoint() spawnGM() end function spawnGM() local mon; if gmSpawnpointSettings[1] == nil then return end for i=1, #gmSpawnpointSettings do local monsterIds = gmSpawnpointSettings[i][1]; local position = gmSpawnpointSettings[i][2]; local amount = gmSpawnpointSettings[i][3]; local intervals = gmSpawnpointSettings[i][4]; local endurance = gmSpawnpointSettings[i][5]; local gfxId = gmSpawnpointSettings[i][6]; local sfxId = gmSpawnpointSettings[i][7]; local pause = gmSpawnpointSettings[i][9]; --sets/checks 8 array pos as counter if checkValue(pause) == false then if gmSpawnpointSettings[i][8] == nil then gmSpawnpointSettings[i][8] = 0; else gmSpawnpointSettings[i][8] = gmSpawnpointSettings[i][8]+1; end if checkValue(intervals) == false then intervals = 1 end if gmSpawnpointSettings[i][8] % intervals == 0 then --keeps counter from overflow if checkValue(endurance) == false then gmSpawnpointSettings[i][8] = 0 end if #gmMonsters[i]-1 < amount then updateMonsters(gmMonsters,i); mon = world:createMonster(monsterIds[Random.uniform(1,#monsterIds)], position,10); if isValidChar(mon) then table.insert(gmMonsters[i],mon); --does GFX with spawn if checkValue(gfxId) == true then world:gfx(gfxId,position) end --Does SFX with spawn if checkValue(sfxId) == true then world:makeSound(sfxId,position) end end else updateMonsters(gmMonsters,i); end end --Removes spawnpoint if he reaches the maximum number of cycles if checkValue(endurance) == true then if gmSpawnpointSettings[i][8] >= endurance then table.remove(gmSpawnpointSettings, i) table.remove(gmMonsters, i) end end end end end function checkValue(input) if input == 0 then return false else return true end end function updateMonsters(array,number) if #array[number] > 1 then for i=2, #array[number] do local mon = array[number][i]; if not isValidChar(mon) then table.remove(array[number], i) end end end end
Fix spawnPoint
Fix spawnPoint
Lua
agpl-3.0
LaFamiglia/Illarion-Content,KayMD/Illarion-Content,Illarion-eV/Illarion-Content,vilarion/Illarion-Content,Baylamon/Illarion-Content
ec78031251b3f5e7cc343144141d92dfbe51fa7e
src/cosy/cli/test.lua
src/cosy/cli/test.lua
-- These lines are required to correctly run tests: require "cosy.loader.busted" require "busted.runner" () local File = require "cosy.file" describe ("Module cosy.cli", function () local Cli local Configuration before_each (function () package.loaded ["cosy.cli"] = nil -- reload to reset Cli = require "cosy.cli" Configuration = require "cosy.configuration" Configuration.cli.data = os.tmpname() Configuration.cli.server = "dummy_default" -- override to a known default value end) after_each (function () os.remove( Configuration.cli.data ) end) describe ("parsing options by method configure", function () for _, key in ipairs { "server", -- "color", } do it ("should detect the --" .. key, function () Cli.configure { "--debug=true", "--".. key .. "=any_value", } assert.are.equal (Cli [key], "any_value") end) it ("should detect --" .. key .. " is missing", function () Cli.configure { "--debug=true", "-".. key .. "=any_value", } assert.are.equal (Cli [key] , "dummy_default") end) it ("should fail by detecting several --" .. key, function () assert.has.errors (function () Cli.configure { "--debug=true", "--".. key .. "=any_value", "--".. key .. "=any_value", } end) end) end end) describe ("saving options by method configure", function () it ("should detect the --server", function () Cli.configure { "--debug=true", "--server=server_uri_from_cmd_line", } -- assert server was found was set assert.are.equal (Cli.server, "server_uri_from_cmd_line") -- assert config was saved to config file local saved_config = File.decode (Configuration.cli.data) assert.are.equal (saved_config.server, Cli.server) end) -- case server defined by file -- case server defined by default -- case no server defined end) end)
-- These lines are required to correctly run tests: require "cosy.loader.busted" require "busted.runner" () local File = require "cosy.file" describe ("Module cosy.cli", function () local Cli local Configuration before_each (function () package.loaded ["cosy.cli"] = nil -- reload to reset Cli = require "cosy.cli" Configuration = require "cosy.configuration" Configuration.cli.data = os.tmpname() Configuration.cli.server = "dummy_default" -- override to a known default value end) after_each (function () os.remove( Configuration.cli.data ) end) describe ("parsing options by method configure", function () for _, key in ipairs { "server", -- "color", } do it ("should detect the --" .. key, function () Cli.configure { "--debug=true", "--".. key .. "=any_value", } assert.are.equal (Cli [key], "any_value") end) it ("should detect --" .. key .. " is missing", function () Cli.configure { "--debug=true", "-".. key .. "=any_value", } assert.are.equal (Cli [key] , "dummy_default") end) it ("should fail by detecting several --" .. key, function () assert.has.errors (function () Cli.configure { "--debug=true", "--".. key .. "=any_value", "--".. key .. "=any_value", } end) end) end end) describe ("saving options by method configure", function () it ("should detect the --server", function () Cli.configure { "--debug=true", "--server=server_uri_from_cmd_line", } -- assert server was found and set assert.are.equal (Cli.server, "server_uri_from_cmd_line") -- assert config was saved to config file local saved_config = File.decode (Configuration.cli.data) assert.are.equal (saved_config.server, Cli.server) end) end) end)
Fix comments.
Fix comments.
Lua
mit
CosyVerif/library,CosyVerif/library,CosyVerif/library
b5e08529c5257589df14cea7942bacf634f7ba54
share/luaplaylist/youtube.lua
share/luaplaylist/youtube.lua
-- $Id$ -- Helper function to get a parameter's value in a URL function get_url_param( url, name ) return string.gsub( vlc.path, "^.*"..name.."=([^&]*).*$", "%1" ) end -- Probe function. function probe() return vlc.access == "http" and string.match( vlc.path, "youtube.com" ) and ( string.match( vlc.path, "watch%?v=" ) or string.match( vlc.path, "watch_fullscreen%?video_id=" ) or string.match( vlc.path, "p.swf" ) or string.match( vlc.path, "player2.swf" ) ) end -- Parse function. function parse() if string.match( vlc.path, "watch%?v=" ) then -- This is the HTML page's URL while true do -- Try to find the video's title line = vlc.readline() if not line then break end if string.match( line, "<meta name=\"title\"" ) then name = string.gsub( line, "^.*content=\"([^\"]*).*$", "%1" ) end if string.match( line, "<meta name=\"description\"" ) then description = string.gsub( line, "^.*content=\"([^\"]*).*$", "%1" ) end if string.match( line, "subscribe_to_user=" ) then artist = string.gsub( line, ".*subscribe_to_user=([^&]*).*", "%1" ) end if string.match( line, "player2.swf" ) then video_id = string.gsub( line, ".*BASE_YT_URL=http://youtube.com/&video_id=([^\"]*).*", "%1" ) end if name and description and artist and video_id then break end end return { { path = "http://www.youtube.com/get_video.php?video_id="..video_id; name = name; description = description; artist = artist } } else -- This is the flash player's URL if string.match( vlc.path, "title=" ) then name = get_url_param( vlc.path, "title" ) end return { { path = "http://www.youtube.com/get_video.php?video_id="..get_url_param( vlc.path, "video_id" ).."&t="..get_url_param( vlc.patch, "t" ); name = name } } end end
-- $Id$ -- Helper function to get a parameter's value in a URL function get_url_param( url, name ) return string.gsub( vlc.path, "^.*"..name.."=([^&]*).*$", "%1" ) end -- Probe function. function probe() return vlc.access == "http" and string.match( vlc.path, "youtube.com" ) and ( string.match( vlc.path, "watch%?v=" ) or string.match( vlc.path, "watch_fullscreen%?video_id=" ) or string.match( vlc.path, "p.swf" ) or string.match( vlc.path, "player2.swf" ) ) end -- Parse function. function parse() if string.match( vlc.path, "watch%?v=" ) then -- This is the HTML page's URL while true do -- Try to find the video's title line = vlc.readline() if not line then break end if string.match( line, "<meta name=\"title\"" ) then name = string.gsub( line, "^.*content=\"([^\"]*).*$", "%1" ) end if string.match( line, "<meta name=\"description\"" ) then description = string.gsub( line, "^.*content=\"([^\"]*).*$", "%1" ) end if string.match( line, "subscribe_to_user=" ) then artist = string.gsub( line, ".*subscribe_to_user=([^&]*).*", "%1" ) end if string.match( line, "player2.swf" ) then video_id = string.gsub( line, ".*&video_id=([^\"]*).*", "%1" ) end if name and description and artist and video_id then break end end return { { path = "http://www.youtube.com/get_video.php?video_id="..video_id; name = name; description = description; artist = artist } } else -- This is the flash player's URL if string.match( vlc.path, "title=" ) then name = get_url_param( vlc.path, "title" ) end return { { path = "http://www.youtube.com/get_video.php?video_id="..get_url_param( vlc.path, "video_id" ).."&t="..get_url_param( vlc.patch, "t" ); name = name } } end end
Fixes youtube parsing on www.youtube.com website
Fixes youtube parsing on www.youtube.com website
Lua
lgpl-2.1
jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,shyamalschandra/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.1,shyamalschandra/vlc,shyamalschandra/vlc,shyamalschandra/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc,vlc-mirror/vlc,vlc-mirror/vlc-2.1,jomanmuk/vlc-2.2,jomanmuk/vlc-2.1,xkfz007/vlc,vlc-mirror/vlc,jomanmuk/vlc-2.1,shyamalschandra/vlc,krichter722/vlc,vlc-mirror/vlc,krichter722/vlc,xkfz007/vlc,jomanmuk/vlc-2.2,krichter722/vlc,xkfz007/vlc,krichter722/vlc,shyamalschandra/vlc,xkfz007/vlc,jomanmuk/vlc-2.1,vlc-mirror/vlc,vlc-mirror/vlc-2.1,shyamalschandra/vlc,vlc-mirror/vlc-2.1,krichter722/vlc,xkfz007/vlc,vlc-mirror/vlc-2.1,vlc-mirror/vlc-2.1,xkfz007/vlc,jomanmuk/vlc-2.2,vlc-mirror/vlc-2.1,krichter722/vlc,jomanmuk/vlc-2.2,jomanmuk/vlc-2.2,xkfz007/vlc,jomanmuk/vlc-2.1,jomanmuk/vlc-2.1,krichter722/vlc