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
e2b790ac217656b8ed52047426151a7d3e0f56de
frlib/primitives/simple.lua
frlib/primitives/simple.lua
-- Import relevant base types. local types = require "base.types" require "base.vec2" require "base.vec3" -- Import utility functions. local geometric = require "base.geometric" -- Module aliases. local vec2 = types.vec2 local vec3 = types.vec3 local normalize = geometric.normalize -- Creates a function that returns geometry for a cube with sides of length n -- centered at the origin. local function cube(n) return function() local half_n = n / 2 -- Front face. triangle {{ v = vec3(half_n, -half_n, half_n), n = normalize(vec3(1, -1, 1)), t = vec2(0, 0) }, { v = vec3(half_n, half_n, half_n), n = normalize(vec3(1, 1, 1)), t = vec2(0, 1) }, { v = vec3(half_n, -half_n, half_n), n = normalize(vec3(1, -1, 1)), t = vec2(1, 0) }} triangle {{ v = vec3(half_n, half_n, half_n), n = normalize(vec3(1, 1, 1)), t = vec2(1, 1) }, { v = vec3(half_n, -half_n, half_n), n = normalize(vec3(1, -1, 1)), t = vec2(1, 0) }, { v = vec3(half_n, half_n, half_n), n = normalize(vec3(1, 1, 1)), t = vec2(0, 1) }} -- Back face. triangle {{ v = vec3(half_n, -half_n, -half_n), n = normalize(vec3(1, -1, -1)), t = vec2(0, 0) }, { v = vec3(half_n, half_n, -half_n), n = normalize(vec3(1, 1, -1)), t = vec2(0, 1) }, { v = vec3(half_n, -half_n, -half_n), n = normalize(vec3(1, -1, -1)), t = vec2(1, 0) }} triangle {{ v = vec3(half_n, half_n, -half_n), n = normalize(vec3(1, 1, -1)), t = vec2(1, 1) }, { v = vec3(half_n, -half_n, -half_n), n = normalize(vec3(1, -1, -1)), t = vec2(1, 0) }, { v = vec3(half_n, half_n, -half_n), n = normalize(vec3(1, 1, -1)), t = vec2(0, 1) }} -- Left face. triangle {{ v = vec3(half_n, -half_n, -half_n), n = normalize(vec3(1, -1, -1)), t = vec2(0, 0) }, { v = vec3(half_n, half_n, -half_n), n = normalize(vec3(1, 1, -1)), t = vec2(0, 1) }, { v = vec3(half_n, -half_n, half_n), n = normalize(vec3(1, -1, 1)), t = vec2(1, 0) }} triangle {{ v = vec3(half_n, half_n, half_n), n = normalize(vec3(1, 1, 1)), t = vec2(1, 1) }, { v = vec3(half_n, -half_n, half_n), n = normalize(vec3(1, -1, 1)), t = vec2(1, 0) }, { v = vec3(half_n, half_n, -half_n), n = normalize(vec3(1, 1, -1)), t = vec2(0, 1) }} -- Right face. triangle {{ v = vec3(half_n, -half_n, half_n), n = normalize(vec3(1, -1, 1)), t = vec2(0, 0) }, { v = vec3(half_n, half_n, half_n), n = normalize(vec3(1, 1, 1)), t = vec2(0, 1) }, { v = vec3(half_n, -half_n, -half_n), n = normalize(vec3(1, -1, -1)), t = vec2(1, 0) }} triangle {{ v = vec3(half_n, half_n, -half_n), n = normalize(vec3(1, 1, -1)), t = vec2(1, 1) }, { v = vec3(half_n, -half_n, -half_n), n = normalize(vec3(1, -1, -1)), t = vec2(1, 0) }, { v = vec3(half_n, half_n, half_n), n = normalize(vec3(1, 1, 1)), t = vec2(0, 1) }} -- Top face. triangle {{ v = vec3(half_n, half_n, half_n), n = normalize(vec3(1, 1, 1)), t = vec2(0, 0) }, { v = vec3(half_n, half_n, -half_n), n = normalize(vec3(1, 1, -1)), t = vec2(0, 1) }, { v = vec3(half_n, half_n, half_n), n = normalize(vec3(1, 1, 1)), t = vec2(1, 0) }} triangle {{ v = vec3(half_n, half_n, -half_n), n = normalize(vec3(1, 1, -1)), t = vec2(1, 1) }, { v = vec3(half_n, half_n, half_n), n = normalize(vec3(1, 1, 1)), t = vec2(1, 0) }, { v = vec3(half_n, half_n, -half_n), n = normalize(vec3(1, 1, -1)), t = vec2(0, 1) }} -- Bottom face. triangle {{ v = vec3(half_n, -half_n, -half_n), n = normalize(vec3(1, -1, -1)), t = vec2(0, 0) }, { v = vec3(half_n, -half_n, half_n), n = normalize(vec3(1, -1, 1)), t = vec2(0, 1) }, { v = vec3(half_n, -half_n, -half_n), n = normalize(vec3(1, -1, -1)), t = vec2(1, 0) }} triangle {{ v = vec3(half_n, -half_n, half_n), n = normalize(vec3(1, -1, 1)), t = vec2(1, 1) }, { v = vec3(half_n, -half_n, -half_n), n = normalize(vec3(1, -1, -1)), t = vec2(1, 0) }, { v = vec3(half_n, -half_n, half_n), n = normalize(vec3(1, -1, 1)), t = vec2(0, 1) }} end end -- Module exports. return { cube = cube }
-- Import relevant base types. local types = require "base.types" require "base.vec2" require "base.vec3" -- Import utility functions. local geometric = require "base.geometric" -- Module aliases. local vec2 = types.vec2 local vec3 = types.vec3 -- Creates a function that returns geometry for a cube with sides of length n -- centered at the origin. local function cube(n) return function() local h = n / 2 -- Front face. triangle {{ v = vec3(-h, -h, h), n = vec3(0, 0, 1), t = vec2(0, 0) }, { v = vec3(-h, h, h), n = vec3(0, 0, 1), t = vec2(0, 1) }, { v = vec3(h, -h, h), n = vec3(0, 0, 1), t = vec2(1, 0) }} triangle {{ v = vec3(h, h, h), n = vec3(0, 0, 1), t = vec2(1, 1) }, { v = vec3(h, -h, h), n = vec3(0, 0, 1), t = vec2(1, 0) }, { v = vec3(-h, h, h), n = vec3(0, 0, 1), t = vec2(0, 1) }} -- Back face. triangle {{ v = vec3(h, -h, -h), n = vec3(0, 0, -1), t = vec2(0, 0) }, { v = vec3(h, h, -h), n = vec3(0, 0, -1), t = vec2(0, 1) }, { v = vec3(-h, -h, -h), n = vec3(0, 0, -1), t = vec2(1, 0) }} triangle {{ v = vec3(-h, h, -h), n = vec3(0, 0, -1), t = vec2(1, 1) }, { v = vec3(-h, -h, -h), n = vec3(0, 0, -1), t = vec2(1, 0) }, { v = vec3(h, h, -h), n = vec3(0, 0, -1), t = vec2(0, 1) }} -- Left face. triangle {{ v = vec3(-h, -h, -h), n = vec3(-1, 0, 0), t = vec2(0, 0) }, { v = vec3(-h, h, -h), n = vec3(-1, 0, 0), t = vec2(0, 1) }, { v = vec3(-h, -h, h), n = vec3(-1, 0, 0), t = vec2(1, 0) }} triangle {{ v = vec3(-h, h, h), n = vec3(-1, 0, 0), t = vec2(1, 1) }, { v = vec3(-h, -h, h), n = vec3(-1, 0, 0), t = vec2(1, 0) }, { v = vec3(-h, h, -h), n = vec3(-1, 0, 0), t = vec2(0, 1) }} -- Right face. triangle {{ v = vec3(h, -h, h), n = vec3(1, 0, 0), t = vec2(0, 0) }, { v = vec3(h, h, h), n = vec3(1, 0, 0), t = vec2(0, 1) }, { v = vec3(h, -h, -h), n = vec3(1, 0, 0), t = vec2(1, 0) }} triangle {{ v = vec3(h, h, -h), n = vec3(1, 0, 0), t = vec2(1, 1) }, { v = vec3(h, -h, -h), n = vec3(1, 0, 0), t = vec2(1, 0) }, { v = vec3(h, h, h), n = vec3(1, 0, 0), t = vec2(0, 1) }} -- Top face. triangle {{ v = vec3(-h, h, h), n = vec3(0, 1, 0), t = vec2(0, 0) }, { v = vec3(-h, h, -h), n = vec3(0, 1, 0), t = vec2(0, 1) }, { v = vec3(h, h, h), n = vec3(0, 1, 0), t = vec2(1, 0) }} triangle {{ v = vec3(h, h, -h), n = vec3(0, 1, 0), t = vec2(1, 1) }, { v = vec3(h, h, h), n = vec3(0, 1, 0), t = vec2(1, 0) }, { v = vec3(-h, h, -h), n = vec3(0, 1, 0), t = vec2(0, 1) }} -- Bottom face. triangle {{ v = vec3(-h, -h, -h), n = vec3(0, -1, 0), t = vec2(0, 0) }, { v = vec3(-h, -h, h), n = vec3(0, -1, 0), t = vec2(0, 1) }, { v = vec3(h, -h, -h), n = vec3(0, -1, 0), t = vec2(1, 0) }} triangle {{ v = vec3(h, -h, h), n = vec3(0, -1, 0), t = vec2(1, 1) }, { v = vec3(h, -h, -h), n = vec3(0, -1, 0), t = vec2(1, 0) }, { v = vec3(-h, -h, h), n = vec3(0, -1, 0), t = vec2(0, 1) }} end end -- Module exports. return { cube = cube }
Fixed bug in cube.
Fixed bug in cube.
Lua
mit
bobsomers/flexrender,bobsomers/flexrender
6703fc1a1af5b8ed63240bf25a25b099d7188a6a
src/hs/finalcutpro/main/Playhead.lua
src/hs/finalcutpro/main/Playhead.lua
local log = require("hs.logger").new("timline") local inspect = require("hs.inspect") local just = require("hs.just") local axutils = require("hs.finalcutpro.axutils") local Playhead = {} function Playhead:new(parent) o = {_parent = parent} setmetatable(o, self) self.__index = self return o end function Playhead:parent() return self._parent end function Playhead:app() return self:parent():app() end ----------------------------------------------------------------------- ----------------------------------------------------------------------- --- BROWSER UI ----------------------------------------------------------------------- ----------------------------------------------------------------------- function Playhead:UI() return axutils.cache(self, "_ui", function() local ui = self:parent():UI() if ui then return axutils.childWith(ui, "AXRole", "AXValueIndicator") end return nil end) end function Playhead:isShowing() return self:UI() ~= nil end function Playhead:show() local parent = self:parent() -- show the parent. if parent:show() then -- ensure the playhead is visible -- TODO end return self end function Playhead:hide() return self:parent():hide() end function Playhead:getTimecode() local ui = self:UI() return ui and ui:attributeValue("AXValue") end function Playhead:getX() local ui = self:UI() return ui and ui:position().x end function Playhead:getPosition() local ui = self:UI() if ui then local frame = ui:frame() return frame.x + frame.w/2 + 1.0 end return nil end return Playhead
local log = require("hs.logger").new("timline") local inspect = require("hs.inspect") local just = require("hs.just") local axutils = require("hs.finalcutpro.axutils") local Playhead = {} function Playhead.isPlayhead(element) return element and element:attributeValue("AXRole") == "AXValueIndicator" end function Playhead:new(parent) o = {_parent = parent} setmetatable(o, self) self.__index = self return o end function Playhead:parent() return self._parent end function Playhead:app() return self:parent():app() end ----------------------------------------------------------------------- ----------------------------------------------------------------------- --- BROWSER UI ----------------------------------------------------------------------- ----------------------------------------------------------------------- function Playhead:UI() return axutils.cache(self, "_ui", function() local ui = self:parent():UI() if ui then return axutils.childWith(ui, "AXRole", "AXValueIndicator") end return nil end, Playhead.isPlayhead) end function Playhead:isShowing() return self:UI() ~= nil end function Playhead:show() local parent = self:parent() -- show the parent. if parent:show() then -- ensure the playhead is visible -- TODO end return self end function Playhead:hide() return self:parent():hide() end function Playhead:getTimecode() local ui = self:UI() return ui and ui:attributeValue("AXValue") end function Playhead:getX() local ui = self:UI() return ui and ui:position().x end function Playhead:getPosition() local ui = self:UI() if ui then local frame = ui:frame() return frame.x + frame.w/2 + 1.0 end return nil end return Playhead
#64 * Fixed bug where making edits on the timeline would confuse Lock Playhead.
#64 * Fixed bug where making edits on the timeline would confuse Lock Playhead.
Lua
mit
cailyoung/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost,cailyoung/CommandPost,cailyoung/CommandPost,fcpxhacks/fcpxhacks
8ba20b1813a06697018504f40f862088956a2017
src/sounds/src/Shared/SoundUtils.lua
src/sounds/src/Shared/SoundUtils.lua
--[=[ Helps plays back sounds in the Roblox engine. ```lua SoundUtils.playFromId("rbxassetid://4255432837") -- Plays a wooshing sound ``` @class SoundUtils ]=] local SoundService = game:GetService("SoundService") local RunService = game:GetService("RunService") local SoundUtils = {} --[=[ Plays back a template given asset id. ```lua SoundUtils.playFromId("rbxassetid://4255432837") -- Plays a wooshing sound ``` :::tip The sound will be automatically cleaned up after the sound is played. ::: @param id string | number @return Sound ]=] function SoundUtils.playFromId(id) local soundId = SoundUtils.toRbxAssetId(id) assert(type(soundId) == "string", "Bad id") local sound = Instance.new("Sound") sound.Name = ("Sound_%s"):format(soundId) sound.SoundId = soundId sound.Volume = 0.25 sound.Archivable = false if RunService:IsClient() then SoundService:PlayLocalSound(sound) else sound:Play() end task.delay(sound.TimeLength + 0.05, function() sound:Destroy() end) return sound end --[=[ Plays back a template given the templateName. :::tip The sound will be automatically cleaned up after the sound is played. ::: @param templates TemplateProvider @param templateName string @return Sound ]=] function SoundUtils.playTemplate(templates, templateName) assert(type(templates) == "table", "Bad templates") assert(type(templateName) == "string", "Bad templateName") local sound = templates:Clone(templateName) sound.Archivable = false SoundService:PlayLocalSound(sound) task.delay(sound.TimeLength + 0.05, function() sound:Destroy() end) return sound end --[=[ Converts a string or number to a string for playback. @param id string | number @return string ]=] function SoundUtils.toRbxAssetId(id) if type(id) == "number" then return ("rbxassetid://%d"):format(id) else return id end end --[=[ Plays back a sound template in a specific parent. :::tip The sound will be automatically cleaned up after the sound is played. ::: @param templates TemplateProvider @param templateName string @param parent Instance @return Sound ]=] function SoundUtils.playTemplateInParent(templates, templateName, parent) local sound = templates:Clone(templateName) sound.Archivable = false sound.Parent = parent sound:Play() task.delay(sound.TimeLength + 0.05, function() sound:Destroy() end) return sound end return SoundUtils
--[=[ Helps plays back sounds in the Roblox engine. ```lua SoundUtils.playFromId("rbxassetid://4255432837") -- Plays a wooshing sound ``` @class SoundUtils ]=] local require = require(script.Parent.loader).load(script) local SoundService = game:GetService("SoundService") local RunService = game:GetService("RunService") local SoundPromiseUtils = require("SoundPromiseUtils") local SoundUtils = {} --[=[ Plays back a template given asset id. ```lua SoundUtils.playFromId("rbxassetid://4255432837") -- Plays a wooshing sound ``` :::tip The sound will be automatically cleaned up after the sound is played. ::: @param id string | number @return Sound ]=] function SoundUtils.playFromId(id) local soundId = SoundUtils.toRbxAssetId(id) assert(type(soundId) == "string", "Bad id") local sound = Instance.new("Sound") sound.Name = ("Sound_%s"):format(soundId) sound.SoundId = soundId sound.Volume = 0.25 sound.Archivable = false if RunService:IsClient() then SoundService:PlayLocalSound(sound) else sound:Play() end SoundUtils.removeAfterTimeLength(sound) return sound end --[=[ Plays back a template given asset id in the parent @param id string | number @param parent Instance @return Sound ]=] function SoundUtils.playFromIdInParent(id, parent) assert(typeof(parent) == "Instance", "Bad parent") local soundId = SoundUtils.toRbxAssetId(id) assert(type(soundId) == "string", "Bad id") local sound = Instance.new("Sound") sound.Name = ("Sound_%s"):format(soundId) sound.SoundId = soundId sound.Volume = 0.25 sound.Archivable = false sound.Parent = parent if not RunService:IsRunning() then SoundService:PlayLocalSound(sound) else sound:Play() end SoundUtils.removeAfterTimeLength(sound) return sound end --[=[ Loads the sound and then cleans up the sound after load. @param sound Sound ]=] function SoundUtils.removeAfterTimeLength(sound) -- TODO: clean up on destroying SoundPromiseUtils.promiseLoaded(sound):Then(function() task.delay(sound.TimeLength + 0.05, function() sound:Destroy() end) end, function() sound:Destroy() end) end --[=[ Plays back a template given the templateName. :::tip The sound will be automatically cleaned up after the sound is played. ::: @param templates TemplateProvider @param templateName string @return Sound ]=] function SoundUtils.playTemplate(templates, templateName) assert(type(templates) == "table", "Bad templates") assert(type(templateName) == "string", "Bad templateName") local sound = templates:Clone(templateName) sound.Archivable = false SoundService:PlayLocalSound(sound) SoundUtils.removeAfterTimeLength(sound) return sound end --[=[ Converts a string or number to a string for playback. @param id string | number @return string ]=] function SoundUtils.toRbxAssetId(id) if type(id) == "number" then return ("rbxassetid://%d"):format(id) else return id end end --[=[ Plays back a sound template in a specific parent. :::tip The sound will be automatically cleaned up after the sound is played. ::: @param templates TemplateProvider @param templateName string @param parent Instance @return Sound ]=] function SoundUtils.playTemplateInParent(templates, templateName, parent) local sound = templates:Clone(templateName) sound.Archivable = false sound.Parent = parent sound:Play() SoundUtils.removeAfterTimeLength(sound) return sound end return SoundUtils
fix: Allow way to play a sound in a parent
fix: Allow way to play a sound in a parent
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
fc6a6aa8ff6a0baa2595dcf94303483186ccfab1
usr/product/sigma-firmware/rules.lua
usr/product/sigma-firmware/rules.lua
-- Sigma rules -- base Pkg:add { 'ast-files' } Pkg:add { 'cmake-modules' } Pkg:add { 'linux' } Pkg:add { 'xsdk' } Pkg:add { 'ucode', 'target', { 'install' } } -- host Pkg:add { 'utils', 'host' } Pkg:add { 'karaoke-player', 'host', requires = { 'chicken-eggs', 'ffmpeg', 'libuv', }, { 'configure', { 'astindex', 'unpack' }, } } Pkg:add { 'astindex', { 'unpack', { 'karaoke-player', 'unpack' } } } -- kernel local kernel_rule_template = { config = 'target', { 'configure', { 'kernel', 'compile', 'target' } } } local function kernel_rule(r) r.template = kernel_rule_template Pkg:add(r) end Pkg:add { 'kernel', 'target', { 'configure', { 'linux', 'unpack' }, }, { 'install' }, } kernel_rule { 'loop-aes' } kernel_rule { 'ralink' } -- rootfs Pkg:add { 'rootfs', 'target', requires = { 'busybox', 'gnupg', 'loop-aes', 'mrua', 'ntpclient', 'ralink', 'util-linux', 'utils', }, { 'configure', { 'ast-files', 'unpack' }, { 'xsdk', 'unpack' }, { 'toolchain', 'install', 'target' }, }, { 'compile' }, { 'install' } } Pkg:add { 'mrua', 'target', { 'compile', { 'kernel', 'compile', 'target' } }, { 'install' }, } Pkg:add { 'busybox', 'target', install = { root = '$jagen_sdk_initfs_dir', prefix = '' }, { 'patch', { 'ast-files', 'unpack' } } } Pkg:add { 'utils', 'target', requires = { 'gpgme' }, { 'configure', { 'dbus', 'install', 'target' } } } Pkg:add { 'ezboot', 'target', requires = { 'rootfs' } } -- firmware local firmware_rule_template = { config = 'target', install = { prefix = '$jagen_firmware_install_prefix' }, { 'install', { 'firmware', 'unpack' } } } local function firmware_rule(r) r.template = firmware_rule_template Pkg:add(r) end Pkg:add { 'firmware', 'target', pass_template = firmware_rule_template, requires = { 'ezboot', 'karaoke-player', 'kernel', 'mrua', 'rsync', 'ucode', 'wpa_supplicant', }, install = { prefix = '$jagen_firmware_install_prefix' }, { 'compile' }, { 'install' } } firmware_rule { 'karaoke-player', requires = { 'chicken-eggs', 'connman', 'dbus', 'ffmpeg', 'freetype', 'libass', 'libpng', 'libuv', 'mrua', 'soundtouch', 'sqlite', }, { 'configure', { 'astindex', 'unpack' }, { 'chicken-eggs', 'install', 'host' } } } -- additional packages should come last to apply all templates defined here require 'chicken'
-- Sigma rules -- base Pkg:add { 'ast-files' } Pkg:add { 'cmake-modules' } Pkg:add { 'linux' } Pkg:add { 'xsdk' } Pkg:add { 'ucode', 'target', { 'install' } } -- host Pkg:add { 'utils', 'host' } Pkg:add { 'karaoke-player', 'host', requires = { 'chicken-eggs', 'ffmpeg', 'libuv', }, { 'configure', { 'astindex', 'unpack' }, } } Pkg:add { 'astindex', { 'unpack', { 'karaoke-player', 'unpack' } } } -- kernel local kernel_rule_template = { config = 'target', { 'configure', { 'kernel', 'compile', 'target' } } } local function kernel_rule(r) r.template = kernel_rule_template Pkg:add(r) end Pkg:add { 'kernel', 'target', { 'configure', { 'linux', 'unpack' }, }, { 'install', -- for genzbf and other utils { 'rootfs', 'compile', 'target' } }, } kernel_rule { 'loop-aes' } kernel_rule { 'ralink' } -- rootfs Pkg:add { 'rootfs', 'target', requires = { 'busybox', 'gnupg', 'loop-aes', 'mrua', 'ntpclient', 'ralink', 'util-linux', 'utils', }, { 'configure', { 'ast-files', 'unpack' }, { 'xsdk', 'unpack' }, { 'toolchain', 'install', 'target' }, }, { 'compile' }, { 'install' } } Pkg:add { 'mrua', 'target', { 'compile', { 'kernel', 'compile', 'target' } }, { 'install' }, } Pkg:add { 'busybox', 'target', install = { root = '$jagen_sdk_initfs_dir', prefix = '' }, { 'patch', { 'ast-files', 'unpack' } } } Pkg:add { 'utils', 'target', requires = { 'gpgme' }, { 'configure', { 'dbus', 'install', 'target' } } } Pkg:add { 'ezboot', 'target', requires = { 'rootfs' } } -- firmware local firmware_rule_template = { config = 'target', install = { prefix = '$jagen_firmware_install_prefix' }, { 'install', { 'firmware', 'unpack' } } } local function firmware_rule(r) r.template = firmware_rule_template Pkg:add(r) end Pkg:add { 'firmware', 'target', pass_template = firmware_rule_template, requires = { 'ezboot', 'karaoke-player', 'kernel', 'mrua', 'rsync', 'ucode', 'wpa_supplicant', }, install = { prefix = '$jagen_firmware_install_prefix' }, { 'compile' }, { 'install' } } firmware_rule { 'karaoke-player', requires = { 'chicken-eggs', 'connman', 'dbus', 'ffmpeg', 'freetype', 'libass', 'libpng', 'libuv', 'mrua', 'soundtouch', 'sqlite', }, { 'configure', { 'astindex', 'unpack' }, { 'chicken-eggs', 'install', 'host' } } } -- additional packages should come last to apply all templates defined here require 'chicken'
Fix kernel install deps in sigma rules
Fix kernel install deps in sigma rules
Lua
mit
bazurbat/jagen
942d80734518ce29a136dcb0e3bfcdf546011ab9
src/plugins/finalcutpro/browser/insertvertical.lua
src/plugins/finalcutpro/browser/insertvertical.lua
--- === plugins.finalcutpro.browser.insertvertical === --- --- Insert Clips Vertically from Browser to Timeline. local require = require local log = require "hs.logger".new "addnote" local fcp = require "cp.apple.finalcutpro" local dialog = require "cp.dialog" local i18n = require "cp.i18n" local go = require "cp.rx.go" local Do = go.Do local If = go.If local Throw = go.Throw local WaitUntil = go.WaitUntil local Given = go.Given local List = go.List local Retry = go.Retry local plugin = { id = "finalcutpro.browser.insertvertical", group = "finalcutpro", dependencies = { ["finalcutpro.commands"] = "fcpxCmds", } } function plugin.init(deps) local timeline = fcp:timeline() local libraries = fcp:browser():libraries() deps.fcpxCmds :add("insertClipsVerticallyFromBrowserToTimeline") :whenActivated( Do(libraries:doShow()) :Then( If(function() local clips = libraries:selectedClips() return clips and #clips >= 2 end):Then( Given(List(function() return libraries:selectedClips() end)) :Then(function(child) log.df("Selecting clip: %s", child) libraries:selectClip(child) return true end) :Then(function() log.df("Connecting to primary storyline") return true end) :Then(fcp:doSelectMenu({"Edit", "Connect to Primary Storyline"})) :Then(function() log.df("Focussing on timeline.") return true end) :Then(timeline:doFocus()) :Then( Retry(function() if timeline.isFocused() then return true else return Throw("Failed to make the timeline focused.") end end):UpTo(10):DelayedBy(100) ) :Then(function() log.df("Go to previous edit.") return true end) :Then(fcp:doSelectMenu({"Mark", "Previous", "Edit"})) :Then(function() log.df("End of block") return true end) ):Otherwise( Throw("No clips selected in the Browser.") ) ) :Catch(function(message) log.ef("Error in insertClipsVerticallyFromBrowserToTimeline: %s", message) dialog.displayMessage(message) end) ) :titled(i18n("insertClipsVerticallyFromBrowserToTimeline")) return mod end return plugin
--- === plugins.finalcutpro.browser.insertvertical === --- --- Insert Clips Vertically from Browser to Timeline. local require = require local log = require "hs.logger".new "addnote" local fcp = require "cp.apple.finalcutpro" local dialog = require "cp.dialog" local i18n = require "cp.i18n" local go = require "cp.rx.go" local Do = go.Do local If = go.If local Throw = go.Throw local Given = go.Given local List = go.List local Retry = go.Retry local plugin = { id = "finalcutpro.browser.insertvertical", group = "finalcutpro", dependencies = { ["finalcutpro.commands"] = "fcpxCmds", } } function plugin.init(deps) local timeline = fcp:timeline() local libraries = fcp:browser():libraries() deps.fcpxCmds :add("insertClipsVerticallyFromBrowserToTimeline") :whenActivated( Do(libraries:doShow()) :Then( If(function() local clips = libraries:selectedClips() return clips and #clips >= 2 end):Then( Given(List(function() return libraries:selectedClips() end)) :Then(function(child) log.df("Selecting clip: %s", child) libraries:selectClip(child) return true end) :Then(function() log.df("Connecting to primary storyline") return true end) :Then(fcp:doSelectMenu({"Edit", "Connect to Primary Storyline"})) :Then(function() log.df("Focussing on timeline.") return true end) :Then(timeline:doFocus()) :Then( Retry(function() if timeline.isFocused() then return true else return Throw("Failed to make the timeline focused.") end end):UpTo(10):DelayedBy(100) ) :Then(function() log.df("Go to previous edit.") return true end) :Then(fcp:doSelectMenu({"Mark", "Previous", "Edit"})) :Then(function() log.df("End of block") return true end) ):Otherwise( Throw("No clips selected in the Browser.") ) ) :Catch(function(message) log.ef("Error in insertClipsVerticallyFromBrowserToTimeline: %s", message) dialog.displayMessage(message) end) ) :titled(i18n("insertClipsVerticallyFromBrowserToTimeline")) end return plugin
#1671
#1671 - Fixed @stickler-ci errors
Lua
mit
CommandPost/CommandPost,CommandPost/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks,fcpxhacks/fcpxhacks
de37332ac7757c73056a9320231b74fcecdae3ed
lib/upstream.lua
lib/upstream.lua
local digest = require('openssl').digest.digest local git = require('creationix/git') local deframe = git.deframe local decodeTag = git.decoders.tag local decodeTree = git.decoders.tree local connect = require('creationix/coro-tcp').connect local makeRemote = require('./codec').makeRemote return function (storage, host, port) local read, write, socket = assert(connect(host, port or 4821)) local remote = makeRemote(read, write) local upstream = {} -- Client: SEND tagObject -- Server: WANTS objectHash -- Client: SEND object -- Server: WANTS ... -- Client: SEND ... -- Client: SEND ... -- Client: SEND ... -- Server: DONE hash function upstream.push(hash) remote.writeAs("send", storage.load(hash)) while true do local name, data = remote.read() if name == "wants" then for i = 1, #data do remote.writeAs("send", storage.load(data[i])) end elseif name == "done" then return data else error("Expected more wants or done in reply to send to server") end end end -- Client: WANT tagHash -- Server: SEND tagObject -- Client: WANT objectHash -- Server: SEND object -- Client: WANT ... -- Client: WANT ... -- Client: WANT ... -- Server: SEND ... -- Server: SEND ... -- Server: SEND ... function upstream.pull(hash) local list = {hash} local refs = {} repeat local hashes = list list = {} -- Fetch any hashes from list we don't have already local wants = {} for i = 1, #hashes do local hash = hashes[i] if not storage.has(hash) then wants[#wants + 1] = hash end end if #wants > 0 then remote.writeAs("wants", wants) for i = 1, #wants do local hash = hashes[i] local data = remote.readAs("send") assert(digest("sha1", data) == hash, "hash mismatch in result object") assert(storage.save(data) == hash) end end -- Process the hashes looking for child nodes for i = 1, #hashes do local hash = hashes[i] local data = storage.load(hash) local kind, body = deframe(data) if kind == "tag" then local tag = decodeTag(body) -- TODO: verify tag refs[tag.tag] = hash table.insert(list, tag.object) elseif kind == "tree" then local tree = decodeTree(body) for i = 1, #tree do local subHash = tree[i].hash table.insert(list, subHash) end end end until #list == 0 for ref, hash in pairs(refs) do storage.write(ref, hash) end return refs end -- Client: WANTS hash -- Server: SEND data function upstream.load(hash) remote.writeAs("wants", {hash}) local data = remote.readAs("send") assert(digest("sha1", data) == hash, "hash mismatch in result object") storage.save(data) return data end -- Client: MATCH name version -- SERVER: REPLY version hash function upstream.read(name, version) remote.writeAs("read", name .. " " .. version) local data = assert(remote.readAs("reply")) local match, hash = string.match(data, "^([^ ]+) (.*)$") return match, hash end function upstream.match(name, version) remote.writeAs("match", version and (name .. " " .. version) or name) local data = assert(remote.readAs("reply")) local match, hash = string.match(data, "^([^ ]+) (.*)$") return match, hash end --[[ upstream.close() ---------------- Called when the db is done with the connection. ]]-- function upstream.close() return socket:close() end return upstream end
local digest = require('openssl').digest.digest local git = require('creationix/git') local deframe = git.deframe local decodeTag = git.decoders.tag local decodeTree = git.decoders.tree local connect = require('creationix/coro-tcp').connect local makeRemote = require('./codec').makeRemote return function (storage, host, port) local read, write, socket = assert(connect(host, port or 4821)) local remote = makeRemote(read, write) local upstream = {} -- Client: SEND tagObject -- Server: WANTS objectHash -- Client: SEND object -- Server: WANTS ... -- Client: SEND ... -- Client: SEND ... -- Client: SEND ... -- Server: DONE hash function upstream.push(hash) remote.writeAs("send", storage.load(hash)) while true do local name, data = remote.read() if name == "wants" then for i = 1, #data do remote.writeAs("send", storage.load(data[i])) end elseif name == "done" then return data else error("Expected more wants or done in reply to send to server") end end end -- Client: WANT tagHash -- Server: SEND tagObject -- Client: WANT objectHash -- Server: SEND object -- Client: WANT ... -- Client: WANT ... -- Client: WANT ... -- Server: SEND ... -- Server: SEND ... -- Server: SEND ... function upstream.pull(hash) local list = {hash} local refs = {} repeat local hashes = list list = {} -- Fetch any hashes from list we don't have already local wants = {} for i = 1, #hashes do local hash = hashes[i] if not storage.has(hash) then wants[#wants + 1] = hash end end if #wants > 0 then remote.writeAs("wants", wants) for i = 1, #wants do local hash = hashes[i] local data = remote.readAs("send") assert(digest("sha1", data) == hash, "hash mismatch in result object") assert(storage.save(data) == hash) end end -- Process the hashes looking for child nodes for i = 1, #hashes do local hash = hashes[i] local data = storage.load(hash) local kind, body = deframe(data) if kind == "tag" then local tag = decodeTag(body) -- TODO: verify tag refs[tag.tag] = hash table.insert(list, tag.object) elseif kind == "tree" then local tree = decodeTree(body) for i = 1, #tree do local subHash = tree[i].hash table.insert(list, subHash) end end end until #list == 0 for ref, hash in pairs(refs) do local name, version = string.match(ref, "^(.*)/v(.*)$") storage.writeTag(name, version, hash) end return refs end -- Client: WANTS hash -- Server: SEND data function upstream.load(hash) remote.writeAs("wants", {hash}) local data = remote.readAs("send") assert(digest("sha1", data) == hash, "hash mismatch in result object") storage.save(data) return data end -- Client: MATCH name version -- SERVER: REPLY version hash function upstream.read(name, version) remote.writeAs("read", name .. " " .. version) return remote.readAs("reply") end function upstream.match(name, version) remote.writeAs("match", version and (name .. " " .. version) or name) local data = remote.readAs("reply") return data and string.match(data, "^([^ ]+) (.*)$") end --[[ upstream.close() ---------------- Called when the db is done with the connection. ]]-- function upstream.close() return socket:close() end return upstream end
Fix read result in upstream code
Fix read result in upstream code
Lua
apache-2.0
lduboeuf/lit,kaustavha/lit,james2doyle/lit,kidaa/lit,zhaozg/lit,DBarney/lit,1yvT0s/lit,luvit/lit,squeek502/lit
ea71593a992c11c22d0c30c285abf44c8c5ee756
modules/note.lua
modules/note.lua
local date = require'date' local ev = require'ev' local notes = ivar2.persist local handleOutput = function(self, source, destination) -- Only accept notes on channels. if(destination:sub(1,1) ~= '#') then return end local nick = source.nick local key = 'notes:' .. destination .. ':' .. nick:lower() local nick_notes = notes[key] local numNotes = tonumber(#nick_notes) if(not numNotes or numNotes == 0) then return end for i = 1, numNotes do local note = nick_notes[i] local time = tonumber(note.time) local from = note.from self:Msg('privmsg', destination, source, "%s: %s left a note %s ago: %s", nick, from, date.relativeTimeShort(time), note.message) end local globalNumNotes = tonumber(notes['global:' .. nick:lower()]) if(globalNumNotes) then note['global:' .. nick:lower()] = globalNumNotes - numNotes end notes[key] = {} end return { NICK = { function(self, source, nick) if(not notes['global:' .. nick:lower()]) then return end -- source still contains the old nick. source.nick = nick handleOutput(self, source, channel) end, }, JOIN = { -- Check if we have notes for the person who joined the channel. function(self, source, destination) return handleOutput(self, source, destination) end, }, PRIVMSG = { -- Check if we have notes for the person who sent the message. handleOutput, ['^%pnote (%S+)%s+(.+)$'] = function(self, source, destination, recipient, message) -- Only accept notes on channels. if(destination:sub(1,1) ~= '#') then return end local globalNumNotes = tonumber(notes['global:' .. recipient:lower()]) or 0 if(globalNumNotes >= 5) then say("I'm sorry, Dave. I'm afraid I can't do that. Too many notes.") else self:Notice(source.nick, "%s will be notified!", recipient) end local key = 'notes:' .. destination .. ':' .. recipient:lower() local nick_notes = notes[key] or {} local note = { message = message, time = os.time(), from = source.nick, } table.insert(nick_notes, note) notes[key] = nick_notes notes['global:' .. recipient:lower()] = globalNumNotes + 1 end } }
local date = require'date' local ev = require'ev' local notes = ivar2.persist local handleOutput = function(self, source, destination) -- Only accept notes on channels. if(destination:sub(1,1) ~= '#') then return end local nick = source.nick local key = 'notes:' .. destination .. ':' .. nick:lower() local nick_notes = notes[key] local numNotes = tonumber(#nick_notes) if(not numNotes or numNotes == 0) then return end for i = 1, numNotes do local note = nick_notes[i] local time = tonumber(note.time) local from = note.from self:Msg('privmsg', destination, source, "%s: %s left a note %s ago: %s", nick, from, date.relativeTimeShort(time), note.message) end notes[key] = {} local globalNumNotes = tonumber(notes['global:' .. nick:lower()]) if(globalNumNotes) then notes['global:' .. nick:lower()] = globalNumNotes - numNotes end end return { NICK = { function(self, source, nick) if(not notes['global:' .. nick:lower()]) then return end -- source still contains the old nick. source.nick = nick handleOutput(self, source, channel) end, }, JOIN = { -- Check if we have notes for the person who joined the channel. function(self, source, destination) return handleOutput(self, source, destination) end, }, PRIVMSG = { -- Check if we have notes for the person who sent the message. handleOutput, ['^%pnote (%S+)%s+(.+)$'] = function(self, source, destination, recipient, message) -- Only accept notes on channels. if(destination:sub(1,1) ~= '#') then return end local globalNumNotes = tonumber(notes['global:' .. recipient:lower()]) or 0 if(globalNumNotes >= 5) then say("I'm sorry, Dave. I'm afraid I can't do that. Too many notes.") else self:Notice(source.nick, "%s will be notified!", recipient) end local key = 'notes:' .. destination .. ':' .. recipient:lower() local nick_notes = notes[key] or {} local note = { message = message, time = os.time(), from = source.nick, } table.insert(nick_notes, note) notes[key] = nick_notes notes['global:' .. recipient:lower()] = globalNumNotes + 1 end } }
note: fix problem with global notes checking
note: fix problem with global notes checking
Lua
mit
torhve/ivar2,haste/ivar2,torhve/ivar2,torhve/ivar2
b59674bd4a15b81c33b148d05cd46f3ee093e79f
kong/plugins/oauth2/migrations/postgres.lua
kong/plugins/oauth2/migrations/postgres.lua
return { { name = "2015-08-03-132400_init_oauth2", up = [[ CREATE TABLE IF NOT EXISTS oauth2_credentials( id uuid, name text, consumer_id uuid REFERENCES consumers (id) ON DELETE CASCADE, client_id text UNIQUE, client_secret text UNIQUE, redirect_uri text, created_at timestamp without time zone default (CURRENT_TIMESTAMP(0) at time zone 'utc'), PRIMARY KEY (id) ); DO $$ BEGIN IF (SELECT to_regclass('oauth2_credentials_consumer_idx')) IS NULL THEN CREATE INDEX oauth2_credentials_consumer_idx ON oauth2_credentials(consumer_id); END IF; IF (SELECT to_regclass('oauth2_credentials_client_idx')) IS NULL THEN CREATE INDEX oauth2_credentials_client_idx ON oauth2_credentials(client_id); END IF; IF (SELECT to_regclass('oauth2_credentials_secret_idx')) IS NULL THEN CREATE INDEX oauth2_credentials_secret_idx ON oauth2_credentials(client_secret); END IF; END$$; CREATE TABLE IF NOT EXISTS oauth2_authorization_codes( id uuid, code text UNIQUE, authenticated_userid text, scope text, created_at timestamp without time zone default (CURRENT_TIMESTAMP(0) at time zone 'utc'), PRIMARY KEY (id) ); DO $$ BEGIN IF (SELECT to_regclass('oauth2_autorization_code_idx')) IS NULL THEN CREATE INDEX oauth2_autorization_code_idx ON oauth2_authorization_codes(code); END IF; IF (SELECT to_regclass('oauth2_authorization_userid_idx')) IS NULL THEN CREATE INDEX oauth2_authorization_userid_idx ON oauth2_authorization_codes(authenticated_userid); END IF; END$$; CREATE TABLE IF NOT EXISTS oauth2_tokens( id uuid, credential_id uuid REFERENCES oauth2_credentials (id) ON DELETE CASCADE, access_token text UNIQUE, token_type text, refresh_token text UNIQUE, expires_in int, authenticated_userid text, scope text, created_at timestamp without time zone default (CURRENT_TIMESTAMP(0) at time zone 'utc'), PRIMARY KEY (id) ); DO $$ BEGIN IF (SELECT to_regclass('oauth2_accesstoken_idx')) IS NULL THEN CREATE INDEX oauth2_accesstoken_idx ON oauth2_tokens(access_token); END IF; IF (SELECT to_regclass('oauth2_token_refresh_idx')) IS NULL THEN CREATE INDEX oauth2_token_refresh_idx ON oauth2_tokens(refresh_token); END IF; IF (SELECT to_regclass('oauth2_token_userid_idx')) IS NULL THEN CREATE INDEX oauth2_token_userid_idx ON oauth2_tokens(authenticated_userid); END IF; END$$; ]], down = [[ DROP TABLE oauth2_credentials; DROP TABLE oauth2_authorization_codes; DROP TABLE oauth2_tokens; ]] }, { name = "2016-04-14-283949_serialize_redirect_uri", up = function(_, _, factory) local schema = factory.oauth2_credentials.schema schema.fields.redirect_uri.type = "string" local json = require "cjson" local apps, err = factory.oauth2_credentials.db:find_all('oauth2_credentials', nil, schema); if err then return err end for _, app in ipairs(apps) do local redirect_uri = {}; redirect_uri[1] = app.redirect_uri local redirect_uri_str = json.encode(redirect_uri) local req = "UPDATE oauth2_credentials SET redirect_uri='"..redirect_uri_str.."' WHERE id='"..app.id.."'" local _, err = factory.oauth2_credentials.db:queries(req) if err then return err end end end, down = function(_,_,factory) local apps, err = factory.oauth2_credentials:find_all() if err then return err end for _, app in ipairs(apps) do local redirect_uri = app.redirect_uri[1] local req = "UPDATE oauth2_credentials SET redirect_uri='"..redirect_uri.."' WHERE id='"..app.id.."'" local _, err = factory.oauth2_credentials.db:queries(req) if err then return err end end end }, { name = "2016-07-15-oauth2_code_credential_id", up = [[ DELETE FROM oauth2_authorization_codes; ALTER TABLE oauth2_authorization_codes ADD COLUMN credential_id uuid REFERENCES oauth2_credentials (id) ON DELETE CASCADE; ]], down = [[ ALTER TABLE oauth2_authorization_codes DROP COLUMN credential_id; ]] } }
return { { name = "2015-08-03-132400_init_oauth2", up = [[ CREATE TABLE IF NOT EXISTS oauth2_credentials( id uuid, name text, consumer_id uuid REFERENCES consumers (id) ON DELETE CASCADE, client_id text UNIQUE, client_secret text UNIQUE, redirect_uri text, created_at timestamp without time zone default (CURRENT_TIMESTAMP(0) at time zone 'utc'), PRIMARY KEY (id) ); DO $$ BEGIN IF (SELECT to_regclass('oauth2_credentials_consumer_idx')) IS NULL THEN CREATE INDEX oauth2_credentials_consumer_idx ON oauth2_credentials(consumer_id); END IF; IF (SELECT to_regclass('oauth2_credentials_client_idx')) IS NULL THEN CREATE INDEX oauth2_credentials_client_idx ON oauth2_credentials(client_id); END IF; IF (SELECT to_regclass('oauth2_credentials_secret_idx')) IS NULL THEN CREATE INDEX oauth2_credentials_secret_idx ON oauth2_credentials(client_secret); END IF; END$$; CREATE TABLE IF NOT EXISTS oauth2_authorization_codes( id uuid, code text UNIQUE, authenticated_userid text, scope text, created_at timestamp without time zone default (CURRENT_TIMESTAMP(0) at time zone 'utc'), PRIMARY KEY (id) ); DO $$ BEGIN IF (SELECT to_regclass('oauth2_autorization_code_idx')) IS NULL THEN CREATE INDEX oauth2_autorization_code_idx ON oauth2_authorization_codes(code); END IF; IF (SELECT to_regclass('oauth2_authorization_userid_idx')) IS NULL THEN CREATE INDEX oauth2_authorization_userid_idx ON oauth2_authorization_codes(authenticated_userid); END IF; END$$; CREATE TABLE IF NOT EXISTS oauth2_tokens( id uuid, credential_id uuid REFERENCES oauth2_credentials (id) ON DELETE CASCADE, access_token text UNIQUE, token_type text, refresh_token text UNIQUE, expires_in int, authenticated_userid text, scope text, created_at timestamp without time zone default (CURRENT_TIMESTAMP(0) at time zone 'utc'), PRIMARY KEY (id) ); DO $$ BEGIN IF (SELECT to_regclass('oauth2_accesstoken_idx')) IS NULL THEN CREATE INDEX oauth2_accesstoken_idx ON oauth2_tokens(access_token); END IF; IF (SELECT to_regclass('oauth2_token_refresh_idx')) IS NULL THEN CREATE INDEX oauth2_token_refresh_idx ON oauth2_tokens(refresh_token); END IF; IF (SELECT to_regclass('oauth2_token_userid_idx')) IS NULL THEN CREATE INDEX oauth2_token_userid_idx ON oauth2_tokens(authenticated_userid); END IF; END$$; ]], down = [[ DROP TABLE oauth2_credentials; DROP TABLE oauth2_authorization_codes; DROP TABLE oauth2_tokens; ]] }, { name = "2016-07-15-oauth2_code_credential_id", up = [[ DELETE FROM oauth2_authorization_codes; ALTER TABLE oauth2_authorization_codes ADD COLUMN credential_id uuid REFERENCES oauth2_credentials (id) ON DELETE CASCADE; ]], down = [[ ALTER TABLE oauth2_authorization_codes DROP COLUMN credential_id; ]] }, { name = "2016-12-22-283949_serialize_redirect_uri", up = function(_, _, factory) local schema = factory.oauth2_credentials.schema schema.fields.redirect_uri.type = "string" local json = require "cjson" local apps, err = factory.oauth2_credentials.db:find_all('oauth2_credentials', nil, schema); if err then return err end for _, app in ipairs(apps) do local redirect_uri = {}; redirect_uri[1] = app.redirect_uri local redirect_uri_str = json.encode(redirect_uri) local req = "UPDATE oauth2_credentials SET redirect_uri='"..redirect_uri_str.."' WHERE id='"..app.id.."'" local _, err = factory.oauth2_credentials.db:queries(req) if err then return err end end end, down = function(_,_,factory) local apps, err = factory.oauth2_credentials:find_all() if err then return err end for _, app in ipairs(apps) do local redirect_uri = app.redirect_uri[1] local req = "UPDATE oauth2_credentials SET redirect_uri='"..redirect_uri.."' WHERE id='"..app.id.."'" local _, err = factory.oauth2_credentials.db:queries(req) if err then return err end end end } }
hotfix(oauth2) fixing postgres migration
hotfix(oauth2) fixing postgres migration
Lua
apache-2.0
Kong/kong,Kong/kong,icyxp/kong,ccyphers/kong,salazar/kong,jebenexer/kong,shiprabehera/kong,li-wl/kong,Mashape/kong,akh00/kong,Kong/kong
f342e5f5f0ee3c82a0404ce95944f27369d887f0
mod_adhoc_cmd_admin/mod_adhoc_cmd_admin.lua
mod_adhoc_cmd_admin/mod_adhoc_cmd_admin.lua
-- Copyright (C) 2009 Florian Zeitz -- -- This file is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local st, jid, uuid = require "util.stanza", require "util.jid", require "util.uuid"; local dataforms_new = require "util.dataforms".new; local usermanager_user_exists = require "core.usermanager".user_exists; local usermanager_create_user = require "core.usermanager".create_user; local is_admin = require "core.usermanager".is_admin; local admins = set.new(config.get(module:get_host(), "core", "admins")); local sessions = {}; local add_user_layout = { title= "Adding a User"; instructions = "Fill out this form to add a user."; { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/admin" }; { name = "accountjid", type = "jid-single", required = true, label = "The Jabber ID for the account to be added" }; { name = "password", type = "text-private", label = "The password for this account" }; { name = "password-verify", type = "text-private", label = "Retype password" }; }; dataforms_new(add_user_layout) function add_user_command_handler(item, origin, stanza) if not is_admin(stanza.attr.from) then module:log("warn", "Non-admin %s tried to add a user", tostring(jid.bare(stanza.attr.from))); origin.send(st.error_reply(stanza, "auth", "forbidden", "You don't have permission to add a user"):up() :tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", status="canceled"}) :tag("note", {type="error"}):text("You don't have permission to add a user")); return true; end if stanza.tags[1].attr.sessionid and sessions[stanza.tags[1].attr.sessionid] then if stanza.tags[1].attr.action == "cancel" then origin.send(st.reply(stanza):tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", sessionid=stanza.tags[1].attr.sessionid, status="canceled"})); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end for _, tag in ipairs(stanza.tags[1].tags) do if tag.name == "x" and tag.attr.xmlns == "jabber:x:data" then form = tag; break; end end local fields = add_user_layout:data(form); local username, host, resource = jid.split(fields.accountjid); if (fields.password == fields["password-verify"]) and username and host and host == stanza.attr.to then if usermanager_user_exists(username, host) then origin.send(st.error_reply(stanza, "cancel", "conflict", "Account already exists"):up() :tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", status="canceled"}) :tag("note", {type="error"}):text("Account already exists")); sessions[stanza.tags[1].attr.sessionid] = nil; return true; else if usermanager_create_user(username, fields.password, host) then origin.send(st.reply(stanza):tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", sessionid=stanza.tags[1].attr.sessionid, status="completed"}) :tag("note", {type="info"}):text("Account successfully created")); sessions[stanza.tags[1].attr.sessionid] = nil; module:log("debug", "Created new account " .. username.."@"..host); return true; else origin.send(st.error_reply(stanza, "wait", "internal-server-error", "Failed to write data to disk"):up() :tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", status="canceled"}) :tag("note", {type="error"}):text("Failed to write data to disk")); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end end else module:log("debug", fields.accountjid .. " " .. fields.password .. " " .. fields["password-verify"]); origin.send(st.error_reply(stanza, "cancel", "conflict", "Invalid data.\nPasswords missmatch, or empy username"):up() :tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", status="canceled"}) :tag("note", {type="error"}):text("Invalid data.\nPasswords missmatch, or empy username")); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end else local sessionid=uuid.generate(); sessions[sessionid] = "executing"; origin.send(st.reply(stanza):tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", sessionid=sessionid, status="executing"}):add_child(add_user_layout:form())); end return true; end local descriptor = { name="Add User", node="http://jabber.org/protocol/admin#add-user", handler=add_user_command_handler }; function module.unload() module:remove_item("adhoc", descriptor); end module:add_item ("adhoc", descriptor);
-- Copyright (C) 2009 Florian Zeitz -- -- This file is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local st, jid, uuid = require "util.stanza", require "util.jid", require "util.uuid"; local dataforms_new = require "util.dataforms".new; local usermanager_user_exists = require "core.usermanager".user_exists; local usermanager_create_user = require "core.usermanager".create_user; local is_admin = require "core.usermanager".is_admin; local admins = set.new(config.get(module:get_host(), "core", "admins")); local sessions = {}; local add_user_layout = dataforms_new{ title= "Adding a User"; instructions = "Fill out this form to add a user."; { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/admin" }; { name = "accountjid", type = "jid-single", required = true, label = "The Jabber ID for the account to be added" }; { name = "password", type = "text-private", label = "The password for this account" }; { name = "password-verify", type = "text-private", label = "Retype password" }; }; function add_user_command_handler(item, origin, stanza) if not is_admin(stanza.attr.from) then module:log("warn", "Non-admin %s tried to add a user", tostring(jid.bare(stanza.attr.from))); origin.send(st.error_reply(stanza, "auth", "forbidden", "You don't have permission to add a user"):up() :tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", status="canceled"}) :tag("note", {type="error"}):text("You don't have permission to add a user")); return true; end if stanza.tags[1].attr.sessionid and sessions[stanza.tags[1].attr.sessionid] then if stanza.tags[1].attr.action == "cancel" then origin.send(st.reply(stanza):tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", sessionid=stanza.tags[1].attr.sessionid, status="canceled"})); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end form = stanza.tags[1]:find_child_with_ns("jabber:x:data"); local fields = add_user_layout:data(form); local username, host, resource = jid.split(fields.accountjid); if (fields.password == fields["password-verify"]) and username and host and host == stanza.attr.to then if usermanager_user_exists(username, host) then origin.send(st.error_reply(stanza, "cancel", "conflict", "Account already exists"):up() :tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", status="canceled"}) :tag("note", {type="error"}):text("Account already exists")); sessions[stanza.tags[1].attr.sessionid] = nil; return true; else if usermanager_create_user(username, fields.password, host) then origin.send(st.reply(stanza):tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", sessionid=stanza.tags[1].attr.sessionid, status="completed"}) :tag("note", {type="info"}):text("Account successfully created")); sessions[stanza.tags[1].attr.sessionid] = nil; module:log("debug", "Created new account " .. username.."@"..host); return true; else origin.send(st.error_reply(stanza, "wait", "internal-server-error", "Failed to write data to disk"):up() :tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", status="canceled"}) :tag("note", {type="error"}):text("Failed to write data to disk")); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end end else module:log("debug", fields.accountjid .. " " .. fields.password .. " " .. fields["password-verify"]); origin.send(st.error_reply(stanza, "cancel", "conflict", "Invalid data.\nPassword mismatch, or empty username"):up() :tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", status="canceled"}) :tag("note", {type="error"}):text("Invalid data.\nPassword mismatch, or empty username")); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end else local sessionid=uuid.generate(); sessions[sessionid] = "executing"; origin.send(st.reply(stanza):tag("command", {xmlns="http://jabber.org/protocol/commands", node="http://jabber.org/protocol/admin#add-user", sessionid=sessionid, status="executing"}):add_child(add_user_layout:form())); end return true; end local descriptor = { name="Add User", node="http://jabber.org/protocol/admin#add-user", handler=add_user_command_handler }; function module.unload() module:remove_item("adhoc", descriptor); end module:add_item ("adhoc", descriptor);
mod_adhoc_cmd_admin: Fixed style, some typos, and got down to <100LOC. Perhaps we need util.adhoc?
mod_adhoc_cmd_admin: Fixed style, some typos, and got down to <100LOC. Perhaps we need util.adhoc?
Lua
mit
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
c1770cac9b45c8a91cdd9f82e0edc0463060db4a
Interface/AddOns/RayUI/modules/chat/easyChannel.lua
Interface/AddOns/RayUI/modules/chat/easyChannel.lua
local R, L, P, G = unpack(select(2, ...)) --Import: Engine, Locales, ProfileDB, GlobalDB local CH = R:GetModule("Chat") --Cache global variables --Lua functions local select, pairs, ipairs = select, pairs, ipairs local strsub = string.sub local tostring = tostring --WoW API / Variables local IsInGroup = IsInGroup local IsInRaid = IsInRaid local IsInInstance = IsInInstance local IsInGuild = IsInGuild local IsShiftKeyDown = IsShiftKeyDown local ChatEdit_UpdateHeader = ChatEdit_UpdateHeader --Global variables that we don't cache, list them here for the mikk's Find Globals script -- GLOBALS: RayUITabChannelTutorial local cycles = { { chatType = "SAY", --SAY use = function(self, editbox) return 1 end, }, --[[ { chatType = "YELL", --大喊 use = function(self, editbox) return 1 end, }, ]] { chatType = "PARTY", --小队 use = function(self, editbox) return IsInGroup() end, }, { chatType = "RAID", --团队 use = function(self, editbox) return IsInRaid() end, }, { chatType = "INSTANCE_CHAT", --副本 use = function(self, editbox) return select(2, IsInInstance()) == 'pvp' end, }, { chatType = "GUILD", --工会 use = function(self, editbox) return IsInGuild() end, use = function(self, editbox) return IsInGuild() end, }, --[[ { chatType = "CHANNEL", use = function(self, editbox, currChatType) if currChatType~="CHANNEL" then currNum = IsShiftKeyDown() and 21 or 0 else currNum = editbox:GetAttribute("channelTarget"); end local h, r, step = currNum+1, 20, 1 if IsShiftKeyDown() then h, r, step = currNum-1, 1, -1 end for i=h,r,step do local channelNum, channelName = GetChannelName(i); if channelNum > 0 and not channelName:find("本地防务 %-") and not channelName:find("本地防務 %-") and not channelName:find("LFGForwarder") and not channelName:find("TCForwarder") then editbox:SetAttribute("channelTarget", i); return true; end end end, }, ]] { chatType = "SAY", use = function(self, editbox) return 1 end, }, } function CH:ChatEdit_CustomTabPressed(self) if not R.global.Tutorial.tabchannel then RayUITabChannelTutorial:Hide() R.global.Tutorial.tabchannel = true end if strsub(tostring(self:GetText()), 1, 1) == "/" then return end local currChatType = self:GetAttribute("chatType") for i, curr in ipairs(cycles) do if curr.chatType== currChatType then local h, r, step = i+1, #cycles, 1 if IsShiftKeyDown() then h, r, step = i-1, 1, -1 end if currChatType=="CHANNEL" then h = i end --频道仍然要测试一下 for j=h, r, step do if cycles[j]:use(self, currChatType) then self:SetAttribute("chatType", cycles[j].chatType); ChatEdit_UpdateHeader(self); return; end end end end end function CH:EasyChannel() self:RawHook("ChatEdit_CustomTabPressed", true) end
local R, L, P, G = unpack(select(2, ...)) --Import: Engine, Locales, ProfileDB, GlobalDB local CH = R:GetModule("Chat") --Cache global variables --Lua functions local select, pairs, ipairs = select, pairs, ipairs local strsub = string.sub local tostring = tostring --WoW API / Variables local IsInGroup = IsInGroup local IsInRaid = IsInRaid local IsInInstance = IsInInstance local IsInGuild = IsInGuild local IsShiftKeyDown = IsShiftKeyDown --Global variables that we don't cache, list them here for the mikk's Find Globals script -- GLOBALS: RayUITabChannelTutorial, ChatEdit_UpdateHeader local cycles = { { chatType = "SAY", --SAY use = function(self, editbox) return 1 end, }, --[[ { chatType = "YELL", --大喊 use = function(self, editbox) return 1 end, }, ]] { chatType = "PARTY", --小队 use = function(self, editbox) return IsInGroup() end, }, { chatType = "RAID", --团队 use = function(self, editbox) return IsInRaid() end, }, { chatType = "INSTANCE_CHAT", --副本 use = function(self, editbox) return select(2, IsInInstance()) == 'pvp' end, }, { chatType = "GUILD", --工会 use = function(self, editbox) return IsInGuild() end, use = function(self, editbox) return IsInGuild() end, }, --[[ { chatType = "CHANNEL", use = function(self, editbox, currChatType) if currChatType~="CHANNEL" then currNum = IsShiftKeyDown() and 21 or 0 else currNum = editbox:GetAttribute("channelTarget"); end local h, r, step = currNum+1, 20, 1 if IsShiftKeyDown() then h, r, step = currNum-1, 1, -1 end for i=h,r,step do local channelNum, channelName = GetChannelName(i); if channelNum > 0 and not channelName:find("本地防务 %-") and not channelName:find("本地防務 %-") and not channelName:find("LFGForwarder") and not channelName:find("TCForwarder") then editbox:SetAttribute("channelTarget", i); return true; end end end, }, ]] { chatType = "SAY", use = function(self, editbox) return 1 end, }, } function CH:ChatEdit_CustomTabPressed(self) if not R.global.Tutorial.tabchannel then RayUITabChannelTutorial:Hide() R.global.Tutorial.tabchannel = true end if strsub(tostring(self:GetText()), 1, 1) == "/" then return end local currChatType = self:GetAttribute("chatType") for i, curr in ipairs(cycles) do if curr.chatType== currChatType then local h, r, step = i+1, #cycles, 1 if IsShiftKeyDown() then h, r, step = i-1, 1, -1 end if currChatType=="CHANNEL" then h = i end --频道仍然要测试一下 for j=h, r, step do if cycles[j]:use(self, currChatType) then self:SetAttribute("chatType", cycles[j].chatType); ChatEdit_UpdateHeader(self); return; end end end end end function CH:EasyChannel() self:RawHook("ChatEdit_CustomTabPressed", true) end
fix chat editbox border color
fix chat editbox border color
Lua
mit
fgprodigal/RayUI
a13d04a559da4a90e8c715838828998c3f31aed1
MMOCoreORB/bin/scripts/mobile/lok/serverobjects.lua
MMOCoreORB/bin/scripts/mobile/lok/serverobjects.lua
includeFile("lok/blood_razor_berzerker.lua") includeFile("lok/blood_razor_captain.lua") includeFile("lok/blood_razor_cutthroat.lua") includeFile("lok/blood_razor_destroyer.lua") includeFile("lok/blood_razor_elite_pirate.lua") includeFile("lok/blood_razor_guard.lua") includeFile("lok/blood_razor_officer.lua") includeFile("lok/blood_razor_scout.lua") includeFile("lok/blood_razor_strong_pirate.lua") includeFile("lok/blood_razor_weak_pirate.lua") includeFile("lok/canyon_corsair_captain.lua") includeFile("lok/canyon_corsair_cutthroat.lua") includeFile("lok/canyon_corsair_destroyer.lua") includeFile("lok/canyon_corsair_elite_pirate.lua") includeFile("lok/canyon_corsair_guard.lua") includeFile("lok/canyon_corsair_scout.lua") includeFile("lok/canyon_corsair_strong_pirate.lua") includeFile("lok/canyon_corsair_weak_pirate.lua") includeFile("lok/cas_vankoo.lua") includeFile("lok/crazed_gurk_destroyer.lua") includeFile("lok/deadly_vesp.lua") includeFile("lok/demolishing_snorbal_titan.lua") includeFile("lok/desert_vesp.lua") includeFile("lok/domesticated_gurnaset.lua") includeFile("lok/domesticated_snorbal.lua") includeFile("lok/droideka.lua") includeFile("lok/dune_kimogila.lua") includeFile("lok/elder_snorbal_female.lua") includeFile("lok/elder_snorbal_male.lua") includeFile("lok/elite_canyon_corsair.lua") includeFile("lok/enraged_dune_kimogila.lua") includeFile("lok/enraged_kimogila.lua") includeFile("lok/female_langlatch.lua") includeFile("lok/female_snorbal_calf.lua") includeFile("lok/feral_gurk.lua") includeFile("lok/ferocious_kusak.lua") includeFile("lok/flit_bloodsucker.lua") includeFile("lok/flit_harasser.lua") includeFile("lok/flit.lua") includeFile("lok/flit_youth.lua") includeFile("lok/giant_dune_kimogila.lua") includeFile("lok/giant_flit.lua") includeFile("lok/giant_kimogila.lua") includeFile("lok/giant_pharple.lua") includeFile("lok/giant_spined_snake.lua") includeFile("lok/gorge_vesp.lua") includeFile("lok/gurk_gatherer.lua") includeFile("lok/gurk.lua") includeFile("lok/gurk_tracker.lua") includeFile("lok/gurk_whelp.lua") includeFile("lok/gurnaset_be.lua") includeFile("lok/gurnaset_hatchling.lua") includeFile("lok/gurnaset.lua") includeFile("lok/imperial_deserter.lua") includeFile("lok/jinkins.lua") includeFile("lok/juvenile_langlatch.lua") includeFile("lok/kimogila_be.lua") includeFile("lok/kimogila_hatchling.lua") includeFile("lok/kimogila.lua") includeFile("lok/kole.lua") includeFile("lok/kusak_be.lua") includeFile("lok/kusak_hunter.lua") includeFile("lok/kusak.lua") includeFile("lok/kusak_mauler.lua") includeFile("lok/kusak_pup.lua") includeFile("lok/kusak_stalker.lua") includeFile("lok/langlatch_be.lua") includeFile("lok/langlatch_destroyer.lua") includeFile("lok/langlatch_hatchling.lua") includeFile("lok/langlatch_hunter.lua") includeFile("lok/langlatch_marauder.lua") includeFile("lok/lethargic_behemoth.lua") includeFile("lok/loathsome_mangler.lua") includeFile("lok/lowland_salt_mynock.lua") includeFile("lok/male_langlatch.lua") includeFile("lok/male_snorbal_calf.lua") includeFile("lok/marooned_pirate_captain.lua") includeFile("lok/marooned_pirate_engineer.lua") includeFile("lok/marooned_pirate_first_mate.lua") includeFile("lok/marooned_pirate.lua") includeFile("lok/mature_snorbal_female.lua") includeFile("lok/mature_snorbal_male.lua") includeFile("lok/mercenary_commander.lua") includeFile("lok/mercenary_destroyer.lua") includeFile("lok/mercenary_elite.lua") includeFile("lok/mercenary_messenger.lua") includeFile("lok/mercenary_warlord.lua") includeFile("lok/mercenary_weak.lua") includeFile("lok/mountain_vesp_medium.lua") includeFile("lok/nien_nunb.lua") includeFile("lok/nym_guard_elite.lua") includeFile("lok/nym_guard_strong.lua") includeFile("lok/nym_guard_weak.lua") includeFile("lok/nym.lua") includeFile("lok/nym_bodyguard.lua") includeFile("lok/nym_brawler.lua") includeFile("lok/nym_destroyer.lua") --includeFile("lok/nym_domesticated_gurk.lua") --includeFile("lok/nym_droideka.lua") includeFile("lok/nym_patrol_elite.lua") includeFile("lok/nym_pirate_elite.lua") includeFile("lok/nym_kusak_guardian.lua") includeFile("lok/nym_patrol_strong.lua") includeFile("lok/nym_patrol_weak.lua") includeFile("lok/nym_pirate_strong.lua") includeFile("lok/nym_pirate_weak.lua") includeFile("lok/nym_surveyor.lua") includeFile("lok/perlek.lua") includeFile("lok/perlek_ravager.lua") includeFile("lok/perlek_scavenger.lua") includeFile("lok/pharple.lua") includeFile("lok/reclusive_gurk_king.lua") includeFile("lok/riverside_sulfur_mynok.lua") includeFile("lok/runty_pharple.lua") includeFile("lok/salt_mynock.lua") includeFile("lok/sandy_spined_snake.lua") includeFile("lok/shaggy_gurk_youth.lua") includeFile("lok/sharptooth_langlatch.lua") includeFile("lok/snorbal_be.lua") includeFile("lok/snorbal.lua") includeFile("lok/snorbal_matriarch.lua") includeFile("lok/spined_snake.lua") includeFile("lok/spined_snake_recluse.lua") includeFile("lok/strong_mercenary.lua") includeFile("lok/sulfer_pool_mynock.lua") includeFile("lok/sulfur_lake_pirate.lua") includeFile("lok/theme_park_rebel_bounty_hunter.lua") includeFile("lok/theme_park_rebel_edycu.lua") includeFile("lok/theme_park_rebel_engineer.lua") includeFile("lok/weak_mercenary.lua") includeFile("lok/rifea_eicik.lua") includeFile("lok/rorha_wahe.lua") includeFile("lok/reggi_tirver.lua") includeFile("lok/vixur_webb.lua") includeFile("lok/ifoja_lico.lua") includeFile("lok/evathm.lua") includeFile("lok/bapibac.lua") includeFile("lok/lok_herald_01.lua") includeFile("lok/lok_herald_02.lua") includeFile("lok/melo.lua") includeFile("lok/idhak_ipath.lua") includeFile("lok/ciwi_mosregri.lua")
includeFile("lok/blood_razor_berzerker.lua") includeFile("lok/blood_razor_captain.lua") includeFile("lok/blood_razor_cutthroat.lua") includeFile("lok/blood_razor_destroyer.lua") includeFile("lok/blood_razor_elite_pirate.lua") includeFile("lok/blood_razor_guard.lua") includeFile("lok/blood_razor_officer.lua") includeFile("lok/blood_razor_scout.lua") includeFile("lok/blood_razor_strong_pirate.lua") includeFile("lok/blood_razor_weak_pirate.lua") includeFile("lok/canyon_corsair_captain.lua") includeFile("lok/canyon_corsair_cutthroat.lua") includeFile("lok/canyon_corsair_destroyer.lua") includeFile("lok/canyon_corsair_elite_pirate.lua") includeFile("lok/canyon_corsair_guard.lua") includeFile("lok/canyon_corsair_scout.lua") includeFile("lok/canyon_corsair_strong_pirate.lua") includeFile("lok/canyon_corsair_weak_pirate.lua") includeFile("lok/cas_vankoo.lua") includeFile("lok/crazed_gurk_destroyer.lua") includeFile("lok/deadly_vesp.lua") includeFile("lok/demolishing_snorbal_titan.lua") includeFile("lok/desert_vesp.lua") includeFile("lok/domesticated_gurnaset.lua") includeFile("lok/domesticated_snorbal.lua") includeFile("lok/droideka.lua") includeFile("lok/dune_kimogila.lua") includeFile("lok/elder_snorbal_female.lua") includeFile("lok/elder_snorbal_male.lua") includeFile("lok/elite_canyon_corsair.lua") includeFile("lok/enraged_dune_kimogila.lua") includeFile("lok/enraged_kimogila.lua") includeFile("lok/female_langlatch.lua") includeFile("lok/female_snorbal_calf.lua") includeFile("lok/feral_gurk.lua") includeFile("lok/ferocious_kusak.lua") includeFile("lok/flit_bloodsucker.lua") includeFile("lok/flit_harasser.lua") includeFile("lok/flit.lua") includeFile("lok/flit_youth.lua") includeFile("lok/giant_dune_kimogila.lua") includeFile("lok/giant_flit.lua") includeFile("lok/giant_kimogila.lua") includeFile("lok/giant_pharple.lua") includeFile("lok/giant_spined_snake.lua") includeFile("lok/gorge_vesp.lua") includeFile("lok/gurk_gatherer.lua") includeFile("lok/gurk.lua") includeFile("lok/gurk_tracker.lua") includeFile("lok/gurk_whelp.lua") includeFile("lok/gurnaset_be.lua") includeFile("lok/gurnaset_hatchling.lua") includeFile("lok/gurnaset.lua") includeFile("lok/imperial_deserter.lua") includeFile("lok/jinkins.lua") includeFile("lok/juvenile_langlatch.lua") includeFile("lok/kimogila_be.lua") includeFile("lok/kimogila_hatchling.lua") includeFile("lok/kimogila.lua") includeFile("lok/kole.lua") includeFile("lok/kusak_be.lua") includeFile("lok/kusak_hunter.lua") includeFile("lok/kusak.lua") includeFile("lok/kusak_mauler.lua") includeFile("lok/kusak_pup.lua") includeFile("lok/kusak_stalker.lua") includeFile("lok/langlatch_be.lua") includeFile("lok/langlatch_destroyer.lua") includeFile("lok/langlatch_hatchling.lua") includeFile("lok/langlatch_hunter.lua") includeFile("lok/langlatch_marauder.lua") includeFile("lok/lethargic_behemoth.lua") includeFile("lok/loathsome_mangler.lua") includeFile("lok/lowland_salt_mynock.lua") includeFile("lok/male_langlatch.lua") includeFile("lok/male_snorbal_calf.lua") includeFile("lok/marooned_pirate_captain.lua") includeFile("lok/marooned_pirate_engineer.lua") includeFile("lok/marooned_pirate_first_mate.lua") includeFile("lok/marooned_pirate.lua") includeFile("lok/mature_snorbal_female.lua") includeFile("lok/mature_snorbal_male.lua") includeFile("lok/mercenary_commander.lua") includeFile("lok/mercenary_destroyer.lua") includeFile("lok/mercenary_elite.lua") includeFile("lok/mercenary_messenger.lua") includeFile("lok/mercenary_warlord.lua") includeFile("lok/mercenary_weak.lua") includeFile("lok/mountain_vesp_medium.lua") includeFile("lok/nien_nunb.lua") includeFile("lok/nym_guard_elite.lua") includeFile("lok/nym_guard_strong.lua") includeFile("lok/nym_guard_weak.lua") includeFile("lok/nym.lua") includeFile("lok/nym_bodyguard.lua") includeFile("lok/nym_brawler.lua") includeFile("lok/nym_destroyer.lua") --includeFile("lok/nym_domesticated_gurk.lua") --includeFile("lok/nym_droideka.lua") includeFile("lok/nym_patrol_elite.lua") includeFile("lok/nym_pirate_elite.lua") includeFile("lok/nym_kusak_guardian.lua") includeFile("lok/nym_patrol_strong.lua") includeFile("lok/nym_patrol_weak.lua") includeFile("lok/nym_pirate_strong.lua") includeFile("lok/nym_pirate_weak.lua") includeFile("lok/nym_surveyor.lua") includeFile("lok/perlek.lua") includeFile("lok/perlek_ravager.lua") includeFile("lok/perlek_scavenger.lua") includeFile("lok/pharple.lua") includeFile("lok/reclusive_gurk_king.lua") includeFile("lok/riverside_sulfur_mynok.lua") includeFile("lok/runty_pharple.lua") includeFile("lok/salt_mynock.lua") includeFile("lok/sandy_spined_snake.lua") includeFile("lok/shaggy_gurk_youth.lua") includeFile("lok/sharptooth_langlatch.lua") includeFile("lok/snorbal_be.lua") includeFile("lok/snorbal.lua") includeFile("lok/snorbal_matriarch.lua") includeFile("lok/spined_snake.lua") includeFile("lok/spined_snake_recluse.lua") includeFile("lok/strong_mercenary.lua") includeFile("lok/sulfer_pool_mynock.lua") includeFile("lok/sulfur_lake_pirate.lua") includeFile("lok/theme_park_rebel_bounty_hunter.lua") includeFile("lok/theme_park_rebel_edycu.lua") includeFile("lok/theme_park_rebel_engineer.lua") includeFile("lok/theme_park_rebel_pirate.lua") includeFile("lok/weak_mercenary.lua") includeFile("lok/rifea_eicik.lua") includeFile("lok/rorha_wahe.lua") includeFile("lok/reggi_tirver.lua") includeFile("lok/vixur_webb.lua") includeFile("lok/ifoja_lico.lua") includeFile("lok/evathm.lua") includeFile("lok/bapibac.lua") includeFile("lok/lok_herald_01.lua") includeFile("lok/lok_herald_02.lua") includeFile("lok/melo.lua") includeFile("lok/idhak_ipath.lua") includeFile("lok/ciwi_mosregri.lua")
(unstable) [fixed] missing reference to npc template for nien nunb mission 3.
(unstable) [fixed] missing reference to npc template for nien nunb mission 3. git-svn-id: e4cf3396f21da4a5d638eecf7e3b4dd52b27f938@5924 c3d1530f-68f5-4bd0-87dc-8ef779617e40
Lua
agpl-3.0
Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo
3c323ad3eaf31cc34ad0a3de0dba54272094f0f5
ini.lua
ini.lua
-- Copyright (c) 2015 Laurent Zubiaur -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- See README.md for the documentation and examples local lpeg = require 'lpeg' lpeg.locale(lpeg) -- adds locale entries into 'lpeg' table -- The module local ini = {} -- TODO failed if there is an empty line at eof ini.config = function(t) -- Config parameters local sc = t.separator or '=' -- Separator character local cc = t.comment or ';#' -- Comment characters local trim = t.trim == nil and true or t.trim -- Should capture or trim white spaces local lc = t.lowercase == nil and false or t.lowercase -- Should key be lowercase -- LPeg shortcut local P = lpeg.P -- Pattern local R = lpeg.R -- Range local S = lpeg.S -- String local V = lpeg.V -- Variable local C = lpeg.C -- Capture local Cf = lpeg.Cf -- Capture floding local Cc = lpeg.Cc -- Constant capture local Ct = lpeg.Ct -- Table capture local Cg = lpeg.Cg -- Group capture local Cs = lpeg.Cs -- Capture String (replace) local space = lpeg.space -- include tab and new line (\n) local alpha = lpeg.alpha local digit = lpeg.digit local any = P(1) local _alpha = P('_') + alpha -- underscore or alpha character local keyid = _alpha^1 * (_alpha + digit)^0 ini.grammar = P{ 'all'; key = not lc and C(keyid) * space^0 or Cs(keyid / function(s) return s:lower() end) * space^0, sep = P(sc), cr = P'\n' + P'\r\n', comment = S(cc)^1 * lpeg.print^0, string = space^0 * P'"' * Cs((any - P'"' + P'""'/'"')^0) * P'"' * space^0, value = trim and space^0 * C(((space - '\n')^0 * (any - space)^1)^1) * space^0 or C((any - P'\n') ^1), set = Cg(V'key' * V'sep' * (V'string' + V'value')), line = space^0 * (V'comment' + V'set'), body = Cf(Ct'' * (V'cr' + V'line')^0, rawset), label = P'['^1 * space^0 * V'key' * space^0 * P']'^1 * space^0, -- the section label section = space^0 * Cg(V'label' * V'body'), sections = V'section' * (V'cr' + V'section')^0, all = Cf(Ct'' * ((V'cr' + V'line')^0 * V'sections'^0), rawset) * (V'cr' + -1), -- lines followed by a line return or end of string } end ini.parse = function(data) if type(data) == 'string' then return lpeg.match(ini.grammar, data) end return {} end ini.parse_file = function(filename) local f = assert(io.open(filename, "r")) local t = ini.parse(f:read('*all')) f:close() return t end -- Use default settings ini.config{} return ini
-- Copyright (c) 2015 Laurent Zubiaur -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- See README.md for the documentation and examples local lpeg = require 'lpeg' lpeg.locale(lpeg) -- adds locale entries into 'lpeg' table -- The module local ini = {} ini.config = function(t) -- Config parameters local sc = t.separator or '=' -- Separator character local cc = t.comment or ';#' -- Comment characters local trim = t.trim == nil and true or t.trim -- Should capture or trim white spaces local lc = t.lowercase == nil and false or t.lowercase -- Should key be lowercase -- LPeg shortcut local P = lpeg.P -- Pattern local R = lpeg.R -- Range local S = lpeg.S -- String local V = lpeg.V -- Variable local C = lpeg.C -- Capture local Cf = lpeg.Cf -- Capture floding local Cc = lpeg.Cc -- Constant capture local Ct = lpeg.Ct -- Table capture local Cg = lpeg.Cg -- Group capture local Cs = lpeg.Cs -- Capture String (replace) local space = lpeg.space -- include tab and new line (\n) local alpha = lpeg.alpha local digit = lpeg.digit local any = P(1) local _alpha = P('_') + alpha -- underscore or alpha character local keyid = _alpha^1 * (_alpha + digit)^0 ini.grammar = P{ 'all'; key = not lc and C(keyid) * space^0 or Cs(keyid / function(s) return s:lower() end) * space^0, sep = P(sc), cr = P'\n' + P'\r\n', comment = S(cc)^1 * lpeg.print^0, string = space^0 * P'"' * Cs((any - P'"' + P'""'/'"')^0) * P'"' * space^0, value = trim and space^0 * C(((space - '\n')^0 * (any - space)^1)^1) * space^0 or C((any - P'\n') ^1), set = Cg(V'key' * V'sep' * (V'string' + V'value')), line = space^0 * (V'comment' + V'set'), body = Cf(Ct'' * (V'cr' + V'line')^0, rawset), label = P'['^1 * space^0 * V'key' * space^0 * P']'^1 * space^0, -- the section label section = space^0 * Cg(V'label' * V'body'), sections = V'section' * (V'cr' + V'section')^0, all = Cf(Ct'' * ((V'cr' + V'line')^0 * V'sections'^0), rawset) * (V'cr' + -1), -- lines followed by a line return or end of string } end ini.parse = function(data) if type(data) == 'string' then return lpeg.match(ini.grammar, data) end return {} end ini.parse_file = function(filename) local f = assert(io.open(filename, "r")) local t = ini.parse(f:read('*all')) f:close() return t end -- Use default settings ini.config{} return ini
Remove note about fixed bug
Remove note about fixed bug
Lua
mit
lzubiaur/ini.lua
a090094b2e55b1ee43d85d1e83f26b3659078090
MMOCoreORB/bin/scripts/object/tangible/gem/armor.lua
MMOCoreORB/bin/scripts/object/tangible/gem/armor.lua
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_tangible_gem_armor = object_tangible_gem_shared_armor:new { gameObjectType = 8223 } ObjectTemplates:addTemplate(object_tangible_gem_armor, "object/tangible/gem/armor.iff")
--Copyright (C) 2010 <SWGEmu> --This File is part of Core3. --This program is free software; you can redistribute --it and/or modify it under the terms of the GNU Lesser --General Public License as published by the Free Software --Foundation; either version 2 of the License, --or (at your option) any later version. --This program is distributed in the hope that it will be useful, --but WITHOUT ANY WARRANTY; without even the implied warranty of --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. --See the GNU Lesser General Public License for --more details. --You should have received a copy of the GNU Lesser General --Public License along with this program; if not, write to --the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA --Linking Engine3 statically or dynamically with other modules --is making a combined work based on Engine3. --Thus, the terms and conditions of the GNU Lesser General Public License --cover the whole combination. --In addition, as a special exception, the copyright holders of Engine3 --give you permission to combine Engine3 program with free software --programs or libraries that are released under the GNU LGPL and with --code included in the standard release of Core3 under the GNU LGPL --license (or modified versions of such code, with unchanged license). --You may copy and distribute such a system following the terms of the --GNU LGPL for Engine3 and the licenses of the other code concerned, --provided that you include the source code of that other code when --and as the GNU LGPL requires distribution of source code. --Note that people who make modified versions of Engine3 are not obligated --to grant this special exception for their modified versions; --it is their choice whether to do so. The GNU Lesser General Public License --gives permission to release a modified version without this exception; --this exception also makes it possible to release a modified version object_tangible_gem_armor = object_tangible_gem_shared_armor:new { gameObjectType = 8223, --clientGameObjectType = 8221 --8221 = Clothing attachment - mistake by SOE clientGameObjectType = 8223 } ObjectTemplates:addTemplate(object_tangible_gem_armor, "object/tangible/gem/armor.iff")
[fixed] Armor attachments appear under Armor Attachments category now on bazaar.
[fixed] Armor attachments appear under Armor Attachments category now on bazaar. git-svn-id: c34995188cc7e843f8a799edec2d9d4b36f36456@4738 c3d1530f-68f5-4bd0-87dc-8ef779617e40
Lua
agpl-3.0
Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo
dcf3b40d183c63c789e13204bc25ca9f4d0c328b
police/client/cloackroom.lua
police/client/cloackroom.lua
--[[ Cops_FiveM - A cops script for FiveM RP servers. Copyright (C) 2018 FiveM-Scripts 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 Cops_FiveM in the file "LICENSE". If not, see <http://www.gnu.org/licenses/>. ]] local buttons = {} function load_cloackroom() for k in ipairs (buttons) do buttons [k] = nil end for k, data in pairs(skins) do if config.useCopWhitelist then if dept == k then for k, v in pairs(data) do buttons[#buttons+1] = {name = tostring(v.name), func = "clockIn", params = tostring(v.model)} end end else for k, v in pairs(data) do buttons[#buttons+1] = {name = tostring(v.name), func = "clockIn", params = tostring(v.model)} end end end buttons[#buttons+1] = {name = i18n.translate("cloackroom_break_service_title"), func = "clockOut", params = ""} if(config.enableOutfits == true) then if(rank <= 0) then buttons[#buttons+1] = {name = i18n.translate("cloackroom_add_yellow_vest_title"), func = "cloackroom_add_yellow_vest", params = ""} buttons[#buttons+1] = {name = i18n.translate("cloackroom_remove_yellow_vest_title"), func = "cloackroom_rem_yellow_vest", params = ""} end end end function clockIn(model) if model then if IsModelValid(model) and IsModelInCdimage(model) then ServiceOn() SetCopModel(model) drawNotification(i18n.translate("now_in_service_notification")) drawNotification(i18n.translate("help_open_menu_notification")) else drawNotification("This model is ~r~invalid~w~.") end end end function clockOut() ServiceOff() removeUniforme() drawNotification(i18n.translate("break_service_notification")) end function cloackroom_add_yellow_vest() Citizen.CreateThread(function() if(GetEntityModel(PlayerPedId()) == hashSkin) then SetPedComponentVariation(PlayerPedId(), 8, 59, 0, 2) else SetPedComponentVariation(PlayerPedId(), 8, 36, 0, 2) end end) end function cloackroom_rem_yellow_vest() Citizen.CreateThread(function() if(GetEntityModel(PlayerPedId()) == hashSkin) then SetPedComponentVariation(PlayerPedId(), 8, 58, 0, 2) else SetPedComponentVariation(PlayerPedId(), 8, 35, 0, 2) end end) end function SetCopModel(model) SetMaxWantedLevel(0) SetWantedLevelMultiplier(0.0) SetRelationshipBetweenGroups(0, GetHashKey("police"), GetHashKey("PLAYER")) SetRelationshipBetweenGroups(0, GetHashKey("PLAYER"), GetHashKey("police")) modelHash = GetHashKey(model) RequestModel(modelHash) while not HasModelLoaded(modelHash) do Citizen.Wait(0) end if model == "s_m_y_cop_01" then if (config.enableOutfits == true) then if(GetEntityModel(PlayerPedId()) == GetHashKey("mp_m_freemode_01")) then SetPedPropIndex(PlayerPedId(), 1, 5, 0, 2) --Sunglasses SetPedPropIndex(PlayerPedId(), 2, 0, 0, 2) --Bluetoothn earphone SetPedComponentVariation(PlayerPedId(), 11, 55, 0, 2) --Shirt SetPedComponentVariation(PlayerPedId(), 8, 58, 0, 2) --Nightstick decoration SetPedComponentVariation(PlayerPedId(), 4, 35, 0, 2) --Pants SetPedComponentVariation(PlayerPedId(), 6, 24, 0, 2) --Shooes SetPedComponentVariation(PlayerPedId(), 10, 8, config.rank.outfit_badge[rank], 2) --rank else SetPedPropIndex(PlayerPedId(), 1, 11, 3, 2) --Sunglasses SetPedPropIndex(PlayerPedId(), 2, 0, 0, 2) --Bluetoothn earphone SetPedComponentVariation(PlayerPedId(), 3, 14, 0, 2) --Non buggy tshirt SetPedComponentVariation(PlayerPedId(), 11, 48, 0, 2) --Shirt SetPedComponentVariation(PlayerPedId(), 8, 35, 0, 2) --Nightstick decoration SetPedComponentVariation(PlayerPedId(), 4, 34, 0, 2) --Pants SetPedComponentVariation(PlayerPedId(), 6, 29, 0, 2) --Shooes SetPedComponentVariation(PlayerPedId(), 10, 7, config.rank.outfit_badge[rank], 2) --rank end else SetPlayerModel(PlayerId(), modelHash) end elseif model == "s_m_y_hwaycop_01" then SetPlayerModel(PlayerId(), modelHash) SetPedComponentVariation(PlayerPedId(), 10, 7, config.rank.outfit_badge[rank], 2) elseif model == "s_m_y_sheriff_01" then SetPlayerModel(PlayerId(), modelHash) SetPedComponentVariation(PlayerPedId(), 10, 7, config.rank.outfit_badge[rank], 2) elseif model == "s_m_y_ranger_01" then SetPlayerModel(PlayerId(), modelHash) SetPedComponentVariation(PlayerPedId(), 10, 7, config.rank.outfit_badge[rank], 2) else -- SetPlayerModel(PlayerId(), modelHash) end giveBasicKit() SetModelAsNoLongerNeeded(modelHash) end function removeUniforme() if(config.enableOutfits == true) then RemoveAllPedWeapons(PlayerPedId()) TriggerServerEvent("skin_customization:SpawnPlayer") else local model = GetHashKey("a_m_y_mexthug_01") RequestModel(model) while not HasModelLoaded(model) do Citizen.Wait(0) end SetPlayerModel(PlayerId(), model) SetModelAsNoLongerNeeded(model) SetMaxWantedLevel(5) SetWantedLevelMultiplier(1.0) SetRelationshipBetweenGroups(3, GetHashKey("police"), GetHashKey("PLAYER")) SetRelationshipBetweenGroups(3, GetHashKey("PLAYER"), GetHashKey("police")) end end function OpenCloackroom() if anyMenuOpen.menuName ~= "cloackroom" and not anyMenuOpen.isActive then SendNUIMessage({ title = GetLabelText("collision_8vlv02g"), subtitle = GetLabelText("INPUT_CHARACTER_WHEEL"), buttons = buttons, action = "setAndOpen" }) anyMenuOpen.menuName = "cloackroom" anyMenuOpen.isActive = true if config.enableVersionNotifier then TriggerServerEvent('police:UpdateNotifier') end end end
--[[ Cops_FiveM - A cops script for FiveM RP servers. Copyright (C) 2018 FiveM-Scripts 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 Cops_FiveM in the file "LICENSE". If not, see <http://www.gnu.org/licenses/>. ]] local buttons = {} function load_cloackroom() for k in ipairs (buttons) do buttons [k] = nil end for k, data in pairs(skins) do if config.useCopWhitelist then if dept == k then for k, v in pairs(data) do buttons[#buttons+1] = {name = tostring(v.name), func = "clockIn", params = tostring(v.model)} end end else for k, v in pairs(data) do buttons[#buttons+1] = {name = tostring(v.name), func = "clockIn", params = tostring(v.model)} end end end buttons[#buttons+1] = {name = i18n.translate("cloackroom_break_service_title"), func = "clockOut", params = ""} if(config.enableOutfits == true) then if(rank <= 0) then buttons[#buttons+1] = {name = i18n.translate("cloackroom_add_yellow_vest_title"), func = "cloackroom_add_yellow_vest", params = ""} buttons[#buttons+1] = {name = i18n.translate("cloackroom_remove_yellow_vest_title"), func = "cloackroom_rem_yellow_vest", params = ""} end end end function clockIn(model) if model then if IsModelValid(model) and IsModelInCdimage(model) then ServiceOn() SetCopModel(model) drawNotification(i18n.translate("now_in_service_notification")) drawNotification(i18n.translate("help_open_menu_notification")) else drawNotification("This model is ~r~invalid~w~.") end end end function clockOut() ServiceOff() removeUniforme() drawNotification(i18n.translate("break_service_notification")) end function cloackroom_add_yellow_vest() Citizen.CreateThread(function() if(GetEntityModel(PlayerPedId()) == hashSkin) then SetPedComponentVariation(PlayerPedId(), 8, 59, 0, 2) else SetPedComponentVariation(PlayerPedId(), 8, 36, 0, 2) end end) end function cloackroom_rem_yellow_vest() Citizen.CreateThread(function() if(GetEntityModel(PlayerPedId()) == hashSkin) then SetPedComponentVariation(PlayerPedId(), 8, 58, 0, 2) else SetPedComponentVariation(PlayerPedId(), 8, 35, 0, 2) end end) end function SetCopModel(model) SetMaxWantedLevel(0) SetWantedLevelMultiplier(0.0) SetRelationshipBetweenGroups(0, GetHashKey("police"), GetHashKey("PLAYER")) SetRelationshipBetweenGroups(0, GetHashKey("PLAYER"), GetHashKey("police")) modelHash = GetHashKey(model) RequestModel(modelHash) while not HasModelLoaded(modelHash) do Citizen.Wait(0) end if model == "s_m_y_cop_01" then if (config.enableOutfits == true) then if(GetEntityModel(PlayerPedId()) == GetHashKey("mp_m_freemode_01")) then SetPedPropIndex(PlayerPedId(), 1, 5, 0, 2) --Sunglasses SetPedPropIndex(PlayerPedId(), 2, 0, 0, 2) --Bluetoothn earphone SetPedComponentVariation(PlayerPedId(), 11, 55, 0, 2) --Shirt SetPedComponentVariation(PlayerPedId(), 8, 58, 0, 2) --Nightstick decoration SetPedComponentVariation(PlayerPedId(), 4, 35, 0, 2) --Pants SetPedComponentVariation(PlayerPedId(), 6, 24, 0, 2) --Shooes SetPedComponentVariation(PlayerPedId(), 10, 8, config.rank.outfit_badge[rank], 2) --rank else SetPedPropIndex(PlayerPedId(), 1, 11, 3, 2) --Sunglasses SetPedPropIndex(PlayerPedId(), 2, 0, 0, 2) --Bluetoothn earphone SetPedComponentVariation(PlayerPedId(), 3, 14, 0, 2) --Non buggy tshirt SetPedComponentVariation(PlayerPedId(), 11, 48, 0, 2) --Shirt SetPedComponentVariation(PlayerPedId(), 8, 35, 0, 2) --Nightstick decoration SetPedComponentVariation(PlayerPedId(), 4, 34, 0, 2) --Pants SetPedComponentVariation(PlayerPedId(), 6, 29, 0, 2) --Shooes SetPedComponentVariation(PlayerPedId(), 10, 7, config.rank.outfit_badge[rank], 2) --rank end else SetPlayerModel(PlayerId(), modelHash) end elseif model == "s_m_y_hwaycop_01" then SetPlayerModel(PlayerId(), modelHash) SetPedComponentVariation(PlayerPedId(), 10, 7, config.rank.outfit_badge[rank], 2) elseif model == "s_m_y_sheriff_01" then SetPlayerModel(PlayerId(), modelHash) SetPedComponentVariation(PlayerPedId(), 10, 7, config.rank.outfit_badge[rank], 2) elseif model == "s_m_y_ranger_01" then SetPlayerModel(PlayerId(), modelHash) SetPedComponentVariation(PlayerPedId(), 10, 7, config.rank.outfit_badge[rank], 2) elseif model == "a_m_y_genstreet_01" then else SetPlayerModel(PlayerId(), modelHash) end giveBasicKit() SetModelAsNoLongerNeeded(modelHash) end function removeUniforme() if(config.enableOutfits == true) then RemoveAllPedWeapons(PlayerPedId()) TriggerServerEvent("skin_customization:SpawnPlayer") else local model = GetHashKey("a_m_y_mexthug_01") RequestModel(model) while not HasModelLoaded(model) do Citizen.Wait(0) end SetPlayerModel(PlayerId(), model) SetModelAsNoLongerNeeded(model) SetMaxWantedLevel(5) SetWantedLevelMultiplier(1.0) SetRelationshipBetweenGroups(3, GetHashKey("police"), GetHashKey("PLAYER")) SetRelationshipBetweenGroups(3, GetHashKey("PLAYER"), GetHashKey("police")) end end function OpenCloackroom() if anyMenuOpen.menuName ~= "cloackroom" and not anyMenuOpen.isActive then SendNUIMessage({ title = GetLabelText("collision_8vlv02g"), subtitle = GetLabelText("INPUT_CHARACTER_WHEEL"), buttons = buttons, action = "setAndOpen" }) anyMenuOpen.menuName = "cloackroom" anyMenuOpen.isActive = true if config.enableVersionNotifier then TriggerServerEvent('police:UpdateNotifier') end end end
fixed typo
fixed typo
Lua
mit
Kyominii/Cops_FiveM,Kyominii/Cops_FiveM
e72fc960d9707f50c90217ce767e3ddc196d87ca
messages/client/messages.lua
messages/client/messages.lua
local messages = { global = { }, client = { } } local screenWidth, screenHeight = guiGetScreenSize( ) local messageWidth, messageHeight = 316, 152 function createMessage( message, messageType, messageGlobalID, hideButton, disableInput ) destroyMessage( messageType ) destroyMessage( nil, nil, messageGlobalID ) local messageID = messageGlobalID or exports.common:nextIndex( messages ) local messageRealm = messageGlobalID and "global" or "client" local messageHolder messages[ messageRealm ][ messageID ] = { messageType = messageType or "other", disableInput = disableInput } messageHolder = messages[ messageRealm ][ messageID ] local messageHeight = messageHeight - ( hideButton and 25 or 0 ) messageHolder.window = guiCreateWindow( ( screenWidth - messageWidth ) / 2, ( screenHeight - messageHeight ) / 2, messageWidth, messageHeight, "Message", false ) guiWindowSetSizable( messageHolder.window, false ) guiSetProperty( messageHolder.window, "AlwaysOnTop", "True" ) guiSetAlpha( messageHolder.window, 0.925 ) setElementData( messageHolder.window, "messages:id", messageID, false ) setElementData( messageHolder.window, "messages:type", messageHolder.messageType, false ) setElementData( messageHolder.window, "messages:realm", messageRealm, false ) setElementData( messageHolder.window, "messages:disableInput", disableInput, false ) messageHolder.message = guiCreateLabel( 17, 35, 283, 60, message, false, messageHolder.window ) guiLabelSetHorizontalAlign( messageHolder.message, "center", true ) guiLabelSetVerticalAlign( messageHolder.message, "center" ) showCursor( true ) guiSetInputEnabled( disableInput or false ) if ( not hideButton ) then messageHolder.button = guiCreateButton( 16, 109, 284, 25, "Continue", false, messageHolder.window ) addEventHandler( "onClientGUIClick", messageHolder.button, function( ) destroyMessage( messageHolder.messageType ) end, false ) end end addEvent( "messages:create", true ) addEventHandler( "messages:create", root, createMessage ) function destroyMessage( messageType, messageGlobalID ) if ( messageType ) then for messageIndex, messageID in ipairs( exports.common:findByValue( messages.client, messageType, true ) ) do local message = messages.client[ messageID ] if ( isElement( message.window ) ) then destroyElement( message.window ) end triggerEvent( "messages:onContinue", localPlayer, messageID, message.messageType, "client", message.disableInput ) messages.client[ messageIndex ] = nil end else if ( messageGlobalID ) then local message = messages.global[ messageGlobalID ] if ( message ) then if ( isElement( message.window ) ) then destroyElement( message.window ) end triggerEvent( "messages:onContinue", localPlayer, messageID, message.messageType, "global", message.disableInput ) messages.global[ messageGlobalID ] = nil end end end if ( #messages.client == 0 ) and ( #messages.global == 0 ) then showCursor( false ) guiSetInputEnabled( false ) end end addEvent( "messages:destroy", true ) addEventHandler( "messages:destroy", root, destroyMessage ) addEvent( "messages:onContinue", true ) addEventHandler( "messages:onContinue", root, function( id, type, realm, disableInput ) if ( type == "login" ) then triggerEvent( "accounts:enableGUI", localPlayer ) elseif ( type == "selection" ) then triggerEvent( "characters:enableGUI", localPlayer ) end end ) addEventHandler( "onClientResourceStop", root, function( resource ) if ( not getElementData( localPlayer, "account:id" ) ) then triggerEvent( "accounts:enableGUI", localPlayer ) end if ( getResourceName( resource ) == "accounts" ) then destroyMessage( "login" ) destroyMessage( "selection" ) end end ) addEventHandler( "onClientResourceStart", root, function( ) triggerServerEvent( "messages:ready", localPlayer ) end )
local messages = { global = { }, client = { } } local screenWidth, screenHeight = guiGetScreenSize( ) local messageWidth, messageHeight = 316, 152 function createMessage( message, messageType, messageGlobalID, hideButton, disableInput ) destroyMessage( messageType ) destroyMessage( nil, nil, messageGlobalID ) local messageRealm = messageGlobalID and "global" or "client" local messageID = messageGlobalID or exports.common:nextIndex( messages[ messageRealm ] ) messages[ messageRealm ][ messageID ] = { messageType = messageType or "other", disableInput = disableInput } local messageHeight = messageHeight - ( hideButton and 25 or 0 ) messages[ messageRealm ][ messageID ].window = guiCreateWindow( ( screenWidth - messageWidth ) / 2, ( screenHeight - messageHeight ) / 2, messageWidth, messageHeight, "Message", false ) guiWindowSetSizable( messages[ messageRealm ][ messageID ].window, false ) guiSetProperty( messages[ messageRealm ][ messageID ].window, "AlwaysOnTop", "True" ) guiSetAlpha( messages[ messageRealm ][ messageID ].window, 0.925 ) setElementData( messages[ messageRealm ][ messageID ].window, "messages:id", messageID, false ) setElementData( messages[ messageRealm ][ messageID ].window, "messages:type", messages[ messageRealm ][ messageID ].messageType, false ) setElementData( messages[ messageRealm ][ messageID ].window, "messages:realm", messageRealm, false ) setElementData( messages[ messageRealm ][ messageID ].window, "messages:disableInput", disableInput, false ) if ( messageRealm == "global" ) then setElementData( messages[ messageRealm ][ messageID ].window, "messages:globalID", messageGlobalID, false ) end messages[ messageRealm ][ messageID ].message = guiCreateLabel( 17, 35, 283, 60, message, false, messages[ messageRealm ][ messageID ].window ) guiLabelSetHorizontalAlign( messages[ messageRealm ][ messageID ].message, "center", true ) guiLabelSetVerticalAlign( messages[ messageRealm ][ messageID ].message, "center" ) showCursor( true ) guiSetInputEnabled( disableInput or false ) if ( not hideButton ) then messages[ messageRealm ][ messageID ].button = guiCreateButton( 16, 109, 284, 25, "Continue", false, messages[ messageRealm ][ messageID ].window ) addEventHandler( "onClientGUIClick", messages[ messageRealm ][ messageID ].button, function( ) local type = getElementData( getElementParent( source ), "messages:type" ) local globalID = getElementData( getElementParent( source ), "messages:globalID" ) destroyMessage( type, globalID or nil ) end, false ) end end addEvent( "messages:create", true ) addEventHandler( "messages:create", root, createMessage ) function destroyMessage( messageType, messageGlobalID ) if ( not messageGlobalID ) then for index, data in pairs( messages.client ) do if ( data.messageType == messageType ) then if ( isElement( messages.client[ index ].window ) ) then destroyElement( messages.client[ index ].window ) end triggerEvent( "messages:onContinue", localPlayer, index, data.messageType, "client", data.disableInput ) messages.client[ index ] = nil end end else if ( messages.global[ messageGlobalID ] ) then if ( isElement( messages.global[ messageGlobalID ].window ) ) then destroyElement( messages.global[ messageGlobalID ].window ) end triggerEvent( "messages:onContinue", localPlayer, messageID, messages.global[ messageGlobalID ].messageType, "global", messages.global[ messageGlobalID ].disableInput ) messages.global[ messageGlobalID ] = nil end end if ( exports.common:count( messages.client ) == 0 ) and ( exports.common:count( messages.global ) == 0 ) then showCursor( false ) guiSetInputEnabled( false ) end end addEvent( "messages:destroy", true ) addEventHandler( "messages:destroy", root, destroyMessage ) addEvent( "messages:onContinue", true ) addEventHandler( "messages:onContinue", root, function( id, type, realm, disableInput ) if ( type == "login" ) then triggerEvent( "accounts:enableGUI", localPlayer ) elseif ( type == "selection" ) then triggerEvent( "characters:enableGUI", localPlayer ) end end ) addEventHandler( "onClientResourceStop", root, function( resource ) if ( not getElementData( localPlayer, "account:id" ) ) then triggerEvent( "accounts:enableGUI", localPlayer ) end if ( getResourceName( resource ) == "accounts" ) then destroyMessage( "login" ) destroyMessage( "selection" ) end end ) addEventHandler( "onClientResourceStart", root, function( ) triggerServerEvent( "messages:ready", localPlayer ) end )
messages: fixed non-working messages again
messages: fixed non-working messages again
Lua
mit
smile-tmb/lua-mta-fairplay-roleplay
445adde6d11b76d1f3bc41fba38573746e021b9d
mods/base/req/quick_menu.lua
mods/base/req/quick_menu.lua
QuickMenu = QuickMenu or class() QuickMenu._menu_id_key = "quick_menu_id_" QuickMenu._menu_id_index = 0 function QuickMenu:init( title, text, options, show_immediately ) QuickMenu._menu_id_index = QuickMenu._menu_id_index + 1 self.menu_data = { id = QuickMenu._menu_id_key .. tostring( QuickMenu._menu_id_index ), title = title, text = text, button_list = {}, } self.visible = false local add_default = false if (not options) or (options ~= nil and type(options) ~= "table") or (options ~= nil and type(options) == "table" and #options == 0) then add_default = true end if add_default then local tbl = { text = "OK", is_cancel_button = true, } table.insert( options, tbl ) end for k, option in ipairs( options ) do option.data = option.data option.callback = option.callback local button = {} local callback_data = { data = option.data, callback = option.callback } button.text = option.text button.callback_func = callback( self, self, "_callback", callback_data ) button.cancel_button = option.is_cancel_button or false if option.is_focused_button then self.menu_data.focus_button = #self.menu_data.button_list + 1 end table.insert( self.menu_data.button_list, button ) end if show_immediately then self:show() end return self end function QuickMenu:_callback( callback_data ) if callback_data.callback then callback_data.callback( callback_data.data ) end self.visible = false end function QuickMenu:Show() if not self.visible then self.visible = true managers.system_menu:show( self.menu_data ) end end function QuickMenu:show() self:Show() end function QuickMenu:Hide() if self.visible then managers.system_menu:close( self.menu_data.id ) self.visible = false end end function QuickMenu:hide() self:Hide() end
QuickMenu = QuickMenu or class() QuickMenu._menu_id_key = "quick_menu_id_" QuickMenu._menu_id_index = 0 function QuickMenu:new( ... ) return self:init( ... ) end function QuickMenu:init( title, text, options, show_immediately ) QuickMenu._menu_id_index = QuickMenu._menu_id_index + 1 self.menu_data = { id = QuickMenu._menu_id_key .. tostring( QuickMenu._menu_id_index ), title = title, text = text, button_list = {}, } self.visible = false local add_default = false if (not options) or (options ~= nil and type(options) ~= "table") or (options ~= nil and type(options) == "table" and #options == 0) then add_default = true end if add_default then local tbl = { text = "OK", is_cancel_button = true, } table.insert( options, tbl ) end for k, option in ipairs( options ) do option.data = option.data option.callback = option.callback local button = {} local callback_data = { data = option.data, callback = option.callback } button.text = option.text button.callback_func = callback( self, self, "_callback", callback_data ) button.cancel_button = option.is_cancel_button or false if option.is_focused_button then self.menu_data.focus_button = #self.menu_data.button_list + 1 end table.insert( self.menu_data.button_list, button ) end if show_immediately then self:show() end return self end function QuickMenu:_callback( callback_data ) if callback_data.callback then callback_data.callback( callback_data.data ) end self.visible = false end function QuickMenu:Show() if not self.visible then self.visible = true managers.system_menu:show( self.menu_data ) end end function QuickMenu:show() self:Show() end function QuickMenu:Hide() if self.visible then managers.system_menu:close( self.menu_data.id ) self.visible = false end end function QuickMenu:hide() self:Hide() end
Fixed quick menu not returning correct table
Fixed quick menu not returning correct table
Lua
mit
SirWaddles/Payday-2-BLT,Olipro/Payday-2-BLT_Club-Sandwich-Edition,Olipro/Payday-2-BLT_Club-Sandwich-Edition,SirWaddles/Payday-2-BLT,JamesWilko/Payday-2-BLT,antonpup/Payday-2-BLT,JamesWilko/Payday-2-BLT,antonpup/Payday-2-BLT
47978eb63825042963b1a192c32bab18874fa1b0
script/index.lua
script/index.lua
local white = Color.new(255,255,255) local green = Color.new(0,255,0) local url = "https://joshuadoes.com/projects/3DSHomebrew/BUILDS/nds-bootstrap/bootstrap-dldi.nds" function unicodify(str) local new_str = "" for i = 1, #str,1 do new_str = new_str..string.sub(str,i,i)..string.char(00) end return new_str end function main() Screen.refresh() Screen.debugPrint(5,5, "nds-bootstrap updater", green, TOP_SCREEN) Screen.debugPrint(5,30, "Press A to update nds-bootstrap", white, TOP_SCREEN) Screen.debugPrint(5,50, "Press START to go to HOME menu", white, TOP_SCREEN) Screen.debugPrint(5,70, "Press X to go to TWLauncher", white, TOP_SCREEN) Screen.debugPrint(5,155, "Thanks to:", white, TOP_SCREEN) Screen.debugPrint(5,170, "Alerdy for the updater", white, TOP_SCREEN) Screen.debugPrint(5,185, "JoshuaDoes for hosting the builds", white, TOP_SCREEN) Screen.debugPrint(5,200, "Rinnegatamante for lpp-3ds", white, TOP_SCREEN) Screen.debugPrint(5,215, "ahezard for nds-bootstrap", white, TOP_SCREEN) Screen.waitVblankStart() Screen.flip() while true do pad = Controls.read() if pad ~= oldPad then oldPad = pad if Controls.check(pad,KEY_START) then Screen.waitVblankStart() Screen.flip() System.exit() elseif Controls.check(pad,KEY_X) then System.launchCIA(75252224, SDMC) elseif Controls.check(pad,KEY_A) then Screen.refresh() Screen.waitVblankStart() Screen.flip() Screen.clear(TOP_SCREEN) if Network.isWifiEnabled() then Screen.debugPrint(5,5, "Downloading the latest NDS file...", white, TOP_SCREEN) Network.downloadFile(url, "/bootstrap-dldi.nds") Screen.debugPrint(5,20, "File downloaded!", white, TOP_SCREEN) Screen.debugPrint(5,50, "Moving file to /_nds folder", white, TOP_SCREEN) System.renameFile("/bootstrap-dldi.nds","/_nds/bootstrap-dldi.nds") Screen.debugPrint(5,95, "Done!", white, TOP_SCREEN) Screen.debugPrint(5,110, "Press START to go to HOME menu", white, TOP_SCREEN) Screen.debugPrint(5,125, "Press X to go to TWLauncher", white, TOP_SCREEN) while true do pad = Controls.read() if pad ~= oldPad then oldPad = pad if Controls.check(pad,KEY_START) then Screen.waitVblankStart() Screen.flip() System.exit() elseif Controls.check(pad,KEY_X) then System.launchCIA(75252224, SDMC) end end end else Screen.debugPrint(5,5, "WiFi is off! Please turn it on and retry!", white, TOP_SCREEN) Screen.debugPrint(5,20, "Press START to go back to Home menu", white, TOP_SCREEN) Screen.debugPrint(5,25, "Press X to go to TWLauncher", white, TOP_SCREEN) while true do pad = Controls.read() if pad ~= oldPad then oldPad = pad if Controls.check(pad,KEY_START) then Screen.waitVblankStart() Screen.flip() System.exit() end end end end end end end end main()
local white = Color.new(255,255,255) local green = Color.new(0,255,0) local url = "https://joshuadoes.com/projects/3DSHomebrew/BUILDS/nds-bootstrap/bootstrap-dldi.nds" function unicodify(str) local new_str = "" for i = 1, #str,1 do new_str = new_str..string.sub(str,i,i)..string.char(00) end return new_str end function main() Screen.refresh() Screen.debugPrint(5,5, "nds-bootstrap updater", green, TOP_SCREEN) Screen.debugPrint(5,30, "Press A to update nds-bootstrap", white, TOP_SCREEN) Screen.debugPrint(5,50, "Press START to go to HOME menu", white, TOP_SCREEN) Screen.debugPrint(5,70, "Press X to go to TWLauncher", white, TOP_SCREEN) Screen.debugPrint(5,155, "Thanks to:", white, TOP_SCREEN) Screen.debugPrint(5,170, "Alerdy for the updater", white, TOP_SCREEN) Screen.debugPrint(5,185, "JoshuaDoes for hosting the builds", white, TOP_SCREEN) Screen.debugPrint(5,200, "Rinnegatamante for lpp-3ds", white, TOP_SCREEN) Screen.debugPrint(5,215, "ahezard for nds-bootstrap", white, TOP_SCREEN) Screen.waitVblankStart() Screen.flip() while true do pad = Controls.read() if pad ~= oldPad then oldPad = pad if Controls.check(pad,KEY_START) then Screen.waitVblankStart() Screen.flip() System.exit() elseif Controls.check(pad,KEY_X) then System.launchCIA(75252224, SDMC) elseif Controls.check(pad,KEY_A) then Screen.refresh() Screen.waitVblankStart() Screen.flip() Screen.clear(TOP_SCREEN) if Network.isWifiEnabled() then Screen.debugPrint(5,5, "Downloading the latest NDS file...", white, TOP_SCREEN) Network.downloadFile(url, "/bootstrap-dldi.nds") Screen.debugPrint(5,20, "File downloaded!", white, TOP_SCREEN) Screen.debugPrint(5,50, "Moving file to /_nds folder", white, TOP_SCREEN) System.renameFile("/bootstrap-dldi.nds","/_nds/bootstrap-dldi.nds") Screen.debugPrint(5,95, "Done!", white, TOP_SCREEN) Screen.debugPrint(5,110, "Press START to go to HOME menu", white, TOP_SCREEN) Screen.debugPrint(5,125, "Press X to go to TWLauncher", white, TOP_SCREEN) while true do pad = Controls.read() if pad ~= oldPad then oldPad = pad if Controls.check(pad,KEY_START) then Screen.waitVblankStart() Screen.flip() System.exit() elseif Controls.check(pad,KEY_X) then System.launchCIA(75252224, SDMC) end end end else Screen.debugPrint(5,5, "WiFi is off! Please turn it on and retry!", white, TOP_SCREEN) Screen.debugPrint(5,20, "Press START to go back to Home menu", white, TOP_SCREEN) Screen.debugPrint(5,35, "Press X to go to TWLauncher", white, TOP_SCREEN) while true do pad = Controls.read() if pad ~= oldPad then oldPad = pad if Controls.check(pad,KEY_START) then Screen.waitVblankStart() Screen.flip() System.exit() elseif Controls.check(pad,KEY_X) then System.launchCIA(75252224, SDMC) end end end end end end end end main()
Fixed GUI issue
Fixed GUI issue The screen saying to connect to wifi if not connected had some GUI issues, which I fixed. You can also launch TWLoader from that specific screen as well.
Lua
mit
Alerdy/ReBootstrap
c5b337df975dd3e46b530d8ba92f1086f8e49704
kong/plugins/pre-function/handler.lua
kong/plugins/pre-function/handler.lua
local BasePlugin = require "kong.plugins.base_plugin" local PreFunction = BasePlugin:extend() local config_cache = setmetatable({}, { __mode = "k" }) function PreFunction:new() PreFunction.super.new(self, "pre-function") end function PreFunction:access(config) PreFunction.super.access(self) local functions = config_cache[config] if not functions then functions = {} for _, fn_str in ipairs(config.functions) do table.insert(functions, loadstring(fn_str)) end config_cache[config] = functions end for _, fn in ipairs(functions) do fn() end end PreFunction.PRIORITY = math.huge PreFunction.VERSION = "0.1.0" return PreFunction
local BasePlugin = require "kong.plugins.base_plugin" local PreFunction = BasePlugin:extend() local config_cache = setmetatable({}, { __mode = "k" }) function PreFunction:new() PreFunction.super.new(self, "pre-function") end function PreFunction:access(config) PreFunction.super.access(self) local functions = config_cache[config] if not functions then functions = {} for _, fn_str in ipairs(config.functions) do table.insert(functions, loadstring(fn_str)) end config_cache[config] = functions end for _, fn in ipairs(functions) do fn() end end PreFunction.VERSION = "0.1.0" -- Set priority to just below infinity so that it runs immediately after -- tracing plugins to ensure tracing metrics are accurately measured and -- reported. See https://github.com/Kong/kong/pull/3551#issue-195293286 PreFunction.PRIORITY = 1.7976931348623e+308 return PreFunction
fix(serverless-functions) update priority to be math.huge - 1
fix(serverless-functions) update priority to be math.huge - 1
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
a64549288a6ca881cc69a24b913293b4fa4af765
mod_storage_gdbm/mod_storage_gdbm.lua
mod_storage_gdbm/mod_storage_gdbm.lua
-- mod_storage_gdbm -- Copyright (C) 2014-2015 Kim Alvefur -- -- This file is MIT/X11 licensed. -- -- Depends on lgdbm: -- http://webserver2.tecgraf.puc-rio.br/~lhf/ftp/lua/#lgdbm local gdbm = require"gdbm"; local path = require"util.paths"; local lfs = require"lfs"; local st = require"util.stanza"; local uuid = require"util.uuid".generate; local serialization = require"util.serialization"; local serialize = serialization.serialize; local deserialize = serialization.deserialize; local g_set, g_get, g_del = gdbm.replace, gdbm.fetch, gdbm.delete; local g_first, g_next = gdbm.firstkey, gdbm.nextkey; local t_remove = table.remove; local empty = {}; local function id(v) return v; end local function is_stanza(s) return getmetatable(s) == st.stanza_mt; end local function t(c, a, b) if c then return a; end return b; end local base_path = path.resolve_relative_path(prosody.paths.data, module.host); lfs.mkdir(base_path); local cache = {}; local keyval = {}; local keyval_mt = { __index = keyval, suffix = ".db" }; function keyval:set(user, value) if type(value) == "table" and next(value) == nil then value = nil; end if value ~= nil then value = serialize(value); end local ok, err = (value and g_set or g_del)(self._db, user or "@", value); if not ok then return nil, err; end return true; end function keyval:get(user) local data, err = g_get(self._db, user or "@"); if not data then return nil, err; end return deserialize(data); end local archive = {}; local archive_mt = { __index = archive, suffix = ".adb" }; archive.get = keyval.get; archive.set = keyval.set; function archive:append(username, key, when, with, value) key = key or uuid(); local meta = self:get(username); if not meta then meta = {}; end local i = meta[key] or #meta+1; local type; if is_stanza(value) then type, value = "stanza", st.preserialize(value); end meta[i] = { key = key, when = when, with = with, type = type }; meta[key] = i; local ok, err = self:set(key, value); if not ok then return nil, err; end ok, err = self:set(username, meta); if not ok then return nil, err; end return key; end local deserialize = { stanza = st.deserialize; }; function archive:find(username, query) query = query or empty_query; local meta = self:get(username) or empty; local r = query.reverse; local d = t(r, -1, 1); local s = meta[t(r, query.before, query.after)]; local limit = query.limit; if s then s = s + d; else s = t(r, #meta, 1) end local e = t(r, 1, #meta); local c = 0; return function () if limit and c >= limit then return end local item, value; for i = s, e, d do item = meta[i]; if (not query.with or item.with == query.with) and (not query.start or item.when >= query.start) and (not query["end"] or item.when <= query["end"]) then s = i + d; c = c + 1; value = self:get(item.key); return item.key, (deserialize[item.type] or id)(value), item.when, item.with; end end end end local drivers = { keyval = keyval_mt; archive = archive_mt; } function open(_, store, typ) typ = typ or "keyval"; local driver_mt = drivers[typ]; if not driver_mt then return nil, "unsupported-store"; end local db_path = path.join(base_path, store) .. driver_mt.suffix; local db = cache[db_path]; if not db then db = assert(gdbm.open(db_path, "c")); cache[db_path] = db; end return setmetatable({ _db = db; _path = db_path; store = store, typ = type }, driver_mt); end function module.unload() for path, db in pairs(cache) do gdbm.sync(db); gdbm.close(db); end end module:provides"storage";
-- mod_storage_gdbm -- Copyright (C) 2014-2015 Kim Alvefur -- -- This file is MIT/X11 licensed. -- -- Depends on lgdbm: -- http://webserver2.tecgraf.puc-rio.br/~lhf/ftp/lua/#lgdbm local gdbm = require"gdbm"; local path = require"util.paths"; local lfs = require"lfs"; local st = require"util.stanza"; local uuid = require"util.uuid".generate; local serialization = require"util.serialization"; local serialize = serialization.serialize; local deserialize = serialization.deserialize; local g_set, g_get, g_del = gdbm.replace, gdbm.fetch, gdbm.delete; local g_first, g_next = gdbm.firstkey, gdbm.nextkey; local t_remove = table.remove; local empty = {}; local function id(v) return v; end local function is_stanza(s) return getmetatable(s) == st.stanza_mt; end local function t(c, a, b) if c then return a; end return b; end local base_path = path.resolve_relative_path(prosody.paths.data, module.host); lfs.mkdir(base_path); local cache = {}; local keyval = {}; local keyval_mt = { __index = keyval, suffix = ".db" }; function keyval:set(user, value) if type(value) == "table" and next(value) == nil then value = nil; end if value ~= nil then value = serialize(value); end local ok, err = (value and g_set or g_del)(self._db, user or "@", value); if not ok then return nil, err; end return true; end function keyval:get(user) local data, err = g_get(self._db, user or "@"); if not data then return nil, err; end return deserialize(data); end local archive = {}; local archive_mt = { __index = archive, suffix = ".adb" }; archive.get = keyval.get; archive.set = keyval.set; function archive:append(username, key, when, with, value) key = key or uuid(); local meta = self:get(username); if not meta then meta = {}; end local i = meta[key] or #meta+1; local type; if is_stanza(value) then type, value = "stanza", st.preserialize(value); end meta[i] = { key = key, when = when, with = with, type = type }; meta[key] = i; local prefix = (username or "@") .. "#"; local ok, err = self:set(prefix..key, value); if not ok then return nil, err; end ok, err = self:set(username, meta); if not ok then return nil, err; end return key; end local deserialize = { stanza = st.deserialize; }; function archive:find(username, query) query = query or empty_query; local meta = self:get(username) or empty; local prefix = (username or "@") .. "#"; local r = query.reverse; local d = t(r, -1, 1); local s = meta[t(r, query.before, query.after)]; local limit = query.limit; if s then s = s + d; else s = t(r, #meta, 1) end local e = t(r, 1, #meta); local c = 0; return function () if limit and c >= limit then return end local item, value; for i = s, e, d do item = meta[i]; if (not query.with or item.with == query.with) and (not query.start or item.when >= query.start) and (not query["end"] or item.when <= query["end"]) then s = i + d; c = c + 1; value = self:get(prefix..item.key); return item.key, (deserialize[item.type] or id)(value), item.when, item.with; end end end end local drivers = { keyval = keyval_mt; archive = archive_mt; } function open(_, store, typ) typ = typ or "keyval"; local driver_mt = drivers[typ]; if not driver_mt then return nil, "unsupported-store"; end local db_path = path.join(base_path, store) .. driver_mt.suffix; local db = cache[db_path]; if not db then db = assert(gdbm.open(db_path, "c")); cache[db_path] = db; end return setmetatable({ _db = db; _path = db_path; store = store, typ = type }, driver_mt); end function module.unload() for path, db in pairs(cache) do gdbm.sync(db); gdbm.close(db); end end module:provides"storage";
mod_storage_gdbm: Prefix archive item keys with username to prevent collisions
mod_storage_gdbm: Prefix archive item keys with username to prevent collisions
Lua
mit
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
23c4421d7bb4e35a598699c3f1361173906088d8
lualib/http/server.lua
lualib/http/server.lua
local socket = require "socket" local stream = require "http.stream" local server = {} local listen = socket.listen local readline = socket.readline local read = socket.read local write = socket.write local http_err_msg = { [100] = "Continue", [101] = "Switching Protocols", [102] = "Processing", [200] = "OK", [201] = "Created", [202] = "Accepted", [203] = "Non-authoritative Information", [204] = "No Content", [205] = "Reset Content", [206] = "Partial Content", [207] = "Multi-Status", [208] = "Already Reported", [226] = "IM Used", [300] = "Multiple Choices", [301] = "Moved Permanently", [302] = "Found", [303] = "See Other", [304] = "Not Modified", [305] = "Use Proxy", [307] = "Temporary Redirect", [308] = "Permanent Redirect", [400] = "Bad Request", [401] = "Unauthorized", [402] = "Payment Required", [403] = "Forbidden", [404] = "Not Found", [405] = "Method Not Allowed", [406] = "Not Acceptable", [407] = "Proxy Authentication Required", [408] = "Request Timeout", [409] = "Conflict", [410] = "Gone", [411] = "Length Required", [412] = "Precondition Failed", [413] = "Payload Too Large", [414] = "Request-URI Too Long", [415] = "Unsupported Media Type", [416] = "Requested Range Not Satisfiable", [417] = "Expectation Failed", [418] = "I'm a teapot", [421] = "Misdirected Request", [422] = "Unprocessable Entity", [423] = "Locked", [424] = "Failed Dependency", [426] = "Upgrade Required", [428] = "Precondition Required", [429] = "Too Many Requests", [431] = "Request Header Fields Too Large", [451] = "Unavailable For Legal Reasons", [499] = "Client Closed Request", [500] = "Internal Server Error", [501] = "Not Implemented", [502] = "Bad Gateway", [503] = "Service Unavailable", [504] = "Gateway Timeout", [505] = "HTTP Version Not Supported", [506] = "Variant Also Negotiates", [507] = "Insufficient Storage", [508] = "Loop Detected", [510] = "Not Extended", [511] = "Network Authentication Required", [599] = "Network Connect Timeout Error", } local function parse_uri(str) local form = {} local start = string.find(str, "?", 1, true) if not start then return str, form end assert(start > 1) local uri = string.sub(str, 1, start - 1) local f = string.sub(str, start + 1) for k, v in string.gmatch(f, "(%w+)=(%w+)") do form[k] = v end return uri, form end local function httpd(fd, handler) socket.limit(fd, 1024 * 512) local readl = function() return readline(fd, "\r\n") end local readn = function(n) return read(fd, n) end local write = function (status, header, body) server.send(fd, status, header, body) end while true do local status, first, header, body = stream.recv_request(readl, readn) if not status then --disconnected return end if status ~= 200 then write(status, {}, "") socket.close(fd) return end --request line local method, uri, ver = first:match("(%w+)%s+(.-)%s+HTTP/([%d|.]+)\r\n") assert(method and uri and ver) header.method = method header.version = ver header.uri, header.form = parse_uri(uri) if tonumber(ver) > 1.1 then write(505, {}, "") socket.close(fd) return end if header["Content-Type"] == "application/x-www-form-urlencoded" then for k, v in string.gmatch(body, "(%w+)=(%w+)") do header.form[k] = v end body = "" end handler(header, body, write) end end function server.listen(port, handler) local h = function(fd) httpd(fd, handler) end listen(port, h) end function server.send(fd, status, header, body) local tmp = string.format("HTTP/1.1 %d %s\r\n", status, http_err_msg[status]) tmp = tmp .. table.concat(header, "\r\n") tmp = tmp .. string.format("Content-Length: %d\r\n", #body) tmp = tmp .. "\r\n" tmp = tmp .. body write(fd, tmp) end return server
local socket = require "socket" local stream = require "http.stream" local server = {} local listen = socket.listen local readline = socket.readline local read = socket.read local write = socket.write local http_err_msg = { [100] = "Continue", [101] = "Switching Protocols", [102] = "Processing", [200] = "OK", [201] = "Created", [202] = "Accepted", [203] = "Non-authoritative Information", [204] = "No Content", [205] = "Reset Content", [206] = "Partial Content", [207] = "Multi-Status", [208] = "Already Reported", [226] = "IM Used", [300] = "Multiple Choices", [301] = "Moved Permanently", [302] = "Found", [303] = "See Other", [304] = "Not Modified", [305] = "Use Proxy", [307] = "Temporary Redirect", [308] = "Permanent Redirect", [400] = "Bad Request", [401] = "Unauthorized", [402] = "Payment Required", [403] = "Forbidden", [404] = "Not Found", [405] = "Method Not Allowed", [406] = "Not Acceptable", [407] = "Proxy Authentication Required", [408] = "Request Timeout", [409] = "Conflict", [410] = "Gone", [411] = "Length Required", [412] = "Precondition Failed", [413] = "Payload Too Large", [414] = "Request-URI Too Long", [415] = "Unsupported Media Type", [416] = "Requested Range Not Satisfiable", [417] = "Expectation Failed", [418] = "I'm a teapot", [421] = "Misdirected Request", [422] = "Unprocessable Entity", [423] = "Locked", [424] = "Failed Dependency", [426] = "Upgrade Required", [428] = "Precondition Required", [429] = "Too Many Requests", [431] = "Request Header Fields Too Large", [451] = "Unavailable For Legal Reasons", [499] = "Client Closed Request", [500] = "Internal Server Error", [501] = "Not Implemented", [502] = "Bad Gateway", [503] = "Service Unavailable", [504] = "Gateway Timeout", [505] = "HTTP Version Not Supported", [506] = "Variant Also Negotiates", [507] = "Insufficient Storage", [508] = "Loop Detected", [510] = "Not Extended", [511] = "Network Authentication Required", [599] = "Network Connect Timeout Error", } local function parse_uri(str) local form = {} local start = string.find(str, "?", 1, true) if not start then return str, form end assert(start > 1) local uri = string.sub(str, 1, start - 1) local f = string.sub(str, start + 1) for k, v in string.gmatch(f, "(%w+)=(%w+)") do form[k] = v end return uri, form end local function httpd(fd, handler) socket.limit(fd, 1024 * 512) local readl = function() return readline(fd, "\r\n") end local readn = function(n) return read(fd, n) end local write = function (status, header, body) server.send(fd, status, header, body) end while true do local status, first, header, body = stream.recv_request(readl, readn) if not status then --disconnected return end if status ~= 200 then write(status, {}, "") socket.close(fd) return end --request line local method, uri, ver = first:match("(%w+)%s+(.-)%s+HTTP/([%d|.]+)\r\n") assert(method and uri and ver) header.method = method header.version = ver header.uri, header.form = parse_uri(uri) if tonumber(ver) > 1.1 then write(505, {}, "") socket.close(fd) return end if header["Content-Type"] == "application/x-www-form-urlencoded" then for k, v in string.gmatch(body, "(%w+)=(%w+)") do header.form[k] = v end body = "" end handler(header, body, write) end end function server.listen(port, handler) local h = function(fd) httpd(fd, handler) end listen(port, h) end function server.send(fd, status, header, body) table.insert(header, 1, string.format("HTTP/1.1 %d %s", status, http_err_msg[status])) table.insert(header, string.format("Content-Length: %d", #body)) local tmp = table.concat(header, "\r\n") tmp = tmp .. "\r\n\r\n" tmp = tmp .. body write(fd, tmp) end return server
bug fix incorrect http header pack
bug fix incorrect http header pack
Lua
mit
findstr/silly
2e2d8f0d65fd47456d01e39c17639672382d14fe
WildImps.lua
WildImps.lua
--[[-------------------------------------------------------------------- Copyright (C) 2016 Sidoine De Wispelaere See the file LICENSE.txt for copying permission. Use code from IcyDemonsIndicator --]]-------------------------------------------------------------------- local OVALE, Ovale = ... local OvaleWildImps = Ovale:NewModule("OvaleWildImps", "AceEvent-3.0") Ovale.OvaleWildImps = OvaleWildImps local OvaleState = nil local tinsert = table.insert local tremove = table.remove local demonData = { [55659] = { duration=12}, -- Wild imps from Hand of Gul'dan [98035] = { duration=12}, -- Dreadstalkers, which is a vehicle. Imps on dreadstalkers are 99737 [103673] = { duration=12}, -- Darkglare [11859] = { duration=25}, -- Doomguard [89] = { duration= 25 } -- Infernal } local self_demons = {} local self_serial = 1 local API_GetTime = GetTime --<public-static-methods> function OvaleWildImps:OnInitialize() -- Resolve module dependencies. OvaleState = Ovale.OvaleState end function OvaleWildImps:OnEnable() if Ovale.playerClass == "WARLOCK" and GetSpecialization() == 2 then self:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED") OvaleState:RegisterState(self, self.statePrototype) self_demons = {} end end function OvaleWildImps:OnDisable() if Ovale.playerClass == "WARLOCK" then OvaleState:UnregisterState(self) self:UnregisterEvent("COMBAT_LOG_EVENT_UNFILTERED") end end function OvaleWildImps:COMBAT_LOG_EVENT_UNFILTERED(event, timestamp, cleuEvent, hideCaster, sourceGUID, sourceName, sourceFlags, sourceRaidFlags, destGUID, destName, destFlags, destRaidFlags,...) -- Advance age of current totem state. self_serial = self_serial + 1 Ovale.refreshNeeded[Ovale.playerGUID] = true if sourceGUID ~= Ovale.playerGUID then return end if cleuEvent == "SPELL_SUMMON" then local _, _, _, _, _, _, _, creatureId = destGUID:find('(%S+)-(%d+)-(%d+)-(%d+)-(%d+)-(%d+)-(%S+)') creatureId = tonumber(creatureId) self:Print("summon %d", creatureId) local now = API_GetTime() for id, v in pairs(demonData) do if id == creatureId then self_demons[destGUID] = { id = creatureId, timestamp = now, finish = now + v.duration } break end end for k, d in pairs(self_demons) do if d.finish < now then self_demons[k] = nil end end elseif cleuEvent == 'SPELL_INSTAKILL' then if spellId == 196278 then -- implosion self_demons[destGUID] = nil end elseif cleuEvent == 'SPELL_CAST_SUCCESS' then local spellId = ... if spellId == 193396 then for k, d in pairs(self_demons) do d.de = true end end end end --</public-static-methods> --[[---------------------------------------------------------------------------- State machine for simulator. --]]---------------------------------------------------------------------------- --<public-static-properties> OvaleWildImps.statePrototype = {} --</public-static-properties> --<private-static-properties> local statePrototype = OvaleWildImps.statePrototype --</private-static-properties> statePrototype.GetNotDemonicEmpoweredDemonsCount = function(state, creatureId, atTime) local count = 0 for k, d in pairs(self_demons) do if d.finish >= atTime and d.id == creatureId and not d.de then count = count + 1 end end return count end statePrototype.GetDemonsCount = function(state, creatureId, atTime) local count = 0 for k, d in pairs(self_demons) do if d.finish >= atTime and d.id == creatureId then count = count + 1 end end return count end statePrototype.GetRemainingDemonDuration = function(state, creatureId, atTime) local max = 0 for k, d in pairs(self_demons) do if d.finish >= atTime and d.id == creatureId then local remaining = d.finish - atTime if remaining > max then max = remaining end end end return max end
--[[-------------------------------------------------------------------- Copyright (C) 2016 Sidoine De Wispelaere See the file LICENSE.txt for copying permission. Use code from IcyDemonsIndicator --]]-------------------------------------------------------------------- local OVALE, Ovale = ... local OvaleWildImps = Ovale:NewModule("OvaleWildImps", "AceEvent-3.0") Ovale.OvaleWildImps = OvaleWildImps local OvaleState = nil local tinsert = table.insert local tremove = table.remove local demonData = { [55659] = { duration=12}, -- Wild imps from Hand of Gul'dan [98035] = { duration=12}, -- Dreadstalkers, which is a vehicle. Imps on dreadstalkers are 99737 [103673] = { duration=12}, -- Darkglare [11859] = { duration=25}, -- Doomguard [89] = { duration= 25 } -- Infernal } local self_demons = {} local self_serial = 1 local API_GetTime = GetTime --<public-static-methods> function OvaleWildImps:OnInitialize() -- Resolve module dependencies. OvaleState = Ovale.OvaleState end function OvaleWildImps:OnEnable() if Ovale.playerClass == "WARLOCK" and GetSpecialization() == 2 then self:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED") OvaleState:RegisterState(self, self.statePrototype) self_demons = {} end end function OvaleWildImps:OnDisable() if Ovale.playerClass == "WARLOCK" then OvaleState:UnregisterState(self) self:UnregisterEvent("COMBAT_LOG_EVENT_UNFILTERED") end end function OvaleWildImps:COMBAT_LOG_EVENT_UNFILTERED(event, timestamp, cleuEvent, hideCaster, sourceGUID, sourceName, sourceFlags, sourceRaidFlags, destGUID, destName, destFlags, destRaidFlags,...) -- Advance age of current totem state. self_serial = self_serial + 1 Ovale.refreshNeeded[Ovale.playerGUID] = true if sourceGUID ~= Ovale.playerGUID then return end if cleuEvent == "SPELL_SUMMON" then local _, _, _, _, _, _, _, creatureId = destGUID:find('(%S+)-(%d+)-(%d+)-(%d+)-(%d+)-(%d+)-(%S+)') creatureId = tonumber(creatureId) local now = API_GetTime() for id, v in pairs(demonData) do if id == creatureId then self_demons[destGUID] = { id = creatureId, timestamp = now, finish = now + v.duration } break end end for k, d in pairs(self_demons) do if d.finish < now then self_demons[k] = nil end end elseif cleuEvent == 'SPELL_INSTAKILL' then if spellId == 196278 then -- implosion self_demons[destGUID] = nil end elseif cleuEvent == 'SPELL_CAST_SUCCESS' then local spellId = ... if spellId == 193396 then for k, d in pairs(self_demons) do d.de = true end end end end --</public-static-methods> --[[---------------------------------------------------------------------------- State machine for simulator. --]]---------------------------------------------------------------------------- --<public-static-properties> OvaleWildImps.statePrototype = {} --</public-static-properties> --<private-static-properties> local statePrototype = OvaleWildImps.statePrototype --</private-static-properties> statePrototype.GetNotDemonicEmpoweredDemonsCount = function(state, creatureId, atTime) local count = 0 for k, d in pairs(self_demons) do if d.finish >= atTime and d.id == creatureId and not d.de then count = count + 1 end end return count end statePrototype.GetDemonsCount = function(state, creatureId, atTime) local count = 0 for k, d in pairs(self_demons) do if d.finish >= atTime and d.id == creatureId then count = count + 1 end end return count end statePrototype.GetRemainingDemonDuration = function(state, creatureId, atTime) local max = 0 for k, d in pairs(self_demons) do if d.finish >= atTime and d.id == creatureId then local remaining = d.finish - atTime if remaining > max then max = remaining end end end return max end
Fixes #117: remove unwanted trace
Fixes #117: remove unwanted trace
Lua
mit
ultijlam/ovale,ultijlam/ovale,Xeltor/ovale,ultijlam/ovale
7e4d2aa7eacac70382b89ae718d22f8b4d851bb6
openLuupExtensions/L_openLuupExtensions.lua
openLuupExtensions/L_openLuupExtensions.lua
_NAME = "openLuup:Extensions" _VERSION = "2015.11.01" _DESCRIPTION = "openLuup:Extensions plugin for openLuup!!" _AUTHOR = "@akbooer" -- -- provide added functionality, including: -- * useful device variables -- * useful actions -- * etc., etc... -- local timers = require "openLuup.timers" local SID = { ole = "openLuup", -- no need for those incomprehensible UPnP serviceIds altui = "urn:upnp-org:serviceId:altui1", -- Variables = 'DisplayLine1' and 'DisplayLine2' } local function round (x, p) p = p or 1 x = x + p / 2 return x - x % p end -- init local function display (line1, line2) luup.variable_set (SID.altui, "DisplayLine1", line1 or '', lul_device) luup.variable_set (SID.altui, "DisplayLine2", line2 or '', lul_device) end local function ticker () local AppMemoryUsed = math.floor(collectgarbage "count") -- openLuup's memory usage in kB local now, cpu = timers.timenow(), timers.cpu_clock() local uptime = now - timers.loadtime + 1 local percent = round (100 * cpu / uptime, 0.1) local memory = round (AppMemoryUsed / 1000, 0.1) local days = round (uptime / 24 / 60 / 60, 0.01) local hours = round (cpu /60 /60, 0.01) luup.variable_set (SID.ole, "Memory_Mb", memory, lul_device) luup.variable_set (SID.ole, "CpuLoad_Percent", percent, lul_device) luup.variable_set (SID.ole, "CpuLoad_Hours", hours, lul_device) luup.variable_set (SID.ole, "Uptime_Days", days, lul_device) display ("Uptime " .. days .. " days", "Memory " .. memory .. " Mb") local sfmt = "openLuup PLUGIN memory: %0.1f Mb, uptime: %0.2f days, cpu: %0.2f hours (%0.1f%%)" local stats = sfmt: format (memory, days, hours, percent) luup.log (stats) end -- init local function synchronise () local days, data -- unused parameters local timer_type = 1 -- interval timer local recurring = true -- reschedule automatically timers.call_timer (ticker, timer_type, "2m", days, data, recurring) luup.log "synchronisation completed, system monitor started" end function init () local later = timers.timenow() + 120 -- two minutes in the future later = 120 - later % 120 -- adjust to on-the-hour timers.call_delay (synchronise, later) local msg = ("synchronising in %0.1f seconds"): format (later) display "Uptime 0" return nil, msg, _NAME end -----
_NAME = "openLuup:Extensions" _VERSION = "2015.11.02" _DESCRIPTION = "openLuup:Extensions plugin for openLuup!!" _AUTHOR = "@akbooer" -- -- provide added functionality, including: -- * useful device variables -- * useful actions -- * etc., etc... -- local timers = require "openLuup.timers" local SID = { ole = "openLuup", -- no need for those incomprehensible UPnP serviceIds altui = "urn:upnp-org:serviceId:altui1", -- Variables = 'DisplayLine1' and 'DisplayLine2' } local function round (x, p) p = p or 1 x = x + p / 2 return x - x % p end -- init local function display (line1, line2) luup.variable_set (SID.altui, "DisplayLine1", line1 or '', lul_device) luup.variable_set (SID.altui, "DisplayLine2", line2 or '', lul_device) end local function ticker () local AppMemoryUsed = math.floor(collectgarbage "count") -- openLuup's memory usage in kB local now, cpu = timers.timenow(), timers.cpu_clock() local uptime = now - timers.loadtime + 1 local percent = round (100 * cpu / uptime, 0.1) local memory = round (AppMemoryUsed / 1000, 0.1) local days = round (uptime / 24 / 60 / 60, 0.01) local hours = round (cpu /60 /60, 0.01) luup.variable_set (SID.ole, "Memory_Mb", memory, lul_device) luup.variable_set (SID.ole, "CpuLoad_Percent", percent, lul_device) luup.variable_set (SID.ole, "CpuLoad_Hours", hours, lul_device) luup.variable_set (SID.ole, "Uptime_Days", days, lul_device) display ( "Uptime " .. days .. " days", "Memory " .. memory .. " Mb, CPU " .. percent .. " %") local sfmt = "openLuup PLUGIN memory: %0.1f Mb, uptime: %0.2f days, cpu: %0.2f hours (%0.1f%%)" local stats = sfmt: format (memory, days, hours, percent) luup.log (stats) end -- init local function synchronise () local days, data -- unused parameters local timer_type = 1 -- interval timer local recurring = true -- reschedule automatically timers.call_timer (ticker, timer_type, "2m", days, data, recurring) luup.log "synchronisation completed, system monitor started" end function init () local later = timers.timenow() + 120 -- two minutes in the future later = 120 - later % 120 -- adjust to on-the-hour timers.call_delay (synchronise, later) local msg = ("synchronising in %0.1f seconds"): format (later) display "Uptime 0" return nil, msg, _NAME end -----
hot-fix-extensions-cpu-display
hot-fix-extensions-cpu-display - add CPU % to front panel display
Lua
apache-2.0
akbooer/openLuup
3116fc12e79b80bdf9844e3bb3c664deaca9d5ca
nyagos.d/catalog/subcomplete.lua
nyagos.d/catalog/subcomplete.lua
if not nyagos then print("This is a script for nyagos not lua.exe") os.exit() end share.maincmds = {} -- git local githelp=io.popen("git help -a 2>nul","r") if githelp then local gitcmds={} for line in githelp:lines() do if string.match(line,"^ %S") then for word in string.gmatch(line,"%S+") do gitcmds[ #gitcmds+1 ] = word end end end githelp:close() if #gitcmds > 1 then local maincmds = share.maincmds maincmds["git"] = gitcmds maincmds["git.exe"] = gitcmds share.maincmds = maincmds end end -- Subversion local svnhelp=io.popen("svn help 2>nul","r") if svnhelp then local svncmds={} for line in svnhelp:lines() do local m=string.match(line,"^ ([a-z]+)") if m then svncmds[ #svncmds+1 ] = m end end svnhelp:close() if #svncmds > 1 then local maincmds = share.maincmds maincmds["svn"] = svncmds maincmds["svn.exe"] = svncmds share.maincmds = maincmds end end -- Mercurial local hghelp=io.popen("hg debugcomplete 2>nul","r") if hghelp then local hgcmds={} for line in hghelp:lines() do for word in string.gmatch(line,"[a-z]+") do hgcmds[#hgcmds+1] = word end end hghelp:close() if #hgcmds > 1 then local maincmds=share.maincmds maincmds["hg"] = hgcmds maincmds["hg.exe"] = hgcmds share.maincmds = maincmds end end -- Rclone local rclonehelp=io.popen("rclone --help 2>nul","r") if rclonehelp then local rclonecmds={} local startflag = false for line in rclonehelp:lines() do if string.match(line,"Available Commands:") then startflag = true end if string.match(line,"Flags:") then break end if startflag then local m=string.match(line,"^%s+([a-z]+)") if m then rclonecmds[ #rclonecmds+1 ] = m end end end rclonehelp:close() if #rclonecmds > 1 then local maincmds=share.maincmds maincmds["rclone"] = rclonecmds maincmds["rclone.exe"] = rclonecmds share.maincmds = maincmds end end if next(share.maincmds) then nyagos.completion_hook = function(c) if c.pos <= 1 then return nil end local cmdname = string.match(c.text,"^%S+") if not cmdname then return nil end --[[ 2nd command completion like :git bisect go[od] user define-able local subcommands={"good", "bad"} local maincmds=share.maincmds maincmds["git bisect"] = subcommands share.maincmds = maincmds --]] local cmd2nd = string.match(c.text,"^%S+%s+%S+") if share.maincmds[cmd2nd] then cmdname = cmd2nd end local subcmds = {} local subcmdData = share.maincmds[cmdname] if not subcmdData then return nil end local subcmdType = type(subcmdData) if "table" == subcmdType then subcmds = subcmdData elseif "function" == subcmdType then subcmds = subcmdData() end for i=1,#subcmds do table.insert(c.list,subcmds[i]) end return c.list end end
if not nyagos then print("This is a script for nyagos not lua.exe") os.exit() end share.maincmds = {} -- git local githelp=io.popen("git help -a 2>nul","r") if githelp then local gitcmds={} for line in githelp:lines() do if string.match(line,"^ %S") then for word in string.gmatch(line,"%S+") do gitcmds[ #gitcmds+1 ] = word end end end githelp:close() if #gitcmds > 1 then local maincmds = share.maincmds maincmds["git"] = gitcmds maincmds["git.exe"] = gitcmds share.maincmds = maincmds end end -- Subversion local svnhelp=io.popen("svn help 2>nul","r") if svnhelp then local svncmds={} for line in svnhelp:lines() do local m=string.match(line,"^ ([a-z]+)") if m then svncmds[ #svncmds+1 ] = m end end svnhelp:close() if #svncmds > 1 then local maincmds = share.maincmds maincmds["svn"] = svncmds maincmds["svn.exe"] = svncmds share.maincmds = maincmds end end -- Mercurial local hghelp=io.popen("hg debugcomplete 2>nul","r") if hghelp then local hgcmds={} for line in hghelp:lines() do for word in string.gmatch(line,"[a-z]+") do hgcmds[#hgcmds+1] = word end end hghelp:close() if #hgcmds > 1 then local maincmds=share.maincmds maincmds["hg"] = hgcmds maincmds["hg.exe"] = hgcmds share.maincmds = maincmds end end -- Rclone local rclonehelp=io.popen("rclone --help 2>nul","r") if rclonehelp then local rclonecmds={} local startflag = false local flagsfound=false for line in rclonehelp:lines() do if not flagsfound then if string.match(line,"Available Commands:") then startflag = true end if string.match(line,"Flags:") then flagsfound = true end if startflag then local m=string.match(line,"^%s+([a-z]+)") if m then rclonecmds[ #rclonecmds+1 ] = m end end end end rclonehelp:close() if #rclonecmds > 1 then local maincmds=share.maincmds maincmds["rclone"] = rclonecmds maincmds["rclone.exe"] = rclonecmds share.maincmds = maincmds end end if next(share.maincmds) then nyagos.completion_hook = function(c) if c.pos <= 1 then return nil end local cmdname = string.match(c.text,"^%S+") if not cmdname then return nil end --[[ 2nd command completion like :git bisect go[od] user define-able local subcommands={"good", "bad"} local maincmds=share.maincmds maincmds["git bisect"] = subcommands share.maincmds = maincmds --]] local cmd2nd = string.match(c.text,"^%S+%s+%S+") if share.maincmds[cmd2nd] then cmdname = cmd2nd end local subcmds = {} local subcmdData = share.maincmds[cmdname] if not subcmdData then return nil end local subcmdType = type(subcmdData) if "table" == subcmdType then subcmds = subcmdData elseif "function" == subcmdType then subcmds = subcmdData() end for i=1,#subcmds do table.insert(c.list,subcmds[i]) end return c.list end end
Try to fix 317: rlcone subcomplete expand is locked
Try to fix 317: rlcone subcomplete expand is locked
Lua
bsd-3-clause
zetamatta/nyagos,tsuyoshicho/nyagos,nocd5/nyagos
a37e690c0723641766e4d3374d1794ffce4e4f36
src/db/mongo_on_luamongo.lua
src/db/mongo_on_luamongo.lua
-- -- in this version, we use luamongo as our low level -- module(..., package.seeall) local mongo = require "mongo" local function cursor_all(cursor) local results = {} for r in cursor:results() do table.insert(results, r) end return results end -- XXX: can this work? local addAttachMethod2Cursor = function (cursor) local cursor_mt = getmetatable(cursor) local up_mt = cursor_mt.__index -- add function all up_mt.all = cursor_all end local find = function (self, ns, query, fieldsToReturn, nToSkip, nToReturn, queryOptions, batchSize) assert(type(ns) == 'string') assert(type(query) == 'string') local cursor, err = self.conn:query(self.db..'.'..ns, query, nToReturn, nToSkip, fieldsToReturn, queryOptions, batchSize) if err then error(err) end addAttachMethod2Cursor(cursor) return cursor end local findOne = function (self, ns, query, fieldsToReturn, nToSkip) local cursor = find(self, ns, query, fieldsToReturn, nToSkip) local result = cursor:next() -- XXX: need to notice whether it is nil when none found return result end local insert = function (self, ns, doc) local ns = self.db..'.'..ns local ok, err = self.conn:insert(ns, doc) -- XXX: need disturb or continue?? if err then error(err) end return ok end local insert_batch = function (self, ns, docs) local ns = self.db..'.'..ns local ok, err = self.conn:insert_batch(ns, docs) -- XXX: need disturb or continue?? if err then error(err) end return ok end local update = function (self, ns, query, modifier, upsert, multi) local ns = self.db..'.'..ns local ok, err = self.conn:update(ns, query, modifier, upsert, multi) -- XXX: need disturb or continue?? if err then error(err) end return ok end local remove = function (self, ns, query, justOne) local ns = self.db..'.'..ns local ok, err = self.conn:remove(ns, query, justOne) -- XXX: need disturb or continue?? if err then error(err) end return ok end local count = function (self, ns, query) local ns = self.db..'.'..ns local count, err = self.conn:count(ns, query) -- XXX: need disturb or continue?? if err then error(err) end return count end -- useage: -- local mongo = require 'bamboo.db.mongo' -- local conn = mongo.connect(mongo_config) -- local db = conn:use('one_db_name') -- function _connect(config) assert(type(config) == 'table', 'missing config in mongo.connect') local host = config.host local port = config.port local dbname = config.db local conn_str = host..':'..port -- Create a Connection object local conn = mongo.Connection.New({auto_reconnect = true}) assert( conn ~= nil, 'unable to create mongo.Connection' ) assert( conn:connect(conn_str), 'unable to forcefully connect to mongo instance' ) if config.user then assert( conn:auth { dbname = 'admin', username = config.user, password = config.password } == true, "unable to auth to db" ) end return conn end function _connect_replica_set(config) assert(type(config) == 'table', 'missing config in mongo.connect') local host = config.host local port = config.port local dbname = config.db -- ensure replicaset is a host:port array local replicaset = config.replicaset -- Create a Connection object local conn = mongo.ReplicaSet.New(dbname, replicaset) assert( conn ~= nil, 'unable to create mongo.ReplicaSetConnection' ) assert( conn:connect(), 'unable to forcefully connect to mongo instance' ) if config.user then assert( conn:auth { dbname = 'admin', username = config.user, password = config.password } == true, "unable to auth to db" ) end return conn end -- mongodb methods metatable local _mt_db = { find = find, findOne = findOne, insert = insert, insert_batch = insert_batch, update = update, remove = remove, count = count } function connect (config) assert(type(config) == 'table', 'missing config in mongo.connect') local config.host = config.host or '127.0.0.1' local config.port = config.port or '27017' local config.db = config.db or 'test' local replicaset = config.replicaset local db = {} -- attach all methods to db setmetatable(db, { __index = _mt_db }) local conn if replicaset == true then conn = _connect_replica_set(config) else conn = _connect(config) end table.update(db, config) -- add db instance to db db.conn = conn return db end
-- -- in this version, we use luamongo as our low level -- module(..., package.seeall) local mongo = require "mongo" local function cursor_all(cursor) local results = {} for r in cursor:results() do table.insert(results, r) end return results end -- XXX: can this work? local addAttachMethod2Cursor = function (cursor) local cursor_mt = getmetatable(cursor) local up_mt = cursor_mt.__index -- add function all up_mt.all = cursor_all end local find = function (self, ns, query, fieldsToReturn, nToSkip, nToReturn, queryOptions, batchSize) assert(type(ns) == 'string') local cursor, err = self.conn:query(self.db..'.'..ns, query, nToReturn, nToSkip, fieldsToReturn, queryOptions, batchSize) if err then print(err) end addAttachMethod2Cursor(cursor) return cursor end local findOne = function (self, ns, query, fieldsToReturn, nToSkip) local cursor = find(self, ns, query, fieldsToReturn, nToSkip) local result = cursor:next() -- XXX: need to notice whether it is nil when none found return result end local insert = function (self, ns, doc) local ns = self.db..'.'..ns local ok, err = self.conn:insert(ns, doc) -- XXX: need disturb or continue?? if err then print(err) end return ok end local insert_batch = function (self, ns, docs) local ns = self.db..'.'..ns local ok, err = self.conn:insert_batch(ns, docs) -- XXX: need disturb or continue?? if err then print(err) end return ok end local update = function (self, ns, query, modifier, upsert, multi) local ns = self.db..'.'..ns local ok, err = self.conn:update(ns, query, modifier, upsert, multi) -- XXX: need disturb or continue?? if err then print(err) end return ok end local remove = function (self, ns, query, justOne) local ns = self.db..'.'..ns local ok, err = self.conn:remove(ns, query, justOne) -- XXX: need disturb or continue?? if err then print(err) end return ok end local count = function (self, ns, query) local ns = self.db..'.'..ns local count, err = self.conn:count(ns, query) -- XXX: need disturb or continue?? if err then print(err) end return count end -- useage: -- local mongo = require 'bamboo.db.mongo' -- local conn = mongo.connect(mongo_config) -- local db = conn:use('one_db_name') -- function _connect(config) assert(type(config) == 'table', 'missing config in mongo.connect') local host = config.host local port = config.port local dbname = config.db local conn_str = host..':'..port -- Create a Connection object local conn = mongo.Connection.New({auto_reconnect = true}) assert( conn ~= nil, 'unable to create mongo.Connection' ) assert( conn:connect(conn_str), 'unable to forcefully connect to mongo instance' ) if config.user then assert( conn:auth { dbname = 'admin', username = config.user, password = config.password } == true, "unable to auth to db" ) end return conn end function _connect_replica_set(config) assert(type(config) == 'table', 'missing config in mongo.connect') local dbname = config.db -- ensure replicaset is a host:port array local replicaset = config.replicaset -- Create a Connection object local conn = mongo.ReplicaSet.New(dbname, replicaset) assert( conn ~= nil, 'unable to create mongo.ReplicaSetConnection' ) assert( conn:connect(), 'unable to forcefully connect to mongo instance' ) print(conn, type(conn)) print(config.user) print(config.password) if config.user then assert( conn:auth { dbname = 'admin', username = config.user, password = config.password } == true, "unable to auth to db" ) end return conn end -- mongodb methods metatable local _mt_db = { find = find, findOne = findOne, insert = insert, insert_batch = insert_batch, update = update, remove = remove, count = count } function connect (config) assert(type(config) == 'table', 'missing config in mongo.connect') config.host = config.host or '127.0.0.1' config.port = config.port or '27017' config.db = config.db or 'test' local replicaset = config.replicaset local db = {} -- attach all methods to db setmetatable(db, { __index = _mt_db }) local conn if replicaset then conn = _connect_replica_set(config) else conn = _connect(config) end for k, v in pairs(config) do db[k] = v end -- add db instance to db db.conn = conn return db end
minimal fixes.
minimal fixes. Signed-off-by: Daogang Tang <6435653d2db08e7863743a16df53ecbb301fb4b0@126.com>
Lua
bsd-3-clause
daogangtang/bamboo,daogangtang/bamboo
70a2849e395864526ab4ac5e359ac87157ac59f2
lib/minibatch_adam.lua
lib/minibatch_adam.lua
require 'optim' require 'cutorch' require 'xlua' local function minibatch_adam(model, criterion, eval_metric, train_x, train_y, config) local parameters, gradParameters = model:getParameters() config = config or {} local sum_loss = 0 local sum_eval = 0 local count_loss = 0 local batch_size = config.xBatchSize or 32 local shuffle = torch.randperm(train_x:size(1)) local c = 1 local inputs_tmp = torch.Tensor(batch_size, train_x:size(2), train_x:size(3), train_x:size(4)):zero() local targets_tmp = torch.Tensor(batch_size, train_y:size(2)):zero() local inputs = inputs_tmp:clone():cuda() local targets = targets_tmp:clone():cuda() print("## update") for t = 1, train_x:size(1), batch_size do if t + batch_size -1 > train_x:size(1) then break end for i = 1, batch_size do inputs_tmp[i]:copy(train_x[shuffle[t + i - 1]]) targets_tmp[i]:copy(train_y[shuffle[t + i - 1]]) end inputs:copy(inputs_tmp) targets:copy(targets_tmp) local feval = function(x) if x ~= parameters then parameters:copy(x) end gradParameters:zero() local output = model:forward(inputs) local f = criterion:forward(output, targets) sum_eval = sum_eval + eval_metric:forward(output, targets) sum_loss = sum_loss + f count_loss = count_loss + 1 model:backward(inputs, criterion:backward(output, targets)) return f, gradParameters end optim.adam(feval, parameters, config) c = c + 1 if c % 50 == 0 then collectgarbage() xlua.progress(t, train_x:size(1)) end end xlua.progress(train_x:size(1), train_x:size(1)) return { loss = sum_loss / count_loss, MSE = sum_eval / count_loss, PSNR = 10 * math.log10(1 / (sum_eval / count_loss))} end return minibatch_adam
require 'optim' require 'cutorch' require 'xlua' local function minibatch_adam(model, criterion, eval_metric, train_x, train_y, config) local parameters, gradParameters = model:getParameters() config = config or {} local sum_loss = 0 local sum_eval = 0 local count_loss = 0 local batch_size = config.xBatchSize or 32 local shuffle = torch.randperm(train_x:size(1)) local c = 1 local inputs_tmp = torch.Tensor(batch_size, train_x:size(2), train_x:size(3), train_x:size(4)):zero() local targets_tmp = torch.Tensor(batch_size, train_y:size(2)):zero() local inputs = inputs_tmp:clone():cuda() local targets = targets_tmp:clone():cuda() local instance_loss = torch.Tensor(train_x:size(1)):zero() print("## update") for t = 1, train_x:size(1), batch_size do if t + batch_size -1 > train_x:size(1) then break end for i = 1, batch_size do inputs_tmp[i]:copy(train_x[shuffle[t + i - 1]]) targets_tmp[i]:copy(train_y[shuffle[t + i - 1]]) end inputs:copy(inputs_tmp) targets:copy(targets_tmp) local feval = function(x) if x ~= parameters then parameters:copy(x) end gradParameters:zero() local output = model:forward(inputs) local f = criterion:forward(output, targets) local se = 0 for i = 1, batch_size do local el = eval_metric:forward(output[i], targets[i]) se = se + el instance_loss[shuffle[t + i - 1]] = el end sum_eval = sum_eval + (se / batch_size) sum_loss = sum_loss + f count_loss = count_loss + 1 model:backward(inputs, criterion:backward(output, targets)) return f, gradParameters end optim.adam(feval, parameters, config) c = c + 1 if c % 50 == 0 then collectgarbage() xlua.progress(t, train_x:size(1)) end end xlua.progress(train_x:size(1), train_x:size(1)) return { loss = sum_loss / count_loss, MSE = sum_eval / count_loss, PSNR = 10 * math.log10(1 / (sum_eval / count_loss))}, instance_loss end return minibatch_adam
Fix missing file
Fix missing file
Lua
mit
Spitfire1900/upscaler,nagadomi/waifu2x,Spitfire1900/upscaler,zyhkz/waifu2x,nagadomi/waifu2x,zyhkz/waifu2x,nagadomi/waifu2x,nagadomi/waifu2x,zyhkz/waifu2x,nagadomi/waifu2x,zyhkz/waifu2x
dc532363b9008679c6d9a4de328e6cf53cf2c405
busted/outputHandlers/TAP.lua
busted/outputHandlers/TAP.lua
local pretty = require 'pl.pretty' return function(options, busted) local handler = require 'busted.outputHandlers.base'(busted) handler.suiteEnd = function() local total = handler.successesCount + handler.errorsCount + handler.failuresCount print('1..' .. total) local success = 'ok %u - %s' local failure = 'not ' .. success local counter = 0 for i,t in pairs(handler.successes) do counter = counter + 1 print( success:format( counter, t.name )) end for i,t in pairs(handler.failures) do counter = counter + 1 local message = t.message if message == nil then message = 'Nil error' elseif type(message) ~= 'string' then message = pretty.write(message) end print( failure:format( counter, t.name )) print('# ' .. t.element.trace.short_src .. ' @ ' .. t.element.trace.currentline) print('# Failure message: ' .. message:gsub('\n', '\n# ' )) end return nil, true end busted.subscribe({ 'suite', 'end' }, handler.suiteEnd) return handler end
local pretty = require 'pl.pretty' return function(options, busted) local handler = require 'busted.outputHandlers.base'(busted) handler.suiteEnd = function() local total = handler.successesCount + handler.errorsCount + handler.failuresCount print('1..' .. total) local success = 'ok %u - %s' local failure = 'not ' .. success local counter = 0 for i,t in pairs(handler.successes) do counter = counter + 1 print( success:format( counter, t.name )) end showFailure = function(t) counter = counter + 1 local message = t.message if message == nil then message = 'Nil error' elseif type(message) ~= 'string' then message = pretty.write(message) end print( failure:format( counter, t.name )) print('# ' .. t.element.trace.short_src .. ' @ ' .. t.element.trace.currentline) print('# Failure message: ' .. message:gsub('\n', '\n# ' )) end for i,t in pairs(handler.errors) do showFailure(t) end for i,t in pairs(handler.failures) do showFailure(t) end return nil, true end busted.subscribe({ 'suite', 'end' }, handler.suiteEnd) return handler end
Fix TAP output to show errors
Fix TAP output to show errors TAP output was only showing success and failure results, but not errors. So update TAP output to show errors as "not ok", just like failures.
Lua
mit
sobrinho/busted,xyliuke/busted,mpeterv/busted,leafo/busted,istr/busted,o-lim/busted,ryanplusplus/busted,Olivine-Labs/busted,DorianGray/busted,nehz/busted
45c19f954b88018b98ea2ca2b821ca296425b20a
scripts/AllRecordsUpload.lua
scripts/AllRecordsUpload.lua
---- -- Upload All MP3 file to CDR Server without domain ---- api = freeswitch.API(); p = io.popen('find /recordings/ -maxdepth 1 -type f') cdr_url = freeswitch.getGlobalVariable("cdr_url"); pattern = "%x%x%x%x%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%x%x%x%x%x%x%x%x" function shell(c) local o, h h = assert(io.popen(c,"r")) o = h:read("*all") h:close() return o end function file_exists(name) local f=io.open(name,"r") if f~=nil then io.close(f) return true else return false end end for file in p:lines() do if (file_exists(file) ) then r = api:executeString("http_put "..cdr_url.."/sys/formLoadFile?id="..file:match(pattern).."&type=mp3 "..file); freeswitch.consoleLog("debug", "[AllRecordsUpload.lua]: "..r); if (r:gsub("%s*$", "") == '+OK') then del = "/bin/rm -rf "..file; freeswitch.consoleLog("debug", "[AllRecordsUpload.lua]: "..del.."\n"); shell(del); end end end
---- -- Upload All MP3 file to CDR Server without domain ---- api = freeswitch.API(); p = io.popen('find /recordings/ -maxdepth 1 -regextype sed -regex ".*/[a-f0-9\\-]\\{36\\}.*"') cdr_url = freeswitch.getGlobalVariable("cdr_url"); pattern = "%x%x%x%x%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%-%x%x%x%x%x%x%x%x%x%x%x%x" function shell(c) local o, h h = assert(io.popen(c,"r")) o = h:read("*all") h:close() return o end function file_exists(name) local f=io.open(name,"r") if f~=nil then io.close(f) return true else return false end end for file in p:lines() do if (file_exists(file) ) then r = api:executeString("http_put "..cdr_url.."/sys/formLoadFile?id="..file:match(pattern).."&type=mp3 "..file); freeswitch.consoleLog("debug", "[AllRecordsUpload.lua]: "..r); if (r:gsub("%s*$", "") == '+OK') then del = "/bin/rm -rf "..file; freeswitch.consoleLog("debug", "[AllRecordsUpload.lua]: "..del.."\n"); shell(del); end end end
WTEL-295 - fixed find command;
WTEL-295 - fixed find command;
Lua
mit
webitel/docker-freeswitch
f0e9cf070ea8076d3447b1fb2021ece78fcca061
modules/corelib/ui/uiscrollarea.lua
modules/corelib/ui/uiscrollarea.lua
-- @docclass UIScrollArea = extends(UIWidget) -- public functions function UIScrollArea.create() local scrollarea = UIScrollArea.internalCreate() scrollarea:setClipping(true) scrollarea.inverted = false scrollarea.alwaysScrollMaximum = false return scrollarea end function UIScrollArea:onStyleApply(styleName, styleNode) for name,value in pairs(styleNode) do if name == 'vertical-scrollbar' then addEvent(function() self:setVerticalScrollBar(self:getParent():getChildById(value)) end) elseif name == 'horizontal-scrollbar' then addEvent(function() self:setHorizontalScrollBar(self:getParent():getChildById(value)) end) elseif name == 'inverted-scroll' then self:setInverted(value) elseif name == 'always-scroll-maximum' then self:setAlwaysScrollMaximum(value) end end end function UIScrollArea:updateScrollBars() local scrollWidth = math.max(self:getChildrenRect().width - self:getPaddingRect().width, 0) local scrollHeight = math.max(self:getChildrenRect().height - self:getPaddingRect().height, 0) local scrollbar = self.verticalScrollBar if scrollbar then if self.inverted then scrollbar:setMinimum(-scrollHeight) scrollbar:setMaximum(0) else scrollbar:setMinimum(0) scrollbar:setMaximum(scrollHeight) end end local scrollbar = self.horizontalScrollBar if scrollbar then if self.inverted then scrollbar:setMinimum(-scrollWidth) scrollbar:setMaximum(0) else scrollbar:setMinimum(0) scrollbar:setMaximum(scrollWidth) end end if self.lastScrollWidth ~= scrollWidth then self:onScrollWidthChange() end if self.lastScrollHeight ~= scrollHeight then self:onScrollHeightChange() end self.lastScrollWidth = scrollWidth self.lastScrollHeight = scrollHeight end function UIScrollArea:setVerticalScrollBar(scrollbar) self.verticalScrollBar = scrollbar self.verticalScrollBar.onValueChange = function(scrollbar, value) local virtualOffset = self:getVirtualOffset() virtualOffset.y = value self:setVirtualOffset(virtualOffset) self:onScrollbarChange(value) -- Maybe there is a better way to do this? end self:updateScrollBars() end function UIScrollArea:setHorizontalScrollBar(scrollbar) self.horizontalScrollBar = scrollbar self.horizontalScrollBar.onValueChange = function(scrollbar, value) local virtualOffset = self:getVirtualOffset() virtualOffset.x = value self:setVirtualOffset(virtualOffset) self:onScrollbarChange(value) -- Maybe there is a better way to do this? end self:updateScrollBars() end function UIScrollArea:setInverted(inverted) self.inverted = inverted end function UIScrollArea:setAlwaysScrollMaximum(value) self.alwaysScrollMaximum = value end function UIScrollArea:onLayoutUpdate() self:updateScrollBars() end function UIScrollArea:onMouseWheel(mousePos, mouseWheel) if self.verticalScrollBar then if mouseWheel == MouseWheelUp then self.verticalScrollBar:decrement() else self.verticalScrollBar:increment() end elseif self.horizontalScrollBar then if mouseWheel == MouseWheelUp then self.horizontalScrollBar:increment() else self.horizontalScrollBar:decrement() end end return true end function UIScrollArea:onChildFocusChange(focusedChild, oldFocused, reason) if focusedChild and (reason == MouseFocusReason or reason == KeyboardFocusReason) then local paddingRect = self:getPaddingRect() if self.verticalScrollBar then local deltaY = paddingRect.y - focusedChild:getY() if deltaY > 0 then self.verticalScrollBar:decrement(deltaY) end deltaY = (focusedChild:getY() + focusedChild:getHeight()) - (paddingRect.y + paddingRect.height) if deltaY > 0 then self.verticalScrollBar:increment(deltaY) end else local deltaX = paddingRect.x - focusedChild:getX() if deltaX > 0 then self.horizontalScrollBar:decrement(deltaX) end deltaX = (focusedChild:getX() + focusedChild:getWidth()) - (paddingRect.x + paddingRect.width) if deltaX > 0 then self.horizontalScrollBar:increment(deltaX) end end end end function UIScrollArea:onScrollWidthChange() if self.alwaysScrollMaximum and self.horizontalScrollBar then self.horizontalScrollBar:setValue(self.horizontalScrollBar:getMaximum()) end end function UIScrollArea:onScrollHeightChange() if self.alwaysScrollMaximum and self.verticalScrollBar then self.verticalScrollBar:setValue(self.verticalScrollBar:getMaximum()) end end
-- @docclass UIScrollArea = extends(UIWidget) -- public functions function UIScrollArea.create() local scrollarea = UIScrollArea.internalCreate() scrollarea:setClipping(true) scrollarea.inverted = false scrollarea.alwaysScrollMaximum = false return scrollarea end function UIScrollArea:onStyleApply(styleName, styleNode) for name,value in pairs(styleNode) do if name == 'vertical-scrollbar' then addEvent(function() self:setVerticalScrollBar(self:getParent():getChildById(value)) end) elseif name == 'horizontal-scrollbar' then addEvent(function() self:setHorizontalScrollBar(self:getParent():getChildById(value)) end) elseif name == 'inverted-scroll' then self:setInverted(value) elseif name == 'always-scroll-maximum' then self:setAlwaysScrollMaximum(value) end end end function UIScrollArea:updateScrollBars() local scrollWidth = math.max(self:getChildrenRect().width - self:getPaddingRect().width, 0) local scrollHeight = math.max(self:getChildrenRect().height - self:getPaddingRect().height, 0) local scrollbar = self.verticalScrollBar if scrollbar then if self.inverted then scrollbar:setMinimum(-scrollHeight) scrollbar:setMaximum(0) else scrollbar:setMinimum(0) scrollbar:setMaximum(scrollHeight) end end local scrollbar = self.horizontalScrollBar if scrollbar then if self.inverted then scrollbar:setMinimum(-scrollWidth) scrollbar:setMaximum(0) else scrollbar:setMinimum(0) scrollbar:setMaximum(scrollWidth) end end if self.lastScrollWidth ~= scrollWidth then self:onScrollWidthChange() end if self.lastScrollHeight ~= scrollHeight then self:onScrollHeightChange() end self.lastScrollWidth = scrollWidth self.lastScrollHeight = scrollHeight end function UIScrollArea:setVerticalScrollBar(scrollbar) self.verticalScrollBar = scrollbar self.verticalScrollBar.onValueChange = function(scrollbar, value) local virtualOffset = self:getVirtualOffset() virtualOffset.y = value self:setVirtualOffset(virtualOffset) if self.onScrollbarChange then self:onScrollbarChange(value) end end self:updateScrollBars() end function UIScrollArea:setHorizontalScrollBar(scrollbar) self.horizontalScrollBar = scrollbar self.horizontalScrollBar.onValueChange = function(scrollbar, value) local virtualOffset = self:getVirtualOffset() virtualOffset.x = value self:setVirtualOffset(virtualOffset) if self.onScrollbarChange then self:onScrollbarChange(value) end end self:updateScrollBars() end function UIScrollArea:setInverted(inverted) self.inverted = inverted end function UIScrollArea:setAlwaysScrollMaximum(value) self.alwaysScrollMaximum = value end function UIScrollArea:onLayoutUpdate() self:updateScrollBars() end function UIScrollArea:onMouseWheel(mousePos, mouseWheel) if self.verticalScrollBar then if mouseWheel == MouseWheelUp then self.verticalScrollBar:decrement() else self.verticalScrollBar:increment() end elseif self.horizontalScrollBar then if mouseWheel == MouseWheelUp then self.horizontalScrollBar:increment() else self.horizontalScrollBar:decrement() end end return true end function UIScrollArea:onChildFocusChange(focusedChild, oldFocused, reason) if focusedChild and (reason == MouseFocusReason or reason == KeyboardFocusReason) then local paddingRect = self:getPaddingRect() if self.verticalScrollBar then local deltaY = paddingRect.y - focusedChild:getY() if deltaY > 0 then self.verticalScrollBar:decrement(deltaY) end deltaY = (focusedChild:getY() + focusedChild:getHeight()) - (paddingRect.y + paddingRect.height) if deltaY > 0 then self.verticalScrollBar:increment(deltaY) end else local deltaX = paddingRect.x - focusedChild:getX() if deltaX > 0 then self.horizontalScrollBar:decrement(deltaX) end deltaX = (focusedChild:getX() + focusedChild:getWidth()) - (paddingRect.x + paddingRect.width) if deltaX > 0 then self.horizontalScrollBar:increment(deltaX) end end end end function UIScrollArea:onScrollWidthChange() if self.alwaysScrollMaximum and self.horizontalScrollBar then self.horizontalScrollBar:setValue(self.horizontalScrollBar:getMaximum()) end end function UIScrollArea:onScrollHeightChange() if self.alwaysScrollMaximum and self.verticalScrollBar then self.verticalScrollBar:setValue(self.verticalScrollBar:getMaximum()) end end
Important fix to uiscrollarea
Important fix to uiscrollarea I messed up the code and forgot to commit this. ->Check if function is set before calling it here.
Lua
mit
dreamsxin/otclient,Radseq/otclient,EvilHero90/otclient,gpedro/otclient,Radseq/otclient,EvilHero90/otclient,dreamsxin/otclient,gpedro/otclient,gpedro/otclient,dreamsxin/otclient,kwketh/otclient,Cavitt/otclient_mapgen,Cavitt/otclient_mapgen,kwketh/otclient
cdefc768b2fbae5a29a561e4445a1773a321852e
lib/switchboard_modules/lua_script_debugger/premade_scripts/ain_config/ain_config.lua
lib/switchboard_modules/lua_script_debugger/premade_scripts/ain_config/ain_config.lua
-- This is an example showing how to configure analog input settings on -- on T-Series devices. print("Configure & Read Analog Input") ainChannels = {0,1} -- Read AIN0 and AIN1 ainRange = 10 -- +/-10V ainResolution = 1 -- Fastest ainSettling = 0 -- Default -- This function can be used to configure general analog input settings such as -- Range, Resolution, and Settling. More information about these settings can -- be found on the LabJack website under the AIN section: -- https://labjack.com/support/datasheets/t-series/ain function ainChConfig(ainChNum, range, resolution, settling, isDifferential) MB.W(40000 + ainChNum * 2, 3, range) -- Set AIN Range MB.W(41500 + ainChNum * 1, 0, resolution) -- Set Resolution Index MB.W(42000 + ainChNum * 2, 3, settling) -- Set Settling US dt = MB.R(60000, 3) -- Read device type if isDifferential and (ainChNum%2 == 0) and (dt == 7) then -- The negative channels setting is only valid for even -- analog input channels and is not valid for the T4. if (ainChNum < 14) then -- The negative channel is 1+ the channel for AIN0-13 on the T7 MB.W(41000 + ainChNum, 0, ainChNum + 1) elseif (ainChNum > 47) then -- The negative channel is 8+ the channel for AIN48-127 on the T7 -- when using a Mux80. -- https://labjack.com/support/datasheets/accessories/mux80 MB.W(41000 + ainChNum, 0, ainChNum + 8) else print(string.format("Can not set negative channel for AIN%d",ainChNum)) end end end -- Configure each analog input for i=1,table.getn(ainChannels) do ainChConfig(ainChannels[i], ainRange, ainResolution, ainSettling) end LJ.IntervalConfig(0, 500) -- Configure interval local checkInterval=LJ.CheckInterval while true do if checkInterval(0) then -- interval finished -- Read & Print out each read AIN channel for i=1, table.getn(ainChannels) do ainVal = MB.R(ainChannels[i] * 2, 3) print(string.format("AIN%d: %.3f", ainChannels[i], ainVal)) end end end
--[[ Name: ain_config.lua Desc: This is an example showing how to configure analog input settings on T-Series devices. --]] -- Assign functions locally for faster processing local modbus_read = MB.R local modbus_write = MB.W local interval_config = LJ.IntervalConfig local check_interval = LJ.CheckInterval ------------------------------------------------------------------------------- -- Desc: This function can be used to configure general analog input settings -- such as range, resolution, and settling. More information about -- these settings can be found on the LabJack website under the AIN -- section: -- https://labjack.com/support/datasheets/t-series/ain ------------------------------------------------------------------------------- function ain_channel_config(ainchannel, range, resolution, settling, isdifferential) -- Set AIN range modbus_write(40000 + ainchannel * 2, 3, range) -- Set resolution index modbus_write(41500 + ainchannel * 1, 0, resolution) -- Set settling time modbus_write(42000 + ainchannel * 2, 3, settling) -- Read the device type devicetype = modbus_read(60000, 3) -- Setup the negative channel if using a differential input if isdifferential and (ainchannel%2 == 0) and (devicetype == 7) then -- The negative channels setting is only valid for even -- analog input channels and is not valid for the T4. if (ainchannel < 14) then -- The negative channel is 1+ the channel for AIN0-13 on the T7 modbus_write(41000 + ainchannel, 0, ainchannel + 1) elseif (ainchannel > 47) then -- The negative channel is 8+ the channel for AIN48-127 on the T7 -- when using a Mux80. -- https://labjack.com/support/datasheets/accessories/mux80 modbus_write(41000 + ainchannel, 0, ainchannel + 8) else print(string.format("Can not set negative channel for AIN%d",ainchannel)) end end end print("Configure & Read Analog Input") -- Use AIN0 and AIN1 for our analog inputs ainchannels = {0,1} -- Use +/-10V for analog input range ainrange = 10 -- Resolution of 1 is the fastest setting ainresolution = 1 -- Use the default settling time ainsettling = 0 -- Configure each analog input for i=1,table.getn(ainchannels) do ain_channel_config(ainchannels[i], ainrange, ainresolution, ainsettling) end interval_config(0, 500) -- Configure interval while true do -- The interval is finished if check_interval(0) then -- Read & Print out each read AIN channel for i=1, table.getn(ainchannels) do ainval = modbus_read(ainchannels[i] * 2, 3) print(string.format("AIN%d: %.3f", ainchannels[i], ainval)) end end end
Fixed up the ain config example formatting
Fixed up the ain config example formatting
Lua
mit
chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager
4617b91983792f3282757b93134f0b7e8f287d52
src/lua-factory/sources/grl-radiofrance.lua
src/lua-factory/sources/grl-radiofrance.lua
--[[ * Copyright (C) 2014 Bastien Nocera * * Contact: Bastien Nocera <hadess@hadess.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; 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 * --]] local stations = { 'franceinter', 'franceinfo', 'franceculture', 'francemusique', 'fipradio', 'lemouv' } --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-radiofrance-lua", name = "Radio France", description = "A source for browsing Radio France radio stations", supported_keys = { "id", "thumbnail", "title", "url", "mime-type" }, icon = 'resource:///org/gnome/grilo/plugins/radiofrance/radiofrance.png', supported_media = 'audio', tags = { 'radio', 'country:fr', 'net:internet', 'net:plaintext' } } ------------------ -- Source utils -- ------------------ function grl_source_browse(media_id) if grl.get_options("skip") > 0 then grl.callback() else local urls = {} for index, item in pairs(stations) do local url = 'http://www.' .. item .. '.fr/player' table.insert(urls, url) end grl.fetch(urls, radiofrance_now_fetch_cb) end end ------------------------ -- Callback functions -- ------------------------ -- return all the media found function radiofrance_now_fetch_cb(results) for index, result in pairs(results) do local media = create_media(stations[index], result) grl.callback(media, -1) end grl.callback() end ------------- -- Helpers -- ------------- function get_thumbnail(id) local images = {} images['franceinter'] = 'http://www.franceinter.fr/sites/all/themes/franceinter/logo.png' images['franceinfo'] = 'http://www.franceinfo.fr/sites/all/themes/custom/france_info/logo.png' images['franceculture'] = 'http://www.franceculture.fr/sites/all/themes/franceculture/images/logo.png' images['francemusique'] = 'http://www.francemusique.fr/sites/all/themes/custom/france_musique/logo.png' images['fipradio'] = 'http://www.fipradio.fr/sites/all/themes/custom/fip/logo.png' images['lemouv'] = 'http://www.lemouv.fr/sites/all/themes/mouv/images/logo_119x119.png' return images[id] end function get_title(id) local names = {} names['franceinter'] = 'France Inter' names['franceinfo'] = 'France Info' names['franceculture'] = 'France Culture' names['francemusique'] = 'France Musique' names['fipradio'] = 'Fip Radio' names['lemouv'] = "Le Mouv'" return names[id] end function create_media(id, result) local media = {} media.type = "audio" media.mime_type = "audio/mpeg" media.id = id if media.id == 'fipradio' then media.id = 'fip' end media.url = result:match("liveUrl: '(.-)',") if not media.url then media.url = result:match('"player" href="(http.-%.mp3)') end media.title = get_title(id) media.thumbnail = get_thumbnail(id) -- FIXME Add metadata about the currently playing tracks -- Available in 'http://www.' .. item .. '.fr/api/now&full=true' return media end
--[[ * Copyright (C) 2014 Bastien Nocera * * Contact: Bastien Nocera <hadess@hadess.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; 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 * --]] local stations = { 'franceinter', 'franceinfo', 'franceculture', 'francemusique', 'fipradio', 'lemouv' } --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-radiofrance-lua", name = "Radio France", description = "A source for browsing Radio France radio stations", supported_keys = { "id", "thumbnail", "title", "url", "mime-type" }, icon = 'resource:///org/gnome/grilo/plugins/radiofrance/radiofrance.png', supported_media = 'audio', tags = { 'radio', 'country:fr', 'net:internet', 'net:plaintext' } } ------------------ -- Source utils -- ------------------ function grl_source_browse(media_id) if grl.get_options("skip") > 0 then grl.callback() else local urls = {} for index, item in pairs(stations) do local url = 'http://www.' .. item .. '.fr/player' table.insert(urls, url) end grl.fetch(urls, radiofrance_now_fetch_cb) end end ------------------------ -- Callback functions -- ------------------------ -- return all the media found function radiofrance_now_fetch_cb(results) for index, result in pairs(results) do local media = create_media(stations[index], result) grl.callback(media, -1) end grl.callback() end ------------- -- Helpers -- ------------- function get_thumbnail(id) local images = {} images['franceinter'] = 'http://www.franceinter.fr/sites/all/themes/franceinter/logo.png' images['franceinfo'] = 'http://www.franceinfo.fr/sites/all/themes/custom/france_info/logo.png' images['franceculture'] = 'http://www.franceculture.fr/sites/all/themes/franceculture/images/logo.png' images['francemusique'] = 'http://www.francemusique.fr/sites/all/themes/custom/france_musique/logo.png' images['fipradio'] = 'http://www.fipradio.fr/sites/all/themes/custom/fip/logo.png' images['lemouv'] = 'http://www.lemouv.fr/sites/all/themes/mouv/images/logo_119x119.png' return images[id] end function get_title(id) local names = {} names['franceinter'] = 'France Inter' names['franceinfo'] = 'France Info' names['franceculture'] = 'France Culture' names['francemusique'] = 'France Musique' names['fipradio'] = 'Fip Radio' names['lemouv'] = "Le Mouv'" return names[id] end function create_media(id, result) local media = {} media.type = "audio" media.mime_type = "audio/mpeg" media.id = id if media.id == 'fipradio' then media.id = 'fip' end media.url = result:match("urlLive:'(http.-%mp3)") if not media.url then media.url = result:match('player" href="(http.-%.mp3)') end if not media.url then media.url = result:match('data%-url%-live="(http.-%.mp3)') end media.title = get_title(id) media.thumbnail = get_thumbnail(id) -- FIXME Add metadata about the currently playing tracks -- Available in 'http://www.' .. item .. '.fr/api/now&full=true' return media end
radiofrance: Fix unset URLs after recent website changes
radiofrance: Fix unset URLs after recent website changes https://bugzilla.gnome.org/show_bug.cgi?id=773310
Lua
lgpl-2.1
grilofw/grilo-plugins,GNOME/grilo-plugins,MikePetullo/grilo-plugins,MikePetullo/grilo-plugins,GNOME/grilo-plugins,jasuarez/grilo-plugins,jasuarez/grilo-plugins,grilofw/grilo-plugins,MikePetullo/grilo-plugins
d28f5e203f7278b32348c23ef13d3bd7e9488d6f
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") EXPECT_RESPONSE(correlationId, { success = true }) EXPECT_NOTIFICATION("OnPermissionsChange") 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) end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_RemovePTUfiles() os.remove(ptu_app_registered) end function Test.Postcondition_Stop_SDL() StopSDL() end
--------------------------------------------------------------------------------------------- -- 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
Fix issues
Fix issues
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
134ced7e0fdd17b109ebfbe78476cef977662e43
otouto/plugins/admin/listgroups.lua
otouto/plugins/admin/listgroups.lua
local utilities = require('otouto.utilities') local P = {} function P:init(bot) self.triggers = utilities.triggers(bot.info.username, bot.config.cmd_pat) :t('groups', true):t('listgroups', true).table self.command = 'groups [query]' self.doc = "/groups [query]\ Returns a list of all public, administrated groups, or the results of a query." end function P:action(bot, msg, _group) local input = utilities.input_from_msg(msg) -- Output will be a list of results, a list of all groups, or an explanation -- that there are no (listed) groups. local results, listed_groups = {}, {} for id_str, chat in pairs(bot.database.groupdata.admin) do if not chat.flags.private then local title = bot.database.groupdata.info[id_str].title local link = string.format( '<a href="%s">%s</a>', chat.link, utilities.html_escape(title) ) table.insert(listed_groups, link) if input and title:find(input, 1, true) then table.insert(results, link) end end end local output if input then if #results == 0 then output = bot.config.errors.results else output = string.format( '<b>Groups matching</b> <i>%s</i><b>:</b>\n• %s', utilities.html_escape(input), table.concat(results, '\n• ') ) end else local group_list = '<b>Groups:</b>\n• ' .. table.concat(listed_groups, '\n• ') if #listed_groups == 0 then output = 'There are no listed groups.' elseif #listed_groups < 5 then output = group_list else if utilities.send_message(msg.from.id, group_list, true, nil, 'html') then if msg.chat.type ~= 'private' then output = 'I have sent you the requested information in a private message.' end else output = string.format( 'Please <a href="https://t.me/%s?start=groups">message me privately</a> for a list of groups.', bot.info.username ) end end end if output then utilities.send_reply(msg, output, 'html') end end return P
local utilities = require('otouto.utilities') local P = {} function P:init(bot) self.triggers = utilities.triggers(bot.info.username, bot.config.cmd_pat) :t('groups', true):t('listgroups', true).table self.command = 'groups [query]' self.doc = "/groups [query]\ Returns a list of all public, administrated groups, or the results of a query." end function P:action(bot, msg, _group) local input = utilities.input_from_msg(msg) input = input and input:lower() -- Output will be a list of results, a list of all groups, or an explanation -- that there are no (listed) groups. local results, listed_groups = {}, {} for id_str, chat in pairs(bot.database.groupdata.admin) do if not chat.flags.private then local title = bot.database.groupdata.info[id_str].title local link = string.format( '<a href="%s">%s</a>', chat.link, utilities.html_escape(title) ) table.insert(listed_groups, link) if input and title:find(input, 1, true) then table.insert(results, link) end end end local output if input then if #results == 0 then output = bot.config.errors.results else output = string.format( '<b>Groups matching</b> <i>%s</i><b>:</b>\n• %s', utilities.html_escape(input), table.concat(results, '\n• ') ) end else local group_list = '<b>Groups:</b>\n• ' .. table.concat(listed_groups, '\n• ') if #listed_groups == 0 then output = 'There are no listed groups.' elseif #listed_groups < 5 then output = group_list else if utilities.send_message(msg.from.id, group_list, true, nil, 'html') then if msg.chat.type ~= 'private' then output = 'I have sent you the requested information in a private message.' end else output = string.format( 'Please <a href="https://t.me/%s?start=groups">message me privately</a> for a list of groups.', bot.info.username ) end end end if output then utilities.send_reply(msg, output, 'html') end end return P
fixed listgroups not matching capitalized queries
fixed listgroups not matching capitalized queries
Lua
agpl-3.0
topkecleon/otouto
a0b06adac8ce7ba03e51db3acc582beabfb2ec86
resources/rewriter.lua
resources/rewriter.lua
-- The first argument is where the rTorrent directory files should be placed. -- The second argument is the home directory of the user -- The third argument is the user name function replaceVars(file,keywords,replacees,replacers) local edit_file = io.open(file, "r") local text = {} for line in edit_file:lines() do table.insert (text, line) end edit_file:close() for i = 1, #text do for j = 1, #keywords do if text[i]:match(keywords[j]) then text[i] = text[i]:gsub(replacees[j],replacers[j]) end end end edit_file = io.open(file, "w") for i = 1, #text do edit_file:write(text[i] .. "\n") end edit_file:close() end function replaceLine(file,indentifier,replacer) local edit_file = io.open(file, "r") local text = {} for line in edit_file:lines() do table.insert (text, line) end edit_file:close() for i = 1, #text do for j = 1, #keywords do if text[i]:sub(1,indentifier:len()) == indentifier then text[i] = replacer end end end edit_file = io.open(file, "w") for i = 1, #text do edit_file:write(text[i] .. "\n") end edit_file:close() end print("Rewriting rutorrent config file") local config_file = "/var/www/html/rutorrent/conf/config.php" local config_keywords = {"\"php\" =>","\"curl\" =>","\"gzip\" =>","\"id\" =>","\"stat\" =>", "$topDirectory"} local config_replacees = {"\'\'","\'\'","\'\'","\'\'","\'\'","\'/\'"} local config_replacers = {"'/usr/bin/php'","'/usr/bin/curl'","'/bin/gzip'","'/usr/bin/id'","'/usr/bin/stat'","\'".. arg[1] .. "\'"} replaceVars(config_file,config_keywords,config_replacees,config_replacers) print("Adding rtorrent to startup") local startup_fix_file = "/etc/rc.local" local startup_fix_indentifier = {"su -c \"screen -S rtorrent -fa -d -m rtorrent\" " .. arg[3]} local startup_fix_replacer = {""} replaceLine(startup_fix_file,startup_fix_indentifier,startup_fix_replacer) local startup_file = "/etc/rc.local" local startup_indentifier = {"exit 0"} local startup_replacer = {"su -c \"screen -S rtorrent -fa -d -m rtorrent\" " .. arg[3] .. "\nexit 0"} replaceLine(startup_file,startup_indentifier,startup_replacer) print("Rewriting the rTorrent config file") local torrentrc_file = arg[2] .. "/.rtorrent.rc" local torrentrc_keywords = {"KEYWORD"} local torrentrc_replacees = {"KEYWORD"} local torrentrc_replacers = {arg[1]} replaceVars(torrentrc_file,torrentrc_keywords,torrentrc_replacees,torrentrc_replacers) print("Rewriting apache2 configuration file") local apache_file = "/etc/apache2/apache2.conf" local apache_keywords = {"Timeout"} local apache_replacer = {"Timeout 30"} replaceLine(apache_file,apache_indentifier,apache_replacer)
-- The first argument is where the rTorrent directory files should be placed. -- The second argument is the home directory of the user -- The third argument is the user name function replaceVars(file,keywords,replacees,replacers) local edit_file = io.open(file, "r") local text = {} for line in edit_file:lines() do table.insert (text, line) end edit_file:close() for i = 1, #text do for j = 1, #keywords do if text[i]:match(keywords[j]) then text[i] = text[i]:gsub(replacees[j],replacers[j]) end end end edit_file = io.open(file, "w") for i = 1, #text do edit_file:write(text[i] .. "\n") end edit_file:close() end function replaceLine(file,indentifier,replacer) local edit_file = io.open(file, "r") local text = {} for line in edit_file:lines() do table.insert (text, line) end edit_file:close() for i = 1, #text do if text[i]:sub(1,indentifier:len()) == indentifier then text[i] = replacer end end edit_file = io.open(file, "w") for i = 1, #text do edit_file:write(text[i] .. "\n") end edit_file:close() end print("Rewriting rutorrent config file") local config_file = "/var/www/html/rutorrent/conf/config.php" local config_keywords = {"\"php\" =>","\"curl\" =>","\"gzip\" =>","\"id\" =>","\"stat\" =>", "$topDirectory"} local config_replacees = {"\'\'","\'\'","\'\'","\'\'","\'\'","\'/\'"} local config_replacers = {"'/usr/bin/php'","'/usr/bin/curl'","'/bin/gzip'","'/usr/bin/id'","'/usr/bin/stat'","\'".. arg[1] .. "\'"} replaceVars(config_file,config_keywords,config_replacees,config_replacers) print("Adding rtorrent to startup") local startup_fix_file = "/etc/rc.local" local startup_fix_indentifier = {"su -c \"screen -S rtorrent -fa -d -m rtorrent\" " .. arg[3]} local startup_fix_replacer = {""} replaceLine(startup_fix_file,startup_fix_indentifier,startup_fix_replacer) local startup_file = "/etc/rc.local" local startup_indentifier = {"exit 0"} local startup_replacer = {"su -c \"screen -S rtorrent -fa -d -m rtorrent\" " .. arg[3] .. "\nexit 0"} replaceLine(startup_file,startup_indentifier,startup_replacer) print("Rewriting the rTorrent config file") local torrentrc_file = arg[2] .. "/.rtorrent.rc" local torrentrc_keywords = {"KEYWORD"} local torrentrc_replacees = {"KEYWORD"} local torrentrc_replacers = {arg[1]} replaceVars(torrentrc_file,torrentrc_keywords,torrentrc_replacees,torrentrc_replacers) print("Rewriting apache2 configuration file") local apache_file = "/etc/apache2/apache2.conf" local apache_keywords = {"Timeout"} local apache_replacer = {"Timeout 30"} replaceLine(apache_file,apache_indentifier,apache_replacer)
fixed a bug in new algorithm
fixed a bug in new algorithm
Lua
mit
LarsHLunde/RuTorrent-Installer
40c0574b07d3c48a1a0044686ff4f3a45e246806
scen_edit/command/import_heightmap_command.lua
scen_edit/command/import_heightmap_command.lua
ImportHeightmapCommand = Command:extends{} ImportHeightmapCommand.className = "ImportHeightmapCommand" function ImportHeightmapCommand:init(heightmapImage, maxHeight, minHeight) self.className = "ImportHeightmapCommand" self.heightmapImagePath = heightmapImage self.maxHeight = maxHeight self.minHeight = minHeight end function ImportHeightmapCommand:execute() SB.delayGL(function() if not VFS.FileExists(self.heightmapImagePath) then Log.Error("Missing heightmap file: " .. tostring(self.heightmapImagePath)) return end Log.Debug("scened", LOG.DEBUG, "Importing heightmap..") local heightmapTexture = gl.CreateTexture(Game.mapSizeX / Game.squareSize + 1, Game.mapSizeZ / Game.squareSize + 1, { border = false, min_filter = GL.NEAREST, mag_filter = GL.NEAREST, wrap_s = GL.CLAMP_TO_EDGE, wrap_t = GL.CLAMP_TO_EDGE, fbo = true, }) local texInfo = gl.TextureInfo(heightmapTexture) local w, h = texInfo.xsize, texInfo.ysize local res gl.Blending("disable") gl.RenderToTexture(heightmapTexture, function() gl.Texture(self.heightmapImagePath) gl.TexRect(-1,-1, 1, 1, 0, 0, 1, 1) res = gl.ReadPixels(0, 0, w, h) gl.DeleteTexture(self.heightmapImagePath) end) local greyscale = {} for i, row in pairs(res) do greyscale[i] = {} for j, point in pairs(row) do greyscale[i][j] = (point[1] + point[2] + point[3]) / 3 * point[4] greyscale[i][j] = self.minHeight + greyscale[i][j] * (self.maxHeight - self.minHeight) end end SB.commandManager:execute(ImportHeightmapCommandSynced(greyscale)) end) end ImportHeightmapCommandSynced = Command:extends{} ImportHeightmapCommandSynced.className = "ImportHeightmapCommandSynced" function ImportHeightmapCommandSynced:init(greyscale) self.className = "ImportHeightmapCommandSynced" self.greyscale = greyscale end function ImportHeightmapCommandSynced:execute() Spring.SetHeightMapFunc(function() for z = 0, Game.mapSizeZ, Game.squareSize do for x = 0, Game.mapSizeX, Game.squareSize do local column = self.greyscale[z / Game.squareSize + 1] Spring.SetHeightMap(x, z, column[x / Game.squareSize + 1]) end end end) end
ImportHeightmapCommand = Command:extends{} ImportHeightmapCommand.className = "ImportHeightmapCommand" function ImportHeightmapCommand:init(heightmapImage, maxHeight, minHeight) self.className = "ImportHeightmapCommand" self.heightmapImagePath = heightmapImage self.maxHeight = maxHeight self.minHeight = minHeight end function ImportHeightmapCommand:execute() SB.delayGL(function() if not VFS.FileExists(self.heightmapImagePath) then Log.Error("Missing heightmap file: " .. tostring(self.heightmapImagePath)) return end Log.Debug("Importing heightmap..") local heightmapTexture = gl.CreateTexture( Game.mapSizeX / Game.squareSize + 1, Game.mapSizeZ / Game.squareSize + 1, { border = false, min_filter = GL.NEAREST, mag_filter = GL.NEAREST, wrap_s = GL.CLAMP_TO_EDGE, wrap_t = GL.CLAMP_TO_EDGE, fbo = true, }) local texInfo = gl.TextureInfo(heightmapTexture) local w, h = texInfo.xsize, texInfo.ysize local res gl.Blending("disable") gl.Texture(self.heightmapImagePath) gl.RenderToTexture(heightmapTexture, function() gl.TexRect(-1,-1, 1, 1, 0, 0, 1, 1) res = gl.ReadPixels(0, 0, w, h) end) gl.Texture(false) gl.DeleteTexture(self.heightmapImagePath) gl.DeleteTexture(heightmapTexture) local greyscale = {} local h = 0 for i, row in ipairs(res) do greyscale[i] = {} for j, point in ipairs(row) do h = (point[1] + point[2] + point[3]) / 3 * point[4] greyscale[i][j] = self.minHeight + h * (self.maxHeight - self.minHeight) end end SB.commandManager:execute(ImportHeightmapCommandSynced(greyscale)) end) end ImportHeightmapCommandSynced = Command:extends{} ImportHeightmapCommandSynced.className = "ImportHeightmapCommandSynced" function ImportHeightmapCommandSynced:init(greyscale) self.className = "ImportHeightmapCommandSynced" self.greyscale = greyscale end function ImportHeightmapCommandSynced:execute() Spring.SetHeightMapFunc(function() for x = 0, Game.mapSizeX, Game.squareSize do for z = 0, Game.mapSizeZ, Game.squareSize do local column = self.greyscale[x / Game.squareSize + 1] Spring.SetHeightMap(x, z, column[z / Game.squareSize + 1])--column[z / Game.squareSize + 1]) end end end) end
fail to fix heightmap import
fail to fix heightmap import
Lua
mit
Spring-SpringBoard/SpringBoard-Core,Spring-SpringBoard/SpringBoard-Core
c1f66b616b5757cce6d87f32c74d087d11272472
kong/plugins/prometheus/handler.lua
kong/plugins/prometheus/handler.lua
local prometheus = require "kong.plugins.prometheus.exporter" local basic_serializer = require "kong.plugins.log-serializers.basic" local kong = kong local timer_at = ngx.timer.at local function log(premature, message) if premature then return end prometheus.log(message) end local PrometheusHandler = { PRIORITY = 13, VERSION = "0.4.0", } function PrometheusHandler:new() return prometheus.init() end function PrometheusHandler:log(_) local message = basic_serializer.serialize(ngx) local ok, err = timer_at(0, log, message) if not ok then kong.log.err("failed to create timer: ", err) end end return PrometheusHandler
local prometheus = require "kong.plugins.prometheus.exporter" local basic_serializer = require "kong.plugins.log-serializers.basic" local kong = kong local timer_at = ngx.timer.at prometheus.init() local function log(premature, message) if premature then return end prometheus.log(message) end local PrometheusHandler = { PRIORITY = 13, VERSION = "0.4.0", } function PrometheusHandler:log(_) local message = basic_serializer.serialize(ngx) local ok, err = timer_at(0, log, message) if not ok then kong.log.err("failed to create timer: ", err) end end return PrometheusHandler
fix(prometheus) move prometheus.init call to top-level scope
fix(prometheus) move prometheus.init call to top-level scope `:new` is no longer available as this plugin no longer inherits from the BasePlugin class. This commit updates the handler so it initialize its shared dictionary in the top-level scope (executed in the `init` phase).
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
1b6982b788c5fc986ab46a1c82cec2f39fd1937a
lgi/record.lua
lgi/record.lua
------------------------------------------------------------------------------ -- -- lgi - handling of structs and unions -- -- Copyright (c) 2010, 2011,2013 Pavel Holejsovsky -- Licensed under the MIT license: -- http://www.opensource.org/licenses/mit-license.php -- ------------------------------------------------------------------------------ local rawget, assert, select, pairs, type, error, setmetatable = rawget, assert, select, pairs, type, error, setmetatable -- Require core lgi utilities, used during bootstrap. local core = require 'lgi.core' local gi = core.gi local component = require 'lgi.component' -- Implementation of record_mt, which is inherited from component -- and provides customizations for structures and unions. local record = { struct_mt = component.mt:clone('struct', { '_method', '_field' }), } -- Checks whether given argument is type of this class. function record.struct_mt:is_type_of(instance) if type(instance) == 'userdata' then local instance_type = core.record.query(instance, 'repo') while instance_type do if instance_type == self then return true end instance_type = rawget(instance_type, '_parent') end end return false end -- Resolver for records, recursively resolves also all parents. function record.struct_mt:_resolve(recursive) -- Resolve itself using inherited implementation. component.mt._resolve(self) -- Go to parent and resolve it too. if recursive and self._parent then self._parent:_resolve(recursive) end return self end function record.struct_mt:_element(instance, symbol) -- First of all, try normal inherited functionality. local element, category = component.mt._element(self, instance, symbol) if element then if category == '_field' then if type(element) == 'table' and element.ret then category = '_cbkfield' local ffi = require 'lgi.ffi' element = { name = element.name, ptrfield = { element.offset, 0, ffi.types.ptr }, callable = element } elseif gi.isinfo(element) and element.is_field then local ii = element.typeinfo.interface if ii and ii.type == 'callback' then category = '_cbkfield' local ffi = require 'lgi.ffi' element = { name = element.name, ptrfield = { element.offset, 0, ffi.types.ptr }, callable = ii } end end end return element, category end -- Special handling of '_native' attribute. if symbol == '_native' then return symbol, '_internal' elseif symbol == '_type' then return symbol, '_internal' elseif symbol == '_refsink' then return symbol, '_internal' end -- If the record has parent struct, try it there. local parent = rawget(self, '_parent') if parent then return parent:_element(instance, symbol) end end -- Add accessor for handling fields. function record.struct_mt:_access_field(instance, element, ...) -- Check whether we are marshalling subrecord local subrecord if select('#', ...) > 0 then if gi.isinfo(element) and element.is_field then local ii = element.typeinfo.interface if ii and (ii.type == 'struct' or ii.type == 'union') then subrecord = true end else if type(element) == 'table' and (element[2] == 1 or element[2] == 2) then subrecord = true end end end if subrecord then -- Write to nested structure, handle assignment to it by -- assigning separate fields. subrecord = core.record.field(instance, element) for name, value in pairs(...) do subrecord[name] = value end else -- In other cases, just access the instance using given info. return core.record.field(instance, element, ...) end end -- Add accessor for handling fields containing callbacks local guards_station = setmetatable({}, { __mode = 'k' }) function record.struct_mt:_access_cbkfield(instance, element, ...) if select('#', ...) == 0 then -- Reading callback field, get pointer and wrap it in proper -- callable, so that caller can actually call it. local addr = core.record.field(instance, element.ptrfield) return core.callable.new(element.callable, addr) else local target = ... if type(target) ~= 'userdata' then -- Create closure over Lua target, keep guard stored. local guard guard, target = core.marshal.callback(element.callable, target) local guards = guards_station[instance] if not guards then guards = {} guards_station[instance] = guards end guards[element.name] = guard end core.record.field(instance, element.ptrfield, target) end end -- Add accessor for 'internal' fields handling. function record.struct_mt:_access_internal(instance, element, ...) if select('#', ...) ~= 0 then return end if element == '_native' then return core.record.query(instance, 'addr') elseif element == '_type' then return core.record.query(instance, 'repo') end end function record.struct_mt:_index_internal(element) return nil end -- Create structure instance and initialize it with given fields. function record.struct_mt:_new(param, owns) local struct if type(param) == 'userdata' or type(param) == 'number' then -- Wrap existing pointer. struct = core.record.new(self, param, owns) else -- Check that we are allowed to create the record. if not self._size then error(("%s: not directly instantiable"):format(self._name), 2) end -- Create the structure instance. struct = core.record.new(self) -- Set values of fields. for name, value in pairs(param or {}) do struct[name] = value end end return struct end -- Loads structure information into table representing the structure function record.load(info) local record = component.create( info, info.is_struct and record.struct_mt or record.union_mt) record._size = info.size record._method = component.get_category(info.methods, core.callable.new) record._field = component.get_category(info.fields) -- Check, whether global namespace contains 'constructor' method, -- i.e. method which has the same name as our record type (except -- that type is in CamelCase, while method is -- under_score_delimited). If not found, check for 'new' method. local func = core.downcase(info.name:gsub('([%l%d])([%u])', '%1_%2')) local ctor = gi[info.namespace][func] or gi[info.namespace][func .. '_new'] if not ctor then ctor = info.methods.new end -- Check, whether ctor is valid. In order to be valid, it must -- return instance of this record. if (ctor and ctor.return_type.tag =='interface' and ctor.return_type.interface == info) then ctor = core.callable.new(ctor) record._new = function(typetable, ...) return ctor(...) end end return record end -- Union metatable is the same as struct one, but has different name -- to differentiate unions. record.union_mt = record.struct_mt:clone('union') return record
------------------------------------------------------------------------------ -- -- lgi - handling of structs and unions -- -- Copyright (c) 2010, 2011,2013 Pavel Holejsovsky -- Licensed under the MIT license: -- http://www.opensource.org/licenses/mit-license.php -- ------------------------------------------------------------------------------ local rawget, assert, select, pairs, type, error, setmetatable = rawget, assert, select, pairs, type, error, setmetatable -- Require core lgi utilities, used during bootstrap. local core = require 'lgi.core' local gi = core.gi local component = require 'lgi.component' -- Implementation of record_mt, which is inherited from component -- and provides customizations for structures and unions. local record = { struct_mt = component.mt:clone('struct', { '_method', '_field' }), } -- Checks whether given argument is type of this class. function record.struct_mt:is_type_of(instance) if type(instance) == 'userdata' then local instance_type = core.record.query(instance, 'repo') while instance_type do if instance_type == self then return true end instance_type = rawget(instance_type, '_parent') end end return false end -- Resolver for records, recursively resolves also all parents. function record.struct_mt:_resolve(recursive) -- Resolve itself using inherited implementation. component.mt._resolve(self) -- Go to parent and resolve it too. if recursive and self._parent then self._parent:_resolve(recursive) end return self end function record.struct_mt:_element(instance, symbol) -- First of all, try normal inherited functionality. local element, category = component.mt._element(self, instance, symbol) if element then if category == '_field' then if type(element) == 'table' and element.ret then category = '_cbkfield' local ffi = require 'lgi.ffi' element = { name = element.name, ptrfield = { element.offset, 0, ffi.types.ptr }, callable = element } elseif gi.isinfo(element) and element.is_field then local ii = element.typeinfo.interface if ii and ii.type == 'callback' then category = '_cbkfield' local ffi = require 'lgi.ffi' element = { name = element.name, ptrfield = { element.offset, 0, ffi.types.ptr }, callable = ii } end end end return element, category end -- Special handling of '_native' attribute. if symbol == '_native' then return symbol, '_internal' elseif symbol == '_type' then return symbol, '_internal' elseif symbol == '_refsink' then return symbol, '_internal' end -- If the record has parent struct, try it there. local parent = rawget(self, '_parent') if parent then return parent:_element(instance, symbol) end end -- Add accessor for handling fields. function record.struct_mt:_access_field(instance, element, ...) -- Check whether we are marshalling subrecord local subrecord if select('#', ...) > 0 then if gi.isinfo(element) and element.is_field then local ii = element.typeinfo.interface if ii and (ii.type == 'struct' or ii.type == 'union') then subrecord = true end else if type(element) == 'table' and (element[2] == 1 or element[2] == 2) then subrecord = true end end end if subrecord then -- Write to nested structure, handle assignment to it by -- assigning separate fields. subrecord = core.record.field(instance, element) for name, value in pairs(...) do subrecord[name] = value end else -- In other cases, just access the instance using given info. return core.record.field(instance, element, ...) end end -- Add accessor for handling fields containing callbacks local guards_station = setmetatable({}, { __mode = 'k' }) function record.struct_mt:_access_cbkfield(instance, element, ...) if select('#', ...) == 0 then -- Reading callback field, get pointer and wrap it in proper -- callable, so that caller can actually call it. local addr = core.record.field(instance, element.ptrfield) return core.callable.new(element.callable, addr) else local target = ... if type(target) ~= 'userdata' then -- Create closure over Lua target, keep guard stored. local guard guard, target = core.marshal.callback(element.callable, target) local guards = guards_station[instance] if not guards then guards = {} guards_station[instance] = guards end guards[element.name] = guard end core.record.field(instance, element.ptrfield, target) end end -- Add accessor for 'internal' fields handling. function record.struct_mt:_access_internal(instance, element, ...) if select('#', ...) ~= 0 then return end if element == '_native' then return core.record.query(instance, 'addr') elseif element == '_type' then return core.record.query(instance, 'repo') end end function record.struct_mt:_index_internal(element) return nil end -- Create structure instance and initialize it with given fields. function record.struct_mt:_new(param, owns) local struct if type(param) == 'userdata' or type(param) == 'number' then -- Wrap existing pointer. struct = core.record.new(self, param, owns) else -- Check that we are allowed to create the record. if not self._size then error(("%s: not directly instantiable"):format(self._name), 2) end -- Create the structure instance. struct = core.record.new(self) -- Set values of fields. for name, value in pairs(param or {}) do struct[name] = value end end return struct end -- Loads structure information into table representing the structure function record.load(info) local record = component.create( info, info.is_struct and record.struct_mt or record.union_mt) record._size = info.size record._method = component.get_category(info.methods, core.callable.new) record._field = component.get_category(info.fields) -- Check, whether global namespace contains 'constructor' method, -- i.e. method which has the same name as our record type (except -- that type is in CamelCase, while method is -- under_score_delimited). If not found, check for 'new' method. local func = core.downcase(info.name:gsub('([%l%d])([%u])', '%1_%2')) local ctor = gi[info.namespace][func] or gi[info.namespace][func .. '_new'] if not ctor then ctor = info.methods.new end -- Check, whether ctor is valid. In order to be valid, it must -- return instance of this record. if (ctor and ctor.type == 'function' and ctor.return_type.tag =='interface' and ctor.return_type.interface == info) then ctor = core.callable.new(ctor) record._new = function(typetable, ...) return ctor(...) end end return record end -- Union metatable is the same as struct one, but has different name -- to differentiate unions. record.union_mt = record.struct_mt:clone('union') return record
record.load: Require constructor to be a function
record.load: Require constructor to be a function libgtop (available at https://github.com/GNOME/libgtop/commits/master) has a struct glibtop_cpu. While trying to load this through e.g. require("lgi").GTop.glibtop_cpu, the following error occurred: lgi/record.lua:153: attempt to index a nil value (field 'return_type') This occurred because the code tried to find a constructor for this struct and for this it "un-camel-cased" the struct name, which didn't change anything, because the struct name isn't camel-cased, and then assumed that the result were information about a function. However, this just found the struct again. Fix this by explicitly testing if the type of the result is a function. Signed-off-by: Uli Schlachter <ede10f140ad8f5ad90197d17839fb90345d66dd4@informatik.uni-oldenburg.de>
Lua
mit
psychon/lgi,pavouk/lgi
d3b8c7fb4f22ddb8ceb04efd726253b811e60bd8
lua/entities/gmod_wire_expression2/core/extloader.lua
lua/entities/gmod_wire_expression2/core/extloader.lua
--[[ Loading extensions ]] -- Save E2's metatable for wire_expression2_reload if ENT then local wire_expression2_ENT = ENT function wire_expression2_reload(ply, cmd, args) if IsValid(ply) and ply:IsPlayer() and not ply:IsSuperAdmin() and not game.SinglePlayer() then return end Msg("Calling destructors for all Expression2 chips.\n") local chips = ents.FindByClass("gmod_wire_expression2") for _, chip in ipairs(chips) do if not chip.error then chip:PCallHook('destruct') end chip.script = nil end Msg("Reloading Expression2 extensions.\n") ENT = wire_expression2_ENT wire_expression2_is_reload = true include("entities/gmod_wire_expression2/core/extloader.lua") wire_expression2_is_reload = nil ENT = nil Msg("Calling constructors for all Expression2 chips.\n") wire_expression2_prepare_functiondata() if not args or args[1] ~= "nosend" then wire_expression2_sendfunctions(player.GetAll()) end for _, chip in ipairs(chips) do pcall(chip.OnRestore, chip) end Msg("Done reloading Expression2 extensions.\n") end concommand.Add("wire_expression2_reload", wire_expression2_reload) end wire_expression2_reset_extensions() include("extpp.lua") local function luaExists(luaname) return #file.Find(luaname, "LUA") ~= 0 end local included_files = {} -- parses typename/typeid associations from a file and stores info about the file for later use by e2_include_finalize/e2_include_pass2 local function e2_include(name) local path, filename = string.match(name, "^(.-/?)([^/]*)$") local cl_name = path .. "cl_" .. filename if luaExists("entities/gmod_wire_expression2/core/" .. cl_name) then -- If a file of the same name prefixed with cl_ exists, send it to the client and load it there. AddCSE2File(cl_name) end local luaname = "entities/gmod_wire_expression2/core/" .. name local contents = file.Read(luaname, "LUA") or "" e2_extpp_pass1(contents) table.insert(included_files, { name, luaname, contents }) end -- parses and executes an extension local function e2_include_pass2(name, luaname, contents) local ok, ret = pcall(e2_extpp_pass2, contents) if not ok then WireLib.ErrorNoHalt(luaname .. ret .. "\n") return end if not ret then -- e2_extpp_pass2 returned false => file didn't need preprocessing => use the regular means of inclusion return include(name) end -- file needed preprocessing => Run the processed file RunStringEx(ret, luaname) __e2setcost(nil) -- Reset ops cost at the end of each file end local function e2_include_finalize() for _, info in ipairs(included_files) do e2_include_pass2(unpack(info)) end included_files = nil e2_include = nil end -- end preprocessor stuff e2_include("core.lua") e2_include("array.lua") e2_include("number.lua") e2_include("vector.lua") e2_include("string.lua") e2_include("angle.lua") e2_include("entity.lua") e2_include("player.lua") e2_include("timer.lua") e2_include("selfaware.lua") e2_include("unitconv.lua") e2_include("wirelink.lua") e2_include("console.lua") e2_include("find.lua") e2_include("files.lua") e2_include("cl_files.lua") e2_include("globalvars.lua") e2_include("ranger.lua") e2_include("sound.lua") e2_include("color.lua") e2_include("serverinfo.lua") e2_include("chat.lua") e2_include("constraint.lua") e2_include("weapon.lua") e2_include("gametick.lua") e2_include("npc.lua") e2_include("matrix.lua") e2_include("vector2.lua") e2_include("signal.lua") e2_include("bone.lua") e2_include("table.lua") e2_include("glon.lua") e2_include("hologram.lua") e2_include("complex.lua") e2_include("bitwise.lua") e2_include("quaternion.lua") e2_include("debug.lua") e2_include("http.lua") e2_include("compat.lua") e2_include("custom.lua") e2_include("datasignal.lua") e2_include("egpfunctions.lua") e2_include("functions.lua") e2_include("strfunc.lua") do local list = file.Find("entities/gmod_wire_expression2/core/custom/*.lua", "LUA") for _, filename in pairs(list) do if filename:sub(1, 3) == "cl_" then -- If the is prefixed with "cl_", send it to the client and load it there. AddCSE2File("custom/" .. filename) else e2_include("custom/" .. filename) end end end e2_include_finalize() wire_expression2_CallHook("postinit")
--[[ Loading extensions ]] -- Save E2's metatable for wire_expression2_reload if ENT then local wire_expression2_ENT = ENT function wire_expression2_reload(ply, cmd, args) if IsValid(ply) and ply:IsPlayer() and not ply:IsSuperAdmin() and not game.SinglePlayer() then return end Msg("Calling destructors for all Expression2 chips.\n") local chips = ents.FindByClass("gmod_wire_expression2") for _, chip in ipairs(chips) do if not chip.error then chip:PCallHook('destruct') end chip.script = nil end Msg("Reloading Expression2 extensions.\n") ENT = wire_expression2_ENT wire_expression2_is_reload = true include("entities/gmod_wire_expression2/core/extloader.lua") wire_expression2_is_reload = nil ENT = nil Msg("Calling constructors for all Expression2 chips.\n") wire_expression2_prepare_functiondata() if not args or args[1] ~= "nosend" then wire_expression2_sendfunctions(player.GetAll()) end for _, chip in ipairs(chips) do pcall(chip.OnRestore, chip) end Msg("Done reloading Expression2 extensions.\n") end concommand.Add("wire_expression2_reload", wire_expression2_reload) end wire_expression2_reset_extensions() include("extpp.lua") local function luaExists(luaname) return #file.Find(luaname, "LUA") ~= 0 end local included_files = {} -- parses typename/typeid associations from a file and stores info about the file for later use by e2_include_finalize/e2_include_pass2 local function e2_include(name) local path, filename = string.match(name, "^(.-/?)([^/]*)$") local cl_name = path .. "cl_" .. filename if luaExists("entities/gmod_wire_expression2/core/" .. cl_name) then -- If a file of the same name prefixed with cl_ exists, send it to the client and load it there. AddCSE2File(cl_name) end local luaname = "entities/gmod_wire_expression2/core/" .. name local contents = file.Read(luaname, "LUA") or "" e2_extpp_pass1(contents) table.insert(included_files, { name, luaname, contents }) end -- parses and executes an extension local function e2_include_pass2(name, luaname, contents) local ok, ret = pcall(e2_extpp_pass2, contents) if not ok then WireLib.ErrorNoHalt(luaname .. ret .. "\n") return end if not ret then -- e2_extpp_pass2 returned false => file didn't need preprocessing => use the regular means of inclusion return include(name) end -- file needed preprocessing => Run the processed file local ok, func = pcall(CompileString,ret,luaname) if not ok then -- an error occurred while compiling error(func) return end local ok, err = pcall(func) if not ok then -- an error occured while executing if string.find(err,"Skipping disabled E2 extension") ~= 0 then -- if it's just a disabled E2 extension... local err = string.match(err,"(Skipping disabled E2 extension.+).$") -- filter to the part we want print(err) -- print the error else error(err) -- otherwise, actually cause an error end return end __e2setcost(nil) -- Reset ops cost at the end of each file end local function e2_include_finalize() for _, info in ipairs(included_files) do e2_include_pass2(unpack(info)) end included_files = nil e2_include = nil end -- end preprocessor stuff e2_include("core.lua") e2_include("array.lua") e2_include("number.lua") e2_include("vector.lua") e2_include("string.lua") e2_include("angle.lua") e2_include("entity.lua") e2_include("player.lua") e2_include("timer.lua") e2_include("selfaware.lua") e2_include("unitconv.lua") e2_include("wirelink.lua") e2_include("console.lua") e2_include("find.lua") e2_include("files.lua") e2_include("cl_files.lua") e2_include("globalvars.lua") e2_include("ranger.lua") e2_include("sound.lua") e2_include("color.lua") e2_include("serverinfo.lua") e2_include("chat.lua") e2_include("constraint.lua") e2_include("weapon.lua") e2_include("gametick.lua") e2_include("npc.lua") e2_include("matrix.lua") e2_include("vector2.lua") e2_include("signal.lua") e2_include("bone.lua") e2_include("table.lua") e2_include("glon.lua") e2_include("hologram.lua") e2_include("complex.lua") e2_include("bitwise.lua") e2_include("quaternion.lua") e2_include("debug.lua") e2_include("http.lua") e2_include("compat.lua") e2_include("custom.lua") e2_include("datasignal.lua") e2_include("egpfunctions.lua") e2_include("functions.lua") e2_include("strfunc.lua") do local list = file.Find("entities/gmod_wire_expression2/core/custom/*.lua", "LUA") for _, filename in pairs(list) do if filename:sub(1, 3) == "cl_" then -- If the is prefixed with "cl_", send it to the client and load it there. AddCSE2File("custom/" .. filename) else e2_include("custom/" .. filename) end end end e2_include_finalize() wire_expression2_CallHook("postinit")
Fixed disabled E2 extensions loading anyway
Fixed disabled E2 extensions loading anyway Fixes #456
Lua
apache-2.0
rafradek/wire,plinkopenguin/wiremod,sammyt291/wire,thegrb93/wire,Python1320/wire,garrysmodlua/wire,wiremod/wire,notcake/wire,mms92/wire,Grocel/wire,CaptainPRICE/wire,mitterdoo/wire,immibis/wiremod,dvdvideo1234/wire,NezzKryptic/Wire,bigdogmat/wire
2e2398271ce80ef82fd046d9a464dda7ce3a1ba3
src/cosy/loader/js.lua
src/cosy/loader/js.lua
if #setmetatable ({}, { __len = function () return 1 end }) ~= 1 then error "Cosy requires Lua >= 5.2 to run." end return function (options) options = options or {} local loader = {} for k, v in pairs (options) do loader [k] = v end local global = _G or _ENV loader.home = "/" loader.prefix = "/" loader.js = global.js loader.window = loader.js.global loader.document = loader.js.global.document loader.screen = loader.js.global.screen local modules = setmetatable ({}, { __mode = "kv" }) loader.request = function (url) local request = loader.js.new (loader.window.XMLHttpRequest) request:open ("GET", url, false) request:send (nil) if request.status == 200 then return request.responseText, request.status else return nil , request.status end end table.insert (package.searchers, 2, function (name) local url = "/lua/" .. name local result, err result, err = loader.request (url) if not result then error (err) end return load (result, url) end) loader.require = require loader.load = function (name) if modules [name] then return modules [name] end local module = loader.require (name) (loader) or true modules [name] = module return module end loader.coroutine = loader.require "coroutine.make" () loader.logto = true loader.scheduler = { _running = nil, waiting = {}, ready = {}, blocked = {}, coroutine = loader.coroutine, timeout = {}, } function loader.scheduler.running () return loader.scheduler._running end function loader.scheduler.addthread (f, ...) local co = loader.scheduler.coroutine.create (f) loader.scheduler.ready [co] = { parameters = { ... }, } if loader.scheduler.co and coroutine.status (loader.scheduler.co) == "suspended" then coroutine.resume (loader.scheduler.co) end end function loader.scheduler.block (co) loader.scheduler.blocked [co] = true end function loader.scheduler.release (co) loader.scheduler.blocked [co] = nil end function loader.scheduler.sleep (time) time = time or -math.huge local co = loader.scheduler.running () if time > 0 then loader.scheduler.timeout [co] = loader.window:setTimeout (function () loader.window:clearTimeout (loader.scheduler.timeout [co]) loader.scheduler.waiting [co] = nil loader.scheduler.ready [co] = true if coroutine.status (loader.scheduler.co) == "suspended" then coroutine.resume (loader.scheduler.co) end end, time * 1000) end if time ~= 0 then loader.scheduler.waiting [co] = true loader.scheduler.ready [co] = nil loader.scheduler.coroutine.yield () end end function loader.scheduler.wakeup (co) loader.window:clearTimeout (loader.scheduler.timeout [co]) loader.scheduler.waiting [co] = nil loader.scheduler.ready [co] = true coroutine.resume (loader.scheduler.co) end function loader.scheduler.loop () while true do for to_run, t in pairs (loader.scheduler.ready) do if not loader.scheduler.blocked [to_run] then if loader.scheduler.coroutine.status (to_run) == "suspended" then loader.scheduler._running = to_run local ok, err = loader.scheduler.coroutine.resume (to_run, type (t) == "table" and table.unpack (t.parameters)) if not ok then loader.window.console:log (err) end end if loader.scheduler.coroutine.status (to_run) == "dead" then loader.scheduler.waiting [to_run] = nil loader.scheduler.ready [to_run] = nil end end end if not next (loader.scheduler.ready ) and not next (loader.scheduler.waiting) and not next (loader.scheduler.blocked) then loader.scheduler.co = nil break else local runnable = 0 for k in pairs (loader.scheduler.ready) do if not loader.scheduler.blocked [k] then runnable = runnable + 1 break end end if runnable == 0 then loader.scheduler.co = coroutine.running () else coroutine.yield () end end end end loader.load "cosy.string" return loader end
if #setmetatable ({}, { __len = function () return 1 end }) ~= 1 then error "Cosy requires Lua >= 5.2 to run." end return function (options) options = options or {} local loader = {} for k, v in pairs (options) do loader [k] = v end local global = _G or _ENV loader.home = "/" loader.prefix = "/" loader.js = global.js loader.window = loader.js.global loader.document = loader.js.global.document loader.screen = loader.js.global.screen local modules = setmetatable ({}, { __mode = "kv" }) loader.request = function (url) local request = loader.js.new (loader.window.XMLHttpRequest) request:open ("GET", url, false) request:send (nil) if request.status == 200 then return request.responseText, request.status else return nil, request.status end end table.insert (package.searchers, 2, function (name) local url = "/lua/" .. name local result, err result, err = loader.request (url) if not result then error (err) end return load (result, url) end) loader.require = require loader.load = function (name) if modules [name] then return modules [name] end local module = loader.require (name) (loader) or true modules [name] = module return module end loader.coroutine = loader.require "coroutine.make" () loader.logto = true loader.scheduler = { _running = nil, waiting = {}, ready = {}, blocked = {}, coroutine = loader.coroutine, timeout = {}, } function loader.scheduler.running () return loader.scheduler._running end function loader.scheduler.addthread (f, ...) local co = loader.scheduler.coroutine.create (f) loader.scheduler.ready [co] = { parameters = { ... }, } if loader.scheduler.co and coroutine.status (loader.scheduler.co) == "suspended" then coroutine.resume (loader.scheduler.co) end end function loader.scheduler.block (co) loader.scheduler.blocked [co] = true end function loader.scheduler.release (co) loader.scheduler.blocked [co] = nil end function loader.scheduler.sleep (time) time = time or -math.huge local co = loader.scheduler.running () if time > 0 then loader.scheduler.timeout [co] = loader.window:setTimeout (function () loader.window:clearTimeout (loader.scheduler.timeout [co]) loader.scheduler.waiting [co] = nil loader.scheduler.ready [co] = true if coroutine.status (loader.scheduler.co) == "suspended" then coroutine.resume (loader.scheduler.co) end end, time * 1000) end if time ~= 0 then loader.scheduler.waiting [co] = true loader.scheduler.ready [co] = nil loader.scheduler.coroutine.yield () end end function loader.scheduler.wakeup (co) loader.window:clearTimeout (loader.scheduler.timeout [co]) loader.scheduler.waiting [co] = nil loader.scheduler.ready [co] = true coroutine.resume (loader.scheduler.co) end function loader.scheduler.loop () loader.scheduler.co = coroutine.running () while true do for to_run, t in pairs (loader.scheduler.ready) do if not loader.scheduler.blocked [to_run] then if loader.scheduler.coroutine.status (to_run) == "suspended" then loader.scheduler._running = to_run local ok, err = loader.scheduler.coroutine.resume (to_run, type (t) == "table" and table.unpack (t.parameters)) if not ok then loader.window.console:log (err) end end if loader.scheduler.coroutine.status (to_run) == "dead" then loader.scheduler.waiting [to_run] = nil loader.scheduler.ready [to_run] = nil end end end if not next (loader.scheduler.ready ) and not next (loader.scheduler.waiting) and not next (loader.scheduler.blocked) then loader.scheduler.co = nil return else local runnable = 0 for k in pairs (loader.scheduler.ready) do if not loader.scheduler.blocked [k] then runnable = runnable + 1 break end end if runnable == 0 then coroutine.yield () end end end end loader.load "cosy.string" return loader end
Fix JS scheduler.
Fix JS scheduler.
Lua
mit
CosyVerif/library,CosyVerif/library,CosyVerif/library
7160ca6e7ba3f849d56ec922e7ae3ee8a7626a37
nwf_modules/direct_view_access_mod/init.lua
nwf_modules/direct_view_access_mod/init.lua
-- -- desc: Supports direct access to the views via file path for front-end debugging -- Author: Elvin -- Date: 17-5-25 -- others: It is only enabled when the nwf.config.echoDebugInfo configuration is set to true. -- print("direct_view_access_mod module init..."); if (nwf.config.echoDebugInfo) then nwf.registerRequestMapper(function(requestPath) return function(ctx) local filePath = "www/view" .. requestPath if (not ParaIO.DoesFileExist(filePath, false)) then return; end local f = assert(io.open(filePath, "r")) local str = f:read("*all"); f:close(); return "raw", {content = str} end; end); print("warning: direct_view_access_mod module is enabled."); end
-- -- desc: Supports direct access to the views via file path for front-end debugging -- Author: Elvin -- Date: 17-5-25 -- others: It is only enabled when the nwf.config.echoDebugInfo configuration is set to true. -- print("direct_view_access_mod module init..."); if (nwf.config.echoDebugInfo) then nwf.registerRequestMapper(function(requestPath) local filePath = "www/view" .. requestPath if (not ParaIO.DoesFileExist(filePath, false)) then return; end return function(ctx) local f = assert(io.open(filePath, "r")) local str = f:read("*all"); f:close(); return "raw", {content = str} end; end); print("warning: direct_view_access_mod module is enabled."); end
fix bug about direct_view_access_mod
fix bug about direct_view_access_mod
Lua
mit
Links7094/nwf,Links7094/nwf,elvinzeng/nwf,elvinzeng/nwf
86c32d917c41f7ead059908c43e08aa704df1d61
applications/luci-statistics/luasrc/controller/luci_statistics/luci_statistics.lua
applications/luci-statistics/luasrc/controller/luci_statistics/luci_statistics.lua
--[[ Luci statistics - statistics controller module (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.controller.luci_statistics.luci_statistics", package.seeall) function index() require("nixio.fs") require("luci.util") require("luci.statistics.datatree") -- get rrd data tree local tree = luci.statistics.datatree.Instance() -- override entry(): check for existance <plugin>.so where <plugin> is derived from the called path function _entry( path, ... ) local file = path[5] or path[4] if nixio.fs.access( "/usr/lib/collectd/" .. file .. ".so" ) then entry( path, ... ) end end local labels = { s_output = _("Output plugins"), s_system = _("System plugins"), s_network = _("Network plugins"), rrdtool = _("RRDTool"), network = _("Network"), unixsock = _("UnixSock"), csv = _("CSV Output"), exec = _("Exec"), email = _("Email"), cpu = _("Processor"), df = _("Disk Space Usage"), disk = _("Disk Usage"), irq = _("Interrupts"), processes = _("Processes"), load = _("System Load"), interface = _("Interfaces"), netlink = _("Netlink"), iptables = _("Firewall"), tcpconns = _("TCP Connections"), ping = _("Ping"), dns = _("DNS"), wireless = _("Wireless") } -- our collectd menu local collectd_menu = { output = { "rrdtool", "network", "unixsock", "csv" }, system = { "exec", "email", "cpu", "df", "disk", "irq", "processes", "load" }, network = { "interface", "netlink", "iptables", "tcpconns", "ping", "dns", "wireless" } } -- create toplevel menu nodes local st = entry({"admin", "statistics"}, call("statistics_index"), _("Statistics"), 80) st.i18n = "statistics" st.index = true entry({"admin", "statistics", "collectd"}, cbi("luci_statistics/collectd"), _("Collectd"), 10).subindex = true -- populate collectd plugin menu local index = 1 for section, plugins in luci.util.kspairs( collectd_menu ) do local e = entry( { "admin", "statistics", "collectd", section }, call( "statistics_" .. section .. "plugins" ), labels["s_"..section], index * 10 ) e.index = true e.i18n = "rrdtool" for j, plugin in luci.util.vspairs( plugins ) do _entry( { "admin", "statistics", "collectd", section, plugin }, cbi("luci_statistics/" .. plugin ), labels[plugin], j * 10 ) end index = index + 1 end -- output views local page = entry( { "admin", "statistics", "graph" }, call("statistics_index"), _("Graphs"), 80) page.i18n = "statistics" page.setuser = "nobody" page.setgroup = "nogroup" local vars = luci.http.formvalue(nil, true) local span = vars.timespan or nil for i, plugin in luci.util.vspairs( tree:plugins() ) do -- get plugin instances local instances = tree:plugin_instances( plugin ) -- plugin menu entry entry( { "admin", "statistics", "graph", plugin }, call("statistics_render"), labels[plugin], i ).query = { timespan = span } -- if more then one instance is found then generate submenu if #instances > 1 then for j, inst in luci.util.vspairs(instances) do -- instance menu entry entry( { "admin", "statistics", "graph", plugin, inst }, call("statistics_render"), inst, j ).query = { timespan = span } end end end end function statistics_index() luci.template.render("admin_statistics/index") end function statistics_outputplugins() local translate = luci.i18n.translate local plugins = { rrdtool = _("RRDTool"), network = _("Network"), unixsock = _("UnixSock"), csv = _("CSV Output") } luci.template.render("admin_statistics/outputplugins", {plugins=plugins}) end function statistics_systemplugins() local translate = luci.i18n.translate local plugins = { exec = _("Exec"), email = _("Email"), cpu = _("Processor"), df = _("Disk Space Usage"), disk = _("Disk Usage"), irq = _("Interrupts"), processes = _("Processes"), load = _("System Load"), } luci.template.render("admin_statistics/systemplugins", {plugins=plugins}) end function statistics_networkplugins() local translate = luci.i18n.translate local plugins = { interface = _("Interfaces"), netlink = _("Netlink"), iptables = _("Firewall"), tcpconns = _("TCP Connections"), ping = _("Ping"), dns = _("DNS"), wireless = _("Wireless") } luci.template.render("admin_statistics/networkplugins", {plugins=plugins}) end function statistics_render() require("luci.statistics.rrdtool") require("luci.template") require("luci.model.uci") local vars = luci.http.formvalue() local req = luci.dispatcher.context.request local path = luci.dispatcher.context.path local uci = luci.model.uci.cursor() local spans = luci.util.split( uci:get( "luci_statistics", "collectd_rrdtool", "RRATimespans" ), "%s+", nil, true ) local span = vars.timespan or uci:get( "luci_statistics", "rrdtool", "default_timespan" ) or spans[1] local graph = luci.statistics.rrdtool.Graph( luci.util.parse_units( span ) ) -- deliver image if vars.img then local l12 = require "luci.ltn12" local png = io.open(graph.opts.imgpath .. "/" .. vars.img:gsub("%.+", "."), "r") if png then luci.http.prepare_content("image/png") l12.pump.all(l12.source.file(png), luci.http.write) png:close() end return end local plugin, instances local images = { } -- find requested plugin and instance for i, p in ipairs( luci.dispatcher.context.path ) do if luci.dispatcher.context.path[i] == "graph" then plugin = luci.dispatcher.context.path[i+1] instances = { luci.dispatcher.context.path[i+2] } end end -- no instance requested, find all instances if #instances == 0 then instances = { graph.tree:plugin_instances( plugin )[1] } -- index instance requested elseif instances[1] == "-" then instances[1] = "" end -- render graphs for i, inst in ipairs( instances ) do for i, img in ipairs( graph:render( plugin, inst ) ) do table.insert( images, graph:strippngpath( img ) ) end end luci.template.render( "public_statistics/graph", { images = images, plugin = plugin, timespans = spans, current_timespan = span } ) end
--[[ Luci statistics - statistics controller module (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.controller.luci_statistics.luci_statistics", package.seeall) function index() require("nixio.fs") require("luci.util") require("luci.statistics.datatree") -- get rrd data tree local tree = luci.statistics.datatree.Instance() -- override entry(): check for existance <plugin>.so where <plugin> is derived from the called path function _entry( path, ... ) local file = path[5] or path[4] if nixio.fs.access( "/usr/lib/collectd/" .. file .. ".so" ) then entry( path, ... ) end end local labels = { s_output = _("Output plugins"), s_system = _("System plugins"), s_network = _("Network plugins"), rrdtool = _("RRDTool"), network = _("Network"), unixsock = _("UnixSock"), csv = _("CSV Output"), exec = _("Exec"), email = _("Email"), cpu = _("Processor"), df = _("Disk Space Usage"), disk = _("Disk Usage"), irq = _("Interrupts"), processes = _("Processes"), load = _("System Load"), interface = _("Interfaces"), netlink = _("Netlink"), iptables = _("Firewall"), tcpconns = _("TCP Connections"), ping = _("Ping"), dns = _("DNS"), wireless = _("Wireless") } -- our collectd menu local collectd_menu = { output = { "rrdtool", "network", "unixsock", "csv" }, system = { "exec", "email", "cpu", "df", "disk", "irq", "processes", "load" }, network = { "interface", "netlink", "iptables", "tcpconns", "ping", "dns", "wireless" } } -- create toplevel menu nodes local st = entry({"admin", "statistics"}, call("statistics_index"), _("Statistics"), 80) st.i18n = "statistics" st.index = true entry({"admin", "statistics", "collectd"}, cbi("luci_statistics/collectd"), _("Collectd"), 10).subindex = true -- populate collectd plugin menu local index = 1 for section, plugins in luci.util.kspairs( collectd_menu ) do local e = entry( { "admin", "statistics", "collectd", section }, call( "statistics_" .. section .. "plugins" ), labels["s_"..section], index * 10 ) e.index = true e.i18n = "rrdtool" for j, plugin in luci.util.vspairs( plugins ) do _entry( { "admin", "statistics", "collectd", section, plugin }, cbi("luci_statistics/" .. plugin ), labels[plugin], j * 10 ) end index = index + 1 end -- output views local page = entry( { "admin", "statistics", "graph" }, call("statistics_index"), _("Graphs"), 80) page.i18n = "statistics" page.setuser = "nobody" page.setgroup = "nogroup" local vars = luci.http.formvalue(nil, true) local span = vars.timespan or nil for i, plugin in luci.util.vspairs( tree:plugins() ) do -- get plugin instances local instances = tree:plugin_instances( plugin ) -- plugin menu entry entry( { "admin", "statistics", "graph", plugin }, call("statistics_render"), labels[plugin], i ).query = { timespan = span } -- if more then one instance is found then generate submenu if #instances > 1 then for j, inst in luci.util.vspairs(instances) do -- instance menu entry entry( { "admin", "statistics", "graph", plugin, inst }, call("statistics_render"), inst, j ).query = { timespan = span } end end end end function statistics_index() luci.template.render("admin_statistics/index") end function statistics_outputplugins() local translate = luci.i18n.translate local plugins = { rrdtool = translate("RRDTool"), network = translate("Network"), unixsock = translate("UnixSock"), csv = translate("CSV Output") } luci.template.render("admin_statistics/outputplugins", {plugins=plugins}) end function statistics_systemplugins() local translate = luci.i18n.translate local plugins = { exec = translate("Exec"), email = translate("Email"), cpu = translate("Processor"), df = translate("Disk Space Usage"), disk = translate("Disk Usage"), irq = translate("Interrupts"), processes = translate("Processes"), load = translate("System Load"), } luci.template.render("admin_statistics/systemplugins", {plugins=plugins}) end function statistics_networkplugins() local translate = luci.i18n.translate local plugins = { interface = translate("Interfaces"), netlink = translate("Netlink"), iptables = translate("Firewall"), tcpconns = translate("TCP Connections"), ping = translate("Ping"), dns = translate("DNS"), wireless = translate("Wireless") } luci.template.render("admin_statistics/networkplugins", {plugins=plugins}) end function statistics_render() require("luci.statistics.rrdtool") require("luci.template") require("luci.model.uci") local vars = luci.http.formvalue() local req = luci.dispatcher.context.request local path = luci.dispatcher.context.path local uci = luci.model.uci.cursor() local spans = luci.util.split( uci:get( "luci_statistics", "collectd_rrdtool", "RRATimespans" ), "%s+", nil, true ) local span = vars.timespan or uci:get( "luci_statistics", "rrdtool", "default_timespan" ) or spans[1] local graph = luci.statistics.rrdtool.Graph( luci.util.parse_units( span ) ) -- deliver image if vars.img then local l12 = require "luci.ltn12" local png = io.open(graph.opts.imgpath .. "/" .. vars.img:gsub("%.+", "."), "r") if png then luci.http.prepare_content("image/png") l12.pump.all(l12.source.file(png), luci.http.write) png:close() end return end local plugin, instances local images = { } -- find requested plugin and instance for i, p in ipairs( luci.dispatcher.context.path ) do if luci.dispatcher.context.path[i] == "graph" then plugin = luci.dispatcher.context.path[i+1] instances = { luci.dispatcher.context.path[i+2] } end end -- no instance requested, find all instances if #instances == 0 then instances = { graph.tree:plugin_instances( plugin )[1] } -- index instance requested elseif instances[1] == "-" then instances[1] = "" end -- render graphs for i, inst in ipairs( instances ) do for i, img in ipairs( graph:render( plugin, inst ) ) do table.insert( images, graph:strippngpath( img ) ) end end luci.template.render( "public_statistics/graph", { images = images, plugin = plugin, timespans = spans, current_timespan = span } ) end
applications/luci-statistics: fix translation issues in controller
applications/luci-statistics: fix translation issues in controller
Lua
apache-2.0
artynet/luci,urueedi/luci,rogerpueyo/luci,Kyklas/luci-proto-hso,jchuang1977/luci-1,Wedmer/luci,Kyklas/luci-proto-hso,aircross/OpenWrt-Firefly-LuCI,david-xiao/luci,rogerpueyo/luci,cshore-firmware/openwrt-luci,tobiaswaldvogel/luci,artynet/luci,cshore/luci,oyido/luci,lbthomsen/openwrt-luci,ollie27/openwrt_luci,taiha/luci,kuoruan/lede-luci,thess/OpenWrt-luci,aa65535/luci,Wedmer/luci,opentechinstitute/luci,urueedi/luci,openwrt/luci,maxrio/luci981213,Noltari/luci,cappiewu/luci,keyidadi/luci,Noltari/luci,maxrio/luci981213,981213/luci-1,Kyklas/luci-proto-hso,teslamint/luci,fkooman/luci,LuttyYang/luci,thesabbir/luci,cappiewu/luci,palmettos/cnLuCI,db260179/openwrt-bpi-r1-luci,ff94315/luci-1,db260179/openwrt-bpi-r1-luci,oyido/luci,teslamint/luci,tobiaswaldvogel/luci,oyido/luci,david-xiao/luci,jchuang1977/luci-1,keyidadi/luci,opentechinstitute/luci,florian-shellfire/luci,Noltari/luci,dwmw2/luci,nwf/openwrt-luci,dwmw2/luci,lbthomsen/openwrt-luci,Wedmer/luci,981213/luci-1,cshore-firmware/openwrt-luci,daofeng2015/luci,thess/OpenWrt-luci,jorgifumi/luci,keyidadi/luci,marcel-sch/luci,ReclaimYourPrivacy/cloak-luci,jlopenwrtluci/luci,keyidadi/luci,daofeng2015/luci,harveyhu2012/luci,Hostle/luci,maxrio/luci981213,remakeelectric/luci,dismantl/luci-0.12,oneru/luci,Wedmer/luci,tobiaswaldvogel/luci,thess/OpenWrt-luci,Sakura-Winkey/LuCI,keyidadi/luci,RuiChen1113/luci,MinFu/luci,male-puppies/luci,Hostle/openwrt-luci-multi-user,openwrt-es/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,fkooman/luci,oneru/luci,LazyZhu/openwrt-luci-trunk-mod,hnyman/luci,dwmw2/luci,joaofvieira/luci,slayerrensky/luci,joaofvieira/luci,ReclaimYourPrivacy/cloak-luci,nmav/luci,Hostle/luci,bright-things/ionic-luci,cshore/luci,Sakura-Winkey/LuCI,joaofvieira/luci,jorgifumi/luci,rogerpueyo/luci,cappiewu/luci,chris5560/openwrt-luci,wongsyrone/luci-1,Noltari/luci,ff94315/luci-1,bittorf/luci,fkooman/luci,mumuqz/luci,palmettos/cnLuCI,deepak78/new-luci,bittorf/luci,harveyhu2012/luci,db260179/openwrt-bpi-r1-luci,nmav/luci,bright-things/ionic-luci,chris5560/openwrt-luci,slayerrensky/luci,deepak78/new-luci,jlopenwrtluci/luci,dwmw2/luci,male-puppies/luci,bright-things/ionic-luci,keyidadi/luci,shangjiyu/luci-with-extra,aircross/OpenWrt-Firefly-LuCI,ollie27/openwrt_luci,LazyZhu/openwrt-luci-trunk-mod,ollie27/openwrt_luci,kuoruan/lede-luci,dismantl/luci-0.12,bittorf/luci,Hostle/openwrt-luci-multi-user,harveyhu2012/luci,fkooman/luci,hnyman/luci,artynet/luci,openwrt-es/openwrt-luci,jorgifumi/luci,ReclaimYourPrivacy/cloak-luci,Kyklas/luci-proto-hso,Noltari/luci,lcf258/openwrtcn,zhaoxx063/luci,LazyZhu/openwrt-luci-trunk-mod,teslamint/luci,urueedi/luci,db260179/openwrt-bpi-r1-luci,NeoRaider/luci,schidler/ionic-luci,tcatm/luci,forward619/luci,taiha/luci,joaofvieira/luci,bright-things/ionic-luci,kuoruan/luci,tcatm/luci,cshore/luci,tcatm/luci,cshore-firmware/openwrt-luci,aa65535/luci,palmettos/cnLuCI,remakeelectric/luci,kuoruan/lede-luci,chris5560/openwrt-luci,cshore-firmware/openwrt-luci,daofeng2015/luci,forward619/luci,ReclaimYourPrivacy/cloak-luci,bittorf/luci,Kyklas/luci-proto-hso,remakeelectric/luci,oyido/luci,cshore-firmware/openwrt-luci,dwmw2/luci,openwrt-es/openwrt-luci,kuoruan/lede-luci,deepak78/new-luci,ff94315/luci-1,chris5560/openwrt-luci,wongsyrone/luci-1,kuoruan/luci,lcf258/openwrtcn,daofeng2015/luci,david-xiao/luci,maxrio/luci981213,LuttyYang/luci,urueedi/luci,forward619/luci,nmav/luci,lbthomsen/openwrt-luci,zhaoxx063/luci,LuttyYang/luci,RedSnake64/openwrt-luci-packages,ff94315/luci-1,marcel-sch/luci,daofeng2015/luci,kuoruan/lede-luci,dwmw2/luci,thess/OpenWrt-luci,ff94315/luci-1,sujeet14108/luci,florian-shellfire/luci,NeoRaider/luci,urueedi/luci,oyido/luci,db260179/openwrt-bpi-r1-luci,schidler/ionic-luci,taiha/luci,sujeet14108/luci,remakeelectric/luci,thesabbir/luci,tcatm/luci,obsy/luci,db260179/openwrt-bpi-r1-luci,zhaoxx063/luci,thess/OpenWrt-luci,MinFu/luci,remakeelectric/luci,lcf258/openwrtcn,mumuqz/luci,Wedmer/luci,jorgifumi/luci,thess/OpenWrt-luci,florian-shellfire/luci,male-puppies/luci,shangjiyu/luci-with-extra,ff94315/luci-1,mumuqz/luci,obsy/luci,palmettos/cnLuCI,RedSnake64/openwrt-luci-packages,opentechinstitute/luci,tobiaswaldvogel/luci,ReclaimYourPrivacy/cloak-luci,kuoruan/luci,tobiaswaldvogel/luci,Wedmer/luci,wongsyrone/luci-1,joaofvieira/luci,palmettos/cnLuCI,palmettos/test,jchuang1977/luci-1,chris5560/openwrt-luci,oneru/luci,oneru/luci,marcel-sch/luci,jlopenwrtluci/luci,obsy/luci,artynet/luci,mumuqz/luci,bittorf/luci,Noltari/luci,david-xiao/luci,maxrio/luci981213,ollie27/openwrt_luci,nwf/openwrt-luci,981213/luci-1,jorgifumi/luci,981213/luci-1,opentechinstitute/luci,Hostle/openwrt-luci-multi-user,shangjiyu/luci-with-extra,hnyman/luci,urueedi/luci,slayerrensky/luci,jlopenwrtluci/luci,bittorf/luci,forward619/luci,cshore/luci,Noltari/luci,palmettos/cnLuCI,schidler/ionic-luci,lbthomsen/openwrt-luci,daofeng2015/luci,bright-things/ionic-luci,Hostle/openwrt-luci-multi-user,shangjiyu/luci-with-extra,jlopenwrtluci/luci,RedSnake64/openwrt-luci-packages,nmav/luci,deepak78/new-luci,sujeet14108/luci,palmettos/test,wongsyrone/luci-1,Kyklas/luci-proto-hso,aa65535/luci,joaofvieira/luci,tcatm/luci,chris5560/openwrt-luci,taiha/luci,ollie27/openwrt_luci,deepak78/new-luci,daofeng2015/luci,maxrio/luci981213,thesabbir/luci,LuttyYang/luci,LazyZhu/openwrt-luci-trunk-mod,tobiaswaldvogel/luci,Sakura-Winkey/LuCI,lcf258/openwrtcn,shangjiyu/luci-with-extra,slayerrensky/luci,rogerpueyo/luci,dismantl/luci-0.12,Wedmer/luci,Sakura-Winkey/LuCI,male-puppies/luci,RuiChen1113/luci,zhaoxx063/luci,shangjiyu/luci-with-extra,slayerrensky/luci,male-puppies/luci,aa65535/luci,Sakura-Winkey/LuCI,openwrt-es/openwrt-luci,jlopenwrtluci/luci,bittorf/luci,chris5560/openwrt-luci,obsy/luci,981213/luci-1,Noltari/luci,taiha/luci,LazyZhu/openwrt-luci-trunk-mod,oneru/luci,tcatm/luci,openwrt-es/openwrt-luci,nwf/openwrt-luci,sujeet14108/luci,NeoRaider/luci,cshore/luci,opentechinstitute/luci,jlopenwrtluci/luci,palmettos/test,artynet/luci,openwrt/luci,RedSnake64/openwrt-luci-packages,palmettos/cnLuCI,openwrt/luci,aircross/OpenWrt-Firefly-LuCI,MinFu/luci,981213/luci-1,cshore-firmware/openwrt-luci,oyido/luci,sujeet14108/luci,cappiewu/luci,MinFu/luci,sujeet14108/luci,artynet/luci,marcel-sch/luci,openwrt-es/openwrt-luci,marcel-sch/luci,artynet/luci,male-puppies/luci,nmav/luci,schidler/ionic-luci,palmettos/cnLuCI,lbthomsen/openwrt-luci,kuoruan/luci,maxrio/luci981213,artynet/luci,oneru/luci,RedSnake64/openwrt-luci-packages,keyidadi/luci,kuoruan/lede-luci,schidler/ionic-luci,rogerpueyo/luci,rogerpueyo/luci,thesabbir/luci,aa65535/luci,deepak78/new-luci,openwrt/luci,LuttyYang/luci,cshore-firmware/openwrt-luci,lcf258/openwrtcn,dwmw2/luci,Hostle/openwrt-luci-multi-user,teslamint/luci,hnyman/luci,ollie27/openwrt_luci,shangjiyu/luci-with-extra,sujeet14108/luci,ReclaimYourPrivacy/cloak-luci,ollie27/openwrt_luci,urueedi/luci,MinFu/luci,obsy/luci,openwrt/luci,thess/OpenWrt-luci,palmettos/test,jchuang1977/luci-1,Hostle/luci,mumuqz/luci,jorgifumi/luci,marcel-sch/luci,LuttyYang/luci,zhaoxx063/luci,RuiChen1113/luci,zhaoxx063/luci,lbthomsen/openwrt-luci,hnyman/luci,zhaoxx063/luci,david-xiao/luci,harveyhu2012/luci,fkooman/luci,Sakura-Winkey/LuCI,RedSnake64/openwrt-luci-packages,nmav/luci,ReclaimYourPrivacy/cloak-luci,Noltari/luci,male-puppies/luci,fkooman/luci,fkooman/luci,thesabbir/luci,aa65535/luci,bittorf/luci,opentechinstitute/luci,RuiChen1113/luci,slayerrensky/luci,RuiChen1113/luci,kuoruan/lede-luci,oyido/luci,sujeet14108/luci,aircross/OpenWrt-Firefly-LuCI,lcf258/openwrtcn,taiha/luci,openwrt-es/openwrt-luci,nwf/openwrt-luci,rogerpueyo/luci,thesabbir/luci,jchuang1977/luci-1,forward619/luci,oyido/luci,cshore/luci,kuoruan/lede-luci,obsy/luci,Hostle/openwrt-luci-multi-user,deepak78/new-luci,LuttyYang/luci,LazyZhu/openwrt-luci-trunk-mod,tcatm/luci,ollie27/openwrt_luci,david-xiao/luci,db260179/openwrt-bpi-r1-luci,harveyhu2012/luci,hnyman/luci,obsy/luci,MinFu/luci,mumuqz/luci,marcel-sch/luci,lcf258/openwrtcn,LazyZhu/openwrt-luci-trunk-mod,maxrio/luci981213,lcf258/openwrtcn,MinFu/luci,dismantl/luci-0.12,Hostle/luci,david-xiao/luci,cappiewu/luci,db260179/openwrt-bpi-r1-luci,ff94315/luci-1,wongsyrone/luci-1,mumuqz/luci,artynet/luci,nmav/luci,tcatm/luci,ReclaimYourPrivacy/cloak-luci,Sakura-Winkey/LuCI,joaofvieira/luci,981213/luci-1,forward619/luci,taiha/luci,kuoruan/luci,cappiewu/luci,opentechinstitute/luci,opentechinstitute/luci,chris5560/openwrt-luci,openwrt-es/openwrt-luci,taiha/luci,teslamint/luci,cshore/luci,RuiChen1113/luci,jlopenwrtluci/luci,lbthomsen/openwrt-luci,jorgifumi/luci,nwf/openwrt-luci,dismantl/luci-0.12,kuoruan/luci,openwrt/luci,hnyman/luci,schidler/ionic-luci,daofeng2015/luci,LazyZhu/openwrt-luci-trunk-mod,aircross/OpenWrt-Firefly-LuCI,harveyhu2012/luci,Hostle/openwrt-luci-multi-user,florian-shellfire/luci,cappiewu/luci,dwmw2/luci,remakeelectric/luci,Hostle/luci,jchuang1977/luci-1,lbthomsen/openwrt-luci,NeoRaider/luci,palmettos/test,nmav/luci,oneru/luci,urueedi/luci,nwf/openwrt-luci,ff94315/luci-1,harveyhu2012/luci,NeoRaider/luci,wongsyrone/luci-1,mumuqz/luci,slayerrensky/luci,RuiChen1113/luci,oneru/luci,florian-shellfire/luci,LuttyYang/luci,fkooman/luci,palmettos/test,keyidadi/luci,lcf258/openwrtcn,nwf/openwrt-luci,joaofvieira/luci,kuoruan/luci,jchuang1977/luci-1,teslamint/luci,palmettos/test,male-puppies/luci,florian-shellfire/luci,hnyman/luci,dismantl/luci-0.12,RedSnake64/openwrt-luci-packages,nwf/openwrt-luci,wongsyrone/luci-1,MinFu/luci,teslamint/luci,palmettos/test,cappiewu/luci,david-xiao/luci,Wedmer/luci,rogerpueyo/luci,bright-things/ionic-luci,cshore-firmware/openwrt-luci,bright-things/ionic-luci,openwrt/luci,NeoRaider/luci,slayerrensky/luci,nmav/luci,bright-things/ionic-luci,shangjiyu/luci-with-extra,jchuang1977/luci-1,Hostle/openwrt-luci-multi-user,remakeelectric/luci,NeoRaider/luci,aircross/OpenWrt-Firefly-LuCI,marcel-sch/luci,schidler/ionic-luci,tobiaswaldvogel/luci,forward619/luci,kuoruan/luci,dismantl/luci-0.12,obsy/luci,forward619/luci,teslamint/luci,remakeelectric/luci,wongsyrone/luci-1,Sakura-Winkey/LuCI,tobiaswaldvogel/luci,florian-shellfire/luci,thess/OpenWrt-luci,Hostle/luci,schidler/ionic-luci,Hostle/luci,zhaoxx063/luci,Hostle/luci,aa65535/luci,NeoRaider/luci,florian-shellfire/luci,RuiChen1113/luci,jorgifumi/luci,Kyklas/luci-proto-hso,thesabbir/luci,openwrt/luci,cshore/luci,aa65535/luci,lcf258/openwrtcn,thesabbir/luci,deepak78/new-luci
86b11f36c902a0bd4f3a6be18e912a6e99b72396
util/debug.lua
util/debug.lua
-- Variables ending with these names will not -- have their values printed ('password' includes -- 'new_password', etc.) local censored_names = { password = true; passwd = true; pass = true; pwd = true; }; local optimal_line_length = 65; local termcolours = require "util.termcolours"; local getstring = termcolours.getstring; local styles; do _ = termcolours.getstyle; styles = { boundary_padding = _("bright"); filename = _("bright", "blue"); level_num = _("green"); funcname = _("yellow"); location = _("yellow"); }; end module("debugx", package.seeall); function get_locals_table(level) level = level + 1; -- Skip this function itself local locals = {}; for local_num = 1, math.huge do local name, value = debug.getlocal(level, local_num); if not name then break; end table.insert(locals, { name = name, value = value }); end return locals; end function get_upvalues_table(func) local upvalues = {}; if func then for upvalue_num = 1, math.huge do local name, value = debug.getupvalue(func, upvalue_num); if not name then break; end table.insert(upvalues, { name = name, value = value }); end end return upvalues; end function string_from_var_table(var_table, max_line_len, indent_str) local var_string = {}; local col_pos = 0; max_line_len = max_line_len or math.huge; indent_str = "\n"..(indent_str or ""); for _, var in ipairs(var_table) do local name, value = var.name, var.value; if name:sub(1,1) ~= "(" then if type(value) == "string" then if censored_names[name:match("%a+$")] then value = "<hidden>"; else value = ("%q"):format(value); end else value = tostring(value); end if #value > max_line_len then value = value:sub(1, max_line_len-3).."…"; end local str = ("%s = %s"):format(name, tostring(value)); col_pos = col_pos + #str; if col_pos > max_line_len then table.insert(var_string, indent_str); col_pos = 0; end table.insert(var_string, str); end end if #var_string == 0 then return nil; else return "{ "..table.concat(var_string, ", "):gsub(indent_str..", ", indent_str).." }"; end end function get_traceback_table(thread, start_level) local levels = {}; for level = start_level, math.huge do local info; if thread then info = debug.getinfo(thread, level); else info = debug.getinfo(level+1); end if not info then break; end levels[(level-start_level)+1] = { level = level; info = info; locals = not thread and get_locals_table(level+1); upvalues = get_upvalues_table(info.func); }; end return levels; end function traceback(...) local ok, ret = pcall(_traceback, ...); if not ok then return "Error in error handling: "..ret; end return ret; end local function build_source_boundary_marker(last_source_desc) local padding = string.rep("-", math.floor(((optimal_line_length - 6) - #last_source_desc)/2)); return getstring(styles.boundary_padding, "v"..padding).." "..getstring(styles.filename, last_source_desc).." "..getstring(styles.boundary_padding, padding..(#last_source_desc%2==0 and "-v" or "v ")); end function _traceback(thread, message, level) -- Lua manual says: debug.traceback ([thread,] [message [, level]]) -- I fathom this to mean one of: -- () -- (thread) -- (message, level) -- (thread, message, level) if thread == nil then -- Defaults thread, message, level = coroutine.running(), message, level; elseif type(thread) == "string" then thread, message, level = coroutine.running(), thread, message; elseif type(thread) ~= "thread" then return nil; -- debug.traceback() does this end level = level or 0; message = message and (message.."\n") or ""; -- +3 counts for this function, and the pcall() and wrapper above us, the +1... I don't know. local levels = get_traceback_table(thread, level+(thread == nil and 4 or 0)); local last_source_desc; local lines = {}; for nlevel, level in ipairs(levels) do local info = level.info; local line = "..."; local func_type = info.namewhat.." "; local source_desc = (info.short_src == "[C]" and "C code") or info.short_src or "Unknown"; if func_type == " " then func_type = ""; end; if info.short_src == "[C]" then line = "[ C ] "..func_type.."C function "..getstring(styles.location, (info.name and ("%q"):format(info.name) or "(unknown name)")); elseif info.what == "main" then line = "[Lua] "..getstring(styles.location, info.short_src.." line "..info.currentline); else local name = info.name or " "; if name ~= " " then name = ("%q"):format(name); end if func_type == "global " or func_type == "local " then func_type = func_type.."function "; end line = "[Lua] "..getstring(styles.location, info.short_src.." line "..info.currentline).." in "..func_type..getstring(styles.funcname, name).." (defined on line "..info.linedefined..")"; end if source_desc ~= last_source_desc then -- Venturing into a new source, add marker for previous last_source_desc = source_desc; table.insert(lines, "\t "..build_source_boundary_marker(last_source_desc)); end nlevel = nlevel-1; table.insert(lines, "\t"..(nlevel==0 and ">" or " ")..getstring(styles.level_num, "("..nlevel..") ")..line); local npadding = (" "):rep(#tostring(nlevel)); if level.locals then local locals_str = string_from_var_table(level.locals, optimal_line_length, "\t "..npadding); if locals_str then table.insert(lines, "\t "..npadding.."Locals: "..locals_str); end end local upvalues_str = string_from_var_table(level.upvalues, optimal_line_length, "\t "..npadding); if upvalues_str then table.insert(lines, "\t "..npadding.."Upvals: "..upvalues_str); end end -- table.insert(lines, "\t "..build_source_boundary_marker(last_source_desc)); return message.."stack traceback:\n"..table.concat(lines, "\n"); end function use() debug.traceback = traceback; end return _M;
-- Variables ending with these names will not -- have their values printed ('password' includes -- 'new_password', etc.) local censored_names = { password = true; passwd = true; pass = true; pwd = true; }; local optimal_line_length = 65; local termcolours = require "util.termcolours"; local getstring = termcolours.getstring; local styles; do _ = termcolours.getstyle; styles = { boundary_padding = _("bright"); filename = _("bright", "blue"); level_num = _("green"); funcname = _("yellow"); location = _("yellow"); }; end module("debugx", package.seeall); function get_locals_table(thread, level) if not thread then level = level + 1; -- Skip this function itself end local locals = {}; for local_num = 1, math.huge do local name, value = debug.getlocal(thread, level, local_num); if not name then break; end table.insert(locals, { name = name, value = value }); end return locals; end function get_upvalues_table(func) local upvalues = {}; if func then for upvalue_num = 1, math.huge do local name, value = debug.getupvalue(func, upvalue_num); if not name then break; end table.insert(upvalues, { name = name, value = value }); end end return upvalues; end function string_from_var_table(var_table, max_line_len, indent_str) local var_string = {}; local col_pos = 0; max_line_len = max_line_len or math.huge; indent_str = "\n"..(indent_str or ""); for _, var in ipairs(var_table) do local name, value = var.name, var.value; if name:sub(1,1) ~= "(" then if type(value) == "string" then if censored_names[name:match("%a+$")] then value = "<hidden>"; else value = ("%q"):format(value); end else value = tostring(value); end if #value > max_line_len then value = value:sub(1, max_line_len-3).."…"; end local str = ("%s = %s"):format(name, tostring(value)); col_pos = col_pos + #str; if col_pos > max_line_len then table.insert(var_string, indent_str); col_pos = 0; end table.insert(var_string, str); end end if #var_string == 0 then return nil; else return "{ "..table.concat(var_string, ", "):gsub(indent_str..", ", indent_str).." }"; end end function get_traceback_table(thread, start_level) local levels = {}; for level = start_level, math.huge do local info; if thread then info = debug.getinfo(thread, level); else info = debug.getinfo(level+1); end if not info then break; end levels[(level-start_level)+1] = { level = level; info = info; locals = get_locals_table(thread, level+(thread and 0 or 1)); upvalues = get_upvalues_table(info.func); }; end return levels; end function traceback(...) local ok, ret = pcall(_traceback, ...); if not ok then return "Error in error handling: "..ret; end return ret; end local function build_source_boundary_marker(last_source_desc) local padding = string.rep("-", math.floor(((optimal_line_length - 6) - #last_source_desc)/2)); return getstring(styles.boundary_padding, "v"..padding).." "..getstring(styles.filename, last_source_desc).." "..getstring(styles.boundary_padding, padding..(#last_source_desc%2==0 and "-v" or "v ")); end function _traceback(thread, message, level) -- Lua manual says: debug.traceback ([thread,] [message [, level]]) -- I fathom this to mean one of: -- () -- (thread) -- (message, level) -- (thread, message, level) if thread == nil then -- Defaults thread, message, level = coroutine.running(), message, level; elseif type(thread) == "string" then thread, message, level = coroutine.running(), thread, message; elseif type(thread) ~= "thread" then return nil; -- debug.traceback() does this end level = level or 0; message = message and (message.."\n") or ""; -- +3 counts for this function, and the pcall() and wrapper above us, the +1... I don't know. local levels = get_traceback_table(thread, level+(thread == nil and 4 or 0)); local last_source_desc; local lines = {}; for nlevel, level in ipairs(levels) do local info = level.info; local line = "..."; local func_type = info.namewhat.." "; local source_desc = (info.short_src == "[C]" and "C code") or info.short_src or "Unknown"; if func_type == " " then func_type = ""; end; if info.short_src == "[C]" then line = "[ C ] "..func_type.."C function "..getstring(styles.location, (info.name and ("%q"):format(info.name) or "(unknown name)")); elseif info.what == "main" then line = "[Lua] "..getstring(styles.location, info.short_src.." line "..info.currentline); else local name = info.name or " "; if name ~= " " then name = ("%q"):format(name); end if func_type == "global " or func_type == "local " then func_type = func_type.."function "; end line = "[Lua] "..getstring(styles.location, info.short_src.." line "..info.currentline).." in "..func_type..getstring(styles.funcname, name).." (defined on line "..info.linedefined..")"; end if source_desc ~= last_source_desc then -- Venturing into a new source, add marker for previous last_source_desc = source_desc; table.insert(lines, "\t "..build_source_boundary_marker(last_source_desc)); end nlevel = nlevel-1; table.insert(lines, "\t"..(nlevel==0 and ">" or " ")..getstring(styles.level_num, "("..nlevel..") ")..line); local npadding = (" "):rep(#tostring(nlevel)); if level.locals then local locals_str = string_from_var_table(level.locals, optimal_line_length, "\t "..npadding); if locals_str then table.insert(lines, "\t "..npadding.."Locals: "..locals_str); end end local upvalues_str = string_from_var_table(level.upvalues, optimal_line_length, "\t "..npadding); if upvalues_str then table.insert(lines, "\t "..npadding.."Upvals: "..upvalues_str); end end -- table.insert(lines, "\t "..build_source_boundary_marker(last_source_desc)); return message.."stack traceback:\n"..table.concat(lines, "\n"); end function use() debug.traceback = traceback; end return _M;
util.debug: Further fix to display locals in extended tracebacks
util.debug: Further fix to display locals in extended tracebacks
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
d704cae460d2cbdd991b8c4aea22af9238d78c74
rapidshare.lua
rapidshare.lua
dofile("urlcode.lua") dofile("table_show.lua") local url_count = 0 local tries = 0 local downloaded = {} local addedtolist = {} read_file = function(file) if file then local f = assert(io.open(file)) local data = f:read("*all") f:close() return data else return "" end end wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} local html = nil local function check(newurl) if (downloaded[newurl] ~= true and addedtolist[newurl] ~= true) then table.insert(urls, { url=newurl }) addedtolist[newurl] = true end end if string.match(url, "https?://rapid%-search%-engine%.com/") then html = read_file(file) for newurl in string.gmatch(html, '"(https?://rapidshare%.com/[^"]+)"') do check(newurl) end for newurl in string.gmatch(html, '"(https?://www%.rapidshare%.com/[^"]+)"') do check(newurl) end end return urls end wget.callbacks.httploop_result = function(url, err, http_stat) -- NEW for 2014: Slightly more verbose messages because people keep -- complaining that it's not moving or not working local status_code = http_stat["statcode"] last_http_statcode = status_code url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n") io.stdout:flush() if (status_code >= 200 and status_code <= 399) then downloaded[url["url"]] = true end if status_code >= 500 or (status_code >= 400 and status_code ~= 404) then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 5") tries = tries + 1 if tries >= 20 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.ABORT else return wget.actions.CONTINUE end elseif status_code == 0 then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 10 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.ABORT else return wget.actions.CONTINUE end end tries = 0 -- We're okay; sleep a bit (if we have to) and continue -- local sleep_time = 0.1 * (math.random(500, 5000) / 100.0) local sleep_time = math.random(100, 200) -- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then -- -- We should be able to go fast on images since that's what a web browser does -- sleep_time = 0 -- end if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end
dofile("urlcode.lua") dofile("table_show.lua") local url_count = 0 local tries = 0 local downloaded = {} local addedtolist = {} read_file = function(file) if file then local f = assert(io.open(file)) local data = f:read("*all") f:close() return data else return "" end end wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} local html = nil local function check(newurl) if (downloaded[newurl] ~= true and addedtolist[newurl] ~= true) then table.insert(urls, { url=newurl }) addedtolist[newurl] = true end end if string.match(url, "https?://rapid%-search%-engine%.com/") then html = read_file(file) for newurl in string.gmatch(html, '"(https?://rapidshare%.com/[^"]+)"') do check(newurl) end for newurl in string.gmatch(html, '"(https?://www%.rapidshare%.com/[^"]+)"') do check(newurl) end end if string.match(url, "rapidshare%.com/files/[0-9]+/") then html = read_file(file) for newurl in string.gmatch(html, 'location="(https?://[^%.]+%.rapidshare%.com/cgi%-bin/[^"]+)"') do check(newurl) end end return urls end wget.callbacks.httploop_result = function(url, err, http_stat) -- NEW for 2014: Slightly more verbose messages because people keep -- complaining that it's not moving or not working local status_code = http_stat["statcode"] last_http_statcode = status_code url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n") io.stdout:flush() if (status_code >= 200 and status_code <= 399) then downloaded[url["url"]] = true end if status_code >= 500 or (status_code >= 400 and status_code ~= 404) then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 5") tries = tries + 1 if tries >= 20 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.ABORT else return wget.actions.CONTINUE end elseif status_code == 0 then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 10 then io.stdout:write("\nI give up...\n") io.stdout:flush() return wget.actions.ABORT else return wget.actions.CONTINUE end end tries = 0 -- We're okay; sleep a bit (if we have to) and continue -- local sleep_time = 0.1 * (math.random(500, 5000) / 100.0) local sleep_time = math.random(100, 200) -- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then -- -- We should be able to go fast on images since that's what a web browser does -- sleep_time = 0 -- end if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end
rapidshare.lua: fixes
rapidshare.lua: fixes
Lua
unlicense
ArchiveTeam/rapidshare-grab,ArchiveTeam/rapidshare-grab
797ac0160bdec88047b3e3a83ef42e882ee1fcb6
spec/helpers/perf/drivers/local.lua
spec/helpers/perf/drivers/local.lua
local perf = require("spec.helpers.perf") local pl_path = require("pl.path") local tools = require("kong.tools.utils") local helpers local _M = {} local mt = {__index = _M} local UPSTREAM_PORT = 62412 local WRK_SCRIPT_PREFIX = "/tmp/perf-wrk-" local KONG_ERROR_LOG_PATH = "/tmp/error.log" function _M.new(opts) return setmetatable({ opts = opts, log = perf.new_logger("[local]"), upstream_nginx_pid = nil, nginx_bin = nil, wrk_bin = nil, git_head = nil, git_stashed = false, systemtap_sanity_checked = false, systemtap_dest_path = nil, }, mt) end function _M:setup() local bin for _, test in ipairs({"nginx", "/usr/local/openresty/nginx/sbin/nginx"}) do bin, _ = perf.execute("which " .. test) if bin then self.nginx_bin = bin break end end if not self.nginx_bin then return nil, "nginx binary not found, either install nginx package or Kong" end bin = perf.execute("which wrk") if not bin then return nil, "wrk binary not found" end self.wrk_bin = bin bin = perf.execute("which git") if not bin then return nil, "git binary not found" end package.loaded["spec.helpers"] = nil helpers = require("spec.helpers") return helpers end function _M:teardown() if self.upstream_nginx_pid then local _, err = perf.execute("kill " .. self.upstream_nginx_pid) if err then return false, "stopping upstream: " .. err end self.upstream_nginx_pid = nil end perf.git_restore() perf.execute("rm -v " .. WRK_SCRIPT_PREFIX .. "*.lua", { logger = self.log.log_exec }) return self:stop_kong() end function _M:start_upstreams(conf, port_count) local listeners = {} for i=1,port_count do listeners[i] = ("listen %d reuseport;"):format(UPSTREAM_PORT+i-1) end listeners = table.concat(listeners, "\n") local nginx_conf_path = "/tmp/perf-test-nginx.conf" local nginx_prefix = "/tmp/perf-test-nginx" pl_path.mkdir(nginx_prefix .. "/logs") local f = io.open(nginx_conf_path, "w") f:write(([[ events {} pid nginx.pid; error_log error.log; http { access_log off; server { %s %s } } ]]):format(listeners, conf)) f:close() local res, err = perf.execute("nginx -c " .. nginx_conf_path .. " -p " .. nginx_prefix, { logger = self.log.log_exec }) if err then return false, "failed to start nginx: " .. err .. ": " .. (res or "nil") end f = io.open(nginx_prefix .. "/nginx.pid") local pid = f:read() f:close() if not tonumber(pid) then return false, "pid is not a number: " .. pid end self.upstream_nginx_pid = pid self.log.info("upstream started at PID: " .. pid) local uris = {} for i=1,port_count do uris[i] = "http://127.0.0.1:" .. UPSTREAM_PORT+i-1 end return uris end function _M:start_kong(version, kong_conf) if not version:startswith("git:") then return nil, "\"local\" driver only support testing between git commits, " .. "version should be prefixed with \"git:\"" end version = version:sub(#("git:")+1) perf.git_checkout(version) -- cleanup log file perf.execute("echo > /tmp/kong_error.log") kong_conf = kong_conf or {} kong_conf['proxy_access_log'] = "/dev/null" kong_conf['proxy_error_log'] = KONG_ERROR_LOG_PATH kong_conf['admin_error_log'] = KONG_ERROR_LOG_PATH return helpers.start_kong(kong_conf) end function _M:stop_kong() helpers.stop_kong() return true end function _M:get_start_load_cmd(stub, script, uri) if not uri then uri = string.format("http://%s:%s", helpers.get_proxy_ip(), helpers.get_proxy_port()) end local script_path if script then script_path = WRK_SCRIPT_PREFIX .. tools.random_string() .. ".lua" local f = assert(io.open(script_path, "w")) assert(f:write(script)) assert(f:close()) end script_path = script_path and ("-s " .. script_path) or "" return stub:format(script_path, uri) end local function check_systemtap_sanity(self) local bin, _ = perf.execute("which stap") if not bin then return nil, "systemtap binary not found" end -- try compile the kernel module local out, err = perf.execute("sudo stap -ve 'probe begin { print(\"hello\\n\"); exit();}'") if err then return nil, "systemtap failed to compile kernel module: " .. (out or "nil") .. " err: " .. (err or "nil") .. "\n Did you install gcc and kernel headers?" end local cmds = { "stat /tmp/stapxx || git clone https://github.com/Kong/stapxx /tmp/stapxx", "stat /tmp/perf-ost || git clone https://github.com/openresty/openresty-systemtap-toolkit /tmp/perf-ost", "stat /tmp/perf-fg || git clone https://github.com/brendangregg/FlameGraph /tmp/perf-fg" } for _, cmd in ipairs(cmds) do local _, err = perf.execute(cmd, { logger = self.log.log_exec }) if err then return nil, cmd .. " failed: " .. err end end return true end function _M:get_start_stapxx_cmd(sample, ...) if not self.systemtap_sanity_checked then local ok, err = check_systemtap_sanity(self) if not ok then return nil, err end self.systemtap_sanity_checked = true end -- find one of kong's child process hopefully it's a worker -- (does kong have cache loader/manager?) local pid, err = perf.execute("pid=$(cat servroot/pids/nginx.pid);" .. "cat /proc/$pid/task/$pid/children | awk '{print $1}'") if not pid then return nil, "failed to get Kong worker PID: " .. (err or "nil") end local args = table.concat({...}, " ") self.systemtap_dest_path = "/tmp/" .. tools.random_string() return "sudo /tmp/stapxx/stap++ /tmp/stapxx/samples/" .. sample .. " --skip-badvars -D MAXSKIPPED=1000000 -x " .. pid .. " " .. args .. " > " .. self.systemtap_dest_path .. ".bt" end function _M:get_wait_stapxx_cmd(timeout) return "lsmod | grep stap_" end function _M:generate_flamegraph(title, opts) local path = self.systemtap_dest_path self.systemtap_dest_path = nil local f = io.open(path .. ".bt") if not f or f:seek("end") == 0 then return nil, "systemtap output is empty, possibly no sample are captured" end f:close() local cmds = { "/tmp/perf-ost/fix-lua-bt " .. path .. ".bt > " .. path .. ".fbt", "/tmp/perf-fg/stackcollapse-stap.pl " .. path .. ".fbt > " .. path .. ".cbt", "/tmp/perf-fg/flamegraph.pl --title='" .. title .. "' " .. (opts or "") .. " " .. path .. ".cbt > " .. path .. ".svg", "cat " .. path .. ".svg", } local out, err for _, cmd in ipairs(cmds) do out, err = perf.execute(cmd, { logger = self.log.log_exec }) if err then return nil, cmd .. " failed: " .. err end end perf.execute("rm " .. path .. ".*") return out end function _M:save_error_log(path) return perf.execute("mv " .. KONG_ERROR_LOG_PATH .. " '" .. path .. "'", { logger = self.log.log_exec }) end return _M
local perf = require("spec.helpers.perf") local pl_path = require("pl.path") local tools = require("kong.tools.utils") local helpers local _M = {} local mt = {__index = _M} local UPSTREAM_PORT = 62412 local WRK_SCRIPT_PREFIX = "/tmp/perf-wrk-" local KONG_ERROR_LOG_PATH = "/tmp/error.log" function _M.new(opts) return setmetatable({ opts = opts, log = perf.new_logger("[local]"), upstream_nginx_pid = nil, nginx_bin = nil, wrk_bin = nil, git_head = nil, git_stashed = false, systemtap_sanity_checked = false, systemtap_dest_path = nil, }, mt) end function _M:setup() local bin for _, test in ipairs({"nginx", "/usr/local/openresty/nginx/sbin/nginx"}) do bin, _ = perf.execute("which " .. test) if bin then self.nginx_bin = bin break end end if not self.nginx_bin then return nil, "nginx binary not found, either install nginx package or Kong" end bin = perf.execute("which wrk") if not bin then return nil, "wrk binary not found" end self.wrk_bin = bin bin = perf.execute("which git") if not bin then return nil, "git binary not found" end package.loaded["spec.helpers"] = nil helpers = require("spec.helpers") return helpers end function _M:teardown() if self.upstream_nginx_pid then local _, err = perf.execute("kill " .. self.upstream_nginx_pid) if err then return false, "stopping upstream: " .. err end self.upstream_nginx_pid = nil end perf.git_restore() perf.execute("rm -v " .. WRK_SCRIPT_PREFIX .. "*.lua", { logger = self.log.log_exec }) return self:stop_kong() end function _M:start_upstreams(conf, port_count) local listeners = {} for i=1,port_count do listeners[i] = ("listen %d reuseport;"):format(UPSTREAM_PORT+i-1) end listeners = table.concat(listeners, "\n") local nginx_conf_path = "/tmp/perf-test-nginx.conf" local nginx_prefix = "/tmp/perf-test-nginx" pl_path.mkdir(nginx_prefix .. "/logs") local f = io.open(nginx_conf_path, "w") f:write(([[ events {} pid nginx.pid; error_log error.log; http { access_log off; server { %s %s } } ]]):format(listeners, conf)) f:close() local res, err = perf.execute("nginx -c " .. nginx_conf_path .. " -p " .. nginx_prefix, { logger = self.log.log_exec }) if err then return false, "failed to start nginx: " .. err .. ": " .. (res or "nil") end f = io.open(nginx_prefix .. "/nginx.pid") local pid = f:read() f:close() if not tonumber(pid) then return false, "pid is not a number: " .. pid end self.upstream_nginx_pid = pid self.log.info("upstream started at PID: " .. pid) local uris = {} for i=1,port_count do uris[i] = "http://127.0.0.1:" .. UPSTREAM_PORT+i-1 end return uris end function _M:start_kong(version, kong_conf) if not version:startswith("git:") then return nil, "\"local\" driver only support testing between git commits, " .. "version should be prefixed with \"git:\"" end version = version:sub(#("git:")+1) perf.git_checkout(version) -- cleanup log file perf.execute("echo > /tmp/kong_error.log") kong_conf = kong_conf or {} kong_conf['proxy_access_log'] = "/dev/null" kong_conf['proxy_error_log'] = KONG_ERROR_LOG_PATH kong_conf['admin_error_log'] = KONG_ERROR_LOG_PATH return helpers.start_kong(kong_conf) end function _M:stop_kong() helpers.stop_kong() return true end function _M:get_start_load_cmd(stub, script, uri) if not uri then uri = string.format("http://%s:%s", helpers.get_proxy_ip(), helpers.get_proxy_port()) end local script_path if script then script_path = WRK_SCRIPT_PREFIX .. tools.random_string() .. ".lua" local f = assert(io.open(script_path, "w")) assert(f:write(script)) assert(f:close()) end script_path = script_path and ("-s " .. script_path) or "" return stub:format(script_path, uri) end local function check_systemtap_sanity(self) local bin, _ = perf.execute("which stap") if not bin then return nil, "systemtap binary not found" end -- try compile the kernel module local out, err = perf.execute("sudo stap -ve 'probe begin { print(\"hello\\n\"); exit();}'") if err then return nil, "systemtap failed to compile kernel module: " .. (out or "nil") .. " err: " .. (err or "nil") .. "\n Did you install gcc and kernel headers?" end local cmds = { "stat /tmp/stapxx || git clone https://github.com/Kong/stapxx /tmp/stapxx", "stat /tmp/perf-ost || git clone https://github.com/openresty/openresty-systemtap-toolkit /tmp/perf-ost", "stat /tmp/perf-fg || git clone https://github.com/brendangregg/FlameGraph /tmp/perf-fg" } for _, cmd in ipairs(cmds) do local _, err = perf.execute(cmd, { logger = self.log.log_exec }) if err then return nil, cmd .. " failed: " .. err end end return true end function _M:get_start_stapxx_cmd(sample, ...) if not self.systemtap_sanity_checked then local ok, err = check_systemtap_sanity(self) if not ok then return nil, err end self.systemtap_sanity_checked = true end -- find one of kong's child process hopefully it's a worker -- (does kong have cache loader/manager?) local pid, err = perf.execute("pid=$(cat servroot/pids/nginx.pid);" .. "cat /proc/$pid/task/$pid/children | awk '{print $1}'") if not pid then return nil, "failed to get Kong worker PID: " .. (err or "nil") end local args = table.concat({...}, " ") self.systemtap_dest_path = "/tmp/" .. tools.random_string() return "sudo /tmp/stapxx/stap++ /tmp/stapxx/samples/" .. sample .. " --skip-badvars -D MAXSKIPPED=1000000 -x " .. pid .. " " .. args .. " > " .. self.systemtap_dest_path .. ".bt" end function _M:get_wait_stapxx_cmd(timeout) return "lsmod | grep stap_" end function _M:generate_flamegraph(title, opts) local path = self.systemtap_dest_path self.systemtap_dest_path = nil local f = io.open(path .. ".bt") if not f or f:seek("end") == 0 then return nil, "systemtap output is empty, possibly no sample are captured" end f:close() local cmds = { "/tmp/perf-ost/fix-lua-bt " .. path .. ".bt > " .. path .. ".fbt", "/tmp/perf-fg/stackcollapse-stap.pl " .. path .. ".fbt > " .. path .. ".cbt", "/tmp/perf-fg/flamegraph.pl --title='" .. title .. "' " .. (opts or "") .. " " .. path .. ".cbt > " .. path .. ".svg", } local err for _, cmd in ipairs(cmds) do _, err = perf.execute(cmd, { logger = self.log.log_exec }) if err then return nil, cmd .. " failed: " .. err end end local out, _ = perf.execute("cat " .. path .. ".svg") perf.execute("rm " .. path .. ".*") return out end function _M:save_error_log(path) return perf.execute("mv " .. KONG_ERROR_LOG_PATH .. " '" .. path .. "'", { logger = self.log.log_exec }) end return _M
tests(flamegraph) fix generate flamegraph in local driver (#8275)
tests(flamegraph) fix generate flamegraph in local driver (#8275) * fix flame graph tests in local driver * generate flame grah : cat cmd use empty opts * local driver will keep the same logic with terraform * style fix, make lint happy
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
7257f3de5b902bdbe7e4b34663c7a9e16a816ba6
test_scripts/Policies/HMI_PTU/010_PTU_retry_sequence_HMI_has_timeout_more_then_SDL_propr.lua
test_scripts/Policies/HMI_PTU/010_PTU_retry_sequence_HMI_has_timeout_more_then_SDL_propr.lua
--------------------------------------------------------------------------------------------------- -- Proposal: https://github.com/smartdevicelink/sdl_evolution/blob/master/proposals/0248-hmi-ptu-support.md -- -- Description: Retry strategy after failed HMI PTU on proprietary flow -- In case: -- 1. timeout_after_x_seconds is set to 4 seconds in preloaded file -- 2. secondsBetweenRetries is set to { 1, 2 } in preloaded file -- 3. Mobile app is registered and activated -- 4. PTU via HMI is started -- SDL does: -- a. start timeout_after_x_seconds timeout -- 5. Timeout expired -- SDL does: -- a. start retry strategy -- b. send SDL.OnStatusUpdate(UPDATE_NEDDED) to HMI -- c. send OnSystemRequest(Proprietary) to mobile app -- d. sends SDL.OnStatusUpdate(UPDATING) to HMI -- i. start timeout_for_first_try = timeout_after_x_seconds + secondsBetweenRetries[1] -- 6. Timeout expired -- SDL does: -- a. send SDL.OnStatusUpdate(UPDATE_NEDDED) to HMI -- b. send OnSystemRequest(Proprietary) to mobile app -- c. sends SDL.OnStatusUpdate(UPDATING) to HMI -- d. start timeout_for_second_try = timeout_for_first_try + secondsBetweenRetries[2] -- 7. Timeout expired -- SDL does: -- a. send SDL.OnStatusUpdate(UPDATE_NEDDED) to HMI --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require('user_modules/script_runner') local common = require('test_scripts/Policies/HMI_PTU/common_hmi_ptu') local test = require('testbase') --[[ Test Configuration ]] runner.testSettings.isSelfIncluded = false runner.testSettings.restrictions.sdlBuildOptions = { { extendedPolicy = { "PROPRIETARY" } } } --[[ Local Variables ]] local secondsBetweenRetries = { 1, 2 } -- in sec local timeout_after_x_seconds = 4 -- in sec local retryNotificationTime = {} local expectedTimeRetry = { -- in msec timeout_after_x_seconds*1000, (timeout_after_x_seconds + secondsBetweenRetries[1])*1000, (timeout_after_x_seconds*#secondsBetweenRetries + secondsBetweenRetries[1] + secondsBetweenRetries[2])*1000 } local inaccuracy = 500 -- in msec --[[ Local Functions ]] local function updatePreloadedTimeout(pTbl) pTbl.policy_table.module_config.timeout_after_x_seconds = timeout_after_x_seconds pTbl.policy_table.module_config.seconds_between_retries = secondsBetweenRetries end function common.registerApp() common.register() common.hmi():ExpectNotification("SDL.OnStatusUpdate", { status = "UPDATE_NEEDED" }, { status = "UPDATING" }) :Times(2) :Do(function(_, data) common.log("SDL->HMI:", "SDL.OnStatusUpdate(" .. data.params.status .. ")") if data.params.status == "UPDATING" then table.insert(retryNotificationTime, timestamp()) end end) end local function retrySequence() local reserveTime = 2000 local timeout = expectedTimeRetry[1] + expectedTimeRetry[2] + expectedTimeRetry[3] + reserveTime common.mobile():ExpectNotification("OnSystemRequest", { requestType = "PROPRIETARY" }) :Times(2) :Timeout(timeout) common.hmi():ExpectNotification("SDL.OnStatusUpdate", { status = "UPDATE_NEEDED" }, { status = "UPDATING" }, { status = "UPDATE_NEEDED" }, { status = "UPDATING" }, { status = "UPDATE_NEEDED" }) :Times(5) :Timeout(timeout) :Do(function(_, data) common.log("SDL->HMI:", "SDL.OnStatusUpdate(" .. data.params.status .. ")") table.insert(retryNotificationTime, timestamp()) end) end local function checkOnStatusUpdateNotificationTimers() local actualCheckTime = {} local checkTimeIterations = { firstIteration = { retryNotificationTime[1], retryNotificationTime[2] }, secondIteration = { retryNotificationTime[3], retryNotificationTime[4] }, thirdIteration = { retryNotificationTime[5], retryNotificationTime[6] } } for _, value in ipairs(checkTimeIterations) do table.insert(actualCheckTime, value[2] - value[1]) end for key, retryTime in pairs(actualCheckTime) do if retryTime > expectedTimeRetry[key] + inaccuracy or retryTime < expectedTimeRetry[key] - inaccuracy then test:FailTestCase("Time between messages UPDATING and UPDATE_NEEDED is not equal to expected.\n" .. "Expected time is " .. expectedTimeRetry[key] .. ", actual time is " .. retryTime) end end end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", common.preconditions) runner.Step("Preloaded update with retry parameters", common.updatePreloaded, { updatePreloadedTimeout }) runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start) runner.Title("Test") runner.Step("Register App", common.registerApp) runner.Step("Unsuccessful PTU via a HMI", common.unsuccessfulPTUviaHMI) runner.Step("Retry sequence", retrySequence) runner.Step("Check OnStatusUpdate Notification Timers", checkOnStatusUpdateNotificationTimers) runner.Title("Postconditions") runner.Step("Stop SDL", common.postconditions)
--------------------------------------------------------------------------------------------------- -- Proposal: https://github.com/smartdevicelink/sdl_evolution/blob/master/proposals/0248-hmi-ptu-support.md -- -- Description: Retry strategy after failed HMI PTU on proprietary flow -- In case: -- 1. timeout_after_x_seconds is set to 4 seconds in preloaded file -- 2. secondsBetweenRetries is set to { 1, 2 } in preloaded file -- 3. Mobile app is registered and activated -- 4. PTU via HMI is started -- SDL does: -- a. start timeout_after_x_seconds timeout -- 5. Timeout expired -- SDL does: -- a. start retry strategy -- b. send SDL.OnStatusUpdate(UPDATE_NEDDED) to HMI -- c. send OnSystemRequest(Proprietary) to mobile app -- d. sends SDL.OnStatusUpdate(UPDATING) to HMI -- i. start timeout_for_first_try = timeout_after_x_seconds + secondsBetweenRetries[1] -- 6. Timeout expired -- SDL does: -- a. send SDL.OnStatusUpdate(UPDATE_NEDDED) to HMI -- b. send OnSystemRequest(Proprietary) to mobile app -- c. sends SDL.OnStatusUpdate(UPDATING) to HMI -- d. start timeout_for_second_try = timeout_for_first_try + secondsBetweenRetries[2] -- 7. Timeout expired -- SDL does: -- a. send SDL.OnStatusUpdate(UPDATE_NEDDED) to HMI --------------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require('user_modules/script_runner') local common = require('test_scripts/Policies/HMI_PTU/common_hmi_ptu') local test = require('testbase') --[[ Test Configuration ]] runner.testSettings.isSelfIncluded = false runner.testSettings.restrictions.sdlBuildOptions = { { extendedPolicy = { "PROPRIETARY" } } } --[[ Local Variables ]] local secondsBetweenRetries = { 1, 2 } -- in sec local timeout_after_x_seconds = 4 -- in sec local retryNotificationTime = {} local expectedTimeRetry = { -- in msec timeout_after_x_seconds*1000, (timeout_after_x_seconds + secondsBetweenRetries[1])*1000, (timeout_after_x_seconds*#secondsBetweenRetries + secondsBetweenRetries[1] + secondsBetweenRetries[2])*1000 } local inaccuracy = 500 -- in msec --[[ Local Functions ]] local function updatePreloadedTimeout(pTbl) pTbl.policy_table.module_config.timeout_after_x_seconds = timeout_after_x_seconds pTbl.policy_table.module_config.seconds_between_retries = secondsBetweenRetries end function common.registerApp() common.register() common.hmi():ExpectNotification("SDL.OnStatusUpdate", { status = "UPDATE_NEEDED" }, { status = "UPDATING" }) :Times(2) :Do(function(_, data) common.log("SDL->HMI:", "SDL.OnStatusUpdate(" .. data.params.status .. ")") if data.params.status == "UPDATING" then table.insert(retryNotificationTime, timestamp()) end end) end local function retrySequence() common.hmi():SendNotification("BasicCommunication.OnSystemRequest", { requestType = "PROPRIETARY", fileName = "files/ptu.json" }) local reserveTime = 2000 local timeout = expectedTimeRetry[1] + expectedTimeRetry[2] + expectedTimeRetry[3] + reserveTime common.mobile():ExpectNotification("OnSystemRequest", { requestType = "PROPRIETARY" }) :Times(3) :Timeout(timeout) common.hmi():ExpectNotification("SDL.OnStatusUpdate", { status = "UPDATE_NEEDED" }, { status = "UPDATING" }, { status = "UPDATE_NEEDED" }, { status = "UPDATING" }, { status = "UPDATE_NEEDED" }) :Times(5) :Timeout(timeout) :Do(function(_, data) common.log("SDL->HMI:", "SDL.OnStatusUpdate(" .. data.params.status .. ")") table.insert(retryNotificationTime, timestamp()) end) end local function checkOnStatusUpdateNotificationTimers() local actualCheckTime = {} local checkTimeIterations = { firstIteration = { retryNotificationTime[1], retryNotificationTime[2] }, secondIteration = { retryNotificationTime[3], retryNotificationTime[4] }, thirdIteration = { retryNotificationTime[5], retryNotificationTime[6] } } for _, value in ipairs(checkTimeIterations) do table.insert(actualCheckTime, value[2] - value[1]) end for key, retryTime in pairs(actualCheckTime) do if retryTime > expectedTimeRetry[key] + inaccuracy or retryTime < expectedTimeRetry[key] - inaccuracy then test:FailTestCase("Time between messages UPDATING and UPDATE_NEEDED is not equal to expected.\n" .. "Expected time is " .. expectedTimeRetry[key] .. ", actual time is " .. retryTime) end end end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", common.preconditions) runner.Step("Preloaded update with retry parameters", common.updatePreloaded, { updatePreloadedTimeout }) runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start) runner.Title("Test") runner.Step("Register App", common.registerApp) runner.Step("Unsuccessful PTU via a HMI", common.unsuccessfulPTUviaHMI) runner.Step("Retry sequence", retrySequence) runner.Step("Check OnStatusUpdate Notification Timers", checkOnStatusUpdateNotificationTimers) runner.Title("Postconditions") runner.Step("Stop SDL", common.postconditions)
Update script according to fixed issue (#2418)
Update script according to fixed issue (#2418)
Lua
bsd-3-clause
smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts,smartdevicelink/sdl_atf_test_scripts
b0a4dac7ef157df5c2f85020a91b9c197b496fc6
mods/bobblocks/trap.lua
mods/bobblocks/trap.lua
-- State Changes local update_bobtrap = function (pos, node) local nodename="" local param2="" --Switch Trap State if -- Swap Traps node.name == 'bobblocks:trap_spike' then nodename = 'bobblocks:trap_spike_set' elseif node.name == 'bobblocks:trap_spike_set' then nodename = 'bobblocks:trap_spike' elseif node.name == 'bobblocks:trap_spike_major' then nodename = 'bobblocks:trap_spike_major_set' elseif node.name == 'bobblocks:trap_spike_major_set' then nodename = 'bobblocks:trap_spike_major' end minetest.add_node(pos, {name = nodename}) end -- Punch Traps local on_bobtrap_punched = function (pos, node, puncher) if -- Start Traps node.name == 'bobblocks:trap_spike' or node.name == 'bobblocks:trap_spike_set' or node.name == 'bobblocks:trap_spike_major' or node.name == 'bobblocks:trap_spike_major_set' then update_bobtrap(pos, node) end end minetest.register_on_punchnode(on_bobtrap_punched) --ABM (Spring The Traps) minetest.register_abm( {nodenames = {"bobblocks:trap_spike_set"}, interval = 1.0, chance = 1, action = function(pos, node, active_object_count, active_object_count_wider) local objs = minetest.get_objects_inside_radius(pos, 1) for k, obj in pairs(objs) do update_bobtrap(pos, node) end end, }) minetest.register_abm( {nodenames = {"bobblocks:trap_spike_major_set"}, interval = 1.0, chance = 1, action = function(pos, node, active_object_count, active_object_count_wider) local objs = minetest.get_objects_inside_radius(pos, 1) for k, obj in pairs(objs) do update_bobtrap(pos, node) end end, }) -- Nodes minetest.register_node("bobblocks:trap_grass", { description = "Trap Grass", tiles = {"default_grass.png"}, paramtype2 = "facedir", legacy_facedir_simple = true, groups = {snappy=2,cracky=3,oddly_breakable_by_hand=3}, is_ground_content = false, walkable = false, climbable = false, }) local function spikenode(name, desc, texture, drop, groups, drawtype) minetest.register_node("bobblocks:trap_"..name, { description = desc, drawtype = drawtype, tiles = {"bobblocks_"..texture..".png"}, inventory_image = ("bobblocks_"..texture..".png"), paramtype = "light", walkable = false, sunlight_propagates = true, groups = groups, drop = drop, }) end local function spike1(name, desc, texture) spikenode(name, desc, texture, "bobblocks:trap_"..name, {cracky=3,melty=3}, "plantlike") end local function spike2(name, desc, texture, drop) spikenode(name, desc, texture, drop, {cracky=3,melty=3,not_in_creative_inventory=1}, "raillike") end spike1("spike", "Trap Spike Minor", "minorspike") spike2("spike_set", "Trap Spike Minor Set", "trap_set", 'bobblocks:trap_spike') spike1("spike_major", "Trap Spike Major", "majorspike") spike2("spike_major_set", "Trap Spike Major Set", "trap_set", 'bobblocks:trap_spike_major') minetest.register_node("bobblocks:spike_major_reverse", { description = "Trap Spike Major Reverse", drawtype = "plantlike", visual_scale = 1, tiles = {"bobblocks_majorspike_reverse.png"}, inventory_image = ("bobblocks_majorspike_reverse.png"), paramtype = "light", walkable = false, sunlight_propagates = true, groups = {cracky=2,melty=2}, }) -- Crafting minetest.register_craft({ output = 'bobblocks:trap_spike 3', recipe = { {'', 'default:obsidian_shard', ''}, {'', 'default:steel_ingot', ''}, } }) minetest.register_craft({ output = 'bobblocks:trap_spike_major', recipe = { {'default:obsidian_shard', 'default:obsidian_shard', 'default:obsidian_shard'}, {'', 'default:steel_ingot', ''}, } }) minetest.register_craft({ output = 'bobblocks:trap_grass', recipe = { {'', '', ''}, {'', 'default:dirt', ''}, {'', 'default:stick', ''}, } }) minetest.register_craft({ output = 'bobblocks:spike_major_reverse', recipe = { {'', 'default:steel_ingot', ''}, {'default:obsidian_shard', 'default:obsidian_shard', 'default:obsidian_shard'}, } }) -- ABM minetest.register_abm( {nodenames = {"bobblocks:trap_spike"}, interval = 1.0, chance = 1, action = function(pos, node, active_object_count, active_object_count_wider) local objs = minetest.get_objects_inside_radius(pos, 1) for k, obj in pairs(objs) do obj:set_hp(obj:get_hp()-1) minetest.sound_play("bobblocks_trap_fall", {pos = pos, gain = 1.0, max_hear_distance = 3,}) end end, }) minetest.register_abm( {nodenames = {"bobblocks:trap_spike_major"}, interval = 1.0, chance = 1, action = function(pos, node, active_object_count, active_object_count_wider) local objs = minetest.get_objects_inside_radius(pos, 1) for k, obj in pairs(objs) do obj:set_hp(obj:get_hp()-100) minetest.sound_play("bobblocks_trap_fall", {pos = pos, gain = 1.0, max_hear_distance = 3,}) end end, }) minetest.register_abm( {nodenames = {"bobblocks:spike_major_reverse"}, interval = 1.0, chance = 1, action = function(pos, node, active_object_count, active_object_count_wider) pos.y = pos.y-1.2 local objs = minetest.get_objects_inside_radius(pos, 1) for k, obj in pairs(objs) do obj:set_hp(obj:get_hp()-100) minetest.sound_play("bobblocks_trap_fall", {pos = pos, gain = 1.0, max_hear_distance = 3,}) end end, })
-- State Changes local update_bobtrap = function (pos, node) local nodename="" local param2="" --Switch Trap State if -- Swap Traps node.name == 'bobblocks:trap_spike' then nodename = 'bobblocks:trap_spike_set' elseif node.name == 'bobblocks:trap_spike_set' then nodename = 'bobblocks:trap_spike' elseif node.name == 'bobblocks:trap_spike_major' then nodename = 'bobblocks:trap_spike_major_set' elseif node.name == 'bobblocks:trap_spike_major_set' then nodename = 'bobblocks:trap_spike_major' end minetest.add_node(pos, {name = nodename}) end -- Punch Traps local on_bobtrap_punched = function (pos, node, puncher) if -- Start Traps node.name == 'bobblocks:trap_spike' or node.name == 'bobblocks:trap_spike_set' or node.name == 'bobblocks:trap_spike_major' or node.name == 'bobblocks:trap_spike_major_set' then update_bobtrap(pos, node) end end minetest.register_on_punchnode(on_bobtrap_punched) --ABM (Spring The Traps) minetest.register_abm( {nodenames = {"bobblocks:trap_spike_set"}, interval = 1.0, chance = 1, action = function(pos, node, active_object_count, active_object_count_wider) local objs = minetest.get_objects_inside_radius(pos, 1) for k, obj in pairs(objs) do update_bobtrap(pos, node) end end, }) minetest.register_abm( {nodenames = {"bobblocks:trap_spike_major_set"}, interval = 1.0, chance = 1, action = function(pos, node, active_object_count, active_object_count_wider) local objs = minetest.get_objects_inside_radius(pos, 1) for k, obj in pairs(objs) do update_bobtrap(pos, node) end end, }) -- Nodes minetest.register_node("bobblocks:trap_grass", { description = "Trap Grass", tiles = {"default_grass.png"}, paramtype2 = "facedir", legacy_facedir_simple = true, groups = {snappy=2,cracky=3,oddly_breakable_by_hand=3}, is_ground_content = false, walkable = false, climbable = false, }) local function spikenode(name, desc, texture, drop, groups, drawtype) minetest.register_node("bobblocks:trap_"..name, { description = desc, drawtype = drawtype, tiles = {"bobblocks_"..texture..".png"}, inventory_image = ("bobblocks_"..texture..".png"), paramtype = "light", walkable = false, sunlight_propagates = true, groups = groups, drop = drop, }) end local function spike1(name, desc, texture) spikenode(name, desc, texture, "bobblocks:trap_"..name, {cracky=3,melty=3}, "plantlike") end local function spike2(name, desc, texture, drop) spikenode(name, desc, texture, drop, {cracky=3,melty=3,not_in_creative_inventory=1}, "raillike") end spike1("spike", "Trap Spike Minor", "minorspike") spike2("spike_set", "Trap Spike Minor Set", "trap_set", 'bobblocks:trap_spike') spike1("spike_major", "Trap Spike Major", "majorspike") spike2("spike_major_set", "Trap Spike Major Set", "trap_set", 'bobblocks:trap_spike_major') minetest.register_node("bobblocks:spike_major_reverse", { description = "Trap Spike Major Reverse", drawtype = "plantlike", visual_scale = 1, tiles = {"bobblocks_majorspike_reverse.png"}, inventory_image = ("bobblocks_majorspike_reverse.png"), paramtype = "light", walkable = false, sunlight_propagates = true, groups = {cracky=2,melty=2}, }) -- Crafting minetest.register_craft({ output = 'bobblocks:trap_spike 3', recipe = { {'', 'default:obsidian_shard', ''}, {'', 'default:steel_ingot', ''}, } }) minetest.register_craft({ output = 'bobblocks:trap_spike_major', recipe = { {'default:obsidian_shard', 'default:obsidian_shard', 'default:obsidian_shard'}, {'', 'default:steel_ingot', ''}, } }) minetest.register_craft({ output = 'bobblocks:trap_grass', recipe = { {'', '', ''}, {'', 'default:dirt', ''}, {'', 'default:stick', ''}, } }) minetest.register_craft({ output = 'bobblocks:spike_major_reverse', recipe = { {'', 'default:steel_ingot', ''}, {'default:obsidian_shard', 'default:obsidian_shard', 'default:obsidian_shard'}, } }) -- ABM minetest.register_abm( {nodenames = {"bobblocks:trap_spike"}, interval = 1.0, chance = 1, action = function(pos, node, active_object_count, active_object_count_wider) local objs = minetest.get_objects_inside_radius(pos, 1) for k, obj in pairs(objs) do if obj:get_hp() > 0 then --MFF (crabman 8/1/2016) dont re-kill dead player obj:set_hp(obj:get_hp()-1) end minetest.sound_play("bobblocks_trap_fall", {pos = pos, gain = 1.0, max_hear_distance = 3,}) end end, }) minetest.register_abm( {nodenames = {"bobblocks:trap_spike_major"}, interval = 1.0, chance = 1, action = function(pos, node, active_object_count, active_object_count_wider) local objs = minetest.get_objects_inside_radius(pos, 1) for k, obj in pairs(objs) do if obj:get_hp() > 0 then --MFF (crabman 8/1/2016) dont re-kill dead player obj:set_hp(obj:get_hp()-100) end minetest.sound_play("bobblocks_trap_fall", {pos = pos, gain = 1.0, max_hear_distance = 3,}) end end, }) minetest.register_abm( {nodenames = {"bobblocks:spike_major_reverse"}, interval = 1.0, chance = 1, action = function(pos, node, active_object_count, active_object_count_wider) pos.y = pos.y-1.2 local objs = minetest.get_objects_inside_radius(pos, 1) for k, obj in pairs(objs) do if obj:get_hp() > 0 then --MFF (crabman 8/1/2016) dont re-kill dead player obj:set_hp(obj:get_hp()-100) end minetest.sound_play("bobblocks_trap_fall", {pos = pos, gain = 1.0, max_hear_distance = 3,}) end end, })
trap spike don't re-kill dead player, fix multidead, issue https://github.com/MinetestForFun/server-minetestforfun/issues/375
trap spike don't re-kill dead player, fix multidead, issue https://github.com/MinetestForFun/server-minetestforfun/issues/375
Lua
unlicense
Ombridride/minetest-minetestforfun-server,LeMagnesium/minetest-minetestforfun-server,Coethium/server-minetestforfun,MinetestForFun/server-minetestforfun,Gael-de-Sailly/minetest-minetestforfun-server,Coethium/server-minetestforfun,crabman77/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,Ombridride/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,MinetestForFun/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,MinetestForFun/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,MinetestForFun/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,sys4-fr/server-minetestforfun,Ombridride/minetest-minetestforfun-server,crabman77/minetest-minetestforfun-server,Gael-de-Sailly/minetest-minetestforfun-server,sys4-fr/server-minetestforfun,Coethium/server-minetestforfun,LeMagnesium/minetest-minetestforfun-server
4853605a5fc5c32d6dbecab58cb18e088bfbf13e
thinkpad/awesome/console.lua
thinkpad/awesome/console.lua
-- Float Console (ccs) -- Similar to "quake console": http://awesome.naquadah.org/wiki/Drop-down_terminal -- -- Difference: console created at awesome launch time, so it is more smooth -- at the first time calling the console. There is only one console for all screen. -- -- Usage: -- require("console") -- awful.key({ modkey, }, "`", function () console.toggle() end) -- console.init(terminal) local awful = require("awful") local capi = { mouse = mouse, screen = screen, client = client, timer = timer } module("console") -- {{{ parameters to adjust the console display console_margin = 8 console_borderwidth = 1 console_height_ratio = 0.3 -- }}} console_term = nil console_name = "ccs" function get_console_client () local cc = nil for c in awful.client.iterate(function (c) return c.instance == console_name end, nil, nil) do cc = c end return cc end function create() if get_console_client() == nil then awful.util.spawn(console_term .. " -name " .. console_name) end end function init(terminal) if terminal ~= nil then console_term = terminal end local reattach = capi.timer { timeout = 0 } reattach:connect_signal("timeout", function() reattach:stop() create(console_term) end) reattach:start() capi.client.connect_signal("manage", function (c, startup) if c.instance == console_name then c.hidden = true end end) capi.client.connect_signal("unmanage", function (c, startup) if c.instance == console_name then c.hidden = true end end) end function toggle() init(nil) local cc = get_console_client() if cc.hidden then -- Comptute size local geom = capi.screen[capi.mouse.screen].workarea local width, height, x, y width = geom.width - (console_margin + console_borderwidth) * 2 height = geom.height * console_height_ratio x = geom.x + console_margin y = geom.height + geom.y - height - console_margin - console_borderwidth -- Resize awful.client.floating.set(cc, true) cc.border_width = console_borderwidth cc.size_hints_honor = false cc:geometry({ x = x, y = y, width = width, height = height }) -- Sticky and on top cc.ontop = true cc.above = true cc.skip_taskbar = true cc.sticky = true -- This is not a normal window, don't apply any specific keyboard stuff cc:buttons({}) cc:keys({}) -- display the console cc.hidden = false cc:raise() capi.client.focus = cc else cc.hidden = true end end
-- Float Console (ccs) -- Similar to "quake console": http://awesome.naquadah.org/wiki/Drop-down_terminal -- -- Difference: console created at awesome launch time, so it is more smooth -- at the first time calling the console. There is only one console for all screen. -- -- Usage: -- require("console") -- awful.key({ modkey, }, "`", function () console.toggle() end) -- console.init(terminal) local awful = require("awful") local capi = { mouse = mouse, screen = screen, client = client, timer = timer } module("console") -- {{{ parameters to adjust the console display console_margin = 8 console_borderwidth = 1 console_height_ratio = 0.3 -- }}} console_term = nil console_name = "ccs" function get_console_client () local cc = nil for c in awful.client.iterate(function (c) return c.instance == console_name end, nil, nil) do cc = c end return cc end function create() if get_console_client() == nil then awful.util.spawn(console_term .. " -name " .. console_name) end end function init(terminal) if terminal ~= nil then console_term = terminal end local reattach = capi.timer { timeout = 0 } reattach:connect_signal("timeout", function() reattach:stop() create() end) reattach:start() capi.client.connect_signal("manage", function (c, startup) if c.instance == console_name then c.hidden = true end end) capi.client.connect_signal("unmanage", function (c, startup) if c.instance == console_name then c.hidden = true end end) end function toggle() init(nil) local cc = get_console_client() if cc ~= nil then if cc.hidden then -- Comptute size local geom = capi.screen[capi.mouse.screen].workarea local width, height, x, y width = geom.width - (console_margin + console_borderwidth) * 2 height = geom.height * console_height_ratio x = geom.x + console_margin y = geom.height + geom.y - height - console_margin - console_borderwidth -- Resize awful.client.floating.set(cc, true) cc.border_width = console_borderwidth cc.size_hints_honor = false cc:geometry({ x = x, y = y, width = width, height = height }) -- Sticky and on top cc.ontop = true cc.above = true cc.skip_taskbar = true cc.sticky = true -- This is not a normal window, don't apply any specific keyboard stuff cc:buttons({}) cc:keys({}) -- display the console cc.hidden = false cc:raise() capi.client.focus = cc else cc.hidden = true end end end
bug fix.
bug fix.
Lua
apache-2.0
subbyte/configurations,subbyte/configurations,subbyte/configurations,subbyte/configurations
5425fc1249671efba9339ae9d6c356884c002e4e
filters/hugo.lua
filters/hugo.lua
-- Remove TeX/LaTeX RawInlines function RawInline(el) if el.format:match 'tex' or el.format:match 'latex' then return {} end end -- Remove TeX/LaTeX RawBlocks function RawBlock(el) if el.format:match 'tex' or el.format:match 'latex' then return {} end end -- Encapsulate TeX Math function Math(el) if el.mathtype:match 'InlineMath' then return { pandoc.RawInline('markdown', '<span>'), el, pandoc.RawInline('markdown', '</span>') } end if el.mathtype:match 'DisplayMath' then return { pandoc.RawInline('markdown', '<div>'), el, pandoc.RawInline('markdown', '</div>') } end end -- Nest an image in a Div to center it and allow manual scaling -- -- This is essentially the construct that Hugo would create for -- shortcode `{{% figure src="path" title="text" width="60%" %}}` -- Now we can just write `![text](path){width="60%}` instead ... function Image(el) local width = el.attributes["width"] or "auto" local height = el.attributes["height"] or "auto" local style = string.format("width:%s;height:%s;", width, height) local alt = pandoc.utils.stringify(el.caption) return { pandoc.RawInline('markdown', '<div class="center" style="' .. style .. '">'), pandoc.RawInline('markdown', '<figure>'), pandoc.RawInline('markdown', '<img src="' .. el.src .. '" alt="' .. alt ..'">'), pandoc.RawInline('markdown', '<figcaption><h4>'), pandoc.Str(alt), pandoc.RawInline('markdown', '</h4></figcaption>'), pandoc.RawInline('markdown', '</figure>'), pandoc.RawInline('markdown', '</div>') } end -- Replace native Divs with "real" Divs or Shortcodes function Div(el) -- Replace "showme" Div with "expand" Shortcode if el.classes[1] == "showme" then return { pandoc.RawBlock("markdown", '{{% expand "Show Me" %}}'), pandoc.RawBlock("markdown", "<div class='showme'>") } .. el.content .. { pandoc.RawBlock("markdown", "</div>"), pandoc.RawBlock("markdown", "{{% /expand %}}") } end -- Transform all other native Divs to "real" Divs digestible to Hugo return { pandoc.RawBlock("markdown", "<div class='" .. el.classes[1] .. "'>") } .. el.content .. { pandoc.RawBlock("markdown", "</div>") } end -- Replace native Spans with "real" Spans or Shortcodes function Span(el) -- Replace "bsp" Span with "button" Shortcode if el.classes[1] == "bsp" then return { pandoc.RawInline("markdown", "{{% button %}}") } .. el.content .. { pandoc.RawInline("markdown", "{{% /button %}}") } end -- Transform all other native Spans to "real" Spans digestible to Hugo return { pandoc.RawInline("markdown", "<span class='" .. el.classes[1] .. "'>") } .. el.content .. { pandoc.RawInline("markdown", "</span>") } end -- Handle citations -- use "#id_KEY" as target => needs be be defined in the document -- i.e. the shortcode/partial "bib.html" needs to create this targets local keys = {} function Cite(el) -- translate a citation into a link local citation_to_link = function(citation) local id = citation.id local suffix = pandoc.utils.stringify(citation.suffix) -- remember this id, needs to be added to the meta data keys[id] = true -- create a link into the current document return pandoc.Link("[" .. id .. suffix .. "]", "#id_" .. id) end -- replace citation with list of links return el.citations:map(citation_to_link) end function Meta(md) -- meta data "readings" md.readings = md.readings or pandoc.MetaList(pandoc.List()) -- has a "readings" element "x" a "key" with value "k"? local has_id = function(k) return function(x) return pandoc.utils.stringify(x.key) == k end end -- collect all "keys" which are not in "readings" for k, _ in pairs(keys) do if #md.readings:filter(has_id(k)) == 0 then md.readings:insert(pandoc.MetaMap{key = pandoc.MetaInlines{pandoc.Str(k)}}) end end return md end
-- Remove TeX/LaTeX RawInlines function RawInline(el) if el.format:match 'tex' or el.format:match 'latex' then -- replace RawInlines ("latex") w/ a space return pandoc.Space() end end -- Remove TeX/LaTeX RawBlocks function RawBlock(el) if el.format:match 'tex' or el.format:match 'latex' then -- use empty Para instead of just returning an empty list, -- which turns up in the result as HTML comment?! return pandoc.Para{} end end -- Encapsulate TeX Math function Math(el) if el.mathtype:match 'InlineMath' then return { pandoc.RawInline('markdown', '<span>'), el, pandoc.RawInline('markdown', '</span>') } end if el.mathtype:match 'DisplayMath' then return { pandoc.RawInline('markdown', '<div>'), el, pandoc.RawInline('markdown', '</div>') } end end -- Nest an image in a Div to center it and allow manual scaling -- -- This is essentially the construct that Hugo would create for -- shortcode `{{% figure src="path" title="text" width="60%" %}}` -- Now we can just write `![text](path){width="60%}` instead ... function Image(el) local width = el.attributes["width"] or "auto" local height = el.attributes["height"] or "auto" local style = string.format("width:%s;height:%s;", width, height) local alt = pandoc.utils.stringify(el.caption) return { pandoc.RawInline('markdown', '<div class="center" style="' .. style .. '">'), pandoc.RawInline('markdown', '<figure>'), pandoc.RawInline('markdown', '<img src="' .. el.src .. '" alt="' .. alt ..'">'), pandoc.RawInline('markdown', '<figcaption><h4>'), pandoc.Str(alt), pandoc.RawInline('markdown', '</h4></figcaption>'), pandoc.RawInline('markdown', '</figure>'), pandoc.RawInline('markdown', '</div>') } end -- Replace native Divs with "real" Divs or Shortcodes function Div(el) -- Replace "showme" Div with "expand" Shortcode if el.classes[1] == "showme" then return { pandoc.RawBlock("markdown", '{{% expand "Show Me" %}}'), pandoc.RawBlock("markdown", "<div class='showme'>") } .. el.content .. { pandoc.RawBlock("markdown", "</div>"), pandoc.RawBlock("markdown", "{{% /expand %}}") } end -- Transform all other native Divs to "real" Divs digestible to Hugo return { pandoc.RawBlock("markdown", "<div class='" .. el.classes[1] .. "'>") } .. el.content .. { pandoc.RawBlock("markdown", "</div>") } end -- Replace native Spans with "real" Spans or Shortcodes function Span(el) -- Replace "bsp" Span with "button" Shortcode if el.classes[1] == "bsp" then return { pandoc.RawInline("markdown", "{{% button %}}") } .. el.content .. { pandoc.RawInline("markdown", "{{% /button %}}") } end -- Transform all other native Spans to "real" Spans digestible to Hugo return { pandoc.RawInline("markdown", "<span class='" .. el.classes[1] .. "'>") } .. el.content .. { pandoc.RawInline("markdown", "</span>") } end -- Handle citations -- use "#id_KEY" as target => needs be be defined in the document -- i.e. the shortcode/partial "bib.html" needs to create this targets local keys = {} function Cite(el) -- translate a citation into a link local citation_to_link = function(citation) local id = citation.id local suffix = pandoc.utils.stringify(citation.suffix) -- remember this id, needs to be added to the meta data keys[id] = true -- create a link into the current document return pandoc.Link("[" .. id .. suffix .. "]", "#id_" .. id) end -- replace citation with list of links return el.citations:map(citation_to_link) end function Meta(md) -- meta data "readings" md.readings = md.readings or pandoc.MetaList(pandoc.List()) -- has a "readings" element "x" a "key" with value "k"? local has_id = function(k) return function(x) return pandoc.utils.stringify(x.key) == k end end -- collect all "keys" which are not in "readings" for k, _ in pairs(keys) do if #md.readings:filter(has_id(k)) == 0 then md.readings:insert(pandoc.MetaMap{key = pandoc.MetaInlines{pandoc.Str(k)}}) end end return md end
fix hugo filter (#9)
fix hugo filter (#9) return empty para instead of empty list, which would turn up as html comment in the result
Lua
mit
cagix/pandoc-lecture
b1c1942dd77aff9390cc4b9a0d6d720577adb516
nyagos.d/aliases.lua
nyagos.d/aliases.lua
nyagos.alias.ls='ls -oF $*' nyagos.alias.lua_e=function(args) if #args >= 1 then assert(load(args[1]))() end end nyagos.alias.lua_f=function(args) local path=table.remove(args,1) assert(loadfile(path))(args) end nyagos.alias["for"]='%COMSPEC% /c "@set PROMPT=$G & @for $*"' nyagos.alias.kill = function(args) local command="taskkill.exe" for i=1,#args do if args[i] == "-f" then command="taskkill.exe /F" else nyagos.exec(command .. " /PID " .. args[i]) end end end nyagos.alias.killall = function(args) local command="taskkill.exe" for i=1,#args do if args[i] == "-f" then command="taskkill.exe /F" else nyagos.exec(command .. " /IM " .. args[i]) end end end -- on chcp, font-width is changed. nyagos.alias.chcp = function(args) nyagos.resetcharwidth() nyagos.rawexec(args[0],table.unpack(args)) end
nyagos.alias.ls='ls -oF $*' nyagos.alias.lua_e=function(args) if #args >= 1 then assert(load(args[1]))() end end nyagos.alias.lua_f=function(args) local path=table.remove(args,1) assert(loadfile(path))(args) end nyagos.alias["for"]=function(args) local batchpathu = nyagos.env.temp .. os.tmpname() .. ".cmd" local batchpatha = nyagos.utoa(batchpathu) local fd,fd_err = nyagos.open(batchpathu,"w") if not fd then nyagos.writerr(fd_err.."\n") return end local cmdline = "@for "..table.concat(args.rawargs," ").."\n" fd:write("@set prompt=$G\n") fd:write(cmdline) fd:close() nyagos.rawexec(nyagos.env.comspec,"/c",batchpathu) os.remove(batchpatha) end nyagos.alias.kill = function(args) local command="taskkill.exe" for i=1,#args do if args[i] == "-f" then command="taskkill.exe /F" else nyagos.exec(command .. " /PID " .. args[i]) end end end nyagos.alias.killall = function(args) local command="taskkill.exe" for i=1,#args do if args[i] == "-f" then command="taskkill.exe /F" else nyagos.exec(command .. " /IM " .. args[i]) end end end -- on chcp, font-width is changed. nyagos.alias.chcp = function(args) nyagos.resetcharwidth() nyagos.rawexec(args[0],table.unpack(args)) end
Fix #134 `for /F "delims=;" %I in ('dir /b') do echo %I` failed.
Fix #134 `for /F "delims=;" %I in ('dir /b') do echo %I` failed. Use not %I but %%I
Lua
bsd-3-clause
zetamatta/nyagos,nocd5/nyagos,tsuyoshicho/nyagos,tyochiai/nyagos
8c7ffbca1c0aa91f1298d16f9595f938e1397336
.config/nvim/lua/plugins.lua
.config/nvim/lua/plugins.lua
local M = {} --- nvim-treesitter/nvim-treesitter local function nvim_treesitter_setup() return require'nvim-treesitter.configs'.setup{ ensure_installed = "maintained", highlight = { enable = true }, incremental_selection = { enable = true }, indent = { enabled = true }, } end --- junegunn/fzf.vim local function fzf_vim_setup() local map = vim.api.nvim_set_keymap local opts = { noremap = true, silent = true } -- From fzf official doc. -- An action can be a reference to a function that processes selected lines. vim.api.nvim_command [[ function! s:build_qflist(lines) call setqflist(map(copy(a:lines), '{ "filename": v:val }')) | copen | cc endfunction let g:fzf_action = { 'ctrl-q': function('s:build_qflist'), 'ctrl-t': 'tab split', 'ctrl-x': 'split', 'ctrl-v': 'vsplit' } ]] vim.api.nvim_command("command! -bang -nargs=? -complete=dir AllFiles call fzf#vim#files(<q-args>, fzf#vim#with_preview({'source': 'rg --files --smart-case -uu --glob !.git'}), <bang>0)") vim.g.fzf_layout = { window = { width = 0.9, height = 0.9 } } map('n', '<localleader>b', '<cmd>Buffers<cr>', opts) map('n', '<localleader>c', '<cmd>Commands<cr>', opts) map('n', '<c-p>', '<cmd>Files<cr>', opts) map('n', '<localleader><c-p>', '<cmd>AllFiles<cr>', opts) map('n', '<localleader>g', "<cmd>Rg<cr>", opts) end --- preservim/nerdtree local function nerdtree_setup() local map = vim.api.nvim_set_keymap local opts = { noremap = true, silent = true } map('n', '<localleader>n', '<cmd>NERDTreeToggle<cr>', opts) end -- akinsho/nvim-toggleterm.lua local function nvim_toggleterm_lua_setup() local map = vim.api.nvim_set_keymap local opts = { noremap = true, silent = true } map('n', '<localleader>t', ':<c-u>execute v:count1 . "ToggleTerm"<cr>', opts) map('t', '<localleader>t', '<c-\\><c-n>:<c-u>execute v:count1 . "ToggleTerm"<cr>', opts) end --- Load all plugins M.load_all = function () -- Auto install packer.nvim local install_path = vim.fn.stdpath('data') .. '/site/pack/packer/opt/packer.nvim' local cmd = vim.api.nvim_command if vim.fn.empty(vim.fn.glob(install_path)) > 0 then cmd('!git clone https://github.com/wbthomason/packer.nvim ' .. install_path) cmd('packadd packer.nvim') end cmd('packadd packer.nvim') cmd('autocmd BufWritePost plugins.lua PackerCompile') -- Declare and load plugins require'packer'.startup(function(use) use {'wbthomason/packer.nvim', opt = true} -- user interface use {'itchyny/lightline.vim'} use {'sainnhe/gruvbox-material'} use {'edkolev/tmuxline.vim', opt = true} -- nvim-lsp use { 'neovim/nvim-lspconfig', event = {'BufNew'}, wants = { 'nvim-compe', 'lsp_extensions.nvim', 'nvim-lightbulb', 'nvim-treesitter', }, config = function() require'lsp'.setup() end, } use {'hrsh7th/nvim-compe', opt = true} use {'nvim-lua/lsp_extensions.nvim', opt = true} use {'kosayoda/nvim-lightbulb', opt = true} use {'liuchengxu/vista.vim', cmd = 'Vista'} -- fast moves use {'preservim/nerdtree', cmd = 'NERDTreeToggle'} use {'troydm/zoomwintab.vim', cmd = 'ZoomWinTabToggle'} use {'mg979/vim-visual-multi'} use { 'akinsho/nvim-toggleterm.lua', cmd = 'ToggleTerm', config = function () require'toggleterm'.setup{start_in_insert = false} end, } -- vcs use {'airblade/vim-gitgutter'} -- filetype use {'sheerun/vim-polyglot', event = {'BufNew'}} use { 'nvim-treesitter/nvim-treesitter', opt = true, config = nvim_treesitter_setup, } -- search use {'google/vim-searchindex', opt = true} -- show search index beyond [>99/>99] use { 'junegunn/fzf.vim', cmd = {'Files', 'GFiles', 'Buffers', 'Rg', 'Commands', 'BCommits'}, wants = {'fzf'}, requires = { {'junegunn/fzf', opt = true} } } -- registers use {'tversteeg/registers.nvim'} -- profiling startup time use {'dstein64/vim-startuptime', cmd = 'StartupTime'} end) -- Configure plugins nerdtree_setup() fzf_vim_setup() nvim_toggleterm_lua_setup() vim.g.vista_default_executive = 'nvim_lsp' vim.g['vista#renderer#enable_icon'] = false -- Disable keymaps from ocaml/vim-ocaml (https://git.io/JYbMm) vim.g.no_ocaml_maps = true -- gitgutter symbols vim.g.gitgutter_sign_added = '▎' vim.g.gitgutter_sign_modified = '▎' vim.g.gitgutter_sign_removed = '▁' vim.g.gitgutter_sign_removed_first_line = '▔' vim.g.gitgutter_sign_removed_above_and_below = '░' vim.g.gitgutter_sign_modified_removed = '▎' end return M
local M = {} --- nvim-treesitter/nvim-treesitter local function nvim_treesitter_config() return require'nvim-treesitter.configs'.setup{ ensure_installed = "maintained", highlight = { enable = true }, incremental_selection = { enable = true }, indent = { enabled = true }, } end --- junegunn/fzf.vim local function fzf_vim_setup() local map = vim.api.nvim_set_keymap local opts = { noremap = true, silent = true } -- From fzf official doc. -- An action can be a reference to a function that processes selected lines. vim.api.nvim_command [[ function! s:build_qflist(lines) call setqflist(map(copy(a:lines), '{ "filename": v:val }')) | copen | cc endfunction let g:fzf_action = { 'ctrl-q': function('s:build_qflist'), 'ctrl-t': 'tab split', 'ctrl-x': 'split', 'ctrl-v': 'vsplit' } ]] vim.api.nvim_command("command! -bang -nargs=? -complete=dir AllFiles call fzf#vim#files(<q-args>, fzf#vim#with_preview({'source': 'rg --files --smart-case -uu --glob !.git'}), <bang>0)") vim.g.fzf_layout = { window = { width = 0.9, height = 0.9 } } map('n', '<localleader>b', '<cmd>Buffers<cr>', opts) map('n', '<localleader>c', '<cmd>Commands<cr>', opts) map('n', '<c-p>', '<cmd>Files<cr>', opts) map('n', '<localleader><c-p>', '<cmd>AllFiles<cr>', opts) map('n', '<localleader>g', "<cmd>Rg<cr>", opts) end --- preservim/nerdtree local function nerdtree_setup() local map = vim.api.nvim_set_keymap local opts = { noremap = true, silent = true } map('n', '<localleader>n', '<cmd>NERDTreeToggle<cr>', opts) end -- akinsho/nvim-toggleterm.lua local function nvim_toggleterm_lua_setup() local map = vim.api.nvim_set_keymap local opts = { noremap = true, silent = true } map('n', '<localleader>t', ':<c-u>execute v:count . "ToggleTerm"<cr>', opts) map('t', '<localleader>t', '<c-\\><c-n>:<c-u>execute v:count . "ToggleTerm"<cr>', opts) end local function nvim_toggleterm_lua_config() require'toggleterm'.setup{ start_in_insert = false, persist_size = false, } end --- Load all plugins M.load_all = function () -- Auto install packer.nvim local install_path = vim.fn.stdpath('data') .. '/site/pack/packer/opt/packer.nvim' local cmd = vim.api.nvim_command if vim.fn.empty(vim.fn.glob(install_path)) > 0 then cmd('!git clone https://github.com/wbthomason/packer.nvim ' .. install_path) cmd('packadd packer.nvim') end cmd('packadd packer.nvim') cmd('autocmd BufWritePost plugins.lua PackerCompile') -- Declare and load plugins require'packer'.startup(function(use) use {'wbthomason/packer.nvim', opt = true} -- user interface use {'itchyny/lightline.vim'} use {'sainnhe/gruvbox-material'} use {'edkolev/tmuxline.vim', opt = true} -- nvim-lsp use { 'neovim/nvim-lspconfig', event = {'BufNew'}, wants = { 'nvim-compe', 'lsp_extensions.nvim', 'nvim-lightbulb', 'nvim-treesitter', }, config = function() require'lsp'.setup() end, } use {'hrsh7th/nvim-compe', opt = true} use {'nvim-lua/lsp_extensions.nvim', opt = true} use {'kosayoda/nvim-lightbulb', opt = true} use {'liuchengxu/vista.vim', cmd = 'Vista'} -- fast moves use {'preservim/nerdtree', cmd = 'NERDTreeToggle'} use {'troydm/zoomwintab.vim', cmd = 'ZoomWinTabToggle'} use {'mg979/vim-visual-multi'} use { 'akinsho/nvim-toggleterm.lua', cmd = 'ToggleTerm', config = nvim_toggleterm_lua_config, } -- vcs use {'airblade/vim-gitgutter'} -- filetype use {'sheerun/vim-polyglot', event = {'BufNew'}} use { 'nvim-treesitter/nvim-treesitter', opt = true, config = nvim_treesitter_config, } -- search use {'google/vim-searchindex', opt = true} -- show search index beyond [>99/>99] use { 'junegunn/fzf.vim', cmd = {'Files', 'GFiles', 'Buffers', 'Rg', 'Commands', 'BCommits'}, wants = {'fzf'}, requires = { {'junegunn/fzf', opt = true} } } -- registers use {'tversteeg/registers.nvim'} -- profiling startup time use {'dstein64/vim-startuptime', cmd = 'StartupTime'} end) -- Configure plugins nerdtree_setup() fzf_vim_setup() nvim_toggleterm_lua_setup() vim.g.vista_default_executive = 'nvim_lsp' vim.g['vista#renderer#enable_icon'] = false -- Disable keymaps from ocaml/vim-ocaml (https://git.io/JYbMm) vim.g.no_ocaml_maps = true -- gitgutter symbols vim.g.gitgutter_sign_added = '▎' vim.g.gitgutter_sign_modified = '▎' vim.g.gitgutter_sign_removed = '▁' vim.g.gitgutter_sign_removed_first_line = '▔' vim.g.gitgutter_sign_removed_above_and_below = '░' vim.g.gitgutter_sign_modified_removed = '▎' end return M
[nvim] fix toggleterm recreate issue
[nvim] fix toggleterm recreate issue
Lua
mit
weihanglo/linux-config,weihanglo/linux-config,weihanglo/linux-config,weihanglo/dotfiles
c1924f900c227cd8603ed4a0b222db6b39a4ba9c
applications/luci-olsr/luasrc/model/cbi/olsr/olsrd.lua
applications/luci-olsr/luasrc/model/cbi/olsr/olsrd.lua
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.tools.webadmin") m = Map("olsrd", translate("olsrd", "OLSR Daemon")) s = m:section(TypedSection, "olsrd", translate("olsrd_general")) s.dynamic = true s.anonymous = true debug = s:option(ListValue, "DebugLevel") for i=0, 9 do debug:value(i) end debug.optional = true ipv = s:option(ListValue, "IpVersion") ipv:value("4", "IPv4") ipv:value("6", "IPv6") noint = s:option(Flag, "AllowNoInt") noint.enabled = "yes" noint.disabled = "no" noint.optional = true s:option(Value, "Pollrate").optional = true tcr = s:option(ListValue, "TcRedundancy") tcr:value("0", translate("olsrd_olsrd_tcredundancy_0")) tcr:value("1", translate("olsrd_olsrd_tcredundancy_1")) tcr:value("2", translate("olsrd_olsrd_tcredundancy_2")) tcr.optional = true s:option(Value, "MprCoverage").optional = true lql = s:option(ListValue, "LinkQualityLevel") lql:value("0", translate("disable")) lql:value("1", translate("olsrd_olsrd_linkqualitylevel_1")) lql:value("2", translate("olsrd_olsrd_linkqualitylevel_2")) lql.optional = true s:option(Value, "LinkQualityAging").optional = true lqa = s:option(ListValue, "LinkQualityAlgorithm") lqa.optional = true lqa:value("etx_fpm", translate("olsrd_etx_fpm")) lqa:value("etx_float", translate("olsrd_etx_float")) lqa:value("etx_ff", translate("olsrd_etx_ff")) lqa.optional = true lqfish = s:option(Flag, "LinkQualityFishEye") lqfish.optional = true s:option(Value, "LinkQualityWinSize").optional = true s:option(Value, "LinkQualityDijkstraLimit").optional = true hyst = s:option(Flag, "UseHysteresis") hyst.enabled = "yes" hyst.disabled = "no" hyst.optional = true fib = s:option(ListValue, "FIBMetric") fib.optional = true fib:value("flat") fib:value("correct") fib:value("approx") fib.optional = true clrscr = s:option(Flag, "ClearScreen") clrscr.enabled = "yes" clrscr.disabled = "no" clrscr.optional = true willingness = s:option(ListValue, "Willingness") for i=0,7 do willingness:value(i) end willingness.optional = true i = m:section(TypedSection, "Interface", translate("interfaces")) i.anonymous = true i.addremove = true i.dynamic = true ign = i:option(Flag, "ignore", "Enable") ign.enabled = "0" ign.disabled = "1" ign.rmempty = false network = i:option(ListValue, "interface", translate("network")) luci.tools.webadmin.cbi_add_networks(network) i:option(Value, "Ip4Broadcast").optional = true ip6t = i:option(ListValue, "Ip6AddrType") ip6t:value("", translate("cbi_select")) ip6t:value("auto") ip6t:value("site-local") ip6t:value("unique-local") ip6t:value("global") ip6t.optional = true i:option(Value, "HelloInterval").optional = true i:option(Value, "HelloValidityTime").optional = true i:option(Value, "TcInterval").optional = true i:option(Value, "TcValidityTime").optional = true i:option(Value, "MidInterval").optional = true i:option(Value, "MidValidityTime").optional = true i:option(Value, "HnaInterval").optional = true i:option(Value, "HnaValidityTime").optional = true adc = i:option(Flag, "AutoDetectChanges") adc.enabled = "yes" adc.disabled = "no" adc.optional = true --[[ ipc = m:section(TypedSection, "IpcConnect") ipc.anonymous = true conns = ipc:option(Value, "MaxConnections") conns.isInteger = true nets = ipc:option(Value, "Net") nets.optional = true hosts = ipc:option(Value, "Host") hosts.optional = true ]] return m
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.tools.webadmin") m = Map("olsrd", translate("olsrd", "OLSR Daemon")) s = m:section(TypedSection, "olsrd", translate("olsrd_general")) s.dynamic = true s.anonymous = true debug = s:option(ListValue, "DebugLevel") for i=0, 9 do debug:value(i) end debug.optional = true ipv = s:option(ListValue, "IpVersion") ipv:value("4", "IPv4") ipv:value("6", "IPv6") noint = s:option(Flag, "AllowNoInt") noint.enabled = "yes" noint.disabled = "no" noint.optional = true s:option(Value, "Pollrate").optional = true tcr = s:option(ListValue, "TcRedundancy") tcr:value("0", translate("olsrd_olsrd_tcredundancy_0")) tcr:value("1", translate("olsrd_olsrd_tcredundancy_1")) tcr:value("2", translate("olsrd_olsrd_tcredundancy_2")) tcr.optional = true s:option(Value, "MprCoverage").optional = true lql = s:option(ListValue, "LinkQualityLevel") lql:value("0", translate("disable")) lql:value("1", translate("olsrd_olsrd_linkqualitylevel_1")) lql:value("2", translate("olsrd_olsrd_linkqualitylevel_2")) lql.optional = true s:option(Value, "LinkQualityAging").optional = true lqa = s:option(ListValue, "LinkQualityAlgorithm") lqa.optional = true lqa:value("etx_fpm", translate("olsrd_etx_fpm")) lqa:value("etx_float", translate("olsrd_etx_float")) lqa:value("etx_ff", translate("olsrd_etx_ff")) lqa.optional = true lqfish = s:option(Flag, "LinkQualityFishEye") lqfish.optional = true s:option(Value, "LinkQualityWinSize").optional = true s:option(Value, "LinkQualityDijkstraLimit").optional = true hyst = s:option(Flag, "UseHysteresis") hyst.enabled = "yes" hyst.disabled = "no" hyst.optional = true fib = s:option(ListValue, "FIBMetric") fib.optional = true fib:value("flat") fib:value("correct") fib:value("approx") fib.optional = true clrscr = s:option(Flag, "ClearScreen") clrscr.enabled = "yes" clrscr.disabled = "no" clrscr.optional = true willingness = s:option(ListValue, "Willingness") for i=0,7 do willingness:value(i) end willingness.optional = true i = m:section(TypedSection, "Interface", translate("interfaces")) i.anonymous = true i.addremove = true i.dynamic = true ign = i:option(Flag, "ignore", "Enable") ign.enabled = "0" ign.disabled = "1" ign.rmempty = false function ign.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "0" end network = i:option(ListValue, "interface", translate("network")) luci.tools.webadmin.cbi_add_networks(network) i:option(Value, "Ip4Broadcast").optional = true ip6t = i:option(ListValue, "Ip6AddrType") ip6t:value("", translate("cbi_select")) ip6t:value("auto") ip6t:value("site-local") ip6t:value("unique-local") ip6t:value("global") ip6t.optional = true i:option(Value, "HelloInterval").optional = true i:option(Value, "HelloValidityTime").optional = true i:option(Value, "TcInterval").optional = true i:option(Value, "TcValidityTime").optional = true i:option(Value, "MidInterval").optional = true i:option(Value, "MidValidityTime").optional = true i:option(Value, "HnaInterval").optional = true i:option(Value, "HnaValidityTime").optional = true adc = i:option(Flag, "AutoDetectChanges") adc.enabled = "yes" adc.disabled = "no" adc.optional = true --[[ ipc = m:section(TypedSection, "IpcConnect") ipc.anonymous = true conns = ipc:option(Value, "MaxConnections") conns.isInteger = true nets = ipc:option(Value, "Net") nets.optional = true hosts = ipc:option(Value, "Host") hosts.optional = true ]] return m
[applications] luci-olsr: Fix enable option for interfaces
[applications] luci-olsr: Fix enable option for interfaces
Lua
apache-2.0
8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci
03d46a858093a60e0876f146cf1521b97cf7cac6
MMOCoreORB/bin/scripts/mobile/misc/probot.lua
MMOCoreORB/bin/scripts/mobile/misc/probot.lua
probot = Creature:new { objectName = "@droid_name:imperial_probot_base", socialGroup = "", pvpFaction = "", faction = "", level = 9, chanceHit = 0.27, damageMin = 80, damageMax = 90, baseXp = 0, baseHAM = 700, baseHAMmax = 900, armor = 0, resists = {0,0,0,0,0,0,0,-1,-1}, meatType = "", meatAmount = 0, hideType = "", hideAmount = 0, boneType = "", boneAmount = 0, milk = 0, tamingChance = 0, ferocity = 0, pvpBitmask = NONE, creatureBitmask = NONE, optionsBitmask = 128, diet = HERBIVORE, templates = {"object/mobile/probot.iff"}, lootGroups = {}, weapons = {}, conversationTemplate = "", attacks = { } } CreatureTemplates:addCreatureTemplate(probot, "probot")
probot = Creature:new { objectName = "@droid_name:imperial_probot_base", socialGroup = "", pvpFaction = "", faction = "", level = 9, chanceHit = 0.27, damageMin = 80, damageMax = 90, baseXp = 0, baseHAM = 700, baseHAMmax = 900, armor = 0, resists = {0,0,0,0,0,0,0,-1,-1}, meatType = "", meatAmount = 0, hideType = "", hideAmount = 0, boneType = "", boneAmount = 0, milk = 0, tamingChance = 0, ferocity = 0, pvpBitmask = NONE, creatureBitmask = NONE, optionsBitmask = 128, diet = HERBIVORE, templates = {"object/creature/npc/droid/crafted/imperial_probot.iff"}, lootGroups = {}, weapons = {}, conversationTemplate = "", attacks = { } } CreatureTemplates:addCreatureTemplate(probot, "probot")
(unstable) [fixed] arakyd probot droid now usable again.
(unstable) [fixed] arakyd probot droid now usable again. git-svn-id: e4cf3396f21da4a5d638eecf7e3b4dd52b27f938@5103 c3d1530f-68f5-4bd0-87dc-8ef779617e40
Lua
agpl-3.0
lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,Tatwi/legend-of-hondo
9f2218a06f2fb896ed840ef7d2a035d1c88300ac
src/kong/plugins/authentication/schema.lua
src/kong/plugins/authentication/schema.lua
local constants = require "kong.constants" local utils = require "kong.tools.utils" local stringy = require "stringy" local function check_authentication_key_names(names, plugin_value) if plugin_value.authentication_type == constants.AUTHENTICATION.BASIC then return false, "This field is not available for \""..BASIC.."\" authentication" elseif plugin_value.authentication_type ~= BASIC then if names then if type(names) == "table" and utils.table_size(names) > 0 then return true else return false, "You need to specify an array" end else return false, "This field is required for query and header authentication" end end end return { authentication_type = { required = true, immutable = true, enum = { constants.AUTHENTICATION.QUERY, constants.AUTHENTICATION.BASIC, constants.AUTHENTICATION.HEADER }}, authentication_key_names = { type = "table", func = check_authentication_key_names }, hide_credentials = { type = "boolean", default = false } }
local constants = require "kong.constants" local utils = require "kong.tools.utils" local stringy = require "stringy" local function check_authentication_key_names(names, plugin_value) if plugin_value.authentication_type == constants.AUTHENTICATION.BASIC then return false, "This field is not available for \""..constants.AUTHENTICATION.BASIC.."\" authentication" elseif plugin_value.authentication_type ~= constants.AUTHENTICATION.BASIC then if names then if type(names) == "table" and utils.table_size(names) > 0 then return true else return false, "You need to specify an array" end else return false, "This field is required for query and header authentication" end end end return { authentication_type = { required = true, immutable = true, enum = { constants.AUTHENTICATION.QUERY, constants.AUTHENTICATION.BASIC, constants.AUTHENTICATION.HEADER }}, authentication_key_names = { type = "table", func = check_authentication_key_names }, hide_credentials = { type = "boolean", default = false } }
fixing constant value
fixing constant value
Lua
apache-2.0
ChristopherBiscardi/kong,puug/kong,sbuettner/kong,skynet/kong,bbalu/kong,ropik/kong,chourobin/kong,AnsonSmith/kong,vmercierfr/kong,wakermahmud/kong,Skyscanner/kong,paritoshmmmec/kong,peterayeni/kong
93f34883492dc42c9c44ad610c8d2240e326d6a0
test_scripts/Polices/user_consent_of_Policies/108_ATF_ActivateApp_isSDLAllowed_true.lua
test_scripts/Polices/user_consent_of_Policies/108_ATF_ActivateApp_isSDLAllowed_true.lua
--------------------------------------------------------------------------------------------- -- Description: -- SDL receives request for app activation from HMI and the device the app is running on is consented by the User -- 1. Used preconditions: -- Close current connection -- Overwrite preloaded Policy Table to ensure device is not preconsented. -- Connect device -- Register 1st application -- -- 2. Performed steps -- Activate 1st application -- Consent device -- Add new session -- Register 2nd application -- Activate 2nd application -- -- Requirement summary: -- [UpdateDeviceList] isSDLAllowed:true -- [HMI API] BasicCommunication.UpdateDeviceList request/response -- -- Expected result: -- PoliciesManager must respond with "isSDLAllowed: true" in the response to HMI without consent request --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonFunctions = require ('user_modules/shared_testcases/commonFunctions') local commonSteps = require('user_modules/shared_testcases/commonSteps') local commonTestCases = require('user_modules/shared_testcases/commonTestCases') local commonPreconditions = require('user_modules/shared_testcases/commonPreconditions') --[[ Preconditions ]] commonSteps:DeleteLogsFileAndPolicyTable() commonPreconditions:Connecttest_without_ExitBySDLDisconnect_WithoutOpenConnectionRegisterApp("connecttest_ConnectMobile.lua") --[[ General Settings for configuration ]] Test = require('user_modules/connecttest_ConnectMobile') require('cardinalities') require('user_modules/AppTypes') local mobile_session = require('mobile_session') function Test:ConnectDevice() local ServerAddress = commonFunctions:read_parameter_from_smart_device_link_ini("ServerAddress") commonTestCases:DelayedExp(2000) self:connectMobile() EXPECT_HMICALL("BasicCommunication.UpdateDeviceList", { deviceList = { { id = config.deviceMAC, isSDLAllowed = false, name = ServerAddress, transportType = "WIFI" } } } ):Do(function(_,data) self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {}) end) end function Test:RegisterApp1() commonTestCases:DelayedExp(3000) self.mobileSession = mobile_session.MobileSession(self, self.mobileConnection) self.mobileSession:StartService(7) :Do(function() local correlationId = self.mobileSession:SendRPC("RegisterAppInterface", config.application1.registerAppInterfaceParams) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered") :Do(function(_,data) self.HMIAppID = data.params.application.appID end) self.mobileSession:ExpectResponse(correlationId, { success = true, resultCode = "SUCCESS" }) self.mobileSession:ExpectNotification("OnHMIStatus", {hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN"}) end) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:ActivateApp1() local RequestId = self.hmiConnection:SendRequest("SDL.ActivateApp", { appID = self.HMIAppID}) EXPECT_HMIRESPONSE(RequestId, {result = { code = 0, isAppPermissionsRevoked = false, isAppRevoked = false, isSDLAllowed = false, isPermissionsConsentNeeded = false, method ="SDL.ActivateApp"}}) :Do(function(_,data) --App is not allowed so consent for device is needed if data.result.isSDLAllowed ~= false then commonFunctions:userPrint(31, "Error: wrong behavior of SDL - device needs to be consented on HMI") else local RequestId1 = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage", {language = "EN-US", messageCodes = {"DataConsent"}}) EXPECT_HMIRESPONSE(RequestId1) :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) end) end end) EXPECT_NOTIFICATION("OnHMIStatus", {hmiLevel = "FULL", systemContext = "MAIN"}) end function Test:AddSession2() self.mobileSession1 = mobile_session.MobileSession(self,self.mobileConnection) self.mobileSession1:StartService(7) end function Test:RegisterApp2() local correlationId = self.mobileSession1:SendRPC("RegisterAppInterface", config.application2.registerAppInterfaceParams) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered") :Do(function(_,data) self.HMIAppID2 = data.params.application.appID end) self.mobileSession1:ExpectResponse(correlationId, { success = true, resultCode = "SUCCESS" }) self.mobileSession1:ExpectNotification("OnHMIStatus", {hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN"}) end function Test:ActivateApp2_isSDLAllowed_true() local RequestId = self.hmiConnection:SendRequest("SDL.ActivateApp", { appID = self.HMIAppID2 }) EXPECT_HMIRESPONSE(RequestId, {result = { code = 0, isAppPermissionsRevoked = false, isAppRevoked = false, isPermissionsConsentNeeded = false, isSDLAllowed = true, method ="SDL.ActivateApp", priority ="NONE"}}) :Do(function(_,data) --Device is consented already, so no consent is needed: if data.result.isSDLAllowed ~= true then commonFunctions:userPrint(31, "Error: wrong behavior of SDL - device already consented") else self.hmiConnection:SendResponse(data.id,"BasicCommunication.ActivateApp", "SUCCESS", {}) end end) EXPECT_NOTIFICATION("OnHMIStatus", {}) self.mobileSession1:ExpectNotification("OnHMIStatus", {hmiLevel = "FULL", systemContext = "MAIN"}) end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_StopSDL() StopSDL() end return Test
--------------------------------------------------------------------------------------------- -- Description: -- SDL receives request for app activation from HMI and the device the app is running on is consented by the User -- 1. Used preconditions: -- Close current connection -- Overwrite preloaded Policy Table to ensure device is not preconsented. -- Connect device -- Register 1st application -- -- 2. Performed steps -- Activate 1st application -- Consent device -- Add new session -- Register 2nd application -- Activate 2nd application -- -- Requirement summary: -- [UpdateDeviceList] isSDLAllowed:true -- [HMI API] BasicCommunication.UpdateDeviceList request/response -- -- Expected result: -- PoliciesManager must respond with "isSDLAllowed: true" in the response to HMI without consent request --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonFunctions = require ('user_modules/shared_testcases/commonFunctions') local commonSteps = require('user_modules/shared_testcases/commonSteps') -- local commonTestCases = require('user_modules/shared_testcases/commonTestCases') -- local commonPreconditions = require('user_modules/shared_testcases/commonPreconditions') --[[ Preconditions ]] commonFunctions:SDLForceStop() commonSteps:DeleteLogsFileAndPolicyTable() --[[ General Settings for configuration ]] Test = require('connecttest') require('cardinalities') require('user_modules/AppTypes') local mobile_session = require('mobile_session') --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:ActivateApp1() local RequestId = self.hmiConnection:SendRequest("SDL.ActivateApp", { appID = self.applications[config.application1.registerAppInterfaceParams.appName]}) EXPECT_HMIRESPONSE(RequestId, {result = { code = 0, isAppPermissionsRevoked = false, isAppRevoked = false, isSDLAllowed = false, isPermissionsConsentNeeded = false, method ="SDL.ActivateApp"}}) :Do(function(_,data) --App is not allowed so consent for device is needed if data.result.isSDLAllowed ~= false then commonFunctions:userPrint(31, "Error: wrong behavior of SDL - device needs to be consented on HMI") else local RequestId1 = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage", {language = "EN-US", messageCodes = {"DataConsent"}}) EXPECT_HMIRESPONSE(RequestId1) :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) end) end end) EXPECT_NOTIFICATION("OnHMIStatus", {hmiLevel = "FULL", systemContext = "MAIN"}) end function Test:AddSession2() self.mobileSession1 = mobile_session.MobileSession(self,self.mobileConnection) self.mobileSession1:StartService(7) end function Test:RegisterApp2() local correlationId = self.mobileSession1:SendRPC("RegisterAppInterface", config.application2.registerAppInterfaceParams) EXPECT_HMINOTIFICATION("BasicCommunication.OnAppRegistered") :Do(function(_,data) self.HMIAppID2 = data.params.application.appID end) self.mobileSession1:ExpectResponse(correlationId, { success = true, resultCode = "SUCCESS" }) self.mobileSession1:ExpectNotification("OnHMIStatus", {hmiLevel = "NONE", audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN"}) end function Test:ActivateApp2_isSDLAllowed_true() local RequestId = self.hmiConnection:SendRequest("SDL.ActivateApp", { appID = self.applications[config.application2.registerAppInterfaceParams.appName] }) EXPECT_HMIRESPONSE(RequestId, {result = { code = 0, isAppPermissionsRevoked = false, isAppRevoked = false, isPermissionsConsentNeeded = false, isSDLAllowed = true, method ="SDL.ActivateApp", priority ="NONE"}}) :Do(function(_,data) --Device is consented already, so no consent is needed: if data.result.isSDLAllowed ~= true then commonFunctions:userPrint(31, "Error: wrong behavior of SDL - device already consented") else self.hmiConnection:SendResponse(data.id,"BasicCommunication.ActivateApp", "SUCCESS", {}) end end) EXPECT_NOTIFICATION("OnHMIStatus", {}) self.mobileSession1:ExpectNotification("OnHMIStatus", {hmiLevel = "FULL", systemContext = "MAIN"}) end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_StopSDL() 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
ed5d843a81c38346c1a1ff4725d69075545db7f6
spec/04-phases_spec.lua
spec/04-phases_spec.lua
local helpers = require "spec.helpers" local mock_one_fn = [[ local plugin_name = "%s" local filename = kong.configuration.prefix .. "/" .. plugin_name .. "_output" local text = "phase: '%s', index: '%s', plugin: '" .. plugin_name .. "'\n" local readfile = require("pl.utils").readfile local writefile = require("pl.utils").writefile return function() local file_content, err = readfile(filename) or "" file_content = file_content .. text assert(writefile(filename, file_content)) end ]] for _, plugin_name in ipairs({ "pre-function", "post-function" }) do describe("Plugin: " .. plugin_name, function() setup(function() local bp, db = helpers.get_db_utils() assert(db:truncate()) local service = bp.services:insert { name = "service-1", host = helpers.mock_upstream_host, port = helpers.mock_upstream_port, } bp.routes:insert { service = { id = service.id }, hosts = { "one." .. plugin_name .. ".com" }, } local config = {} for _, phase in ipairs({ "certificate", "rewrite", "access", "header_filter", "body_filter", "log"}) do config[phase] = {} for i, index in ipairs({"first", "second", "third"}) do config[phase][i] = mock_one_fn:format(plugin_name, phase, index) end end bp.plugins:insert { name = plugin_name, config = config, } assert(helpers.start_kong({ nginx_conf = "spec/fixtures/custom_nginx.template", })) end) teardown(function() helpers.stop_kong() end) it("hits all phases, with 3 functions, on 3 requests", function() local filename = helpers.test_conf.prefix .. "/" .. plugin_name .. "_output" os.remove(filename) for i = 1,3 do local client = helpers.proxy_ssl_client() local res = assert(client:send { method = "GET", path = "/status/200", headers = { ["Host"] = "one." .. plugin_name .. ".com" } }) assert.response(res).has.status(200) client:close() ngx.sleep(0.1) -- wait for log-phase handler to execute end local content = require("pl.utils").readfile(filename) assert.equal(([[ phase: 'certificate', index: 'first', plugin: 'pre-function' phase: 'certificate', index: 'second', plugin: 'pre-function' phase: 'certificate', index: 'third', plugin: 'pre-function' phase: 'rewrite', index: 'first', plugin: 'pre-function' phase: 'rewrite', index: 'second', plugin: 'pre-function' phase: 'rewrite', index: 'third', plugin: 'pre-function' phase: 'access', index: 'first', plugin: 'pre-function' phase: 'access', index: 'second', plugin: 'pre-function' phase: 'access', index: 'third', plugin: 'pre-function' phase: 'header_filter', index: 'first', plugin: 'pre-function' phase: 'header_filter', index: 'second', plugin: 'pre-function' phase: 'header_filter', index: 'third', plugin: 'pre-function' phase: 'body_filter', index: 'first', plugin: 'pre-function' phase: 'body_filter', index: 'second', plugin: 'pre-function' phase: 'body_filter', index: 'third', plugin: 'pre-function' phase: 'body_filter', index: 'first', plugin: 'pre-function' phase: 'body_filter', index: 'second', plugin: 'pre-function' phase: 'body_filter', index: 'third', plugin: 'pre-function' phase: 'log', index: 'first', plugin: 'pre-function' phase: 'log', index: 'second', plugin: 'pre-function' phase: 'log', index: 'third', plugin: 'pre-function' phase: 'certificate', index: 'first', plugin: 'pre-function' phase: 'certificate', index: 'second', plugin: 'pre-function' phase: 'certificate', index: 'third', plugin: 'pre-function' phase: 'rewrite', index: 'first', plugin: 'pre-function' phase: 'rewrite', index: 'second', plugin: 'pre-function' phase: 'rewrite', index: 'third', plugin: 'pre-function' phase: 'access', index: 'first', plugin: 'pre-function' phase: 'access', index: 'second', plugin: 'pre-function' phase: 'access', index: 'third', plugin: 'pre-function' phase: 'header_filter', index: 'first', plugin: 'pre-function' phase: 'header_filter', index: 'second', plugin: 'pre-function' phase: 'header_filter', index: 'third', plugin: 'pre-function' phase: 'body_filter', index: 'first', plugin: 'pre-function' phase: 'body_filter', index: 'second', plugin: 'pre-function' phase: 'body_filter', index: 'third', plugin: 'pre-function' phase: 'body_filter', index: 'first', plugin: 'pre-function' phase: 'body_filter', index: 'second', plugin: 'pre-function' phase: 'body_filter', index: 'third', plugin: 'pre-function' phase: 'log', index: 'first', plugin: 'pre-function' phase: 'log', index: 'second', plugin: 'pre-function' phase: 'log', index: 'third', plugin: 'pre-function' phase: 'certificate', index: 'first', plugin: 'pre-function' phase: 'certificate', index: 'second', plugin: 'pre-function' phase: 'certificate', index: 'third', plugin: 'pre-function' phase: 'rewrite', index: 'first', plugin: 'pre-function' phase: 'rewrite', index: 'second', plugin: 'pre-function' phase: 'rewrite', index: 'third', plugin: 'pre-function' phase: 'access', index: 'first', plugin: 'pre-function' phase: 'access', index: 'second', plugin: 'pre-function' phase: 'access', index: 'third', plugin: 'pre-function' phase: 'header_filter', index: 'first', plugin: 'pre-function' phase: 'header_filter', index: 'second', plugin: 'pre-function' phase: 'header_filter', index: 'third', plugin: 'pre-function' phase: 'body_filter', index: 'first', plugin: 'pre-function' phase: 'body_filter', index: 'second', plugin: 'pre-function' phase: 'body_filter', index: 'third', plugin: 'pre-function' phase: 'body_filter', index: 'first', plugin: 'pre-function' phase: 'body_filter', index: 'second', plugin: 'pre-function' phase: 'body_filter', index: 'third', plugin: 'pre-function' phase: 'log', index: 'first', plugin: 'pre-function' phase: 'log', index: 'second', plugin: 'pre-function' phase: 'log', index: 'third', plugin: 'pre-function' ]]):gsub("pre%-function", plugin_name),content) end) end) end
local helpers = require "spec.helpers" local mock_one_fn = [[ local plugin_name = "%s" local filename = "/tmp/" .. plugin_name .. "_output" local text = "phase: '%s', index: '%s', plugin: '" .. plugin_name .. "'\n" local readfile = require("pl.utils").readfile local writefile = require("pl.utils").writefile return function() local file_content, err = readfile(filename) or "" file_content = file_content .. text assert(writefile(filename, file_content)) end ]] for _, plugin_name in ipairs({ "pre-function", "post-function" }) do describe("Plugin: " .. plugin_name, function() setup(function() local bp, db = helpers.get_db_utils() assert(db:truncate()) local service = bp.services:insert { name = "service-1", host = helpers.mock_upstream_host, port = helpers.mock_upstream_port, } bp.routes:insert { service = { id = service.id }, hosts = { "one." .. plugin_name .. ".com" }, } local config = {} for _, phase in ipairs({ "certificate", "rewrite", "access", "header_filter", "body_filter", "log"}) do config[phase] = {} for i, index in ipairs({"first", "second", "third"}) do config[phase][i] = mock_one_fn:format(plugin_name, phase, index) end end bp.plugins:insert { name = plugin_name, config = config, } assert(helpers.start_kong({ nginx_conf = "spec/fixtures/custom_nginx.template", })) end) teardown(function() helpers.stop_kong() end) it("hits all phases, with 3 functions, on 3 requests", function() local filename = "/tmp/" .. plugin_name .. "_output" os.remove(filename) for i = 1,3 do local client = helpers.proxy_ssl_client() local res = assert(client:send { method = "GET", path = "/status/200", headers = { ["Host"] = "one." .. plugin_name .. ".com" } }) assert.response(res).has.status(200) client:close() ngx.sleep(0.1) -- wait for log-phase handler to execute end local content = require("pl.utils").readfile(filename) assert.equal(([[ phase: 'certificate', index: 'first', plugin: 'pre-function' phase: 'certificate', index: 'second', plugin: 'pre-function' phase: 'certificate', index: 'third', plugin: 'pre-function' phase: 'rewrite', index: 'first', plugin: 'pre-function' phase: 'rewrite', index: 'second', plugin: 'pre-function' phase: 'rewrite', index: 'third', plugin: 'pre-function' phase: 'access', index: 'first', plugin: 'pre-function' phase: 'access', index: 'second', plugin: 'pre-function' phase: 'access', index: 'third', plugin: 'pre-function' phase: 'header_filter', index: 'first', plugin: 'pre-function' phase: 'header_filter', index: 'second', plugin: 'pre-function' phase: 'header_filter', index: 'third', plugin: 'pre-function' phase: 'body_filter', index: 'first', plugin: 'pre-function' phase: 'body_filter', index: 'second', plugin: 'pre-function' phase: 'body_filter', index: 'third', plugin: 'pre-function' phase: 'body_filter', index: 'first', plugin: 'pre-function' phase: 'body_filter', index: 'second', plugin: 'pre-function' phase: 'body_filter', index: 'third', plugin: 'pre-function' phase: 'log', index: 'first', plugin: 'pre-function' phase: 'log', index: 'second', plugin: 'pre-function' phase: 'log', index: 'third', plugin: 'pre-function' phase: 'certificate', index: 'first', plugin: 'pre-function' phase: 'certificate', index: 'second', plugin: 'pre-function' phase: 'certificate', index: 'third', plugin: 'pre-function' phase: 'rewrite', index: 'first', plugin: 'pre-function' phase: 'rewrite', index: 'second', plugin: 'pre-function' phase: 'rewrite', index: 'third', plugin: 'pre-function' phase: 'access', index: 'first', plugin: 'pre-function' phase: 'access', index: 'second', plugin: 'pre-function' phase: 'access', index: 'third', plugin: 'pre-function' phase: 'header_filter', index: 'first', plugin: 'pre-function' phase: 'header_filter', index: 'second', plugin: 'pre-function' phase: 'header_filter', index: 'third', plugin: 'pre-function' phase: 'body_filter', index: 'first', plugin: 'pre-function' phase: 'body_filter', index: 'second', plugin: 'pre-function' phase: 'body_filter', index: 'third', plugin: 'pre-function' phase: 'body_filter', index: 'first', plugin: 'pre-function' phase: 'body_filter', index: 'second', plugin: 'pre-function' phase: 'body_filter', index: 'third', plugin: 'pre-function' phase: 'log', index: 'first', plugin: 'pre-function' phase: 'log', index: 'second', plugin: 'pre-function' phase: 'log', index: 'third', plugin: 'pre-function' phase: 'certificate', index: 'first', plugin: 'pre-function' phase: 'certificate', index: 'second', plugin: 'pre-function' phase: 'certificate', index: 'third', plugin: 'pre-function' phase: 'rewrite', index: 'first', plugin: 'pre-function' phase: 'rewrite', index: 'second', plugin: 'pre-function' phase: 'rewrite', index: 'third', plugin: 'pre-function' phase: 'access', index: 'first', plugin: 'pre-function' phase: 'access', index: 'second', plugin: 'pre-function' phase: 'access', index: 'third', plugin: 'pre-function' phase: 'header_filter', index: 'first', plugin: 'pre-function' phase: 'header_filter', index: 'second', plugin: 'pre-function' phase: 'header_filter', index: 'third', plugin: 'pre-function' phase: 'body_filter', index: 'first', plugin: 'pre-function' phase: 'body_filter', index: 'second', plugin: 'pre-function' phase: 'body_filter', index: 'third', plugin: 'pre-function' phase: 'body_filter', index: 'first', plugin: 'pre-function' phase: 'body_filter', index: 'second', plugin: 'pre-function' phase: 'body_filter', index: 'third', plugin: 'pre-function' phase: 'log', index: 'first', plugin: 'pre-function' phase: 'log', index: 'second', plugin: 'pre-function' phase: 'log', index: 'third', plugin: 'pre-function' ]]):gsub("pre%-function", plugin_name),content) end) end) end
fix(serverless-functions) travis file-permissions
fix(serverless-functions) travis file-permissions
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
d186a5dd5636e81c9f09adadb19f7e1ad48732cd
coding/textadept/logtalk.lua
coding/textadept/logtalk.lua
-- Copyright © 2017-2019 Michael T. Richter <ttmrichter@gmail.com>. See License.txt. -- Logtalk LPeg lexer. local lexer = require('lexer') local token, word_match = lexer.token, lexer.word_match local P, R, S = lpeg.P, lpeg.R, lpeg.S local lex = lexer.new('logtalk', {inherit = lexer.load('prolog')}) lex:modify_rule('keyword', token(lexer.KEYWORD, word_match[[ -- Logtalk "keywords" generated from Vim syntax highlighting file with Prolog -- keywords stripped since were building up on the Prolog lexer. abolish_category abolish_events abolish_object abolish_protocol after alias as before built_in calls category category_property coinductive complements complements_object conforms_to_protocol context create_category create_object create_protocol create_logtalk_flag current current_category current_event current_logtalk_flag current_object current_protocol define_events domain_error encoding end_category end_class end_object end_protocol evaluation_error existence_error extends extends_category extends_object extends_protocol forward implements implements_protocol imports imports_category include info instantiates instantiates_class instantiation_error is logtalk_compile logtalk_library_path logtalk_load logtalk_load_context logtalk_make logtalk_make_target_action meta_non_terminal mode object object_property parameter permission_error private protected protocol_property representation_error resource_error self sender set_logtalk_flag specializes specializes_class synchronized syntax_error system_error this threaded threaded_call threaded_cancel threaded_engine threaded_engine_create threaded_engine_destroy threaded_engine_fetch threaded_engine_next threaded_engine_next_reified threaded_engine_post threaded_engine_self threaded_engine_yield threaded_exit threaded_ignore threaded_notify threaded_once threaded_peek threaded_wait type_error uses -- info/1 and info/2 predicates have their own keywords manually extracted -- from documentation. comment argnames arguments author version date parameters parnames copyright license remarks see_also ]]) + lex:get_rule('keyword')) return lex
-- Copyright © 2017-2019 Michael T. Richter <ttmrichter@gmail.com>. See License.txt. -- Logtalk LPeg lexer. local lexer = require('lexer') local token, word_match = lexer.token, lexer.word_match local P, R, S = lpeg.P, lpeg.R, lpeg.S local lex = lexer.new('logtalk', {inherit = lexer.load('prolog')}) lex:modify_rule('operator', token(lexer.OPERATOR, S('^/*@-!+\\|=:;&<>()[]{}'))) lex:modify_rule('keyword', token(lexer.KEYWORD, word_match[[ -- Logtalk "keywords" generated from Vim syntax highlighting file with Prolog -- keywords stripped since were building up on the Prolog lexer. abolish_category abolish_events abolish_object abolish_protocol after alias as before built_in calls category category_property coinductive complements complements_object conforms_to_protocol context create_category create_object create_protocol create_logtalk_flag current current_category current_event current_logtalk_flag current_object current_protocol define_events domain_error encoding end_category end_class end_object end_protocol evaluation_error existence_error extends extends_category extends_object extends_protocol forward implements implements_protocol imports imports_category include info instantiates instantiates_class instantiation_error is logtalk_compile logtalk_library_path logtalk_load logtalk_load_context logtalk_make logtalk_make_target_action meta_non_terminal mode object object_property parameter permission_error private protected protocol_property representation_error resource_error self sender set_logtalk_flag specializes specializes_class synchronized syntax_error system_error this threaded threaded_call threaded_cancel threaded_engine threaded_engine_create threaded_engine_destroy threaded_engine_fetch threaded_engine_next threaded_engine_next_reified threaded_engine_post threaded_engine_self threaded_engine_yield threaded_exit threaded_ignore threaded_notify threaded_once threaded_peek threaded_wait type_error uses -- info/1 and info/2 predicates have their own keywords manually extracted -- from documentation. comment argnames arguments author version date parameters parnames copyright license remarks see_also ]]) + lex:get_rule('keyword')) return lex
Fix operator highlighting in the update support for the Textadept editor
Fix operator highlighting in the update support for the Textadept editor
Lua
apache-2.0
LogtalkDotOrg/logtalk3,LogtalkDotOrg/logtalk3,LogtalkDotOrg/logtalk3,LogtalkDotOrg/logtalk3,LogtalkDotOrg/logtalk3,LogtalkDotOrg/logtalk3,LogtalkDotOrg/logtalk3
87bca6ac9a647d0f99e7c60e6daaa01e1a2b4fe2
premake4.lua
premake4.lua
function args_contains( element ) for _, value in pairs(_ARGS) do if value == element then return true end end return false end solution "efsw" location("./make/" .. os.get() .. "/") targetdir("./bin") configurations { "debug", "release" } if os.is("windows") then osfiles = "src/efsw/platform/win/*.cpp" else osfiles = "src/efsw/platform/posix/*.cpp" end -- This is for testing in other platforms that don't support kqueue if args_contains( "kqueue" ) then links { "kqueue" } defines { "EFSW_KQUEUE" } printf("Forced Kqueue backend build.") end -- Activates verbose mode if args_contains( "verbose" ) then defines { "EFSW_VERBOSE" } end if os.is("macosx") then -- Premake 4.4 needed for this if not string.match(_PREMAKE_VERSION, "^4.[123]") then local ver = os.getversion(); if not ( ver.majorversion >= 10 and ver.minorversion >= 5 ) then defines { "EFSW_FSEVENTS_NOT_SUPPORTED" } end end end objdir("obj/" .. os.get() .. "/") project "efsw-static-lib" kind "StaticLib" language "C++" targetdir("./lib") includedirs { "include", "src" } files { "src/efsw/*.cpp", osfiles } configuration "debug" defines { "DEBUG" } flags { "Symbols" } buildoptions{ "-Wall -pedantic -Wno-long-long" } targetname "efsw-static-debug" configuration "release" defines { "NDEBUG" } flags { "Optimize" } targetname "efsw-static-release" project "efsw-test" kind "ConsoleApp" language "C++" links { "efsw-static-lib" } files { "src/test/*.cpp" } includedirs { "include", "src" } if not os.is("windows") and not os.is("haiku") then links { "pthread" } end if os.is("macosx") then links { "CoreFoundation.framework", "CoreServices.framework" } end configuration "debug" defines { "DEBUG" } flags { "Symbols" } buildoptions{ "-Wall" } targetname "efsw-test-debug" configuration "release" defines { "NDEBUG" } flags { "Optimize" } buildoptions{ "-Wall" } targetname "efsw-test-release" project "efsw-shared-lib" kind "SharedLib" language "C++" targetdir("./lib") includedirs { "include", "src" } files { "src/efsw/*.cpp", osfiles } defines { "EFSW_DYNAMIC", "EFSW_EXPORTS" } configuration "debug" defines { "DEBUG" } buildoptions{ "-Wall" } flags { "Symbols" } targetname "efsw-debug" configuration "release" defines { "NDEBUG" } flags { "Optimize" } buildoptions{ "-Wall" } targetname "efsw"
function args_contains( element ) for _, value in pairs(_ARGS) do if value == element then return true end end return false end solution "efsw" location("./make/" .. os.get() .. "/") targetdir("./bin") configurations { "debug", "release" } if os.is("windows") then osfiles = "src/efsw/platform/win/*.cpp" else osfiles = "src/efsw/platform/posix/*.cpp" end -- This is for testing in other platforms that don't support kqueue if args_contains( "kqueue" ) then links { "kqueue" } defines { "EFSW_KQUEUE" } printf("Forced Kqueue backend build.") end -- Activates verbose mode if args_contains( "verbose" ) then defines { "EFSW_VERBOSE" } end if os.is("macosx") then -- Premake 4.4 needed for this if not string.match(_PREMAKE_VERSION, "^4.[123]") then local ver = os.getversion(); if not ( ver.majorversion >= 10 and ver.minorversion >= 5 ) then defines { "EFSW_FSEVENTS_NOT_SUPPORTED" } end end end objdir("obj/" .. os.get() .. "/") project "efsw-static-lib" kind "StaticLib" language "C++" targetdir("./lib") includedirs { "include", "src" } files { "src/efsw/*.cpp", osfiles } configuration "debug" defines { "DEBUG" } flags { "Symbols" } buildoptions{ "-Wall -pedantic -Wno-long-long" } targetname "efsw-static-debug" configuration "release" defines { "NDEBUG" } flags { "Optimize" } targetname "efsw-static-release" project "efsw-test" kind "ConsoleApp" language "C++" links { "efsw-static-lib" } files { "src/test/*.cpp" } includedirs { "include", "src" } if not os.is("windows") and not os.is("haiku") then links { "pthread" } end if os.is("macosx") then links { "CoreFoundation.framework", "CoreServices.framework" } end configuration "debug" defines { "DEBUG" } flags { "Symbols" } buildoptions{ "-Wall" } targetname "efsw-test-debug" configuration "release" defines { "NDEBUG" } flags { "Optimize" } buildoptions{ "-Wall" } targetname "efsw-test-release" project "efsw-shared-lib" kind "SharedLib" language "C++" targetdir("./lib") includedirs { "include", "src" } files { "src/efsw/*.cpp", osfiles } defines { "EFSW_DYNAMIC", "EFSW_EXPORTS" } if not os.is("windows") and not os.is("haiku") then links { "pthread" } end if os.is("macosx") then links { "CoreFoundation.framework", "CoreServices.framework" } end configuration "debug" defines { "DEBUG" } buildoptions{ "-Wall" } flags { "Symbols" } targetname "efsw-debug" configuration "release" defines { "NDEBUG" } flags { "Optimize" } buildoptions{ "-Wall" } targetname "efsw"
Fixed shared library links.
Fixed shared library links.
Lua
mit
pixty/efsw,pixty/efsw,pixty/efsw
5ad0e273eb3ed824bd6d80d9fff85144fa462456
ConfusionMatrix.lua
ConfusionMatrix.lua
local ConfusionMatrix = torch.class('nn.ConfusionMatrix') function ConfusionMatrix:__init(nclasses, classes) self.mat = lab.zeros(nclasses,nclasses) self.valids = lab.zeros(nclasses) self.totalValid = 0 self.averageValid = 0 self.classes = classes end function ConfusionMatrix:add(prediction, target) if type(prediction) == 'number' then -- comparing numbers self.mat[target][prediction] = self.mat[target][prediction] + 1 else -- comparing vectors local _,prediction = lab.max(prediction) local _,target = lab.max(target) self.mat[target[1]][prediction[1]] = self.mat[target[1]][prediction[1]] + 1 end end function ConfusionMatrix:zero() self.mat:zero() self.valids:zero() self.totalValid = 0 self.averageValid = 0 end function ConfusionMatrix:updateValids() local total = 0 for t = 1,self.mat:size(1) do self.valids[t] = self.mat[t][t] / self.mat:select(1,t):sum() total = total + self.mat[t][t] end self.totalValid = total / self.mat:sum() self.averageValid = 0 local nvalids = 0 for t = 1,self.mat:size(1) do if not sys.isNaN(self.valids[t]) then self.averageValid = self.averageValid + self.valids[t] nvalids = nvalids + 1 end end self.averageValid = self.averageValid / nvalids end function ConfusionMatrix:__tostring__() self:updateValids() local str = 'ConfusionMatrix:\n' local nclasses = self.mat:size(1) str = str .. '[' for t = 1,nclasses do local pclass = self.valids[t] * 100 if t == 1 then str = str .. '[' else str = str .. ' [' end for p = 1,nclasses do str = str .. '' .. string.format('%8d\t', self.mat[t][p]) end if self.classes then if t == nclasses then str = str .. ']] ' .. pclass .. '% \t[class: ' .. (self.classes[t] or '') .. ']\n' else str = str .. '] ' .. pclass .. '% \t[class: ' .. (self.classes[t] or '') .. ']\n' end else if t == nclasses then str = str .. ']] ' .. pclass .. '% \n' else str = str .. '] ' .. pclass .. '% \n' end end end str = str .. ' + average row correct: ' .. (self.averageValid*100) .. '% \n' str = str .. ' + global correct: ' .. (self.totalValid*100) .. '%' return str end
local ConfusionMatrix = torch.class('nn.ConfusionMatrix') function ConfusionMatrix:__init(nclasses, classes) self.mat = lab.zeros(nclasses,nclasses) self.valids = lab.zeros(nclasses) self.nclasses = nclasses self.totalValid = 0 self.averageValid = 0 self.classes = classes end function ConfusionMatrix:add(prediction, target) if type(prediction) == 'number' then -- comparing numbers self.mat[target][prediction] = self.mat[target][prediction] + 1 else -- comparing vectors local prediction_1d = torch.Tensor(prediction):resize(self.nclasses) local target_1d = torch.Tensor(target):resize(self.nclasses) local _,prediction = lab.max(prediction_1d) local _,target = lab.max(target_1d) self.mat[target[1]][prediction[1]] = self.mat[target[1]][prediction[1]] + 1 end end function ConfusionMatrix:zero() self.mat:zero() self.valids:zero() self.totalValid = 0 self.averageValid = 0 end function ConfusionMatrix:updateValids() local total = 0 for t = 1,self.nclasses do self.valids[t] = self.mat[t][t] / self.mat:select(1,t):sum() total = total + self.mat[t][t] end self.totalValid = total / self.mat:sum() self.averageValid = 0 local nvalids = 0 for t = 1,self.nclasses do if not sys.isNaN(self.valids[t]) then self.averageValid = self.averageValid + self.valids[t] nvalids = nvalids + 1 end end self.averageValid = self.averageValid / nvalids end function ConfusionMatrix:__tostring__() self:updateValids() local str = 'ConfusionMatrix:\n' local nclasses = self.nclasses str = str .. '[' for t = 1,nclasses do local pclass = self.valids[t] * 100 if t == 1 then str = str .. '[' else str = str .. ' [' end for p = 1,nclasses do str = str .. '' .. string.format('%8d\t', self.mat[t][p]) end if self.classes then if t == nclasses then str = str .. ']] ' .. pclass .. '% \t[class: ' .. (self.classes[t] or '') .. ']\n' else str = str .. '] ' .. pclass .. '% \t[class: ' .. (self.classes[t] or '') .. ']\n' end else if t == nclasses then str = str .. ']] ' .. pclass .. '% \n' else str = str .. '] ' .. pclass .. '% \n' end end end str = str .. ' + average row correct: ' .. (self.averageValid*100) .. '% \n' str = str .. ' + global correct: ' .. (self.totalValid*100) .. '%' return str end
Fixed ConfusionMatrix:add()
Fixed ConfusionMatrix:add()
Lua
mit
clementfarabet/lua---nnx
3981a1ccca43f389fa6705b996d7bc9bb6895792
lib/switchboard_modules/lua_script_debugger/premade_scripts/13_uart_example.lua
lib/switchboard_modules/lua_script_debugger/premade_scripts/13_uart_example.lua
print("Basic UART example.") print("Please connect a jumper wire between FIO0 and FIO1 (FIO4 and FIO5 on T4)") print("") --UART part of the T7 datasheet http://labjack.com/support/datasheets/t7/digital-io/asynchronous-serial local mbRead=MB.R --local functions for faster processing local mbWrite=MB.W local RXPin = 1--FIO1. Changed if T4 instead of T7 local TXPin = 0--FIO0 devType = MB.R(60000, 3) if devType == 4 then RXPin = 5--FIO5 on T4 TXPin = 4--FIO4 end mbWrite(5400, 0, 0) --disable ASYNCH during config -- Baud Example Options: 4800,9600,14400,19200,38400,57600,115200 mbWrite(5420, 1, 9600) --baud, 9600 is default of FGPMMOPA6H mbWrite(5405, 0, RXPin) --RX set to FIO1 (FIO5 on T4) mbWrite(5410, 0, TXPin) --TX set to FIO0 (FIO4 on T4) mbWrite(5460, 0, 0) --ASYNCH_PARITY set to 0=none mbWrite(5430, 0, 600) --ASYNCH_RX_BUFFER_SIZE_BYTES set to 600 mbWrite(5400, 0, 1) --enable ASYNCH -- Various variables local UART_TEST_STRING = "Hello World!" local strLen = 0 local strData = {} -- Set the baud rate local strLen = string.len(UART_TEST_STRING) print("Sending String of length:", strLen) -- Allocate space for the string mbWrite(5440, 0, strLen) --ASYNCH_NUM_BYTES_TX, UINT16 (0) --Convert and write string to the allocated UART TX buffer for i=1, strLen do -- COnvert ASCII character to number local ASCIIcharAsByte = string.byte(UART_TEST_STRING, i) -- Write data to TX buffer mbWrite(5490, 0, ASCIIcharAsByte) --ASYNCH_DATA_TX, UINT16 (0) end -- Send data saved in TX buffer mbWrite(5450, 0, 1) --ASYNCH_TX_GO, UINT16(0) -- Configure the interval timer for once per second. LJ.IntervalConfig(0, 1000) local checkInterval=LJ.CheckInterval -- Variables used to end the program local maxNumIterations = 3 local currentIteration = 0 local runApp = true -- Enter while loop. while runApp do -- Check to see if the interval is completed. if checkInterval(0) then -- Read the number of bytes in RX buffer local numBytesRX = mbRead(5435, 0) --ASYNCH_NUM_BYTES_RX, UINT16(0) -- If there are more than zero bytes... if numBytesRX > 0 then print ("numBytesRX ", numBytesRX) -- Allocate a string to save data to local dataStr = "" -- Read data from the T7 and conver to a string for i=1, numBytesRX do local dataByte = mbRead(5495, 0) --ASYNCH_DATA_RX, UINT16(0) local dataChar = string.char(dataByte) dataStr = dataStr .. dataChar end print("Data:",dataStr) end -- Decide when to exit if currentIteration < maxNumIterations then currentIteration = currentIteration + 1 else runApp = false end end end print("Script Finished") mbWrite(6000, 1, 0)
--[[ Name: 13_uart_example.lua Desc: Example showing how to use a UART Note: This example requires you to connect a jumper between the RX and TX pins See the UART section of the T7 datasheet: http://labjack.com/support/datasheets/t7/digital-io/asynchronous-serial This example requires firmware 1.0282 (T7) or 1.0023 (T4) --]] print("Basic UART example.") print("Please connect a jumper wire between FIO0 and FIO1 (FIO4 and FIO5 on T4)") print("") -- Assume the device being used is a T7, use FIO1 for the RX pin local rxpin = 1 -- Use FIO0 for the TX pin local txpin = 0 local devtype = MB.readName("PRODUCT_ID") -- If actually using a T4 if devtype == 4 then -- Change the RX pin to FIO5 rxpin = 5 -- Change the TX pin to FIO4 txpin = 4 end --disable ASYNCH during configuration MB.writeName("ASYNCH_ENABLE", 0) -- Baud Example Options: 4800,9600,14400,19200,38400,57600,115200 MB.writeName("ASYNCH_BAUD", 9600) -- Set the RX pin MB.writeName("ASYNCH_RX_DIONUM", rxpin) -- Set the TX pin MB.writeName("ASYNCH_TX_DIONUM", txpin) -- Set 0 parity MB.writeName("ASYNCH_PARITY", 0) -- Set the buffer size to be 600 bytes MB.writeName("ASYNCH_RX_BUFFER_SIZE_BYTES", 600) -- Enable ASYNCH MB.writeName("ASYNCH_ENABLE", 1) local teststring = "Hello World!" local strlen = string.len(teststring) print("Sending String of length:", strlen) -- Configure an interval of 1000ms LJ.IntervalConfig(0, 1000) -- Variables used to stop the program local maxiterations = 3 local currentiteration = 0 local running = true while running do -- Check to see if the interval is completed. if LJ.CheckInterval(0) then -- Allocate space for the string MB.writeName("ASYNCH_NUM_BYTES_TX", strlen) -- Convert and write the string to the UART TX buffer for i=1, strlen do -- Convert ASCII character to number local charbyte = string.byte(teststring, i) -- Write data to the TX buffer MB.writeName("ASYNCH_DATA_TX", charbyte) end -- Send data saved in the TX buffer MB.writeName("ASYNCH_TX_GO", 1) -- Read the number of bytes in RX buffer local rxbytes = MB.readName("ASYNCH_NUM_BYTES_RX") -- If there are more than zero bytes... if rxbytes > 0 then print ("RX bytes ", rxbytes) -- Allocate a string to save data to local datastr = "" -- Read data from the T7 and convert it to a string for i=1, rxbytes do local databyte = MB.readName("ASYNCH_DATA_RX") local datachar = string.char(databyte) -- Concatenate the data string with the data char datastr = datastr .. datachar end print("Data:",datastr) print("") end -- Exit after 3 iterations if currentiteration < maxiterations then currentiteration = currentiteration + 1 else running = false end end end print("Script Finished") -- Writing 0 to LUA_RUN stops the script MB.writeName("LUA_RUN", 0)
Fixed up the formatting of the UART example
Fixed up the formatting of the UART example
Lua
mit
chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager,chrisJohn404/ljswitchboard-module_manager
63d0a242f9d3e2a48bcf871249119a36b8f0ffbc
libs/web/luasrc/template.lua
libs/web/luasrc/template.lua
--[[ LuCI - Template Parser Description: A template parser supporting includes, translations, Lua code blocks and more. It can be used either as a compiler or as an interpreter. FileId: $Id$ License: Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- module("luci.template", package.seeall) require("luci.config") require("luci.util") require("luci.fs") require("luci.http") luci.config.template = luci.config.template or {} viewdir = luci.config.template.viewdir or luci.sys.libpath() .. "/view" compiledir = luci.config.template.compiledir or luci.sys.libpath() .. "/view" -- Enforce cache security compiledir = compiledir .. "/" .. luci.sys.process.info("uid") -- Compile modes: -- none: Never compile, only use precompiled data from files -- memory: Always compile, do not save compiled files, ignore precompiled -- file: Compile on demand, save compiled files, update precompiled compiler_mode = luci.config.template.compiler_mode or "memory" -- Define the namespace for template modules viewns = { write = io.write, include = function(name) Template(name):render(getfenv(2)) end, } -- Compiles a given template into an executable Lua module function compile(template) -- Search all <% %> expressions (remember: Lua table indexes begin with #1) local function expr_add(command) table.insert(expr, command) return "<%" .. tostring(#expr) .. "%>" end -- As "expr" should be local, we have to assign it to the "expr_add" scope local expr = {} luci.util.extfenv(expr_add, "expr", expr) -- Save all expressiosn to table "expr" template = template:gsub("<%%(.-)%%>", expr_add) local function sanitize(s) s = luci.util.escape(s) s = luci.util.escape(s, "'") s = luci.util.escape(s, "\n") return s end -- Escape and sanitize all the template (all non-expressions) template = sanitize(template) -- Template module header/footer declaration local header = "write('" local footer = "')" template = header .. template .. footer -- Replacements local r_include = "')\ninclude('%s')\nwrite('" local r_i18n = "'..translate('%1','%2')..'" local r_pexec = "'..(%s or '')..'" local r_exec = "')\n%s\nwrite('" -- Parse the expressions for k,v in pairs(expr) do local p = v:sub(1, 1) local re = nil if p == "+" then re = r_include:format(sanitize(string.sub(v, 2))) elseif p == ":" then re = sanitize(v):gsub(":(.-) (.+)", r_i18n) elseif p == "=" then re = r_pexec:format(v:sub(2)) else re = r_exec:format(v) end template = template:gsub("<%%"..tostring(k).."%%>", re) end return loadstring(template) end -- Oldstyle render shortcut function render(name, scope, ...) scope = scope or getfenv(2) local s, t = pcall(Template, name) if not s then error(t) else t:render(scope, ...) end end -- Template class Template = luci.util.class() -- Shared template cache to store templates in to avoid unnecessary reloading Template.cache = {} -- Constructor - Reads and compiles the template on-demand function Template.__init__(self, name) if self.cache[name] then self.template = self.cache[name] else self.template = nil end -- Create a new namespace for this template self.viewns = {} -- Copy over from general namespace for k, v in pairs(viewns) do self.viewns[k] = v end -- If we have a cached template, skip compiling and loading if self.template then return end -- Compile and build local sourcefile = viewdir .. "/" .. name .. ".htm" local compiledfile = compiledir .. "/" .. luci.http.urlencode(name) .. ".lua" local err if compiler_mode == "file" then local tplmt = luci.fs.mtime(sourcefile) local commt = luci.fs.mtime(compiledfile) if not luci.fs.mtime(compiledir) then luci.fs.mkdir(compiledir, true) end -- Build if there is no compiled file or if compiled file is outdated if ((commt == nil) and not (tplmt == nil)) or (not (commt == nil) and not (tplmt == nil) and commt < tplmt) then local source source, err = luci.fs.readfile(sourcefile) if source then local compiled, err = compile(source) luci.fs.writefile(compiledfile, luci.util.dump(compiled)) self.template = compiled end else self.template, err = loadfile(compiledfile) end elseif compiler_mode == "none" then self.template, err = loadfile(self.compiledfile) elseif compiler_mode == "memory" then local source source, err = luci.fs.readfile(sourcefile) if source then self.template, err = compile(source) end end -- If we have no valid template throw error, otherwise cache the template if not self.template then error(err) else self.cache[name] = self.template end end -- Renders a template function Template.render(self, scope) scope = scope or getfenv(2) -- Save old environment local oldfenv = getfenv(self.template) -- Put our predefined objects in the scope of the template luci.util.resfenv(self.template) luci.util.updfenv(self.template, scope) luci.util.updfenv(self.template, self.viewns) -- Now finally render the thing self.template() -- Reset environment setfenv(self.template, oldfenv) end
--[[ LuCI - Template Parser Description: A template parser supporting includes, translations, Lua code blocks and more. It can be used either as a compiler or as an interpreter. FileId: $Id$ License: Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- module("luci.template", package.seeall) require("luci.config") require("luci.util") require("luci.fs") require("luci.http") luci.config.template = luci.config.template or {} viewdir = luci.config.template.viewdir or luci.sys.libpath() .. "/view" compiledir = luci.config.template.compiledir or luci.sys.libpath() .. "/view" -- Enforce cache security compiledir = compiledir .. "/" .. luci.sys.process.info("uid") -- Compile modes: -- none: Never compile, only use precompiled data from files -- memory: Always compile, do not save compiled files, ignore precompiled -- file: Compile on demand, save compiled files, update precompiled compiler_mode = luci.config.template.compiler_mode or "memory" -- Define the namespace for template modules viewns = { write = io.write, include = function(name) Template(name):render(getfenv(2)) end, } -- Compiles a given template into an executable Lua module function compile(template) -- Search all <% %> expressions (remember: Lua table indexes begin with #1) local function expr_add(command) table.insert(expr, command) return "<%" .. tostring(#expr) .. "%>" end -- As "expr" should be local, we have to assign it to the "expr_add" scope local expr = {} luci.util.extfenv(expr_add, "expr", expr) -- Save all expressiosn to table "expr" template = template:gsub("<%%(.-)%%>", expr_add) local function sanitize(s) s = luci.util.escape(s) s = luci.util.escape(s, "'") s = luci.util.escape(s, "\n") return s end -- Escape and sanitize all the template (all non-expressions) template = sanitize(template) -- Template module header/footer declaration local header = "write('" local footer = "')" template = header .. template .. footer -- Replacements local r_include = "')\ninclude('%s')\nwrite('" local r_i18n = "'..translate('%1','%2')..'" local r_pexec = "'..(%s or '')..'" local r_exec = "')\n%s\nwrite('" -- Parse the expressions for k,v in pairs(expr) do local p = v:sub(1, 1) local re = nil if p == "+" then re = r_include:format(sanitize(string.sub(v, 2))) elseif p == ":" then re = sanitize(v):gsub(":(.-) (.+)", r_i18n) elseif p == "=" then re = r_pexec:format(v:sub(2)) else re = r_exec:format(v) end template = template:gsub("<%%"..tostring(k).."%%>", re) end return loadstring(template) end -- Oldstyle render shortcut function render(name, scope, ...) scope = scope or getfenv(2) local s, t = pcall(Template, name) if not s then error(t) else t:render(scope, ...) end end -- Template class Template = luci.util.class() -- Shared template cache to store templates in to avoid unnecessary reloading Template.cache = {} -- Constructor - Reads and compiles the template on-demand function Template.__init__(self, name) if self.cache[name] then self.template = self.cache[name] else self.template = nil end -- Create a new namespace for this template self.viewns = {} -- Copy over from general namespace for k, v in pairs(viewns) do self.viewns[k] = v end -- If we have a cached template, skip compiling and loading if self.template then return end -- Compile and build local sourcefile = viewdir .. "/" .. name .. ".htm" local compiledfile = compiledir .. "/" .. luci.http.urlencode(name) .. ".lua" local err if compiler_mode == "file" then local tplmt = luci.fs.mtime(sourcefile) local commt = luci.fs.mtime(compiledfile) if not luci.fs.mtime(compiledir) then luci.fs.mkdir(compiledir, true) luci.fs.chmod(luci.fs.dirname(compiledir), "a+rxw") end -- Build if there is no compiled file or if compiled file is outdated if ((commt == nil) and not (tplmt == nil)) or (not (commt == nil) and not (tplmt == nil) and commt < tplmt) then local source source, err = luci.fs.readfile(sourcefile) if source then local compiled, err = compile(source) luci.fs.writefile(compiledfile, luci.util.dump(compiled)) self.template = compiled end else self.template, err = loadfile(compiledfile) end elseif compiler_mode == "none" then self.template, err = loadfile(self.compiledfile) elseif compiler_mode == "memory" then local source source, err = luci.fs.readfile(sourcefile) if source then self.template, err = compile(source) end end -- If we have no valid template throw error, otherwise cache the template if not self.template then error(err) else self.cache[name] = self.template end end -- Renders a template function Template.render(self, scope) scope = scope or getfenv(2) -- Save old environment local oldfenv = getfenv(self.template) -- Put our predefined objects in the scope of the template luci.util.resfenv(self.template) luci.util.updfenv(self.template, scope) luci.util.updfenv(self.template, self.viewns) -- Now finally render the thing self.template() -- Reset environment setfenv(self.template, oldfenv) end
* Fixed last commit
* Fixed last commit
Lua
apache-2.0
deepak78/luci,8devices/luci,8devices/luci,8devices/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci
9f5707f3b08149c0a232aef08861c6db64251574
tools/rest_translation_server.lua
tools/rest_translation_server.lua
#!/usr/bin/env lua --[[ This requires the restserver-xavante rock to run. run server (this file) th tools/rest_translation_server.lua -model ../Recipes/baseline-1M-enfr/exp/model-baseline-1M-enfr_epoch13_3.44.t7 -gpuid 1 query the server curl -v -H "Content-Type: application/json" -X POST -d '{ "src" : "international migration" }' http://127.0.0.1:8080/translator/translate ]] require('onmt.init') local separators = require('tools.utils.separators') local tokenizer = require('tools.utils.tokenizer') local cmd = onmt.utils.ExtendedCmdLine.new('rest_translation_server.lua') local options = { {'-host', '127.0.0.1', [[Host to run the server on]]}, {'-port', '8080', [[Port to run the server on]]} } cmd:setCmdLineOptions(options, 'Server') onmt.translate.Translator.declareOpts(cmd) cmd:text("") cmd:text("**Other options**") cmd:text("") onmt.utils.Cuda.declareOpts(cmd) onmt.utils.Logger.declareOpts(cmd) cmd:option('-mode', 'conservative', [[Define how aggressive should the tokenization be - 'aggressive' only keeps sequences of letters/numbers, 'conservative' allows mix of alphanumeric as in: '2,000', 'E65', 'soft-landing']]) cmd:option('-joiner_annotate', false, [[Include joiner annotation using 'joiner' character]]) cmd:option('-joiner', separators.joiner_marker, [[Character used to annotate joiners]]) cmd:option('-joiner_new', false, [[in joiner_annotate mode, 'joiner' is an independent token]]) cmd:option('-case_feature', false, [[Generate case feature]]) cmd:option('-bpe_model', '', [[Apply Byte Pair Encoding if the BPE model path is given]]) cmd:option('-nparallel', 1, [[Number of parallel thread to run the tokenization]]) cmd:option('-batchsize', 1000, [[Size of each parallel batch - you should not change except if low memory]]) local opt = cmd:parse(arg) local function translateMessage(translator, lines) local batch = {} -- We need to tokenize the input line before translation local srcTokens = {} local bpe local srcTokenized = {} local res local err local tokens local BPE = require ('tools.utils.BPE') if opt.bpe_model ~= '' then bpe = BPE.new(opt.bpe_model, opt.joiner_annotate, opt.joiner_new) end res, err = pcall(function() tokens = tokenizer.tokenize(opt, lines.src, bpe) end) -- it can generate an exception if there are utf-8 issues in the text if not res then if string.find(err, "interrupted") then error("interrupted") else error("unicode error in line " .. err) end end table.insert(srcTokenized, table.concat(tokens, ' ')) -- Extract from the line. for word in srcTokenized[1]:gmatch'([^%s]+)' do table.insert(srcTokens, word) end -- Currently just a single batch. table.insert(batch, translator:buildInput(srcTokens)) -- Translate local results = translator:translate(batch) -- Return the nbest translations for each in the batch. local translations = {} local ret = {} for i = 1, translator.opt.n_best do local srcSent = translator:buildOutput(batch[1]) local predSent = translator:buildOutput(results[1].preds[i]) local oline res, err = pcall(function() oline = tokenizer.detokenize(predSent, opt) end) -- table.insert(output, oline) if not res then if string.find(err,"interrupted") then error("interrupted") else error("unicode error in line ".. err) end end local attnTable = {} for j = 1, #results[1].preds[i].attention do table.insert(attnTable, results[1].preds[i].attention[j]:totable()) end table.insert(ret, { tgt = oline, attn = attnTable, src = srcSent, n_best = i, pred_score = results[1].preds[i].score }) end table.insert(translations, ret) return translations end local restserver = require("restserver") local server = restserver:new():port(opt.port) local translator server:add_resource("translator", { { method = "POST", path = "/translate", consumes = "application/json", produces = "application/json", input_schema = { src = { type = "string" }, }, handler = function(req) print("receiving request: ") print(req) local translate = translateMessage(translator, req) print("sending response: ") print(translate) return restserver.response():status(200):entity(translate) end, }, }) local function main() _G.logger = onmt.utils.Logger.new(opt.log_file, opt.disable_logs, opt.log_level) _G.logger:info("Loading model") translator = onmt.translate.Translator.new(opt) -- This loads the restserver.xavante plugin server:enable("restserver.xavante"):start() end main()
#!/usr/bin/env lua --[[ This requires the restserver-xavante rock to run. run server (this file) th tools/rest_translation_server.lua -model ../Recipes/baseline-1M-enfr/exp/model-baseline-1M-enfr_epoch13_3.44.t7 -gpuid 1 query the server curl -v -H "Content-Type: application/json" -X POST -d '{ "src" : "international migration" }' http://127.0.0.1:8080/translator/translate ]] require('onmt.init') local separators = require('tools.utils.separators') local tokenizer = require('tools.utils.tokenizer') local cmd = onmt.utils.ExtendedCmdLine.new('rest_translation_server.lua') local options = { {'-host', '127.0.0.1', [[Host to run the server on]]}, {'-port', '8080', [[Port to run the server on]]} } cmd:setCmdLineOptions(options, 'Server') onmt.translate.Translator.declareOpts(cmd) cmd:text("") cmd:text("**Other options**") cmd:text("") onmt.utils.Cuda.declareOpts(cmd) onmt.utils.Logger.declareOpts(cmd) cmd:option('-mode', 'conservative', [[Define how aggressive should the tokenization be - 'aggressive' only keeps sequences of letters/numbers, 'conservative' allows mix of alphanumeric as in: '2,000', 'E65', 'soft-landing']]) cmd:option('-joiner_annotate', false, [[Include joiner annotation using 'joiner' character]]) cmd:option('-joiner', separators.joiner_marker, [[Character used to annotate joiners]]) cmd:option('-joiner_new', false, [[in joiner_annotate mode, 'joiner' is an independent token]]) cmd:option('-case_feature', false, [[Generate case feature]]) cmd:option('-bpe_model', '', [[Apply Byte Pair Encoding if the BPE model path is given]]) cmd:option('-nparallel', 1, [[Number of parallel thread to run the tokenization]]) cmd:option('-batchsize', 1000, [[Size of each parallel batch - you should not change except if low memory]]) local opt = cmd:parse(arg) local function translateMessage(translator, lines) local batch = {} -- We need to tokenize the input line before translation local srcTokens = {} local bpe local srcTokenized = {} local res local err local tokens local BPE = require ('tools.utils.BPE') timer = torch.Timer() if opt.bpe_model ~= '' then bpe = BPE.new(opt.bpe_model, opt.joiner_annotate, opt.joiner_new) end res, err = pcall(function() tokens = tokenizer.tokenize(opt, lines.src, bpe) end) -- it can generate an exception if there are utf-8 issues in the text if not res then if string.find(err, "interrupted") then error("interrupted") else error("unicode error in line " .. err) end end table.insert(srcTokenized, table.concat(tokens, ' ')) -- Extract from the line. for word in srcTokenized[1]:gmatch'([^%s]+)' do table.insert(srcTokens, word) end print('it took: ' .. timer:time().real .. 'seconds to tokenize') -- Currently just a single batch. table.insert(batch, translator:buildInput(srcTokens)) timer = torch.Timer() -- Translate local results = translator:translate(batch) print('it took: ' .. timer:time().real .. 'seconds to translate') -- Return the nbest translations for each in the batch. local translations = {} local ret = {} for i = 1, translator.opt.n_best do local srcSent = translator:buildOutput(batch[1]) local predSent = translator:buildOutput(results[1].preds[i]) local oline res, err = pcall(function() oline = tokenizer.detokenize(predSent, opt) end) -- table.insert(output, oline) if not res then if string.find(err,"interrupted") then error("interrupted") else error("unicode error in line ".. err) end end local attnTable = {} for j = 1, #results[1].preds[i].attention do table.insert(attnTable, results[1].preds[i].attention[j]:totable()) end table.insert(ret, { tgt = oline, attn = attnTable, src = srcSent, n_best = i, pred_score = results[1].preds[i].score }) end table.insert(translations, ret) return translations end local restserver = require("restserver") local server = restserver:new():port(opt.port) local translator server:add_resource("translator", { { method = "POST", path = "/translate", consumes = "application/json", produces = "application/json", input_schema = { src = { type = "string" }, }, handler = function(req) print("receiving request: ") print(req) local translate = translateMessage(translator, req) print("sending response: ") -- print(translate) return restserver.response():status(200):entity(translate) end, }, }) local function main() _G.logger = onmt.utils.Logger.new(opt.log_file, opt.disable_logs, opt.log_level) _G.logger:info("Loading model") translator = onmt.translate.Translator.new(opt) -- This loads the restserver.xavante plugin server:enable("restserver.xavante"):start() end main()
minor fix
minor fix
Lua
mit
da03/OpenNMT,monsieurzhang/OpenNMT,jsenellart-systran/OpenNMT,jungikim/OpenNMT,monsieurzhang/OpenNMT,jungikim/OpenNMT,da03/OpenNMT,jsenellart/OpenNMT,jsenellart/OpenNMT,jungikim/OpenNMT,monsieurzhang/OpenNMT,OpenNMT/OpenNMT,jsenellart-systran/OpenNMT,da03/OpenNMT,jsenellart-systran/OpenNMT,jsenellart/OpenNMT,OpenNMT/OpenNMT,OpenNMT/OpenNMT
2af3edee13cd2a0367477e784c4d1bf033b36969
lua/entities/gmod_wire_nailer.lua
lua/entities/gmod_wire_nailer.lua
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Nailer" ENT.RenderGroup = RENDERGROUP_BOTH ENT.WireDebugName = "Nailer" function ENT:SetupDataTables() self:NetworkVar( "Float", 0, "BeamLength" ) self:NetworkVar( "Bool", 0, "ShowBeam" ) end if CLIENT then return end -- No more client function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.Inputs = Wire_CreateInputs(self, { "A" }) self:SetBeamLength(2048) end function ENT:Setup(flim, Range, ShowBeam) self.Flim = math.Clamp(flim, 0, 10000) if Range then self:SetBeamLength(Range) end if ShowBeam ~= nil then self:SetShowBeam(ShowBeam) end self:ShowOutput() end function ENT:CanNail(trace) -- Bail if we hit world or a player if not IsValid(trace.Entity) or trace.Entity:IsPlayer() then return false end -- If there's no physics object then we can't constraint it! if not util.IsValidPhysicsObject(trace.Entity, trace.PhysicsBone) then return false end -- The nailer tool no longer exists, but we ask for permission under its name anyway if not hook.Run( "CanTool", self:GetOwner(), trace, "nailer" ) then return false end return true end function ENT:TriggerInput(iname, value) if iname == "A" and value ~= 0 then local vStart = self:GetPos() local vForward = self:GetUp() local trace1 = util.TraceLine { start = vStart, endpos = vStart + (vForward * self:GetBeamLength()), filter = { self } } if not self:CanNail(trace1) then return end local trace2 = util.TraceLine { start = trace1.HitPos, endpos = trace1.HitPos + (vForward * 50.0), filter = { trace1.Entity, self } } if not self:CanNail(trace2) then return end local constraint = constraint.Weld( trace1.Entity, trace2.Entity, trace1.PhysicsBone, trace2.PhysicsBone, self.Flim ) -- effect on weld (tomb332) local effectdata = EffectData() effectdata:SetOrigin( trace2.HitPos ) effectdata:SetNormal( trace1.HitNormal ) effectdata:SetMagnitude( 5 ) effectdata:SetScale( 1 ) effectdata:SetRadius( 10 ) util.Effect( "Sparks", effectdata ) end end function ENT:ShowOutput() self:SetOverlayText("Force Limit: " .. self.Flim ) end duplicator.RegisterEntityClass("gmod_wire_nailer", WireLib.MakeWireEnt, "Data", "Flim")
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Nailer" ENT.RenderGroup = RENDERGROUP_BOTH ENT.WireDebugName = "Nailer" function ENT:SetupDataTables() self:NetworkVar( "Float", 0, "BeamLength" ) self:NetworkVar( "Bool", 0, "ShowBeam" ) end if CLIENT then return end -- No more client function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.Inputs = WireLib.CreateInputs(self, { "Weld", "Axis", "Ballsocket" }) self:SetBeamLength(2048) end function ENT:Setup(flim, Range, ShowBeam) self.Flim = math.Clamp(flim, 0, 10000) if Range then self:SetBeamLength(Range) end if ShowBeam ~= nil then self:SetShowBeam(ShowBeam) end self:ShowOutput() end function ENT:CanNail(trace) -- Bail if we hit world or a player if not IsValid(trace.Entity) or trace.Entity:IsPlayer() then return false end -- If there's no physics object then we can't constraint it! if not util.IsValidPhysicsObject(trace.Entity, trace.PhysicsBone) then return false end -- The nailer tool no longer exists, but we ask for permission under its name anyway if hook.Run( "CanTool", self:GetPlayer(), trace, "nailer" ) == false then return false end return true end function ENT:TriggerInput(name, value) if value == 0 then return end local up = self:GetUp() local trace1 = util.TraceLine( { start = self:GetPos(), endpos = self:GetPos() + up * self:GetBeamLength(), filter = { self } } ) if not self:CanNail( trace1 ) then return end local trace2 = util.TraceLine( { start = trace1.HitPos, endpos = trace1.HitPos + up * 50, filter = { trace1.Entity, self } } ) if not self:CanNail( trace2 ) then return end if name == "Weld" then constraint.Weld( trace1.Entity, trace2.Entity, trace1.PhysicsBone, trace2.PhysicsBone, self.Flim ) elseif name == "Axis" then local phys1 = trace1.Entity:GetPhysicsObject() local phys2 = trace2.Entity:GetPhysicsObject() if not IsValid( phys1 ) or not IsValid( phys2 ) then return end local LPos1 = phys1:WorldToLocal( trace2.HitPos + trace2.HitNormal ) local LPos2 = phys2:WorldToLocal( trace2.HitPos ) constraint.Axis( trace1.Entity, trace2.Entity, trace1.PhysicsBone, trace2.PhysicsBone, LPos1, LPos2, self.Flim ) elseif name == "Ballsocket" then constraint.Ballsocket( trace1.Entity, trace2.Entity, trace1.PhysicsBone, trace2.PhysicsBone, trace2.Entity:WorldToLocal(trace1.HitPos), self.Flim ) end -- effect on weld (tomb332) local effectdata = EffectData() effectdata:SetOrigin( trace2.HitPos ) effectdata:SetNormal( trace1.HitNormal ) effectdata:SetMagnitude( 5 ) effectdata:SetScale( 1 ) effectdata:SetRadius( 10 ) util.Effect( "Sparks", effectdata, false, true ) end function ENT:ShowOutput() self:SetOverlayText(string.format( "Range: %s\nForce limit: %s", math.Round(self:GetBeamLength(),2), math.Round(self.Flim,2) )) end WireLib.AddInputAlias( "A", "Weld" ) duplicator.RegisterEntityClass("gmod_wire_nailer", WireLib.MakeWireEnt, "Data", "Flim", "Range", "ShowBeam")
Updated nailer
Updated nailer Added axis and ballsocket inputs Fixes #883
Lua
apache-2.0
immibis/wiremod,NezzKryptic/Wire,garrysmodlua/wire,sammyt291/wire,notcake/wire,wiremod/wire,bigdogmat/wire,dvdvideo1234/wire,Grocel/wire,thegrb93/wire,mitterdoo/wire,rafradek/wire,plinkopenguin/wiremod,CaptainPRICE/wire,Python1320/wire,mms92/wire
2555495d0754be12e3de4edc9e1b2e67da1d4ac7
lua/weapons/disguiser/sh_init.lua
lua/weapons/disguiser/sh_init.lua
/** * Disguiser SWEP - Lets you disguise as any prop on a map. * * File: * sh_init.lua * * Purpose: * Initializes all the stuff and data that client and server share. * * Copyright (C) 2013 Carl Kittelberger (Icedream) * * 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/>. */ // DEBUG DEBUG DEBUG print("[Disguiser] Loading shared...") // Weapon info SWEP.Author = "Icedream" SWEP.Contact = "icedream@modernminas.de" SWEP.Category = "Fun" SWEP.Purpose = "Lets you disguise as a map model." SWEP.Instructions = "Aim at a model on the map and press the left mouse button to disguise." .. " Undisguise with right mouse button." SWEP.Spawnable = true SWEP.AdminSpawnable = true SWEP.UseHands = true SWEP.ViewModel = "models/weapons/c_toolgun.mdl" SWEP.WorldModel = "models/weapons/w_toolgun.mdl" // Disable ammo system SWEP.DrawAmmo = false SWEP.Primary.ClipSize = -1 SWEP.Primary.DefaultClip = -1 SWEP.Primary.Automatic = false SWEP.Primary.Ammo = "none" // lasers would be nice :3 SWEP.Secondary.ClipSize = -1 SWEP.Secondary.DefaultClip = -1 SWEP.Secondary.Automatic = false SWEP.Secondary.Ammo = "none" // Precache models util.PrecacheModel(SWEP.ViewModel) util.PrecacheModel(SWEP.WorldModel) // Sounds SWEP.Sounds = { Disguise = { "garrysmod/balloon_pop_cute.wav" }, Undisguise = { "garrysmod/balloon_pop_cute.wav" }, Shot = { "weapons/disguiser/shot1.mp3" // original sound by http://freesound.org/people/ejfortin/sounds/49678/ } } SWEP.ChannelMapping = { Disguise = { Channel = CHAN_BODY, Volume = 1.0, Level = 85, Pitch = { 70, 130 } }, Undisguise = { Channel = CHAN_BODY, Volume = 1.0, Level = 85, Pitch = { 70, 130 } }, Shot = { Channel = CHAN_WEAPON, Volume = 0.5, Level = 60, Pitch = { 80, 160 } } } // Load the sounds for soundName, soundPaths in pairs(SWEP.Sounds) do local internalSoundName = "Disguiser." .. soundName for k, soundPath in pairs(soundPaths) do if SERVER then resource.AddFile("sound/" .. soundPath) end if !file.Exists("sound/" .. soundPath, "GAME") then MsgC(Color(255, 0, 0), "[Disguiser] WARNING: Sound not found: " .. soundPath) end util.PrecacheSound(soundPath) end print("[Disguiser] Loading sound " .. internalSoundName .. "...") sound.Add({ name = internalSoundName, channel = SWEP.ChannelMapping[soundName].Channel, volume = SWEP.ChannelMapping[soundName].Volume, soundlevel = SWEP.ChannelMapping[soundName].Level, pitchstart = SWEP.ChannelMapping[soundName].Pitch[0], pitchend = SWEP.ChannelMapping[soundName].Pitch[1], sound = soundPaths }) end function SWEP:DoShootEffect(hitpos, hitnormal, entity, physbone, bFirstTimePredicted) if SERVER then umsg.Start("disguiserShootFX", self.Owner) umsg.Vector(hitpos) umsg.VectorNormal(hitnormal) umsg.Entity(entity) umsg.Long(physbone) umsg.Bool(bFirstTimePredicted) umsg.End() end self.Weapon:EmitSound("Disguiser.Shot") self.Weapon:SendWeaponAnim( ACT_VM_PRIMARYATTACK ) -- View model animation -- There's a bug with the model that's causing a muzzle to -- appear on everyone's screen when we fire this animation. self.Owner:SetAnimation( PLAYER_ATTACK1 ) -- 3rd Person Animation if ( !bFirstTimePredicted ) then return end local effectdata = EffectData() effectdata:SetOrigin( hitpos ) effectdata:SetNormal( hitnormal ) effectdata:SetEntity( entity ) effectdata:SetAttachment( physbone ) util.Effect( "selection_indicator", effectdata ) local effectdata = EffectData() effectdata:SetOrigin( hitpos ) effectdata:SetStart( self.Owner:GetShootPos() ) effectdata:SetAttachment( 1 ) effectdata:SetEntity( self.Weapon ) util.Effect( "ToolTracer", effectdata ) end function SWEP:PreDrawViewModel(vm, ply, wep) if self.Owner:GetNWBool("isDisguised", false) then vm:SetRenderMode(RENDERMODE_TRANSALPHA) vm:SetColor(Color(0, 0, 0, 0)) else vm:SetRenderMode(RENDERMODE_TRANSALPHA) vm:SetColor(Color(255,255,255,255)) end end function SWEP:DrawWorldModel() if !self.Owner:GetNWBool("isDisguised", false) then self.Weapon:DrawModel() end end function SWEP:DrawWorldModelTranslucent() if !self.Owner:GetNWBool("isDisguised", false) then self.Weapon:DrawModel() end end function SWEP:DrawIfNotDisguised() self.Owner:DrawViewModel(!self.Owner:GetNWBool("isDisguised", false)) if !!self.Owner.DrawWorldModel then self.Owner:DrawWorldModel(!self.Owner:GetNWBool("isDisguised", false)) end end function SWEP:Think() self:DrawIfNotDisguised() end function SWEP:Deploy() self:DrawIfNotDisguised() end
/** * Disguiser SWEP - Lets you disguise as any prop on a map. * * File: * sh_init.lua * * Purpose: * Initializes all the stuff and data that client and server share. * * Copyright (C) 2013 Carl Kittelberger (Icedream) * * 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/>. */ // DEBUG DEBUG DEBUG print("[Disguiser] Loading shared...") // Weapon info SWEP.Author = "Icedream" SWEP.Contact = "icedream@modernminas.de" SWEP.Category = "Fun" SWEP.Purpose = "Lets you disguise as a map model." SWEP.Instructions = "Aim at a model on the map and press the left mouse button to disguise." .. " Undisguise with right mouse button." SWEP.Spawnable = true SWEP.AdminSpawnable = true SWEP.UseHands = true SWEP.ViewModel = "models/weapons/c_toolgun.mdl" SWEP.WorldModel = "models/weapons/w_toolgun.mdl" // Disable ammo system SWEP.DrawAmmo = false SWEP.Primary.ClipSize = -1 SWEP.Primary.DefaultClip = -1 SWEP.Primary.Automatic = false SWEP.Primary.Ammo = "none" // lasers would be nice :3 SWEP.Secondary.ClipSize = -1 SWEP.Secondary.DefaultClip = -1 SWEP.Secondary.Automatic = false SWEP.Secondary.Ammo = "none" // Sounds SWEP.Sounds = { Disguise = { "garrysmod/balloon_pop_cute.wav" }, Undisguise = { "garrysmod/balloon_pop_cute.wav" }, Shot = { "weapons/disguiser/shot1.mp3" // original sound by http://freesound.org/people/ejfortin/sounds/49678/ } } SWEP.ChannelMapping = { Disguise = { Channel = CHAN_BODY, Volume = 1.0, Level = 85, Pitch = { 70, 130 } }, Undisguise = { Channel = CHAN_BODY, Volume = 1.0, Level = 85, Pitch = { 70, 130 } }, Shot = { Channel = CHAN_WEAPON, Volume = 0.5, Level = 60, Pitch = { 80, 160 } } } // Load the sounds for soundName, soundPaths in pairs(SWEP.Sounds) do local internalSoundName = "Disguiser." .. soundName for k, soundPath in pairs(soundPaths) do if SERVER then resource.AddFile("sound/" .. soundPath) end if !file.Exists("sound/" .. soundPath, "GAME") then MsgC(Color(255, 0, 0), "[Disguiser] WARNING: Sound not found: " .. soundPath) end util.PrecacheSound(soundPath) end print("[Disguiser] Loading sound " .. internalSoundName .. "...") sound.Add({ name = internalSoundName, channel = SWEP.ChannelMapping[soundName].Channel, volume = SWEP.ChannelMapping[soundName].Volume, soundlevel = SWEP.ChannelMapping[soundName].Level, pitchstart = SWEP.ChannelMapping[soundName].Pitch[0], pitchend = SWEP.ChannelMapping[soundName].Pitch[1], sound = soundPaths }) end // Precache models function SWEP:Precache() util.PrecacheModel(SWEP.ViewModel) util.PrecacheModel(SWEP.WorldModel) end // Shooting effect function SWEP:DoShootEffect(hitpos, hitnormal, entity, physbone, bFirstTimePredicted) if SERVER then umsg.Start("disguiserShootFX", self.Owner) umsg.Vector(hitpos) umsg.VectorNormal(hitnormal) umsg.Entity(entity) umsg.Long(physbone) umsg.Bool(bFirstTimePredicted) umsg.End() end self.Weapon:EmitSound("Disguiser.Shot") self.Weapon:SendWeaponAnim( ACT_VM_PRIMARYATTACK ) -- View model animation -- There's a bug with the model that's causing a muzzle to -- appear on everyone's screen when we fire this animation. self.Owner:SetAnimation( PLAYER_ATTACK1 ) -- 3rd Person Animation if ( !bFirstTimePredicted ) then return end local effectdata = EffectData() effectdata:SetOrigin( hitpos ) effectdata:SetNormal( hitnormal ) effectdata:SetEntity( entity ) effectdata:SetAttachment( physbone ) util.Effect( "selection_indicator", effectdata ) local effectdata = EffectData() effectdata:SetOrigin( hitpos ) effectdata:SetStart( self.Owner:GetShootPos() ) effectdata:SetAttachment( 1 ) effectdata:SetEntity( self.Weapon ) util.Effect( "ToolTracer", effectdata ) end function SWEP:PreDrawViewModel(vm, ply, wep) if self.Owner:GetNWBool("isDisguised", false) then vm:SetRenderMode(RENDERMODE_TRANSALPHA) vm:SetColor(Color(0, 0, 0, 0)) else vm:SetRenderMode(RENDERMODE_TRANSALPHA) vm:SetColor(Color(255,255,255,255)) end end function SWEP:DrawWorldModel() if !self.Owner:GetNWBool("isDisguised", false) then self.Weapon:DrawModel() end end function SWEP:DrawWorldModelTranslucent() if !self.Owner:GetNWBool("isDisguised", false) then self.Weapon:DrawModel() end end function SWEP:DrawIfNotDisguised() self.Owner:DrawViewModel(!self.Owner:GetNWBool("isDisguised", false)) if !!self.Owner.DrawWorldModel then self.Owner:DrawWorldModel(!self.Owner:GetNWBool("isDisguised", false)) end end function SWEP:Think() self:DrawIfNotDisguised() end function SWEP:Deploy() self:DrawIfNotDisguised() end
Precache weapon inside SWEP:Precache hook. Fixes #3.
Precache weapon inside SWEP:Precache hook. Fixes #3.
Lua
agpl-3.0
icedream/gmod-disguiser
7be4ac1fedf9f6e00a356e6717019febf3e9982d
conditions/TickTime.lua
conditions/TickTime.lua
--[[-------------------------------------------------------------------- Ovale Spell Priority Copyright (C) 2012, 2013 Sidoine Copyright (C) 2012, 2013 Johnny C. Lam This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License in the LICENSE file accompanying this program. --]]-------------------------------------------------------------------- local _, Ovale = ... do local OvaleCondition = Ovale.OvaleCondition local OvaleState = Ovale.OvaleState local Compare = OvaleCondition.Compare local ParseCondition = OvaleCondition.ParseCondition local state = OvaleState.state --- Get the number of seconds between ticks of a periodic aura on a target. -- @name TickTime -- @paramsig number or boolean -- @param id The spell ID of the aura or the name of a spell list. -- @param operator Optional. Comparison operator: less, atMost, equal, atLeast, more. -- @param number Optional. The number to compare against. -- @param filter Optional. The type of aura to check. -- Default is any. -- Valid values: any, buff, debuff -- @param target Optional. Sets the target to check. The target may also be given as a prefix to the condition. -- Defaults to target=player. -- Valid values: player, target, focus, pet. -- @return The number of seconds. -- @return A boolean value for the result of the comparison. -- @see NextTick, Ticks, TicksRemain local function TickTime(condition) local auraId, comparator, limit = condition[1], condition[2], condition[3] local target, filter, mine = ParseCondition(condition) local aura = state:GetAura(target, auraId, filter, mine) if state:IsActiveAura(aura) and aura.tick then local value = aura.tick return Compare(value, comparator, limit) end return Compare(math.huge, comparator, limit) end OvaleCondition:RegisterCondition("ticktime", false, TickTime) end
--[[-------------------------------------------------------------------- Ovale Spell Priority Copyright (C) 2012, 2013 Sidoine Copyright (C) 2012, 2013 Johnny C. Lam This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License in the LICENSE file accompanying this program. --]]-------------------------------------------------------------------- local _, Ovale = ... do local OvaleCondition = Ovale.OvaleCondition local OvaleState = Ovale.OvaleState local Compare = OvaleCondition.Compare local ParseCondition = OvaleCondition.ParseCondition local state = OvaleState.state --- Get the number of seconds between ticks of a periodic aura on a target. -- @name TickTime -- @paramsig number or boolean -- @param id The spell ID of the aura or the name of a spell list. -- @param operator Optional. Comparison operator: less, atMost, equal, atLeast, more. -- @param number Optional. The number to compare against. -- @param filter Optional. The type of aura to check. -- Default is any. -- Valid values: any, buff, debuff -- @param target Optional. Sets the target to check. The target may also be given as a prefix to the condition. -- Defaults to target=player. -- Valid values: player, target, focus, pet. -- @return The number of seconds. -- @return A boolean value for the result of the comparison. -- @see NextTick, Ticks, TicksRemain local function TickTime(condition) local auraId, comparator, limit = condition[1], condition[2], condition[3] local target, filter, mine = ParseCondition(condition) local aura = state:GetAura(target, auraId, filter, mine) local tickTime if state:IsActiveAura(aura) then tickTime = aura.tick else local _, _, tick = state:GetDuration(auraId) tickTime = tick end if tickTime and tickTime > 0 then return Compare(tickTime, comparator, limit) end return Compare(math.huge, comparator, limit) end OvaleCondition:RegisterCondition("ticktime", false, TickTime) end
Make TickTime() return the tick length of a new DoT if one isn't present.
Make TickTime() return the tick length of a new DoT if one isn't present. This matches SimC semantics where if a DoT is present, then "tick_time" is the actual tick length of the DoT, but if the DoT is not present, then it is the tick length of a new DoT with a current stat snapshot. This fixes mage scripts not suggesting mage bombs. git-svn-id: b2bb544abab4b09d60f88077ac82407cb244c9c9@1390 d5049fe3-3747-40f7-a4b5-f36d6801af5f
Lua
mit
ultijlam/ovale,eXhausted/Ovale,ultijlam/ovale,Xeltor/ovale,ultijlam/ovale,eXhausted/Ovale,eXhausted/Ovale
cacf6ba5b38527003d121919e6bd03d19c0a3d69
test/fs.lua
test/fs.lua
local uv = require 'yaluv' local fs = uv.fs local loop = uv.loop local Buffer = uv.Buffer local exports = {} exports['fs.open.sync.OK'] = function(test) local err, fd = fs.open('../test/fs.lua', 'r', '0666') test.is_nil(err) test.is_number(fd) err = fs.close(fd) test.is_nil(err) -- try to close twice err = fs.close(fd) test.equal(err, 'EBADF') test.done() end exports['fs.open.sync.ENOENT'] = function(test) local err, fd = fs.open('not_exist_file', 'r', '0666') test.equal(err, 'ENOENT') test.is_nil(fd) test.done() end exports['fs.open.async.OK'] = function(test) coroutine.wrap(function() local err, fd = fs.open('../test/fs.lua', 'r', '0666') test.is_nil(err) test.is_number(fd) err = fs.close(fd) test.is_nil(err) test.done() end)() loop.get():run() end exports['fs.open.async.ENOENT'] = function(test) coroutine.wrap(function() local err, fd = fs.open('non_exist_file', 'r', '0666') test.equal(err, 'ENOENT') test.is_nil(fd) test.done() end)() loop.get():run() end exports['fs.stat.sync'] = function(test) local err, stat = fs.stat('Makefile') test.is_nil(err) test.ok(stat) test.ok(stat:isFile()) test.done() end exports['fs.stat.async'] = function(test) coroutine.wrap(function() local err, stat = fs.stat('../test/fs.lua') test.is_nil(err) test.ok(stat:isFile()) test.done() end)() loop.get():run() end exports['fs.write_and_read.sync'] = function(test) local path = '_test_fs.write_and_read.sync' local err, fd = fs.open(path, 'w', '0666') test.is_nil(err) local str = 'Hello, libuv!\n' local n err, n = fs.write(fd, str) test.is_nil(err) test.equal(n, #str) err = fs.close(fd) test.is_nil(err) err, fd = fs.open(path, 'r') test.is_nil(err) local buf = Buffer.new(#str) err, n = fs.read(fd, buf) test.is_nil(err) test.equal(buf:toString(), str) err = fs.close(fd) test.is_nil(err) err = fs.unlink(path) test.is_nil(err) test.done() end exports['fs.write_and_read.async'] = function(test) coroutine.wrap(function() local path = '_test_fs.write_and_read.async' local err, fd = fs.open(path, 'w', '0666') test.is_nil(err) local str = 'Hello, libuv!\n' local n err, n = fs.write(fd, str) test.is_nil(err) test.equal(n, #str) err = fs.close(fd) test.is_nil(err) err, fd = fs.open(path, 'r') test.is_nil(err) local buf = Buffer.new(#str) err, n = fs.read(fd, buf) test.is_nil(err) test.equal(buf:toString(), str) err = fs.close(fd) test.is_nil(err) err = fs.unlink(path) test.is_nil(err) test.done() end)() loop.get():run() end exports['fs.unlink.sync'] = function(test) local path = '_test_fs.unlink.sync' local err, fd = fs.open(path, 'w', '0666') test.is_nil(err) err = fs.close(fd) test.is_nil(err) err = fs.unlink(path) test.is_nil(err) test.done() end exports['fs.unlink.async'] = function(test) coroutine.wrap(function() local path = '_test_fs.unlink.async' local err, fd = fs.open(path, 'w', '0666') test.is_nil(err) err = fs.close(fd) test.is_nil(err) err = fs.unlink(path) test.is_nil(err) test.done() end)() loop.get():run() end exports['fs.mkdir_rmdir.sync'] = function(test) local path = '_test_fs_mkdir_rmdir.sync' local err = fs.mkdir(path) test.is_nil(err) local stat err, stat = fs.stat(path) test.ok(stat:isDirectory()) err = fs.rmdir(path) test.is_nil(err) test.done() end exports['fs.mkdir_rmdir.async'] = function(test) coroutine.wrap(function() local path = '_test_fs_mkdir_rmdir.async' local err = fs.mkdir(path) test.is_nil(err) local stat err, stat = fs.stat(path) test.ok(stat:isDirectory()) err = fs.rmdir(path) test.is_nil(err) test.done() end)() loop.get():run() end exports['fs.rename_dir.sync'] = function(test) local oldPath = '_test_fs_rename_dir.sync.old' local newPath = '_test_fs_rename_dir.sync.new' test.ok(not fs.exists(oldPath)) test.ok(not fs.exists(newPath)) local err = fs.mkdir(oldPath) test.is_nil(err) test.ok(fs.exists(oldPath)) test.ok(not fs.exists(newPath)) err = fs.rename(oldPath, newPath) test.is_nil(err) test.ok(not fs.exists(oldPath)) test.ok(fs.exists(newPath)) err = fs.rmdir(newPath) test.is_nil(err) test.done() end --[[ TODO: investigate why this test blocks. exports['fs.rename_dir.async'] = function(test) coroutine.wrap(function() local oldPath = '_test_fs_rename_dir.async.old' local newPath = '_test_fs_rename_dir.async.new' test.ok(not fs.exists(oldPath)) test.ok(not fs.exists(newPath)) local err = fs.mkdir(oldPath) test.is_nil(err) test.ok(fs.exists(oldPath)) test.ok(not fs.exists(newPath)) err = fs.rename(oldPath, newPath) test.is_nil(err) test.ok(not fs.exists(oldPath)) test.ok(fs.exists(newPath)) err = fs.rmdir(newPath) test.is_nil(err) test.done() end)() loop.get():run() end ]] exports['fs.ftruncate.sync'] = function(test) local path = '_test_fs_ftruncate.sync' local err, fd = fs.open(path, 'w', '0666') test.is_nil(err) local str = 'Hello, libuv!\n' local n err, n = fs.write(fd, str) test.is_nil(err) err = fs.ftruncate(fd, 5) test.is_nil(err) local stat err, stat = fs.stat(path) test.is_nil(err) test.equal(stat:size(), 5) err = fs.ftruncate(fd) test.is_nil(err) err, stat = fs.stat(path) test.is_nil(err) test.equal(stat:size(), 0) err = fs.close(fd) test.is_nil(err) err = fs.unlink(path) test.is_nil(err) test.done() end exports['fs.ftruncate.async'] = function(test) coroutine.wrap(function() local path = '_test_fs_ftruncate.async' local err, fd = fs.open(path, 'w', '0666') test.is_nil(err) local str = 'Hello, libuv!\n' local n err, n = fs.write(fd, str) test.is_nil(err) err = fs.ftruncate(fd, 5) test.is_nil(err) local stat err, stat = fs.stat(path) test.is_nil(err) test.equal(stat:size(), 5) err = fs.ftruncate(fd) test.is_nil(err) err, stat = fs.stat(path) test.is_nil(err) test.equal(stat:size(), 0) err = fs.close(fd) test.is_nil(err) err = fs.unlink(path) test.is_nil(err) test.done() end)() loop.get():run() end return exports
local uv = require 'yaluv' local fs = uv.fs local loop = uv.loop local Buffer = uv.Buffer local exports = {} exports['fs.open.sync.OK'] = function(test) local err, fd = fs.open('../test/fs.lua', 'r', '0666') test.is_nil(err) test.is_number(fd) err = fs.close(fd) test.is_nil(err) -- try to close twice err = fs.close(fd) test.equal(err, 'EBADF') test.done() end exports['fs.open.sync.ENOENT'] = function(test) local err, fd = fs.open('not_exist_file', 'r', '0666') test.equal(err, 'ENOENT') test.is_nil(fd) test.done() end exports['fs.open.async.OK'] = function(test) local co = coroutine.create(function() local err, fd = fs.open('../test/fs.lua', 'r', '0666') test.is_nil(err) test.is_number(fd) err = fs.close(fd) test.is_nil(err) test.done() end) coroutine.resume(co) loop.get():run() end exports['fs.open.async.ENOENT'] = function(test) local co = coroutine.create(function() local err, fd = fs.open('non_exist_file', 'r', '0666') test.equal(err, 'ENOENT') test.is_nil(fd) test.done() end) coroutine.resume(co) loop.get():run() end exports['fs.stat.sync'] = function(test) local err, stat = fs.stat('Makefile') test.is_nil(err) test.ok(stat) test.ok(stat:isFile()) test.done() end exports['fs.stat.async'] = function(test) local co = coroutine.create(function() local err, stat = fs.stat('../test/fs.lua') test.is_nil(err) test.ok(stat:isFile()) test.done() end) coroutine.resume(co) loop.get():run() end exports['fs.write_and_read.sync'] = function(test) local path = '_test_fs.write_and_read.sync' local err, fd = fs.open(path, 'w', '0666') test.is_nil(err) local str = 'Hello, libuv!\n' local n err, n = fs.write(fd, str) test.is_nil(err) test.equal(n, #str) err = fs.close(fd) test.is_nil(err) err, fd = fs.open(path, 'r') test.is_nil(err) local buf = Buffer.new(#str) err, n = fs.read(fd, buf) test.is_nil(err) test.equal(buf:toString(), str) err = fs.close(fd) test.is_nil(err) err = fs.unlink(path) test.is_nil(err) test.done() end exports['fs.write_and_read.async'] = function(test) local co = coroutine.create(function() local path = '_test_fs.write_and_read.async' local err, fd = fs.open(path, 'w', '0666') test.is_nil(err) local str = 'Hello, libuv!\n' local n err, n = fs.write(fd, str) test.is_nil(err) test.equal(n, #str) err = fs.close(fd) test.is_nil(err) err, fd = fs.open(path, 'r') test.is_nil(err) local buf = Buffer.new(#str) err, n = fs.read(fd, buf) test.is_nil(err) test.equal(buf:toString(), str) err = fs.close(fd) test.is_nil(err) err = fs.unlink(path) test.is_nil(err) test.done() end) coroutine.resume(co) loop.get():run() end exports['fs.unlink.sync'] = function(test) local path = '_test_fs.unlink.sync' local err, fd = fs.open(path, 'w', '0666') test.is_nil(err) err = fs.close(fd) test.is_nil(err) err = fs.unlink(path) test.is_nil(err) test.done() end exports['fs.unlink.async'] = function(test) local co = coroutine.create(function() local path = '_test_fs.unlink.async' local err, fd = fs.open(path, 'w', '0666') test.is_nil(err) err = fs.close(fd) test.is_nil(err) err = fs.unlink(path) test.is_nil(err) test.done() end) coroutine.resume(co) loop.get():run() end exports['fs.mkdir_rmdir.sync'] = function(test) local path = '_test_fs_mkdir_rmdir.sync' local err = fs.mkdir(path) test.is_nil(err) local stat err, stat = fs.stat(path) test.ok(stat:isDirectory()) err = fs.rmdir(path) test.is_nil(err) test.done() end exports['fs.mkdir_rmdir.async'] = function(test) local co = coroutine.create(function() local path = '_test_fs_mkdir_rmdir.async' local err = fs.mkdir(path) test.is_nil(err) local stat err, stat = fs.stat(path) test.ok(stat:isDirectory()) err = fs.rmdir(path) test.is_nil(err) test.done() end) coroutine.resume(co) loop.get():run() end exports['fs.rename_dir.sync'] = function(test) local oldPath = '_test_fs_rename_dir.sync.old' local newPath = '_test_fs_rename_dir.sync.new' test.ok(not fs.exists(oldPath)) test.ok(not fs.exists(newPath)) local err = fs.mkdir(oldPath) test.is_nil(err) test.ok(fs.exists(oldPath)) test.ok(not fs.exists(newPath)) err = fs.rename(oldPath, newPath) test.is_nil(err) test.ok(not fs.exists(oldPath)) test.ok(fs.exists(newPath)) err = fs.rmdir(newPath) test.is_nil(err) test.done() end --[[ TODO: investigate why this test blocks. exports['fs.rename_dir.async'] = function(test) local co = coroutine.create(function() local oldPath = '_test_fs_rename_dir.async.old' local newPath = '_test_fs_rename_dir.async.new' test.ok(not fs.exists(oldPath)) test.ok(not fs.exists(newPath)) local err = fs.mkdir(oldPath) test.is_nil(err) test.ok(fs.exists(oldPath)) test.ok(not fs.exists(newPath)) err = fs.rename(oldPath, newPath) test.is_nil(err) test.ok(not fs.exists(oldPath)) test.ok(fs.exists(newPath)) err = fs.rmdir(newPath) test.is_nil(err) test.done() end) coroutine.resume(co) loop.get():run() end ]] exports['fs.ftruncate.sync'] = function(test) local path = '_test_fs_ftruncate.sync' local err, fd = fs.open(path, 'w', '0666') test.is_nil(err) local str = 'Hello, libuv!\n' local n err, n = fs.write(fd, str) test.is_nil(err) err = fs.ftruncate(fd, 5) test.is_nil(err) local stat err, stat = fs.stat(path) test.is_nil(err) test.equal(stat:size(), 5) err = fs.ftruncate(fd) test.is_nil(err) err, stat = fs.stat(path) test.is_nil(err) test.equal(stat:size(), 0) err = fs.close(fd) test.is_nil(err) err = fs.unlink(path) test.is_nil(err) test.done() end exports['fs.ftruncate.async'] = function(test) local co = coroutine.create(function() local path = '_test_fs_ftruncate.async' local err, fd = fs.open(path, 'w', '0666') test.is_nil(err) local str = 'Hello, libuv!\n' local n err, n = fs.write(fd, str) test.is_nil(err) err = fs.ftruncate(fd, 5) test.is_nil(err) local stat err, stat = fs.stat(path) test.is_nil(err) test.equal(stat:size(), 5) err = fs.ftruncate(fd) test.is_nil(err) err, stat = fs.stat(path) test.is_nil(err) test.equal(stat:size(), 0) err = fs.close(fd) test.is_nil(err) err = fs.unlink(path) test.is_nil(err) test.done() end) coroutine.resume(co) loop.get():run() end return exports
Fix fs tests to keep coroutine references.
Fix fs tests to keep coroutine references.
Lua
mit
hnakamur/couv,hnakamur/couv
cca715a324d5ccdd45e2c1bc62a445dab3549847
examples/l3-tcp-syn-flood.lua
examples/l3-tcp-syn-flood.lua
local dpdk = require "dpdk" local memory = require "memory" local device = require "device" function master(...) local txPort = tonumber((select(1, ...))) local minIP = select(2, ...) local numIPs = tonumber((select(3, ...))) local rate = tonumber(select(4, ...)) if not txPort or not minIP or not numIPs or not rate then printf("usage: txPort minIP numIPs rate") return end local rxMempool = memory.createMemPool() local txDev = device.config(txPort, rxMempool, 2, 2) txDev:wait() txDev:getTxQueue(0):setRate(rate) dpdk.launchLua("loadSlave", txPort, 0, minIP, numIPs) dpdk.waitForSlaves() end function loadSlave(port, queue, minA, numIPs) --- parse and check ip addresses -- min TCP packet size for IPv6 is 78 bytes -- 4 bytes subtracted as the CRC gets appended by the NIC local packetLen = 78 - 4 local minIP, ipv4 = parseIPAddress(minA) if minIP then printf("INFO: Detected in %s address.", minIP and "IPv4" or "IPv6") else errorf("Invalid minIP: %s", minA) end --continue normally local queue = device.get(port):getTxQueue(queue) local mem = memory.createMemPool(function(buf) buf:getTcpPacket(ipv4):fill{ ethSrc="90:e2:ba:2c:cb:02", ethDst="90:e2:ba:35:b5:81", ipDst="192.168.1.1", ip6Dst="fd06::1", tcpSyn=1, tcpSeqNumber=1, tcpWindow=10, pktLength=packetLen } end) local lastPrint = dpdk.getTime() local totalSent = 0 local lastTotal = 0 local lastSent = 0 local bufs = mem:bufArray(128) local counter = 0 local c = 0 print("Start sending...") while dpdk.running() do -- faill packets and set their size bufs:alloc(packetLen) for i, buf in ipairs(bufs) do local pkt = buf:getTcpPacket(ipv4) --increment IP pkt.ip.src:set(minIP) pkt.ip.src:add(counter) counter = incAndWrap(counter, numIPs) -- dump first 3 packets if c < 3 then buf:dump() c = c + 1 end end --offload checksums to NIC bufs:offloadTcpChecksums(ipv4) totalSent = totalSent + queue:send(bufs) local time = dpdk.getTime() if time - lastPrint > 0.1 then --counter frequency local mpps = (totalSent - lastTotal) / (time - lastPrint) / 10^6 --printf("%.5f %d", time - lastPrint, totalSent - lastTotal) -- packet_counter-like output printf("Sent %d packets, current rate %.2f Mpps, %.2f MBit/s, %.2f MBit/s wire rate", totalSent, mpps, mpps * 64 * 8, mpps * 84 * 8) lastTotal = totalSent lastPrint = time end end printf("Sent %d packets", totalSent) end
local dpdk = require "dpdk" local memory = require "memory" local device = require "device" local stats = require "stats" function master(...) local txPort = tonumber((select(1, ...))) local minIP = select(2, ...) local numIPs = tonumber((select(3, ...))) local rate = tonumber(select(4, ...)) if not txPort or not minIP or not numIPs or not rate then printf("usage: txPort minIP numIPs rate") return end local rxMempool = memory.createMemPool() local txDev = device.config(txPort, rxMempool, 2, 2) txDev:wait() txDev:getTxQueue(0):setRate(rate) dpdk.launchLua("loadSlave", txPort, 0, minIP, numIPs) dpdk.waitForSlaves() end function loadSlave(port, queue, minA, numIPs) --- parse and check ip addresses local minIP, ipv4 = parseIPAddress(minA) if minIP then printf("INFO: Detected in %s address.", minIP and "IPv4" or "IPv6") else errorf("Invalid minIP: %s", minA) end -- min TCP packet size for IPv6 is 74 bytes (+ CRC) local packetLen = ipv4 and 60 or 74 --continue normally local queue = device.get(port):getTxQueue(queue) local mem = memory.createMemPool(function(buf) buf:getTcpPacket(ipv4):fill{ ethSrc="90:e2:ba:2c:cb:02", ethDst="90:e2:ba:35:b5:81", ipDst="192.168.1.1", ip6Dst="fd06::1", tcpSyn=1, tcpSeqNumber=1, tcpWindow=10, pktLength=packetLen } end) local lastPrint = dpdk.getTime() local totalSent = 0 local lastTotal = 0 local lastSent = 0 local bufs = mem:bufArray(128) local counter = 0 local c = 0 local txStats = stats:newDevTxCounter(queue, "plain") while dpdk.running() do -- faill packets and set their size bufs:alloc(packetLen) for i, buf in ipairs(bufs) do local pkt = buf:getTcpPacket(ipv4) --increment IP pkt.ip.src:set(minIP) pkt.ip.src:add(counter) counter = incAndWrap(counter, numIPs) -- dump first 3 packets if c < 3 then buf:dump() c = c + 1 end end --offload checksums to NIC bufs:offloadTcpChecksums(ipv4) totalSent = totalSent + queue:send(bufs) txStats:update() end txStats:finalize() end
fix ipv4 packet sizes and stats output
fix ipv4 packet sizes and stats output this fixes #59
Lua
mit
scholzd/MoonGen,gallenmu/MoonGen,wenhuizhang/MoonGen,kidaa/MoonGen,bmichalo/MoonGen,slyon/MoonGen,duk3luk3/MoonGen,werpat/MoonGen,bmichalo/MoonGen,gallenmu/MoonGen,scholzd/MoonGen,wenhuizhang/MoonGen,atheurer/MoonGen,schoenb/MoonGen,werpat/MoonGen,atheurer/MoonGen,slyon/MoonGen,kidaa/MoonGen,gallenmu/MoonGen,emmericp/MoonGen,slyon/MoonGen,atheurer/MoonGen,emmericp/MoonGen,werpat/MoonGen,gallenmu/MoonGen,gallenmu/MoonGen,emmericp/MoonGen,NetronomeMoongen/MoonGen,gallenmu/MoonGen,duk3luk3/MoonGen,NetronomeMoongen/MoonGen,bmichalo/MoonGen,NetronomeMoongen/MoonGen,dschoeffm/MoonGen,kidaa/MoonGen,slyon/MoonGen,schoenb/MoonGen,scholzd/MoonGen,wenhuizhang/MoonGen,gallenmu/MoonGen,bmichalo/MoonGen,duk3luk3/MoonGen,dschoeffm/MoonGen,gallenmu/MoonGen,dschoeffm/MoonGen,schoenb/MoonGen
68105ef086e6531aea29d8c235fd22fb6ffaa40b
Modules/Shared/IK/FABRIK/FABRIKConstraint.lua
Modules/Shared/IK/FABRIK/FABRIKConstraint.lua
--- -- @classmod FABRIKConstraint local PI2 = math.pi/2 local PI4 = math.pi/4 -- local FABRIKConstraint = {} FABRIKConstraint.__index = FABRIKConstraint -- local function inEllipse(p, a, b) return ((p.x*p.x) / (a*a)) + ((p.y*p.y) / (b*b)) <= 1 end local function constrainEllipse(isInEllipse, p, a, b) local px, py = math.abs(p.x), math.abs(p.y) local t, x, y = isInEllipse and math.atan2(py, px) or PI4 for _ = 1, 4 do local ct, st = math.cos(t), math.sin(t) x, y = a*ct, b*st local ex = (a*a - b*b) * ct*ct*ct / a local ey = (b*b - a*a) * st*st*st / b local rx, ry = x - ex, y - ey local qx, qy = px - ex, py - ey local r = math.sqrt(rx*rx + ry*ry) local q = math.sqrt(qx*qx + qy*qy) local delta_c = r*math.asin((rx*qy - ry*qx)/(r*q)) local delta_t = delta_c / math.sqrt(a*a + b*b - x*x - y*y) t = t + delta_t t = math.clamp(t, 0, PI2) end return Vector3.new(math.sign(p.x)*x, math.sign(p.y)*y, p.z) end -- function FABRIKConstraint.new(left, right, up, down, twistLeft, twistRight) local self = setmetatable({}, FABRIKConstraint) self.Left = left self.Right = right self.Up = up self.Down = down return self end -- function FABRIKConstraint:Constrain(lpoint, length) local z = math.abs(lpoint.z) local w = z * (lpoint.x >= 0 and math.cos(self.Right) or math.cos(self.Left)) local h = z * (lpoint.y >= 0 and math.sin(self.Up) or math.sin(self.Down)) local isInEllipse = inEllipse(lpoint, w, h) if (lpoint.z >= 0) then local x, y, z = lpoint.x, lpoint.y, -lpoint.z if (x == 0 and y == 0) then return Vector3.new(0, h, z) else lpoint = Vector3.new(x, y, z) end elseif (isInEllipse) then return lpoint end return constrainEllipse(isInEllipse, lpoint, w, h).Unit * length end -- return FABRIKConstraint
--- -- @classmod FABRIKConstraint local PI2 = math.pi/2 local PI4 = math.pi/4 -- local FABRIKConstraint = {} FABRIKConstraint.__index = FABRIKConstraint -- local function inEllipse(p, a, b) return ((p.x*p.x) / (a*a)) + ((p.y*p.y) / (b*b)) <= 1 end local function constrainEllipse(isInEllipse, p, a, b) local px, py = math.abs(p.x), math.abs(p.y) local t, x, y = isInEllipse and math.atan2(py, px) or PI4 for _ = 1, 4 do local ct, st = math.cos(t), math.sin(t) x, y = a*ct, b*st local ex = (a*a - b*b) * ct*ct*ct / a local ey = (b*b - a*a) * st*st*st / b local rx, ry = x - ex, y - ey local qx, qy = px - ex, py - ey local r = math.sqrt(rx*rx + ry*ry) local q = math.sqrt(qx*qx + qy*qy) local delta_c = r*math.asin((rx*qy - ry*qx)/(r*q)) local delta_t = delta_c / math.sqrt(a*a + b*b - x*x - y*y) t = t + delta_t t = math.clamp(t, 0, PI2) end return Vector3.new(math.sign(p.x)*x, math.sign(p.y)*y, p.z) end -- function FABRIKConstraint.new(left, right, up, down, twistLeft, twistRight) local self = setmetatable({}, FABRIKConstraint) self.Left = math.pi*2 - left self.Right = math.pi*2 - right self.Up = up self.Down = down return self end -- function FABRIKConstraint:Constrain(lpoint, length) local z = length local w = z * (lpoint.x >= 0 and math.cos(self.Right) or math.cos(self.Left)) local h = z * (lpoint.y >= 0 and math.sin(self.Up) or math.sin(self.Down)) local isInEllipse = inEllipse(lpoint, w, h) if (lpoint.z >= 0) then local x, y, z = lpoint.x, lpoint.y, -lpoint.z if (x == 0 and y == 0) then return Vector3.new(0, h, z) else lpoint = Vector3.new(x, y, z) end elseif (isInEllipse) then return lpoint end return constrainEllipse(isInEllipse, lpoint, w, h).Unit * length end -- return FABRIKConstraint
Maybe fix constraints
Maybe fix constraints
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine
7d6b84c1d17417f6c479cb92c4c02b5d39089f5f
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 (based on file extension). module('textadept.mime_types', package.seeall) --- -- 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 --- -- [Local function] 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. -- @param buffer The buffer to set the lexer language of. -- @param lang The string language to set. local function set_lexer_language(buffer, lang) buffer._lexer = lang buffer:set_lexer_language_(lang) end textadept.events.add_handler('buffer_new', function() buffer.set_lexer_language_ = buffer.set_lexer_language buffer.set_lexer_language = set_lexer_language end) --- -- [Local function] 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_language(lexer or 'container') if buffer.filename then local lang = extensions[buffer.filename:match('[^/\\.]+$')] if lang then 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 textadept.events.error(err) end end end end --- -- [Local function] 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 (based on file extension). module('textadept.mime_types', package.seeall) --- -- 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 --- -- [Local function] 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. -- @param buffer The buffer to set the lexer language of. -- @param lang The string language to set. local function set_lexer(buffer, lang) buffer._lexer = lang buffer:set_lexer_language(lang) end textadept.events.add_handler('buffer_new', function() buffer.set_lexer = set_lexer end) --- -- [Local function] 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') if buffer.filename then local lang = extensions[buffer.filename:match('[^/\\.]+$')] if lang then 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 textadept.events.error(err) end end end end --- -- [Local function] 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 with lexer restoration.
Fixed bug with lexer restoration.
Lua
mit
rgieseke/textadept,rgieseke/textadept
131c6284a3ab5c2f2154548de6d78534e5ff2b07
src/cosy/store.lua
src/cosy/store.lua
local Configuration = require "cosy.configuration" local Redis = require "cosy.redis" local Value = require "cosy.value" local Coromake = require "coroutine.make" local Store = {} local Collection = {} local Document = {} Store.Error = setmetatable ({}, { __tostring = function () return "ERROR" end }) local PATTERN = setmetatable ({}, { __tostring = function () return "PATTERN" end }) local DATA = setmetatable ({}, { __tostring = function () return "DATA" end }) local ROOT = setmetatable ({}, { __tostring = function () return "ROOT" end }) local DIRTY = setmetatable ({}, { __tostring = function () return "DIRTY" end }) function Store.new () return setmetatable ({}, Store) end function Store.__index (store, key) local collection = Collection.new (key) rawset (store, key, collection) return collection end function Store.__newindex () assert (false) end function Store.commit (store) local client = Redis () client:multi () for _, collection in pairs (store) do local pattern = collection [PATTERN] for key, document in pairs (collection [DATA]) do if document [DIRTY] then local name = pattern % { key = Value.expression (key), } local value = document [DATA] if value == nil then client:del (name) else client:set (name, Value.encode (value)) if type (value) == "table" and value.expire_at then client:expireat (name, math.ceil (value.expire_at)) else client:persist (name) end end end end end if not client:exec () then error (Store.Error) end end function Collection.new (key) local pattern = Configuration.redis.key [key]._ assert (pattern, key) return setmetatable ({ [PATTERN] = pattern, [DATA ] = {}, }, Collection) end function Collection.__index (collection, key) if not collection [DATA] [key] then local name = collection [PATTERN] % { key = Value.expression (key), } local client = Redis () client:watch (name) local value = client:get (name) if value ~= nil then value = Value.decode (value) end collection [DATA] [key] = { [DIRTY] = false, [DATA ] = value, } end return Document.new (collection [DATA] [key]) end function Collection.__newindex (collection, key, value) collection [DATA] [key] = { [DIRTY] = true, [DATA ] = value, } end function Collection.__pairs (collection) local coroutine = require "coroutine.make" () return coroutine.wrap (function () local name = collection [PATTERN] % { key = "*" } local client = Redis () local cursor = 0 repeat local t = client:scan (cursor, { match = name, count = 100, }) cursor = t [1] local data = t [2] for i = 1, #data do local key = (collection [PATTERN] / data [i]).key local value = collection [key] coroutine.yield (Value.decode (key), value) end until cursor == "0" end) end function Collection.__len (collection) local i = 0 repeat i = i+1 local value = collection [i] until value == nil return i-1 end function Collection.__ipairs (collection) local coroutine = Coromake () return coroutine.wrap (function () local i = 0 repeat i = i+1 local value = collection [i] if value == nil then return end coroutine.yield (i, value) until true end) end function Document.new (root) local result = root [DATA] if type (result) ~= "table" then return result else return setmetatable ({ [ROOT] = root, [DATA] = result, }, Document) end end function Document.__index (document, key) local result = document [DATA] [key] if type (result) ~= "table" then return result else return setmetatable ({ [ROOT] = document [ROOT], [DATA] = result, }, Document) end end function Document.__newindex (document, key, value) document [DATA] [key ] = value document [ROOT] [DIRTY] = true end function Document.__pairs (document) local coroutine = Coromake () return coroutine.wrap (function () for k in pairs (document [DATA]) do coroutine.yield (k, document [k]) end end) end function Document.__ipairs (document) local coroutine = Coromake () return coroutine.wrap (function () for i = 1, #document do coroutine.yield (i, document [i]) end end) end function Document.__len (document) return # document [DATA] end return Store
local Configuration = require "cosy.configuration" local Redis = require "cosy.redis" local Value = require "cosy.value" local Coromake = require "coroutine.make" local Store = {} local Collection = {} local Document = {} Store.Error = setmetatable ({}, { __tostring = function () return "ERROR" end }) local PATTERN = setmetatable ({}, { __tostring = function () return "PATTERN" end }) local DATA = setmetatable ({}, { __tostring = function () return "DATA" end }) local ROOT = setmetatable ({}, { __tostring = function () return "ROOT" end }) local DIRTY = setmetatable ({}, { __tostring = function () return "DIRTY" end }) function Store.new () return setmetatable ({}, Store) end function Store.__index (store, key) local collection = Collection.new (key) rawset (store, key, collection) return collection end function Store.__newindex () assert (false) end function Store.commit (store) local client = Redis () client:multi () for _, collection in pairs (store) do local pattern = collection [PATTERN] for key, document in pairs (collection [DATA]) do if document [DIRTY] then local name = pattern % { key = key, } local value = document [DATA] if value == nil then client:del (name) else client:set (name, Value.encode (value)) if type (value) == "table" and value.expire_at then client:expireat (name, math.ceil (value.expire_at)) else client:persist (name) end end end end end if not client:exec () then error (Store.Error) end end function Store.iterate (collection, filter) local coroutine = Coromake () return coroutine.wrap (function () local name = collection [PATTERN] % { key = filter } local client = Redis () local cursor = 0 repeat local t = client:scan (cursor, { match = name, count = 100, }) cursor = t [1] local data = t [2] for i = 1, #data do local key = (collection [PATTERN] / data [i]).key local value = collection [key] coroutine.yield (key, value) end until cursor == "0" end) end function Collection.new (key) local pattern = Configuration.redis.key [key]._ assert (pattern, key) return setmetatable ({ [PATTERN] = pattern, [DATA ] = {}, }, Collection) end function Collection.__index (collection, key) if not collection [DATA] [key] then local name = collection [PATTERN] % { key = key, } local client = Redis () client:watch (name) local value = client:get (name) if value ~= nil then value = Value.decode (value) end collection [DATA] [key] = { [DIRTY] = false, [DATA ] = value, } end return Document.new (collection [DATA] [key]) end function Collection.__newindex (collection, key, value) collection [DATA] [key] = { [DIRTY] = true, [DATA ] = value, } end function Collection.__pairs (collection) return Store.iterate (collection, "*") end function Collection.__len (collection) local i = 0 repeat i = i+1 local value = collection [i] until value == nil return i-1 end function Collection.__ipairs (collection) local coroutine = Coromake () return coroutine.wrap (function () local i = 0 repeat i = i+1 local value = collection [i] if value == nil then return end coroutine.yield (i, value) until true end) end function Document.new (root) local result = root [DATA] if type (result) ~= "table" then return result else return setmetatable ({ [ROOT] = root, [DATA] = result, }, Document) end end function Document.__index (document, key) local result = document [DATA] [key] if type (result) ~= "table" then return result else return setmetatable ({ [ROOT] = document [ROOT], [DATA] = result, }, Document) end end function Document.__newindex (document, key, value) document [DATA] [key ] = value document [ROOT] [DIRTY] = true end function Document.__pairs (document) local coroutine = Coromake () return coroutine.wrap (function () for k in pairs (document [DATA]) do coroutine.yield (k, document [k]) end end) end function Document.__ipairs (document) local coroutine = Coromake () return coroutine.wrap (function () for i = 1, #document do coroutine.yield (i, document [i]) end end) end function Document.__len (document) return # document [DATA] end return Store
Fix redis keys and allow filtered iteration.
Fix redis keys and allow filtered iteration.
Lua
mit
CosyVerif/library,CosyVerif/library,CosyVerif/library
410f3329fe31e260247a2917c5714feb71c58159
test_scripts/Polices/user_consent_of_Policies/120_ATF_Device_user_disallowed_after_consent.lua
test_scripts/Polices/user_consent_of_Policies/120_ATF_Device_user_disallowed_after_consent.lua
------------- -------------------------------------------------------------------------------- -- Requirement summary: -- [Policies]: User-disallowed device after applications consent -- -- Description: -- User disallows device via Settings Menu after device and apps on device are consented -- -- 1. Used preconditions: -- Delete log files and policy table from previous ignition cycle -- Activate app -> consent device -- Disallow device via Settings Menu -- 2.Performed steps: -- Send RPC from default group -- Allow device -- Send RPC from default group again -- -- Expected result: -- App consents must remain the same, app must be rolled back to pre_DataConstented group -> RPC from defult should not be allowed -- App must be rolled back to default group -- RPC from defult should be allowed --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonFunctions = require("user_modules/shared_testcases/commonFunctions") local commonSteps = require("user_modules/shared_testcases/commonSteps") local testCasesForPolicyTable = require("user_modules/shared_testcases/testCasesForPolicyTable") --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() --[[ Local variables ]] local pre_dataconsent = "129372391" local base4 = "686787169" --[[ General Settings for configuration ]] Test = require("connecttest") require("user_modules/AppTypes") --[[ Precondition ]] function Test:Precondition_ActivateRegisteredApp() testCasesForPolicyTable:trigger_getting_device_consent(self, config.application1.registerAppInterfaceParams.appName, config.deviceMAC) end function Test:Precondition_Check_App_assigned_BASE4() local group_app_id_table = commonFunctions:get_data_policy_sql(config.pathToSDL.."/storage/policy.sqlite", "SELECT functional_group_id FROM app_group where application_id = '0000001'") local group_app_id for _, value in pairs(group_app_id_table) do group_app_id = value end if(group_app_id ~= base4) then self:FailTestCase("Application is not assigned to Base-4. Group: "..group_app_id) end end function Test:Precondition_Disallow_device() self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality", {allowed = false, source = "GUI", device = {id = config.deviceMAC , name = "127.0.0.1"}}) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep1_Check_App_assigned_PreDataConsent() local group_app_id_table = commonFunctions:get_data_policy_sql(config.pathToSDL.."/storage/policy.sqlite", "SELECT functional_group_id FROM app_group where application_id = '0000001'") local group_app_id for _, value in pairs(group_app_id_table) do group_app_id = value end if(group_app_id ~= pre_dataconsent) then self:FailTestCase("Application is not assigned to BaseBeforeDataConsent. Group: "..group_app_id) end end function Test:TestStep1_Send_RPC_from_default_disallowed() --AddCommand belongs to default permissions, so should be disallowed local RequestIDAddCommand = self.mobileSession:SendRPC("AddCommand", { cmdID = 111, menuParams = { position = 1, menuName ="Command111" } }) EXPECT_HMICALL("UI.AddCommand",{}) :Times(0) EXPECT_RESPONSE(RequestIDAddCommand, { success = false, resultCode = "DISALLOWED" }) EXPECT_NOTIFICATION("OnHashChange") :Times(0) end function Test:TestStep2_Allow_device() testCasesForPolicyTable:trigger_getting_device_consent(self, config.application1.registerAppInterfaceParams.appName, config.deviceMAC) end function Test:TestStep3_Send_RPC_from_default_again() local RequestIDAddCommand = self.mobileSession:SendRPC("AddCommand", { cmdID = 111, menuParams = { position = 1, menuName ="Command111" } }) EXPECT_HMICALL("UI.AddCommand",{}) :Do(function(_,data) self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {}) end) EXPECT_RESPONSE(RequestIDAddCommand, { success = true, resultCode = "SUCCESS" }) EXPECT_NOTIFICATION("OnHashChange") end function Test:Precondition_Check_App_assigned_BASE4() local group_app_id_table = commonFunctions:get_data_policy_sql(config.pathToSDL.."/storage/policy.sqlite", "SELECT functional_group_id FROM app_group where application_id = '0000001'") local group_app_id for _, value in pairs(group_app_id_table) do group_app_id = value end if(group_app_id ~= base4) then self:FailTestCase("Application is not assigned to Base-4. Group: "..group_app_id) end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_Stop() StopSDL() end return Test
------------- -------------------------------------------------------------------------------- -- Requirement summary: -- [Policies]: User-disallowed device after applications consent -- -- Description: -- User disallows device via Settings Menu after device and apps on device are consented -- -- 1. Used preconditions: -- Delete log files and policy table from previous ignition cycle -- Activate app -> consent device -- Disallow device via Settings Menu -- 2.Performed steps: -- Send RPC from default group -- Allow device -- Send RPC from default group again -- -- Expected result: -- App consents must remain the same, app must be rolled back to pre_DataConstented group -> RPC from defult should not be allowed -- App must be rolled back to default group -- RPC from defult should be allowed --------------------------------------------------------------------------------------------- --[[ General configuration parameters ]] config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0" --[[ Required Shared libraries ]] local commonFunctions = require("user_modules/shared_testcases/commonFunctions") local commonSteps = require("user_modules/shared_testcases/commonSteps") local testCasesForPolicyTable = require("user_modules/shared_testcases/testCasesForPolicyTable") --[[ General Precondition before ATF start ]] commonSteps:DeleteLogsFileAndPolicyTable() --[[ Local variables ]] local pre_dataconsent = "129372391" local base4 = "686787169" --[[ General Settings for configuration ]] Test = require("connecttest") require("user_modules/AppTypes") --[[ Precondition ]] function Test:Precondition_ActivateRegisteredApp() testCasesForPolicyTable:trigger_getting_device_consent(self, config.application1.registerAppInterfaceParams.appName, config.deviceMAC) end function Test:Precondition_Check_App_assigned_BASE4() local group_app_id_table = commonFunctions:get_data_policy_sql(config.pathToSDL.."/storage/policy.sqlite", "SELECT functional_group_id FROM app_group where application_id = '0000001'") local group_app_id for _, value in pairs(group_app_id_table) do group_app_id = value end if(group_app_id ~= base4) then self:FailTestCase("Application is not assigned to Base-4. Group: "..group_app_id) end end function Test:Precondition_Disallow_device() self.hmiConnection:SendNotification("SDL.OnAllowSDLFunctionality", {allowed = false, source = "GUI", device = {id = config.deviceMAC , name = "127.0.0.1"}}) end --[[ Test ]] commonFunctions:newTestCasesGroup("Test") function Test:TestStep1_Check_App_assigned_PreDataConsent() local group_app_id_table = commonFunctions:get_data_policy_sql(config.pathToSDL.."/storage/policy.sqlite", "SELECT functional_group_id FROM app_group where application_id = '0000001'") local group_app_id for _, value in pairs(group_app_id_table) do group_app_id = value end if(group_app_id ~= pre_dataconsent) then self:FailTestCase("Application is not assigned to BaseBeforeDataConsent. Group: "..group_app_id) end end function Test:TestStep1_Send_RPC_from_default_disallowed() --AddCommand belongs to default permissions, so should be disallowed local RequestIDAddCommand = self.mobileSession:SendRPC("AddCommand", { cmdID = 111, menuParams = { position = 1, menuName ="Command111" } }) EXPECT_HMICALL("UI.AddCommand",{}) :Times(0) EXPECT_RESPONSE(RequestIDAddCommand, { success = false, resultCode = "DISALLOWED" }) EXPECT_NOTIFICATION("OnHashChange") :Times(0) end function Test:ActivateApp() local requestId1 = self.hmiConnection:SendRequest("SDL.ActivateApp", { appID = self.applications[config.application1.registerAppInterfaceParams.appName] }) EXPECT_HMIRESPONSE(requestId1) :Do(function(_, data1) if data1.result.isSDLAllowed ~= true then local requestId2 = self.hmiConnection:SendRequest("SDL.GetUserFriendlyMessage", { language = "EN-US", messageCodes = { "DataConsent" } }) EXPECT_HMIRESPONSE(requestId2) :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(_, data2) self.hmiConnection:SendResponse(data2.id,"BasicCommunication.ActivateApp", "SUCCESS", { }) end) :Times(1) end) end end) end function Test:TestStep3_Send_RPC_from_default_again() local RequestIDAddCommand = self.mobileSession:SendRPC("AddCommand", { cmdID = 111, menuParams = { position = 1, menuName ="Command111" } }) EXPECT_HMICALL("UI.AddCommand",{}) :Do(function(_,data) self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {}) end) EXPECT_RESPONSE(RequestIDAddCommand, { success = true, resultCode = "SUCCESS" }) EXPECT_NOTIFICATION("OnHashChange") end function Test:Precondition_Check_App_assigned_BASE4() local group_app_id_table = commonFunctions:get_data_policy_sql(config.pathToSDL.."/storage/policy.sqlite", "SELECT functional_group_id FROM app_group where application_id = '0000001'") local group_app_id for _, value in pairs(group_app_id_table) do group_app_id = value end if(group_app_id ~= base4) then self:FailTestCase("Application is not assigned to Base-4. Group: "..group_app_id) end end --[[ Postconditions ]] commonFunctions:newTestCasesGroup("Postconditions") function Test.Postcondition_Stop() 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
82796f24448947ee87f3fb5ae249ebf1051ea395
rc.lua
rc.lua
-- ####################################### -- Simple remote control through REST API -- Endpoints: -- / -> return last status -- /up -> trigger up button -- /down -> trigger down button -- ####################################### -- Global vars ssid = "YOUR_SSID" pass = "YOUR_PASSWORD" pin_up = 1 pin_down = 2 last_status = "UNKNOWN" -- ======================================= function triggerPin(pin, duration) if pin == pin_up then last_status = "UP" function triggerPin(pin, duration) if pin == pin_up then last_status = "UP" elseif pin == pin_down then last_status = "DOWN" end gpio.mode(pin, gpio.OUTPUT) gpio.write(pin, gpio.HIGH) tmr.alarm(0, duration, tmr.ALARM_SINGLE, function() gpio.write(pin, gpio.LOW) end) end function split(str, sep) -- copy string, as gmatch consumes it local s = str .. "" local r = {} local i = 1 for val in s:gmatch(sep) do r[i] = val i = i + 1 end if r[1] == nil or r[1] == "" then r[1] = str end return r end function parseHttpRequest(payload) local request = {} local data = split(payload, "^\r\n\r\n") if (data[2] ~= nil and data[2] ~= "") then request.data = json.decode(data[1]) end local header = split(data[1], "%S+") request.method = header[1] request.path = header[2] -- ignore headers... return request end -- Response format: { status: 200, json: false, data: "Hello" } -- If json == false, content is assumed to be HTML function sendHttpResponse(conn, response) if response == nil then response = {} end if response.status == nil then response.status = 200 print("status") end local res = "HTTP/1.1 " .. response.status .. " OK\r\n" if response.data ~= nil then local type = "text/html" local content = response.data if response.json ~= nil and response.json then print("json") type = "application/json" content = json.encode(response.data) end res = res .. "Content-Type:" .. type .. "\r\n\r\n" .. content else res = res .. "\r\n" end conn:send(res, function() conn:close() end) end -- ======================================= -- Setup wifi wifi.setmode(wifi.STATION) wifi.sta.config(ssid, pass) -- Blink led led_on = 0 gpio.mode(4, gpio.OUTPUT) gpio.write(4, gpio.LOW) tmr.alarm(0, 50, tmr.ALARM_AUTO, function() if led_on == 0 then led_on = 1 gpio.write(4, gpio.HIGH) else led_on = 0 gpio.write(4, gpio.LOW) end end) tmr.alarm(1, 1000, tmr.ALARM_SINGLE, function() gpio.write(4, gpio.HIGH) tmr.unregister(0) end) -- Init server srv = net.createServer(net.TCP) srv:listen(80, function(conn) conn:on("receive", function(conn,payload) local request = parseHttpRequest(payload) print("path: " .. request.path) if request.path == "/up" then triggerPin(pin_up, 200) sendHttpResponse(conn) elseif request.path == "/down" then triggerPin(pin_down, 200) sendHttpResponse(conn) else local html = "NodeMCU RC Status: " .. last_status sendHttpResponse(conn, { data = "<!doctype html><html><body>" .. html .. "</body></html>" }) end print(node.heap()) end) end)
-- ####################################### -- Simple remote control through REST API -- Endpoints: -- / -> return last status -- /up -> trigger up button -- /down -> trigger down button -- ####################################### -- Global vars ssid = "YOUR_SSID" pass = "YOUR_PASSWORD" pin_up = 1 pin_down = 2 last_status = "UNKNOWN" -- ======================================= function triggerPin(pin, duration) if pin == pin_up then last_status = "UP" elseif pin == pin_down then last_status = "DOWN" end gpio.mode(pin, gpio.OUTPUT) gpio.write(pin, gpio.HIGH) tmr.alarm(0, duration, tmr.ALARM_SINGLE, function() gpio.write(pin, gpio.LOW) end) end function split(str, sep) -- copy string, as gmatch consumes it local s = str .. "" local r = {} local i = 1 for val in s:gmatch(sep) do r[i] = val i = i + 1 end if r[1] == nil or r[1] == "" then r[1] = str end return r end function parseHttpRequest(payload) local request = {} local data = split(payload, "^\r\n\r\n") if (data[2] ~= nil and data[2] ~= "") then request.data = json.decode(data[1]) end local header = split(data[1], "%S+") request.method = header[1] request.path = header[2] -- ignore headers... return request end -- Response format: { status: 200, json: false, data: "Hello" } -- If json == false, content is assumed to be HTML function sendHttpResponse(conn, response) if response == nil then response = {} end if response.status == nil then response.status = 200 print("status") end local res = "HTTP/1.1 " .. response.status .. " OK\r\n" if response.data ~= nil then local type = "text/html" local content = response.data if response.json ~= nil and response.json then print("json") type = "application/json" content = json.encode(response.data) end res = res .. "Content-Type:" .. type .. "\r\n\r\n" .. content else res = res .. "\r\n" end conn:send(res, function() conn:close() end) end -- ======================================= -- Setup wifi wifi.setmode(wifi.STATION) wifi.sta.config(ssid, pass) -- Blink led led_on = 0 gpio.mode(4, gpio.OUTPUT) gpio.write(4, gpio.LOW) tmr.alarm(0, 50, tmr.ALARM_AUTO, function() if led_on == 0 then led_on = 1 gpio.write(4, gpio.HIGH) else led_on = 0 gpio.write(4, gpio.LOW) end end) tmr.alarm(1, 1000, tmr.ALARM_SINGLE, function() gpio.write(4, gpio.HIGH) tmr.unregister(0) end) -- Init server srv = net.createServer(net.TCP) srv:listen(80, function(conn) conn:on("receive", function(conn,payload) local request = parseHttpRequest(payload) print("path: " .. request.path) if request.path == "/up" then triggerPin(pin_up, 200) sendHttpResponse(conn) elseif request.path == "/down" then triggerPin(pin_down, 200) sendHttpResponse(conn) else local html = "NodeMCU RC Status: " .. last_status sendHttpResponse(conn, { data = "<!doctype html><html><body>" .. html .. "</body></html>" }) end print(node.heap()) end) end)
Fixed last commit
Fixed last commit
Lua
mit
sinedied/nodemcu-experiments
8d2bda36df94eaf8382d3dabdec130e0334410f4
Peripherals/WEB/webthread.lua
Peripherals/WEB/webthread.lua
--WEB Peripheral Thread print("WEB Peripheral started") --Thread communication channels local web_channel, peripheral_path = ... --Check if we have libcurl and/or luasec local has_libcurl = pcall(require,"Engine.luajit-request") local has_luasec = pcall(require,"Engine.luasec") print(has_libcurl and "libcurl is available" or "libcurl is not available") print(has_luasec and "luasec is available" or "luasec is not available") print((has_libcurl or has_luasec) and (has_luasec and "using luasec for https" or "using libcurl for http") or "https is not possible") --Load the libraries --Luajit-Request local lj_request if has_libcurl then lj_request = require("Engine.luajit-request") end local function lj_body_stream(chunk) if not chunk then return end web_channel:push("body") web_channel:push(chunk) end --LuaSec local ls_https if has_luasec then ls_https = require(peripheral_path.."https") end --LuaSocket local ls_http = require("socket.http") local ls_ltn12 = require("ltn12") local ls_url = require("socket.url") local ls_body --Set later when requesting to an empty table local function ls_sink(chunk) if not chunk then return end web_channel:push("body") web_channel:push(chunk) ls_body[#ls_body + 1] = chunk return 1 end while true do local specifiedLibrary = web_channel:demand() local request = web_channel:demand() if type(request) == "string" and request == "shutdown" then break end --Use LuaJIT-Request if LuaSec is not available if has_libcurl and ((not has_luasec) or (specifiedLibrary and specifiedLibrary == "libcurl")) then local url = request.url request.url = nil request.body_stream_callback = lj_body_stream local respond, _, message = lj_request(url,request) if respond then web_channel:push("respond") web_channel:push(respond) else web_channel:push("failed") web_channel:push(tostring(message)) end else --Use luaSec or luaSocket local http = ls_https or ls_http if specifiedLibrary and specifiedLibrary == "luasocket" then http = ls_http end ls_body = {} --Reset the receive body. if request.auth_type and request.auth_type == "basic" then local parsedURL = ls_url.parse(request.url) parsedURL.user = request.username or parsedURL.user parsedURL.password = request.password or parsedURL.password request.url = ls_url.build(parsedURL) end local http_req = { url = request.url, sink = ls_sink, method = request.method, headers = request.headers or {}, } if request.data then http_req.source = ls_ltn12.source.string(request.data) http_req.headers["Content-Length"] = http_req.headers["Content-Length"] or #request.data end if type(request.allow_redirects) ~= "nil" then http_req.redirect = request.allow_redirects end if request.cookies then http_req.headers["Cookie"] = request.cookies end http.TIMEOUT = (request.timeout or 1)*60 local success,statuscode, headers, statusline = http.request(http_req) ls_body = table.concat(ls_body) if success then local respond = { code = statuscode, body = ls_body, headers = headers } if headers["Set-Cookie"] then respond.set_cookies = headers["Set-Cookie"] end web_channel:push("respond") web_channel:push(respond) else web_channel:push("failed") web_channel:push(tostring(statuscode)) end end end
--WEB Peripheral Thread print("------------------------------") --Thread communication channels local web_channel, peripheral_path = ... --Check if we have libcurl and/or luasec local has_libcurl = pcall(require,"Engine.luajit-request") local has_luasec = pcall(require,"ssl") print(has_libcurl and "- libcurl is available" or "- libcurl is not available") print(has_luasec and "- luasec is available" or "- luasec is not available") print((has_libcurl or has_luasec) and (has_luasec and "- using luasec for https" or "- using libcurl for https") or "- https is not available") print("------------------------------") --Load the libraries --Luajit-Request local lj_request if has_libcurl then lj_request = require("Engine.luajit-request") end local function lj_body_stream(chunk) if not chunk then return end web_channel:push("body") web_channel:push(chunk) end --LuaSec local ls_https if has_luasec then ls_https = require(peripheral_path.."https") end --LuaSocket local ls_http = require("socket.http") local ls_ltn12 = require("ltn12") local ls_url = require("socket.url") local ls_body --Set later when requesting to an empty table local function ls_sink(chunk) if not chunk then return end web_channel:push("body") web_channel:push(chunk) ls_body[#ls_body + 1] = chunk return 1 end while true do local specifiedLibrary = web_channel:demand() local request = web_channel:demand() if type(request) == "string" and request == "shutdown" then break end --Use LuaJIT-Request if LuaSec is not available if has_libcurl and ((not has_luasec) or (specifiedLibrary and specifiedLibrary == "libcurl")) then local url = request.url request.url = nil request.body_stream_callback = lj_body_stream local respond, _, message = lj_request(url,request) if respond then web_channel:push("respond") web_channel:push(respond) else web_channel:push("failed") web_channel:push(tostring(message)) end else --Use luaSec or luaSocket local http = ls_https or ls_http if specifiedLibrary and specifiedLibrary == "luasocket" then http = ls_http end ls_body = {} --Reset the receive body. if request.auth_type and request.auth_type == "basic" then local parsedURL = ls_url.parse(request.url) parsedURL.user = request.username or parsedURL.user parsedURL.password = request.password or parsedURL.password request.url = ls_url.build(parsedURL) end local http_req = { url = request.url, sink = ls_sink, method = request.method, headers = request.headers or {}, } if request.data then http_req.source = ls_ltn12.source.string(request.data) http_req.headers["Content-Length"] = http_req.headers["Content-Length"] or #request.data end if type(request.allow_redirects) ~= "nil" then http_req.redirect = request.allow_redirects end if request.cookies then http_req.headers["Cookie"] = request.cookies end http.TIMEOUT = (request.timeout or 1)*60 local success,statuscode, headers, statusline = http.request(http_req) ls_body = table.concat(ls_body) if success then local respond = { code = statuscode, body = ls_body, headers = headers } if headers["Set-Cookie"] then respond.set_cookies = headers["Set-Cookie"] end web_channel:push("respond") web_channel:push(respond) else web_channel:push("failed") web_channel:push(tostring(statuscode)) end end end
Typofix
Typofix Former-commit-id: 83cff8bcbca863de144e3555c7be26b173b06c6c
Lua
mit
RamiLego4Game/LIKO-12
90cdd0771c52d4ce245599305e7fa96aaa9c59ca
30log.lua
30log.lua
--[[ Copyright (c) 2012 Roland Yonaba Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --]] local function deep_copy(t) local r = {} for k,v in pairs(t) do if type(v) == 'table' then r[k] = deep_copy(v) else r[k] = v end end return r end local function instantiate(self,...) local instance = setmetatable({},self) if self.__init then self.__init(instance, ...) end return instance end local function extends(self,extra_params) local heirClass = class(extra_params) heirClass.__index, heirClass.super = heirClass, self return setmetatable(heirClass,self) end local baseMt = {__call = function (self,...) return self:new(...) end} class = function(members) local newClass = members and deep_copy(members) or {} newClass.__index, newClass.__call = newClass, baseMt.__call newClass.new = instantiate newClass.extends = extends return setmetatable(newClass,baseMt) end
--[[ Copyright (c) 2012 Roland Yonaba Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --]] local function deep_copy(t) local r = {} for k,v in pairs(t) do if type(v) == 'table' then r[k] = deep_copy(v) else r[k] = v end end return r end local function instantiate(self,...) local instance = setmetatable({},self) if self.__init then self.__init(instance, ...) end return instance end local function extends(self,extra_params) local heirClass = class(extra_params) heirClass.__index, heirClass.super = heirClass, self return setmetatable(heirClass,self) end local baseMt = {__call = function (self,...) return self:new(...) end} class = function(members) local newClass = members and deep_copy(members) or {} newClass.__index, newClass.__call = newClass, baseMt.__call newClass.new = instantiate newClass.extends = extends return setmetatable(newClass,baseMt) end
Fixed Indentation style, regards to LuaStyle Convention
Fixed Indentation style, regards to LuaStyle Convention
Lua
mit
tizzybec/30log,aubergine10/30log
e91a539e823a947bfdc1f9947ac4929238bebce6
mod_tcpproxy/mod_tcpproxy.lua
mod_tcpproxy/mod_tcpproxy.lua
local st = require "util.stanza"; local xmlns_ibb = "http://jabber.org/protocol/ibb"; local xmlns_tcp = "http://prosody.im/protocol/tcpproxy"; local host_attr, port_attr = xmlns_tcp.."\1host", xmlns_tcp.."\1port"; local base64 = require "util.encodings".base64; local b64, unb64 = base64.encode, base64.decode; local host = module.host; local open_connections = {}; local function new_session(jid, sid, conn) if not open_connections[jid] then open_connections[jid] = {}; end open_connections[jid][sid] = conn; end local function close_session(jid, sid) if open_connections[jid] then open_connections[jid][sid] = nil; if next(open_connections[jid]) == nil then open_connections[jid] = nil; end return true; end end function proxy_component(origin, stanza) local ibb_tag = stanza.tags[1]; if (not (stanza.name == "iq" and stanza.attr.type == "set") and stanza.name ~= "message") or (not (ibb_tag) or ibb_tag.attr.xmlns ~= xmlns_ibb) then if stanza.attr.type ~= "error" then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); end return; end if ibb_tag.name == "open" then -- Starting a new stream local to_host, to_port = ibb_tag.attr[host_attr], ibb_tag.attr[port_attr]; local jid, sid = stanza.attr.from, ibb_tag.attr.sid; if not (to_host and to_port) then return origin.send(st.error_reply(stanza, "modify", "bad-request", "No host/port specified")); elseif not sid or sid == "" then return origin.send(st.error_reply(stanza, "modify", "bad-request", "No sid specified")); elseif ibb_tag.attr.stanza ~= "message" then return origin.send(st.error_reply(stanza, "modify", "bad-request", "Only 'message' stanza transport is supported")); end local conn, err = socket.tcp(); if not conn then return origin.send(st.error_reply(stanza, "wait", "resource-constraint", err)); end conn:settimeout(0); local success, err = conn:connect(to_host, to_port); if not success and err ~= "timeout" then return origin.send(st.error_reply(stanza, "wait", "remote-server-not-found", err)); end local listener,seq = {}, 0; function listener.onconnect(conn) origin.send(st.reply(stanza)); end function listener.onincoming(conn, data) origin.send(st.message({to=jid,from=host}) :tag("data", {xmlns=xmlns_ibb,seq=seq,sid=sid}) :text(b64(data))); seq = seq + 1; end function listener.ondisconnect(conn, err) origin.send(st.message({to=jid,from=host}) :tag("close", {xmlns=xmlns_ibb,sid=sid})); close_session(jid, sid); end conn = server.wrapclient(conn, to_host, to_port, listener, "*a" ); new_session(jid, sid, conn); elseif ibb_tag.name == "data" then local conn = open_connections[stanza.attr.from][ibb_tag.attr.sid]; if conn then conn:write(unb64(ibb_tag:get_text())); else return origin.send(st.error_reply(stanza, "cancel", "item-not-found")); end elseif ibb_tag.name == "close" then if close_session(stanza.attr.from, ibb_tag.attr.sid) then origin.send(st.reply(stanza)); else return origin.send(st.error_reply(stanza, "cancel", "item-not-found")); end end end require "core.componentmanager".register_component(host, proxy_component);
local st = require "util.stanza"; local xmlns_ibb = "http://jabber.org/protocol/ibb"; local xmlns_tcp = "http://prosody.im/protocol/tcpproxy"; local host_attr, port_attr = xmlns_tcp.."\1host", xmlns_tcp.."\1port"; local base64 = require "util.encodings".base64; local b64, unb64 = base64.encode, base64.decode; local host = module.host; local open_connections = {}; local function new_session(jid, sid, conn) if not open_connections[jid] then open_connections[jid] = {}; end open_connections[jid][sid] = conn; end local function close_session(jid, sid) if open_connections[jid] then open_connections[jid][sid] = nil; if next(open_connections[jid]) == nil then open_connections[jid] = nil; end return true; end end function proxy_component(origin, stanza) local ibb_tag = stanza.tags[1]; if (not (stanza.name == "iq" and stanza.attr.type == "set") and stanza.name ~= "message") or (not (ibb_tag) or ibb_tag.attr.xmlns ~= xmlns_ibb) then if stanza.attr.type ~= "error" then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); end return; end if ibb_tag.name == "open" then -- Starting a new stream local to_host, to_port = ibb_tag.attr[host_attr], ibb_tag.attr[port_attr]; local jid, sid = stanza.attr.from, ibb_tag.attr.sid; if not (to_host and to_port) then return origin.send(st.error_reply(stanza, "modify", "bad-request", "No host/port specified")); elseif not sid or sid == "" then return origin.send(st.error_reply(stanza, "modify", "bad-request", "No sid specified")); elseif ibb_tag.attr.stanza ~= "message" then return origin.send(st.error_reply(stanza, "modify", "bad-request", "Only 'message' stanza transport is supported")); end local conn, err = socket.tcp(); if not conn then return origin.send(st.error_reply(stanza, "wait", "resource-constraint", err)); end conn:settimeout(0); local success, err = conn:connect(to_host, to_port); if not success and err ~= "timeout" then return origin.send(st.error_reply(stanza, "wait", "remote-server-not-found", err)); end local listener,seq = {}, 0; function listener.onconnect(conn) origin.send(st.reply(stanza)); end function listener.onincoming(conn, data) origin.send(st.message({to=jid,from=host}) :tag("data", {xmlns=xmlns_ibb,seq=seq,sid=sid}) :text(b64(data))); seq = seq + 1; end function listener.ondisconnect(conn, err) origin.send(st.message({to=jid,from=host}) :tag("close", {xmlns=xmlns_ibb,sid=sid})); close_session(jid, sid); end conn = server.wrapclient(conn, to_host, to_port, listener, "*a" ); new_session(jid, sid, conn); elseif ibb_tag.name == "data" then local conn = open_connections[stanza.attr.from][ibb_tag.attr.sid]; if conn then local data = unb64(ibb_tag:get_text()); if data then conn:write(data); else return origin.send( st.error_reply(stanza, "modify", "bad-request", "Invalid data (base64?)") ); end else return origin.send(st.error_reply(stanza, "cancel", "item-not-found")); end elseif ibb_tag.name == "close" then if close_session(stanza.attr.from, ibb_tag.attr.sid) then origin.send(st.reply(stanza)); else return origin.send(st.error_reply(stanza, "cancel", "item-not-found")); end end end require "core.componentmanager".register_component(host, proxy_component);
mod_tcpproxy: Handle gracefully invalid base64 data, fixes #2 (thanks dersd)
mod_tcpproxy: Handle gracefully invalid base64 data, fixes #2 (thanks dersd)
Lua
mit
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
1d3b23cb46df49f14d568d47a46092b5ea3ba017
mod_pastebin/mod_pastebin.lua
mod_pastebin/mod_pastebin.lua
local st = require "util.stanza"; local httpserver = require "net.httpserver"; local uuid_new = require "util.uuid".generate; local os_time = os.time; local t_insert, t_remove = table.insert, table.remove; local add_task = require "util.timer".add_task; local length_threshold = config.get(module.host, "core", "pastebin_threshold") or 500; local base_url = config.get(module.host, "core", "pastebin_url"); -- Seconds a paste should live for in seconds (config is in hours), default 24 hours local expire_after = math.floor((config.get(module.host, "core", "pastebin_expire_after") or 24) * 3600); local trigger_string = config.get(module.host, "core", "pastebin_trigger"); trigger_string = (trigger_string and trigger_string .. " ") or ""; local pastes = {}; local default_headers = { ["Content-Type"] = "text/plain; charset=utf-8" }; local xmlns_xhtmlim = "http://jabber.org/protocol/xhtml-im"; local xmlns_xhtml = "http://www.w3.org/1999/xhtml"; function pastebin_text(text) local uuid = uuid_new(); pastes[uuid] = { body = text, time = os_time(), headers = default_headers }; pastes[#pastes+1] = uuid; if not pastes[2] then -- No other pastes, give the timer a kick add_task(expire_after, expire_pastes); end return base_url..uuid; end function handle_request(method, body, request) local pasteid = request.url.path:match("[^/]+$"); if not pasteid or not pastes[pasteid] then return "Invalid paste id, perhaps it expired?"; end --module:log("debug", "Received request, replying: %s", pastes[pasteid].text); return pastes[pasteid]; end function check_message(data) local origin, stanza = data.origin, data.stanza; local body, bodyindex, htmlindex; for k,v in ipairs(stanza) do if v.name == "body" then body, bodyindex = v, k; elseif v.name == "html" and v.attr.xmlns == xmlns_xhtmlim then htmlindex = k; end end if not body then return; end body = body:get_text(); --module:log("debug", "Body(%s) length: %d", type(body), #(body or "")); if body and ((#body > length_threshold) or (body:find(trigger_string, 1, true) == 1)) then body = body:gsub("^" .. trigger_string, "", 1); local url = pastebin_text(body); module:log("debug", "Pasted message as %s", url); --module:log("debug", " stanza[bodyindex] = %q", tostring( stanza[bodyindex])); stanza[bodyindex][1] = url; local html = st.stanza("html", { xmlns = xmlns_xhtmlim }):tag("body", { xmlns = xmlns_xhtml }); html:tag("p"):text(body:sub(1,150)):up(); html:tag("a", { href = url }):text("[...]"):up(); stanza[htmlindex or #stanza+1] = html; end end module:hook("message/bare", check_message); function expire_pastes(time) time = time or os_time(); -- COMPAT with 0.5 if pastes[1] then pastes[pastes[1]] = nil; t_remove(pastes, 1); if pastes[1] then return (expire_after - (time - pastes[pastes[1]].time)) + 1; end end end local ports = config.get(module.host, "core", "pastebin_ports") or { 5280 }; for _, options in ipairs(ports) do local port, base, ssl, interface = 5280, "pastebin", false, nil; if type(options) == "number" then port = options; elseif type(options) == "table" then port, base, ssl, interface = options.port or 5280, options.path or "pastebin", options.ssl or false, options.interface; elseif type(options) == "string" then base = options; end base_url = base_url or ("http://"..module:get_host()..(port ~= 80 and (":"..port) or "").."/"..base.."/"); httpserver.new{ port = port, base = base, handler = handle_request, ssl = ssl } end
local st = require "util.stanza"; local httpserver = require "net.httpserver"; local uuid_new = require "util.uuid".generate; local os_time = os.time; local t_insert, t_remove = table.insert, table.remove; local add_task = require "util.timer".add_task; local length_threshold = config.get(module.host, "core", "pastebin_threshold") or 500; local line_threshold = config.get(module.host, "core", "pastebin_line_threshold") or 4; local base_url = config.get(module.host, "core", "pastebin_url"); -- Seconds a paste should live for in seconds (config is in hours), default 24 hours local expire_after = math.floor((config.get(module.host, "core", "pastebin_expire_after") or 24) * 3600); local trigger_string = config.get(module.host, "core", "pastebin_trigger"); trigger_string = (trigger_string and trigger_string .. " "); local pastes = {}; local default_headers = { ["Content-Type"] = "text/plain; charset=utf-8" }; local xmlns_xhtmlim = "http://jabber.org/protocol/xhtml-im"; local xmlns_xhtml = "http://www.w3.org/1999/xhtml"; function pastebin_text(text) local uuid = uuid_new(); pastes[uuid] = { body = text, time = os_time(), headers = default_headers }; pastes[#pastes+1] = uuid; if not pastes[2] then -- No other pastes, give the timer a kick add_task(expire_after, expire_pastes); end return base_url..uuid; end function handle_request(method, body, request) local pasteid = request.url.path:match("[^/]+$"); if not pasteid or not pastes[pasteid] then return "Invalid paste id, perhaps it expired?"; end --module:log("debug", "Received request, replying: %s", pastes[pasteid].text); return pastes[pasteid]; end function check_message(data) local origin, stanza = data.origin, data.stanza; local body, bodyindex, htmlindex; for k,v in ipairs(stanza) do if v.name == "body" then body, bodyindex = v, k; elseif v.name == "html" and v.attr.xmlns == xmlns_xhtmlim then htmlindex = k; end end if not body then return; end body = body:get_text(); --module:log("debug", "Body(%s) length: %d", type(body), #(body or "")); if body and ( (#body > length_threshold) or (trigger_string and body:find(trigger_string, 1, true) == 1) or (select(2, body:gsub("\n", "%0")) >= line_threshold) ) then if trigger_string then body = body:gsub("^" .. trigger_string, "", 1); end local url = pastebin_text(body); module:log("debug", "Pasted message as %s", url); --module:log("debug", " stanza[bodyindex] = %q", tostring( stanza[bodyindex])); stanza[bodyindex][1] = url; local html = st.stanza("html", { xmlns = xmlns_xhtmlim }):tag("body", { xmlns = xmlns_xhtml }); html:tag("p"):text(body:sub(1,150)):up(); html:tag("a", { href = url }):text("[...]"):up(); stanza[htmlindex or #stanza+1] = html; end end module:hook("message/bare", check_message); function expire_pastes(time) time = time or os_time(); -- COMPAT with 0.5 if pastes[1] then pastes[pastes[1]] = nil; t_remove(pastes, 1); if pastes[1] then return (expire_after - (time - pastes[pastes[1]].time)) + 1; end end end local ports = config.get(module.host, "core", "pastebin_ports") or { 5280 }; for _, options in ipairs(ports) do local port, base, ssl, interface = 5280, "pastebin", false, nil; if type(options) == "number" then port = options; elseif type(options) == "table" then port, base, ssl, interface = options.port or 5280, options.path or "pastebin", options.ssl or false, options.interface; elseif type(options) == "string" then base = options; end base_url = base_url or ("http://"..module:get_host()..(port ~= 80 and (":"..port) or "").."/"..base.."/"); httpserver.new{ port = port, base = base, handler = handle_request, ssl = ssl } end
mod_pastebin: Fix trigger_string matching when no trigger is set, and add support for counting lines (pastebin_line_threshold, default: 4)
mod_pastebin: Fix trigger_string matching when no trigger is set, and add support for counting lines (pastebin_line_threshold, default: 4)
Lua
mit
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
fd8853fa6edf49d5463896505a7f7d713faa26ed
mod_adhoc_cmd_admin/mod_adhoc_cmd_admin.lua
mod_adhoc_cmd_admin/mod_adhoc_cmd_admin.lua
-- Copyright (C) 2009 Florian Zeitz -- -- This file is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local _G = _G; local prosody = _G.prosody; local hosts = prosody.hosts; local usermanager_user_exists = require "core.usermanager".user_exists; local usermanager_create_user = require "core.usermanager".create_user; local is_admin = require "core.usermanager".is_admin; local st, jid, uuid = require "util.stanza", require "util.jid", require "util.uuid"; local dataforms_new = require "util.dataforms".new; local adhoc_new = module:require "adhoc".new; local sessions = {}; local add_user_layout = dataforms_new{ title = "Adding a User"; instructions = "Fill out this form to add a user."; { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/admin" }; { name = "accountjid", type = "jid-single", required = true, label = "The Jabber ID for the account to be added" }; { name = "password", type = "text-private", label = "The password for this account" }; { name = "password-verify", type = "text-private", label = "Retype password" }; }; local get_online_users_layout = dataforms_new{ title = "Getting List of Online Users"; instructions = "How many users should be returned at most?"; { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/admin" }; { name = "max_items", type = "list-single", label = "Maximum number of users", value = { "25", "50", "75", "100", "150", "200", "all" } }; }; function add_user_command_handler(item, origin, stanza) if not is_admin(stanza.attr.from) then module:log("warn", "Non-admin %s tried to add a user", tostring(jid.bare(stanza.attr.from))); origin.send(st.error_reply(stanza, "auth", "forbidden", "You don't have permission to add a user"):up() :add_child(item:cmdtag("canceled") :tag("note", {type="error"}):text("You don't have permission to add a user"))); return true; end if stanza.tags[1].attr.sessionid and sessions[stanza.tags[1].attr.sessionid] then if stanza.tags[1].attr.action == "cancel" then origin.send(st.reply(stanza):add_child(item:cmdtag("canceled", stanza.tags[1].attr.sessionid))); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end form = stanza.tags[1]:child_with_ns("jabber:x:data"); local fields = add_user_layout:data(form); local username, host, resource = jid.split(fields.accountjid); if (fields.password == fields["password-verify"]) and username and host and host == stanza.attr.to then if usermanager_user_exists(username, host) then origin.send(st.error_reply(stanza, "cancel", "conflict", "Account already exists"):up() :add_child(item:cmdtag("canceled", stanza.tags[1].attr.sessionid) :tag("note", {type="error"}):text("Account already exists"))); sessions[stanza.tags[1].attr.sessionid] = nil; return true; else if usermanager_create_user(username, fields.password, host) then origin.send(st.reply(stanza):add_child(item:cmdtag("completed", stanza.tags[1].attr.sessionid) :tag("note", {type="info"}):text("Account successfully created"))); sessions[stanza.tags[1].attr.sessionid] = nil; module:log("debug", "Created new account " .. username.."@"..host); return true; else origin.send(st.error_reply(stanza, "wait", "internal-server-error", "Failed to write data to disk"):up() :add_child(item:cmdtag("canceled", stanza.tags[1].attr.sessionid) :tag("note", {type="error"}):text("Failed to write data to disk"))); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end end else module:log("debug", fields.accountjid .. " " .. fields.password .. " " .. fields["password-verify"]); origin.send(st.error_reply(stanza, "cancel", "conflict", "Invalid data.\nPassword mismatch, or empty username"):up() :add_child(item:cmdtag("canceled", stanza.tags[1].attr.sessionid) :tag("note", {type="error"}):text("Invalid data.\nPassword mismatch, or empty username"))); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end else local sessionid=uuid.generate(); sessions[sessionid] = "executing"; origin.send(st.reply(stanza):add_child(item:cmdtag("executing", sessionid):add_child(add_user_layout:form()))); end return true; end function get_online_users_command_handler(item, origin, stanza) if not is_admin(stanza.attr.from) then origin.send(st.error_reply(stanza, "auth", "forbidden", "You don't have permission to request a list of online users"):up() :add_child(item:cmdtag("canceled") :tag("note", {type="error"}):text("You don't have permission to request a list of online users"))); return true; end if stanza.tags[1].attr.sessionid and sessions[stanza.tags[1].attr.sessionid] then if stanza.tags[1].attr.action == "cancel" then origin.send(st.reply(stanza):add_child(item:cmdtag("canceled", stanza.tags[1].attr.sessionid))); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end form = stanza.tags[1]:child_with_ns("jabber:x:data"); local fields = add_user_layout:data(form); local max_items = nil if fields.max_items ~= "all" then max_items = tonumber(fields.max_items); end local count = 0; local field = st.stanza("field", {label="The list of all online users", var="onlineuserjids", type="text-multi"}); for username, user in pairs(hosts[stanza.attr.to].sessions or {}) do if (max_items ~= nil) and (count >= max_items) then break; end field:tag("value"):text(username.."@"..stanza.attr.to):up(); count = count + 1; end origin.send(st.reply(stanza):add_child(item:cmdtag("completed", stanza.tags[1].attr.sessionid) :tag("x", {xmlns="jabber:x:data", type="result"}) :tag("field", {type="hidden", var="FORM_TYPE"}) :tag("value"):text("http://jabber.org/protocol/admin"):up():up() :add_child(field))); else local sessionid=uuid.generate(); sessions[sessionid] = "executing"; origin.send(st.reply(stanza):add_child(item:cmdtag("executing", sessionid):add_child(get_online_users_layout:form()))); end return true; end local add_user_desc = adhoc_new("Add User", "http://jabber.org/protocol/admin#add-user", add_user_command_handler, "admin"); local get_online_users_desc = adhoc_new("Get List of Online Users", "http://jabber.org/protocol/admin#get-online-users", get_online_users_command_handler, "admin"); function module.unload() module:remove_item("adhoc", add_user_desc); module:remove_item("adhoc", get_online_users_desc); end module:add_item("adhoc", add_user_desc); module:add_item("adhoc", get_online_users_desc);
-- Copyright (C) 2009 Florian Zeitz -- -- This file is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local _G = _G; local prosody = _G.prosody; local hosts = prosody.hosts; local usermanager_user_exists = require "core.usermanager".user_exists; local usermanager_create_user = require "core.usermanager".create_user; local is_admin = require "core.usermanager".is_admin; local st, jid, uuid = require "util.stanza", require "util.jid", require "util.uuid"; local dataforms_new = require "util.dataforms".new; local adhoc_new = module:require "adhoc".new; local sessions = {}; local add_user_layout = dataforms_new{ title = "Adding a User"; instructions = "Fill out this form to add a user."; { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/admin" }; { name = "accountjid", type = "jid-single", required = true, label = "The Jabber ID for the account to be added" }; { name = "password", type = "text-private", label = "The password for this account" }; { name = "password-verify", type = "text-private", label = "Retype password" }; }; local get_online_users_layout = dataforms_new{ title = "Getting List of Online Users"; instructions = "How many users should be returned at most?"; { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/admin" }; { name = "max_items", type = "list-single", label = "Maximum number of users", value = { "25", "50", "75", "100", "150", "200", "all" } }; }; function add_user_command_handler(item, origin, stanza) if not is_admin(stanza.attr.from) then module:log("warn", "Non-admin %s tried to add a user", tostring(jid.bare(stanza.attr.from))); origin.send(st.error_reply(stanza, "auth", "forbidden", "You don't have permission to add a user"):up() :add_child(item:cmdtag("canceled") :tag("note", {type="error"}):text("You don't have permission to add a user"))); return true; end if stanza.tags[1].attr.sessionid and sessions[stanza.tags[1].attr.sessionid] then if stanza.tags[1].attr.action == "cancel" then origin.send(st.reply(stanza):add_child(item:cmdtag("canceled", stanza.tags[1].attr.sessionid))); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end form = stanza.tags[1]:child_with_ns("jabber:x:data"); local fields = add_user_layout:data(form); local username, host, resource = jid.split(fields.accountjid); if (fields.password == fields["password-verify"]) and username and host and host == stanza.attr.to then if usermanager_user_exists(username, host) then origin.send(st.error_reply(stanza, "cancel", "conflict", "Account already exists"):up() :add_child(item:cmdtag("canceled", stanza.tags[1].attr.sessionid) :tag("note", {type="error"}):text("Account already exists"))); sessions[stanza.tags[1].attr.sessionid] = nil; return true; else if usermanager_create_user(username, fields.password, host) then origin.send(st.reply(stanza):add_child(item:cmdtag("completed", stanza.tags[1].attr.sessionid) :tag("note", {type="info"}):text("Account successfully created"))); sessions[stanza.tags[1].attr.sessionid] = nil; module:log("debug", "Created new account " .. username.."@"..host); return true; else origin.send(st.error_reply(stanza, "wait", "internal-server-error", "Failed to write data to disk"):up() :add_child(item:cmdtag("canceled", stanza.tags[1].attr.sessionid) :tag("note", {type="error"}):text("Failed to write data to disk"))); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end end else module:log("debug", fields.accountjid .. " " .. fields.password .. " " .. fields["password-verify"]); origin.send(st.error_reply(stanza, "cancel", "conflict", "Invalid data.\nPassword mismatch, or empty username"):up() :add_child(item:cmdtag("canceled", stanza.tags[1].attr.sessionid) :tag("note", {type="error"}):text("Invalid data.\nPassword mismatch, or empty username"))); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end else local sessionid=uuid.generate(); sessions[sessionid] = "executing"; origin.send(st.reply(stanza):add_child(item:cmdtag("executing", sessionid):add_child(add_user_layout:form()))); end return true; end function get_online_users_command_handler(item, origin, stanza) if not is_admin(stanza.attr.from) then origin.send(st.error_reply(stanza, "auth", "forbidden", "You don't have permission to request a list of online users"):up() :add_child(item:cmdtag("canceled") :tag("note", {type="error"}):text("You don't have permission to request a list of online users"))); return true; end if stanza.tags[1].attr.sessionid and sessions[stanza.tags[1].attr.sessionid] then if stanza.tags[1].attr.action == "cancel" then origin.send(st.reply(stanza):add_child(item:cmdtag("canceled", stanza.tags[1].attr.sessionid))); sessions[stanza.tags[1].attr.sessionid] = nil; return true; end form = stanza.tags[1]:child_with_ns("jabber:x:data"); local fields = add_user_layout:data(form); local max_items = nil if fields.max_items ~= "all" then max_items = tonumber(fields.max_items); end local count = 0; local field = st.stanza("field", {label="The list of all online users", var="onlineuserjids", type="text-multi"}); for username, user in pairs(hosts[stanza.attr.to].sessions or {}) do if (max_items ~= nil) and (count >= max_items) then break; end field:tag("value"):text(username.."@"..stanza.attr.to):up(); count = count + 1; end origin.send(st.reply(stanza):add_child(item:cmdtag("completed", stanza.tags[1].attr.sessionid) :tag("x", {xmlns="jabber:x:data", type="result"}) :tag("field", {type="hidden", var="FORM_TYPE"}) :tag("value"):text("http://jabber.org/protocol/admin"):up():up() :add_child(field))); sessions[stanza.tags[1].attr.sessionid] = nil; return true; else local sessionid=uuid.generate(); sessions[sessionid] = "executing"; origin.send(st.reply(stanza):add_child(item:cmdtag("executing", sessionid):add_child(get_online_users_layout:form()))); end return true; end local add_user_desc = adhoc_new("Add User", "http://jabber.org/protocol/admin#add-user", add_user_command_handler, "admin"); local get_online_users_desc = adhoc_new("Get List of Online Users", "http://jabber.org/protocol/admin#get-online-users", get_online_users_command_handler, "admin"); function module.unload() module:remove_item("adhoc", add_user_desc); module:remove_item("adhoc", get_online_users_desc); end module:add_item("adhoc", add_user_desc); module:add_item("adhoc", get_online_users_desc);
mod_adhoc_cmd_admin: Fix session leak
mod_adhoc_cmd_admin: Fix session leak
Lua
mit
Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules,Contatta/prosody-modules
1feeddb712f860965ec4209aed1dedf5f2a036e1
scripts/tundra/syntax/qt.lua
scripts/tundra/syntax/qt.lua
-- qt.lua -- support for Qt-specific compilers and tools module(..., package.seeall) local scanner = require "tundra.scanner" local path = require "tundra.path" DefRule { Name = "Moc", Command = "$(QTMOCCMD)", ConfigInvariant = true, Blueprint = { Source = { Required = true, Type = "string" }, }, Setup = function (env, data) local src = data.Source -- We follow these conventions: -- If the source file is a header, we do a traditional header moc: -- - input: foo.h, output: moc_foo.cpp -- - moc_foo.cpp is then compiled separately together with (presumably) foo.cpp -- If the source file is a cpp file, we do things a little differently: -- - input: foo.cpp, output foo.moc -- - foo.moc is then manually included at the end of foo.cpp local base_name = path.drop_suffix(src) local pfx = 'moc_' local ext = '.cpp' if path.get_extension(src) == ".cpp" then pfx = '' ext = '.moc' end return { InputFiles = { src }, OutputFiles = { "$(OBJECTROOT)$(SEP)" .. pfx .. base_name .. ext }, Scanner = scanner.make_cpp_scanner(env:get_list('CPPPATH')) } end, } DefRule { Name = "Rcc", Command = "$(QTRCCCMD)", ConfigInvariant = true, Blueprint = { Source = { Required = true, Type = "string" }, }, Setup = function (env, data) local src = data.Source local base_name = path.drop_suffix(src) local pfx = 'qrc_' local ext = '.cpp' return { InputFiles = { src }, OutputFiles = { "$(OBJECTROOT)$(SEP)" .. pfx .. base_name .. ext }, Scanner = scanner.make_generic_scanner { Paths = { "." }, KeywordsNoFollow = { "<file" }, UseSeparators = true }, } end, } DefRule { Name = "Uic", Command = "$(QTUICCMD)", ConfigInvariant = true, Blueprint = { Source = { Required = true, Type = "string" }, }, Setup = function (env, data) local src = data.Source local base_name = path.drop_suffix(src) local pfx = 'ui_' local ext = '.h' return { InputFiles = { src }, OutputFiles = { "$(OBJECTROOT)$(SEP)" .. pfx .. base_name .. ext }, } end, }
-- qt.lua -- support for Qt-specific compilers and tools module(..., package.seeall) local scanner = require "tundra.scanner" local path = require "tundra.path" DefRule { Name = "Moc", Command = "$(QTMOCCMD)", ConfigInvariant = true, Blueprint = { Source = { Required = true, Type = "string" }, }, Setup = function (env, data) local src = data.Source -- We follow these conventions: -- If the source file is a header, we do a traditional header moc: -- - input: foo.h, output: moc_foo.cpp -- - moc_foo.cpp is then compiled separately together with (presumably) foo.cpp -- If the source file is a cpp file, we do things a little differently: -- - input: foo.cpp, output foo.moc -- - foo.moc is then manually included at the end of foo.cpp local base_name = path.get_filename_base(src) local pfx = 'moc_' local ext = '.cpp' if path.get_extension(src) == ".cpp" then pfx = '' ext = '.moc' end return { InputFiles = { src }, OutputFiles = { "$(OBJECTDIR)$(SEP)" .. pfx .. base_name .. ext }, Scanner = scanner.make_cpp_scanner(env:get_list('CPPPATH')) } end, } DefRule { Name = "Rcc", Command = "$(QTRCCCMD)", ConfigInvariant = true, Blueprint = { Source = { Required = true, Type = "string" }, }, Setup = function (env, data) local src = data.Source local base_name = path.get_filename_base(src) local pfx = 'qrc_' local ext = '.cpp' return { InputFiles = { src }, OutputFiles = { "$(OBJECTDIR)$(SEP)" .. pfx .. base_name .. ext }, Scanner = scanner.make_generic_scanner { Paths = { "." }, KeywordsNoFollow = { "<file" }, UseSeparators = true }, } end, } DefRule { Name = "Uic", Command = "$(QTUICCMD)", ConfigInvariant = true, Blueprint = { Source = { Required = true, Type = "string" }, }, Setup = function (env, data) local src = data.Source local base_name = path.get_filename_base(src) local pfx = 'ui_' local ext = '.h' return { InputFiles = { src }, OutputFiles = { "$(OBJECTDIR)$(SEP)" .. pfx .. base_name .. ext }, } end, }
Fix up crazy Qt codegen paths.
Fix up crazy Qt codegen paths. Add OBJECTDIR to CPPPATH to use Moc, Rcc and Uic.
Lua
mit
bmharper/tundra,bmharper/tundra,bmharper/tundra,deplinenoise/tundra,deplinenoise/tundra,bmharper/tundra,deplinenoise/tundra
fc4eec59c9d953539ce9ee1801cdaebf1ec2109d
scripts/tundra/decl.lua
scripts/tundra/decl.lua
-- Copyright 2010 Andreas Fredriksson -- -- This file is part of Tundra. -- -- Tundra 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 3 of the License, or -- (at your option) any later version. -- -- Tundra 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 Tundra. If not, see <http://www.gnu.org/licenses/>. module(..., package.seeall) local nodegen = require "tundra.nodegen" local functions = {} local _decl_meta = {} _decl_meta.__index = _decl_meta local current = nil local function new_parser() local obj = { Functions = {}, Results = {}, DefaultTargets = {}, AlwaysTargets = {}, } local outer_env = _G local iseval = nodegen.is_evaluator local function indexfunc(tab, var) if iseval(var) then -- Return an anonymous function such that -- the code "Foo { ... }" will result in a call to -- "nodegen.evaluate('Foo', { ... })" return function (data) local result = nodegen.evaluate(var, data) obj.Results[#obj.Results + 1] = result return result end end local p = obj.Functions[var] if p then return p end return outer_env[var] end obj.FunctionMeta = { __index = indexfunc, __newindex = error } obj.FunctionEnv = setmetatable({}, obj.FunctionMeta) for name, fn in pairs(functions) do obj.Functions[name] = setfenv(fn, obj.FunctionEnv) end obj.Functions["Default"] = function(default_obj) obj.DefaultTargets[#obj.DefaultTargets + 1] = default_obj end obj.Functions["Always"] = function(always_obj) obj.AlwaysTargets[#obj.AlwaysTargets + 1] = always_obj end current = setmetatable(obj, _decl_meta) return current end function add_function(name, fn) assert(name and fn) functions[name] = fn end function _decl_meta:parse_rec(data) local chunk if type(data) == "table" then for _, gen in ipairs(data) do parse_rec(self, gen) end return elseif type(data) == "function" then chunk = data elseif type(data) == "string" then chunk = assert(loadfile(data)) else croak("unknown type %s for unit_generator %q", type(data), tostring(data)) end setfenv(chunk, self.FunctionEnv) chunk() end function parse(data) p = new_parser() current = p p:parse_rec(data) current = nil return p.Results, p.DefaultTargets, p.AlwaysTargets end
-- Copyright 2010 Andreas Fredriksson -- -- This file is part of Tundra. -- -- Tundra 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 3 of the License, or -- (at your option) any later version. -- -- Tundra 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 Tundra. If not, see <http://www.gnu.org/licenses/>. module(..., package.seeall) local nodegen = require "tundra.nodegen" local functions = {} local _decl_meta = {} _decl_meta.__index = _decl_meta local current = nil local function new_parser() local obj = { Functions = {}, Results = {}, DefaultTargets = {}, AlwaysTargets = {}, } local outer_env = _G local iseval = nodegen.is_evaluator local function indexfunc(tab, var) if iseval(var) then -- Return an anonymous function such that -- the code "Foo { ... }" will result in a call to -- "nodegen.evaluate('Foo', { ... })" return function (data) local result = nodegen.evaluate(var, data) obj.Results[#obj.Results + 1] = result return result end end local p = obj.Functions[var] if p then return p end return outer_env[var] end obj.FunctionMeta = { __index = indexfunc, __newindex = error } obj.FunctionEnv = setmetatable({}, obj.FunctionMeta) for name, fn in pairs(functions) do obj.Functions[name] = setfenv(fn, obj.FunctionEnv) end obj.Functions["Default"] = function(default_obj) obj.DefaultTargets[#obj.DefaultTargets + 1] = default_obj end obj.Functions["Always"] = function(always_obj) obj.AlwaysTargets[#obj.AlwaysTargets + 1] = always_obj end current = setmetatable(obj, _decl_meta) return current end function add_function(name, fn) assert(name and fn) functions[name] = fn if current then -- require called from within unit script current.Functions[name] = setfenv(fn, current.FunctionEnv) end end function _decl_meta:parse_rec(data) local chunk if type(data) == "table" then for _, gen in ipairs(data) do parse_rec(self, gen) end return elseif type(data) == "function" then chunk = data elseif type(data) == "string" then chunk = assert(loadfile(data)) else croak("unknown type %s for unit_generator %q", type(data), tostring(data)) end setfenv(chunk, self.FunctionEnv) chunk() end function parse(data) p = new_parser() current = p p:parse_rec(data) current = nil return p.Results, p.DefaultTargets, p.AlwaysTargets end
Fixed syntax requires in Units didn't work.
Fixed syntax requires in Units didn't work.
Lua
mit
deplinenoise/tundra,bmharper/tundra,deplinenoise/tundra,bmharper/tundra,bmharper/tundra,bmharper/tundra,deplinenoise/tundra
c4d09e188db1928e7dbd64827249d91c88cb885d
testserver/item/tree.lua
testserver/item/tree.lua
-- Tree Script -- Envi require("base.common") require("content.tree") module("item.tree", package.seeall) -- UPDATE common SET com_script='item.tree' WHERE com_itemid IN (308, 586, 1804, 1807, 1808, 1809, 1817); TreeListGerman = { "PLACEHOLDER.", }; TreeListEnglish = { "PLACEHOLDER.", }; function LookAtItemIdent(User,Item) local test = "no value"; if (first==nil) then content.tree.InitTree() first=1; end -- fetching local references local signTextDe = content.tree.signTextDe; local signTextEn = content.tree.signTextEn; local signCoo = content.tree.signCoo; local signItemId = content.tree.signItemId; local signPerception = content.tree.signPerception; found = false; UserPer = User:increaseAttrib("perception",0); tablePosition = Item.pos.x .. Item.pos.y .. Item.pos.z; if signCoo ~= nil then if (signCoo[tablePosition] ~= nil) then for i, signpos in pairs(signCoo[tablePosition]) do if (Item.pos == signpos) then if (UserPer >= signPerception[tablePosition][i]) then found = true; world:itemInform(User,Item,base.common.GetNLS(User,string.gsub(signTextDe[tablePosition][i],"currentChar",User.name),string.gsub(signTextEn[tablePosition][i],"currentChar",User.name))); test = signTextDe[tablePosition][i]; else found = true; world:itemInform(User,Item,base.common.GetNLS(User,"~Du erkennst, dass hier etwas ist, kannst es aber nicht entziffern, da du zu blind bist.~","~You recognise something, but you cannot read it, because you are too blind.~")); end end end end end --[[local outText = checkNoobiaSigns(User,Item.pos); if outText and not found then world:itemInform(User,Item,outText); found = true; end ]] if not found then world:itemInform(User,Item,world:getItemName(Item.id,User:getPlayerLanguage())); end --[[if not found then val = ((Item.pos.x + Item.pos.y + Item.pos.z) % table.getn(TreeListGerman))+1; world:itemInform( User, Item, base.common.GetNLS(User, TreeListGerman[val], TreeListEnglish[val]) ); end]]-- -- User:inform("in LookAtItem of base_wegweiser.lua"); --User:inform(test); end --[[ LookAtItemIdent identity of LookAtItem ]] LookAtItem = LookAtItemIdent;
-- Tree Script -- Envi require("base.common") require("base.lookat") require("content.tree") module("item.tree", package.seeall) -- UPDATE common SET com_script='item.tree' WHERE com_itemid IN (308, 586, 1804, 1807, 1808, 1809, 1817); TreeListGerman = { "PLACEHOLDER.", }; TreeListEnglish = { "PLACEHOLDER.", }; function LookAtItemIdent(User,Item) local test = "no value"; if (first==nil) then content.tree.InitTree() first=1; end -- fetching local references local signTextDe = content.tree.signTextDe; local signTextEn = content.tree.signTextEn; local signCoo = content.tree.signCoo; local signItemId = content.tree.signItemId; local signPerception = content.tree.signPerception; local lookAt = base.lookat.GenerateLookAt(User, Item) UserPer = User:increaseAttrib("perception",0); tablePosition = Item.pos.x .. Item.pos.y .. Item.pos.z; if signCoo ~= nil then if (signCoo[tablePosition] ~= nil) then for i, signpos in pairs(signCoo[tablePosition]) do if (Item.pos == signpos) then if (UserPer >= signPerception[tablePosition][i]) then lookAt.description = base.common.GetNLS(User,string.gsub(signTextDe[tablePosition][i],"currentChar",User.name),string.gsub(signTextEn[tablePosition][i],"currentChar",User.name)) test = signTextDe[tablePosition][i]; else lookAt.description = base.common.GetNLS(User,"Du erkennst, dass hier etwas ist, kannst es aber nicht entziffern, da du zu blind bist.","You recognise something, but you cannot read it, because you are too blind.") end end end end end --[[local outText = checkNoobiaSigns(User,Item.pos); if outText and not found then world:itemInform(User,Item,outText); found = true; end ]] world:itemInform(User, Item, lookAt) --[[if not found then val = ((Item.pos.x + Item.pos.y + Item.pos.z) % table.getn(TreeListGerman))+1; world:itemInform( User, Item, base.common.GetNLS(User, TreeListGerman[val], TreeListEnglish[val]) ); end]]-- -- User:inform("in LookAtItem of base_wegweiser.lua"); --User:inform(test); end --[[ LookAtItemIdent identity of LookAtItem ]] LookAtItem = LookAtItemIdent;
Fix tree lookat
Fix tree lookat
Lua
agpl-3.0
vilarion/Illarion-Content,LaFamiglia/Illarion-Content,Baylamon/Illarion-Content,KayMD/Illarion-Content,Illarion-eV/Illarion-Content
cbdd67e64c18c2c9ee18f1ebc3393c2ca6edf4ef
Shilke2D/Utils/Shape.lua
Shilke2D/Utils/Shape.lua
--[[--- Basic geometry classes with draw and intersection helpers. Shape is an abstract base class, Circle and Rect are concrete classes --]] Shape = class() function Shape:init() end ---returns a clone of the current shape function Shape:clone() return table.copy(self) end ---abstract method function Shape:copy(s) error("override me") end ---abstract method function Shape:containsPoint(x,y) error("override me") end ---abstract intersection method between 2 shapes function Shape:intersects(s2) error("override me") end ---abstract draw method function Shape:draw() error("override me") end ---Checks intersection of two rectangles --@param r1 Rect --@param r2 Rect --@return bool local function int_rect2rect(r1,r2) if r1.x > (r2.x + r2.w) or (r1.x + r1.w) < r2.x then return false end if r1.y > (r2.y + r2.h) or (r1.y + r1.h) < r2.y then return false end return true end ---Checks intersection of two circles --@param c1 Circle --@param c2 Circle --@return bool local function int_circle2circle(c1,c2) if (c1.r+c2.r)^2 < (c1.x-c2.x)^2 +(c1.y-c2.y)^2 then return false end return true end ---Checks intersection of a rectangle and a circle --@param r rect --@param c Circle --@return bool local function int_rect2circle(r,c) local halfw = r.w/2 local halfh = r.h/2 local circleDist = vec2(math.abs(c.x-r.x-halfw), math.abs(c.y-r.y-halfh)) if circleDist.x <= halfw then return true end if circleDist.y <= halfh then return true end if circleDist.x > (halfw + c.r) then return false end if circleDist.y > (halfh + c.r) then return false end local cornerDist_sq = (circleDist.x - halfw)^2 + (circleDist.y - halfh)^2 local r2 = c.r^2 return cornerDist_sq <= r2 end --Rect class Rect = class(Shape) ---returns a string describing rect components Rect.__tostring = function(r) return string.format("[x=%f, y=%f, w=%f, h=%f]", r.x,r.y,r.w,r.h) end ---Constructor --@param x default 0 --@param y default 0 --@param w default 0 --@param h default 0 function Rect:init(x,y,w,h) Shape.init(self) self.x = x or 0 self.y = y or 0 self.w = w or 0 self.h = h or 0 end --[[--- assign rect values @param x @param y @param w @param h @return Rect self --]] function Rect:set(x,y,w,h) self.x = x self.y = y self.w = w self.h = h return self end ---Updates itself copying another rect --@param r the rect to be copied --@return self function Rect:copy(r) self.x = r.x self.y = r.y self.w = r.w self.h = r.h return self end ---Returns the center of the rect --@return x --@return y function Rect:getCenter() return self.x + self.w/2, self.y + self.h/2 end ---Checks if a point is inside the rect --@param x --@param y --@return bool function Rect:containsPoint(x,y) if x > self.x and y > self.y then if x < (self.x + self.w) and y < (self.y + self.h) then return true end end return false end ---Checks intersection with other Shapes (rect or circle) --@param s2 the other shape --@return bool function Rect:intersects(s2) if s2:is_a(Rect) then return int_rect2rect(self,s2) elseif s2:is_a(Circle) then return int_rect2circle(self,s2) end end ---Returns the intersection area between two rects --@tparam Rect r2 the second rect --@tparam[opt=nil] Rect helperRect if provided is filled and used as return object --@treturn Rect. if the intersection is nil it returns a defaul ---Rect with each component at 0 function Rect:intersection(r2, helperRect) local res = nil if int_rect2rect(self,r2) then res = helperRect or Rect() res.x = math.max(r2.x,self.x) res.y = math.max(r2.y,self.y) local x2 = math.min(r2.x + r2.w,self.x + self.w) local y2 = math.min(r2.y + r2.h,self.y + self.h) res.w = x2 - res.x res.h = y2 - res.y end return res end ---Wraps the MOAIDraw.drawRect call function Rect:draw() MOAIDraw.drawRect(self.x, self.y, self.x + self.w, self.y+self.h) end --Circle class Circle = class(Shape) ---returns a string describing circle components Circle.__tostring = function(c) return string.format("[x=%f, y=%f, r=%f]",c.x,c.y,c.r) end ---Constructor --@param x center x of the circle --@param y center y of the circle --@param r radius of the circle function Circle:init(x,y,r) self.x = x or 0 self.y = y or 0 self.r = r or 0 end --[[--- assign circle values @param x @param y @param r @return Circle self --]] function Circle:set(x,y,r) self.x = x self.y = y self.r = r return self end ---Updates itself copying another circle --@param c the circle to be copied --@return self function Circle:copy(c) self.x = c.x self.y = c.y self.r = c.r return self end ---Checks if a point is inside the circle --@param x --@param y --@return bool function Circle:containsPoint(x,y) if x > (self.x - self.r) and x < (self.x + self.r) then if y > (self.y - self.r) and y < (self.y + self.r) then return true end end return false end ---Checks intersection with other Shapes (rect or circle) --@param s2 the other shape --@return bool function Circle:intersects(s2) if s2:is_a(Circle) then return int_circle2circle(self,s2) elseif s2:is_a(Rect) then return int_rect2circle(s2,self) end end ---Wraps the MOAIDraw.drawCircle call function Circle:draw() MOAIDraw.drawCircle(self.x, self.y, self.r) end
--[[--- Basic geometry classes with draw and intersection helpers. Shape is an abstract base class, Circle and Rect are concrete classes --]] Shape = class() function Shape:init() end ---returns a clone of the current shape function Shape:clone() return table.copy(self) end ---abstract method function Shape:copy(s) error("override me") end ---abstract method function Shape:containsPoint(x,y) error("override me") end ---abstract intersection method between 2 shapes function Shape:intersects(s2) error("override me") end ---abstract draw method function Shape:draw() error("override me") end ---Checks intersection of two rectangles --@param r1 Rect --@param r2 Rect --@return bool local function int_rect2rect(r1,r2) if r1.x > (r2.x + r2.w) or (r1.x + r1.w) < r2.x then return false end if r1.y > (r2.y + r2.h) or (r1.y + r1.h) < r2.y then return false end return true end ---Checks intersection of two circles --@param c1 Circle --@param c2 Circle --@return bool local function int_circle2circle(c1,c2) if (c1.r+c2.r)^2 < (c1.x-c2.x)^2 +(c1.y-c2.y)^2 then return false end return true end ---Checks intersection of a rectangle and a circle --@param r rect --@param c Circle --@return bool local function int_rect2circle(r,c) local halfw = r.w/2 local halfh = r.h/2 local circleDist = vec2(math.abs(c.x-r.x-halfw), math.abs(c.y-r.y-halfh)) if circleDist.x <= halfw then return true end if circleDist.y <= halfh then return true end if circleDist.x > (halfw + c.r) then return false end if circleDist.y > (halfh + c.r) then return false end local cornerDist_sq = (circleDist.x - halfw)^2 + (circleDist.y - halfh)^2 local r2 = c.r^2 return cornerDist_sq <= r2 end --Rect class Rect = class(Shape) ---returns a string describing rect components Rect.__tostring = function(r) return string.format("[x=%f, y=%f, w=%f, h=%f]", r.x,r.y,r.w,r.h) end ---Constructor --@param x default 0 --@param y default 0 --@param w default 0 --@param h default 0 function Rect:init(x,y,w,h) Shape.init(self) self.x = x or 0 self.y = y or 0 self.w = w or 0 self.h = h or 0 end --[[--- assign rect values @param x @param y @param w @param h @return Rect self --]] function Rect:set(x,y,w,h) self.x = x self.y = y self.w = w self.h = h return self end ---Updates itself copying another rect --@param r the rect to be copied --@return self function Rect:copy(r) self.x = r.x self.y = r.y self.w = r.w self.h = r.h return self end ---Returns the center of the rect --@return x --@return y function Rect:getCenter() return self.x + self.w/2, self.y + self.h/2 end ---Checks if a point is inside the rect --@param x --@param y --@return bool function Rect:containsPoint(x,y) if x > self.x and y > self.y then if x < (self.x + self.w) and y < (self.y + self.h) then return true end end return false end ---Checks intersection with other Shapes (rect or circle) --@param s2 the other shape --@return bool function Rect:intersects(s2) if s2:is_a(Rect) then return int_rect2rect(self,s2) elseif s2:is_a(Circle) then return int_rect2circle(self,s2) end end ---Returns the intersection area between two rects --@tparam Rect r2 the second rect --@tparam[opt=nil] Rect helperRect if provided is filled and used as return object --@treturn Rect. if the intersection is nil it returns a defaul ---Rect with each component at 0 function Rect:intersection(r2, helperRect) res = helperRect or Rect() if int_rect2rect(self,r2) then res.x = math.max(r2.x,self.x) res.y = math.max(r2.y,self.y) local x2 = math.min(r2.x + r2.w,self.x + self.w) local y2 = math.min(r2.y + r2.h,self.y + self.h) res.w = x2 - res.x res.h = y2 - res.y else res:set(0,0,0,0) end return res end ---Wraps the MOAIDraw.drawRect call function Rect:draw() MOAIDraw.drawRect(self.x, self.y, self.x + self.w, self.y+self.h) end --Circle class Circle = class(Shape) ---returns a string describing circle components Circle.__tostring = function(c) return string.format("[x=%f, y=%f, r=%f]",c.x,c.y,c.r) end ---Constructor --@param x center x of the circle --@param y center y of the circle --@param r radius of the circle function Circle:init(x,y,r) self.x = x or 0 self.y = y or 0 self.r = r or 0 end --[[--- assign circle values @param x @param y @param r @return Circle self --]] function Circle:set(x,y,r) self.x = x self.y = y self.r = r return self end ---Updates itself copying another circle --@param c the circle to be copied --@return self function Circle:copy(c) self.x = c.x self.y = c.y self.r = c.r return self end ---Checks if a point is inside the circle --@param x --@param y --@return bool function Circle:containsPoint(x,y) if x > (self.x - self.r) and x < (self.x + self.r) then if y > (self.y - self.r) and y < (self.y + self.r) then return true end end return false end ---Checks intersection with other Shapes (rect or circle) --@param s2 the other shape --@return bool function Circle:intersects(s2) if s2:is_a(Circle) then return int_circle2circle(self,s2) elseif s2:is_a(Rect) then return int_rect2circle(s2,self) end end ---Wraps the MOAIDraw.drawCircle call function Circle:draw() MOAIDraw.drawCircle(self.x, self.y, self.r) end
fix on Rect:intersection()
fix on Rect:intersection()
Lua
mit
Shrike78/Shilke2D
aa820db7e456f8d31b87d68dd53978dcf5585d9e
lua/wire/wire_paths.lua
lua/wire/wire_paths.lua
-- wire_paths.lua -- -- This file implements syncing of wire paths, which are the visual -- component of wires. -- -- Conceptually, a wire path has a material, a color, and a non-zero width, as -- well as as a non-empty polyline along the wire. (Each point in the line -- has both a parent entity, and a local offset from that entity.) -- if not WireLib then return end WireLib.Paths = {} local transmit_queues = setmetatable({}, { __index = function(t,p) t[p] = {} return t[p] end }) if CLIENT then net.Receive("WireLib.Paths.TransmitPath", function(length) local path = { Path = {} } path.Entity = net.ReadEntity() if not path.Entity:IsValid() then return end path.Name = net.ReadString() path.Width = net.ReadFloat() if path.Width<=0 then if path.Entity.WirePaths then path.Entity.WirePaths[path.Name] = nil if not next(path.Entity.WirePaths) then path.Entity.WirePaths = nil end end return end path.StartPos = net.ReadVector() path.Material = net.ReadString() path.Color = net.ReadColor() local num_points = net.ReadUInt(15) for i = 1, num_points do path.Path[i] = { Entity = net.ReadEntity(), Pos = net.ReadVector() } end if path.Entity.WirePaths == nil then path.Entity.WirePaths = {} end path.Entity.WirePaths[path.Name] = path end) hook.Add("NetworkEntityCreated", "WireLib.Paths.NetworkEntityCreated", function(ent) if ent.Inputs then net.Start("WireLib.Paths.RequestPaths") net.WriteEntity(ent) net.SendToServer() end end) return end util.AddNetworkString("WireLib.Paths.RequestPaths") util.AddNetworkString("WireLib.Paths.TransmitPath") net.Receive("WireLib.Paths.RequestPaths", function(length, ply) local ent = net.ReadEntity() if ent:IsValid() and ent.Inputs then for name, input in pairs(ent.Inputs) do if input.Src then WireLib.Paths.Add(path, ply) end end end end) local function TransmitPath(input) local color = input.Color net.WriteEntity(input.Entity) net.WriteString(input.Name) if not input.Src or input.Width<=0 then net.WriteFloat(0) return end net.WriteFloat(input.Width) net.WriteVector(input.StartPos) net.WriteString(input.Material) net.WriteColor(Color(color.r or 255, color.g or 255, color.b or 255, color.a or 255)) net.WriteUInt(#input.Path, 15) for _, point in ipairs(input.Path) do net.WriteEntity(point.Entity) net.WriteVector(point.Pos) end end local function ProcessQueue() for ply, queue in pairs(transmit_queues) do if not ply:IsValid() then transmit_queues[ply] = nil continue end if next(queue) then net.Start("WireLib.Paths.TransmitPath") while queue[1] and net.BytesWritten() < 63 * 1024 do TransmitPath(queue[1]) table.remove(queue, 1) end net.Send(ply) else transmit_queues[ply] = nil end end if not next(transmit_queues) then timer.Remove("WireLib.Paths.ProcessQueue") end end -- Add a path to every player's transmit queue function WireLib.Paths.Add(input, ply) if ply then table.insert(transmit_queues[ply], input) else for _, player in pairs(player.GetAll()) do table.insert(transmit_queues[player], input) end end if not timer.Exists("WireLib.Paths.ProcessQueue") then timer.Create("WireLib.Paths.ProcessQueue", 0.2, 0, ProcessQueue) end end
-- wire_paths.lua -- -- This file implements syncing of wire paths, which are the visual -- component of wires. -- -- Conceptually, a wire path has a material, a color, and a non-zero width, as -- well as as a non-empty polyline along the wire. (Each point in the line -- has both a parent entity, and a local offset from that entity.) -- if not WireLib then return end WireLib.Paths = {} local transmit_queues = setmetatable({}, { __index = function(t,p) t[p] = {} return t[p] end }) if CLIENT then net.Receive("WireLib.Paths.TransmitPath", function(length) local path = { Path = {} } path.Entity = net.ReadEntity() if not path.Entity:IsValid() then return end path.Name = net.ReadString() path.Width = net.ReadFloat() if path.Width<=0 then if path.Entity.WirePaths then path.Entity.WirePaths[path.Name] = nil if not next(path.Entity.WirePaths) then path.Entity.WirePaths = nil end end return end path.StartPos = net.ReadVector() path.Material = net.ReadString() path.Color = net.ReadColor() local num_points = net.ReadUInt(16) for i = 1, num_points do path.Path[i] = { Entity = net.ReadEntity(), Pos = net.ReadVector() } end if path.Entity.WirePaths == nil then path.Entity.WirePaths = {} end path.Entity.WirePaths[path.Name] = path end) hook.Add("NetworkEntityCreated", "WireLib.Paths.NetworkEntityCreated", function(ent) if ent.Inputs then net.Start("WireLib.Paths.RequestPaths") net.WriteEntity(ent) net.SendToServer() end end) return end util.AddNetworkString("WireLib.Paths.RequestPaths") util.AddNetworkString("WireLib.Paths.TransmitPath") net.Receive("WireLib.Paths.RequestPaths", function(length, ply) local ent = net.ReadEntity() if ent:IsValid() and ent.Inputs then for name, input in pairs(ent.Inputs) do if input.Src then WireLib.Paths.Add(path, ply) end end end end) local function TransmitPath(input, ply) net.Start("WireLib.Paths.TransmitPath") local color = input.Color net.WriteEntity(input.Entity) net.WriteString(input.Name) if not input.Src or input.Width<=0 then net.WriteFloat(0) return end net.WriteFloat(input.Width) net.WriteVector(input.StartPos) net.WriteString(input.Material) net.WriteColor(Color(color.r or 255, color.g or 255, color.b or 255, color.a or 255)) net.WriteUInt(#input.Path, 16) for _, point in ipairs(input.Path) do net.WriteEntity(point.Entity) net.WriteVector(point.Pos) end net.Send(ply) end local function ProcessQueue() for ply, queue in pairs(transmit_queues) do if not ply:IsValid() then transmit_queues[ply] = nil continue end local nextinqueue = table.remove(queue, 1) if nextinqueue then TransmitPath(nextinqueue, ply) else transmit_queues[ply] = nil end end if not next(transmit_queues) then timer.Remove("WireLib.Paths.ProcessQueue") end end -- Add a path to every player's transmit queue function WireLib.Paths.Add(input, ply) if ply then table.insert(transmit_queues[ply], input) else for _, player in pairs(player.GetAll()) do table.insert(transmit_queues[player], input) end end if not timer.Exists("WireLib.Paths.ProcessQueue") then timer.Create("WireLib.Paths.ProcessQueue", 0, 0, ProcessQueue) end end
Fix path networking
Fix path networking
Lua
apache-2.0
wiremod/wire,dvdvideo1234/wire,NezzKryptic/Wire,garrysmodlua/wire,Grocel/wire,sammyt291/wire
b52cf97960686553e796be3e0459c38d365c9e5f
src/elasticsearch/helpers.lua
src/elasticsearch/helpers.lua
--- The helper module -- @module helper -- @author Dhaval Kapil ------------------------------------------------------------------------------- -- Declaring module ------------------------------------------------------------------------------- local helpers = {} ------------------------------------------------------------------------------- -- Function to reindex -- -- @param sourceClient The source client -- @param sourceIndex The source index -- @param targetIndex The target index -- @param query Search query to filter data to be reindexed -- @param targetClient The target client -- @param scroll Specify how long a consistent view of the index -- should be maintained for scrolled search ------------------------------------------------------------------------------- function helpers.reindex(sourceClient, sourceIndex, targetIndex, query, targetClient, scroll) -- Setting up query, target_client and scroll query = query or {} targetClient = targetClient or sourceClient scroll = scroll or "1m" -- Performing a search query local data, err = sourceClient:search{ index = sourceIndex, search_type = "scan", scroll = scroll, body = query } -- Checking for error in search query if data == nil then return nil, err end -- Performing a repetitive scroll queries while true do local scrollId = data["_scroll_id"] data, err = sourceClient:scroll{ scroll_id = scrollId, scroll = scroll } -- Checking for error in scroll query if data == nil then print(err) return nil, err end -- If no more hits then break if #data["hits"]["hits"] == 0 then break end -- Bulk indexing the documents local bulkBody = {} for _, item in pairs(data["hits"]["hits"]) do table.insert(bulkBody, { index = { _index = targetIndex, _type = item["_type"], _id = item["_id"] } }) table.insert(bulkBody, item["_source"]) end data, err = targetClient:bulk{ index = targetIndex, body = bulkBody } -- Checking for error in bulk request if data == nil then return nil, err end end end return helpers
--- The helper module -- @module helper -- @author Dhaval Kapil ------------------------------------------------------------------------------- -- Declaring module ------------------------------------------------------------------------------- local helpers = {} ------------------------------------------------------------------------------- -- Reindex all documents from one index to another index that satisfy -- a given query -- -- @param sourceClient The source client -- @param sourceIndex The source index -- @param targetIndex The target index -- @param query Search query to filter data to be reindexed -- query is for request body search -- @param targetClient The target client -- @param scroll Specify how long a consistent view of the index -- should be maintained for scrolled search -- @param scanParams Additional params passed to scan -- @param bulkParams Additional params passed to bulk -- -- @return boolean true if success, otherwise false ------------------------------------------------------------------------------- function helpers.reindex(sourceClient, sourceIndex, targetIndex, query, targetClient, scroll, scanParams, bulkParams) -- Setting up default parameters query = query or {} targetClient = targetClient or sourceClient scroll = scroll or "1m" scanParams = scanParams or {} bulkParams = bulkParams or {} -- Performing a search query scanParams.index = sourceIndex scanParams.search_type = "scan" scanParams.scroll = scroll scanParams.body = query local data, err = sourceClient:search(scanParams) -- Checking for error in search query if data == nil then return false, err end local scrollId = data["_scroll_id"] -- Performing a repetitive scroll queries while true do data, err = sourceClient:scroll{ scroll_id = scrollId, scroll = scroll } -- Checking for error in scroll query if data == nil then return false, err end -- If no more hits then break if #data["hits"]["hits"] == 0 then break end scrollId = data["_scroll_id"] -- Bulk indexing the documents local bulkBody = {} for _, item in pairs(data["hits"]["hits"]) do table.insert(bulkBody, { index = { _index = targetIndex, _type = item["_type"], _id = item["_id"] } }) table.insert(bulkBody, item["_source"]) end bulkParams.body = bulkBody data, err = targetClient:bulk(bulkParams) -- Checking for error in bulk request if data == nil then return false, err end end return true end return helpers
Fixed helpers.reindex and added more options
Fixed helpers.reindex and added more options
Lua
mit
DhavalKapil/elasticsearch-lua
bc3ecd731e87d76fb1d1e4fac9db525f7fd3451b
mod_xinerama/mod_xinerama.lua
mod_xinerama/mod_xinerama.lua
-- Ion xinerama module - lua setup -- -- by Tomas Ebenlendr <ebik@ucw.cz> -- -- 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -- -- This is a slight abuse of the package.loaded variable perhaps, but -- library-like packages should handle checking if they're loaded instead of -- confusing the user with require/include differences. if package.loaded["mod_xinerama"] then return end if not ioncore.load_module("mod_xinerama") then return end local mod_xinerama=_G["mod_xinerama"] assert(mod_xinerama) -- Helper functions {{{ -- }}} -- Mark ourselves loaded. package.loaded["mod_xinerama"]=true -- Load configuration file dopath('cfg_xinerama', true) -- FIXME this function has to be called only once! local screens = mod_xinerama.query_screens(); if screens then mod_xinerama.setup_screens_once(screens); end
-- Ion xinerama module - lua setup -- -- by Tomas Ebenlendr <ebik@ucw.cz> -- -- 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -- -- This is a slight abuse of the package.loaded variable perhaps, but -- library-like packages should handle checking if they're loaded instead of -- confusing the user with require/include differences. if package.loaded["mod_xinerama"] then return end if not ioncore.load_module("mod_xinerama") then return end local mod_xinerama=_G["mod_xinerama"] assert(mod_xinerama) -- Helper functions {{{ -- }}} -- Mark ourselves loaded. package.loaded["mod_xinerama"]=true -- Load configuration file dopath('cfg_xinerama', true) local screens = mod_xinerama.query_screens(); if screens then mod_xinerama.setup_screens_once(screens); end
removed partially resolved FIXME
removed partially resolved FIXME
Lua
lgpl-2.1
anoduck/notion,anoduck/notion,dkogan/notion.xfttest,dkogan/notion,p5n/notion,knixeur/notion,dkogan/notion,knixeur/notion,knixeur/notion,dkogan/notion,anoduck/notion,neg-serg/notion,knixeur/notion,dkogan/notion,p5n/notion,p5n/notion,anoduck/notion,dkogan/notion.xfttest,knixeur/notion,raboof/notion,neg-serg/notion,neg-serg/notion,raboof/notion,raboof/notion,dkogan/notion.xfttest,dkogan/notion.xfttest,p5n/notion,anoduck/notion,raboof/notion,p5n/notion,dkogan/notion,neg-serg/notion
e66c357bfe5c411baff191e910d7336db09fb7de
src/cosy/lang/view/update.lua
src/cosy/lang/view/update.lua
local cosy = require "cosy.lang.cosy" local raw = require "cosy.lang.data" . raw local tags = require "cosy.lang.tags" local type = require "cosy.util.type" local map = require "cosy.lang.iterators" . map local serpent = require "serpent" local NAME = tags.NAME local PARENTS = tags.PARENTS local UPDATES = tags.UPDATES UPDATES.persistent = false local function path_to (data, key) local path if raw (data) == cosy then path = { cosy } elseif type (data) . string then path = { data } elseif type (data) . number then path = { data } elseif type (data) . tag then path = { "cosy", "tags", data [NAME] } else local parents = data [PARENTS] if not parents then path = { raw (data), new = true } else -- Select one parent, ask path to it for p, keys in map (parents) do for key in pairs (keys) do path = path_to (p, key) end end end end if not key then return path end -- Add key: if type (key) . table then path [#path + 1] = path_to (key) else for _, p in ipairs (path_to (key)) do path [#path + 1] = p end end return path end local function path_for (path) if #path == 1 and path.new then return serpent.dump (path [1]) end local result for _, p in ipairs (path) do if p == cosy then result = "cosy" elseif type (p) . string then if result then result = result .. " ['" .. p .. "']" else result = "'" .. p .. "'" end elseif type (p) . number then if result then result = result .. " [" .. tostring (p) .. "]" else result = tostring (p) end elseif type (p) . table then result = result .. " [" .. path_for (p) .. "]" end end return result end function handler (data, key) if type (key) . tag and not key.persistent then return end coroutine.yield () local lhs_path = path_to (data, key) local lhs = path_for (lhs_path) local rhs = path_for (path_to (data [key])) if lhs_path [1] == cosy and #lhs_path > 2 then local model = cosy [lhs_path [2]] model.updates = model.updates or {} model.updates [#(model.updates) + 1] = lhs .. " = " .. rhs end end return handler
local cosy = require "cosy.lang.cosy" local raw = require "cosy.lang.data" . raw local tags = require "cosy.lang.tags" local type = require "cosy.util.type" local map = require "cosy.lang.iterators" . map local is_empty = require "cosy.lang.iterators" . is_empty local serpent = require "serpent" local NAME = tags.NAME local PARENTS = tags.PARENTS local UPDATES = tags.UPDATES local function path_to (data, key) local path if raw (data) == raw (cosy) then path = { cosy } elseif type (data) . string then path = { data } elseif type (data) . number then path = { data } elseif type (data) . boolean then path = { data } elseif type (data) . tag then path = { cosy, "tags", data [NAME] } else local parents = data [PARENTS] if not parents then path = { data, new = true } else -- Select one parent, ask path to it for p, keys in map (parents) do for key in pairs (keys) do path = path_to (p, key) end end end end if not key then return path end -- Add key: if type (key) . table then path [#path + 1] = path_to (key) else for _, p in ipairs (path_to (key)) do path [#path + 1] = p end end return path end local function path_for (path) if #path == 1 and path.new then return "{}" end local result for _, p in ipairs (path) do if p == raw (cosy) then result = "cosy" elseif type (p) . string then if result then local i, j = string.find (p, "[_%a][_%w]*") if i == 1 and j == #p then result = result .. "." .. p else result = result .. " ['" .. p .. "']" end else result = "'" .. p .. "'" end elseif type (p) . number then if result then result = result .. " [" .. tostring (p) .. "]" else result = tostring (p) end elseif type (p) . boolean then if result then result = result .. " [" .. tostring (p) .. "]" else result = tostring (p) end elseif type (p) . table then result = result .. " [" .. path_for (p) .. "]" end end return result end function handler (data, key) if type (key) . tag and not key.persistent then return end local raw_data = raw (data) local raw_key = raw (key) -- local old_value = raw (data [key]) if type (old_value) . table and old_value [PARENTS] then local old_parents = old_value [PARENTS] local ks = old_parents [raw_data] or {} ks [raw_key] = nil if is_empty (ks) then old_parents [raw_data] = nil end if is_empty (old_parents) then old_value [PARENTS] = nil else old_value [PARENTS] = old_parents end end -- coroutine.yield () local lhs_path = path_to (data, key) local lhs = path_for (lhs_path) local rhs_path = path_to (data [key]) local rhs = path_for (rhs_path) if lhs_path [1] == raw (cosy) and #lhs_path > 2 then local model = cosy [lhs_path [2]] model [UPDATES] = model [UPDATES] or {} model [UPDATES] [#(model [UPDATES]) + 1] = lhs .. " = " .. rhs end -- local new_value = data [key] if type (new_value) . table then local new_parents = new_value [PARENTS] or {} if not new_parents [raw_data] then new_parents [raw_data] = {} end new_parents [raw_data] [key] = true new_value [PARENTS] = new_parents end -- if rhs_path.new then local r = data [key] for k, v in map (r) do r [k] = v end end end return handler
Fix update.
Fix update.
Lua
mit
CosyVerif/library,CosyVerif/library,CosyVerif/library
d2df8d20aa3d8cf815649e6fd8ef23e7a381be30
lua/entities/gmod_wire_lever.lua
lua/entities/gmod_wire_lever.lua
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Analog Lever" ENT.WireDebugName = "Lever" if CLIENT then return end -- No more client function ENT:Initialize() self:SetModel("models/props_wasteland/tram_lever01.mdl") self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self:SetUseType( SIMPLE_USE ) self.EntToOutput = NULL self.Ang = 0 self.Value = 0 self:Setup(0, 1) self.Inputs = WireLib.CreateInputs(self, {"SetValue", "Min", "Max"}) self.Outputs = WireLib.CreateOutputs(self, {"Value", "Entity [ENTITY]"}) end function ENT:Setup(min, max) if min then self.Min = min end if max then self.Max = max end end function ENT:TriggerInput(iname, value) if iname == "SetValue" then self.Ang = (math.Clamp(value, self.Min, self.Max) - self.Min)/(self.Max - self.Min) * 90 - 45 elseif (iname == "Min") then self.Min = value elseif (iname == "Max") then self.Max = value end end function ENT:Use( ply ) if not IsValid(ply) or not ply:IsPlayer() or IsValid(self.User) then return end self.User = ply WireLib.TriggerOutput( self, "Entity", ply) end function ENT:Think() self.BaseClass.Think(self) if not IsValid(self.BaseEnt) then return end if IsValid(self.User) then local dist = self.User:GetShootPos():Distance(self.BaseEnt:GetPos()) if dist < 160 and (self.User:KeyDown(IN_USE) or self.User:KeyDown(IN_ATTACK)) then local TargPos = self.User:GetShootPos() + self.User:GetAimVector() * dist local distMax = TargPos:Distance(self.BaseEnt:GetPos() + self.BaseEnt:GetForward() * 30) local distMin = TargPos:Distance(self.BaseEnt:GetPos() + self.BaseEnt:GetForward() * -30) local FPos = (distMax - distMin) * 0.5 distMax = TargPos:Distance(self.BaseEnt:GetPos()) distMin = TargPos:Distance(self.BaseEnt:GetPos() + self.BaseEnt:GetUp() * 40) local HPos = 20 - ((distMin - distMax) * 0.5) self.Ang = math.Clamp( math.deg( math.atan2( HPos, FPos ) ) - 90, -45, 45 ) else self.User = NULL WireLib.TriggerOutput( self, "Entity", NULL) end end self.Value = Lerp((self.Ang + 45) / 90, self.Min, self.Max) Wire_TriggerOutput(self, "Value", self.Value) local NAng = self.BaseEnt:GetAngles() NAng:RotateAroundAxis( NAng:Right(), -self.Ang ) local RAng = self.BaseEnt:WorldToLocalAngles(NAng) self:SetLocalPos( RAng:Up() * 21 ) self:SetLocalAngles( RAng ) self:ShowOutput() self:NextThink(CurTime()) return true end function ENT:ShowOutput() self:SetOverlayText(string.format("(%.2f - %.2f) = %.2f", self.Min, self.Max, self.Value)) end function ENT:OnRemove( ) if IsValid(self.BaseEnt) then self.BaseEnt:Remove() self.BaseEnt = nil end end function ENT:BuildDupeInfo() local info = self.BaseClass.BuildDupeInfo(self) or {} if IsValid(self.BaseEnt) then info.baseent = self.BaseEnt:EntIndex() end info.value = self.Value return info end function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) if info.baseent then self.BaseEnt = GetEntByID(info.baseent) end if info.value then self.Value = info.value self:TriggerInput("SetValue", self.Value) end end duplicator.RegisterEntityClass("gmod_wire_lever", WireLib.MakeWireEnt, "Data", "Min", "Max" )
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Analog Lever" ENT.WireDebugName = "Lever" if CLIENT then return end -- No more client function ENT:Initialize() self:SetModel("models/props_wasteland/tram_lever01.mdl") self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self:SetUseType( SIMPLE_USE ) self.EntToOutput = NULL self.Ang = 0 self.Value = 0 self:Setup(0, 1) self.Inputs = WireLib.CreateInputs(self, {"SetValue", "Min", "Max"}) self.Outputs = WireLib.CreateOutputs(self, {"Value", "Entity [ENTITY]"}) end function ENT:Setup(min, max) if min then self.Min = min end if max then self.Max = max end end function ENT:TriggerInput(iname, value) if iname == "SetValue" then self.Ang = (math.Clamp(value, self.Min, self.Max) - self.Min)/(self.Max - self.Min) * 90 - 45 elseif (iname == "Min") then self.Min = value elseif (iname == "Max") then self.Max = value end end function ENT:Use( ply ) if not IsValid(ply) or not ply:IsPlayer() or IsValid(self.User) then return end self.User = ply WireLib.TriggerOutput( self, "Entity", ply) end function ENT:Think() self.BaseClass.Think(self) if not IsValid(self.BaseEnt) then return end if IsValid(self.User) then local dist = self.User:GetShootPos():Distance(self:GetPos()) if dist < 160 and (self.User:KeyDown(IN_USE) or self.User:KeyDown(IN_ATTACK)) then local TargPos = self.User:GetShootPos() + self.User:GetAimVector() * dist local distMax = TargPos:Distance(self.BaseEnt:GetPos() + self.BaseEnt:GetForward() * 30) local distMin = TargPos:Distance(self.BaseEnt:GetPos() + self.BaseEnt:GetForward() * -30) local FPos = (distMax - distMin) * 0.5 distMax = TargPos:Distance(self.BaseEnt:GetPos()) distMin = TargPos:Distance(self.BaseEnt:GetPos() + self.BaseEnt:GetUp() * 40) local HPos = 20 - ((distMin - distMax) * 0.5) self.Ang = math.Clamp( math.deg( math.atan2( HPos, FPos ) ) - 90, -45, 45 ) else self.User = NULL WireLib.TriggerOutput( self, "Entity", NULL) end end self.Value = Lerp((self.Ang + 45) / 90, self.Min, self.Max) Wire_TriggerOutput(self, "Value", self.Value) local NAng = self.BaseEnt:GetAngles() NAng:RotateAroundAxis( NAng:Right(), -self.Ang ) local RAng = self.BaseEnt:WorldToLocalAngles(NAng) self:SetLocalPos( RAng:Up() * 21 ) self:SetLocalAngles( RAng ) self:ShowOutput() self:NextThink(CurTime()) return true end function ENT:ShowOutput() self:SetOverlayText(string.format("(%.2f - %.2f) = %.2f", self.Min, self.Max, self.Value)) end function ENT:OnRemove( ) if IsValid(self.BaseEnt) then self.BaseEnt:Remove() self.BaseEnt = nil end end function ENT:BuildDupeInfo() local info = self.BaseClass.BuildDupeInfo(self) or {} if IsValid(self.BaseEnt) then info.baseent = self.BaseEnt:EntIndex() constraint.Weld(self, self.BaseEnt, 0, 0, 0, true) -- Just in case the weld has been broken somehow, remake to ensure inclusion in dupe end info.value = self.Value return info end function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) if info.baseent then self.BaseEnt = GetEntByID(info.baseent) end if info.value then self.Value = info.value self:TriggerInput("SetValue", self.Value) end end duplicator.RegisterEntityClass("gmod_wire_lever", WireLib.MakeWireEnt, "Data", "Min", "Max" )
Levers: Improved playeraim tracking Fixed a parent-duping issue if the lever base had all welds removed
Levers: Improved playeraim tracking Fixed a parent-duping issue if the lever base had all welds removed
Lua
apache-2.0
CaptainPRICE/wire,garrysmodlua/wire,dvdvideo1234/wire,immibis/wiremod,rafradek/wire,mms92/wire,Grocel/wire,plinkopenguin/wiremod,mitterdoo/wire,Python1320/wire,NezzKryptic/Wire,notcake/wire,wiremod/wire,bigdogmat/wire,sammyt291/wire,thegrb93/wire
432fd6a40018f4c29e08f1d4cadf1ccc387a0cff
xmake/actions/config/config_h.lua
xmake/actions/config/config_h.lua
--!The Automatic Cross-platform Build Tool -- -- XMake 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. -- -- XMake 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 XMake; -- If not, see <a href="http://www.gnu.org/licenses/"> http://www.gnu.org/licenses/</a> -- -- Copyright (C) 2015 - 2016, ruki All rights reserved. -- -- @author ruki -- @file config_h.lua -- -- imports import("core.base.option") import("core.project.config") import("core.project.project") -- make configure for the given target name function _make_for_target(files, target) -- get the target configure file local config_h = target:get("config_h") if not config_h then return end -- the prefix local prefix = target:get("config_h_prefix") or (target:name():upper() .. "_CONFIG") -- open the file local file = files[config_h] or io.open(config_h, "w") -- make the head if files[config_h] then file:print("") end file:print("#ifndef %s_H", prefix) file:print("#define %s_H", prefix) file:print("") -- make version local version = target:get("version") if version then file:print("// version") file:print("#define %s_VERSION \"%s\"", prefix, version) local i = 1 local m = {"MAJOR", "MINOR", "ALTER"} for v in version:gmatch("%d+") do file:print("#define %s_VERSION_%s %s", prefix, m[i], v) i = i + 1 if i > 3 then break end end file:print("#define %s_VERSION_BUILD %s", prefix, os.date("%Y%m%d%H%M", os.time())) file:print("") end -- make the defines local defines = table.copy(target:get("defines_h")) -- make the undefines local undefines = table.copy(target:get("undefines_h")) -- make the options for name, opt in pairs(target:options()) do -- get the option defines table.join2(defines, opt:get("defines_h_if_ok")) -- get the option undefines table.join2(undefines, opt:get("undefines_h_if_ok")) end -- make the defines if #defines ~= 0 then file:print("// defines") for _, define in ipairs(defines) do file:print("#define %s 1", define:gsub("=", " "):gsub("%$%((.-)%)", function (w) if w == "prefix" then return prefix end end)) end file:print("") end -- make the undefines if #undefines ~= 0 then file:print("// undefines") for _, undefine in ipairs(undefines) do file:print("#undef %s", undefine:gsub("%$%((.-)%)", function (w) if w == "prefix" then return prefix end end)) end file:print("") end -- make the tail file:print("#endif") -- cache the file files[config_h] = file end -- make the configure file for the given target and dependents function _make_for_target_with_deps(files, targetname) -- the target local target = project.target(targetname) -- make configure for the target _make_for_target(files, target) -- make configure for the dependent targets? for _, dep in ipairs(target:get("deps")) do _make_for_target_with_deps(files, dep) end end -- make the config.h function make() -- the target name local targetname = option.get("target") -- enter project directory os.cd(project.directory()) -- init files local files = {} -- make configure for the given target name if targetname and targetname ~= "all" then _make_for_target_with_deps(files, targetname) else -- make configure for all targets for _, target in pairs(project.targets()) do _make_for_target(files, target) end end -- exit files for _, file in pairs(files) do file:close() end -- leave project directory os.cd("-") end
--!The Automatic Cross-platform Build Tool -- -- XMake 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. -- -- XMake 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 XMake; -- If not, see <a href="http://www.gnu.org/licenses/"> http://www.gnu.org/licenses/</a> -- -- Copyright (C) 2015 - 2016, ruki All rights reserved. -- -- @author ruki -- @file config_h.lua -- -- imports import("core.base.option") import("core.project.config") import("core.project.project") -- make configure for the given target name function _make_for_target(files, target) -- get the target configure file local config_h = target:get("config_h") if not config_h then return end -- the prefix local prefix = target:get("config_h_prefix") or (target:name():upper() .. "_CONFIG") -- open the file local file = files[config_h] or io.open(config_h, "w") -- make the head if files[config_h] then file:print("") end file:print("#ifndef %s_H", prefix) file:print("#define %s_H", prefix) file:print("") -- make version local version = target:get("version") if version then file:print("// version") file:print("#define %s_VERSION \"%s\"", prefix, version) local i = 1 local m = {"MAJOR", "MINOR", "ALTER"} for v in version:gmatch("%d+") do file:print("#define %s_VERSION_%s %s", prefix, m[i], v) i = i + 1 if i > 3 then break end end file:print("#define %s_VERSION_BUILD %s", prefix, os.date("%Y%m%d%H%M", os.time())) file:print("") end -- make the defines local defines = table.copy(target:get("defines_h")) -- make the undefines local undefines = table.copy(target:get("undefines_h")) -- make the options for name, opt in pairs(target:options()) do -- get the option defines table.join2(defines, opt:get("defines_h_if_ok")) -- get the option undefines table.join2(undefines, opt:get("undefines_h_if_ok")) end -- make the defines if #defines ~= 0 then file:print("// defines") for _, define in ipairs(defines) do if define:find("=") then file:print("#define %s", define:gsub("=", " "):gsub("%$%((.-)%)", function (w) if w == "prefix" then return prefix end end)) else file:print("#define %s 1", define:gsub("%$%((.-)%)", function (w) if w == "prefix" then return prefix end end)) end end file:print("") end -- make the undefines if #undefines ~= 0 then file:print("// undefines") for _, undefine in ipairs(undefines) do file:print("#undef %s", undefine:gsub("%$%((.-)%)", function (w) if w == "prefix" then return prefix end end)) end file:print("") end -- make the tail file:print("#endif") -- cache the file files[config_h] = file end -- make the configure file for the given target and dependents function _make_for_target_with_deps(files, targetname) -- the target local target = project.target(targetname) -- make configure for the target _make_for_target(files, target) -- make configure for the dependent targets? for _, dep in ipairs(target:get("deps")) do _make_for_target_with_deps(files, dep) end end -- make the config.h function make() -- the target name local targetname = option.get("target") -- enter project directory os.cd(project.directory()) -- init files local files = {} -- make configure for the given target name if targetname and targetname ~= "all" then _make_for_target_with_deps(files, targetname) else -- make configure for all targets for _, target in pairs(project.targets()) do _make_for_target(files, target) end end -- exit files for _, file in pairs(files) do file:close() end -- leave project directory os.cd("-") end
fix generate defines bug for config.h
fix generate defines bug for config.h
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake
e668379f6d57851f14af2f1c3e494c90e5eebb25
frontend/ui/widget/filechooser.lua
frontend/ui/widget/filechooser.lua
require "ui/widget/menu" FileChooser = Menu:extend{ height = Screen:getHeight(), width = Screen:getWidth(), no_title = true, path = lfs.currentdir(), parent = nil, show_hidden = false, filter = function(filename) return true end, } function FileChooser:init() self.item_table = self:genItemTableFromPath(self.path) Menu.init(self) -- call parent's init() end function FileChooser:compressPath(item_path) if (item_path:sub(1, 1) == ".") then -- ignore relative path return item_path end -- compress paths like "test/pdf/../epub" into "test/epub" local path = item_path while path:match("/[^/]+[/][\\.][\\.]") do path = path:gsub("/[^/]+[/][\\.][\\.]", "") end return path end function FileChooser:genItemTableFromPath(path) local dirs = {} local files = {} for f in lfs.dir(self.path) do if self.show_hidden or not string.match(f, "^%.[^.]") then local filename = self.path.."/"..f local filemode = lfs.attributes(filename, "mode") if filemode == "directory" and f ~= "." and f~=".." then if self.dir_filter(filename) then table.insert(dirs, f) end elseif filemode == "file" then if self.file_filter(filename) then table.insert(files, f) end end end end table.sort(dirs) if path ~= "/" then table.insert(dirs, 1, "..") end table.sort(files) local item_table = {} for _, dir in ipairs(dirs) do table.insert(item_table, { text = dir.."/", path = self.path.."/"..dir }) end for _, file in ipairs(files) do table.insert(item_table, { text = file, path = self.path.."/"..file }) end return item_table end function FileChooser:changeToPath(path) path = self:compressPath(path) self.path = path self:swithItemTable(nil, self:genItemTableFromPath(path)) end function FileChooser:onMenuSelect(item) if lfs.attributes(item.path, "mode") == "directory" then self:changeToPath(item.path) else self:onFileSelect(item.path) end return true end function FileChooser:onFileSelect(file) UIManager:close(self) return true end
require "ui/widget/menu" FileChooser = Menu:extend{ height = Screen:getHeight(), width = Screen:getWidth(), no_title = true, path = lfs.currentdir(), parent = nil, show_hidden = false, filter = function(filename) return true end, } function FileChooser:init() self.item_table = self:genItemTableFromPath(self.path) Menu.init(self) -- call parent's init() end function FileChooser:compressPath(path) local pos if path:sub(1, 1) ~= "/" then -- currently does not work with relative paths return path end path = path:gsub("/+", "/") -- compress paths like "test/pdf/../epub" into "test/epub" repeat path, pos = path:gsub("/?[^/]*/%.%.", "", 1) until pos == 0 return path ~= "" and path or "/" end function FileChooser:genItemTableFromPath(path) local dirs = {} local files = {} for f in lfs.dir(self.path) do if self.show_hidden or not string.match(f, "^%.[^.]") then local filename = self.path.."/"..f local filemode = lfs.attributes(filename, "mode") if filemode == "directory" and f ~= "." and f~=".." then if self.dir_filter(filename) then table.insert(dirs, f) end elseif filemode == "file" then if self.file_filter(filename) then table.insert(files, f) end end end end table.sort(dirs) if path ~= "/" then table.insert(dirs, 1, "..") end table.sort(files) local item_table = {} for _, dir in ipairs(dirs) do table.insert(item_table, { text = dir.."/", path = self.path.."/"..dir }) end for _, file in ipairs(files) do table.insert(item_table, { text = file, path = self.path.."/"..file }) end return item_table end function FileChooser:changeToPath(path) path = self:compressPath(path) self.path = path self:swithItemTable(nil, self:genItemTableFromPath(path)) end function FileChooser:onMenuSelect(item) if lfs.attributes(item.path, "mode") == "directory" then self:changeToPath(item.path) else self:onFileSelect(item.path) end return true end function FileChooser:onFileSelect(file) UIManager:close(self) return true end
Fix crash when trying to go to / on FM
Fix crash when trying to go to / on FM Deals with more cases in FileChooser:compressPath, including `/mnt/..`.
Lua
agpl-3.0
chrox/koreader,ashhher3/koreader,pazos/koreader,Frenzie/koreader,apletnev/koreader,Frenzie/koreader,koreader/koreader,NickSavage/koreader,NiLuJe/koreader,mwoz123/koreader,ashang/koreader,houqp/koreader,lgeek/koreader,frankyifei/koreader,robert00s/koreader,Markismus/koreader,koreader/koreader,poire-z/koreader,NiLuJe/koreader,mihailim/koreader,noname007/koreader,chihyang/koreader,poire-z/koreader,Hzj-jie/koreader
aef2c4123eb07a9394226df8c0b7108725aaedc8
frontend/ui/widget/filechooser.lua
frontend/ui/widget/filechooser.lua
require "ui/widget/menu" FileChooser = Menu:new{ height = Screen:getHeight(), width = Screen:getWidth(), path = lfs.currentdir(), parent = nil, show_hidden = false, filter = function(filename) return true end, } function FileChooser:init() self:changeToPath(self.path) end function FileChooser:compressPath(item_path) -- compress paths like "test/pdf/../epub" into "test/epub" local path = item_path while path:match("/[^/]+[/][\\.][\\.]") do path = path:gsub("/[^/]+[/][\\.][\\.]", "") end return path end function FileChooser:changeToPath(path) path = self:compressPath(path) local dirs = {} local files = {} self.path = path for f in lfs.dir(self.path) do if self.show_hidden or not string.match(f, "^%.[^.]") then local filename = self.path.."/"..f local filemode = lfs.attributes(filename, "mode") if filemode == "directory" and f ~= "." and f~=".." then if self.dir_filter(filename) then table.insert(dirs, f) end elseif filemode == "file" then if self.file_filter(filename) then table.insert(files, f) end end end end table.sort(dirs) if self.path ~= "/" then table.insert(dirs, 1, "..") end table.sort(files) self.item_table = {} for _, dir in ipairs(dirs) do table.insert(self.item_table, { text = dir.."/", path = self.path.."/"..dir }) end for _, file in ipairs(files) do table.insert(self.item_table, { text = file, path = self.path.."/"..file }) end Menu.init(self) -- call parent's init() end function FileChooser:onMenuSelect(item) if lfs.attributes(item.path, "mode") == "directory" then UIManager:close(self) self:changeToPath(item.path) UIManager:show(self) else self:onFileSelect(item.path) end return true end function FileChooser:onFileSelect(file) UIManager:close(self) return true end
require "ui/widget/menu" FileChooser = Menu:extend{ height = Screen:getHeight(), width = Screen:getWidth(), no_title = true, path = lfs.currentdir(), parent = nil, show_hidden = false, filter = function(filename) return true end, } function FileChooser:init() self:updateItemTableFromPath(self.path) Menu.init(self) -- call parent's init() end function FileChooser:compressPath(item_path) -- compress paths like "test/pdf/../epub" into "test/epub" local path = item_path while path:match("/[^/]+[/][\\.][\\.]") do path = path:gsub("/[^/]+[/][\\.][\\.]", "") end return path end function FileChooser:updateItemTableFromPath(path) path = self:compressPath(path) local dirs = {} local files = {} self.path = path for f in lfs.dir(self.path) do if self.show_hidden or not string.match(f, "^%.[^.]") then local filename = self.path.."/"..f local filemode = lfs.attributes(filename, "mode") if filemode == "directory" and f ~= "." and f~=".." then if self.dir_filter(filename) then table.insert(dirs, f) end elseif filemode == "file" then if self.file_filter(filename) then table.insert(files, f) end end end end table.sort(dirs) if self.path ~= "/" then table.insert(dirs, 1, "..") end table.sort(files) self.item_table = {} for _, dir in ipairs(dirs) do table.insert(self.item_table, { text = dir.."/", path = self.path.."/"..dir }) end for _, file in ipairs(files) do table.insert(self.item_table, { text = file, path = self.path.."/"..file }) end end function FileChooser:changeToPath(path) self:updateItemTableFromPath(path) self:updateItems(1) end function FileChooser:onMenuSelect(item) if lfs.attributes(item.path, "mode") == "directory" then self:changeToPath(item.path) else self:onFileSelect(item.path) end return true end function FileChooser:onFileSelect(file) UIManager:close(self) return true end
fix Menu widget initialization on inheritance bug in filechooser
fix Menu widget initialization on inheritance bug in filechooser
Lua
agpl-3.0
poire-z/koreader,chrox/koreader,koreader/koreader,lgeek/koreader,robert00s/koreader,chihyang/koreader,frankyifei/koreader,NickSavage/koreader,mwoz123/koreader,koreader/koreader,ashhher3/koreader,ashang/koreader,pazos/koreader,Hzj-jie/koreader,noname007/koreader,NiLuJe/koreader,NiLuJe/koreader,Frenzie/koreader,apletnev/koreader,Markismus/koreader,mihailim/koreader,poire-z/koreader,houqp/koreader,Frenzie/koreader
8982e05dda54b43eff540f80d0008c13c42d5051
base/ranklist.lua
base/ranklist.lua
require("base.common") module("base.ranklist", package.seeall) --[[ gets the top 5 of the ranklist. Each ranklist entry contains the name of the character and the points. The scriptVar is converted to a table for better handling and then shown in a messageDialog. list format - "<name1>;<points1>;<name2>;<point2>..." showMessage = true: displays a messagebox with the ranklist showMessage = false: returns the ranklist table ]] function getRanklist(User, listName, showMessage) local found = false; local listEntryString; local listEntryTable = {}; local list = " "; found, listEntryString = ScriptVars:find(listName); -- get the top 5 if found then listEntryTable = convertTo2dTable(base.common.split(listEntryString, ";")); elseif not found and showMessage then User:inform(base.common.GetNLS(User, "Die Liste ist leer.","The list is empty.")); return {}; end if (listEntryString == "" or listEntryString == nil) and showMessage then User:inform(base.common.GetNLS(User, "Die Liste ist leer.","The list is empty.")); return {}; end if showMessage then if #listEntryTable ~= 0 then showList(User, listEntryTable) end else return listEntryTable; end end function showList(User, ranklist) local list = "" local mdList = function(dialog) if (not dialog:getSuccess()) then return; end end if User:getPlayerLanguage() == 0 then for i=1, #ranklist do list = list.."Platz "..i.." : "..ranklist[i].name.." mit "..ranklist[i].points.." Punkten.\n"; end mdList = MessageDialog("Top Fnf", list, nil); else for i=1, #ranklist do list = list.."Place "..i.." : "..ranklist[i].name.." with "..ranklist[i].points.." points.\n"; end mdList = MessageDialog("Top five", list, nil); end User:requestMessageDialog(mdList); end maxEntries = 5 --[[ Saves the points of the player and if he reached the top five, also saves the new top five. ]] function setRanklist(User, listName, points) local ranklist = getRanklist(User, listName, false) local joinedRanklist = {} --User:inform("ranklist nr: "..#ranklist) if #ranklist ~= 0 then local userInList, position = isUserInList(User, ranklist); --debug("Number: "..#ranklist) --debug("check this out: "..ranklist[#ranklist].name) --debug("check this out - points: "..ranklist[#ranklist].points) if tonumber(ranklist[#ranklist].points) > points and #ranklist == maxEntries then return; else if not userInList then table.insert(ranklist, {["name"] = User.name; ["points"] = points}); else table.remove(ranklist, position); table.insert(ranklist, {["name"] = User.name; ["points"] = points}); end table.sort(ranklist, compare) joinedRanklist = convertToOneTable(ranklist) local stringList = table.concat(joinedRanklist, ";"); --debug("String before deletion" ..stringList) while #ranklist > maxEntries do table.remove(ranklist); end joinedRanklist = convertToOneTable(ranklist) local stringList = table.concat(joinedRanklist, ";"); --debug("String after join:" ..stringList) ScriptVars:set(listName, stringList) end else local stringList = User.name..";"..points ScriptVars:set(listName, stringList) end end function compare(tableA, tableB) return tonumber(tableA.points) > tonumber(tableB.points); end function convertTo2dTable(list) local newTable = {} for i=1, #list, 2 do table.insert(newTable, {["name"] = list[i]; ["points"] = list[i+1]}); end; return newTable; end function convertToOneTable(list) local joinedTable = {} --debug("lenght of list: "..#list) for i=1, #list do --debug("List: "..i.." "..list[i].name.." "..list[i].points) table.insert(joinedTable, list[i].name); table.insert(joinedTable, list[i].points); end; --debug("JoinedTable "..joinedTable[1]) return joinedTable; end function isUserInList(User, ranklist) for i=1, #ranklist do if ranklist[i].name == User.name then --debug("found "..User.name.." on position"..i); return true, i; end end --debug(User.name.." not found") return false, 0; end
require("base.common") module("base.ranklist", package.seeall) --[[ gets the top 5 of the ranklist. Each ranklist entry contains the name of the character and the points. The scriptVar is converted to a table for better handling and then shown in a messageDialog. list format - "<name1>;<points1>;<name2>;<point2>..." showMessage = true: displays a messagebox with the ranklist showMessage = false: returns the ranklist table ]] function getRanklist(User, listName, showMessage) local found = false; local listEntryString; local listEntryTable = {}; local list = " "; found, listEntryString = ScriptVars:find(listName); -- get the top 5 if found then listEntryTable = convertTo2dTable(base.common.split(listEntryString, ";")); elseif not found and showMessage then User:inform(base.common.GetNLS(User, "Die Liste ist leer.","The list is empty.")); return {}; end if (listEntryString == "" or listEntryString == nil) and showMessage then User:inform(base.common.GetNLS(User, "Die Liste ist leer.","The list is empty.")); return {}; end if showMessage then if #listEntryTable ~= 0 then showList(User, listEntryTable) end else return listEntryTable; end end function showList(User, ranklist) local list = "" local mdList = function(dialog) if (not dialog:getSuccess()) then return; end end if User:getPlayerLanguage() == 0 then for i=1, #ranklist do list = list.."Platz "..i.." : "..ranklist[i].name.." mit "..ranklist[i].points.." Punkten.\n"; end mdList = MessageDialog("Top Fnf", list, nil); else for i=1, #ranklist do list = list.."Place "..i.." : "..ranklist[i].name.." with "..ranklist[i].points.." points.\n"; end mdList = MessageDialog("Top five", list, nil); end User:requestMessageDialog(mdList); end maxEntries = 5 --[[ Saves the points of the player and if he reached the top five, also saves the new top five. ]] function setRanklist(User, listName, points) local ranklist = getRanklist(User, listName, false) local joinedRanklist = {} --User:inform("ranklist nr: "..#ranklist) if User:isAdmin() then return; else if #ranklist ~= 0 then local userInList, position = isUserInList(User, ranklist); --debug("Number: "..#ranklist) --debug("check this out: "..ranklist[#ranklist].name) --debug("check this out - points: "..ranklist[#ranklist].points) if tonumber(ranklist[#ranklist].points) > points and #ranklist == maxEntries then return; else if not userInList then table.insert(ranklist, {["name"] = User.name; ["points"] = points}); else table.remove(ranklist, position); table.insert(ranklist, {["name"] = User.name; ["points"] = points}); end table.sort(ranklist, compare) joinedRanklist = convertToOneTable(ranklist) local stringList = table.concat(joinedRanklist, ";"); --debug("String before deletion" ..stringList) while #ranklist > maxEntries do table.remove(ranklist); end joinedRanklist = convertToOneTable(ranklist) local stringList = table.concat(joinedRanklist, ";"); --debug("String after join:" ..stringList) ScriptVars:set(listName, stringList) end else local stringList = User.name..";"..points ScriptVars:set(listName, stringList) end end end function compare(tableA, tableB) return tonumber(tableA.points) > tonumber(tableB.points); end function convertTo2dTable(list) local newTable = {} for i=1, #list, 2 do table.insert(newTable, {["name"] = list[i]; ["points"] = list[i+1]}); end; return newTable; end function convertToOneTable(list) local joinedTable = {} --debug("lenght of list: "..#list) for i=1, #list do --debug("List: "..i.." "..list[i].name.." "..list[i].points) table.insert(joinedTable, list[i].name); table.insert(joinedTable, list[i].points); end; --debug("JoinedTable "..joinedTable[1]) return joinedTable; end function isUserInList(User, ranklist) for i=1, #ranklist do if ranklist[i].name == User.name then --debug("found "..User.name.." on position"..i); return true, i; end end --debug(User.name.." not found") return false, 0; end
Fix that only non-Admins are added to a ranklist. Mantis id #8922
Fix that only non-Admins are added to a ranklist. Mantis id #8922
Lua
agpl-3.0
Baylamon/Illarion-Content,LaFamiglia/Illarion-Content,KayMD/Illarion-Content,vilarion/Illarion-Content,Illarion-eV/Illarion-Content
a86271a3caa40ddaabbc16820108a84e9ee8c3ea
src/cosy/lang/view/update.lua
src/cosy/lang/view/update.lua
local cosy = require "cosy.lang.cosy" local raw = require "cosy.lang.data" . raw local tags = require "cosy.lang.tags" local type = require "cosy.util.type" local map = require "cosy.lang.iterators" . map local is_empty = require "cosy.lang.iterators" . is_empty local NAME = tags.NAME local PARENTS = tags.PARENTS local UPDATES = tags.UPDATES local WS = tags.WS local TYPE = tags.TYPE local function path_to (data, key) local path if raw (data) == raw (cosy) then path = { cosy } elseif type (data) . string then path = { data } elseif type (data) . number then path = { data } elseif type (data) . boolean then path = { data } elseif type (data) . tag then path = { cosy, "tags", data [NAME] } else local parents = data [PARENTS] if not parents then path = { data, new = true } else -- Select one parent, ask path to it for p, keys in map (parents) do for key in pairs (keys) do path = path_to (p, key) end end end end if not key then return path end -- Add key: if type (key) . table then path [#path + 1] = path_to (key) else for _, p in ipairs (path_to (key)) do path [#path + 1] = p end end return path end local function path_for (path) if #path == 1 and path.new then return "{}" end local result for _, p in ipairs (path) do if p == raw (cosy) then result = cosy [NAME] elseif type (p) . string then if result then local i, j = string.find (p, "[_%a][_%w]*") if i == 1 and j == #p then result = result .. "." .. p else result = result .. "['" .. p .. "']" end else result = "'" .. p .. "'" end elseif type (p) . number then if result then result = result .. "[" .. tostring (p) .. "]" else result = tostring (p) end elseif type (p) . boolean then if result then result = result .. "[" .. tostring (p) .. "]" else result = tostring (p) end elseif type (p) . table then result = result .. "[" .. path_for (p) .. "]" end end return result end local function remove_parent (data, key) local value = data [key] local raw_data = raw (data) local raw_key = raw (key) local raw_value = raw (value) if type (raw_value) . table and raw_value [PARENTS] then local old_parents = raw_value [PARENTS] local ks = old_parents [raw_data] or {} ks [raw_key] = nil if is_empty (ks) then old_parents [raw_data] = nil end if is_empty (old_parents) then raw_value [PARENTS] = nil else raw_value [PARENTS] = old_parents end end end local function insert_parent (data, key) local value = data [key] local raw_data = raw (data) local raw_key = raw (key) local raw_value = raw (value) if type (raw_value) . table then local new_parents = raw_value [PARENTS] or {} if not new_parents [raw_data] then new_parents [raw_data] = {} end new_parents [raw_data] [raw_key] = true raw_value [PARENTS] = new_parents end end local mt = {} function mt:__call (data, key) if type (key) . tag and not key.persistent then return end -- remove_parent (data, key) -- local old_value = raw (data [key]) coroutine.yield () local new_value = raw (data [key]) if js then if old_value ~= new_value then if type (old_value) . table and old_value [TYPE] then js.global:remove_node (old_value) end if type (new_value) . table and new_value [TYPE] then js.global:add_node (new_value) end end if data [TYPE] then js.global:update_node (raw (data)) end end local recursive = self.from_patch if not self.from_patch then local lhs_path = path_to (data, key) local lhs = path_for (lhs_path) local rhs_path = path_to (data [key]) local rhs = path_for (rhs_path) recursive = recursive or rhs_path.new if lhs_path [1] == raw (cosy) and #lhs_path > 2 then local patch_str = lhs .. " = " .. rhs local model = cosy [lhs_path [2]] model [UPDATES] = model [UPDATES] or {} model [UPDATES] [#(model [UPDATES]) + 1] = { unpatch = function () data [key] = old_value insert_parent (data, key) end, patch = patch_str } if model [WS] then model [WS]:patch (patch_str) end end end -- insert_parent (data, key) -- if recursive then local r = data [key] for k, v in map (r) do r [k] = v end end end return setmetatable ({}, mt)
local cosy = require "cosy.lang.cosy" local raw = require "cosy.lang.data" . raw local tags = require "cosy.lang.tags" local type = require "cosy.util.type" local map = require "cosy.lang.iterators" . map local is_empty = require "cosy.lang.iterators" . is_empty local NAME = tags.NAME local PARENTS = tags.PARENTS local UPDATES = tags.UPDATES local WS = tags.WS local TYPE = tags.TYPE local function path_to (data, key) local path if data == nil then path = nil elseif raw (data) == raw (cosy) then path = { cosy } elseif type (data) . string then path = { data } elseif type (data) . number then path = { data } elseif type (data) . boolean then path = { data } elseif type (data) . tag then path = { cosy, "tags", data [NAME] } else local parents = data [PARENTS] if not parents then path = { data, new = true } else -- Select one parent, ask path to it for p, keys in map (parents) do for key in pairs (keys) do path = path_to (p, key) end end end end if not key then return path end -- Add key: if type (key) . table then path [#path + 1] = path_to (key) else for _, p in ipairs (path_to (key)) do path [#path + 1] = p end end return path end local function path_for (path) if path == nil then return "nil" elseif #path == 1 and path.new then return "{}" end local result for _, p in ipairs (path) do if p == raw (cosy) then result = cosy [NAME] elseif type (p) . string then if result then local i, j = string.find (p, "[_%a][_%w]*") if i == 1 and j == #p then result = result .. "." .. p else result = result .. "['" .. p .. "']" end else result = "'" .. p .. "'" end elseif type (p) . number then if result then result = result .. "[" .. tostring (p) .. "]" else result = tostring (p) end elseif type (p) . boolean then if result then result = result .. "[" .. tostring (p) .. "]" else result = tostring (p) end elseif type (p) . table then result = result .. "[" .. path_for (p) .. "]" end end return result end local function remove_parent (data, key) local value = data [key] local raw_data = raw (data) local raw_key = raw (key) local raw_value = raw (value) if type (raw_value) . table and raw_value [PARENTS] then local old_parents = raw_value [PARENTS] local ks = old_parents [raw_data] or {} ks [raw_key] = nil if is_empty (ks) then old_parents [raw_data] = nil end if is_empty (old_parents) then raw_value [PARENTS] = nil else raw_value [PARENTS] = old_parents end end end local function insert_parent (data, key) local value = data [key] local raw_data = raw (data) local raw_key = raw (key) local raw_value = raw (value) if type (raw_value) . table then local new_parents = raw_value [PARENTS] or {} if not new_parents [raw_data] then new_parents [raw_data] = {} end new_parents [raw_data] [raw_key] = true raw_value [PARENTS] = new_parents end end local mt = {} local nodes = {} function mt:__call (data, key) if type (key) . tag and not key.persistent then return end -- remove_parent (data, key) -- local old_value = raw (data [key]) coroutine.yield () local new_value = raw (data [key]) local recursive = self.from_patch if not self.from_patch then local lhs_path = path_to (data, key) local lhs = path_for (lhs_path) local rhs_path = path_to (data [key]) local rhs = path_for (rhs_path) recursive = recursive or (rhs_path and rhs_path.new) if lhs_path [1] == raw (cosy) and #lhs_path > 2 then local patch_str = lhs .. " = " .. rhs local model = cosy [lhs_path [2]] model [UPDATES] = model [UPDATES] or {} model [UPDATES] [#(model [UPDATES]) + 1] = { unpatch = function () data [key] = old_value insert_parent (data, key) end, patch = patch_str } if model [WS] then model [WS]:patch (patch_str) end end end -- if js then -- FIXME: adapt also to non-js if nodes [old_value] and not old_value [PARENTS] then js.global:remove_node (old_value) elseif data [TYPE] and nodes [raw (data)] then js.global:update_node (raw (data)) elseif data [TYPE] and not nodes [raw (data)] then js.global:add_node (raw (data)) nodes [raw (data)] = true end end -- insert_parent (data, key) -- if recursive then local r = data [key] for k, v in map (r) do r [k] = v end end end return setmetatable ({}, mt)
Fix add/update/remove of nodes, at the cost of one table to store them.
Fix add/update/remove of nodes, at the cost of one table to store them.
Lua
mit
CosyVerif/library,CosyVerif/library,CosyVerif/library
9208d4bbfe744607e78b9d700e3f134962d92c41
busted/runner.lua
busted/runner.lua
-- Busted command-line runner local path = require 'pl.path' local tablex = require 'pl.tablex' local term = require 'term' local utils = require 'busted.utils' local exit = require 'busted.compatibility'.exit local loadstring = require 'busted.compatibility'.loadstring local loaded = false return function(options) if loaded then return function() end else loaded = true end local isatty = io.type(io.stdout) == 'file' and term.isatty(io.stdout) options = tablex.update(require 'busted.options', options or {}) options.output = options.output or (isatty and 'utfTerminal' or 'plainTerminal') local busted = require 'busted.core'() local cli = require 'busted.modules.cli'(options) local filterLoader = require 'busted.modules.filter_loader'() local helperLoader = require 'busted.modules.helper_loader'() local outputHandlerLoader = require 'busted.modules.output_handler_loader'() local luacov = require 'busted.modules.luacov'() require 'busted'(busted) local level = 2 local info = debug.getinfo(level, 'Sf') local source = info.source local fileName = source:sub(1,1) == '@' and source:sub(2) or nil local forceExit = fileName == nil -- Parse the cli arguments local appName = path.basename(fileName or 'busted') cli:set_name(appName) local cliArgs, err = cli:parse(arg) if not cliArgs then io.stderr:write(err .. '\n') exit(1, forceExit) end if cliArgs.version then -- Return early if asked for the version print(busted.version) exit(0, forceExit) end -- Load current working directory local _, err = path.chdir(path.normpath(cliArgs.directory)) if err then io.stderr:write(appName .. ': error: ' .. err .. '\n') exit(1, forceExit) end -- If coverage arg is passed in, load LuaCovsupport if cliArgs.coverage then local ok, err = luacov() if not ok then io.stderr:write(appName .. ': error: ' .. err .. '\n') exit(1, forceExit) end end -- If auto-insulate is disabled, re-register file without insulation if not cliArgs['auto-insulate'] then busted.register('file', 'file', {}) end -- If lazy is enabled, make lazy setup/teardown the default if cliArgs.lazy then busted.register('setup', 'lazy_setup') busted.register('teardown', 'lazy_teardown') end -- Add additional package paths based on lpath and cpath cliArgs if #cliArgs.lpath > 0 then package.path = (cliArgs.lpath .. ';' .. package.path):gsub(';;',';') end if #cliArgs.cpath > 0 then package.cpath = (cliArgs.cpath .. ';' .. package.cpath):gsub(';;',';') end -- Load and execute commands given on the command-line if cliArgs.e then for k,v in ipairs(cliArgs.e) do loadstring(v)() end end -- watch for test errors and failures local failures = 0 local errors = 0 local quitOnError = not cliArgs['keep-going'] busted.subscribe({ 'error', 'output' }, function(element, parent, message) io.stderr:write(appName .. ': error: Cannot load output library: ' .. element.name .. '\n' .. message .. '\n') return nil, true end) busted.subscribe({ 'error', 'helper' }, function(element, parent, message) io.stderr:write(appName .. ': error: Cannot load helper script: ' .. element.name .. '\n' .. message .. '\n') return nil, true end) busted.subscribe({ 'error' }, function(element, parent, message) errors = errors + 1 busted.skipAll = quitOnError return nil, true end) busted.subscribe({ 'failure' }, function(element, parent, message) if element.descriptor == 'it' then failures = failures + 1 else errors = errors + 1 end busted.skipAll = quitOnError return nil, true end) -- Set up randomization options busted.sort = cliArgs['sort-tests'] busted.randomize = cliArgs['shuffle-tests'] busted.randomseed = tonumber(cliArgs.seed) or utils.urandom() or os.time() -- Set up output handler to listen to events outputHandlerLoader(busted, cliArgs.output, { defaultOutput = options.output, enableSound = cliArgs['enable-sound'], verbose = cliArgs.verbose, suppressPending = cliArgs['suppress-pending'], language = cliArgs.lang, deferPrint = cliArgs['defer-print'], arguments = cliArgs.Xoutput, }) -- Pre-load the LuaJIT 'ffi' module if applicable local isJit = (tostring(assert):match('builtin') ~= nil) if isJit then -- pre-load the ffi module, such that it becomes part of the environment -- and Busted will not try to GC and reload it. The ffi is not suited -- for that and will occasionally segfault if done so. local ffi = require "ffi" -- Now patch ffi.cdef to only be called once with each definition, as it -- will error on re-registering. local old_cdef = ffi.cdef local exists = {} ffi.cdef = function(def) if exists[def] then return end exists[def] = true return old_cdef(def) end end -- Set up helper script if cliArgs.helper and cliArgs.helper ~= '' then helperLoader(busted, cliArgs.helper, { verbose = cliArgs.verbose, language = cliArgs.lang, arguments = cliArgs.Xhelper }) end -- Load tag and test filters filterLoader(busted, { tags = cliArgs.tags, excludeTags = cliArgs['exclude-tags'], filter = cliArgs.filter, filterOut = cliArgs['filter-out'], list = cliArgs.list, nokeepgoing = not cliArgs['keep-going'], suppressPending = cliArgs['suppress-pending'], }) if cliArgs.ROOT then -- Load test directories/files local rootFiles = cliArgs.ROOT local patterns = cliArgs.pattern local testFileLoader = require 'busted.modules.test_file_loader'(busted, cliArgs.loaders) testFileLoader(rootFiles, patterns, { excludes = cliArgs['exclude-pattern'], verbose = cliArgs.verbose, recursive = cliArgs['recursive'], }) else -- Running standalone, use standalone loader local testFileLoader = require 'busted.modules.standalone_loader'(busted) testFileLoader(info, { verbose = cliArgs.verbose }) end local runs = cliArgs['repeat'] local execute = require 'busted.execute'(busted) execute(runs, { seed = cliArgs.seed, shuffle = cliArgs['shuffle-files'], sort = cliArgs['sort-files'], }) busted.publish({ 'exit' }) if options.standalone or failures > 0 or errors > 0 then exit(failures + errors, forceExit) end end
-- Busted command-line runner local path = require 'pl.path' local tablex = require 'pl.tablex' local term = require 'term' local utils = require 'busted.utils' local exit = require 'busted.compatibility'.exit local loadstring = require 'busted.compatibility'.loadstring local loaded = false return function(options) if loaded then return function() end else loaded = true end local isatty = io.type(io.stdout) == 'file' and term.isatty(io.stdout) options = tablex.update(require 'busted.options', options or {}) options.output = options.output or (isatty and 'utfTerminal' or 'plainTerminal') local busted = require 'busted.core'() local cli = require 'busted.modules.cli'(options) local filterLoader = require 'busted.modules.filter_loader'() local helperLoader = require 'busted.modules.helper_loader'() local outputHandlerLoader = require 'busted.modules.output_handler_loader'() local luacov = require 'busted.modules.luacov'() require 'busted'(busted) local level = 2 local info = debug.getinfo(level, 'Sf') local source = info.source local fileName = source:sub(1,1) == '@' and source:sub(2) or nil local forceExit = fileName == nil -- Parse the cli arguments local appName = path.basename(fileName or 'busted') cli:set_name(appName) local cliArgs, err = cli:parse(arg) if not cliArgs then io.stderr:write(err .. '\n') exit(1, forceExit) end if cliArgs.version then -- Return early if asked for the version print(busted.version) exit(0, forceExit) end -- Load current working directory local _, err = path.chdir(path.normpath(cliArgs.directory)) if err then io.stderr:write(appName .. ': error: ' .. err .. '\n') exit(1, forceExit) end -- If coverage arg is passed in, load LuaCovsupport if cliArgs.coverage then local ok, err = luacov() if not ok then io.stderr:write(appName .. ': error: ' .. err .. '\n') exit(1, forceExit) end end -- If auto-insulate is disabled, re-register file without insulation if not cliArgs['auto-insulate'] then busted.register('file', 'file', {}) end -- If lazy is enabled, make lazy setup/teardown the default if cliArgs.lazy then busted.register('setup', 'lazy_setup') busted.register('teardown', 'lazy_teardown') end -- Add additional package paths based on lpath and cpath cliArgs if #cliArgs.lpath > 0 then package.path = (cliArgs.lpath .. ';' .. package.path):gsub(';;',';') end if #cliArgs.cpath > 0 then package.cpath = (cliArgs.cpath .. ';' .. package.cpath):gsub(';;',';') end -- Load and execute commands given on the command-line if cliArgs.e then for k,v in ipairs(cliArgs.e) do loadstring(v)() end end -- watch for test errors and failures local failures = 0 local errors = 0 local quitOnError = not cliArgs['keep-going'] busted.subscribe({ 'error', 'output' }, function(element, parent, message) io.stderr:write(appName .. ': error: Cannot load output library: ' .. element.name .. '\n' .. message .. '\n') return nil, true end) busted.subscribe({ 'error', 'helper' }, function(element, parent, message) io.stderr:write(appName .. ': error: Cannot load helper script: ' .. element.name .. '\n' .. message .. '\n') return nil, true end) busted.subscribe({ 'error' }, function(element, parent, message) errors = errors + 1 busted.skipAll = quitOnError return nil, true end) busted.subscribe({ 'failure' }, function(element, parent, message) if element.descriptor == 'it' then failures = failures + 1 else errors = errors + 1 end busted.skipAll = quitOnError return nil, true end) -- Set up randomization options busted.sort = cliArgs['sort-tests'] busted.randomize = cliArgs['shuffle-tests'] busted.randomseed = tonumber(cliArgs.seed) or utils.urandom() or os.time() -- Set up output handler to listen to events outputHandlerLoader(busted, cliArgs.output, { defaultOutput = options.output, enableSound = cliArgs['enable-sound'], verbose = cliArgs.verbose, suppressPending = cliArgs['suppress-pending'], language = cliArgs.lang, deferPrint = cliArgs['defer-print'], arguments = cliArgs.Xoutput, }) -- Pre-load the LuaJIT 'ffi' module if applicable local isJit = (tostring(assert):match('builtin') ~= nil) if isJit then -- pre-load the ffi module, such that it becomes part of the environment -- and Busted will not try to GC and reload it. The ffi is not suited -- for that and will occasionally segfault if done so. local ffi = require "ffi" -- Now patch ffi.cdef to only be called once with each definition, as it -- will error on re-registering. local old_cdef = ffi.cdef local exists = {} ffi.cdef = function(def) if exists[def] then return end exists[def] = true return old_cdef(def) end -- Now patch ffi.typeof to only be called once with each definition, as it -- will error on re-registering. local old_typeof = ffi.typeof local exists_typeof = {} ffi.typeof = function(def) if exists_typeof[def] then return exists_typeof[def] end local ok, err = old_typeof(def) if ok then exists_typeof[def] = ok return ok end return ok, err end end -- Set up helper script if cliArgs.helper and cliArgs.helper ~= '' then helperLoader(busted, cliArgs.helper, { verbose = cliArgs.verbose, language = cliArgs.lang, arguments = cliArgs.Xhelper }) end -- Load tag and test filters filterLoader(busted, { tags = cliArgs.tags, excludeTags = cliArgs['exclude-tags'], filter = cliArgs.filter, filterOut = cliArgs['filter-out'], list = cliArgs.list, nokeepgoing = not cliArgs['keep-going'], suppressPending = cliArgs['suppress-pending'], }) if cliArgs.ROOT then -- Load test directories/files local rootFiles = cliArgs.ROOT local patterns = cliArgs.pattern local testFileLoader = require 'busted.modules.test_file_loader'(busted, cliArgs.loaders) testFileLoader(rootFiles, patterns, { excludes = cliArgs['exclude-pattern'], verbose = cliArgs.verbose, recursive = cliArgs['recursive'], }) else -- Running standalone, use standalone loader local testFileLoader = require 'busted.modules.standalone_loader'(busted) testFileLoader(info, { verbose = cliArgs.verbose }) end local runs = cliArgs['repeat'] local execute = require 'busted.execute'(busted) execute(runs, { seed = cliArgs.seed, shuffle = cliArgs['shuffle-files'], sort = cliArgs['sort-files'], }) busted.publish({ 'exit' }) if options.standalone or failures > 0 or errors > 0 then exit(failures + errors, forceExit) end end
fix(luajit) also cache the `ffi.typeof` function
fix(luajit) also cache the `ffi.typeof` function Busted already caches the `ffi.cdef` function, but `ffi.typeof` is another candidate having the same re-register problem
Lua
mit
Olivine-Labs/busted
6d1d1258a51a0514e91d7aea2477d7ea56958169
apply.lua
apply.lua
include 'ffi.lua' local ffi = require 'ffi' local kernel_source = [[ extern "C" __global__ void kernel(float* a, int n) { int i = blockIdx.x * blockDim.x + threadIdx.x; float &x = a[i]; if (i < n) LAMBDA; } ]] local CUDA_NUM_THREADS = 1024 local ptx_cache = {} local function get_blocks(N) return math.floor((N + CUDA_NUM_THREADS - 1) / CUDA_NUM_THREADS); end function torch.CudaTensor:apply(lambda) local ptx if not ptx_cache[lambda] then local kernel = kernel_source:gsub('LAMBDA', lambda) local program = ffi.new'nvrtcProgram[1]' nvrtc.errcheck(nvrtc.C.nvrtcCreateProgram(program, kernel, nil, 0, nil, nil)) nvrtc.errcheck(nvrtc.C.nvrtcCompileProgram(program[0], 0, nil)) --local log = ffi.new'char[1]' --nvrtc.errcheck(nvrtc.C.nvrtcGetProgramLog(program[0], log)) ptx = ffi.new'char[1]' nvrtc.errcheck(nvrtc.C.nvrtcGetPTX(program[0], ptx)) ptx_cache[lambda] = ptx else ptx = ptx_cache[lambda] end -- done with nvrtc, switch to Driver API local context = ffi.new'CUcontext[1]' local module = ffi.new'CUmodule[1]' local func = ffi.new'CUfunction[1]' CU.errcheck(CU.C.cuCtxGetCurrent(context)) CU.errcheck(CU.C.cuModuleLoadDataEx(module, ptx, 0, nil, nil)) CU.errcheck(CU.C.cuModuleGetFunction(func, module[0], 'kernel')) local n = ffi.new('int', self:numel()) local args = ffi.new'void*[2]' args[0] = ffi.new('float*[1]', self:data()) args[1] = ffi.new('int[1]', n) CU.errcheck(CU.C.cuLaunchKernel(func[0], CUDA_NUM_THREADS, 1, 1, get_blocks(self:numel()), 1, 1, 0, nil, args, nil)) CU.errcheck(CU.C.cuCtxSynchronize()) CU.errcheck(CU.C.cuModuleUnload(module[0])) --nvrtc.errcheck(nvrtc.C.nvrtcDestroyProgram(program)) end
include 'ffi.lua' local ffi = require 'ffi' local kernel_source = [[ extern "C" __global__ void kernel(float* a, int n) { int i = blockIdx.x * blockDim.x + threadIdx.x; float &x = a[i]; if (i < n) LAMBDA; } ]] local CUDA_NUM_THREADS = 1024 local ptx_cache = {} local function get_blocks(N) return math.floor((N + CUDA_NUM_THREADS - 1) / CUDA_NUM_THREADS); end function torch.CudaTensor:apply(lambda) local ptx if not ptx_cache[lambda] then local kernel = kernel_source:gsub('LAMBDA', lambda) local program = ffi.new'nvrtcProgram[1]' nvrtc.errcheck(nvrtc.C.nvrtcCreateProgram(program, kernel, nil, 0, nil, nil)) local err = nvrtc.C.nvrtcCompileProgram(program[0], 0, nil) if tonumber(err) == 6 then local log_size = ffi.new'size_t[1]' nvrtc.errcheck(nvrtc.C.nvrtcGetProgramLogSize(program[0], log_size)) local log = ffi.new('char[?]', tonumber(log_size[0])) nvrtc.errcheck(nvrtc.C.nvrtcGetProgramLog(program[0], log)) print(ffi.string(log)) end nvrtc.errcheck(err) local ptx_size = ffi.new'size_t[1]' nvrtc.errcheck(nvrtc.C.nvrtcGetPTXSize(program[0], ptx_size)) ptx = ffi.new('char[?]', tonumber(ptx_size[0])) nvrtc.errcheck(nvrtc.C.nvrtcGetPTX(program[0], ptx)) ptx_cache[lambda] = ptx else ptx = ptx_cache[lambda] end -- done with nvrtc, switch to Driver API local context = ffi.new'CUcontext[1]' local module = ffi.new'CUmodule[1]' local func = ffi.new'CUfunction[1]' CU.errcheck(CU.C.cuCtxGetCurrent(context)) CU.errcheck(CU.C.cuModuleLoadDataEx(module, ptx, 0, nil, nil)) CU.errcheck(CU.C.cuModuleGetFunction(func, module[0], 'kernel')) local args = ffi.new'void*[2]' args[0] = ffi.new('float*[1]', self:data()) args[1] = ffi.new('int[1]', self:numel()) CU.errcheck(CU.C.cuLaunchKernel(func[0], CUDA_NUM_THREADS, 1, 1, get_blocks(self:numel()), 1, 1, 0, nil, args, nil)) CU.errcheck(CU.C.cuCtxSynchronize()) CU.errcheck(CU.C.cuModuleUnload(module[0])) --nvrtc.errcheck(nvrtc.C.nvrtcDestroyProgram(program)) end
fixed a bug with mem alloc
fixed a bug with mem alloc
Lua
bsd-2-clause
szagoruyko/cutorch-rtc
d3f83a43d7a520ba34cb636ee37229b956d370ac
mod_register_json/mod_register_json.lua
mod_register_json/mod_register_json.lua
-- Expose a simple servlet to handle user registrations from web pages -- via JSON. -- -- A Good chunk of the code is from mod_data_access.lua by Kim Alvefur -- aka Zash. local jid_prep = require "util.jid".prep; local jid_split = require "util.jid".split; local usermanager = require "core.usermanager"; local b64_decode = require "util.encodings".base64.decode; local json_decode = require "util.json".decode; module.host = "*" -- HTTP/BOSH Servlets need to be global. -- Pick up configuration. local set_realm_name = module:get_option("reg_servlet_realm") or "Restricted"; local throttle_time = module:get_option("reg_servlet_ttime") or false; local whitelist = module:get_option("reg_servlet_wl") or {}; local blacklist = module:get_option("reg_servlet_bl") or {}; local recent_ips = {}; -- Begin for _, ip in ipairs(whitelist) do whitelisted_ips[ip] = true; end for _, ip in ipairs(blacklist) do blacklisted_ips[ip] = true; end local function http_response(code, message, extra_headers) local response = { status = code .. " " .. message; body = message .. "\n"; } if extra_headers then response.headers = extra_headers; end return response end local function handle_req(method, body, request) if request.method ~= "POST" then return http_response(405, "Bad method...", {["Allow"] = "POST"}); end if not request.headers["authorization"] then return http_response(401, "No... No...", {["WWW-Authenticate"]='Basic realm="'.. set_realm_name ..'"'}) end local user, password = b64_decode(request.headers.authorization :match("[^ ]*$") or ""):match("([^:]*):(.*)"); user = jid_prep(user); if not user or not password then return http_response(400, "What's this..?"); end local user_node, user_host = jid_split(user) if not hosts[user_host] then return http_response(401, "Negative."); end module:log("warn", "%s is authing to submit a new user registration data", user) if not usermanager.test_password(user_node, user_host, password) then module:log("warn", "%s failed authentication", user) return http_response(401, "Who the hell are you?! Guards!"); end local req_body; -- We check that what we have is valid JSON wise else we throw an error... if not pcall(function() req_body = json_decode(body) end) then module:log("debug", "JSON data submitted for user registration by %s failed to Decode.", user); return http_response(400, "JSON Decoding failed."); else -- Check if user is an admin of said host if not usermanager.is_admin(user, req_body["host"]) then module:log("warn", "%s tried to submit registration data for %s but he's not an admin", user, req_body["host"]); return http_response(401, "I obey only to my masters... Have a nice day."); else -- Checks for both Throttling/Whitelist and Blacklist (basically copycatted from prosody's register.lua code) if blacklist[req_body["ip"]] then module:log("warn", "Attempt of reg. submission to the JSON servlet from blacklisted address: %s", req_body["ip"]); return http_response(403, "The specified address is blacklisted, sorry sorry."); end if throttle_time and not whitelist[req_body["ip"]] then if not recent_ips[req_body["ip"]] then recent_ips[req_body["ip"]] = { time = os_time(), count = 1 }; else local ip = recent_ips[req_body["ip"]]; ip.count = ip.count + 1; if os_time() - ip.time < throttle_time then ip.time = os_time(); module:log("warn", "JSON Registration request from %s has been throttled.", req_body["ip"]); return http_response(503, "Woah... How many users you want to register..? Request throttled, wait a bit and try again."); end ip.time = os_time(); end end -- We first check if the supplied username for registration is already there. if not usermanager.user_exists(req_body["username"], req_body["host"]) then usermanager.create_user(req_body["username"], req_body["password"], req_body["host"]); module:log("debug", "%s registration data submission for %s is successful", user, req_body["user"]); return http_response(200, "Done."); else module:log("debug", "%s registration data submission for %s failed (user already exists)", user, req_body["user"]); return http_response(409, "User already exists."); end end end end -- Set it up! local function setup() local ports = module:get_option("reg_servlet_port") or { 9280 }; local base_name = module:get_option("reg_servlet_base") or "register_account"; local ssl_cert = module:get_option("reg_servlet_sslcert") or false; local ssl_key = module:get_option("reg_servlet_sslkey") or false; if not ssl_cert or not ssl_key then require "net.httpserver".new_from_config(ports, handle_req, { base = base_name }); else if module:get_option("reg_servlet_port") == nil then ports = { 9443 }; end require "net.httpserver".new_from_config(ports, handle_req, { ssl = { key = ssl_key, certificate = ssl_cert }, base = base_name }); end end if prosody.start_time then -- already started setup(); else prosody.events.add_handler("server-started", setup); end
-- Expose a simple servlet to handle user registrations from web pages -- via JSON. -- -- A Good chunk of the code is from mod_data_access.lua by Kim Alvefur -- aka Zash. local jid_prep = require "util.jid".prep; local jid_split = require "util.jid".split; local usermanager = require "core.usermanager"; local b64_decode = require "util.encodings".base64.decode; local json_decode = require "util.json".decode; module.host = "*" -- HTTP/BOSH Servlets need to be global. -- Pick up configuration. local set_realm_name = module:get_option("reg_servlet_realm") or "Restricted"; local throttle_time = module:get_option("reg_servlet_ttime") or false; local whitelist = module:get_option("reg_servlet_wl") or {}; local blacklist = module:get_option("reg_servlet_bl") or {}; local recent_ips = {}; -- Begin for _, ip in ipairs(whitelist) do whitelisted_ips[ip] = true; end for _, ip in ipairs(blacklist) do blacklisted_ips[ip] = true; end local function http_response(code, message, extra_headers) local response = { status = code .. " " .. message; body = message .. "\n"; } if extra_headers then response.headers = extra_headers; end return response end local function handle_req(method, body, request) if request.method ~= "POST" then return http_response(405, "Bad method...", {["Allow"] = "POST"}); end if not request.headers["authorization"] then return http_response(401, "No... No...", {["WWW-Authenticate"]='Basic realm="'.. set_realm_name ..'"'}) end local user, password = b64_decode(request.headers.authorization :match("[^ ]*$") or ""):match("([^:]*):(.*)"); user = jid_prep(user); if not user or not password then return http_response(400, "What's this..?"); end local user_node, user_host = jid_split(user) if not hosts[user_host] then return http_response(401, "Negative."); end module:log("warn", "%s is authing to submit a new user registration data", user) if not usermanager.test_password(user_node, user_host, password) then module:log("warn", "%s failed authentication", user) return http_response(401, "Who the hell are you?! Guards!"); end local req_body; -- We check that what we have is valid JSON wise else we throw an error... if not pcall(function() req_body = json_decode(body) end) then module:log("debug", "JSON data submitted for user registration by %s failed to Decode.", user); return http_response(400, "JSON Decoding failed."); else -- Decode JSON data and check that all bits are there else throw an error req_body = json_decode(body); if req_body["username"] == nil or req_body["password"] == nil or req_body["host"] == nil or req_body["ip"] == nil then module:log("debug", "%s supplied an insufficent number of elements or wrong elements for the JSON registration", user); return http_response(400, "Invalid syntax."); end -- Check if user is an admin of said host if not usermanager.is_admin(user, req_body["host"]) then module:log("warn", "%s tried to submit registration data for %s but he's not an admin", user, req_body["host"]); return http_response(401, "I obey only to my masters... Have a nice day."); else -- Checks for both Throttling/Whitelist and Blacklist (basically copycatted from prosody's register.lua code) if blacklist[req_body["ip"]] then module:log("warn", "Attempt of reg. submission to the JSON servlet from blacklisted address: %s", req_body["ip"]); return http_response(403, "The specified address is blacklisted, sorry sorry."); end if throttle_time and not whitelist[req_body["ip"]] then if not recent_ips[req_body["ip"]] then recent_ips[req_body["ip"]] = { time = os_time(), count = 1 }; else local ip = recent_ips[req_body["ip"]]; ip.count = ip.count + 1; if os_time() - ip.time < throttle_time then ip.time = os_time(); module:log("warn", "JSON Registration request from %s has been throttled.", req_body["ip"]); return http_response(503, "Woah... How many users you want to register..? Request throttled, wait a bit and try again."); end ip.time = os_time(); end end -- We first check if the supplied username for registration is already there. if not usermanager.user_exists(req_body["username"], req_body["host"]) then usermanager.create_user(req_body["username"], req_body["password"], req_body["host"]); module:log("debug", "%s registration data submission for %s is successful", user, req_body["user"]); return http_response(200, "Done."); else module:log("debug", "%s registration data submission for %s failed (user already exists)", user, req_body["user"]); return http_response(409, "User already exists."); end end end end -- Set it up! local function setup() local ports = module:get_option("reg_servlet_port") or { 9280 }; local base_name = module:get_option("reg_servlet_base") or "register_account"; local ssl_cert = module:get_option("reg_servlet_sslcert") or false; local ssl_key = module:get_option("reg_servlet_sslkey") or false; if not ssl_cert or not ssl_key then require "net.httpserver".new_from_config(ports, handle_req, { base = base_name }); else if module:get_option("reg_servlet_port") == nil then ports = { 9443 }; end require "net.httpserver".new_from_config(ports, handle_req, { ssl = { key = ssl_key, certificate = ssl_cert }, base = base_name }); end end if prosody.start_time then -- already started setup(); else prosody.events.add_handler("server-started", setup); end
mod_register_json: Let's call it the first commit, fixed all code errors (aka it works).
mod_register_json: Let's call it the first commit, fixed all code errors (aka it works).
Lua
mit
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
acca2c3115570e7f3b1ef059413c4dce49c520d1
xmake/actions/create/main.lua
xmake/actions/create/main.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-2020, TBOOX Open Source Group. -- -- @author ruki -- @file main.lua -- -- imports import("core.base.option") import("core.project.project") import("core.project.template") -- get the builtin variables function _get_builtinvars(tempinst, targetname) return {TARGETNAME = targetname, FAQ = function() return io.readfile(path.join(os.programdir(), "scripts", "faq.lua")) end} end -- create project from template function _create_project(language, templateid, targetname) -- check the language assert(language, "no language!") -- check the template id assert(templateid, "no template id!") -- load all templates for the given language local templates = template.templates(language) -- TODO: deprecated -- in order to be compatible with the old version template local templates_new = { quickapp_qt = "qt.quickapp", widgetapp_qt = "qt.widgetapp", console_qt = "qt.console", static_qt = "qt.static", shared_qt = "qt.shared", console_tbox = "tbox.console", static_tbox = "tbox.static", shared_tbox = "tbox.shared"} if templates_new[templateid] then cprint("${yellow}deprecated: please uses template(%s) instead of template(%s)!", templates_new[templateid], templateid) templateid = templates_new[templateid] end -- get the given template instance local tempinst = nil if templates then for _, t in ipairs(templates) do if t:name() == templateid then tempinst = t break end end end assert(tempinst and tempinst:scriptdir(), "invalid template id: %s!", templateid) -- get project directory local projectdir = path.absolute(option.get("project") or path.join(os.curdir(), targetname)) if not os.isdir(projectdir) then -- make the project directory if not exists os.mkdir(projectdir) elseif not os.emptydir(projectdir) then -- otherwise, check whether it is empty raise("project directory (${underline}%s${reset}) is not empty!", path.relative(projectdir, os.workingdir())) end -- enter the project directory os.cd(projectdir) -- create project local filedirs = {} local sourcedir = path.join(tempinst:scriptdir(), "project") if os.isdir(sourcedir) then for _, filedir in ipairs(os.filedirs(path.join(sourcedir, "*"))) do os.cp(filedir, projectdir) table.insert(filedirs, path.relative(filedir, sourcedir)) end os.cp(path.join(os.programdir(), "scripts", "gitignore"), path.join(projectdir, ".gitignore")) table.insert(filedirs, ".gitignore") else raise("template(%s): project not found!", templateid) end -- get the builtin variables local builtinvars = _get_builtinvars(tempinst, targetname) -- replace all variables for _, configfile in ipairs(tempinst:get("configfiles")) do local pattern = "%${(.-)}" io.gsub(configfile, "(" .. pattern .. ")", function(_, variable) variable = variable:trim() local value = builtinvars[variable] return type(value) == "function" and value() or value end) end -- do after_create local after_create = tempinst:get("create_after") if after_create then after_create(tempinst, {targetname = targetname}) end -- trace for _, filedir in ipairs(filedirs) do if os.isdir(filedir) then for _, file in ipairs(os.files(path.join(filedir, "**"))) do cprint(" ${green}[+]: ${clear}%s", file) end else cprint(" ${green}[+]: ${clear}%s", filedir) end end end -- main function main() -- enter the original working directory, because the default directory is in the project directory os.cd(os.workingdir()) -- the target name local targetname = option.get("target") or path.basename(project.directory()) or "demo" -- trace cprint("${bright}create %s ...", targetname) -- create project from template _create_project(option.get("language"), option.get("template"), targetname) -- trace cprint("${color.success}create ok!") 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-2020, TBOOX Open Source Group. -- -- @author ruki -- @file main.lua -- -- imports import("core.base.option") import("core.project.project") import("core.project.template") -- get the builtin variables function _get_builtinvars(tempinst, targetname) return {TARGETNAME = targetname, FAQ = function() return io.readfile(path.join(os.programdir(), "scripts", "faq.lua")) end} end -- create project from template function _create_project(language, templateid, targetname) -- check the language assert(language, "no language!") -- check the template id assert(templateid, "no template id!") -- load all templates for the given language local templates = template.templates(language) -- TODO: deprecated -- in order to be compatible with the old version template local templates_new = { quickapp_qt = "qt.quickapp", widgetapp_qt = "qt.widgetapp", console_qt = "qt.console", static_qt = "qt.static", shared_qt = "qt.shared", console_tbox = "tbox.console", static_tbox = "tbox.static", shared_tbox = "tbox.shared"} if templates_new[templateid] then cprint("${yellow}deprecated: please uses template(%s) instead of template(%s)!", templates_new[templateid], templateid) templateid = templates_new[templateid] end -- get the given template instance local tempinst = nil if templates then for _, t in ipairs(templates) do if t:name() == templateid then tempinst = t break end end end assert(tempinst and tempinst:scriptdir(), "invalid template id: %s!", templateid) -- get project directory local projectdir = path.absolute(option.get("project") or path.join(os.curdir(), targetname)) if not os.isdir(projectdir) then -- make the project directory if not exists os.mkdir(projectdir) end -- xmake.lua exists? if os.isfile(path.join(projectdir, "xmake.lua")) then raise("project (${underline}%s/xmake.lua${reset}) exists!", projectdir) end -- empty project? os.tryrm(path.join(projectdir, ".xmake")) if not os.emptydir(projectdir) then -- otherwise, check whether it is empty raise("project directory (${underline}%s${reset}) is not empty!", projectdir) end -- enter the project directory os.cd(projectdir) -- create project local filedirs = {} local sourcedir = path.join(tempinst:scriptdir(), "project") if os.isdir(sourcedir) then for _, filedir in ipairs(os.filedirs(path.join(sourcedir, "*"))) do os.cp(filedir, projectdir) table.insert(filedirs, path.relative(filedir, sourcedir)) end os.cp(path.join(os.programdir(), "scripts", "gitignore"), path.join(projectdir, ".gitignore")) table.insert(filedirs, ".gitignore") else raise("template(%s): project not found!", templateid) end -- get the builtin variables local builtinvars = _get_builtinvars(tempinst, targetname) -- replace all variables for _, configfile in ipairs(tempinst:get("configfiles")) do local pattern = "%${(.-)}" io.gsub(configfile, "(" .. pattern .. ")", function(_, variable) variable = variable:trim() local value = builtinvars[variable] return type(value) == "function" and value() or value end) end -- do after_create local after_create = tempinst:get("create_after") if after_create then after_create(tempinst, {targetname = targetname}) end -- trace for _, filedir in ipairs(filedirs) do if os.isdir(filedir) then for _, file in ipairs(os.files(path.join(filedir, "**"))) do cprint(" ${green}[+]: ${clear}%s", file) end else cprint(" ${green}[+]: ${clear}%s", filedir) end end end -- main function main() -- enter the original working directory, because the default directory is in the project directory os.cd(os.workingdir()) -- the target name local targetname = option.get("target") or path.basename(project.directory()) or "demo" -- trace cprint("${bright}create %s ...", targetname) -- create project from template _create_project(option.get("language"), option.get("template"), targetname) -- trace cprint("${color.success}create ok!") end
fix create project
fix create project
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
5f0ecfe984f0e69095a4e888913fe2da38b13ccc
libs/uvl/luasrc/uvl/errors.lua
libs/uvl/luasrc/uvl/errors.lua
--[[ UCI Validation Layer - Error handling (c) 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> (c) 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local uci = require "luci.model.uci" local uvl = require "luci.uvl" local util = require "luci.util" local string = require "string" local ipairs, error, type = ipairs, error, type local tonumber, unpack = tonumber, unpack local luci = luci module "luci.uvl.errors" ERRCODES = { { 'UCILOAD', 'Unable to load config "%p": %1' }, { 'SCHEME', 'Error in scheme "%p":\n%c' }, { 'CONFIG', 'Error in config "%p":\n%c' }, { 'SECTION', 'Error in section "%i" (%I):\n%c' }, { 'OPTION', 'Error in option "%i" (%I):\n%c' }, { 'REFERENCE', 'Option "%i" has invalid reference specification %1:\n%c' }, { 'DEPENDENCY', 'In dependency check for %t "%i":\n%c' }, { 'SME_FIND', 'Can not find scheme "%p" in "%1"' }, { 'SME_READ', 'Can not access file "%1"' }, { 'SME_REQFLD', 'Missing required scheme field "%1" in "%i"' }, { 'SME_INVREF', 'Illegal reference "%1" to an anonymous section' }, { 'SME_BADREF', 'Malformed reference in "%1"' }, { 'SME_BADDEP', 'Malformed dependency specification "%1" in "%i"' }, { 'SME_BADVAL', 'Malformed validator specification "%1" in "%i"' }, { 'SME_ERRVAL', 'External validator "%1" failed: %2' }, { 'SME_VBADPACK', 'Variable "%o" in scheme "%p" references unknown package "%1"' }, { 'SME_VBADSECT', 'Variable "%o" in scheme "%p" references unknown section "%1"' }, { 'SME_EBADPACK', 'Enum "%v" in scheme "%p" references unknown package "%1"' }, { 'SME_EBADSECT', 'Enum "%v" in scheme "%p" references unknown section "%1"' }, { 'SME_EBADOPT', 'Enum "%v" in scheme "%p" references unknown option "%1"' }, { 'SME_EBADTYPE', 'Enum "%v" in scheme "%p" references non-enum option "%I"' }, { 'SME_EBADDEF', 'Enum "%v" in scheme "%p" redeclares the default value of "%I"' }, { 'SECT_UNKNOWN', 'Section "%i" (%I) not found in scheme' }, { 'SECT_REQUIRED', 'Required section "%p.%S" not found in config' }, { 'SECT_UNIQUE', 'Unique section "%p.%S" occurs multiple times in config' }, { 'SECT_NAMED', 'The section of type "%p.%S" is stored anonymously in config but must be named' }, { 'SECT_NOTFOUND', 'Section "%p.%s" not found in config' }, { 'OPT_UNKNOWN', 'Option "%i" (%I) not found in scheme' }, { 'OPT_REQUIRED', 'Required option "%i" has no value' }, { 'OPT_BADVALUE', 'Value "%1" of option "%i" is not defined in enum %2' }, { 'OPT_INVVALUE', 'Value "%1" of option "%i" does not validate as datatype "%2"' }, { 'OPT_NOTLIST', 'Option "%i" is defined as list but stored as plain value' }, { 'OPT_DATATYPE', 'Option "%i" has unknown datatype "%1"' }, { 'OPT_NOTFOUND', 'Option "%p.%s.%o" not found in config' }, { 'OPT_RANGE', 'Option "%p.%s.%o" is not within the specified range' }, { 'DEP_NOTEQUAL', 'Dependency (%1) failed:\nOption "%i" is not eqal "%2"' }, { 'DEP_NOVALUE', 'Dependency (%1) failed:\nOption "%i" has no value' }, { 'DEP_NOTVALID', 'Dependency (%1) failed:\n%c' }, { 'DEP_RECURSIVE', 'Recursive dependency for option "%i" detected' }, { 'DEP_BADENUM', 'In dependency check for enum value "%i":\n%c' } } -- build error constants and instance constructors for i, v in ipairs(ERRCODES) do _M[v[1]] = function(...) return error(i, ...) end _M['ERR_'..v[1]] = i end function i18n(key, def) if luci.i18n then return luci.i18n.translate(key,def) else return def end end error = util.class() function error.__init__(self, code, pso, args) self.code = code self.args = ( type(args) == "table" and args or { args } ) if util.instanceof( pso, uvl.uvlitem ) then self.stype = pso.sref[2] self.package, self.section, self.option, self.value = unpack(pso.cref) self.object = pso self.value = self.value or ( pso.value and pso:value() ) else pso = ( type(pso) == "table" and pso or { pso } ) if pso[2] then local uci = uci.cursor() self.stype = uci:get(pso[1], pso[2]) or pso[2] end self.package, self.section, self.option, self.value = unpack(pso) end end function error.child(self, err) if not self.childs then self.childs = { err } else self.childs[#self.childs+1] = err end return self end function error.string(self,pad) pad = pad or " " local str = i18n( 'uvl_err_%s' % string.lower(ERRCODES[self.code][1]), ERRCODES[self.code][2] ) :gsub("\n", "\n"..pad) :gsub("%%i", self:cid()) :gsub("%%I", self:sid()) :gsub("%%p", self.package or '(nil)') :gsub("%%s", self.section or '(nil)') :gsub("%%S", self.stype or '(nil)') :gsub("%%o", self.option or '(nil)') :gsub("%%v", self.value or '(nil)') :gsub("%%t", self.object and self.object:type() or '(nil)' ) :gsub("%%T", self.object and self.object:title() or '(nil)' ) :gsub("%%([1-9])", function(n) return self.args[tonumber(n)] or '(nil)' end) :gsub("%%c", function() local s = "" for _, err in ipairs(self.childs or {}) do s = s .. err:string(pad.." ") .. "\n" .. pad end return s end ) return (str:gsub("%s+$","")) end function error.cid(self) return self.object and self.object:cid() or self.package .. ( self.section and '.' .. self.section or '' ) .. ( self.option and '.' .. self.option or '' ) .. ( self.value and '.' .. self.value or '' ) end function error.sid(self) return self.object and self.object:sid() or self.package .. ( self.stype and '.' .. self.stype or '' ) .. ( self.option and '.' .. self.option or '' ) .. ( self.value and '.' .. self.value or '' ) end function error.is(self, code) if self.code == code then return true elseif self.childs then for _, c in ipairs(self.childs) do if c:is(code) then return true end end end return false end function error.is_all(self, ...) local codes = { ... } if util.contains(codes, self.code) then return true else local equal = false for _, c in ipairs(self.childs) do if c.childs then equal = c:is_all(...) else equal = util.contains(codes, c.code) end end return equal end end
--[[ UCI Validation Layer - Error handling (c) 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> (c) 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local uci = require "luci.model.uci" local uvl = require "luci.uvl" local util = require "luci.util" local string = require "string" local ipairs, error, type = ipairs, error, type local tonumber, unpack = tonumber, unpack local luci = luci module "luci.uvl.errors" ERRCODES = { { 'UCILOAD', 'Unable to load config "%p": %1' }, { 'SCHEME', 'Error in scheme "%p":\n%c' }, { 'CONFIG', 'Error in config "%p":\n%c' }, { 'SECTION', 'Error in section "%i" (%I):\n%c' }, { 'OPTION', 'Error in option "%i" (%I):\n%c' }, { 'REFERENCE', 'Option "%i" has invalid reference specification %1:\n%c' }, { 'DEPENDENCY', 'In dependency check for %t "%i":\n%c' }, { 'SME_FIND', 'Can not find scheme "%p" in "%1"' }, { 'SME_READ', 'Can not access file "%1"' }, { 'SME_REQFLD', 'Missing required scheme field "%1" in "%i"' }, { 'SME_INVREF', 'Illegal reference "%1" to an anonymous section' }, { 'SME_BADREF', 'Malformed reference in "%1"' }, { 'SME_BADDEP', 'Malformed dependency specification "%1" in "%i"' }, { 'SME_BADVAL', 'Malformed validator specification "%1" in "%i"' }, { 'SME_ERRVAL', 'External validator "%1" failed: %2' }, { 'SME_VBADPACK', 'Variable "%o" in scheme "%p" references unknown package "%1"' }, { 'SME_VBADSECT', 'Variable "%o" in scheme "%p" references unknown section "%1"' }, { 'SME_EBADPACK', 'Enum "%v" in scheme "%p" references unknown package "%1"' }, { 'SME_EBADSECT', 'Enum "%v" in scheme "%p" references unknown section "%1"' }, { 'SME_EBADOPT', 'Enum "%v" in scheme "%p" references unknown option "%1"' }, { 'SME_EBADTYPE', 'Enum "%v" in scheme "%p" references non-enum option "%I"' }, { 'SME_EBADDEF', 'Enum "%v" in scheme "%p" redeclares the default value of "%I"' }, { 'SECT_UNKNOWN', 'Section "%i" (%I) not found in scheme' }, { 'SECT_REQUIRED', 'Required section "%p.%S" not found in config' }, { 'SECT_UNIQUE', 'Unique section "%p.%S" occurs multiple times in config' }, { 'SECT_NAMED', 'The section of type "%p.%S" is stored anonymously in config but must be named' }, { 'SECT_NOTFOUND', 'Section "%p.%s" not found in config' }, { 'OPT_UNKNOWN', 'Option "%i" (%I) not found in scheme' }, { 'OPT_REQUIRED', 'Required option "%i" has no value' }, { 'OPT_BADVALUE', 'Value "%1" of option "%i" is not defined in enum %2' }, { 'OPT_INVVALUE', 'Value "%1" of option "%i" does not validate as datatype "%2"' }, { 'OPT_NOTLIST', 'Option "%i" is defined as list but stored as plain value' }, { 'OPT_DATATYPE', 'Option "%i" has unknown datatype "%1"' }, { 'OPT_NOTFOUND', 'Option "%p.%s.%o" not found in config' }, { 'OPT_RANGE', 'Option "%p.%s.%o" is not within the specified range' }, { 'DEP_NOTEQUAL', 'Dependency (%1) failed:\nOption "%i" is not eqal "%2"' }, { 'DEP_NOVALUE', 'Dependency (%1) failed:\nOption "%i" has no value' }, { 'DEP_NOTVALID', 'Dependency (%1) failed:\n%c' }, { 'DEP_RECURSIVE', 'Recursive dependency for option "%i" detected' }, { 'DEP_BADENUM', 'In dependency check for enum value "%i":\n%c' } } -- build error constants and instance constructors for i, v in ipairs(ERRCODES) do _M[v[1]] = function(...) return error(i, ...) end _M['ERR_'..v[1]] = i end function i18n(key) if luci.i18n then return luci.i18n.translate(key) else return key end end error = util.class() function error.__init__(self, code, pso, args) self.code = code self.args = ( type(args) == "table" and args or { args } ) if util.instanceof( pso, uvl.uvlitem ) then self.stype = pso.sref[2] self.package, self.section, self.option, self.value = unpack(pso.cref) self.object = pso self.value = self.value or ( pso.value and pso:value() ) else pso = ( type(pso) == "table" and pso or { pso } ) if pso[2] then local uci = uci.cursor() self.stype = uci:get(pso[1], pso[2]) or pso[2] end self.package, self.section, self.option, self.value = unpack(pso) end end function error.child(self, err) if not self.childs then self.childs = { err } else self.childs[#self.childs+1] = err end return self end function error.string(self,pad) pad = pad or " " local str = i18n(ERRCODES[self.code][2]) :gsub("\n", "\n"..pad) :gsub("%%i", self:cid()) :gsub("%%I", self:sid()) :gsub("%%p", self.package or '(nil)') :gsub("%%s", self.section or '(nil)') :gsub("%%S", self.stype or '(nil)') :gsub("%%o", self.option or '(nil)') :gsub("%%v", self.value or '(nil)') :gsub("%%t", self.object and self.object:type() or '(nil)' ) :gsub("%%T", self.object and self.object:title() or '(nil)' ) :gsub("%%([1-9])", function(n) return self.args[tonumber(n)] or '(nil)' end) :gsub("%%c", function() local s = "" for _, err in ipairs(self.childs or {}) do s = s .. err:string(pad.." ") .. "\n" .. pad end return s end ) return (str:gsub("%s+$","")) end function error.cid(self) return self.object and self.object:cid() or self.package .. ( self.section and '.' .. self.section or '' ) .. ( self.option and '.' .. self.option or '' ) .. ( self.value and '.' .. self.value or '' ) end function error.sid(self) return self.object and self.object:sid() or self.package .. ( self.stype and '.' .. self.stype or '' ) .. ( self.option and '.' .. self.option or '' ) .. ( self.value and '.' .. self.value or '' ) end function error.is(self, code) if self.code == code then return true elseif self.childs then for _, c in ipairs(self.childs) do if c:is(code) then return true end end end return false end function error.is_all(self, ...) local codes = { ... } if util.contains(codes, self.code) then return true else local equal = false for _, c in ipairs(self.childs) do if c.childs then equal = c:is_all(...) else equal = util.contains(codes, c.code) end end return equal end end
libs/uvl: fix i18n handling for errors
libs/uvl: fix i18n handling for errors
Lua
apache-2.0
taiha/luci,openwrt-es/openwrt-luci,lcf258/openwrtcn,lcf258/openwrtcn,aa65535/luci,RedSnake64/openwrt-luci-packages,thesabbir/luci,taiha/luci,male-puppies/luci,NeoRaider/luci,cshore/luci,jlopenwrtluci/luci,Hostle/openwrt-luci-multi-user,bright-things/ionic-luci,tobiaswaldvogel/luci,keyidadi/luci,sujeet14108/luci,nmav/luci,teslamint/luci,hnyman/luci,florian-shellfire/luci,jorgifumi/luci,thess/OpenWrt-luci,oyido/luci,tcatm/luci,lbthomsen/openwrt-luci,openwrt/luci,tcatm/luci,artynet/luci,ollie27/openwrt_luci,florian-shellfire/luci,zhaoxx063/luci,teslamint/luci,db260179/openwrt-bpi-r1-luci,palmettos/test,opentechinstitute/luci,lcf258/openwrtcn,kuoruan/lede-luci,nwf/openwrt-luci,ollie27/openwrt_luci,lcf258/openwrtcn,Wedmer/luci,cshore/luci,ReclaimYourPrivacy/cloak-luci,sujeet14108/luci,Sakura-Winkey/LuCI,db260179/openwrt-bpi-r1-luci,Hostle/luci,cshore-firmware/openwrt-luci,MinFu/luci,LazyZhu/openwrt-luci-trunk-mod,nmav/luci,RedSnake64/openwrt-luci-packages,bright-things/ionic-luci,remakeelectric/luci,ReclaimYourPrivacy/cloak-luci,kuoruan/lede-luci,fkooman/luci,marcel-sch/luci,florian-shellfire/luci,obsy/luci,marcel-sch/luci,palmettos/cnLuCI,zhaoxx063/luci,forward619/luci,LazyZhu/openwrt-luci-trunk-mod,ReclaimYourPrivacy/cloak-luci,schidler/ionic-luci,dismantl/luci-0.12,shangjiyu/luci-with-extra,Sakura-Winkey/LuCI,opentechinstitute/luci,obsy/luci,male-puppies/luci,MinFu/luci,NeoRaider/luci,dismantl/luci-0.12,sujeet14108/luci,ReclaimYourPrivacy/cloak-luci,Wedmer/luci,Hostle/openwrt-luci-multi-user,jlopenwrtluci/luci,urueedi/luci,Noltari/luci,nwf/openwrt-luci,tcatm/luci,kuoruan/luci,palmettos/test,ff94315/luci-1,chris5560/openwrt-luci,LuttyYang/luci,fkooman/luci,male-puppies/luci,thess/OpenWrt-luci,artynet/luci,openwrt/luci,ff94315/luci-1,LuttyYang/luci,male-puppies/luci,lbthomsen/openwrt-luci,nwf/openwrt-luci,mumuqz/luci,bittorf/luci,ff94315/luci-1,tcatm/luci,Wedmer/luci,bright-things/ionic-luci,981213/luci-1,RedSnake64/openwrt-luci-packages,Wedmer/luci,opentechinstitute/luci,david-xiao/luci,Hostle/openwrt-luci-multi-user,cappiewu/luci,schidler/ionic-luci,kuoruan/luci,Noltari/luci,openwrt/luci,fkooman/luci,marcel-sch/luci,marcel-sch/luci,dwmw2/luci,obsy/luci,nwf/openwrt-luci,jchuang1977/luci-1,kuoruan/luci,openwrt-es/openwrt-luci,aircross/OpenWrt-Firefly-LuCI,lbthomsen/openwrt-luci,Noltari/luci,maxrio/luci981213,daofeng2015/luci,david-xiao/luci,nmav/luci,harveyhu2012/luci,artynet/luci,thess/OpenWrt-luci,wongsyrone/luci-1,male-puppies/luci,kuoruan/luci,david-xiao/luci,Sakura-Winkey/LuCI,rogerpueyo/luci,opentechinstitute/luci,cshore-firmware/openwrt-luci,Sakura-Winkey/LuCI,cshore/luci,cappiewu/luci,MinFu/luci,thesabbir/luci,ollie27/openwrt_luci,Sakura-Winkey/LuCI,lcf258/openwrtcn,oyido/luci,NeoRaider/luci,joaofvieira/luci,aa65535/luci,artynet/luci,david-xiao/luci,dismantl/luci-0.12,rogerpueyo/luci,hnyman/luci,aircross/OpenWrt-Firefly-LuCI,tobiaswaldvogel/luci,harveyhu2012/luci,shangjiyu/luci-with-extra,ff94315/luci-1,kuoruan/lede-luci,jorgifumi/luci,mumuqz/luci,dwmw2/luci,david-xiao/luci,RuiChen1113/luci,cshore-firmware/openwrt-luci,aa65535/luci,daofeng2015/luci,fkooman/luci,taiha/luci,thess/OpenWrt-luci,remakeelectric/luci,shangjiyu/luci-with-extra,dismantl/luci-0.12,palmettos/cnLuCI,MinFu/luci,Noltari/luci,joaofvieira/luci,joaofvieira/luci,jlopenwrtluci/luci,aa65535/luci,wongsyrone/luci-1,oneru/luci,daofeng2015/luci,db260179/openwrt-bpi-r1-luci,bittorf/luci,openwrt-es/openwrt-luci,aa65535/luci,aa65535/luci,slayerrensky/luci,jlopenwrtluci/luci,palmettos/cnLuCI,teslamint/luci,wongsyrone/luci-1,db260179/openwrt-bpi-r1-luci,schidler/ionic-luci,keyidadi/luci,kuoruan/lede-luci,cshore/luci,ollie27/openwrt_luci,oneru/luci,bittorf/luci,LazyZhu/openwrt-luci-trunk-mod,Kyklas/luci-proto-hso,remakeelectric/luci,florian-shellfire/luci,RuiChen1113/luci,remakeelectric/luci,zhaoxx063/luci,palmettos/test,Noltari/luci,dwmw2/luci,Wedmer/luci,palmettos/test,ollie27/openwrt_luci,LuttyYang/luci,thess/OpenWrt-luci,cappiewu/luci,981213/luci-1,bright-things/ionic-luci,bittorf/luci,thesabbir/luci,openwrt-es/openwrt-luci,MinFu/luci,keyidadi/luci,wongsyrone/luci-1,florian-shellfire/luci,RuiChen1113/luci,ReclaimYourPrivacy/cloak-luci,Noltari/luci,taiha/luci,nwf/openwrt-luci,david-xiao/luci,teslamint/luci,openwrt-es/openwrt-luci,Kyklas/luci-proto-hso,Wedmer/luci,aa65535/luci,cshore-firmware/openwrt-luci,daofeng2015/luci,urueedi/luci,forward619/luci,marcel-sch/luci,tobiaswaldvogel/luci,lcf258/openwrtcn,cshore-firmware/openwrt-luci,LuttyYang/luci,lcf258/openwrtcn,jorgifumi/luci,thess/OpenWrt-luci,artynet/luci,jchuang1977/luci-1,artynet/luci,thesabbir/luci,rogerpueyo/luci,mumuqz/luci,openwrt-es/openwrt-luci,thesabbir/luci,Kyklas/luci-proto-hso,joaofvieira/luci,Hostle/luci,keyidadi/luci,NeoRaider/luci,nmav/luci,artynet/luci,oneru/luci,jlopenwrtluci/luci,Hostle/luci,Hostle/luci,Hostle/openwrt-luci-multi-user,MinFu/luci,tobiaswaldvogel/luci,slayerrensky/luci,Kyklas/luci-proto-hso,nmav/luci,tobiaswaldvogel/luci,bright-things/ionic-luci,ff94315/luci-1,cappiewu/luci,db260179/openwrt-bpi-r1-luci,opentechinstitute/luci,kuoruan/luci,Sakura-Winkey/LuCI,wongsyrone/luci-1,zhaoxx063/luci,aircross/OpenWrt-Firefly-LuCI,maxrio/luci981213,Noltari/luci,cshore/luci,thess/OpenWrt-luci,cshore-firmware/openwrt-luci,forward619/luci,schidler/ionic-luci,remakeelectric/luci,LuttyYang/luci,openwrt/luci,tobiaswaldvogel/luci,cshore-firmware/openwrt-luci,shangjiyu/luci-with-extra,mumuqz/luci,maxrio/luci981213,obsy/luci,sujeet14108/luci,harveyhu2012/luci,male-puppies/luci,oneru/luci,maxrio/luci981213,shangjiyu/luci-with-extra,chris5560/openwrt-luci,keyidadi/luci,rogerpueyo/luci,chris5560/openwrt-luci,hnyman/luci,chris5560/openwrt-luci,981213/luci-1,NeoRaider/luci,cshore/luci,harveyhu2012/luci,aircross/OpenWrt-Firefly-LuCI,schidler/ionic-luci,bittorf/luci,lcf258/openwrtcn,LazyZhu/openwrt-luci-trunk-mod,RedSnake64/openwrt-luci-packages,kuoruan/lede-luci,palmettos/test,harveyhu2012/luci,rogerpueyo/luci,palmettos/cnLuCI,cshore/luci,nmav/luci,jchuang1977/luci-1,Kyklas/luci-proto-hso,obsy/luci,LuttyYang/luci,jchuang1977/luci-1,sujeet14108/luci,Wedmer/luci,ollie27/openwrt_luci,palmettos/cnLuCI,jorgifumi/luci,rogerpueyo/luci,zhaoxx063/luci,dwmw2/luci,db260179/openwrt-bpi-r1-luci,wongsyrone/luci-1,fkooman/luci,RuiChen1113/luci,harveyhu2012/luci,deepak78/new-luci,oyido/luci,tobiaswaldvogel/luci,dwmw2/luci,jlopenwrtluci/luci,tcatm/luci,oneru/luci,shangjiyu/luci-with-extra,openwrt-es/openwrt-luci,cshore/luci,deepak78/new-luci,openwrt-es/openwrt-luci,Noltari/luci,oneru/luci,openwrt/luci,daofeng2015/luci,db260179/openwrt-bpi-r1-luci,slayerrensky/luci,lbthomsen/openwrt-luci,hnyman/luci,wongsyrone/luci-1,thesabbir/luci,teslamint/luci,Hostle/openwrt-luci-multi-user,palmettos/cnLuCI,david-xiao/luci,thess/OpenWrt-luci,ff94315/luci-1,remakeelectric/luci,shangjiyu/luci-with-extra,dismantl/luci-0.12,dismantl/luci-0.12,fkooman/luci,lbthomsen/openwrt-luci,LazyZhu/openwrt-luci-trunk-mod,maxrio/luci981213,daofeng2015/luci,forward619/luci,RuiChen1113/luci,bright-things/ionic-luci,florian-shellfire/luci,oneru/luci,palmettos/test,RuiChen1113/luci,mumuqz/luci,palmettos/cnLuCI,taiha/luci,mumuqz/luci,fkooman/luci,thesabbir/luci,urueedi/luci,LazyZhu/openwrt-luci-trunk-mod,chris5560/openwrt-luci,ollie27/openwrt_luci,RedSnake64/openwrt-luci-packages,nmav/luci,bright-things/ionic-luci,opentechinstitute/luci,deepak78/new-luci,dwmw2/luci,florian-shellfire/luci,oyido/luci,nwf/openwrt-luci,kuoruan/luci,keyidadi/luci,keyidadi/luci,oyido/luci,thesabbir/luci,jchuang1977/luci-1,bright-things/ionic-luci,urueedi/luci,maxrio/luci981213,slayerrensky/luci,aa65535/luci,Hostle/openwrt-luci-multi-user,dwmw2/luci,oyido/luci,981213/luci-1,male-puppies/luci,jorgifumi/luci,Hostle/luci,ff94315/luci-1,zhaoxx063/luci,daofeng2015/luci,tcatm/luci,palmettos/test,tobiaswaldvogel/luci,wongsyrone/luci-1,cappiewu/luci,dwmw2/luci,Hostle/luci,remakeelectric/luci,dismantl/luci-0.12,Kyklas/luci-proto-hso,Hostle/luci,ollie27/openwrt_luci,mumuqz/luci,artynet/luci,oyido/luci,oneru/luci,deepak78/new-luci,jlopenwrtluci/luci,LazyZhu/openwrt-luci-trunk-mod,marcel-sch/luci,sujeet14108/luci,chris5560/openwrt-luci,obsy/luci,Sakura-Winkey/LuCI,kuoruan/lede-luci,lbthomsen/openwrt-luci,sujeet14108/luci,rogerpueyo/luci,slayerrensky/luci,deepak78/new-luci,teslamint/luci,RedSnake64/openwrt-luci-packages,jchuang1977/luci-1,zhaoxx063/luci,jorgifumi/luci,NeoRaider/luci,hnyman/luci,db260179/openwrt-bpi-r1-luci,Sakura-Winkey/LuCI,bittorf/luci,lcf258/openwrtcn,lcf258/openwrtcn,joaofvieira/luci,schidler/ionic-luci,opentechinstitute/luci,MinFu/luci,jorgifumi/luci,NeoRaider/luci,bittorf/luci,slayerrensky/luci,lbthomsen/openwrt-luci,nmav/luci,schidler/ionic-luci,urueedi/luci,forward619/luci,981213/luci-1,chris5560/openwrt-luci,981213/luci-1,palmettos/cnLuCI,nwf/openwrt-luci,kuoruan/luci,daofeng2015/luci,forward619/luci,jchuang1977/luci-1,nmav/luci,hnyman/luci,obsy/luci,Kyklas/luci-proto-hso,hnyman/luci,urueedi/luci,jchuang1977/luci-1,jlopenwrtluci/luci,bittorf/luci,RuiChen1113/luci,Noltari/luci,zhaoxx063/luci,male-puppies/luci,LuttyYang/luci,deepak78/new-luci,cappiewu/luci,mumuqz/luci,marcel-sch/luci,tcatm/luci,aircross/OpenWrt-Firefly-LuCI,maxrio/luci981213,openwrt/luci,cappiewu/luci,kuoruan/lede-luci,fkooman/luci,aircross/OpenWrt-Firefly-LuCI,slayerrensky/luci,ReclaimYourPrivacy/cloak-luci,lbthomsen/openwrt-luci,openwrt/luci,981213/luci-1,forward619/luci,remakeelectric/luci,artynet/luci,Hostle/openwrt-luci-multi-user,shangjiyu/luci-with-extra,taiha/luci,kuoruan/lede-luci,joaofvieira/luci,RedSnake64/openwrt-luci-packages,palmettos/test,RuiChen1113/luci,rogerpueyo/luci,david-xiao/luci,MinFu/luci,ReclaimYourPrivacy/cloak-luci,sujeet14108/luci,opentechinstitute/luci,aircross/OpenWrt-Firefly-LuCI,teslamint/luci,Wedmer/luci,deepak78/new-luci,Hostle/luci,ReclaimYourPrivacy/cloak-luci,ff94315/luci-1,teslamint/luci,urueedi/luci,joaofvieira/luci,florian-shellfire/luci,taiha/luci,harveyhu2012/luci,kuoruan/luci,cshore-firmware/openwrt-luci,hnyman/luci,LazyZhu/openwrt-luci-trunk-mod,deepak78/new-luci,LuttyYang/luci,nwf/openwrt-luci,NeoRaider/luci,keyidadi/luci,tcatm/luci,Hostle/openwrt-luci-multi-user,schidler/ionic-luci,cappiewu/luci,chris5560/openwrt-luci,forward619/luci,maxrio/luci981213,openwrt/luci,obsy/luci,joaofvieira/luci,oyido/luci,jorgifumi/luci,marcel-sch/luci,slayerrensky/luci,taiha/luci,urueedi/luci
481721a781da283d1609948ce8cec3aeeac6ed25
nvim/nvim/lua/_/treesitter.lua
nvim/nvim/lua/_/treesitter.lua
local has_config, ts_configs = pcall(require, 'nvim-treesitter.configs') if not has_config then return end ts_configs.setup { ensure_installed={ 'bash', 'cmake', 'comment', 'css', 'go', 'haskell', 'html', 'http', 'javascript', 'jsdoc', 'json', 'lua', 'nix', 'python', 'regex', 'rst', 'rust', 'toml', 'tsx', 'typescript', 'vim' 'yaml' }, highlight={enable=true}, indent={enable=true}, incremental_selection={ enable=true, keymaps={ init_selection='gnn', node_incremental='grn', scope_incremental='grc', node_decremental='grm' } }, refactor={ smart_rename={enable=true, keymaps={smart_rename='grr'}}, highlight_definitions={enable=true} -- highlight_current_scope = { enable = true } }, rainbow={enable=true, extended_mode=true}, textobjects={ select={ enable=true, keymaps={ ['af']='@function.outer', ['if']='@function.inner', ['aC']='@class.outer', ['iC']='@class.inner', ['ac']='@conditional.outer', ['ic']='@conditional.inner', ['ae']='@block.outer', ['ie']='@block.inner', ['al']='@loop.outer', ['il']='@loop.inner', ['is']='@statement.inner', ['as']='@statement.outer', ['ad']='@comment.outer', ['am']='@call.outer', ['im']='@call.inner' } } } }
local has_config, ts_configs = pcall(require, 'nvim-treesitter.configs') if not has_config then return end ts_configs.setup { ensure_installed='maintained', highlight={enable=true}, indent={enable=true}, incremental_selection={ enable=true, keymaps={ init_selection='gnn', node_incremental='grn', scope_incremental='grc', node_decremental='grm' } }, refactor={ smart_rename={enable=true, keymaps={smart_rename='grr'}}, highlight_definitions={enable=true} -- highlight_current_scope = { enable = true } }, rainbow={enable=true, extended_mode=true}, textobjects={ select={ enable=true, keymaps={ ['af']='@function.outer', ['if']='@function.inner', ['aC']='@class.outer', ['iC']='@class.inner', ['ac']='@conditional.outer', ['ic']='@conditional.inner', ['ae']='@block.outer', ['ie']='@block.inner', ['al']='@loop.outer', ['il']='@loop.inner', ['is']='@statement.inner', ['as']='@statement.outer', ['ad']='@comment.outer', ['am']='@call.outer', ['im']='@call.inner' } } } }
fix(nvim): use maintained
fix(nvim): use maintained
Lua
mit
skyuplam/dotfiles,skyuplam/dotfiles
90ccfbaf2e758ef8aa5b3b4aff0ace0659e35001
tools/lua/gradients.lua
tools/lua/gradients.lua
function sk_scrape_startcanvas(c, fileName) end function sk_scrape_endcanvas(c, fileName) end SkScalarNearlyZero = 1.0 / bit32.lshift(1.0, 12) function SkScalarNearlyEqual(a, b) return math.abs(a,b) <= SkScalarNearlyZero end gradients = {} i = 1 function sk_scrape_accumulate(t) local p = t.paint if p then local s = p:getShader() if s then local g = s:asAGradient() if g then gradients[i] = {} gradients[i].colorCount = g.colorCount gradients[i].type = g.type gradients[i].tile = g.tile numHardStops = 0 isEvenlySpaced = true for j = 2, g.colorCount, 1 do if not SkScalarNearlyEqual(g.positions[j], j/(g.colorCount-1)) then isEvenlySpaced = false end if SkScalarNearlyEqual(g.positions[j], g.positions[j-1]) then numHardStops = numHardStops + 1 end end gradients[i].isEvenlySpaced = isEvenlySpaced gradients[i].numHardStops = numHardStops; gradients[i].positions = {} for j = 1, g.colorCount, 1 do gradients[i].positions[j] = g.positions[j] end i = i + 1 end end end end function sk_scrape_summarize() for k, v in pairs(gradients) do local pos = "" for j = 1, v.colorCount , 1 do pos = pos .. v.positions[j] if j ~= v.colorCount then pos = pos .. "," end end io.write(string.format("%d %s %s %d %d %s\n", v.colorCount, v.type, v.tile, tonumber(v.isEvenlySpaced and 1 or 0), v.numHardStops, pos)) end end
function sk_scrape_startcanvas(c, fileName) end function sk_scrape_endcanvas(c, fileName) end LuaDoubleNearlyZero = 1.0 / bit32.lshift(1.0, 12) function LuaDoubleNearlyEqual(a, b) return math.abs(a-b) <= LuaDoubleNearlyZero end gradients = {} i = 1 function sk_scrape_accumulate(t) local p = t.paint if p then local s = p:getShader() if s then local g = s:asAGradient() if g then gradients[i] = {} gradients[i].colorCount = g.colorCount gradients[i].type = g.type gradients[i].tile = g.tile isEvenlySpaced = true for j = 1, g.colorCount, 1 do if not LuaDoubleNearlyEqual(g.positions[j], (j-1)/(g.colorCount-1)) then isEvenlySpaced = false end end gradients[i].isEvenlySpaced = isEvenlySpaced numHardStops = 0 for j = 2, g.colorCount, 1 do if LuaDoubleNearlyEqual(g.positions[j], g.positions[j-1]) then numHardStops = numHardStops + 1 end end gradients[i].numHardStops = numHardStops; gradients[i].positions = {} for j = 1, g.colorCount, 1 do gradients[i].positions[j] = g.positions[j] end i = i + 1 end end end end function sk_scrape_summarize() for k, v in pairs(gradients) do local pos = "" for j = 1, v.colorCount , 1 do pos = pos .. v.positions[j] if j ~= v.colorCount then pos = pos .. "," end end io.write(string.format("%d %s %s %d %d %s\n", v.colorCount, v.type, v.tile, tonumber(v.isEvenlySpaced and 1 or 0), v.numHardStops, pos)) end end
Fix Lua bugs, nit name change
Fix Lua bugs, nit name change BUG=skia: GOLD_TRYBOT_URL= https://gold.skia.org/search?issue=2140293002 Review-Url: https://codereview.chromium.org/2140293002
Lua
bsd-3-clause
rubenvb/skia,google/skia,aosp-mirror/platform_external_skia,google/skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,HalCanary/skia-hc,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,google/skia,aosp-mirror/platform_external_skia,HalCanary/skia-hc,HalCanary/skia-hc,google/skia,google/skia,aosp-mirror/platform_external_skia,rubenvb/skia,google/skia,aosp-mirror/platform_external_skia,rubenvb/skia,HalCanary/skia-hc,HalCanary/skia-hc,rubenvb/skia,rubenvb/skia,Hikari-no-Tenshi/android_external_skia,HalCanary/skia-hc,google/skia,HalCanary/skia-hc,HalCanary/skia-hc,HalCanary/skia-hc,google/skia,Hikari-no-Tenshi/android_external_skia,rubenvb/skia,rubenvb/skia,Hikari-no-Tenshi/android_external_skia,aosp-mirror/platform_external_skia,google/skia,google/skia,aosp-mirror/platform_external_skia,Hikari-no-Tenshi/android_external_skia,Hikari-no-Tenshi/android_external_skia,Hikari-no-Tenshi/android_external_skia,HalCanary/skia-hc,rubenvb/skia,rubenvb/skia,rubenvb/skia,Hikari-no-Tenshi/android_external_skia,Hikari-no-Tenshi/android_external_skia
cffb21f7be1ec654f432a5560c28c3d475918b43
frontend/apps/reader/modules/readerstatus.lua
frontend/apps/reader/modules/readerstatus.lua
local InputContainer = require("ui/widget/container/inputcontainer") local BookStatusWidget = require("ui/widget/bookstatuswidget") local UIManager = require("ui/uimanager") local _ = require("gettext") local ReaderStatus = InputContainer:new { document = nil, summary = { rating = 0, note = nil, status = "", modified = "", }, enabled = true, total_pages = 0 } function ReaderStatus:init() if self.ui.document.is_pic then self.enabled = false return else self.total_pages = self.document:getPageCount() self.ui.menu:registerToMainMenu(self) -- register event listener if enabled self.onEndOfBook = function() self:showStatus() end end end function ReaderStatus:addToMainMenu(tab_item_table) table.insert(tab_item_table.info, { text = _("Book status"), callback = function() self:showStatus() end, }) end function ReaderStatus:showStatus() local status_page = BookStatusWidget:new { thumbnail = self.document:getCoverPageImage(), props = self.document:getProps(), document = self.document, settings = self.settings, view = self.view, } UIManager:show(status_page) end function ReaderStatus:onReadSettings(config) self.settings = config end return ReaderStatus
local InputContainer = require("ui/widget/container/inputcontainer") local BookStatusWidget = require("ui/widget/bookstatuswidget") local UIManager = require("ui/uimanager") local _ = require("gettext") local ReaderStatus = InputContainer:new { document = nil, summary = { rating = 0, note = nil, status = "", modified = "", }, enabled = true, total_pages = 0 } function ReaderStatus:init() if self.ui.document.is_pic then self.enabled = false return else self.total_pages = self.document:getPageCount() self.ui.menu:registerToMainMenu(self) -- register event listener if enabled if G_reader_settings:nilOrTrue("auto_book_status") then self.onEndOfBook = function() self:showStatus() end end end end function ReaderStatus:addToMainMenu(tab_item_table) table.insert(tab_item_table.info, { text = _("Book status"), callback = function() self:showStatus() end, }) end function ReaderStatus:showStatus() local status_page = BookStatusWidget:new { thumbnail = self.document:getCoverPageImage(), props = self.document:getProps(), document = self.document, settings = self.settings, view = self.view, } UIManager:show(status_page) end function ReaderStatus:onReadSettings(config) self.settings = config end return ReaderStatus
Add new setting: auto_book_status
Add new setting: auto_book_status Fixes #2363.
Lua
agpl-3.0
houqp/koreader,Frenzie/koreader,mihailim/koreader,robert00s/koreader,lgeek/koreader,apletnev/koreader,mwoz123/koreader,Frenzie/koreader,pazos/koreader,NiLuJe/koreader,NickSavage/koreader,koreader/koreader,koreader/koreader,poire-z/koreader,NiLuJe/koreader,poire-z/koreader,Markismus/koreader,Hzj-jie/koreader
cdaab739fc41ac49914780b60b36a86496cc9384
busted/core.lua
busted/core.lua
local metatype = function(obj) local otype = type(obj) if otype == 'table' then local mt = getmetatable(obj) if mt and mt.__type then return mt.__type end end return otype end local failureMt = { __index = {}, __tostring = function(e) return e.message end, __type = 'failure' } local pendingMt = { __index = {}, __tostring = function(p) return p.message end, __type = 'pending' } local getfenv = require 'busted.compatibility'.getfenv local setfenv = require 'busted.compatibility'.setfenv local unpack = require 'busted.compatibility'.unpack local throw = error return function() local mediator = require 'mediator'() local busted = {} busted.version = '2.0.rc3-0' local root = require 'busted.context'() busted.context = root.ref() local environment = require 'busted.environment'(busted.context) busted.executors = {} local executors = {} busted.status = require 'busted.status' busted.getTrace = function(element, level, msg) level = level or 3 local info = debug.getinfo(level, 'Sl') while info.what == 'C' or info.short_src:match('luassert[/\\].*%.lua$') or info.short_src:match('busted[/\\].*%.lua$') do level = level + 1 info = debug.getinfo(level, 'Sl') end info.traceback = debug.traceback('', level) info.message = msg local file = busted.getFile(element) return file.getTrace(file.name, info) end busted.rewriteMessage = function(element, message) local file = busted.getFile(element) return file.rewriteMessage and file.rewriteMessage(file.name, message) or message end function busted.publish(...) return mediator:publish(...) end function busted.subscribe(...) return mediator:subscribe(...) end function busted.getFile(element) local current, parent = element, busted.context.parent(element) while parent do if parent.file then local file = parent.file[1] return { name = file.name, getTrace = file.run.getTrace, rewriteMessage = file.run.rewriteMessage } end if parent.descriptor == 'file' then return { name = parent.name, getTrace = parent.run.getTrace, rewriteMessage = parent.run.rewriteMessage } end parent = busted.context.parent(parent) end return parent end function busted.fail(msg, level) local _, emsg = pcall(error, msg, level+2) local e = { message = emsg } setmetatable(e, failureMt) throw(e, level+1) end function busted.pending(msg) local p = { message = msg } setmetatable(p, pendingMt) throw(p) end function busted.replaceErrorWithFail(callable) local env = {} local f = getmetatable(callable).__call or callable setmetatable(env, { __index = getfenv(f) }) env.error = busted.fail setfenv(f, env) end function busted.wrapEnv(callable) if (type(callable) == 'function' or getmetatable(callable).__call) then -- prioritize __call if it exists, like in files environment.wrap(getmetatable(callable).__call or callable) end end function busted.safe(descriptor, run, element) busted.context.push(element) local trace, message local status = 'success' local ret = { xpcall(run, function(msg) local errType = metatype(msg) status = (errType == 'string' and 'error' or errType) message = busted.rewriteMessage(element, tostring(msg)) trace = busted.getTrace(element, 3, msg) end) } if not ret[1] then busted.publish({ status, descriptor }, element, busted.context.parent(element), message, trace) end ret[1] = busted.status(status) busted.context.pop() return unpack(ret) end function busted.register(descriptor, executor) executors[descriptor] = executor local publisher = function(name, fn) if not fn and type(name) == 'function' then fn = name name = nil end local trace local ctx = busted.context.get() if busted.context.parent(ctx) then trace = busted.getTrace(ctx, 3, name) end local publish = function(f) busted.publish({ 'register', descriptor }, name, f, trace) end if fn then publish(fn) else return publish end end busted.executors[descriptor] = publisher if descriptor ~= 'file' then environment.set(descriptor, publisher) end busted.subscribe({ 'register', descriptor }, function(name, fn, trace) local ctx = busted.context.get() local plugin = { descriptor = descriptor, name = name, run = fn, trace = trace } busted.context.attach(plugin) if not ctx[descriptor] then ctx[descriptor] = { plugin } else ctx[descriptor][#ctx[descriptor]+1] = plugin end end) end function busted.execute(current) if not current then current = busted.context.get() end for _, v in pairs(busted.context.children(current)) do local executor = executors[v.descriptor] if executor then busted.safe(v.descriptor, function() return executor(v) end, v) end end end return busted end
local metatype = function(obj) local otype = type(obj) if otype == 'table' then local mt = getmetatable(obj) if mt and mt.__type then return mt.__type end end return otype end local failureMt = { __index = {}, __tostring = function(e) return e.message end, __type = 'failure' } local pendingMt = { __index = {}, __tostring = function(p) return p.message end, __type = 'pending' } local getfenv = require 'busted.compatibility'.getfenv local setfenv = require 'busted.compatibility'.setfenv local unpack = require 'busted.compatibility'.unpack local throw = error return function() local mediator = require 'mediator'() local busted = {} busted.version = '2.0.rc3-0' local root = require 'busted.context'() busted.context = root.ref() local environment = require 'busted.environment'(busted.context) busted.executors = {} local executors = {} busted.status = require 'busted.status' busted.getTrace = function(element, level, msg) level = level or 3 local info = debug.getinfo(level, 'Sl') while info.what == 'C' or info.short_src:match('luassert[/\\].*%.lua$') or info.short_src:match('busted[/\\].*%.lua$') do level = level + 1 info = debug.getinfo(level, 'Sl') end info.traceback = debug.traceback('', level) info.message = msg local file = busted.getFile(element) return file.getTrace(file.name, info) end busted.rewriteMessage = function(element, message) local file = busted.getFile(element) return file.rewriteMessage and file.rewriteMessage(file.name, message) or message end function busted.publish(...) return mediator:publish(...) end function busted.subscribe(...) return mediator:subscribe(...) end function busted.getFile(element) local current, parent = element, busted.context.parent(element) while parent do if parent.file then local file = parent.file[1] return { name = file.name, getTrace = file.run.getTrace, rewriteMessage = file.run.rewriteMessage } end if parent.descriptor == 'file' then return { name = parent.name, getTrace = parent.run.getTrace, rewriteMessage = parent.run.rewriteMessage } end parent = busted.context.parent(parent) end return parent end function busted.fail(msg, level) local _, emsg = pcall(error, msg, level+2) local e = { message = emsg } setmetatable(e, failureMt) throw(e, level+1) end function busted.pending(msg) local p = { message = msg } setmetatable(p, pendingMt) throw(p) end function busted.replaceErrorWithFail(callable) local env = {} local f = getmetatable(callable).__call or callable setmetatable(env, { __index = getfenv(f) }) env.error = busted.fail setfenv(f, env) end function busted.wrapEnv(callable) if (type(callable) == 'function' or getmetatable(callable).__call) then -- prioritize __call if it exists, like in files environment.wrap(getmetatable(callable).__call or callable) end end function busted.safe(descriptor, run, element) busted.context.push(element) local trace, message local status = 'success' local ret = { xpcall(run, function(msg) local errType = metatype(msg) status = ((errType == 'string' or errType == 'table') and 'error' or errType) message = busted.rewriteMessage(element, errType == 'table' and msg or tostring(msg)) trace = busted.getTrace(element, 3, msg) end) } if not ret[1] then busted.publish({ status, descriptor }, element, busted.context.parent(element), message, trace) end ret[1] = busted.status(status) busted.context.pop() return unpack(ret) end function busted.register(descriptor, executor) executors[descriptor] = executor local publisher = function(name, fn) if not fn and type(name) == 'function' then fn = name name = nil end local trace local ctx = busted.context.get() if busted.context.parent(ctx) then trace = busted.getTrace(ctx, 3, name) end local publish = function(f) busted.publish({ 'register', descriptor }, name, f, trace) end if fn then publish(fn) else return publish end end busted.executors[descriptor] = publisher if descriptor ~= 'file' then environment.set(descriptor, publisher) end busted.subscribe({ 'register', descriptor }, function(name, fn, trace) local ctx = busted.context.get() local plugin = { descriptor = descriptor, name = name, run = fn, trace = trace } busted.context.attach(plugin) if not ctx[descriptor] then ctx[descriptor] = { plugin } else ctx[descriptor][#ctx[descriptor]+1] = plugin end end) end function busted.execute(current) if not current then current = busted.context.get() end for _, v in pairs(busted.context.children(current)) do local executor = executors[v.descriptor] if executor then busted.safe(v.descriptor, function() return executor(v) end, v) end end end return busted end
Fix error message for table error objects
Fix error message for table error objects When throwing a table as an error, the error message reads 'Nil error', which is confusing because an error object was thrown. The error message should at least display that a table was thrown. Restore the previous behavior of printing out the error table. Issue #284.
Lua
mit
sobrinho/busted,xyliuke/busted,nehz/busted,Olivine-Labs/busted,DorianGray/busted,mpeterv/busted,leafo/busted,ryanplusplus/busted,o-lim/busted,istr/busted
e4f39b5344036c7ef34d06ebc4c8d7316aef9807
programs/hammerspoon/init.lua
programs/hammerspoon/init.lua
-- Get around paste blockers with cmd+alt+v hs.hotkey.bind({"cmd", "shift"}, "V", function() hs.eventtap.keyStrokes(hs.pasteboard.getContents()) end) -- Set up a hyper key hyper = false hyperTime = nil down = hs.eventtap.new({hs.eventtap.event.types.keyDown}, function(event) local character = event:getCharacters() local keyCode = event:getKeyCode() -- print("down", character, keyCode) -- Disable the insert key because overwrite mode is annoying if keyCode == 114 then return true end -- Set up ; as the hyper key if character == ";" then hyper = true if hyperTime == nil then hyperTime = hs.timer.absoluteTime() end return true end -- Use h, j, k, l as arrow keys if character == 'h' and hyper then hs.eventtap.keyStroke(nil, "left", 0) hyperTime = nil return true end if character == 'j' and hyper then hs.eventtap.keyStroke(nil, "down", 0) hyperTime = nil return true end if character == 'k' and hyper then hs.eventtap.keyStroke(nil, "up", 0) hyperTime = nil return true end if character == 'l' and hyper then hs.eventtap.keyStroke(nil, "right", 0) hyperTime = nil return true end -- Quick switch to applications if character == 'q' and hyper then hs.application.launchOrFocus("Authy Desktop") hyperTime = nil return true end if character == 'w' and hyper then hs.application.launchOrFocus("Firefox Developer Edition") hyperTime = nil return true end if character == 'e' and hyper then hs.application.launchOrFocus("iTerm") hyperTime = nil return true end if character == 'r' and hyper then hs.application.launchOrFocus("Visual Studio Code") hyperTime = nil return true end if character == 't' and hyper then hs.application.launchOrFocus("TablePlus") hyperTime = nil return true end if character == 'y' and hyper then hs.application.launchOrFocus("Todoist") hyperTime = nil return true end if character == 'u' and hyper then hs.application.launchOrFocus("Slack") hyperTime = nil return true end if character == 'i' and hyper then hs.application.launchOrFocus("Spotify") hyperTime = nil return true end end) down:start() up = hs.eventtap.new({hs.eventtap.event.types.keyUp}, function(event) local character = event:getCharacters() if character == ";" and hyper then local currentTime = hs.timer.absoluteTime() -- print(currentTime, hyperTime) if hyperTime ~= nil and (currentTime - hyperTime) / 1000000 < 250 then down:stop() hs.eventtap.keyStrokes(";") down:start() end hyper = false hyperTime = nil end end) up:start() --[[ Set the default output device, based on this priority: 1. Sony headphones 2. Other Bluetooth headphones 3. CalDigit dock audio (i.e. desktop speakers) 4. Built-in speakers Crucially, this also avoids the issue of macOS setting the default device to a monitor that doesn't even have speakers but registers as an output device for some reason. ]] hs.audiodevice.watcher.setCallback(function(event) --[[ We only care about when devices are connected or disconnected. This allows us to manually change the default device without issues. ]] if event ~= "dev#" then return end for i, device in ipairs(hs.audiodevice.allOutputDevices()) do local currentDevice = hs.audiodevice.defaultOutputDevice() if device:transportType() == "Bluetooth" then if currentDevice:name() ~= "WH-1000XM3" then device:setDefaultOutputDevice() end elseif device:transportType() == "USB" then if currentDevice:transportType() ~= "Bluetooth" then device:setDefaultOutputDevice() end elseif device:transportType() == "Built-in" then if currentDevice:transportType() ~= "Bluetooth" and currentDevice:transportType() ~= "USB" then device:setDefaultOutputDevice() end end end end) hs.audiodevice.watcher.start() --[[ Make control act as escape when tapped Thanks to https://gist.github.com/arbelt/b91e1f38a0880afb316dd5b5732759f1 ]] send_escape = false last_mods = {} control_key_handler = function() send_escape = false end control_key_timer = hs.timer.delayed.new(0.15, control_key_handler) control_handler = function(evt) local new_mods = evt:getFlags() if last_mods["ctrl"] == new_mods["ctrl"] then return false end if not last_mods["ctrl"] then last_mods = new_mods send_escape = true control_key_timer:start() else last_mods = new_mods control_key_timer:stop() if send_escape then return true, { hs.eventtap.event.newKeyEvent({}, 'escape', true), hs.eventtap.event.newKeyEvent({}, 'escape', false), } end end return false end control_tap = hs.eventtap.new({hs.eventtap.event.types.flagsChanged}, control_handler) control_tap:start() other_handler = function(evt) send_escape = false return false end other_tap = hs.eventtap.new({hs.eventtap.event.types.keyDown}, other_handler) other_tap:start()
-- Get around paste blockers with cmd+alt+v hs.hotkey.bind({"cmd", "shift"}, "V", function() hs.eventtap.keyStrokes(hs.pasteboard.getContents()) end) -- Set up a hyper key hyper = false hyperTime = nil down = hs.eventtap.new({hs.eventtap.event.types.keyDown}, function(event) local character = event:getCharacters() local keyCode = event:getKeyCode() -- print("down", character, keyCode) -- Disable the insert key because overwrite mode is annoying if keyCode == 114 then return true end -- Set up ; as the hyper key if character == ";" then hyper = true if hyperTime == nil then hyperTime = hs.timer.absoluteTime() end return true end -- Use h, j, k, l as arrow keys if character == 'h' and hyper then hs.eventtap.keyStroke(nil, "left", 0) hyperTime = nil return true end if character == 'j' and hyper then hs.eventtap.keyStroke(nil, "down", 0) hyperTime = nil return true end if character == 'k' and hyper then hs.eventtap.keyStroke(nil, "up", 0) hyperTime = nil return true end if character == 'l' and hyper then hs.eventtap.keyStroke(nil, "right", 0) hyperTime = nil return true end -- Quick switch to applications if character == 'q' and hyper then hs.application.launchOrFocus("Authy Desktop") hyperTime = nil return true end if character == 'w' and hyper then hs.application.launchOrFocus("Firefox Developer Edition") hyperTime = nil return true end if character == 'e' and hyper then hs.application.launchOrFocus("iTerm") hyperTime = nil return true end if character == 'r' and hyper then hs.application.launchOrFocus("Visual Studio Code") hyperTime = nil return true end if character == 't' and hyper then hs.application.launchOrFocus("TablePlus") hyperTime = nil return true end if character == 'y' and hyper then hs.application.launchOrFocus("Todoist") hyperTime = nil return true end if character == 'u' and hyper then hs.application.launchOrFocus("Slack") hyperTime = nil return true end if character == 'i' and hyper then hs.application.launchOrFocus("Spotify") hyperTime = nil return true end end) down:start() up = hs.eventtap.new({hs.eventtap.event.types.keyUp}, function(event) local character = event:getCharacters() if character == ";" and hyper then local currentTime = hs.timer.absoluteTime() -- print(currentTime, hyperTime) if hyperTime ~= nil and (currentTime - hyperTime) / 1000000 < 250 then down:stop() hs.eventtap.keyStrokes(";") down:start() end hyper = false hyperTime = nil end end) up:start() --[[ Set the default output device, based on this priority: 1. Sony headphones 2. Other Bluetooth headphones 3. Headphone jack 4. CalDigit dock audio (i.e. desktop speakers) 5. Built-in speakers Crucially, this also avoids the issue of macOS setting the default device to a monitor that doesn't even have speakers but registers as an output device for some reason. ]] function getAudioOutputPriority (device) if device:name() == "WH-1000XM3" then return 1 elseif device:transportType() == "Bluetooth" then return 2 elseif device:transportType() == "Built-in" and device:name() == "External Headphones" then return 3 elseif device:name() == "CalDigit Thunderbolt 3 Audio" then return 4 elseif device:transportType() == "Built-in" then return 5 else return 6 end end hs.audiodevice.watcher.setCallback(function(event) --[[ We only care about when devices are connected or disconnected. This allows us to manually change the default device without issues. ]] if event ~= "dev#" then return end for i, device in ipairs(hs.audiodevice.allOutputDevices()) do local currentDevice = hs.audiodevice.defaultOutputDevice() local currentPriority = getAudioOutputPriority(currentDevice) if getAudioOutputPriority(device) < currentPriority then device:setDefaultOutputDevice() end end end) hs.audiodevice.watcher.start() --[[ Make control act as escape when tapped Thanks to https://gist.github.com/arbelt/b91e1f38a0880afb316dd5b5732759f1 ]] send_escape = false last_mods = {} control_key_handler = function() send_escape = false end control_key_timer = hs.timer.delayed.new(0.15, control_key_handler) control_handler = function(evt) local new_mods = evt:getFlags() if last_mods["ctrl"] == new_mods["ctrl"] then return false end if not last_mods["ctrl"] then last_mods = new_mods send_escape = true control_key_timer:start() else last_mods = new_mods control_key_timer:stop() if send_escape then return true, { hs.eventtap.event.newKeyEvent({}, 'escape', true), hs.eventtap.event.newKeyEvent({}, 'escape', false), } end end return false end control_tap = hs.eventtap.new({hs.eventtap.event.types.flagsChanged}, control_handler) control_tap:start() other_handler = function(evt) send_escape = false return false end other_tap = hs.eventtap.new({hs.eventtap.event.types.keyDown}, other_handler) other_tap:start()
Fix the audio output priority handling with Hammerspoon
Fix the audio output priority handling with Hammerspoon 1. Handle plugging in headphones into the headphone jack. 2. Avoid using the USB microphone for output.
Lua
mit
dguo/dotfiles,dguo/dotfiles,dguo/dotfiles
e6c776e1e58f4e0e2780c66e0c6d4378f99eb99c
Modules/Time/DebounceTimer.lua
Modules/Time/DebounceTimer.lua
--- DebounceTimer -- @classmod DebounceTimer local DebounceTimer = {} DebounceTimer.ClassName = "DebounceTimer" DebounceTimer.__index = DebounceTimer function DebounceTimer.new(length) local self = setmetatable({}, DebounceTimer) self._length = length or error("No length") return self end function DebounceTimer:Restart() self._startTime = tick() end function DebounceTimer:IsRunning() return self._startTime ~= nil end function DebounceTimer:IsDone() if not self:IsRunning() then return true end return (tick() - self._startTime) <= self._length end return DebounceTimer
--- DebounceTimer -- @classmod DebounceTimer local DebounceTimer = {} DebounceTimer.ClassName = "DebounceTimer" DebounceTimer.__index = DebounceTimer function DebounceTimer.new(length) local self = setmetatable({}, DebounceTimer) self._length = length or error("No length") return self end function DebounceTimer:SetLength(length) self._length = length or error("No length") end function DebounceTimer:Restart() self._startTime = tick() end function DebounceTimer:IsRunning() return self._startTime ~= nil end function DebounceTimer:IsDone() if not self:IsRunning() then return true end return (tick() - self._startTime) >= self._length end return DebounceTimer
Fix :IsDone() on debounce timer
Fix :IsDone() on debounce timer
Lua
mit
Quenty/NevermoreEngine,Quenty/NevermoreEngine,Quenty/NevermoreEngine