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
dab827febb1d7ab47f9b40f5bc1ea9ec57aed649
SVUI_UnitFrames/libs/Plugins/oUF_HyperCombo/oUF_HyperCombo.lua
SVUI_UnitFrames/libs/Plugins/oUF_HyperCombo/oUF_HyperCombo.lua
--GLOBAL NAMESPACE local _G = _G; --LUA local unpack = _G.unpack; local select = _G.select; local class = select(2, UnitClass("player")); if(class ~= "ROGUE") then return end; local assert = _G.assert; local error = _G.error; local print = _G.print; local pairs = _G.pairs; local next = _G.next; local tostring = _G.tostring; local type = _G.type; --STRING local string = _G.string; local format = string.format; --MATH local math = _G.math; local floor = math.floor local ceil = math.ceil --TABLE local table = _G.table; local wipe = _G.wipe; --BLIZZARD API local GetShapeshiftForm = _G.GetShapeshiftForm; local UnitHasVehicleUI = _G.UnitHasVehicleUI; local UnitBuff = _G.UnitBuff; local MAX_COMBO_POINTS = _G.MAX_COMBO_POINTS; local GetSpellInfo = _G.GetSpellInfo; local GetComboPoints = _G.GetComboPoints; local parent, ns = ... local oUF = ns.oUF local ALERTED = false local TextColors = { [1]={1,0.1,0.1}, [2]={1,0.5,0.1}, [3]={1,1,0.1}, [4]={0.5,1,0.1}, [5]={0.1,1,0.1} }; local Update = function(self, event, unit) if(not (unit == 'player')) then return end local bar = self.HyperCombo; local cpoints = bar.Combo; local current = 0 if(UnitHasVehicleUI'player') then current = UnitPower("vehicle", SPELL_POWER_COMBO_POINTS); else current = UnitPower("player", SPELL_POWER_COMBO_POINTS); end if(cpoints and current) then if(bar.PreUpdate) then bar:PreUpdate() end local MAX_COMBO_POINTS = UnitPowerMax("player", SPELL_POWER_COMBO_POINTS); for i=1, MAX_COMBO_POINTS do if(i <= current) then if (cpoints[i]) then cpoints[i]:Show() if(bar.PointShow) then bar.PointShow(cpoints[i]) end end else if (cpoints[i]) then cpoints[i]:Hide() if(bar.PointHide) then bar.PointHide(cpoints[i], i) end end end end if(bar.PostUpdate) then return bar:PostUpdate(current) end end end local Path = function(self, ...) return (self.HyperCombo.Override or Update) (self, ...) end local ForceUpdate = function(element) return Path(element.__owner, 'ForceUpdate', element.__owner.unit) end local Enable = function(self) local bar = self.HyperCombo if(bar) then bar.__owner = self bar.ForceUpdate = ForceUpdate self:RegisterEvent('PLAYER_ENTERING_WORLD', Path, true) self:RegisterEvent('PLAYER_TARGET_CHANGED', Path, true) self:RegisterEvent('UNIT_DISPLAYPOWER', Path, true) self:RegisterUnitEvent('UNIT_DISPLAYPOWER', "player") self:RegisterEvent('UNIT_POWER_FREQUENT', Path, true) self:RegisterUnitEvent("UNIT_POWER_FREQUENT", "player") self:RegisterEvent('UNIT_MAXPOWER', Path, true) self:RegisterUnitEvent("UNIT_MAXPOWER", "player") local cpoints = bar.Combo; if(cpoints) then local maxComboPoints = UnitPowerMax("player", SPELL_POWER_COMBO_POINTS); for index = 1, maxComboPoints do local cpoint = cpoints[index] if(cpoint and cpoint:IsObjectType'Texture' and not cpoint:GetTexture()) then cpoint:SetTexture[[Interface\ComboFrame\ComboPoint]] cpoint:SetTexCoord(0, 0.375, 0, 1) end end end return true end end local Disable = function(self) local bar = self.HyperCombo if(bar) then local cpoints = bar.Combo; if(cpoints) then local maxComboPoints = UnitPowerMax(self.unit, SPELL_POWER_COMBO_POINTS); for index = 1, maxComboPoints do if (cpoints[index]) then cpoints[index]:Hide() end end end self:UnregisterEvent('PLAYER_ENTERING_WORLD', Path) self:UnregisterEvent('UNIT_DISPLAYPOWER', Path) self:UnregisterEvent('PLAYER_TARGET_CHANGED', Path) self:UnregisterEvent('UNIT_POWER_FREQUENT', Path) self:UnregisterEvent('UNIT_MAXPOWER', Path) end end oUF:AddElement('HyperCombo', Path, Enable, Disable)
--GLOBAL NAMESPACE local _G = _G; --LUA local unpack = _G.unpack; local select = _G.select; local class = select(2, UnitClass("player")); if(class ~= "ROGUE") then return end; local assert = _G.assert; local error = _G.error; local print = _G.print; local pairs = _G.pairs; local next = _G.next; local tostring = _G.tostring; local type = _G.type; --STRING local string = _G.string; local format = string.format; --MATH local math = _G.math; local floor = math.floor local ceil = math.ceil --TABLE local table = _G.table; local wipe = _G.wipe; --BLIZZARD API local GetShapeshiftForm = _G.GetShapeshiftForm; local UnitHasVehicleUI = _G.UnitHasVehicleUI; local UnitBuff = _G.UnitBuff; local MAX_COMBO_POINTS = _G.MAX_COMBO_POINTS; local GetSpellInfo = _G.GetSpellInfo; local GetComboPoints = _G.GetComboPoints; local SPELL_POWER_COMBO_POINTS = Enum.PowerType.ComboPoints; local parent, ns = ... local oUF = ns.oUF local ALERTED = false local TextColors = { [1]={1,0.1,0.1}, [2]={1,0.5,0.1}, [3]={1,1,0.1}, [4]={0.5,1,0.1}, [5]={0.1,1,0.1} }; local Update = function(self, event, unit) if(unit and unit ~= self.unit) then return end local bar = self.HyperCombo; local cpoints = bar.Combo; local current = 0 if(UnitHasVehicleUI'player') then current = UnitPower("vehicle", SPELL_POWER_COMBO_POINTS); else current = UnitPower("player", SPELL_POWER_COMBO_POINTS); end if(cpoints and current) then if(bar.PreUpdate) then bar:PreUpdate() end local MAX_COMBO_POINTS = UnitPowerMax("player", SPELL_POWER_COMBO_POINTS); for i=1, MAX_COMBO_POINTS do if(i <= current) then if (cpoints[i]) then cpoints[i]:Show() if(bar.PointShow) then bar.PointShow(cpoints[i]) end end else if (cpoints[i]) then cpoints[i]:Hide() if(bar.PointHide) then bar.PointHide(cpoints[i], i) end end end end if(bar.PostUpdate) then return bar:PostUpdate(current) end end end local Path = function(self, ...) return (self.HyperCombo.Override or Update) (self, ...) end local ForceUpdate = function(element) return Path(element.__owner, 'ForceUpdate', element.__owner.unit) end local Enable = function(self) local bar = self.HyperCombo if(bar) then bar.__owner = self bar.ForceUpdate = ForceUpdate self:RegisterEvent('PLAYER_ENTERING_WORLD', Path, true) self:RegisterEvent('PLAYER_TARGET_CHANGED', Path, true) self:RegisterEvent('UNIT_DISPLAYPOWER', Path, true) self:RegisterUnitEvent('UNIT_DISPLAYPOWER', "player") self:RegisterEvent('UNIT_POWER_FREQUENT', Path, true) self:RegisterUnitEvent("UNIT_POWER_FREQUENT", "player") self:RegisterEvent('UNIT_MAXPOWER', Path, true) self:RegisterUnitEvent("UNIT_MAXPOWER", "player") local cpoints = bar.Combo; if(cpoints) then local maxComboPoints = UnitPowerMax("player", SPELL_POWER_COMBO_POINTS); for index = 1, maxComboPoints do local cpoint = cpoints[index] if(cpoint and cpoint:IsObjectType'Texture' and not cpoint:GetTexture()) then cpoint:SetTexture[[Interface\ComboFrame\ComboPoint]] cpoint:SetTexCoord(0, 0.375, 0, 1) end end end return true end end local Disable = function(self) local bar = self.HyperCombo if(bar) then local cpoints = bar.Combo; if(cpoints) then local maxComboPoints = UnitPowerMax(self.unit, SPELL_POWER_COMBO_POINTS); for index = 1, maxComboPoints do if (cpoints[index]) then cpoints[index]:Hide() end end end self:UnregisterEvent('PLAYER_ENTERING_WORLD', Path) self:UnregisterEvent('UNIT_DISPLAYPOWER', Path) self:UnregisterEvent('PLAYER_TARGET_CHANGED', Path) self:UnregisterEvent('UNIT_POWER_FREQUENT', Path) self:UnregisterEvent('UNIT_MAXPOWER', Path) end end oUF:AddElement('HyperCombo', Path, Enable, Disable)
Updated the power to point to combo points instead of energy. This fixes issue with combo points always appearing.
Updated the power to point to combo points instead of energy. This fixes issue with combo points always appearing.
Lua
mit
FailcoderAddons/supervillain-ui
ec39a4cc145e7919101010cb52700ec6a7730815
libs/pkg.lua
libs/pkg.lua
--[[ Copyright 2014-2015 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] --[[ Package Metadata Commands ================ These commands work with packages metadata. pkg.query(fs, path) -> meta, path - Query an on-disk path for package info. pkg.queryDb(db, path) -> meta, kind - Query an in-db hash for package info. pky.normalize(meta) -> author, tag, version - Extract and normalize pkg info ]] local isFile = require('git').modes.isFile local semver = require('semver') local pathJoin = require('luvi').path.join local listToMap = require('git').listToMap local jsonParse = require('json').parse local function evalModule(data, name) local fn, err = loadstring(data, name) if not fn then return nil, err end local exports = {} local module = { exports = exports } setfenv(fn, { exports = exports, }) local success, ret = pcall(fn) local meta = success and type(ret) == "table" and ret or module.exports if not meta then return nil, "Missing exports in " .. name end if not meta.name then return nil, "Missing name in package description in " .. name end if not meta.version then return nil, "Missing version in package description in " .. name end return meta end local validKeys = { name = "string", version = "string", private = "boolean", -- Don't allow publishing. obsolete = "boolean", -- Hide from search results. description = "string", keywords = "table", -- list of strings tags = "table", -- list of strings homepage = "string", license = "string", licenses = "table", -- table of strings author = "table", -- person {name=name, email=email, url=url} contributors = "table", -- list of people dependencies = "table", -- list of strings luvi = "table", -- {flavor=flavor,version=version}, files = "table", } function exports.query(fs, path) local packagePath = path local stat, data, err stat, err = fs.stat(path) local attempts = {} if stat then if stat.type == "directory" then packagePath = path .. "/" local fullPath = pathJoin(path, "package.lua") attempts[#attempts + 1] = fullPath data, err = fs.readFile(fullPath) if err and not err:match("^ENOENT:") then error(err) end if not data then fullPath = pathJoin(path, "init.lua") attempts[#attempts + 1] = fullPath data, err = fs.readFile(fullPath) if err and not err:match("^ENOENT:") then error(err) end end else attempts[#attempts + 1] = packagePath data, err = fs.readFile(packagePath) end elseif err:match("^ENOENT:") then packagePath = packagePath .. ".lua" attempts[#attempts + 1] = packagePath data, err = fs.readFile(packagePath) end if not data then local sep = "\n Looked in: " return data, "Can't find package at " .. path .. sep .. table.concat(attempts, sep) end local meta = evalModule(data, packagePath) local clean = {} if not meta then return nil, "No meta found" end for key, value in pairs(meta) do if type(value) == validKeys[key] then clean[key] = value end end return clean, packagePath end function exports.queryDb(db, hash) local kind, value = db.loadAny(hash) if kind == "tag" then hash = value.object -- Use metata data in tag message if found local meta = jsonParse(value.message) if meta then return meta, value.type, hash end -- Otherwise search root tree or blob kind, value = db.loadAny(hash) assert(kind == value.type, "type mismatch") end local meta if kind == "tree" then local path = "tree:" .. hash local tree = listToMap(value) local entry = tree["package.lua"] if entry then path = path .. "/package.lua" else entry = tree["init.lua"] path = path .. "/init.lua" end if not (entry and isFile(entry.mode)) then return nil, "ENOENT: No package.lua or init.lua in tree:" .. hash end meta = evalModule(db.loadAs("blob", entry.hash), path) elseif kind == "blob" then meta = evalModule(value, "blob:" .. hash) else error("Illegal kind: " .. kind) end return meta, kind, hash end function exports.normalize(meta) local author, tag = meta.name:match("^([^/]+)/(.*)$") return author, tag, semver.normalize(meta.version) end
--[[ Copyright 2014-2015 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] --[[ Package Metadata Commands ================ These commands work with packages metadata. pkg.query(fs, path) -> meta, path - Query an on-disk path for package info. pkg.queryDb(db, path) -> meta, kind - Query an in-db hash for package info. pky.normalize(meta) -> author, tag, version - Extract and normalize pkg info ]] local isFile = require('git').modes.isFile local semver = require('semver') local pathJoin = require('luvi').path.join local listToMap = require('git').listToMap local jsonParse = require('json').parse local function evalModule(data, name) local fn, err = loadstring(data, name) if not fn then return nil, err end local exports = {} local module = { exports = exports } setfenv(fn, { exports = exports, }) local success, ret = pcall(fn) local meta = success and type(ret) == "table" and ret or module.exports if not meta then return nil, "Missing exports in " .. name end if not meta.name then return nil, "Missing name in package description in " .. name end if not meta.version then return nil, "Missing version in package description in " .. name end return meta end local validKeys = { name = "string", version = "string", private = "boolean", -- Don't allow publishing. obsolete = "boolean", -- Hide from search results. description = "string", keywords = "table", -- list of strings tags = "table", -- list of strings homepage = "string", license = "string", licenses = "table", -- table of strings author = "table", -- person {name=name, email=email, url=url} contributors = "table", -- list of people dependencies = "table", -- list of strings luvi = "table", -- {flavor=flavor,version=version}, files = "table", } function exports.query(fs, path) local packagePath = path local stat, data, err stat, err = fs.stat(path) local attempts = {} if stat then if stat.type == "directory" then packagePath = path .. "/" local fullPath = pathJoin(path, "package.lua") attempts[#attempts + 1] = fullPath data, err = fs.readFile(fullPath) if err and not err:match("^ENOENT:") then error(err) end if not data then fullPath = pathJoin(path, "init.lua") attempts[#attempts + 1] = fullPath data, err = fs.readFile(fullPath) if err and not err:match("^ENOENT:") then error(err) end end else attempts[#attempts + 1] = packagePath data, err = fs.readFile(packagePath) end elseif err:match("^ENOENT:") then packagePath = packagePath .. ".lua" attempts[#attempts + 1] = packagePath data, err = fs.readFile(packagePath) end if not data then local sep = "\n Looked in: " return data, "Can't find package at " .. path .. sep .. table.concat(attempts, sep) end local meta = evalModule(data, packagePath) local clean = {} if not meta then return nil, "No meta found" end for key, value in pairs(meta) do if type(value) == validKeys[key] then clean[key] = value end end return clean, packagePath end function exports.queryDb(db, hash) local kind, value = db.loadAny(hash) if kind == "tag" then hash = value.object -- Use metata data in tag message if found local meta = jsonParse(value.message) if meta then return meta, value.type, hash end local tagType = value.type -- Otherwise search root tree or blob kind, value = db.loadAny(hash) assert(kind == tagType, "type mismatch") end local meta if kind == "tree" then local path = "tree:" .. hash local tree = listToMap(value) local entry = tree["package.lua"] if entry then path = path .. "/package.lua" else entry = tree["init.lua"] path = path .. "/init.lua" end if not (entry and isFile(entry.mode)) then return nil, "ENOENT: No package.lua or init.lua in tree:" .. hash end meta = evalModule(db.loadAs("blob", entry.hash), path) elseif kind == "blob" then meta = evalModule(value, "blob:" .. hash) else error("Illegal kind: " .. kind) end return meta, kind, hash end function exports.normalize(meta) local author, tag = meta.name:match("^([^/]+)/(.*)$") return author, tag, semver.normalize(meta.version) end
Fix assert giving false positives for 'type mismatch'
Fix assert giving false positives for 'type mismatch'
Lua
apache-2.0
1yvT0s/lit,squeek502/lit,james2doyle/lit,kidaa/lit,luvit/lit,zhaozg/lit
4c132961971903db26fcc195276a75dc165d4c42
lib/path.lua
lib/path.lua
local Table = require('table') local Path = {} -- Split a filename into [root, dir, basename], unix version -- 'root' is just a slash, or nothing. local function split_path(filename) local root, dir, basename local i, j = filename:find("[^/]*$") if filename:sub(1, 1) == "/" then root = "/" dir = filename:sub(2, i - 1) else root = "" dir = filename:sub(1, i - 1) end local basename = filename:sub(i, j) return root, dir, basename, ext end -- Modifies an array of path parts in place by interpreting "." and ".." segments local function normalize_array(parts) local skip = 0 for i = #parts, 1, -1 do local part = parts[i] if part == "." then Table.remove(parts, i) elseif part == ".." then Table.remove(parts, i) skip = skip + 1 elseif skip > 0 then Table.remove(parts, i) skip = skip - 1 end end end function Path.normalize(path) local is_absolute = path:sub(1, 1) == "/" local trailing_slash = path:sub(#path) == "/" local parts = {} for part in path:gmatch("[^/]+") do parts[#parts + 1] = part end normalize_array(parts) path = Table.concat(parts, "/") if #path == 0 then if is_absolute then return "/" end return "." end if trailing_slash then path = path .. "/" end if is_absolute then path = "/" .. path end return path end function Path.join(...) return Path.normalize(Table.concat({...}, "/")) end function Path.resolve(root, path) if path:sub(1, 1) == "/" then return Path.normalize(path) end return Path.join(root, path) end function Path.dirname(path) local root, dir = split_path(path) if #dir > 0 then dir = dir:sub(1, #dir - 1) return root .. dir end if #root > 0 then return root end return "." end function Path.basename(path, expected_ext) return path:match("[^/]+$") or "" end function Path.extname(path) return path:match(".[^.]+$") or "" end return Path
local Table = require('table') local Path = {} -- Split a filename into [root, dir, basename], unix version -- 'root' is just a slash, or nothing. local function split_path(filename) local root, dir, basename local i, j = filename:find("[^/]*$") if filename:sub(1, 1) == "/" then root = "/" dir = filename:sub(2, i - 1) else root = "" dir = filename:sub(1, i - 1) end local basename = filename:sub(i, j) return root, dir, basename, ext end -- Modifies an array of path parts in place by interpreting "." and ".." segments local function normalize_array(parts) local skip = 0 for i = #parts, 1, -1 do local part = parts[i] if part == "." then Table.remove(parts, i) elseif part == ".." then Table.remove(parts, i) skip = skip + 1 elseif skip > 0 then Table.remove(parts, i) skip = skip - 1 end end end function Path.normalize(path) local is_absolute = path:sub(1, 1) == "/" local trailing_slash = path:sub(#path) == "/" local parts = {} for part in path:gmatch("[^/]+") do parts[#parts + 1] = part end normalize_array(parts) path = Table.concat(parts, "/") if #path == 0 then if is_absolute then return "/" end return "." end if trailing_slash then path = path .. "/" end if is_absolute then path = "/" .. path end return path end function Path.join(...) return Path.normalize(Table.concat({...}, "/")) end function Path.resolve(root, path) if path:sub(1, 1) == "/" then return Path.normalize(path) end return Path.join(root, path) end function Path.dirname(path) if path:sub(path:len()) == "/" then path = path:sub(1, -2) end local root, dir = split_path(path) if #dir > 0 then dir = dir:sub(1, #dir - 1) return root .. dir end if #root > 0 then return root end return "." end function Path.basename(path, expected_ext) return path:match("[^/]+$") or "" end function Path.extname(path) return path:match(".[^.]+$") or "" end return Path
Make `Path.dirname` work with paths ending with slashes
Make `Path.dirname` work with paths ending with slashes Fixes #47.
Lua
apache-2.0
AndrewTsao/luvit,kaustavha/luvit,GabrielNicolasAvellaneda/luvit-upstream,sousoux/luvit,GabrielNicolasAvellaneda/luvit-upstream,rjeli/luvit,AndrewTsao/luvit,AndrewTsao/luvit,kaustavha/luvit,boundary/luvit,DBarney/luvit,bsn069/luvit,bsn069/luvit,GabrielNicolasAvellaneda/luvit-upstream,kaustavha/luvit,boundary/luvit,rjeli/luvit,DBarney/luvit,sousoux/luvit,boundary/luvit,connectFree/lev,sousoux/luvit,rjeli/luvit,zhaozg/luvit,luvit/luvit,connectFree/lev,DBarney/luvit,DBarney/luvit,boundary/luvit,boundary/luvit,luvit/luvit,boundary/luvit,zhaozg/luvit,sousoux/luvit,GabrielNicolasAvellaneda/luvit-upstream,bsn069/luvit,rjeli/luvit,sousoux/luvit,sousoux/luvit
d21b9b2f096debfcbfe72ed0b6a49c44e2d7e911
deps/websocket-codec.lua
deps/websocket-codec.lua
exports.name = "creationix/websocket-codec" exports.version = "1.0.6" exports.homepage = "https://github.com/luvit/lit/blob/master/deps/websocket-codec.lua" exports.description = "A codec implementing websocket framing and helpers for handshakeing" exports.tags = {"http", "websocket", "codec"} exports.license = "MIT" exports.author = { name = "Tim Caswell" } local digest = require('openssl').digest.digest local base64 = require('openssl').base64 local random = require('openssl').random local band = bit.band local bor = bit.bor local bxor = bit.bxor local rshift = bit.rshift local lshift = bit.lshift local char = string.char local byte = string.byte local sub = string.sub local gmatch = string.gmatch local lower = string.lower local gsub = string.gsub local concat = table.concat local function applyMask(data, mask) local bytes = { [0] = byte(mask, 1), [1] = byte(mask, 2), [2] = byte(mask, 3), [3] = byte(mask, 4) } local out = {} for i = 1, #data do out[i] = char( bxor(byte(data, i), bytes[(i - 1) % 4]) ) end return concat(out) end function exports.decode(chunk) if #chunk < 2 then return end local second = byte(chunk, 2) local len = band(second, 0x7f) local offset if len == 126 then if #chunk < 4 then return end len = bor( lshift(byte(chunk, 3), 8), byte(chunk, 4)) offset = 4 elseif len == 127 then if #chunk < 10 then return end len = bor( lshift(byte(chunk, 3), 56), lshift(byte(chunk, 4), 48), lshift(byte(chunk, 5), 40), lshift(byte(chunk, 6), 32), lshift(byte(chunk, 7), 24), lshift(byte(chunk, 8), 16), lshift(byte(chunk, 9), 8), byte(chunk, 10)) offset = 10 else offset = 2 end local mask = band(second, 0x80) > 0 if mask then offset = offset + 4 end if #chunk < offset + len then return end local first = byte(chunk, 1) local payload = sub(chunk, offset + 1, offset + len) assert(#payload == len, "Length mismatch") if mask then payload = applyMask(payload, sub(chunk, offset - 3, offset)) end local extra = sub(chunk, offset + len + 1) return { fin = band(first, 0x80) > 0, rsv1 = band(first, 0x40) > 0, rsv2 = band(first, 0x20) > 0, rsv3 = band(first, 0x10) > 0, opcode = band(first, 0xf), mask = mask, len = len, payload = payload }, extra end function exports.encode(item) if type(item) == "string" then item = { opcode = 2, payload = item } end local payload = item.payload assert(type(payload) == "string", "payload must be string") local len = #payload local fin = item.fin if fin == nil then fin = true end local rsv1 = item.rsv1 local rsv2 = item.rsv2 local rsv3 = item.rsv3 local opcode = item.opcode or 2 local mask = item.mask local chars = { char(bor( fin and 0x80 or 0, rsv1 and 0x40 or 0, rsv2 and 0x20 or 0, rsv3 and 0x10 or 0, opcode )), char(bor( mask and 0x80 or 0, len < 126 and len or (len < 0x10000) and 126 or 127 )) } if len >= 0x10000 then chars[3] = char(band(rshift(len, 56), 0xff)) chars[4] = char(band(rshift(len, 48), 0xff)) chars[5] = char(band(rshift(len, 40), 0xff)) chars[6] = char(band(rshift(len, 32), 0xff)) chars[7] = char(band(rshift(len, 24), 0xff)) chars[8] = char(band(rshift(len, 16), 0xff)) chars[9] = char(band(rshift(len, 8), 0xff)) chars[10] = char(band(len, 0xff)) elseif len >= 126 then chars[3] = char(band(rshift(len, 8), 0xff)) chars[4] = char(band(len, 0xff)) end if mask then local key = random(4) return concat(chars) .. key .. applyMask(payload, key) end return concat(chars) .. payload end local websocketGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" function exports.acceptKey(key) return gsub(base64(digest("sha1", key .. websocketGuid, true)), "\n", "") end local acceptKey = exports.acceptKey -- Make a client handshake connection function exports.handshake(options, request) local key = gsub(base64(random(20)), "\n", "") local host = options.host local path = options.path or "/" local protocol = options.protocol local req = { method = "GET", path = path, {"Connection", "Upgrade"}, {"Upgrade", "websocket"}, {"Sec-Websocket-Version", "13"}, {"Sec-Websocket-Key", key}, } for i = 1, #options do req[#req + 1] = options[i] end if host then req[#req + 1] = {"Host", host} end if protocol then req[#req + 1] = {"Sec-Websocket-Protocol", protocol} end local res = request(req) if not res then return nil, "Missing response from server" end -- Parse the headers for quick reading if res.code ~= 101 then return nil, "response must be code 101" end local headers = {} for i = 1, #res do local name, value = unpack(res[i]) headers[lower(name)] = value end if not headers.connection or lower(headers.connection) ~= "upgrade" then return nil, "Invalid or missing connection upgrade header in response" end if headers["sec-websocket-accept"] ~= acceptKey(key) then return nil, "challenge key missing or mismatched" end if protocol and headers["sec-websocket-protocol"] ~= protocol then return nil, "protocol missing or mistmatched" end return true end function exports.handleHandshake(head, protocol) -- Websocket connections must be GET requests if not head.method == "GET" then return end -- Parse the headers for quick reading local headers = {} for i = 1, #head do local name, value = unpack(head[i]) headers[lower(name)] = value end -- Must have 'Upgrade: websocket' and 'Connection: Upgrade' headers if not headers.connection or lower(headers.connection) ~= "upgrade" then return end -- Make sure it's a new client speaking v13 of the protocol if tonumber(headers["sec-websocket-version"]) < 13 then return nil, "only websocket protocol v13 supported" end local key = headers["sec-websocket-key"] if not key then return nil, "websocket security key missing" end -- If the server wants a specified protocol, check for it. if protocol then local foundProtocol = false local list = headers["sec-websocket-protocol"] if list then for item in gmatch(list, "[^, ]+") do if item == protocol then foundProtocol = true break end end end if not foundProtocol then return nil, "specified protocol missing in request" end end local accept = acceptKey(key) local res = { code = 101, {"Upgrade", "websocket"}, {"Connection", "Upgrade"}, {"Sec-WebSocket-Accept", accept}, } if protocol then res[#res + 1] = {"Sec-WebSocket-Protocol", protocol} end return res end
exports.name = "creationix/websocket-codec" exports.version = "1.0.6" exports.homepage = "https://github.com/luvit/lit/blob/master/deps/websocket-codec.lua" exports.description = "A codec implementing websocket framing and helpers for handshakeing" exports.tags = {"http", "websocket", "codec"} exports.license = "MIT" exports.author = { name = "Tim Caswell" } local digest = require('openssl').digest.digest local base64 = require('openssl').base64 local random = require('openssl').random local band = bit.band local bor = bit.bor local bxor = bit.bxor local rshift = bit.rshift local lshift = bit.lshift local char = string.char local byte = string.byte local sub = string.sub local gmatch = string.gmatch local lower = string.lower local gsub = string.gsub local concat = table.concat local function applyMask(data, mask) local bytes = { [0] = byte(mask, 1), [1] = byte(mask, 2), [2] = byte(mask, 3), [3] = byte(mask, 4) } local out = {} for i = 1, #data do out[i] = char( bxor(byte(data, i), bytes[(i - 1) % 4]) ) end return concat(out) end function exports.decode(chunk) if #chunk < 2 then return end local second = byte(chunk, 2) local len = band(second, 0x7f) local offset if len == 126 then if #chunk < 4 then return end len = bor( lshift(byte(chunk, 3), 8), byte(chunk, 4)) offset = 4 elseif len == 127 then if #chunk < 10 then return end len = bor( lshift(byte(chunk, 3), 56), lshift(byte(chunk, 4), 48), lshift(byte(chunk, 5), 40), lshift(byte(chunk, 6), 32), lshift(byte(chunk, 7), 24), lshift(byte(chunk, 8), 16), lshift(byte(chunk, 9), 8), byte(chunk, 10)) offset = 10 else offset = 2 end local mask = band(second, 0x80) > 0 if mask then offset = offset + 4 end if #chunk < offset + len then return end local first = byte(chunk, 1) local payload = sub(chunk, offset + 1, offset + len) assert(#payload == len, "Length mismatch") if mask then payload = applyMask(payload, sub(chunk, offset - 3, offset)) end local extra = sub(chunk, offset + len + 1) return { fin = band(first, 0x80) > 0, rsv1 = band(first, 0x40) > 0, rsv2 = band(first, 0x20) > 0, rsv3 = band(first, 0x10) > 0, opcode = band(first, 0xf), mask = mask, len = len, payload = payload }, extra end function exports.encode(item) if type(item) == "string" then item = { opcode = 2, payload = item } end local payload = item.payload assert(type(payload) == "string", "payload must be string") local len = #payload local fin = item.fin if fin == nil then fin = true end local rsv1 = item.rsv1 local rsv2 = item.rsv2 local rsv3 = item.rsv3 local opcode = item.opcode or 2 local mask = item.mask local chars = { char(bor( fin and 0x80 or 0, rsv1 and 0x40 or 0, rsv2 and 0x20 or 0, rsv3 and 0x10 or 0, opcode )), char(bor( mask and 0x80 or 0, len < 126 and len or (len < 0x10000) and 126 or 127 )) } if len >= 0x10000 then chars[3] = char(band(rshift(len, 56), 0xff)) chars[4] = char(band(rshift(len, 48), 0xff)) chars[5] = char(band(rshift(len, 40), 0xff)) chars[6] = char(band(rshift(len, 32), 0xff)) chars[7] = char(band(rshift(len, 24), 0xff)) chars[8] = char(band(rshift(len, 16), 0xff)) chars[9] = char(band(rshift(len, 8), 0xff)) chars[10] = char(band(len, 0xff)) elseif len >= 126 then chars[3] = char(band(rshift(len, 8), 0xff)) chars[4] = char(band(len, 0xff)) end if mask then local key = random(4) return concat(chars) .. key .. applyMask(payload, key) end return concat(chars) .. payload end local websocketGuid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" function exports.acceptKey(key) return gsub(base64(digest("sha1", key .. websocketGuid, true)), "\n", "") end local acceptKey = exports.acceptKey -- Make a client handshake connection function exports.handshake(options, request) local key = gsub(base64(random(20)), "\n", "") local host = options.host local path = options.path or "/" local protocol = options.protocol local req = { method = "GET", path = path, {"Connection", "Upgrade"}, {"Upgrade", "websocket"}, {"Sec-Websocket-Version", "13"}, {"Sec-Websocket-Key", key}, } for i = 1, #options do req[#req + 1] = options[i] end if host then req[#req + 1] = {"Host", host} end if protocol then req[#req + 1] = {"Sec-Websocket-Protocol", protocol} end local res = request(req) if not res then return nil, "Missing response from server" end -- Parse the headers for quick reading if res.code ~= 101 then return nil, "response must be code 101" end local headers = {} for i = 1, #res do local name, value = unpack(res[i]) headers[lower(name)] = value end if not headers.connection or lower(headers.connection) ~= "upgrade" then return nil, "Invalid or missing connection upgrade header in response" end if headers["sec-websocket-accept"] ~= acceptKey(key) then return nil, "challenge key missing or mismatched" end if protocol and headers["sec-websocket-protocol"] ~= protocol then return nil, "protocol missing or mistmatched" end return true end function exports.handleHandshake(head, protocol) -- Websocket connections must be GET requests if not head.method == "GET" then return end -- Parse the headers for quick reading local headers = {} for i = 1, #head do local name, value = unpack(head[i]) headers[lower(name)] = value end -- Must have 'Upgrade: websocket' and 'Connection: Upgrade' headers if not (headers.connection and headers.upgrade and headers.connection:lower():find("upgrade", 1, true) and headers.upgrade:lower():find("websocket", 1, true)) then return end -- Make sure it's a new client speaking v13 of the protocol if tonumber(headers["sec-websocket-version"]) < 13 then return nil, "only websocket protocol v13 supported" end local key = headers["sec-websocket-key"] if not key then return nil, "websocket security key missing" end -- If the server wants a specified protocol, check for it. if protocol then local foundProtocol = false local list = headers["sec-websocket-protocol"] if list then for item in gmatch(list, "[^, ]+") do if item == protocol then foundProtocol = true break end end end if not foundProtocol then return nil, "specified protocol missing in request" end end local accept = acceptKey(key) local res = { code = 101, {"Upgrade", "websocket"}, {"Connection", "Upgrade"}, {"Sec-WebSocket-Accept", accept}, } if protocol then res[#res + 1] = {"Sec-WebSocket-Protocol", protocol} end return res end
Fix #108
Fix #108
Lua
apache-2.0
squeek502/lit,kidaa/lit,luvit/lit,zhaozg/lit,james2doyle/lit,1yvT0s/lit
5d7427bb53ce32208927e18052df14b24b281edb
libs/uci/luasrc/model/uci/bind.lua
libs/uci/luasrc/model/uci/bind.lua
--[[ LuCI - UCI utilities for model classes Copyright 2009 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- local assert, pairs, type = assert, pairs, type local utl = require "luci.util" module "luci.model.uci.bind" bind = utl.class() function bind.__init__(self, config, cursor) assert(config, "call to bind() without config file") self.cfg = config self.uci = cursor end function bind.init(self, cursor) assert(cursor, "call to init() without uci cursor") self.uci = cursor end function bind.section(self, stype) local x = utl.class(bsection) x.__init__ = function(inst, sid) assert(self.uci:get(self.cfg, sid) == stype, "attempt to instantiate bsection(%q) of wrong type, expected %q" % { sid, stype }) inst.bind = self inst.stype = stype inst.sid = sid end return x end function bind.usection(self, stype) local x = utl.class(bsection) x.__init__ = function(inst) inst.bind = self inst.stype = stype inst.sid = true end return x() end function bind.list(self, list, add, rem) local lookup = { } if type(list) == "string" then local item for item in list:gmatch("%S+") do lookup[item] = true end elseif type(list) == "table" then local item for _, item in pairs(list) do lookup[item] = true end end if add then lookup[add] = true end if rem then lookup[rem] = nil end return utl.keys(lookup) end function bind.bool(self, v) return ( v == "1" or v == "true" or v == "yes" or v == "on" ) end bsection = utl.class() function bsection.uciop(self, op, ...) assert(self.bind and self.bind.uci, "attempt to use unitialized binding") if op then return self.bind.uci[op](self.bind.uci, self.bind.cfg, ...) else return self.bind.uci end end function bsection.get(self, k, c) local v if type(c) == "string" then v = self:uciop("get", c, k) else self:uciop("foreach", self.stype, function(s) if type(c) == "table" then local ck, cv for ck, cv in pairs(c) do if s[ck] ~= cv then return true end end end if k ~= nil then v = s[k] else v = s end return false end) end return v end function bsection.set(self, k, v, c) local stat if type(c) == "string" then stat = self:uciop("set", c, k, v) else self:uciop("foreach", self.stype, function(s) if type(c) == "table" then local ck, cv for ck, cv in pairs(c) do if s[ck] ~= cv then return true end end end stat = self:uciop("set", c, k, v) return false end) end return stat or false end function bsection.property(self, k, n) self[n or k] = function(c, val) if val == nil then return c:get(k, c.sid) else return c:set(k, val, c.sid) end end end function bsection.property_bool(self, k, n) self[n or k] = function(c, val) if val == nil then return self.bind:bool(c:get(k, c.sid)) else return c:set(k, self.bind:bool(val) and "1" or "0", c.sid) end end end
--[[ LuCI - UCI utilities for model classes Copyright 2009 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- local assert, pairs, type = assert, pairs, type local utl = require "luci.util" module "luci.model.uci.bind" bind = utl.class() function bind.__init__(self, config, cursor) assert(config, "call to bind() without config file") self.cfg = config self.uci = cursor end function bind.init(self, cursor) assert(cursor, "call to init() without uci cursor") self.uci = cursor end function bind.section(self, stype) local x = utl.class(bsection) x.__init__ = function(inst, sid) assert(self.uci:get(self.cfg, sid) == stype, "attempt to instantiate bsection(%q) of wrong type, expected %q" % { sid, stype }) inst.bind = self inst.stype = stype inst.sid = sid end return x end function bind.usection(self, stype) local x = utl.class(bsection) x.__init__ = function(inst) inst.bind = self inst.stype = stype inst.sid = true end return x() end function bind.list(self, list, add, rem) local lookup = { } if type(list) == "string" then local item for item in list:gmatch("%S+") do lookup[item] = true end elseif type(list) == "table" then local item for _, item in pairs(list) do lookup[item] = true end end if add then lookup[add] = true end if rem then lookup[rem] = nil end return utl.keys(lookup) end function bind.bool(self, v) return ( v == "1" or v == "true" or v == "yes" or v == "on" ) end bsection = utl.class() function bsection.uciop(self, op, ...) assert(self.bind and self.bind.uci, "attempt to use unitialized binding") if op then return self.bind.uci[op](self.bind.uci, self.bind.cfg, ...) else return self.bind.uci end end function bsection.get(self, k, c) local v if type(c) == "string" then v = self:uciop("get", c, k) else self:uciop("foreach", self.stype, function(s) if type(c) == "table" then local ck, cv for ck, cv in pairs(c) do if s[ck] ~= cv then return true end end end if k ~= nil then v = s[k] else v = s end return false end) end return v end function bsection.set(self, k, v, c) local stat if type(c) == "string" then if type(v) == "table" and #v == 0 then stat = self:uciop("delete", c, k) else stat = self:uciop("set", c, k, v) end else self:uciop("foreach", self.stype, function(s) if type(c) == "table" then local ck, cv for ck, cv in pairs(c) do if s[ck] ~= cv then return true end end end stat = self:uciop("set", c, k, v) return false end) end return stat or false end function bsection.property(self, k, n) self[n or k] = function(c, val) if val == nil then return c:get(k, c.sid) else return c:set(k, val, c.sid) end end end function bsection.property_bool(self, k, n) self[n or k] = function(c, val) if val == nil then return self.bind:bool(c:get(k, c.sid)) else return c:set(k, self.bind:bool(val) and "1" or "0", c.sid) end end end
libs/uci: fix attempt to assign empty tables in uci bind class
libs/uci: fix attempt to assign empty tables in uci bind class git-svn-id: f7818b41aa164576329f806d7c3827e8a55298bb@5403 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci,fqrouter/luci
410388d42398edc5bcfd565e16cf939ea6e9959c
lib/light.lua
lib/light.lua
local _PACKAGE = (...):match("^(.+)[%./][^%./]+") or "" local class = require(_PACKAGE.."/class") local stencils = require(_PACKAGE..'/stencils') local util = require(_PACKAGE..'/util') local light = class() light.shadowShader = love.graphics.newShader(_PACKAGE.."/shaders/shadow.glsl") function light:init(x, y, r, g, b, range) self.direction = 0 self.angle = math.pi * 2.0 self.range = 0 self.x = x or 0 self.y = y or 0 self.z = 1 self.red = r or 255 self.green = g or 255 self.blue = b or 255 self.range = range or 300 self.smooth = 1.0 self.glowSize = 0.1 self.glowStrength = 0.0 self.visible = true self:refresh() end function light:refresh(w, h) w, h = w or love.window.getWidth(), h or love.window.getHeight() self.shadowShader:send('screenResolution', {w, h}) end -- set position function light:setPosition(x, y, z) if x ~= self.x or y ~= self.y or (z and z ~= self.z) then self.x = x self.y = y if z then self.z = z end end end -- move position function light:move(x, y, z) if x then self.x = self.x + x end if y then self.y = self.y + y end if z then self.z = self.z + z end end -- get x function light:getPosition() return self.x, self.y, self.z end -- set color function light:setColor(red, green, blue) self.red = red self.green = green self.blue = blue end -- set range function light:setRange(range) if range ~= self.range then self.range = range end end -- set direction function light:setDirection(direction) if direction ~= self.direction then if direction > math.pi * 2 then self.direction = math.mod(direction, math.pi * 2) elseif direction < 0.0 then self.direction = math.pi * 2 - math.mod(math.abs(direction), math.pi * 2) else self.direction = direction end end end -- set angle function light:setAngle(angle) if angle ~= self.angle then if angle > math.pi then self.angle = math.mod(angle, math.pi) elseif angle < 0.0 then self.angle = math.pi - math.mod(math.abs(angle), math.pi) else self.angle = angle end end end -- set glow size function light:setSmooth(smooth) self.smooth = smooth end -- set glow size function light:setGlowSize(size) self.glowSize = size end -- set glow strength function light:setGlowStrength(strength) self.glowStrength = strength end function light:inRange(l,t,w,h,s) local lx, ly, rs = (self.x + l/s) * s, (self.y + t/s) * s, self.range * s return (lx + rs) > 0 and (lx - rs) < w/s and (ly + rs) > 0 and (ly - rs) < h/s end function light:drawNormalShading(l,t,w,h,s, normalMap, shadowMap, canvas) if self.visible and self:inRange(l,t,w,h,s) then self.shadowShader:send('shadowMap', shadowMap) self.shadowShader:send('lightColor', {self.red / 255.0, self.green / 255.0, self.blue / 255.0}) self.shadowShader:send("lightPosition", {(self.x + l/s) * s, (h/s - (self.y + t/s)) * s, (self.z * 10) / 255.0}) self.shadowShader:send('lightRange',{self.range}) self.shadowShader:send("lightSmooth", self.smooth) self.shadowShader:send("lightGlow", {1.0 - self.glowSize, self.glowStrength}) self.shadowShader:send("lightAngle", math.pi - self.angle / 2.0) self.shadowShader:send("lightDirection", self.direction) self.shadowShader:send("invert_normal", self.normalInvert == true) util.drawCanvasToCanvas(normalMap, canvas, {shader = self.shadowShader}) end end function light:setVisible(visible) self.visible = visible end return light
local _PACKAGE = (...):match("^(.+)[%./][^%./]+") or "" local class = require(_PACKAGE.."/class") local stencils = require(_PACKAGE..'/stencils') local util = require(_PACKAGE..'/util') local light = class() light.shadowShader = love.graphics.newShader(_PACKAGE.."/shaders/shadow.glsl") function light:init(x, y, r, g, b, range) self.direction = 0 self.angle = math.pi * 2.0 self.range = 0 self.x = x or 0 self.y = y or 0 self.z = 1 self.red = r or 255 self.green = g or 255 self.blue = b or 255 self.range = range or 300 self.smooth = 1.0 self.glowSize = 0.1 self.glowStrength = 0.0 self.visible = true self:refresh() end function light:refresh(w, h) w, h = w or love.window.getWidth(), h or love.window.getHeight() self.shadowShader:send('screenResolution', {w, h}) end -- set position function light:setPosition(x, y, z) if x ~= self.x or y ~= self.y or (z and z ~= self.z) then self.x = x self.y = y if z then self.z = z end end end -- move position function light:move(x, y, z) if x then self.x = self.x + x end if y then self.y = self.y + y end if z then self.z = self.z + z end end -- get x function light:getPosition() return self.x, self.y, self.z end -- set color function light:setColor(red, green, blue) self.red = red self.green = green self.blue = blue end -- set range function light:setRange(range) if range ~= self.range then self.range = range end end -- set direction function light:setDirection(direction) if direction ~= self.direction then if direction > math.pi * 2 then self.direction = math.mod(direction, math.pi * 2) elseif direction < 0.0 then self.direction = math.pi * 2 - math.mod(math.abs(direction), math.pi * 2) else self.direction = direction end end end -- set angle function light:setAngle(angle) if angle ~= self.angle then if angle > math.pi then self.angle = math.mod(angle, math.pi) elseif angle < 0.0 then self.angle = math.pi - math.mod(math.abs(angle), math.pi) else self.angle = angle end end end -- set glow size function light:setSmooth(smooth) self.smooth = smooth end -- set glow size function light:setGlowSize(size) self.glowSize = size end -- set glow strength function light:setGlowStrength(strength) self.glowStrength = strength end function light:inRange(l,t,w,h,s) local lx, ly, rs = (self.x + l/s) * s, (self.y + t/s) * s, self.range * s return (lx + rs) > 0 and (lx - rs) < w/s and (ly + rs) > 0 and (ly - rs) < h/s end function light:drawNormalShading(l,t,w,h,s, normalMap, shadowMap, canvas) if self.visible and self:inRange(l,t,w,h,s) then self.shadowShader:send('shadowMap', shadowMap) self.shadowShader:send('lightColor', {self.red / 255.0, self.green / 255.0, self.blue / 255.0}) self.shadowShader:send("lightPosition", {(self.x + l/s) * s, (h/s - (self.y + t/s)) * s, (self.z * 10) / 255.0}) self.shadowShader:send('lightRange',{self.range}) self.shadowShader:send("lightSmooth", self.smooth) self.shadowShader:send("lightGlow", {1.0 - self.glowSize, self.glowStrength}) self.shadowShader:send("lightAngle", math.pi - self.angle / 2.0) self.shadowShader:send("lightDirection", self.direction) self.shadowShader:send("invert_normal", self.normalInvert == true) util.drawCanvasToCanvas(normalMap, canvas, { blendmode = 'additive', shader = self.shadowShader }) end end function light:setVisible(visible) self.visible = visible end return light
fixed the multiple lights issue
fixed the multiple lights issue
Lua
mit
willemt/light_world.lua
5c44aead6e7c66130fab8a2173170c2e1ced14fd
Examples/ubuntu-setup.cfg.lua
Examples/ubuntu-setup.cfg.lua
defaults.chrootdir=loader.path.combine(loader.workdir,"ubuntu_chroot") defaults.user="root" defaults.uid=0 defaults.gid=0 defaults.recalculate() sandbox = { setup = { static_executor=true, commands = { }, env_blacklist = { defaults.env.blacklist_main, defaults.env.blacklist_audio, defaults.env.blacklist_desktop, defaults.env.blacklist_home, defaults.env.blacklist_xdg, }, -- set custom env variables, env_set = { { {"PATH","/usr/sbin:/sbin:/usr/bin:/bin:/usr/bin/X11"}, {"HOME","/root"}, {"USER",defaults.user}, {"LOGNAME",defaults.user} }, defaults.env.set_xdg_runtime, } }, bwrap = { defaults.bwrap.unshare_user, defaults.bwrap.unshare_ipc, defaults.bwrap.unshare_pid, defaults.bwrap.unshare_uts, defaults.bwrap.proc_mount, defaults.bwrap.dev_mount, {prio=10,"ro-bind",loader.path.combine(defaults.chrootdir,"etc"),"/etc"}, defaults.bwrap.xdg_runtime_dir, defaults.bwrap.bin_rw_mount, defaults.bwrap.usr_rw_mount, defaults.bwrap.lib_rw_mount, defaults.bwrap.lib64_rw_mount, {prio=10,"bind",loader.path.combine(defaults.chrootdir,"boot"),"/boot"}, {prio=10,"bind",loader.path.combine(defaults.chrootdir,"boot"),"/boot"}, {prio=10,"bind",loader.path.combine(defaults.chrootdir,"root"),"/root"}, {prio=10,"bind",loader.path.combine(defaults.chrootdir,"run"),"/run"}, {prio=10,"bind",loader.path.combine(defaults.chrootdir,"sbin"),"/sbin"}, {prio=10,"bind",loader.path.combine(defaults.chrootdir,"srv"),"/srv"}, {prio=10,"bind",loader.path.combine(defaults.chrootdir,"opt"),"/opt"}, {prio=10,"bind",loader.path.combine(defaults.chrootdir,"tmp"),"/tmp"}, {prio=10,"bind",loader.path.combine(defaults.chrootdir,"var"),"/var"}, {"uid",defaults.uid}, {"gid",defaults.gid}, } } shell = { exec="/bin/bash", path="/", -- optional, chdir to this directory inside sandbox before exec env_unset={"TERM"}, -- optional, variables list to unset env_set= -- optional, variables list to set { {"TERM",os.getenv("TERM")}, }, term_signal=defaults.signals.SIGHUP, attach=true, pty=true, }
defaults.chrootdir=loader.path.combine(loader.workdir,"ubuntu_chroot") defaults.user="root" defaults.uid=0 defaults.gid=0 defaults.recalculate() sandbox = { setup = { static_executor=true, commands = { }, env_blacklist = { defaults.env.blacklist_main, defaults.env.blacklist_audio, defaults.env.blacklist_desktop, defaults.env.blacklist_home, defaults.env.blacklist_xdg, }, -- set custom env variables, env_set = { { {"PATH","/fixups:/usr/sbin:/sbin:/usr/bin:/bin:/usr/bin/X11"}, {"HOME","/root"}, {"USER",defaults.user}, {"LOGNAME",defaults.user} }, defaults.env.set_xdg_runtime, } }, bwrap = { defaults.bwrap.unshare_user, defaults.bwrap.unshare_ipc, defaults.bwrap.unshare_pid, defaults.bwrap.unshare_uts, defaults.bwrap.proc_mount, defaults.bwrap.dev_mount, {prio=10,"ro-bind",loader.path.combine(defaults.chrootdir,"etc"),"/etc"}, defaults.bwrap.xdg_runtime_dir, defaults.bwrap.bin_rw_mount, defaults.bwrap.usr_rw_mount, defaults.bwrap.lib_rw_mount, defaults.bwrap.lib64_rw_mount, defaults.bwrap.fixups_mount, {prio=10,"bind",loader.path.combine(defaults.chrootdir,"boot"),"/boot"}, {prio=10,"bind",loader.path.combine(defaults.chrootdir,"boot"),"/boot"}, {prio=10,"bind",loader.path.combine(defaults.chrootdir,"root"),"/root"}, {prio=10,"bind",loader.path.combine(defaults.chrootdir,"run"),"/run"}, {prio=10,"bind",loader.path.combine(defaults.chrootdir,"sbin"),"/sbin"}, {prio=10,"bind",loader.path.combine(defaults.chrootdir,"srv"),"/srv"}, {prio=10,"bind",loader.path.combine(defaults.chrootdir,"opt"),"/opt"}, {prio=10,"bind",loader.path.combine(defaults.chrootdir,"tmp"),"/tmp"}, {prio=10,"bind",loader.path.combine(defaults.chrootdir,"var"),"/var"}, {"uid",defaults.uid}, {"gid",defaults.gid}, } } shell = { exec="/bin/bash", path="/", -- optional, chdir to this directory inside sandbox before exec env_unset={"TERM"}, -- optional, variables list to unset env_set= -- optional, variables list to set { {"TERM",os.getenv("TERM")}, }, term_signal=defaults.signals.SIGHUP, attach=true, pty=true, }
ubuntu-setup.cfg.lua: mount and use /fixups directory
ubuntu-setup.cfg.lua: mount and use /fixups directory
Lua
mit
DarkCaster/Sandboxer,DarkCaster/Sandboxer
a28afad864bf828f4b89af30c8de460f0ab2c598
net/http.lua
net/http.lua
local socket = require "socket" local mime = require "mime" local url = require "socket.url" local server = require "net.server" local connlisteners_get = require "net.connlisteners".get; local listener = connlisteners_get("httpclient") or error("No httpclient listener!"); local t_insert, t_concat = table.insert, table.concat; local tonumber, tostring, pairs, xpcall, select, debug_traceback = tonumber, tostring, pairs, xpcall, select, debug.traceback; local log = require "util.logger".init("http"); local print = function () end local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end }); local urlencode = function (s) return s and (s:gsub("%W", function (c) return string.format("%%%02x", c:byte()); end)); end module "http" local function expectbody(reqt, code) if reqt.method == "HEAD" then return nil end if code == 204 or code == 304 then return nil end if code >= 100 and code < 200 then return nil end return 1 end local function request_reader(request, data, startpos) if not data then if request.body then log("debug", "Connection closed, but we have data, calling callback..."); request.callback(t_concat(request.body), request.code, request); elseif request.state ~= "completed" then -- Error.. connection was closed prematurely request.callback("connection-closed", 0, request); end destroy_request(request); request.body = nil; request.state = "completed"; return; end if request.state == "body" and request.state ~= "completed" then print("Reading body...") if not request.body then request.body = {}; request.havebodylength, request.bodylength = 0, tonumber(request.responseheaders["content-length"]); end if startpos then data = data:sub(startpos, -1) end t_insert(request.body, data); if request.bodylength then request.havebodylength = request.havebodylength + #data; if request.havebodylength >= request.bodylength then -- We have the body log("debug", "Have full body, calling callback"); if request.callback then request.callback(t_concat(request.body), request.code, request); end request.body = nil; request.state = "completed"; else print("", "Have "..request.havebodylength.." bytes out of "..request.bodylength); end end elseif request.state == "headers" then print("Reading headers...") local pos = startpos; local headers = request.responseheaders or {}; for line in data:sub(startpos, -1):gmatch("(.-)\r\n") do startpos = startpos + #line + 2; local k, v = line:match("(%S+): (.+)"); if k and v then headers[k:lower()] = v; print("Header: "..k:lower().." = "..v); elseif #line == 0 then request.responseheaders = headers; break; else print("Unhandled header line: "..line); end end -- Reached the end of the headers request.state = "body"; if #data > startpos then return request_reader(request, data, startpos); end elseif request.state == "status" then print("Reading status...") local http, code, text, linelen = data:match("^HTTP/(%S+) (%d+) (.-)\r\n()", startpos); code = tonumber(code); if not code then return request.callback("invalid-status-line", 0, request); end request.code, request.responseversion = code, http; if request.onlystatus or not expectbody(request, code) then if request.callback then request.callback(nil, code, request); end destroy_request(request); return; end request.state = "headers"; if #data > linelen then return request_reader(request, data, linelen); end end end local function handleerr(err) log("error", "Traceback[http]: %s: %s", tostring(err), debug_traceback()); end function request(u, ex, callback) local req = url.parse(u); local custom_headers, body; local default_headers = { ["Host"] = req.host, ["User-Agent"] = "Prosody XMPP Server" } if req.userinfo then default_headers["Authorization"] = "Basic "..mime.b64(req.userinfo); end if ex then custom_headers = ex.headers; req.onlystatus = ex.onlystatus; body = ex.body; if body then req.method = "POST "; default_headers["Content-Length"] = tostring(#body); default_headers["Content-Type"] = "application/x-www-form-urlencoded"; end if ex.method then req.method = ex.method; end end req.handler, req.conn = server.wrapclient(socket.tcp(), req.host, req.port or 80, listener, "*a"); req.write = req.handler.write; req.conn:settimeout(0); local ok, err = req.conn:connect(req.host, req.port or 80); if not ok and err ~= "timeout" then return nil, err; end local request_line = { req.method or "GET", " ", req.path, " HTTP/1.1\r\n" }; if req.query then t_insert(request_line, 4, "?"); t_insert(request_line, 5, req.query); end req.write(t_concat(request_line)); local t = { [2] = ": ", [4] = "\r\n" }; if custom_headers then for k, v in pairs(custom_headers) do t[1], t[3] = k, v; req.write(t_concat(t)); default_headers[k] = nil; end end for k, v in pairs(default_headers) do t[1], t[3] = k, v; req.write(t_concat(t)); default_headers[k] = nil; end req.write("\r\n"); if body then req.write(body); end req.callback = function (content, code, request) log("debug", "Calling callback, status %s", code or "---"); return select(2, xpcall(function () return callback(content, code, request) end, handleerr)); end req.reader = request_reader; req.state = "status"; listener.register_request(req.handler, req); return req; end function destroy_request(request) if request.conn then request.handler.close() listener.disconnect(request.conn, "closed"); end end _M.urlencode = urlencode; return _M;
local socket = require "socket" local mime = require "mime" local url = require "socket.url" local server = require "net.server" local connlisteners_get = require "net.connlisteners".get; local listener = connlisteners_get("httpclient") or error("No httpclient listener!"); local t_insert, t_concat = table.insert, table.concat; local tonumber, tostring, pairs, xpcall, select, debug_traceback = tonumber, tostring, pairs, xpcall, select, debug.traceback; local log = require "util.logger".init("http"); local print = function () end local urlcodes = setmetatable({}, { __index = function (t, k) t[k] = char(tonumber("0x"..k)); return t[k]; end }); local urlencode = function (s) return s and (s:gsub("%W", function (c) return string.format("%%%02x", c:byte()); end)); end module "http" local function expectbody(reqt, code) if reqt.method == "HEAD" then return nil end if code == 204 or code == 304 then return nil end if code >= 100 and code < 200 then return nil end return 1 end local function request_reader(request, data, startpos) if not data then if request.body then log("debug", "Connection closed, but we have data, calling callback..."); request.callback(t_concat(request.body), request.code, request); elseif request.state ~= "completed" then -- Error.. connection was closed prematurely request.callback("connection-closed", 0, request); end destroy_request(request); request.body = nil; request.state = "completed"; return; end if request.state == "body" and request.state ~= "completed" then print("Reading body...") if not request.body then request.body = {}; request.havebodylength, request.bodylength = 0, tonumber(request.responseheaders["content-length"]); end if startpos then data = data:sub(startpos, -1) end t_insert(request.body, data); if request.bodylength then request.havebodylength = request.havebodylength + #data; if request.havebodylength >= request.bodylength then -- We have the body log("debug", "Have full body, calling callback"); if request.callback then request.callback(t_concat(request.body), request.code, request); end request.body = nil; request.state = "completed"; else print("", "Have "..request.havebodylength.." bytes out of "..request.bodylength); end end elseif request.state == "headers" then print("Reading headers...") local pos = startpos; local headers = request.responseheaders or {}; for line in data:sub(startpos, -1):gmatch("(.-)\r\n") do startpos = startpos + #line + 2; local k, v = line:match("(%S+): (.+)"); if k and v then headers[k:lower()] = v; print("Header: "..k:lower().." = "..v); elseif #line == 0 then request.responseheaders = headers; break; else print("Unhandled header line: "..line); end end -- Reached the end of the headers request.state = "body"; if #data > startpos then return request_reader(request, data, startpos); end elseif request.state == "status" then print("Reading status...") local http, code, text, linelen = data:match("^HTTP/(%S+) (%d+) (.-)\r\n()", startpos); code = tonumber(code); if not code then return request.callback("invalid-status-line", 0, request); end request.code, request.responseversion = code, http; if request.onlystatus or not expectbody(request, code) then if request.callback then request.callback(nil, code, request); end destroy_request(request); return; end request.state = "headers"; if #data > linelen then return request_reader(request, data, linelen); end end end local function handleerr(err) log("error", "Traceback[http]: %s: %s", tostring(err), debug_traceback()); end function request(u, ex, callback) local req = url.parse(u); if not (req and req.host) then return nil, "invalid-url"; end if not req.path then req.path = "/"; end local custom_headers, body; local default_headers = { ["Host"] = req.host, ["User-Agent"] = "Prosody XMPP Server" } if req.userinfo then default_headers["Authorization"] = "Basic "..mime.b64(req.userinfo); end if ex then custom_headers = ex.headers; req.onlystatus = ex.onlystatus; body = ex.body; if body then req.method = "POST "; default_headers["Content-Length"] = tostring(#body); default_headers["Content-Type"] = "application/x-www-form-urlencoded"; end if ex.method then req.method = ex.method; end end req.handler, req.conn = server.wrapclient(socket.tcp(), req.host, req.port or 80, listener, "*a"); req.write = req.handler.write; req.conn:settimeout(0); local ok, err = req.conn:connect(req.host, req.port or 80); if not ok and err ~= "timeout" then callback(nil, 0, req); return nil, err; end local request_line = { req.method or "GET", " ", req.path, " HTTP/1.1\r\n" }; if req.query then t_insert(request_line, 4, "?"); t_insert(request_line, 5, req.query); end req.write(t_concat(request_line)); local t = { [2] = ": ", [4] = "\r\n" }; if custom_headers then for k, v in pairs(custom_headers) do t[1], t[3] = k, v; req.write(t_concat(t)); default_headers[k] = nil; end end for k, v in pairs(default_headers) do t[1], t[3] = k, v; req.write(t_concat(t)); default_headers[k] = nil; end req.write("\r\n"); if body then req.write(body); end req.callback = function (content, code, request) log("debug", "Calling callback, status %s", code or "---"); return select(2, xpcall(function () return callback(content, code, request) end, handleerr)); end req.reader = request_reader; req.state = "status"; listener.register_request(req.handler, req); return req; end function destroy_request(request) if request.conn then request.handler.close() listener.disconnect(request.conn, "closed"); end end _M.urlencode = urlencode; return _M;
net.http: Don't throw error on invalid URLs. Fixes #56.
net.http: Don't throw error on invalid URLs. Fixes #56.
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
2c91493c6d5be3684c629894d1ab466bd14d8ad6
lua/plugins/treesitter.lua
lua/plugins/treesitter.lua
local nvim = require('nvim') local load_module = require('tools').load_module -- local sys = require('sys') local plugins = nvim.plugins local nvim_set_autocmd = nvim.nvim_set_autocmd -- local executable = nvim.executable -- local isdirectory = nvim.isdirectory local treesitter = load_module('nvim-treesitter.configs') if treesitter == nil then return false end local ensure_installed = { 'c', 'cpp', 'lua', 'bash', 'python', -- 'query', } local disable = nil if plugins.semshi ~= nil then disable = {'python'} end if plugins['vim-lsp-cxx-highlight'] ~= nil then disable = disable == nil and {'c', 'cpp'} or vim.list_extend(disable, {'c', 'cpp'}) end local commet_txtobj = nil if plugins['vim-textobj-comment'] == nil then commet_txtobj = '@comment.outer' end treesitter.setup{ ensure_installed = ensure_installed, highlight = { enable = true, disable = disable, }, textobjects = { swap = { enable = true, swap_next = { ["<leader>a"] = "@parameter.inner", ["<leader>m"] = "@function.outer", }, swap_previous = { ["<leader><leader>a"] = "@parameter.inner", ["<leader><leader>m"] = "@function.outer", }, }, select = { enable = true, keymaps = { ["af"] = "@conditional.outer", ["if"] = "@conditional.inner", ["am"] = "@function.outer", -- Same as [m, ]m "method" ["im"] = "@function.inner", ["as"] = "@class.outer", ["is"] = "@class.inner", ["ia"] = "@parameter.inner", ["aa"] = "@parameter.inner", ["ir"] = "@loop.inner", -- "repeat" mnemonic ["ar"] = "@loop.outer", ["ac"] = commet_txtobj, ["ic"] = commet_txtobj, }, }, move = { enable = true, goto_next_start = { ["]f"] = "@conditional.outer", ["]m"] = "@function.outer", ["]]"] = "@class.outer", ["]r"] = "@loop.outer", ["]a"] = "@parameter.inner", ["]c"] = "@comment.outer", }, goto_next_end = { ["]F"] = "@conditional.outer", ["]M"] = "@function.outer", ["]["] = "@class.outer", ["]R"] = "@loop.outer", ["]A"] = "@parameter.inner", ["]C"] = "@comment.outer", }, goto_previous_start = { ["[f"] = "@conditional.outer", ["[m"] = "@function.outer", ["[["] = "@class.outer", ["[r"] = "@loop.outer", ["[a"] = "@parameter.inner", ["[c"] = "@comment.outer", }, goto_previous_end = { ["[F"] = "@conditional.outer", ["[M"] = "@function.outer", ["[]"] = "@class.outer", ["[R"] = "@loop.outer", ["[A"] = "@parameter.inner", ["[C"] = "@comment.outer", }, }, }, refactor = { -- highlight_current_scope = { enable = true }, smart_rename = { enable = true, keymaps = { smart_rename = "<leader>r", }, }, highlight_definitions = { enable = true, disable = disable, }, navigation = { enable = true, keymaps = { goto_definition = "<A-d>", list_definitions = "<A-l>", -- list_definitions_toc = "<A-t>", goto_next_usage = "<A-n>", goto_previous_usage = "<A-N>", }, }, }, } if ensure_installed.bash ~= nil then ensure_installed[#ensure_installed + 1] = 'sh' end nvim_set_autocmd{ event = 'FileType', pattern = ensure_installed, cmd = 'setlocal foldmethod=expr foldexpr=nvim_treesitter#foldexpr()', group = 'TreesitterAutocmds', } return ensure_installed
local nvim = require('nvim') local load_module = require('tools').load_module -- local sys = require('sys') local plugins = nvim.plugins local nvim_set_autocmd = nvim.nvim_set_autocmd -- local executable = nvim.executable -- local isdirectory = nvim.isdirectory local treesitter = load_module('nvim-treesitter.configs') if treesitter == nil then return false end local ensure_installed = { 'c', 'cpp', 'lua', 'bash', 'python', -- 'query', } local disable = nil if plugins.semshi ~= nil then disable = {'python'} end if plugins['vim-lsp-cxx-highlight'] ~= nil then disable = disable == nil and {'c', 'cpp'} or vim.list_extend(disable, {'c', 'cpp'}) end local commet_txtobj = nil if plugins['vim-textobj-comment'] == nil then commet_txtobj = '@comment.outer' end treesitter.setup{ ensure_installed = ensure_installed, highlight = { enable = true, disable = disable, }, textobjects = { swap = { enable = true, swap_next = { ["<leader>a"] = "@parameter.inner", ["<leader>m"] = "@function.outer", }, swap_previous = { ["<leader><leader>a"] = "@parameter.inner", ["<leader><leader>m"] = "@function.outer", }, }, select = { enable = true, keymaps = { ["af"] = "@conditional.outer", ["if"] = "@conditional.inner", ["am"] = "@function.outer", -- Same as [m, ]m "method" ["im"] = "@function.inner", ["as"] = "@class.outer", ["is"] = "@class.inner", ["ia"] = "@parameter.inner", ["aa"] = "@parameter.inner", ["ir"] = "@loop.inner", -- "repeat" mnemonic ["ar"] = "@loop.outer", ["ac"] = commet_txtobj, ["ic"] = commet_txtobj, }, }, move = { enable = true, goto_next_start = { ["]f"] = "@conditional.outer", ["]m"] = "@function.outer", ["]]"] = "@class.outer", ["]r"] = "@loop.outer", ["]a"] = "@parameter.inner", ["]c"] = "@comment.outer", }, goto_next_end = { ["]F"] = "@conditional.outer", ["]M"] = "@function.outer", ["]["] = "@class.outer", ["]R"] = "@loop.outer", ["]A"] = "@parameter.inner", ["]C"] = "@comment.outer", }, goto_previous_start = { ["[f"] = "@conditional.outer", ["[m"] = "@function.outer", ["[["] = "@class.outer", ["[r"] = "@loop.outer", ["[a"] = "@parameter.inner", ["[c"] = "@comment.outer", }, goto_previous_end = { ["[F"] = "@conditional.outer", ["[M"] = "@function.outer", ["[]"] = "@class.outer", ["[R"] = "@loop.outer", ["[A"] = "@parameter.inner", ["[C"] = "@comment.outer", }, }, }, refactor = { -- highlight_current_scope = { enable = true }, smart_rename = { enable = true, keymaps = { smart_rename = "<leader>r", }, }, highlight_definitions = { enable = true, disable = disable, }, navigation = { enable = true, keymaps = { goto_definition = "<A-d>", list_definitions = "<A-l>", -- list_definitions_toc = "<A-t>", goto_next_usage = "<A-n>", goto_previous_usage = "<A-N>", }, }, }, } for i=0,#ensure_installed do if ensure_installed[i] == 'bash' then ensure_installed[#ensure_installed + 1] = 'sh' break end end nvim_set_autocmd{ event = 'FileType', pattern = ensure_installed, cmd = 'setlocal foldmethod=expr foldexpr=nvim_treesitter#foldexpr()', group = 'TreesitterAutocmds', } return ensure_installed
fix: bash treesitter folding
fix: bash treesitter folding
Lua
mit
Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim,Mike325/.vim
6d1135b6004094936a822ce9bba880b67a311416
kong/cmd/config.lua
kong/cmd/config.lua
local DB = require "kong.db" local log = require "kong.cmd.utils.log" local pl_path = require "pl.path" local pl_file = require "pl.file" local kong_global = require "kong.global" local declarative = require "kong.db.declarative" local conf_loader = require "kong.conf_loader" local kong_yml = require "kong.templates.kong_yml" local INIT_FILE = "kong.yml" local accepted_formats = { yaml = true, json = true, lua = true, } local function generate_init() if pl_file.access_time(INIT_FILE) then error(INIT_FILE .. " already exists in the current directory.\n" .. "Will not overwrite it.") end pl_file.write(INIT_FILE, kong_yml) end local function execute(args) log.disable() -- retrieve default prefix or use given one local default_conf = assert(conf_loader(args.conf, { prefix = args.prefix })) log.enable() assert(pl_path.exists(default_conf.prefix), "no such prefix: " .. default_conf.prefix) assert(pl_path.exists(default_conf.kong_env), "Kong is not running at " .. default_conf.prefix) -- load <PREFIX>/kong.conf containing running node's config local conf = assert(conf_loader(default_conf.kong_env)) if args.command == "init" then generate_init() os.exit(0) end if args.command == "db-import" then args.command = "db_import" end if args.command == "db_import" and conf.database == "off" then error("'kong config db_import' only works with a database.\n" .. "When using database=off, reload your declarative configuration\n" .. "using the /config endpoint.") end package.path = conf.lua_package_path .. ";" .. package.path local dc, err = declarative.new_config(conf) if not dc then error(err) end if args.command == "db_import" or args.command == "parse" then local filename = args[1] if not filename then error("expected a declarative configuration file; see `kong config --help`") end local dc_table, err_or_ver = dc:parse_file(filename, accepted_formats) if not dc_table then error("Failed parsing:\n" .. err_or_ver) end if args.command == "db_import" then log("parse successful, beginning import") _G.kong = kong_global.new() kong_global.init_pdk(_G.kong, conf, nil) -- nil: latest PDK local db = assert(DB.new(conf)) assert(db:init_connector()) assert(db:connect()) assert(db.plugins:load_plugin_schemas(conf.loaded_plugins)) _G.kong.db = db local ok, err = declarative.load_into_db(dc_table) if not ok then error("Failed importing:\n" .. err) end log("import successful") -- send anonymous report if reporting is not disabled if conf.anonymous_reports then local kong_reports = require "kong.reports" kong_reports.configure_ping(conf) kong_reports.toggle(true) local report = { decl_fmt_version = err_or_ver } kong_reports.send("config-db-import", report) end else -- parse log("parse successful:") log(declarative.to_yaml_string(dc_table)) end os.exit(0) end error("unknown command '" .. args.command .. "'") end local lapp = [[ Usage: kong config COMMAND [OPTIONS] Use declarative configuration files with Kong. The available commands are: init Generate an example config file to get you started. db_import <file> Import a declarative config file into the Kong database. parse <file> Parse a declarative config file (check its syntax) but do not load it into Kong. Options: -c,--conf (optional string) Configuration file. -p,--prefix (optional string) Override prefix directory. ]] return { lapp = lapp, execute = execute, sub_commands = { init = true, db_import = true, parse = true, }, }
local DB = require "kong.db" local log = require "kong.cmd.utils.log" local pl_path = require "pl.path" local pl_file = require "pl.file" local kong_global = require "kong.global" local declarative = require "kong.db.declarative" local conf_loader = require "kong.conf_loader" local kong_yml = require "kong.templates.kong_yml" local INIT_FILE = "kong.yml" local accepted_formats = { yaml = true, json = true, lua = true, } local function generate_init() if pl_file.access_time(INIT_FILE) then error(INIT_FILE .. " already exists in the current directory.\n" .. "Will not overwrite it.") end pl_file.write(INIT_FILE, kong_yml) end local function execute(args) log.disable() -- retrieve default prefix or use given one local default_conf = assert(conf_loader(args.conf, { prefix = args.prefix })) log.enable() assert(pl_path.exists(default_conf.prefix), "no such prefix: " .. default_conf.prefix) assert(pl_path.exists(default_conf.kong_env), "Kong is not running at " .. default_conf.prefix) -- load <PREFIX>/kong.conf containing running node's config local conf = assert(conf_loader(default_conf.kong_env)) if args.command == "init" then generate_init() os.exit(0) end if args.command == "db-import" then args.command = "db_import" end if args.command == "db_import" and conf.database == "off" then error("'kong config db_import' only works with a database.\n" .. "When using database=off, reload your declarative configuration\n" .. "using the /config endpoint.") end package.path = conf.lua_package_path .. ";" .. package.path local dc, err = declarative.new_config(conf) if not dc then error(err) end if args.command == "db_import" or args.command == "parse" then local filename = args[1] if not filename then error("expected a declarative configuration file; see `kong config --help`") end local dc_table, err_or_ver = dc:parse_file(filename, accepted_formats) if not dc_table then error("Failed parsing:\n" .. err_or_ver) end if args.command == "db_import" then log("parse successful, beginning import") _G.kong = kong_global.new() kong_global.init_pdk(_G.kong, conf, nil) -- nil: latest PDK local db = assert(DB.new(conf)) assert(db:init_connector()) assert(db:connect()) assert(db.plugins:load_plugin_schemas(conf.loaded_plugins)) _G.kong.db = db local ok, err = declarative.load_into_db(dc_table) if not ok then error("Failed importing:\n" .. err) end log("import successful") -- send anonymous report if reporting is not disabled if conf.anonymous_reports then local kong_reports = require "kong.reports" kong_reports.configure_ping(conf) kong_reports.toggle(true) local report = { decl_fmt_version = err_or_ver } kong_reports.send("config-db-import", report) end else -- parse log("parse successful") end os.exit(0) end error("unknown command '" .. args.command .. "'") end local lapp = [[ Usage: kong config COMMAND [OPTIONS] Use declarative configuration files with Kong. The available commands are: init Generate an example config file to get you started. db_import <file> Import a declarative config file into the Kong database. parse <file> Parse a declarative config file (check its syntax) but do not load it into Kong. Options: -c,--conf (optional string) Configuration file. -p,--prefix (optional string) Override prefix directory. ]] return { lapp = lapp, execute = execute, sub_commands = { init = true, db_import = true, parse = true, }, }
hotfix(cmd) fix output of `kong config parse`.
hotfix(cmd) fix output of `kong config parse`. Do not output the string `nil` upon a successful parse. Thanks @hbagdi for reporting.
Lua
apache-2.0
Mashape/kong,Kong/kong,Kong/kong,Kong/kong
ee4ef70706e7c8d6e99b48dc86e1eb4dc27e2d1a
premake4.lua
premake4.lua
solution "mojo" location "build" configurations { "debug", "release", "windows", "linux" } defines { "MOJO_STATIC_BUILD" } project "mojo" kind "ConsoleApp" language "C++" targetdir "bin" includedirs { "include" } files { "include/**.h", "include/**.hpp", "source/**.c", "source/**.cpp", } configuration "debug" targetsuffix "d" defines { "MOJO_DEBUG_BUILD" } flags { "Symbols" } configuration "release" defines { "MOJO_RELEASE_BUILD" } flags { "Optimize" } configuration "windows" defines { "_HAS_ITERATOR_DEBUGGING=0", "_SECURE_SCL=0", "GLFW_DLL" } links { "opengl32", "GLFWDLL", "FreeImage" } includedirs { "dependencies/glfw-2.7.3/include", "dependencies/glew-1.7.0/include", "dependencies/freeimage-3.15.2/include", "dependencies/freetype-2.4.9/include" } libdirs { "dependencies/glfw-2.7.3/lib-msvc100", "dependencies/glew-1.7.0/lib-msvc100", "dependencies/freeimage-3.15.2/lib-msvc100", "dependencies/freetype-2.4.9/lib-msvc100" } configuration { "debug", "windows" } links { "glew32d", "freetype2-d" } configuration { "release", "windows" } links { "glew32", "freetype2" } configuration "linux" links { "rt", "GL", "glfw", "GLEW", "freeimage", "freetype" } project "mjmc" kind "ConsoleApp" language "C" targetdir "bin/tools" includedirs { "include" } files { "tools/mjmc.c" } configuration "debug" targetsuffix "d" defines { "MOJO_DEBUG_BUILD" } flags { "Symbols" } configuration "release" defines { "MOJO_RELEASE_BUILD" } flags { "Optimize" } configuration "windows" defines { "_HAS_ITERATOR_DEBUGGING=0", "_SECURE_SCL=0" } includedirs { "dependencies/assimp-2.0.863/include" } libdirs { "dependencies/assimp-2.0.863/lib-msvc100" } configuration { "debug", "windows" } links { "assimpd" } configuration { "release", "windows" } links { "assimp" } configuration "linux"
solution "mojo" location "build" configurations { "debug", "release", "windows", "linux" } defines { "MOJO_STATIC_BUILD" } project "mojo" kind "ConsoleApp" language "C++" targetdir "bin" includedirs { "include" } files { "include/**.h", "include/**.hpp", "source/**.c", "source/**.cpp", } configuration "debug" targetsuffix "d" defines { "MOJO_DEBUG_BUILD" } flags { "Symbols" } configuration "release" defines { "MOJO_RELEASE_BUILD" } flags { "Optimize" } configuration "windows" defines { "_HAS_ITERATOR_DEBUGGING=0", "_SECURE_SCL=0", "GLFW_DLL" } links { "opengl32", "GLFWDLL", "FreeImage" } includedirs { "dependencies/glfw-2.7.3/include", "dependencies/glew-1.7.0/include", "dependencies/freeimage-3.15.2/include", "dependencies/freetype-2.4.9/include" } libdirs { "dependencies/glfw-2.7.3/lib-msvc100", "dependencies/glew-1.7.0/lib-msvc100", "dependencies/freeimage-3.15.2/lib-msvc100", "dependencies/freetype-2.4.9/lib-msvc100" } configuration { "debug", "windows" } links { "glew32d", "freetype2-d" } configuration { "release", "windows" } links { "glew32", "freetype2" } configuration "linux" links { "rt", "GL", "glfw", "GLEW", "freeimage", "freetype" } buildoptions { '`freetype-config --cflags`' } project "mjmc" kind "ConsoleApp" language "C" targetdir "bin/tools" includedirs { "include" } files { "tools/mjmc.c" } configuration "debug" targetsuffix "d" defines { "MOJO_DEBUG_BUILD" } flags { "Symbols" } configuration "release" defines { "MOJO_RELEASE_BUILD" } flags { "Optimize" } configuration "windows" defines { "_HAS_ITERATOR_DEBUGGING=0", "_SECURE_SCL=0" } includedirs { "dependencies/assimp-2.0.863/include" } libdirs { "dependencies/assimp-2.0.863/lib-msvc100" } configuration { "debug", "windows" } links { "assimpd" } configuration { "release", "windows" } links { "assimp" } configuration "linux"
FreeType fix on linux.
FreeType fix on linux.
Lua
mit
mtwilliams/mojo,mtwilliams/mojo,mtwilliams/mojo,mtwilliams/mojo,mtwilliams/mojo
c3fcd7f15f874f2494b0a7f16dee8bc828fee29c
AceModuleCore-3.0/AceModuleCore-3.0.lua
AceModuleCore-3.0/AceModuleCore-3.0.lua
local MAJOR, MINOR = "AceModuleCore-3.0", 0 local AceModuleCore, oldversion = LibStub:NewLibrary( MAJOR, MINOR ) local AceAddon = LibStub:GetLibrary("AceAddon-3.0") if not AceAddon then error(MAJOR.." requires AceAddon-3.0") end if not AceModuleCore then return elseif not oldversion then AceModuleCore.embeded = {} -- contains a list of namespaces this has been embeded into end local function safecall(func,...) if type(func) == "function" then local success, err = pcall(func,...) if not err:find("%.lua:%d+:") then err = (debugstack():match("\n(.-: )in.-\n") or "") .. err end geterrorhandler()(err) end end -- AceModuleCore:GetModule( name, [silent]) -- name (string) - unique module object name -- silent (boolean) - if true, module is optional, silently return nil if its not found -- -- throws an error if the addon object can not be found (except silent is set) -- returns the module object if found function GetModule(self, name, silent) if not silent and not self.modules[name] then error(("Cannot find a module named '%s'."):format(name), 2) end return self.modules[name] end -- AceModuleCore:NewModule( name, [prototype, [lib, lib, lib, ...] ) -- name (string) - unique module object name for this addon -- prototype (object) - object to derive this module from, methods and values from this table will be mixed into the module, if a string is passed a lib is assumed -- [lib] (string) - optional libs to embed in the addon object -- -- returns the addon object when succesful function NewModule(self, name, prototype, ... ) assert( type( name ) == "string", "Bad argument #2 to 'NewModule' (string expected)" ) assert( type( prototype ) == "string" or type( prototype ) == "string" or type( prototype ) == "nil" ), "Bad argument #3 to 'NewModule' (string, table or nil expected)" ) if self.modules[name] then error( ("Module '%s' already exists."):format(name), 2 ) end local module = AceAddon:NewAddon(string.format("%s_%s", self.name or tostring(self), name) if type( prototype ) == "table" then module = AceAddon:EmbedLibraries( module, ... ) setmetatable(module, {__index=prototype}) -- More of a Base class type feel. elseif prototype then module = AceAddon:EmbedLibraries( module, prototype, ... ) end safecall(module.OnModuleCreated, self) -- Was in Ace2 and I think it could be a cool thing to have handy. self.modules[name] = module return module end local mixins = {NewModule = NewModule, GetModule = GetModule, modules = {}} -- AceModuleCore:Embed( target ) -- target (object) - target object to embed the modulecore in -- -- Embeds acemodule core into the target object function AceModuleCore:Embed( target ) for k, v in pairs( mixins ) do target[k] = v end table.insert(self.embeded, target) end function AceModuleCore:OnEmbedEnable( target ) for name, module in pairs( target.modules ) do AceAddon:EnableAddon( module ) end end function AceModuleCore:OnEmbedDisable( target ) for name, module in pairs( target.modules ) do AceAddon:DisableAddon( module ) end end
local MAJOR, MINOR = "AceModuleCore-3.0", 0 local AceModuleCore, oldversion = LibStub:NewLibrary( MAJOR, MINOR ) local AceAddon = LibStub:GetLibrary("AceAddon-3.0") if not AceAddon then error(MAJOR.." requires AceAddon-3.0") end if not AceModuleCore then return elseif not oldversion then AceModuleCore.embeded = {} -- contains a list of namespaces this has been embeded into end local function safecall(func,...) if type(func) == "function" then local success, err = pcall(func,...) if not err:find("%.lua:%d+:") then err = (debugstack():match("\n(.-: )in.-\n") or "") .. err end geterrorhandler()(err) end end -- AceModuleCore:GetModule( name, [silent]) -- name (string) - unique module object name -- silent (boolean) - if true, module is optional, silently return nil if its not found -- -- throws an error if the addon object can not be found (except silent is set) -- returns the module object if found function GetModule(self, name, silent) if not silent and not self.modules[name] then error(("Cannot find a module named '%s'."):format(name), 2) end return self.modules[name] end -- AceModuleCore:NewModule( name, [prototype, [lib, lib, lib, ...] ) -- name (string) - unique module object name for this addon -- prototype (object) - object to derive this module from, methods and values from this table will be mixed into the module, if a string is passed a lib is assumed -- [lib] (string) - optional libs to embed in the addon object -- -- returns the addon object when succesful function NewModule(self, name, prototype, ... ) assert( type( name ) == "string", "Bad argument #2 to 'NewModule' (string expected)" ) assert( type( prototype ) == "string" or type( prototype ) == "string" or type( prototype ) == "nil" ), "Bad argument #3 to 'NewModule' (string, table or nil expected)" ) if self.modules[name] then error( ("Module '%s' already exists."):format(name), 2 ) end local module = AceAddon:NewAddon( ("%s_%s"):format( self.name or tostring(self), name) ) if type( prototype ) == "table" then module = AceAddon:EmbedLibraries( module, ... ) setmetatable(module, {__index=prototype}) -- More of a Base class type feel. elseif prototype then module = AceAddon:EmbedLibraries( module, prototype, ... ) end safecall(module.OnModuleCreated, self) -- Was in Ace2 and I think it could be a cool thing to have handy. self.modules[name] = module return module end local mixins = {NewModule = NewModule, GetModule = GetModule, modules = {}} -- AceModuleCore:Embed( target ) -- target (object) - target object to embed the modulecore in -- -- Embeds acemodule core into the target object function AceModuleCore:Embed( target ) for k, v in pairs( mixins ) do target[k] = v end table.insert(self.embeded, target) end function AceModuleCore:OnEmbedInitialize( target ) do for name, module in pairs( target.modules ) do AceAddon:InitializeAddon( module ) -- this whole deal needs serious testing end end function AceModuleCore:OnEmbedEnable( target ) for name, module in pairs( target.modules ) do AceAddon:EnableAddon( module ) -- this whole deal needs serious testing end end function AceModuleCore:OnEmbedDisable( target ) for name, module in pairs( target.modules ) do AceAddon:DisableAddon( module ) - this whole deal needs serious testing end end
Ace3: AceModuleCore-3.0 - cleanup, add OnInit handling, fix typo in NewModule
Ace3: AceModuleCore-3.0 - cleanup, add OnInit handling, fix typo in NewModule git-svn-id: 00c2b8bc9b083c53e126de03a83516ee6a3b87d9@13 5debad98-a965-4143-8383-f471b3509dcf
Lua
bsd-3-clause
sarahgerweck/Ace3
7358aa7f96a3e6bf2f511619c3b0a9dadeeeae33
premake4.lua
premake4.lua
_G.package.path=_G.package.path..[[;./?.lua;./?/?.lua]] assert( require 'premake.quickstart' ) make_solution 'picojson_serializer' configurations { "gcov" } local CURRENT_VERSION = 'v0.9.0' local OS = os.get() local settings = { includedirs = { linux = {}, windows = { './msinttypes' }, macosx = {} } } make_console_app('picojson_serializer_test', { './*.h', './test/*.cpp', './test/*.h' } ) configuration { "linux", "gcov" } flags { "Symbols" } links { "gcov" } buildoptions { "-coverage" } configuration { "*" } includedirs { '.', './Catch/single_include', './picojson', settings.includedirs[OS] } run_target_after_build() make_package( { '*.h', 'picojson/*', 'README.md' }, 'picojson_serializer-' .. CURRENT_VERSION )
include 'premake' make_solution 'picojson_serializer' configurations { "gcov" } local CURRENT_VERSION = 'v0.9.0' local OS = os.get() local local_settings = { includedirs = { linux = {}, windows = { './msinttypes' }, macosx = {} } } make_console_app('picojson_serializer_test', { './*.h', './test/*.cpp', './test/*.h' } ) configuration { "linux", "gcov" } flags { "Symbols" } links { "gcov" } buildoptions { "-coverage" } configuration { "*" } includedirs { '.', './Catch/single_include', './picojson', local_settings.includedirs[OS] } run_target_after_build() local release = dofile 'premake/release.lua' release.make_package( { '*.h', 'picojson/*', 'README.md' }, 'picojson_serializer-' .. CURRENT_VERSION )
fix linux build
fix linux build
Lua
mit
d-led/picojson_serializer,d-led/picojson_serializer
0ad61a92f20627411cc7cacd8acd6a8350139a54
qd_offer.lua
qd_offer.lua
--[[ USAGE: redis-cli --eval qd_offer.lua {name} , {value} * `name` - Name of a qdigest instance: used as a redis key. * `value` - Value to offer. --]] local function value2leaf(capacity, value) return value + capacity + 1 end local function getNewCapacity(value) capacity = 1 while capacity < value do capacity = capacity * 2 end return capacity end local function get(key) return redis.call('HGETALL', key) end local function set(key, data) redis.call('DEL', key) -- TODO: fix method to call HMSET redis.call('HMSET', key, data) end local function getDataKeys(data) local keys = {} for k, v in pairs(data) do local k = tonumber(k) if k ~= nil then table.insert(keys, k) end end table.sort(keys) return keys end local function extendCapacity(key, value, capacity) local newCapacity = getNewCapacity(value) local scaleR = newCapacity / capacity - 1 local scaleL = 1 local data = get(key) local keys = getDataKeys(data) local newdata = {} for i, k in ipairs(keys) do while scaleL <= k / 2 do scaleL = scaleL * 2 end newdata[k + scaleL * scaleR] = data[k] end newdata['capacity'] = data['capacity'] newdata['factor'] = data['factor'] newdata['size'] = data['size'] compressDataFully(newdata) set(key, data) end local function compressUpward(key, id, factor) -- TODO: end local function compressFully(key) local data = get(key) compressDataFully(data) set(key, data) end local function compressDataFully(data) -- TODO: end local function compress(key, id, factor) compressUpward(key, id, factor) local size = redis.call('HLEN', key) - 3 if size > 3 * factor then compressFully(key) end end local function qd_offer(key, value) local info = redis.call('HGET', key, 'capacity', 'factor') local capacity, factor = info[1], info[2] if value < 0 then return 0 elseif value > capacity then extendCapacity(key, value, capacity) end local id = value2leaf(capacity, value) redis.call('HINCRBY', key, id, 1) redis.call('HINCRBY', key, 'size', 1) compress(key, id, factor) return 1 end return qd_offer(KEY[1], ARGV[1])
--[[ USAGE: redis-cli --eval qd_offer.lua {name} , {value} * `name` - Name of a qdigest instance: used as a redis key. * `value` - Value to offer. --]] local function value2leaf(capacity, value) return value + capacity + 1 end local function getNewCapacity(value) capacity = 1 while capacity < value do capacity = capacity * 2 end return capacity end local function get(key) return redis.call('HGETALL', key) end local function set(key, data) redis.call('DEL', key) redis.call('HMSET', key, kvunpack(data)) end local function kvunpack(t) local r = {} for k, v in pairs(t) do table.insert(r, k) table.insert(r, v) end return unpack(r) end local function getDataKeys(data) local keys = {} for k, v in pairs(data) do local k = tonumber(k) if k ~= nil then table.insert(keys, k) end end table.sort(keys) return keys end local function extendCapacity(key, value, capacity) local newCapacity = getNewCapacity(value) local scaleR = newCapacity / capacity - 1 local scaleL = 1 local data = get(key) local keys = getDataKeys(data) local newdata = {} for i, k in ipairs(keys) do while scaleL <= k / 2 do scaleL = scaleL * 2 end newdata[k + scaleL * scaleR] = data[k] end newdata['capacity'] = data['capacity'] newdata['factor'] = data['factor'] newdata['size'] = data['size'] compressDataFully(newdata) set(key, data) end local function compressUpward(key, id, factor) -- TODO: end local function compressFully(key) local data = get(key) compressDataFully(data) set(key, data) end local function compressDataFully(data) -- TODO: end local function compress(key, id, factor) compressUpward(key, id, factor) local size = redis.call('HLEN', key) - 3 if size > 3 * factor then compressFully(key) end end local function qd_offer(key, value) local info = redis.call('HGET', key, 'capacity', 'factor') local capacity, factor = info[1], info[2] if value < 0 then return 0 elseif value > capacity then extendCapacity(key, value, capacity) end local id = value2leaf(capacity, value) redis.call('HINCRBY', key, id, 1) redis.call('HINCRBY', key, 'size', 1) compress(key, id, factor) return 1 end return qd_offer(KEY[1], ARGV[1])
fix the method to call HMSET
fix the method to call HMSET
Lua
mit
koron/redis-qdigest,koron/redis-qdigest
bbef9dfbd45fb668d1dce54ca8dbb5ea7af1983b
Cache.lua
Cache.lua
local L = EPGPGlobalStrings local mod = EPGP:NewModule("EPGP_Cache", "AceEvent-2.0") function mod:OnInitialize() self.guild_member_count = 0 end function mod:OnEnable() self:RegisterEvent("GUILD_ROSTER_UPDATE") self:RegisterEvent("PLAYER_GUILD_UPDATE") self:RegisterEvent("CHAT_MSG_ADDON") self:GuildRosterNow() end function mod:LoadConfig() local lines = {string.split("\n", GetGuildInfoText() or "")} local in_block = false local outsiders = {} local dummies = {} for _,line in pairs(lines) do if line == "-EPGP-" then in_block = not in_block elseif in_block then -- Get options and alts -- Format is: -- @DECAY_P:<number> // for decay percent (defaults to 10) -- @MIN_EP:<number> // for min eps until member can need items (defaults to 1000) -- @FC // for flat credentials (true if specified, false otherwise) -- Decay percent local dp = line:match("@DECAY_P:(%d+)") if dp then dp = tonumber(dp) if dp and dp >= 0 and dp <= 100 then EPGP.db.profile.decay_percent = dp else EPGP:Print(L["Decay Percent should be a number between 0 and 100"]) end end -- Min EPs local mep = tonumber(line:match("@MIN_EP:(%d+)")) if mep then if mep and mep >= 0 then EPGP.db.profile.min_eps = mep else EPGP:Print(L["Min EPs should be a positive number"]) end end -- Base GP local bgp = tonumber(line:match("@BASE_GP:(%d+)")) if bgp then if bgp and bgp >= 0 then EPGP.db.profile.base_gp = bgp else EPGP:Print(L["Base GP should be a positive number"]) end end -- Flat Credentials local fc = line:match("@FC") if fc then EPGP.db.profile.flat_credentials = true end -- Read in Outsiders for outsider, dummy in line:gmatch("(%a+):(%a+)") do outsiders[outsider] = dummy dummies[dummy] = outsider end end end EPGP.db.profile.outsiders = outsiders EPGP.db.profile.dummies = dummies end local function GetMemberData(obj, name) if obj:IsOutsider(name) then return EPGP.db.profile.data[EPGP.db.profile.outsiders[name]] elseif obj:IsAlt(name) then return EPGP.db.profile.data[EPGP.db.profile.alts[name]] else return EPGP.db.profile.data[name] end end function mod:IsAlt(name) return not not EPGP.db.profile.alts[name] end function mod:IsOutsider(name) return not not EPGP.db.profile.outsiders[name] end function mod:IsDummy(name) return not not EPGP.db.profile.dummies[name] end function mod:GetMemberEPGP(name) local t = GetMemberData(self, name) if not t then return else return unpack(t) end end function mod:GetMemberInfo(name) local guild_name = name if self:IsOutsider(name) then guild_name = EPGP.db.profile.outsiders[name] end local t = EPGP.db.profile.info[guild_name] if t then return unpack(t) end end function mod:SetMemberEPGP(name, ep, gp) assert(type(ep) == "number" and ep >= 0 and ep <= 999999999999999) assert(type(gp) == "number" and gp >= 0 and gp <= 999999999999999) local t = GetMemberData(self, name) t[1] = ep t[2] = gp end local function ParseNote(note) if note == "" then return 0, EPGP.db.profile.base_gp end local ep, tep, gp, tgp = string.match(note, "^(%d+)|(%d+)|(%d+)|(%d+)$") tgp = tgp + EPGP.db.profile.base_gp if ep then return tonumber(ep) + tonumber(tep), tonumber(gp) + tonumber(tgp) end ep, gp = string.match(note, "^(%d+)|(%d+)$") return tonumber(ep), tonumber(gp) + EPGP.db.profile.base_gp end function mod:LoadRoster() local data = {} local info = {} local alts = {} for i = 1, GetNumGuildMembers(true) do local name, rank, rankIndex, level, class, zone, note, officernote, online, status = GetGuildRosterInfo(i) -- This is an alt and officernote stores the main if string.match(officernote, "%u%l*") == officernote then alts[name] = officernote data[name] = nil -- This is a main and officernote stores EPGP else data[name] = { ParseNote(officernote) } end info[name] = { rank, rankIndex, level, class, zone, note, officernote, online, status } end EPGP.db.profile.data = data EPGP.db.profile.info = info EPGP.db.profile.alts = alts local old_count = self.guild_member_count self.guild_member_count = GetNumGuildMembers(true) EPGP:Debug("old:%d new:%d", old_count, self.guild_member_count) return old_count ~= self.guild_member_count end local function EncodeNote(ep, gp) gp = gp - EPGP.db.profile.base_gp if gp < 0 then gp = 0 end return string.format("%d|%d|%d|%d", 0, ep, 0, gp) end function mod:SaveRoster() for i = 1, GetNumGuildMembers(true) do local name, _, _, _, _, _, _, officernote, _, _ = GetGuildRosterInfo(i) if not self:IsAlt(name) then local ep, tep, gp, tgp = self:GetMemberEPGP(name) if ep then local new_officernote = EncodeNote(ep, tep, gp, tgp) if new_officernote ~= officernote then GuildRosterSetOfficerNote(i, new_officernote) end end end end EPGP:Debug("Notes changed - sending update to guild") SendAddonMessage("EPGP", "UPDATE", "GUILD") end function mod:GuildRosterNow() if not IsInGuild() then return end GuildRoster() self.last_guild_roster_time = GetTime() end function mod:GuildRoster() if not IsInGuild() then return end if not self.last_guild_roster_time then self:GuildRosterNow() elseif not self:IsEventScheduled("DELAYED_GUILD_ROSTER_UPDATE") then local elapsed = GetTime() - self.last_guild_roster_time if elapsed > 10 then self:GuildRosterNow() else self:ScheduleEvent("DELAYED_GUILD_ROSTER_UPDATE", mod.GuildRoster, 10 - elapsed, self) end end end function mod:PLAYER_GUILD_UPDATE() self:GuildRoster() end function mod:GUILD_ROSTER_UPDATE(local_update) local guild_name = GetGuildInfo("player") if guild_name and guild_name ~= EPGP:GetProfile() then EPGP:SetProfile(guild_name) end if local_update then self:GuildRosterNow() return end EPGP:Debug("Reloading roster and config from game") self:LoadConfig() local member_change = self:LoadRoster() self:TriggerEvent("EPGP_CACHE_UPDATE", member_change) end function mod:CHAT_MSG_ADDON(prefix, msg, type, sender) if prefix == "EPGP" then EPGP:Debug("Processing CHAT_MSG_ADDON(%s,%s,%s,%s)", prefix, msg, type, sender) if sender == UnitName("player") then return end if msg == "UPDATE" then self:GuildRoster() end end end
local L = EPGPGlobalStrings local mod = EPGP:NewModule("EPGP_Cache", "AceEvent-2.0") function mod:OnInitialize() self.guild_member_count = 0 end function mod:OnEnable() self:RegisterEvent("GUILD_ROSTER_UPDATE") self:RegisterEvent("PLAYER_GUILD_UPDATE") self:RegisterEvent("CHAT_MSG_ADDON") self:GuildRosterNow() end function mod:LoadConfig() local lines = {string.split("\n", GetGuildInfoText() or "")} local in_block = false local outsiders = {} local dummies = {} for _,line in pairs(lines) do if line == "-EPGP-" then in_block = not in_block elseif in_block then -- Get options and alts -- Format is: -- @DECAY_P:<number> // for decay percent (defaults to 10) -- @MIN_EP:<number> // for min eps until member can need items (defaults to 1000) -- @FC // for flat credentials (true if specified, false otherwise) -- Decay percent local dp = line:match("@DECAY_P:(%d+)") if dp then dp = tonumber(dp) if dp and dp >= 0 and dp <= 100 then EPGP.db.profile.decay_percent = dp else EPGP:Print(L["Decay Percent should be a number between 0 and 100"]) end end -- Min EPs local mep = tonumber(line:match("@MIN_EP:(%d+)")) if mep then if mep and mep >= 0 then EPGP.db.profile.min_eps = mep else EPGP:Print(L["Min EPs should be a positive number"]) end end -- Base GP local bgp = tonumber(line:match("@BASE_GP:(%d+)")) if bgp then if bgp and bgp >= 0 then EPGP.db.profile.base_gp = bgp else EPGP:Print(L["Base GP should be a positive number"]) end end -- Flat Credentials local fc = line:match("@FC") if fc then EPGP.db.profile.flat_credentials = true end -- Read in Outsiders for outsider, dummy in line:gmatch("(%a+):(%a+)") do outsiders[outsider] = dummy dummies[dummy] = outsider end end end EPGP.db.profile.outsiders = outsiders EPGP.db.profile.dummies = dummies end local function GetMemberData(obj, name) if obj:IsOutsider(name) then return EPGP.db.profile.data[EPGP.db.profile.outsiders[name]] elseif obj:IsAlt(name) then return EPGP.db.profile.data[EPGP.db.profile.alts[name]] else return EPGP.db.profile.data[name] end end function mod:IsAlt(name) return not not EPGP.db.profile.alts[name] end function mod:IsOutsider(name) return not not EPGP.db.profile.outsiders[name] end function mod:IsDummy(name) return not not EPGP.db.profile.dummies[name] end function mod:GetMemberEPGP(name) local t = GetMemberData(self, name) if not t then return else return unpack(t) end end function mod:GetMemberInfo(name) local guild_name = name if self:IsOutsider(name) then guild_name = EPGP.db.profile.outsiders[name] end local t = EPGP.db.profile.info[guild_name] if t then return unpack(t) end end function mod:SetMemberEPGP(name, ep, gp) assert(type(ep) == "number" and ep >= 0 and ep <= 999999999999999) assert(type(gp) == "number" and gp >= 0 and gp <= 999999999999999) local t = GetMemberData(self, name) t[1] = ep t[2] = gp end local function ParseNote(note) if note == "" then return 0, EPGP.db.profile.base_gp end local ep, tep, gp, tgp = string.match(note, "^(%d+)|(%d+)|(%d+)|(%d+)$") if ep then return tonumber(ep) + tonumber(tep), tonumber(gp) + tonumber(tgp) + EPGP.db.profile.base_gp end ep, gp = string.match(note, "^(%d+)|(%d+)$") return tonumber(ep), tonumber(gp) + EPGP.db.profile.base_gp end function mod:LoadRoster() local data = {} local info = {} local alts = {} for i = 1, GetNumGuildMembers(true) do local name, rank, rankIndex, level, class, zone, note, officernote, online, status = GetGuildRosterInfo(i) -- This is an alt and officernote stores the main if string.match(officernote, "%u%l*") == officernote then alts[name] = officernote data[name] = nil -- This is a main and officernote stores EPGP else data[name] = { ParseNote(officernote) } end info[name] = { rank, rankIndex, level, class, zone, note, officernote, online, status } end EPGP.db.profile.data = data EPGP.db.profile.info = info EPGP.db.profile.alts = alts local old_count = self.guild_member_count self.guild_member_count = GetNumGuildMembers(true) EPGP:Debug("old:%d new:%d", old_count, self.guild_member_count) return old_count ~= self.guild_member_count end local function EncodeNote(ep, gp) gp = gp - EPGP.db.profile.base_gp if gp < 0 then gp = 0 end return string.format("%d|%d|%d|%d", 0, ep, 0, gp) end function mod:SaveRoster() for i = 1, GetNumGuildMembers(true) do local name, _, _, _, _, _, _, officernote, _, _ = GetGuildRosterInfo(i) if not self:IsAlt(name) then local ep, tep, gp, tgp = self:GetMemberEPGP(name) if ep then local new_officernote = EncodeNote(ep, tep, gp, tgp) if new_officernote ~= officernote then GuildRosterSetOfficerNote(i, new_officernote) end end end end EPGP:Debug("Notes changed - sending update to guild") SendAddonMessage("EPGP", "UPDATE", "GUILD") end function mod:GuildRosterNow() if not IsInGuild() then return end GuildRoster() self.last_guild_roster_time = GetTime() end function mod:GuildRoster() if not IsInGuild() then return end if not self.last_guild_roster_time then self:GuildRosterNow() elseif not self:IsEventScheduled("DELAYED_GUILD_ROSTER_UPDATE") then local elapsed = GetTime() - self.last_guild_roster_time if elapsed > 10 then self:GuildRosterNow() else self:ScheduleEvent("DELAYED_GUILD_ROSTER_UPDATE", mod.GuildRoster, 10 - elapsed, self) end end end function mod:PLAYER_GUILD_UPDATE() self:GuildRoster() end function mod:GUILD_ROSTER_UPDATE(local_update) local guild_name = GetGuildInfo("player") if guild_name and guild_name ~= EPGP:GetProfile() then EPGP:SetProfile(guild_name) end if local_update then self:GuildRosterNow() return end EPGP:Debug("Reloading roster and config from game") self:LoadConfig() local member_change = self:LoadRoster() self:TriggerEvent("EPGP_CACHE_UPDATE", member_change) end function mod:CHAT_MSG_ADDON(prefix, msg, type, sender) if prefix == "EPGP" then EPGP:Debug("Processing CHAT_MSG_ADDON(%s,%s,%s,%s)", prefix, msg, type, sender) if sender == UnitName("player") then return end if msg == "UPDATE" then self:GuildRoster() end end end
Fix error on empty/unparsable officer notes.
Fix error on empty/unparsable officer notes.
Lua
bsd-3-clause
protomech/epgp-dkp-reloaded,hayword/tfatf_epgp,sheldon/epgp,sheldon/epgp,hayword/tfatf_epgp,ceason/epgp-tfatf,ceason/epgp-tfatf,protomech/epgp-dkp-reloaded
90ddff8afaa5873490d1ab4285579d5b2e1540c7
mods/esmobs/init.lua
mods/esmobs/init.lua
--esmobs v01.0 --maikerumine --made for Extreme Survival game --License for code WTFPL --[[ DEPENDS: default inventory_plus? farming? bones? intllib? es? farorb? jdukebox? ]] esmobs={} --API AND CONFIG dofile(minetest.get_modpath("esmobs").."/config.lua") dofile(minetest.get_modpath("esmobs").."/api.lua") dofile(minetest.get_modpath("esmobs").."/zmastermoblist.lua") --All mobs reside in here, the spawning is handles by groups in the mob settings below. This ensures no unknown nodes during switching. --MOB SETTINGS leave this alone, use config file to change. if (esmobs.MOB_SETTING == 1) then --Just Animals. dofile(minetest.get_modpath("esmobs").."/esanimal.lua") end if (esmobs.MOB_SETTING == 2) then --Animals and good npc's. dofile(minetest.get_modpath("esmobs").."/esanimal.lua") dofile(minetest.get_modpath("esmobs").."/esnpc.lua") if es then dofile(minetest.get_modpath("esmobs").."/esnpc2.lua") end end if (esmobs.MOB_SETTING == 3) then --Animals, Good npc, and MT monsters. dofile(minetest.get_modpath("esmobs").."/esanimal.lua") dofile(minetest.get_modpath("esmobs").."/esnpc.lua") dofile(minetest.get_modpath("esmobs").."/mtmonster.lua") if es then dofile(minetest.get_modpath("esmobs").."/esnpc2.lua") end end if (esmobs.MOB_SETTING == 4) then --Animals, Good npc, MT monsters, and MC like mobs. dofile(minetest.get_modpath("esmobs").."/esanimal.lua") dofile(minetest.get_modpath("esmobs").."/esnpc.lua") dofile(minetest.get_modpath("esmobs").."/mtmonster.lua") dofile(minetest.get_modpath("esmobs").."/mcmonster.lua") if es then dofile(minetest.get_modpath("esmobs").."/esnpc2.lua") end end if (esmobs.MOB_SETTING == 5) then --Animals, Good npc, MT monsters, ES monsters, MC like mobs, and Bad npc's. All 76 of them. dofile(minetest.get_modpath("esmobs").."/esanimal.lua") dofile(minetest.get_modpath("esmobs").."/esnpc.lua") dofile(minetest.get_modpath("esmobs").."/mtmonster.lua") dofile(minetest.get_modpath("esmobs").."/mcmonster.lua") dofile(minetest.get_modpath("esmobs").."/esbadplayer.lua") dofile(minetest.get_modpath("esmobs").."/esmonster.lua") if es then dofile(minetest.get_modpath("esmobs").."/esnpc2.lua") dofile(minetest.get_modpath("esmobs").."/esbadplayer2.lua") end end if (esmobs.MOB_SETTING == 6) then --MT Monsters, Bad npc's. dofile(minetest.get_modpath("esmobs").."/mtmonster.lua") dofile(minetest.get_modpath("esmobs").."/esbadplayer.lua") if es then dofile(minetest.get_modpath("esmobs").."/esbadplayer2.lua") end end if (esmobs.MOB_SETTING == 7) then --Good npc, Bad npc's. dofile(minetest.get_modpath("esmobs").."/esnpc.lua") dofile(minetest.get_modpath("esmobs").."/esbadplayer.lua") if es then dofile(minetest.get_modpath("esmobs").."/esnpc2.lua") dofile(minetest.get_modpath("esmobs").."/esbadplayer2.lua") end end if (esmobs.MOB_SETTING == 8) then --MC like mobs and Animals. dofile(minetest.get_modpath("esmobs").."/esanimal.lua") dofile(minetest.get_modpath("esmobs").."/mcmonster.lua") end if (esmobs.MOB_SETTING == 9) then --MT monsters and Animals. dofile(minetest.get_modpath("esmobs").."/esanimal.lua") dofile(minetest.get_modpath("esmobs").."/mtmonster.lua") end if (esmobs.MOB_SETTING == 10) then --Good npc's. dofile(minetest.get_modpath("esmobs").."/esnpc.lua") if es then dofile(minetest.get_modpath("esmobs").."/esnpc2.lua") end end if (esmobs.MOB_SETTING == 11) then --MT monsters, ES monsters, MC like mobs, and Bad npc's. dofile(minetest.get_modpath("esmobs").."/mtmonster.lua") dofile(minetest.get_modpath("esmobs").."/mcmonster.lua") dofile(minetest.get_modpath("esmobs").."/esbadplayer.lua") dofile(minetest.get_modpath("esmobs").."/esmonster.lua") if es then dofile(minetest.get_modpath("esmobs").."/esbadplayer2.lua") end end if (esmobs.MOB_SETTING == 12) then --MT Monsters. dofile(minetest.get_modpath("esmobs").."/mtmonster.lua") end --MOBS --dofile(minetest.get_modpath("esmobs").."/esnpc.lua") --dofile(minetest.get_modpath("esmobs").."/esmonster.lua") --dofile(minetest.get_modpath("esmobs").."/mtmonster.lua") --dofile(minetest.get_modpath("esmobs").."/esbadplayer.lua") --dofile(minetest.get_modpath("esmobs").."/esbadplayer2.lua") --dofile(minetest.get_modpath("esmobs").."/esanimal.lua") --dofile(minetest.get_modpath("esmobs").."/mcmobs.lua") --CRAFTS AND MISC dofile(minetest.get_modpath("esmobs").."/crafts.lua") dofile(minetest.get_modpath("esmobs").."/spawner.lua") --MOB SEPCS if inventory_plus then dofile(minetest.get_modpath("esmobs").."/mobspec.lua") end --IF ES IS LOADED YOU WILL SEE OTHER MOBS HOLDING THE SPECIAL TOOLS --if es then --dofile(minetest.get_modpath("esmobs").."/esnpc2.lua") --end --if es then --dofile(minetest.get_modpath("esmobs").."/esbadplayer2.lua") --end --IN CASE BONES IS NOT INSTALLED, THIS OVERRIDES NODES SO YOU HAVE THEM FOR MOBS. if not bones then dofile(minetest.get_modpath("esmobs").."/bones.lua") minetest.register_alias("bones:bones", "esmobs:bones") end if bones then minetest.register_alias("esmobs:bones", "bones:bones") end --IN CASE THROWING IS NOT INSTALLED, THIS DOSEN'T LOAD MCMOBS if not throwing then dofile(minetest.get_modpath("esmobs").."/throwing.lua") minetest.register_alias("throwing:arrow_entity", "esmobs:throwing_entity") minetest.register_alias("throwing:bow", "esmobs:bow") minetest.register_alias("throwing:arrow", "esmobs:arrow") end if throwing then minetest.register_alias("esmobs:arrow_entity", "throwing:arrow_entity") minetest.register_alias("esmobs:bow", "throwing:bow") minetest.register_alias("esmobs:arrow", "throwing:arrow") end print("[ES-Mobs] Extreme") print("[ES-Mobs] Survival") print("[ES-Mobs] Mobs") print("[ES-Mobs] Loaded!") if minetest.setting_get("log_mods") then minetest.log("action", "esmobs mobs loaded") end
--esmobs v01.0 --maikerumine --made for Extreme Survival game --License for code WTFPL --[[ DEPENDS: default inventory_plus? farming? bones? intllib? es? farorb? jdukebox? ]] esmobs={} --API AND CONFIG --dofile(minetest.get_modpath("esmobs").."/config.lua") dofile(minetest.get_modpath("esmobs").."/api.lua") dofile(minetest.get_modpath("esmobs").."/zmastermoblist.lua") --All mobs reside in here, the spawning is handles by groups in the mob settings below. This ensures no unknown nodes during switching. --BECAUSE I SUCK AT PROGRAMMING THIS IS THE OVER RIDE TO THE BELOW CODE dofile(minetest.get_modpath("esmobs").."/esanimal.lua") dofile(minetest.get_modpath("esmobs").."/esnpc.lua") dofile(minetest.get_modpath("esmobs").."/mtmonster.lua") dofile(minetest.get_modpath("esmobs").."/mcmonster.lua") dofile(minetest.get_modpath("esmobs").."/esbadplayer.lua") dofile(minetest.get_modpath("esmobs").."/esmonster.lua") dofile(minetest.get_modpath("esmobs").."/esnpc2.lua") dofile(minetest.get_modpath("esmobs").."/esbadplayer2.lua") --[[ --MOB SETTINGS leave this alone, use config file to change. if (esmobs.MOB_SETTING == 1) then --Just Animals. dofile(minetest.get_modpath("esmobs").."/esanimal.lua") end if (esmobs.MOB_SETTING == 2) then --Animals and good npc's. dofile(minetest.get_modpath("esmobs").."/esanimal.lua") dofile(minetest.get_modpath("esmobs").."/esnpc.lua") if es then dofile(minetest.get_modpath("esmobs").."/esnpc2.lua") end end if (esmobs.MOB_SETTING == 3) then --Animals, Good npc, and MT monsters. dofile(minetest.get_modpath("esmobs").."/esanimal.lua") dofile(minetest.get_modpath("esmobs").."/esnpc.lua") dofile(minetest.get_modpath("esmobs").."/mtmonster.lua") if es then dofile(minetest.get_modpath("esmobs").."/esnpc2.lua") end end if (esmobs.MOB_SETTING == 4) then --Animals, Good npc, MT monsters, and MC like mobs. dofile(minetest.get_modpath("esmobs").."/esanimal.lua") dofile(minetest.get_modpath("esmobs").."/esnpc.lua") dofile(minetest.get_modpath("esmobs").."/mtmonster.lua") dofile(minetest.get_modpath("esmobs").."/mcmonster.lua") if es then dofile(minetest.get_modpath("esmobs").."/esnpc2.lua") end end if (esmobs.MOB_SETTING == 5) then --Animals, Good npc, MT monsters, ES monsters, MC like mobs, and Bad npc's. All 76 of them. dofile(minetest.get_modpath("esmobs").."/esanimal.lua") dofile(minetest.get_modpath("esmobs").."/esnpc.lua") dofile(minetest.get_modpath("esmobs").."/mtmonster.lua") dofile(minetest.get_modpath("esmobs").."/mcmonster.lua") dofile(minetest.get_modpath("esmobs").."/esbadplayer.lua") dofile(minetest.get_modpath("esmobs").."/esmonster.lua") if es then dofile(minetest.get_modpath("esmobs").."/esnpc2.lua") dofile(minetest.get_modpath("esmobs").."/esbadplayer2.lua") end end if (esmobs.MOB_SETTING == 6) then --MT Monsters, Bad npc's. dofile(minetest.get_modpath("esmobs").."/mtmonster.lua") dofile(minetest.get_modpath("esmobs").."/esbadplayer.lua") if es then dofile(minetest.get_modpath("esmobs").."/esbadplayer2.lua") end end if (esmobs.MOB_SETTING == 7) then --Good npc, Bad npc's. dofile(minetest.get_modpath("esmobs").."/esnpc.lua") dofile(minetest.get_modpath("esmobs").."/esbadplayer.lua") if es then dofile(minetest.get_modpath("esmobs").."/esnpc2.lua") dofile(minetest.get_modpath("esmobs").."/esbadplayer2.lua") end end if (esmobs.MOB_SETTING == 8) then --MC like mobs and Animals. dofile(minetest.get_modpath("esmobs").."/esanimal.lua") dofile(minetest.get_modpath("esmobs").."/mcmonster.lua") end if (esmobs.MOB_SETTING == 9) then --MT monsters and Animals. dofile(minetest.get_modpath("esmobs").."/esanimal.lua") dofile(minetest.get_modpath("esmobs").."/mtmonster.lua") end if (esmobs.MOB_SETTING == 10) then --Good npc's. dofile(minetest.get_modpath("esmobs").."/esnpc.lua") if es then dofile(minetest.get_modpath("esmobs").."/esnpc2.lua") end end if (esmobs.MOB_SETTING == 11) then --MT monsters, ES monsters, MC like mobs, and Bad npc's. dofile(minetest.get_modpath("esmobs").."/mtmonster.lua") dofile(minetest.get_modpath("esmobs").."/mcmonster.lua") dofile(minetest.get_modpath("esmobs").."/esbadplayer.lua") dofile(minetest.get_modpath("esmobs").."/esmonster.lua") if es then dofile(minetest.get_modpath("esmobs").."/esbadplayer2.lua") end end if (esmobs.MOB_SETTING == 12) then --MT Monsters. dofile(minetest.get_modpath("esmobs").."/mtmonster.lua") end ]] --MOBS --dofile(minetest.get_modpath("esmobs").."/esnpc.lua") --dofile(minetest.get_modpath("esmobs").."/esmonster.lua") --dofile(minetest.get_modpath("esmobs").."/mtmonster.lua") --dofile(minetest.get_modpath("esmobs").."/esbadplayer.lua") --dofile(minetest.get_modpath("esmobs").."/esbadplayer2.lua") --dofile(minetest.get_modpath("esmobs").."/esanimal.lua") --dofile(minetest.get_modpath("esmobs").."/mcmobs.lua") --CRAFTS AND MISC dofile(minetest.get_modpath("esmobs").."/crafts.lua") dofile(minetest.get_modpath("esmobs").."/spawner.lua") --MOB SEPCS if inventory_plus then dofile(minetest.get_modpath("esmobs").."/mobspec.lua") end --IF ES IS LOADED YOU WILL SEE OTHER MOBS HOLDING THE SPECIAL TOOLS --if es then --dofile(minetest.get_modpath("esmobs").."/esnpc2.lua") --end --if es then --dofile(minetest.get_modpath("esmobs").."/esbadplayer2.lua") --end --IN CASE BONES IS NOT INSTALLED, THIS OVERRIDES NODES SO YOU HAVE THEM FOR MOBS. if not bones then dofile(minetest.get_modpath("esmobs").."/bones.lua") minetest.register_alias("bones:bones", "esmobs:bones") end if bones then minetest.register_alias("esmobs:bones", "bones:bones") end --IN CASE THROWING IS NOT INSTALLED, THIS DOSEN'T LOAD MCMOBS if not throwing then dofile(minetest.get_modpath("esmobs").."/throwing.lua") minetest.register_alias("throwing:arrow_entity", "esmobs:throwing_entity") minetest.register_alias("throwing:bow", "esmobs:bow") minetest.register_alias("throwing:arrow", "esmobs:arrow") end if throwing then minetest.register_alias("esmobs:arrow_entity", "throwing:arrow_entity") minetest.register_alias("esmobs:bow", "throwing:bow") minetest.register_alias("esmobs:arrow", "throwing:arrow") end print("[ES-Mobs] Extreme") print("[ES-Mobs] Survival") print("[ES-Mobs] Mobs") print("[ES-Mobs] Loaded!") if minetest.setting_get("log_mods") then minetest.log("action", "esmobs mobs loaded") end
Patch to temporary fix broken selector
Patch to temporary fix broken selector
Lua
lgpl-2.1
maikerumine/extreme_survival
a19b3cc1b4fa04776bde0c08077249f466f8ffc4
frontend/ui/reader/readertoc.lua
frontend/ui/reader/readertoc.lua
ReaderToc = InputContainer:new{ toc_menu_title = "Table of contents", current_page = 0, current_pos = 0, } function ReaderToc:init() if not Device:hasNoKeyboard() then self.key_events = { ShowToc = { { "T" }, doc = "show Table of Content menu" }, } end self.ui.menu:registerToMainMenu(self) end function ReaderToc:cleanUpTocTitle(title) return (title:gsub("\13", "")) end function ReaderToc:onSetDimensions(dimen) self.dimen = dimen end --function ReaderToc:fillToc() --self.toc = self.doc:getToc() --end -- getTocTitleByPage wrapper, so specific reader -- can tranform pageno according its need function ReaderToc:getTocTitleByPage(pageno) return self:_getTocTitleByPage(pageno) end function ReaderToc:_getTocTitleByPage(pageno) if not self.toc then -- build toc when needed. self:fillToc() end -- no table of content if #self.toc == 0 then return "" end local pre_entry = self.toc[1] for _k,_v in ipairs(self.toc) do if _v.page > pageno then break end pre_entry = _v end return self:cleanUpTocTitle(pre_entry.title) end function ReaderToc:getTocTitleOfCurrentPage() return self:getTocTitleByPage(self.pageno) end function ReaderToc:onShowToc() local items = self.ui.document:getToc() -- build menu items for _,v in ipairs(items) do v.text = (" "):rep(v.depth-1)..self:cleanUpTocTitle(v.title) end local toc_menu = Menu:new{ title = "Table of Contents", item_table = items, ui = self.ui, dimen = Geom:new{ w = Screen:getWidth()-20, h = Screen:getHeight()-20 }, } function toc_menu:onMenuChoice(item) self.ui:handleEvent(Event:new("PageUpdate", item.page)) end local menu_container = CenterContainer:new{ dimen = Screen:getSize(), toc_menu, } toc_menu.close_callback = function() UIManager:close(menu_container) end UIManager:show(menu_container) end function ReaderToc:onSetDimensions(dimen) self.dimen = dimen end function ReaderToc:onPageUpdate(new_page_no) self.current_page = new_page_no end function ReaderToc:onPosUpdate(new_pos) self.current_pos = new_pos end function ReaderToc:addToMainMenu(item_table) -- insert table to main reader menu table.insert(item_table, { text = self.toc_menu_title, callback = function() self:onShowToc() end, }) end
ReaderToc = InputContainer:new{ toc_menu_title = "Table of contents", current_page = 0, current_pos = 0, } function ReaderToc:init() if not Device:hasNoKeyboard() then self.key_events = { ShowToc = { { "T" }, doc = "show Table of Content menu" }, } end self.ui.menu:registerToMainMenu(self) end function ReaderToc:cleanUpTocTitle(title) return (title:gsub("\13", "")) end function ReaderToc:onSetDimensions(dimen) self.dimen = dimen end --function ReaderToc:fillToc() --self.toc = self.doc:getToc() --end -- getTocTitleByPage wrapper, so specific reader -- can tranform pageno according its need function ReaderToc:getTocTitleByPage(pageno) return self:_getTocTitleByPage(pageno) end function ReaderToc:_getTocTitleByPage(pageno) if not self.toc then -- build toc when needed. self:fillToc() end -- no table of content if #self.toc == 0 then return "" end local pre_entry = self.toc[1] for _k,_v in ipairs(self.toc) do if _v.page > pageno then break end pre_entry = _v end return self:cleanUpTocTitle(pre_entry.title) end function ReaderToc:getTocTitleOfCurrentPage() return self:getTocTitleByPage(self.pageno) end function ReaderToc:onShowToc() local items = self.ui.document:getToc() -- build menu items for _,v in ipairs(items) do v.text = (" "):rep(v.depth-1)..self:cleanUpTocTitle(v.title) end local toc_menu = Menu:new{ title = "Table of Contents", item_table = items, ui = self.ui, width = Screen:getWidth()-20, height = Screen:getHeight(), } function toc_menu:onMenuChoice(item) self.ui:handleEvent(Event:new("PageUpdate", item.page)) end local menu_container = CenterContainer:new{ dimen = Screen:getSize(), toc_menu, } toc_menu.close_callback = function() UIManager:close(menu_container) end UIManager:show(menu_container) end function ReaderToc:onSetDimensions(dimen) self.dimen = dimen end function ReaderToc:onPageUpdate(new_page_no) self.current_page = new_page_no end function ReaderToc:onPosUpdate(new_pos) self.current_pos = new_pos end function ReaderToc:addToMainMenu(item_table) -- insert table to main reader menu table.insert(item_table, { text = self.toc_menu_title, callback = function() self:onShowToc() end, }) end
bug fix: set toc menu height and width
bug fix: set toc menu height and width
Lua
agpl-3.0
NiLuJe/koreader-base,koreader/koreader-base,houqp/koreader,Hzj-jie/koreader-base,robert00s/koreader,Frenzie/koreader-base,frankyifei/koreader-base,pazos/koreader,apletnev/koreader,koreader/koreader,apletnev/koreader-base,koreader/koreader-base,NiLuJe/koreader-base,koreader/koreader-base,houqp/koreader-base,chrox/koreader,frankyifei/koreader-base,houqp/koreader-base,NiLuJe/koreader,houqp/koreader-base,poire-z/koreader,Hzj-jie/koreader-base,Hzj-jie/koreader-base,apletnev/koreader-base,NiLuJe/koreader-base,Hzj-jie/koreader-base,NiLuJe/koreader,Markismus/koreader,ashang/koreader,apletnev/koreader-base,koreader/koreader-base,apletnev/koreader-base,frankyifei/koreader,frankyifei/koreader-base,houqp/koreader-base,frankyifei/koreader-base,chihyang/koreader,mwoz123/koreader,noname007/koreader,lgeek/koreader,Frenzie/koreader-base,poire-z/koreader,koreader/koreader,ashhher3/koreader,Frenzie/koreader-base,NiLuJe/koreader-base,Frenzie/koreader,Frenzie/koreader-base,Hzj-jie/koreader,Frenzie/koreader,NickSavage/koreader,mihailim/koreader
92b704ed963edcf51398003b6f0b011f55cb394f
src/base/detoken.lua
src/base/detoken.lua
-- -- detoken.lua -- -- Expands tokens. -- -- Copyright (c) 2011-2014 Jason Perkins and the Premake project -- premake.detoken = {} local p = premake local detoken = p.detoken -- -- Expand tokens in a value. -- -- @param value -- The value containing the tokens to be expanded. -- @param environ -- An execution environment for any token expansion. This is a list of -- key-value pairs that will be inserted as global variables into the -- token expansion runtime environment. -- @param field -- The definition of the field which stores the value. -- @param basedir -- If provided, path tokens encountered in non-path fields (where -- field.paths is set to false) will be made relative to this location. -- @return -- The value with any contained tokens expanded. -- function detoken.expand(value, environ, field, basedir) field = field or {} -- fetch the path variable from the action, if needed local varMap = {} if field.pathVars then local action = p.action.current() if action then varMap = action.pathVars or {} end end -- enable access to the global environment setmetatable(environ, {__index = _G}) function expandtoken(token, environ) -- convert the token into a function to execute local func, err = loadstring("return " .. token) if not func then return nil, err end -- give the function access to the project objects setfenv(func, environ) -- run it and get the result local result = func() or "" -- If the result is an absolute path, and it is being inserted into -- a NON-path value, I need to make it relative to the project that -- will contain it. Otherwise I ended up with an absolute path in -- the generated project, and it can no longer be moved around. local isAbs = path.isabsolute(result) if isAbs and not field.paths and basedir then result = path.getrelative(basedir, result) end -- If this token is in my path variable mapping table, replace the -- value with the one from the map. This needs to go here because -- I don't want to make the result relative, but I don't want the -- absolute path handling below. if varMap[token] then result = varMap[token] if type(result) == "function" then result = result(environ) end end -- If the result is an absolute path, and it is being inserted into -- a path value, place a special marker at the start of it. After -- all results have been processed, I can look for these markers to -- find the last absolute path expanded. -- -- Example: the value "/home/user/myprj/%{cfg.objdir}" expands to: -- "/home/user/myprj//home/user/myprj/obj/Debug". -- -- By inserting a marker this becomes: -- "/home/user/myprj/[\0]/home/user/myprj/obj/Debug". -- -- I can now trim everything before the marker to get the right -- result, which should always be the last absolute path specified: -- "/home/user/myprj/obj/Debug" if isAbs and field.paths then result = "\0" .. result end return result end function expandvalue(value) if type(value) ~= "string" then return end local count repeat value, count = value:gsub("%%{(.-)}", function(token) local result, err = expandtoken(token:gsub("\\", "\\\\"), environ) if not result then error(err, 0) end return result end) until count == 0 -- if a path, look for a split out embedded absolute paths if field.paths then local i, j repeat i, j = value:find("\0") if i then value = value:sub(i + 1) end until not i end return value end function recurse(value) if type(value) == "table" then for k, v in pairs(value) do value[k] = recurse(v) end return value else return expandvalue(value) end end return recurse(value) end
-- -- detoken.lua -- -- Expands tokens. -- -- Copyright (c) 2011-2014 Jason Perkins and the Premake project -- premake.detoken = {} local p = premake local detoken = p.detoken -- -- Expand tokens in a value. -- -- @param value -- The value containing the tokens to be expanded. -- @param environ -- An execution environment for any token expansion. This is a list of -- key-value pairs that will be inserted as global variables into the -- token expansion runtime environment. -- @param field -- The definition of the field which stores the value. -- @param basedir -- If provided, path tokens encountered in non-path fields (where -- field.paths is set to false) will be made relative to this location. -- @return -- The value with any contained tokens expanded. -- function detoken.expand(value, environ, field, basedir) field = field or {} -- fetch the path variable from the action, if needed local varMap = {} if field.pathVars then local action = p.action.current() if action then varMap = action.pathVars or {} end end -- enable access to the global environment setmetatable(environ, {__index = _G}) function expandtoken(token, environ) -- convert the token into a function to execute local func, err = loadstring("return " .. token) if not func then return nil, err end -- give the function access to the project objects setfenv(func, environ) -- run it and get the result local result = func() or "" -- If the result is an absolute path, and it is being inserted into -- a NON-path value, I need to make it relative to the project that -- will contain it. Otherwise I ended up with an absolute path in -- the generated project, and it can no longer be moved around. local isAbs = path.isabsolute(result) if isAbs and not field.paths and basedir then result = path.getrelative(basedir, result) end -- If this token is in my path variable mapping table, replace the -- value with the one from the map. This needs to go here because -- I don't want to make the result relative, but I don't want the -- absolute path handling below. if varMap[token] then result = varMap[token] if type(result) == "function" then result = result(environ) end isAbs = path.isabsolute(result) end -- If the result is an absolute path, and it is being inserted into -- a path value, place a special marker at the start of it. After -- all results have been processed, I can look for these markers to -- find the last absolute path expanded. -- -- Example: the value "/home/user/myprj/%{cfg.objdir}" expands to: -- "/home/user/myprj//home/user/myprj/obj/Debug". -- -- By inserting a marker this becomes: -- "/home/user/myprj/[\0]/home/user/myprj/obj/Debug". -- -- I can now trim everything before the marker to get the right -- result, which should always be the last absolute path specified: -- "/home/user/myprj/obj/Debug" if isAbs and field.paths then result = "\0" .. result end return result end function expandvalue(value) if type(value) ~= "string" then return end local count repeat value, count = value:gsub("%%{(.-)}", function(token) local result, err = expandtoken(token:gsub("\\", "\\\\"), environ) if not result then error(err, 0) end return result end) until count == 0 -- if a path, look for a split out embedded absolute paths if field.paths then local i, j repeat i, j = value:find("\0") if i then value = value:sub(i + 1) end until not i end return value end function recurse(value) if type(value) == "table" then for k, v in pairs(value) do value[k] = recurse(v) end return value else return expandvalue(value) end end return recurse(value) end
fix bug in detoken.
fix bug in detoken.
Lua
bsd-3-clause
tvandijck/premake-core,CodeAnxiety/premake-core,tritao/premake-core,prapin/premake-core,prapin/premake-core,premake/premake-core,PlexChat/premake-core,dcourtois/premake-core,LORgames/premake-core,premake/premake-core,soundsrc/premake-core,mandersan/premake-core,xriss/premake-core,kankaristo/premake-core,starkos/premake-core,PlexChat/premake-core,starkos/premake-core,Tiger66639/premake-core,bravnsgaard/premake-core,premake/premake-core,alarouche/premake-core,sleepingwit/premake-core,CodeAnxiety/premake-core,LORgames/premake-core,aleksijuvani/premake-core,aleksijuvani/premake-core,Blizzard/premake-core,alarouche/premake-core,TurkeyMan/premake-core,CodeAnxiety/premake-core,starkos/premake-core,Zefiros-Software/premake-core,mandersan/premake-core,resetnow/premake-core,tritao/premake-core,jsfdez/premake-core,tvandijck/premake-core,soundsrc/premake-core,jsfdez/premake-core,alarouche/premake-core,noresources/premake-core,soundsrc/premake-core,starkos/premake-core,xriss/premake-core,aleksijuvani/premake-core,felipeprov/premake-core,xriss/premake-core,jstewart-amd/premake-core,jstewart-amd/premake-core,Blizzard/premake-core,akaStiX/premake-core,soundsrc/premake-core,bravnsgaard/premake-core,CodeAnxiety/premake-core,soundsrc/premake-core,mandersan/premake-core,mendsley/premake-core,martin-traverse/premake-core,resetnow/premake-core,lizh06/premake-core,alarouche/premake-core,bravnsgaard/premake-core,starkos/premake-core,mendsley/premake-core,mendsley/premake-core,jstewart-amd/premake-core,Zefiros-Software/premake-core,tvandijck/premake-core,kankaristo/premake-core,lizh06/premake-core,dcourtois/premake-core,Blizzard/premake-core,Tiger66639/premake-core,TurkeyMan/premake-core,mendsley/premake-core,noresources/premake-core,premake/premake-core,felipeprov/premake-core,CodeAnxiety/premake-core,dcourtois/premake-core,starkos/premake-core,Blizzard/premake-core,saberhawk/premake-core,PlexChat/premake-core,aleksijuvani/premake-core,martin-traverse/premake-core,Zefiros-Software/premake-core,akaStiX/premake-core,tritao/premake-core,premake/premake-core,Zefiros-Software/premake-core,resetnow/premake-core,tvandijck/premake-core,felipeprov/premake-core,resetnow/premake-core,Tiger66639/premake-core,noresources/premake-core,premake/premake-core,dcourtois/premake-core,prapin/premake-core,Yhgenomics/premake-core,sleepingwit/premake-core,Tiger66639/premake-core,PlexChat/premake-core,bravnsgaard/premake-core,saberhawk/premake-core,LORgames/premake-core,tritao/premake-core,mendsley/premake-core,kankaristo/premake-core,Blizzard/premake-core,prapin/premake-core,noresources/premake-core,mandersan/premake-core,saberhawk/premake-core,Blizzard/premake-core,premake/premake-core,jsfdez/premake-core,Yhgenomics/premake-core,sleepingwit/premake-core,LORgames/premake-core,kankaristo/premake-core,lizh06/premake-core,noresources/premake-core,noresources/premake-core,noresources/premake-core,TurkeyMan/premake-core,Yhgenomics/premake-core,dcourtois/premake-core,dcourtois/premake-core,starkos/premake-core,lizh06/premake-core,akaStiX/premake-core,tvandijck/premake-core,TurkeyMan/premake-core,Yhgenomics/premake-core,jstewart-amd/premake-core,martin-traverse/premake-core,dcourtois/premake-core,felipeprov/premake-core,saberhawk/premake-core,aleksijuvani/premake-core,bravnsgaard/premake-core,Zefiros-Software/premake-core,xriss/premake-core,jstewart-amd/premake-core,martin-traverse/premake-core,jsfdez/premake-core,sleepingwit/premake-core,sleepingwit/premake-core,TurkeyMan/premake-core,resetnow/premake-core,akaStiX/premake-core,LORgames/premake-core,xriss/premake-core,mandersan/premake-core
68e4a4cda7c147babc2887ee09cd493911dcb16a
libs/web/luasrc/config.lua
libs/web/luasrc/config.lua
--[[ LuCI - Configuration Description: Some LuCI configuration values read from uci file "luci" FileId: $Id$ License: Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- local util = require "luci.util" local pcall = pcall local require = require module "luci.config" pcall(function() setmetatable(_M, {__index=require "luci.model.uci".cursor():get_all("luci")}) end)
--[[ LuCI - Configuration Description: Some LuCI configuration values read from uci file "luci" 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.config", function(m) if pcall(require, "luci.model.uci") then setmetatable(m, {__index = luci.model.uci.cursor():get_all("luci")}) end end)
Fixed luci.config
Fixed luci.config
Lua
apache-2.0
deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,8devices/luci
ed0524aa4f0d3875e9882ea745812bd27d3fb3be
src/luarocks/dir.lua
src/luarocks/dir.lua
--- Generic utilities for handling pathnames. module("luarocks.dir", package.seeall) separator = "/" --- Strip the path off a path+filename. -- @param pathname string: A path+name, such as "/a/b/c" -- or "\a\b\c". -- @return string: The filename without its path, such as "c". function base_name(pathname) assert(type(pathname) == "string") local base = pathname:gsub("[/\\]*$", ""):match(".*[/\\]([^/\\]*)") return base or pathname end --- Strip the name off a path+filename. -- @param pathname string: A path+name, such as "/a/b/c". -- @return string: The filename without its path, such as "/a/b/". -- For entries such as "/a/b/", "/a/" is returned. If there are -- no directory separators in input, "" is returned. function dir_name(pathname) assert(type(pathname) == "string") return (pathname:gsub("/*$", ""):match("(.*/)[^/]*")) or "" end function strip_base_dir(pathname) return pathname:gsub("^[^/]*/", "") end --- Describe a path in a cross-platform way. -- Use this function to avoid platform-specific directory -- separators in other modules. If the first item contains a -- protocol descriptor (e.g. "http:"), paths are always constituted -- with forward slashes. -- @param ... strings representing directories -- @return string: a string with a platform-specific representation -- of the path. function path(...) local items = {...} local i = 1 while items[i] do items[i] = items[i]:gsub("/*$", "") if items[i] == "" then table.remove(items, i) else i = i + 1 end end return table.concat(items, "/") end --- Split protocol and path from an URL or local pathname. -- URLs should be in the "protocol://path" format. -- For local pathnames, "file" is returned as the protocol. -- @param url string: an URL or a local pathname. -- @return string, string: the protocol, and the pathname without the protocol. function split_url(url) assert(type(url) == "string") local protocol, pathname = url:match("^([^:]*)://(.*)") if not protocol then protocol = "file" pathname = url end return protocol, pathname end
--- Generic utilities for handling pathnames. module("luarocks.dir", package.seeall) separator = "/" --- Strip the path off a path+filename. -- @param pathname string: A path+name, such as "/a/b/c" -- or "\a\b\c". -- @return string: The filename without its path, such as "c". function base_name(pathname) assert(type(pathname) == "string") local base = pathname:gsub("[/\\]*$", ""):match(".*[/\\]([^/\\]*)") return base or pathname end --- Strip the name off a path+filename. -- @param pathname string: A path+name, such as "/a/b/c". -- @return string: The filename without its path, such as "/a/b/". -- For entries such as "/a/b/", "/a/" is returned. If there are -- no directory separators in input, "" is returned. function dir_name(pathname) assert(type(pathname) == "string") return (pathname:gsub("/*$", ""):match("(.*/)[^/]*")) or "" end function strip_base_dir(pathname) return pathname:gsub("^[^/]*/", "") end --- Describe a path in a cross-platform way. -- Use this function to avoid platform-specific directory -- separators in other modules. Removes trailing slashes from -- each component given, to avoid repeated separators. -- Separators inside strings are kept, to handle URLs containing -- protocols. -- @param ... strings representing directories -- @return string: a string with a platform-specific representation -- of the path. function path(...) local items = {...} local i = 1 while items[i] do items[i] = items[i]:gsub("(.+)/+$", "%1") if items[i] == "" then table.remove(items, i) else i = i + 1 end end return (table.concat(items, "/"):gsub("(.+)/+$", "%1")) end --- Split protocol and path from an URL or local pathname. -- URLs should be in the "protocol://path" format. -- For local pathnames, "file" is returned as the protocol. -- @param url string: an URL or a local pathname. -- @return string, string: the protocol, and the pathname without the protocol. function split_url(url) assert(type(url) == "string") local protocol, pathname = url:match("^([^:]*)://(.*)") if not protocol then protocol = "file" pathname = url end return protocol, pathname end
Fix handling of "/" in dir.path. Closes #80.
Fix handling of "/" in dir.path. Closes #80.
Lua
mit
rrthomas/luarocks,xiaq/luarocks,coderstudy/luarocks,aryajur/luarocks,xpol/luavm,xpol/luainstaller,leafo/luarocks,tst2005/luarocks,usstwxy/luarocks,xpol/luainstaller,tst2005/luarocks,keplerproject/luarocks,xiaq/luarocks,starius/luarocks,rrthomas/luarocks,starius/luarocks,starius/luarocks,ignacio/luarocks,ignacio/luarocks,usstwxy/luarocks,starius/luarocks,usstwxy/luarocks,tarantool/luarocks,tst2005/luarocks,lxbgit/luarocks,lxbgit/luarocks,xpol/luainstaller,coderstudy/luarocks,keplerproject/luarocks,xpol/luavm,aryajur/luarocks,tarantool/luarocks,xiaq/luarocks,aryajur/luarocks,xpol/luainstaller,coderstudy/luarocks,robooo/luarocks,luarocks/luarocks,luarocks/luarocks,xpol/luavm,keplerproject/luarocks,robooo/luarocks,ignacio/luarocks,aryajur/luarocks,xpol/luavm,keplerproject/luarocks,xpol/luarocks,robooo/luarocks,leafo/luarocks,coderstudy/luarocks,tarantool/luarocks,robooo/luarocks,xpol/luarocks,luarocks/luarocks,xpol/luavm,rrthomas/luarocks,xpol/luarocks,lxbgit/luarocks,leafo/luarocks,lxbgit/luarocks,ignacio/luarocks,usstwxy/luarocks,tst2005/luarocks,xpol/luarocks,xiaq/luarocks,rrthomas/luarocks
583c036b378a7efbe47bb1845a089b5c0479e3de
quiz/func.lua
quiz/func.lua
local h = require('quiz.helpers') local rr = h.rr local _ = h._ local func = {} function func.func_summ(req) local a = rr(1, 5) local b = rr(10, 20) local task = [[ def myf(a): return a + %i print(myf(%i))]] return h.f(task, a, b), h.f("%i", a + b), h.f("%i", a), h.f("%i", b), 'Error', h.task(req) end function func.func_arg_name(req) local a = rr(1, 5) local b = rr(10, 20) local task = [[ def myf(b): print(b) a = %i b = %i myf(a)]] return h.f(task, a, b), h.f("%i", a), h.f("%i", b), h.f("%i", a + b), 'Error', h.task(req) end function func.var_undefined(req) local a = rr(1, 5) local task = [[ def myf(x): return 2 * x a = %i b = myf(b) print(b)]] return h.f(task, a), 'Error', h.f("%i", a), h.f("%i", 2 * a), h.f("%i", 0), h.task(req) end function func.sin(req) return h.f([[>>> import math >>> math.sin(90)]]), '0.8939966636005579', '1', '0', '-1', h.task(req) end function func.cos(req) return h.f([[>>> import math >>> math.cos(90)]]), '-0.4480736161291701', '1', '0', '-1', h.task(req) end function func.sin_rev(req) return '1.0', h.f([[>>> import math >>> math.sin(math.radians(90))]]), h.f([[>>> import math >>> math.cos(math.radians(90))]]), h.f([[>>> import math >>> math.sin(90)]]), h.f([[>>> import math >>> math.cos(90)]]), h.task2(req) end function func.argv(req) return '', 'sys.argv', 'os.argv', 'sys.argv()', 'os.argv()', _("How to get command line arguments?") end function func.system(req) return '', 'os.system("dir")', 'sys.system("dir")', 'os.ostem("dir")', 'sys.ostem("dir")', _("How to run external command ('dir')?") end function func.argv1(req) return 'python prog.py 19 input.fasta 6', 'sys.argv[2]', 'sys.argv(2)', 'sys.argv(1)', 'sys.argv[1]', _("How to get argument 'input.fasta'?") end function func.argv2(req) return 'python prog.py 19 input.fasta 6', 'sys.argv[0]', 'sys.argv(0)', 'sys.argv(1)', 'sys.argv[1]', _("How to get script name ('prog.py')?") end function func.urllib2(req) return 'import urllib2', 'urllib2.urlopen("http://ya.ru").read()', 'list(urllib2.urlopen("http://ya.ru"))', 'str(urllib2.urlopen("http://ya.ru"))', 'wget http://ya.ru :3', _("How to get content of web page http://ya.ru as string?") end function func.randint(req) return 'import random', 'random.randint(1, 10)', 'random.randint(1, 11)', 'random.randint(range(1, 11))', 'random.randint(range(1, 10))', _("How to get random number in range [1; 10]?") end function func.complement(req) return 'seq = "ATTGC"', [[seq_compl = "" compl_dict = {"A": "T", "T": "A", "C": "G", "G": "C"} for i in range(len(seq)): nucl = seq[-1 - i] nucl_compl = compl_dict[nucl] seq_compl += nucl_compl print(seq_compl)]], [[seq_compl = "" compl_dict = {"A": "T", "T": "A", "C": "G", "G": "C"} for i in range(len(seq)): nucl = seq[i] nucl_compl = compl_dict[nucl] seq_compl += nucl_compl print(seq_compl)]], [[seq_compl = "" compl_dict = {"A": "T", "T": "A", "C": "G", "G": "C"} for i in range(len(seq)): nucl = seq[-i] nucl_compl = compl_dict[nucl] seq_compl.append(nucl_compl) print(seq_compl)]], [[seq_compl = "" compl_dict = {"A": "A", "T": "T", "C": "C", "G": "G"} for i in range(len(seq)): nucl = seq[-i] nucl_compl = compl_dict[nucl] seq_compl.append(nucl_compl) print(seq_compl)]], _("How to calculate complement DNA sequence?") end return func
local h = require('quiz.helpers') local rr = h.rr local _ = h._ local func = {} function func.func_summ(req) local a = rr(1, 5) local b = rr(10, 20) local task = [[ def myf(a): return a + %i print(myf(%i))]] return h.f(task, a, b), h.f("%i", a + b), h.f("%i", a), h.f("%i", b), 'Error', h.task(req) end function func.func_arg_name(req) local a = rr(1, 5) local b = rr(10, 20) local task = [[ def myf(b): print(b) a = %i b = %i myf(a)]] return h.f(task, a, b), h.f("%i", a), h.f("%i", b), h.f("%i", a + b), 'Error', h.task(req) end function func.var_undefined(req) local a = rr(1, 5) local task = [[ def myf(x): return 2 * x a = %i b = myf(b) print(b)]] return h.f(task, a), 'Error', h.f("%i", a), h.f("%i", 2 * a), h.f("%i", 0), h.task(req) end function func.sin(req) return h.f([[>>> import math >>> math.sin(90)]]), '0.8939966636005579', '1', '0', '-1', h.task(req) end function func.cos(req) return h.f([[>>> import math >>> math.cos(90)]]), '-0.4480736161291701', '1', '0', '-1', h.task(req) end function func.sin_rev(req) return '1.0', h.f([[>>> import math >>> math.sin(math.radians(90))]]), h.f([[>>> import math >>> math.cos(math.radians(90))]]), h.f([[>>> import math >>> math.sin(90)]]), h.f([[>>> import math >>> math.cos(90)]]), h.task2(req) end function func.argv(req) return '', 'sys.argv', 'os.argv', 'sys.argv()', 'os.argv()', _("How to get command line arguments?", req) end function func.system(req) return '', 'os.system("dir")', 'sys.system("dir")', 'os.ostem("dir")', 'sys.ostem("dir")', _("How to run external command ('dir')?", req) end function func.argv1(req) return 'python prog.py 19 input.fasta 6', 'sys.argv[2]', 'sys.argv(2)', 'sys.argv(1)', 'sys.argv[1]', _("How to get argument 'input.fasta'?", req) end function func.argv2(req) return 'python prog.py 19 input.fasta 6', 'sys.argv[0]', 'sys.argv(0)', 'sys.argv(1)', 'sys.argv[1]', _("How to get script name ('prog.py')?", req) end function func.urllib2(req) return 'import urllib2', 'urllib2.urlopen("http://ya.ru").read()', 'list(urllib2.urlopen("http://ya.ru"))', 'str(urllib2.urlopen("http://ya.ru"))', 'wget http://ya.ru :3', _("How to get content of web page http://ya.ru as string?", req) end function func.randint(req) return 'import random', 'random.randint(1, 10)', 'random.randint(1, 11)', 'random.randint(range(1, 11))', 'random.randint(range(1, 10))', _("How to get random number in range [1; 10]?", req) end function func.complement(req) return 'seq = "ATTGC"', [[seq_compl = "" compl_dict = {"A": "T", "T": "A", "C": "G", "G": "C"} for i in range(len(seq)): nucl = seq[-1 - i] nucl_compl = compl_dict[nucl] seq_compl += nucl_compl print(seq_compl)]], [[seq_compl = "" compl_dict = {"A": "T", "T": "A", "C": "G", "G": "C"} for i in range(len(seq)): nucl = seq[i] nucl_compl = compl_dict[nucl] seq_compl += nucl_compl print(seq_compl)]], [[seq_compl = "" compl_dict = {"A": "T", "T": "A", "C": "G", "G": "C"} for i in range(len(seq)): nucl = seq[-i] nucl_compl = compl_dict[nucl] seq_compl.append(nucl_compl) print(seq_compl)]], [[seq_compl = "" compl_dict = {"A": "A", "T": "T", "C": "C", "G": "G"} for i in range(len(seq)): nucl = seq[-i] nucl_compl = compl_dict[nucl] seq_compl.append(nucl_compl) print(seq_compl)]], _("How to calculate complement DNA sequence?", req) end return func
fix translation in quiz.func
fix translation in quiz.func
Lua
mit
starius/kodomoquiz
7f89c1de45a88426b85cb4ca3efd0de45e060b96
test/dev-app/tests/unit/form.lua
test/dev-app/tests/unit/form.lua
local form = require "sailor.form" local model = require "sailor.model" local User = model("user") describe("Testing form generator", function() local u = User:new() it("should not create fields that don't exist", function () assert.has_error( function() local html = form.blah(u,'password') end, "attempt to call field 'blah' (a nil value)" ) end) it("should create a generic field accordingly", function() local html = form.text(u,'password') assert.equal('<input type="text" name="user:password" id="user:password" />',html) end) it("should create textarea field accordingly", function() local html = form.textarea(u,'password') assert.equal(html,'<textarea name="user:password" id="user:password" > asadas </textarea>') end) it("should create a dropdown list accordingly", function() local html = form.dropdown(u,'password',{'a','b'},'Select...') assert.equal(html,'<select name="user:password" id="user:password" > <option value="" selected>Select...</option> <option value="1">a</option> <option value="2">b</option> </select>') end) it("should create a radio list accordingly", function() local html = form.radio_list(u,'password',{'a','b'},1,'vertical') assert.equal(html,'<input type="radio" value="1" checked /> a <br/><input type="radio" value="2" /> b') end) it("should create a checkbox accordingly", function() local html = form.checkbox(u,'password',nil, true) assert.equal(html,'<input type="checkbox" name="user:password" id="user:password" checked /> password') end) end)
local form = require "sailor.form" local model = require "sailor.model" local User = model("user") describe("Testing form generator", function() local u = User:new() it("should not create fields that don't exist", function () assert.has_error( function() local html = form.blah(u,'password') end ) end) it("should create a generic field accordingly", function() local html = form.text(u,'password') assert.equal('<input type="text" name="user:password" id="user:password" />',html) end) it("should create textarea field accordingly", function() local html = form.textarea(u,'password') assert.equal(html,'<textarea name="user:password" id="user:password" > asadas </textarea>') end) it("should create a dropdown list accordingly", function() local html = form.dropdown(u,'password',{'a','b'},'Select...') assert.equal(html,'<select name="user:password" id="user:password" > <option value="" selected>Select...</option> <option value="1">a</option> <option value="2">b</option> </select>') end) it("should create a radio list accordingly", function() local html = form.radio_list(u,'password',{'a','b'},1,'vertical') assert.equal(html,'<input type="radio" value="1" checked /> a <br/><input type="radio" value="2" /> b') end) it("should create a checkbox accordingly", function() local html = form.checkbox(u,'password',nil, true) assert.equal(html,'<input type="checkbox" name="user:password" id="user:password" checked /> password') end) end)
fix test with Lua 5.3
fix test with Lua 5.3 don't check the message of error which depends on Lua version. "attempt to call field 'blah' (a nil value)" "attempt to call a nil value (field 'blah')"
Lua
mit
Etiene/sailor,sailorproject/sailor,Etiene/sailor
c985c0cdc52774eb148cbba840ef6e031ebe97e7
packages/simpletable.lua
packages/simpletable.lua
-- A very simple table formatting class -- Calling conventions: -- myClass:loadPackage("simpletable", { -- tableTag = "a", -- trTag = "b", -- tdTag = "c" -- }) -- Defines commands \a, \b and \c equivalent to HTML -- <table>, <tr> and <td> tags. -- Todo: Set a maximum width for the whole table and ensure -- vbox width is no greater than this. In fact, we should use -- the complete CSS2.1 two-pass table layout algorithm. SILE.scratch.simpletable = { tables = {} } return { exports = {}, init = function (class, args) local tableTag = SU.required(args,"tableTag","setting up table class") local trTag = SU.required(args,"trTag","setting up table class") local tdTag = SU.required(args,"tdTag","setting up table class") SILE.registerCommand(trTag, function(options,content) local tbl = SILE.scratch.simpletable.tables[#(SILE.scratch.simpletable.tables)] tbl[#tbl+1] = {} SILE.process(content) end) SILE.registerCommand(tdTag, function(options,content) local tbl = SILE.scratch.simpletable.tables[#(SILE.scratch.simpletable.tables)] local row = tbl[#tbl] row[#row+1] = { content = content, width = (SILE.Commands["hbox"]({},content)).width } SILE.typesetter.state.nodes[#(SILE.typesetter.state.nodes)] = nil end) SILE.registerCommand(tableTag, function(options, content) SILE.scratch.simpletable.tables[#(SILE.scratch.simpletable.tables)+1] = {} local tbl = SILE.scratch.simpletable.tables[#(SILE.scratch.simpletable.tables)] SILE.settings.temporarily(function () SILE.settings.set("document.parindent", SILE.nodefactory.newGlue("0pt")) SILE.process(content) end) SILE.typesetter:leaveHmode() -- Look down columns and find largest thing per column local colwidths = {} local col = 1 local stuffInThisColumn repeat stuffInThisColumn = false for row = 1,#tbl do cell = tbl[row][col] if cell then stuffInThisColumn = true if not(colwidths[col]) or cell.width > colwidths[col] then colwidths[col] = cell.width end end end col = col + 1 until not stuffInThisColumn -- Now set each row at the given column width for row = 1,#tbl do for col = 1,#(tbl[row]) do cell = tbl[row][col] local box = SILE.Commands["vbox"]({width = colwidths[col]}, cell.content) box = box.nodes[1] if box then box.outputYourself = function(self,typesetter, line) for i, n in ipairs(self.nodes) do n:outputYourself(typesetter, self) end end table.insert(SILE.typesetter.state.nodes, box) -- a vbox on the hbox list! end end SILE.typesetter:leaveHmode() SILE.call("smallskip") end SILE.typesetter:leaveHmode() SILE.scratch.simpletable.tables[#(SILE.scratch.simpletable.tables)] = nil end) end}
-- A very simple table formatting class -- Calling conventions: -- myClass:loadPackage("simpletable", { -- tableTag = "a", -- trTag = "b", -- tdTag = "c" -- }) -- Defines commands \a, \b and \c equivalent to HTML -- <table>, <tr> and <td> tags. -- Todo: Set a maximum width for the whole table and ensure -- vbox width is no greater than this. In fact, we should use -- the complete CSS2.1 two-pass table layout algorithm. SILE.scratch.simpletable = { tables = {} } return { exports = {}, init = function (class, args) local tableTag = SU.required(args,"tableTag","setting up table class") local trTag = SU.required(args,"trTag","setting up table class") local tdTag = SU.required(args,"tdTag","setting up table class") SILE.registerCommand(trTag, function(options,content) local tbl = SILE.scratch.simpletable.tables[#(SILE.scratch.simpletable.tables)] tbl[#tbl+1] = {} SILE.process(content) end) SILE.registerCommand(tdTag, function(options,content) local tbl = SILE.scratch.simpletable.tables[#(SILE.scratch.simpletable.tables)] local row = tbl[#tbl] row[#row+1] = { content = content, hbox = SILE.Commands["hbox"]({},content) } SILE.typesetter.state.nodes[#(SILE.typesetter.state.nodes)] = nil end) SILE.registerCommand(tableTag, function(options, content) SILE.scratch.simpletable.tables[#(SILE.scratch.simpletable.tables)+1] = {} local tbl = SILE.scratch.simpletable.tables[#(SILE.scratch.simpletable.tables)] SILE.settings.temporarily(function () SILE.settings.set("document.parindent", SILE.nodefactory.zeroGlue) SILE.process(content) end) SILE.typesetter:leaveHmode() -- Look down columns and find largest thing per column local colwidths = {} local col = 1 local stuffInThisColumn repeat stuffInThisColumn = false for row = 1,#tbl do cell = tbl[row][col] if cell then stuffInThisColumn = true if not(colwidths[col]) or cell.hbox.width > colwidths[col] then colwidths[col] = cell.hbox.width end end end col = col + 1 until not stuffInThisColumn -- Now set each row at the given column width SILE.settings.temporarily(function () SILE.settings.set("document.parindent", SILE.nodefactory.zeroGlue) for row = 1,#tbl do for col = 1,#(tbl[row]) do local hbox = tbl[row][col].hbox hbox.width = colwidths[col] SILE.typesetter:pushHbox(hbox) end SILE.typesetter:leaveHmode() SILE.call("smallskip") end end) SILE.typesetter:leaveHmode() SILE.scratch.simpletable.tables[#(SILE.scratch.simpletable.tables)] = nil end) end}
fix empty simpletable #555 and indentation of table data
fix empty simpletable #555 and indentation of table data
Lua
mit
simoncozens/sile,simoncozens/sile,simoncozens/sile,alerque/sile,alerque/sile,simoncozens/sile,alerque/sile,alerque/sile
1bd0902fe7d3457fd96e55f5ed04c46f81fe6968
plugins/mod_saslauth.lua
plugins/mod_saslauth.lua
-- Prosody IM v0.4 -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local st = require "util.stanza"; local sm_bind_resource = require "core.sessionmanager".bind_resource; local base64 = require "util.encodings".base64; local usermanager_validate_credentials = require "core.usermanager".validate_credentials; local t_concat, t_insert = table.concat, table.insert; local tostring = tostring; local jid_split = require "util.jid".split local md5 = require "util.hashes".md5; local config = require "core.configmanager"; local log = require "util.logger".init("mod_saslauth"); local xmlns_sasl ='urn:ietf:params:xml:ns:xmpp-sasl'; local xmlns_bind ='urn:ietf:params:xml:ns:xmpp-bind'; local xmlns_stanzas ='urn:ietf:params:xml:ns:xmpp-stanzas'; local new_sasl = require "util.sasl".new; local function build_reply(status, ret, err_msg) local reply = st.stanza(status, {xmlns = xmlns_sasl}); if status == "challenge" then log("debug", ret or ""); reply:text(base64.encode(ret or "")); elseif status == "failure" then reply:tag(ret):up(); if err_msg then reply:tag("text"):text(err_msg); end elseif status == "success" then log("debug", ret or ""); reply:text(base64.encode(ret or "")); else error("Unknown sasl status: "..status); end return reply; end local function handle_status(session, status) if status == "failure" then session.sasl_handler = nil; elseif status == "success" then if not session.sasl_handler.username then error("SASL succeeded but we didn't get a username!"); end -- TODO move this to sessionmanager sessionmanager.make_authenticated(session, session.sasl_handler.username); session.sasl_handler = nil; session:reset_stream(); end end local function password_callback(node, host, mechanism, decoder) local password = (datamanager.load(node, host, "accounts") or {}).password; -- FIXME handle hashed passwords local func = function(x) return x; end; if password then if mechanism == "PLAIN" then return func, password; elseif mechanism == "DIGEST-MD5" then if decoder then node, host, password = decoder(node), decoder(host), decoder(password); end return func, md5(node..":"..host..":"..password); end end return func, nil; end local function sasl_handler(session, stanza) if stanza.name == "auth" then -- FIXME ignoring duplicates because ejabberd does session.sasl_handler = new_sasl(stanza.attr.mechanism, session.host, password_callback); elseif not session.sasl_handler then return; -- FIXME ignoring out of order stanzas because ejabberd does end local text = stanza[1]; if text then text = base64.decode(text); log("debug", text); if not text then session.sasl_handler = nil; session.send(build_reply("failure", "incorrect-encoding")); return; end end local status, ret, err_msg = session.sasl_handler:feed(text); handle_status(session, status); local s = build_reply(status, ret, err_msg); log("debug", "sasl reply: "..tostring(s)); session.send(s); end module:add_handler("c2s_unauthed", "auth", xmlns_sasl, sasl_handler); module:add_handler("c2s_unauthed", "abort", xmlns_sasl, sasl_handler); module:add_handler("c2s_unauthed", "response", xmlns_sasl, sasl_handler); local mechanisms_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-sasl' }; local bind_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-bind' }; local xmpp_session_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-session' }; module:add_event_hook("stream-features", function (session, features) if not session.username then features:tag("mechanisms", mechanisms_attr); -- TODO: Provide PLAIN only if TLS is active, this is a SHOULD from the introduction of RFC 4616. This behavior could be overridden via configuration but will issuing a warning or so. features:tag("mechanism"):text("PLAIN"):up(); features:tag("mechanism"):text("DIGEST-MD5"):up(); if config.get(session.host or "*", "core", "anonymous_login") then features:tag("mechanism"):text("ANONYMOUS"):up(); end features:up(); else features:tag("bind", bind_attr):tag("required"):up():up(); features:tag("session", xmpp_session_attr):up(); end end); module:add_iq_handler("c2s", "urn:ietf:params:xml:ns:xmpp-bind", function (session, stanza) log("debug", "Client tried to bind to a resource"); local resource; if stanza.attr.type == "set" then local bind = stanza.tags[1]; if bind and bind.attr.xmlns == xmlns_bind then resource = bind:child_with_name("resource"); if resource then resource = resource[1]; end end end local success, err_type, err, err_msg = sm_bind_resource(session, resource); if not success then session.send(st.error_reply(stanza, err_type, err, err_msg)); else session.send(st.reply(stanza) :tag("bind", { xmlns = xmlns_bind}) :tag("jid"):text(session.full_jid)); end end); module:add_iq_handler("c2s", "urn:ietf:params:xml:ns:xmpp-session", function (session, stanza) log("debug", "Client tried to bind to a resource"); session.send(st.reply(stanza)); end);
-- Prosody IM v0.4 -- Copyright (C) 2008-2009 Matthew Wild -- Copyright (C) 2008-2009 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local st = require "util.stanza"; local sm_bind_resource = require "core.sessionmanager".bind_resource; local base64 = require "util.encodings".base64; local usermanager_validate_credentials = require "core.usermanager".validate_credentials; local t_concat, t_insert = table.concat, table.insert; local tostring = tostring; local jid_split = require "util.jid".split local md5 = require "util.hashes".md5; local config = require "core.configmanager"; local log = require "util.logger".init("mod_saslauth"); local xmlns_sasl ='urn:ietf:params:xml:ns:xmpp-sasl'; local xmlns_bind ='urn:ietf:params:xml:ns:xmpp-bind'; local xmlns_stanzas ='urn:ietf:params:xml:ns:xmpp-stanzas'; local new_sasl = require "util.sasl".new; local function build_reply(status, ret, err_msg) local reply = st.stanza(status, {xmlns = xmlns_sasl}); if status == "challenge" then log("debug", ret or ""); reply:text(base64.encode(ret or "")); elseif status == "failure" then reply:tag(ret):up(); if err_msg then reply:tag("text"):text(err_msg); end elseif status == "success" then log("debug", ret or ""); reply:text(base64.encode(ret or "")); else error("Unknown sasl status: "..status); end return reply; end local function handle_status(session, status) if status == "failure" then session.sasl_handler = nil; elseif status == "success" then if not session.sasl_handler.username then error("SASL succeeded but we didn't get a username!"); end -- TODO move this to sessionmanager sessionmanager.make_authenticated(session, session.sasl_handler.username); session.sasl_handler = nil; session:reset_stream(); end end local function password_callback(node, host, mechanism, decoder) local password = (datamanager.load(node, host, "accounts") or {}).password; -- FIXME handle hashed passwords local func = function(x) return x; end; if password then if mechanism == "PLAIN" then return func, password; elseif mechanism == "DIGEST-MD5" then if decoder then node, host, password = decoder(node), decoder(host), decoder(password); end return func, md5(node..":"..host..":"..password); end end return func, nil; end local function sasl_handler(session, stanza) if stanza.name == "auth" then -- FIXME ignoring duplicates because ejabberd does if config.get(session.host or "*", "core", "anonymous_login") and stanza.attr.mechanism ~= "ANONYMOUS" then return session.send(build_reply("failure", "invalid-mechanism")); elseif mechanism == "ANONYMOUS" then return session.send(build_reply("failure", "mechanism-too-weak")); end session.sasl_handler = new_sasl(stanza.attr.mechanism, session.host, password_callback); if not session.sasl_handler then return session.send(build_reply("failure", "invalid-mechanism")); end elseif not session.sasl_handler then return; -- FIXME ignoring out of order stanzas because ejabberd does end local text = stanza[1]; if text then text = base64.decode(text); log("debug", text); if not text then session.sasl_handler = nil; session.send(build_reply("failure", "incorrect-encoding")); return; end end local status, ret, err_msg = session.sasl_handler:feed(text); handle_status(session, status); local s = build_reply(status, ret, err_msg); log("debug", "sasl reply: "..tostring(s)); session.send(s); end module:add_handler("c2s_unauthed", "auth", xmlns_sasl, sasl_handler); module:add_handler("c2s_unauthed", "abort", xmlns_sasl, sasl_handler); module:add_handler("c2s_unauthed", "response", xmlns_sasl, sasl_handler); local mechanisms_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-sasl' }; local bind_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-bind' }; local xmpp_session_attr = { xmlns='urn:ietf:params:xml:ns:xmpp-session' }; module:add_event_hook("stream-features", function (session, features) if not session.username then features:tag("mechanisms", mechanisms_attr); -- TODO: Provide PLAIN only if TLS is active, this is a SHOULD from the introduction of RFC 4616. This behavior could be overridden via configuration but will issuing a warning or so. if config.get(session.host or "*", "core", "anonymous_login") then features:tag("mechanism"):text("ANONYMOUS"):up(); else features:tag("mechanism"):text("DIGEST-MD5"):up(); features:tag("mechanism"):text("PLAIN"):up(); end features:up(); else features:tag("bind", bind_attr):tag("required"):up():up(); features:tag("session", xmpp_session_attr):up(); end end); module:add_iq_handler("c2s", "urn:ietf:params:xml:ns:xmpp-bind", function (session, stanza) log("debug", "Client tried to bind to a resource"); local resource; if stanza.attr.type == "set" then local bind = stanza.tags[1]; if bind and bind.attr.xmlns == xmlns_bind then resource = bind:child_with_name("resource"); if resource then resource = resource[1]; end end end local success, err_type, err, err_msg = sm_bind_resource(session, resource); if not success then session.send(st.error_reply(stanza, err_type, err, err_msg)); else session.send(st.reply(stanza) :tag("bind", { xmlns = xmlns_bind}) :tag("jid"):text(session.full_jid)); end end); module:add_iq_handler("c2s", "urn:ietf:params:xml:ns:xmpp-session", function (session, stanza) log("debug", "Client tried to bind to a resource"); session.send(st.reply(stanza)); end);
Fixed: mod_saslauth: "anonymous_login" currently makes SASL ANONYMOUS an exclusive mechanism. Corrected advertised mechanisms and error replies.
Fixed: mod_saslauth: "anonymous_login" currently makes SASL ANONYMOUS an exclusive mechanism. Corrected advertised mechanisms and error replies.
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
35c228b0149e406b04d3b8175c37d5653085d8e4
lua/entities/gmod_wire_forcer.lua
lua/entities/gmod_wire_forcer.lua
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Forcer" ENT.RenderGroup = RENDERGROUP_BOTH ENT.WireDebugName = "Forcer" function ENT:SetupDataTables() self:NetworkVar( "Float", 0, "BeamLength" ) self:NetworkVar( "Bool", 0, "ShowBeam" ) self:NetworkVar( "Bool", 1, "BeamHighlight" ) end if CLIENT then return end -- No more client function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.Force = 0 self.OffsetForce = 0 self.Velocity = 0 self.Inputs = WireLib.CreateInputs( self, { "Force", "OffsetForce", "Velocity", "Length" } ) self:Setup(0, 100, true, false) end function ENT:Setup( Force, Length, ShowBeam, Reaction ) self.ForceMul = Force or 1 self.Reaction = Reaction or false if Length then self:SetBeamLength(Length) end if ShowBeam ~= nil then self:SetShowBeam(ShowBeam) end self:ShowOutput() end function ENT:TriggerInput( name, value ) if (name == "Force") then self.Force = value self:SetBeamHighlight(value != 0) self:ShowOutput() elseif (name == "OffsetForce") then self.OffsetForce = value self:SetBeamHighlight(value != 0) self:ShowOutput() elseif (name == "Velocity") then self.Velocity = math.Clamp(value,-100000,100000) self:SetBeamHighlight(value != 0) self:ShowOutput() elseif (name == "Length") then self:SetBeamLength(math.Round(value)) self:ShowOutput() end end function ENT:Think() if self.Force == 0 and self.OffsetForce == 0 and self.Velocity == 0 then return end local Forward = self:GetUp() local BeamOrigin = self:GetPos() + Forward * self:OBBMaxs().z local trace = util.TraceLine { start = BeamOrigin, endpos = BeamOrigin + self:GetBeamLength() * Forward, filter = self } if not IsValid(trace.Entity) then return end if not gamemode.Call( "GravGunPunt", self:GetPlayer(), trace.Entity ) then return end if trace.Entity:GetMoveType() == MOVETYPE_VPHYSICS then local phys = trace.Entity:GetPhysicsObject() if not IsValid(phys) then return end if self.Force ~= 0 then phys:ApplyForceCenter( Forward * self.Force * self.ForceMul ) end if self.OffsetForce ~= 0 then phys:ApplyForceOffset( Forward * self.OffsetForce * self.ForceMul, trace.HitPos ) end if self.Velocity ~= 0 then phys:SetVelocityInstantaneous( Forward * self.Velocity ) end else if self.Velocity ~= 0 then trace.Entity:SetVelocity( Forward * self.Velocity ) end end if self.Reaction and IsValid(self:GetPhysicsObject()) and (self.Force + self.OffsetForce ~= 0) then self:GetPhysicsObject():ApplyForceCenter( Forward * -(self.Force + self.OffsetForce) * self.ForceMul ) end self:NextThink( CurTime() ) return true end function ENT:ShowOutput() self:SetOverlayText( "Center Force = "..math.Round(self.ForceMul * self.Force).. "\nOffset Force = "..math.Round(self.ForceMul * self.OffsetForce).. "\nVelocity = "..math.Round(self.Velocity).. "\nLength = " .. math.Round(self:GetBeamLength()) ) end function ENT:BuildDupeInfo() local info = self.BaseClass.BuildDupeInfo(self) or {} info.ForceMul = self.ForceMul info.Reaction = self.Reaction return info end function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) self:Setup( info.ForceMul, info.Length, info.ShowBeam, info.Reaction ) self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) end --Moves old "A" input to new "Force" input for older saves WireLib.AddInputAlias( "A", "Force" ) duplicator.RegisterEntityClass("gmod_wire_forcer", WireLib.MakeWireEnt, "Data", "Force", "Length", "ShowBeam", "Reaction")
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Forcer" ENT.RenderGroup = RENDERGROUP_BOTH ENT.WireDebugName = "Forcer" function ENT:SetupDataTables() self:NetworkVar( "Float", 0, "BeamLength" ) self:NetworkVar( "Bool", 0, "ShowBeam" ) self:NetworkVar( "Bool", 1, "BeamHighlight" ) end if CLIENT then return end -- No more client function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.Force = 0 self.OffsetForce = 0 self.Velocity = 0 self.Inputs = WireLib.CreateInputs( self, { "Force", "OffsetForce", "Velocity", "Length" } ) self:Setup(0, 100, true, false) end function ENT:Setup( Force, Length, ShowBeam, Reaction ) self.ForceMul = Force or 1 self.Reaction = Reaction or false if Length then self:SetBeamLength(Length) end if ShowBeam ~= nil then self:SetShowBeam(ShowBeam) end self:ShowOutput() end function ENT:TriggerInput( name, value ) if (name == "Force") then self.Force = value self:SetBeamHighlight(value != 0) self:ShowOutput() elseif (name == "OffsetForce") then self.OffsetForce = value self:SetBeamHighlight(value != 0) self:ShowOutput() elseif (name == "Velocity") then self.Velocity = math.Clamp(value,-100000,100000) self:SetBeamHighlight(value != 0) self:ShowOutput() elseif (name == "Length") then self:SetBeamLength(math.Round(value)) self:ShowOutput() end end local check = WireLib.checkForce function ENT:Think() if self.Force == 0 and self.OffsetForce == 0 and self.Velocity == 0 then return end local Forward = self:GetUp() local BeamOrigin = self:GetPos() + Forward * self:OBBMaxs().z local trace = util.TraceLine { start = BeamOrigin, endpos = BeamOrigin + self:GetBeamLength() * Forward, filter = self } if not IsValid(trace.Entity) then return end if not gamemode.Call( "GravGunPunt", self:GetPlayer(), trace.Entity ) then return end if trace.Entity:GetMoveType() == MOVETYPE_VPHYSICS then local phys = trace.Entity:GetPhysicsObject() if not IsValid(phys) then return end if self.Force ~= 0 and check(Forward * self.Force * self.ForceMul) then phys:ApplyForceCenter( Forward * self.Force * self.ForceMul ) end if self.OffsetForce ~= 0 and check(Forward * self.OffsetForce * self.ForceMul) then phys:ApplyForceOffset( Forward * self.OffsetForce * self.ForceMul, trace.HitPos ) end if self.Velocity ~= 0 then phys:SetVelocityInstantaneous( Forward * self.Velocity ) end else if self.Velocity ~= 0 then trace.Entity:SetVelocity( Forward * self.Velocity ) end end if self.Reaction and IsValid(self:GetPhysicsObject()) and (self.Force + self.OffsetForce ~= 0) and check(Forward * -(self.Force + self.OffsetForce) * self.ForceMul) then self:GetPhysicsObject():ApplyForceCenter( Forward * -(self.Force + self.OffsetForce) * self.ForceMul ) end self:NextThink( CurTime() ) return true end function ENT:ShowOutput() self:SetOverlayText( "Center Force = "..math.Round(self.ForceMul * self.Force).. "\nOffset Force = "..math.Round(self.ForceMul * self.OffsetForce).. "\nVelocity = "..math.Round(self.Velocity).. "\nLength = " .. math.Round(self:GetBeamLength()) ) end function ENT:BuildDupeInfo() local info = self.BaseClass.BuildDupeInfo(self) or {} info.ForceMul = self.ForceMul info.Reaction = self.Reaction return info end function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) self:Setup( info.ForceMul, info.Length, info.ShowBeam, info.Reaction ) self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) end --Moves old "A" input to new "Force" input for older saves WireLib.AddInputAlias( "A", "Force" ) duplicator.RegisterEntityClass("gmod_wire_forcer", WireLib.MakeWireEnt, "Data", "Force", "Length", "ShowBeam", "Reaction")
Fix ApplyForce/physics-crash with Forcer. (#1196)
Fix ApplyForce/physics-crash with Forcer. (#1196)
Lua
apache-2.0
wiremod/wire,bigdogmat/wire,NezzKryptic/Wire,sammyt291/wire,dvdvideo1234/wire,Grocel/wire,garrysmodlua/wire,thegrb93/wire
a9add89332585302ed817c0279d341643cef444b
lua_modules/keystone/lib/init.lua
lua_modules/keystone/lib/init.lua
--[[ Copyright 2012 Rackspace Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local JSON = require('json') local Object = require('core').Object local Error = require('core').Error local https = require('https') local table = require('table') local fmt = require('string').format local url = require('url') local Client = Object:extend() function Client:initialize(authUrl, options) self.authUrl = authUrl self.username = options.username self.apikey = options.apikey self.password = options.password self.extraArgs = options.extraArgs or {} self._token = nil self._tokenExpires = nil self._tenantId = nil self._serviceCatalog = {} end function Client:_updateToken(callback) local body = {} local parsed = url.parse(self.authUrl) local urlPath local options local headers local client local body headers = {} headers['Accept'] = 'application/json' headers['Content-Type'] = 'application/json' urlPath = fmt('%s/tokens', parsed.pathname) if self.password then body = { ['auth'] = { ['passwordCredentials'] = { ['username'] = self.username, ['password'] = self.password } } } else body = { ['auth'] = { ['RAX-KSKEY:apiKeyCredentials'] = { ['username'] = self.username, ['apiKey'] = self.apikey } } } end body = JSON.stringify(body) headers['Content-Length'] = #body options = { host = parsed.hostname, port = tonumber(parsed.port), path = urlPath, headers = headers, method = 'POST' } client = https.request(options, function(res) local data = '' res:on('data', function(chunk) data = data .. chunk end) res:on('end', function() local json, payload, newToken, newExpires local results = { xpcall(function() return JSON.parse(data) end, function(err) return err end) } -- protected call errored out if not results[1] then callback(results[1]) return end payload = results[2] if payload.access then newToken = payload.access.token.id newExpires = payload.access.token.expires else callback(Error:new('Invalid response from auth server')) return end self._token = newToken self._tokenExpires = newExpires self._serviceCatalog = payload.access.serviceCatalog callback(nil, self._token) end) end) client:done(body) end function Client:tenantIdAndToken(callback) self:_updateToken(function(err, token) if err then callback(err) return end for i, _ in ipairs(self._serviceCatalog) do local item = self._serviceCatalog[i] if item.name == 'cloudServers' or item.name == 'cloudServersLegacy' then if #item.endpoints == 0 then error('Endpoints should be > 0') end self._tenantId = item.endpoints[1].tenantId end end callback(nil, { token = self._token, expires = self._tokenExpires, tenantId = self._tenantId }) end) end local exports = {} exports.Client = Client return exports
--[[ Copyright 2012 Rackspace Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local JSON = require('json') local Object = require('core').Object local Error = require('core').Error local https = require('https') local table = require('table') local fmt = require('string').format local url = require('url') local Client = Object:extend() function Client:initialize(authUrl, options) self.authUrl = authUrl self.username = options.username self.apikey = options.apikey self.password = options.password self.extraArgs = options.extraArgs or {} self._token = nil self._tokenExpires = nil self._tenantId = nil self._serviceCatalog = {} end function Client:_updateToken(callback) local body = {} local parsed = url.parse(self.authUrl) local urlPath local options local headers local client local body headers = {} headers['Accept'] = 'application/json' headers['Content-Type'] = 'application/json' urlPath = fmt('%s/tokens', parsed.pathname) if self.password then body = { ['auth'] = { ['passwordCredentials'] = { ['username'] = self.username, ['password'] = self.password } } } else body = { ['auth'] = { ['RAX-KSKEY:apiKeyCredentials'] = { ['username'] = self.username, ['apiKey'] = self.apikey } } } end body = JSON.stringify(body) headers['Content-Length'] = #body options = { host = parsed.hostname, port = tonumber(parsed.port), path = urlPath, headers = headers, method = 'POST' } client = https.request(options, function(res) local data = '' res:on('data', function(chunk) data = data .. chunk end) res:on('end', function() local json, payload, newToken, newExpires local results = { xpcall(function() return JSON.parse(data) end, function(err) return err end) } -- protected call errored out if not results[1] then callback(results[1]) return end payload = results[2] if payload.access then newToken = payload.access.token.id newExpires = payload.access.token.expires else callback(Error:new('Invalid response from auth server')) return end self._token = newToken self._tokenExpires = newExpires self._serviceCatalog = payload.access.serviceCatalog callback(nil, self._token) end) end) client:done(body) end function Client:tenantIdAndToken(callback) self:_updateToken(function(err, token) if err then callback(err) return end for i, _ in ipairs(self._serviceCatalog) do local item = self._serviceCatalog[i] if item.name == 'cloudMonitoring' then if #item.endpoints == 0 then error('Endpoints should be > 0') end self._tenantId = item.endpoints[1].tenantId end end callback(nil, { token = self._token, expires = self._tokenExpires, tenantId = self._tenantId }) end) end local exports = {} exports.Client = Client return exports
fixes(auth): use the cloudMonitoring service catalog
fixes(auth): use the cloudMonitoring service catalog
Lua
apache-2.0
christopherjwang/rackspace-monitoring-agent,christopherjwang/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent
06053f695c3ebe2bc7a8b9228b01fb5887aeb9ed
src/lib/interlink.lua
src/lib/interlink.lua
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(...,package.seeall) -- Based on MCRingBuffer, see -- http://www.cse.cuhk.edu.hk/%7Epclee/www/pubs/ipdps10.pdf local shm = require("core.shm") local ffi = require("ffi") local band = require("bit").band local SIZE = link.max + 1 local CACHELINE = 64 -- XXX - make dynamic local INT = ffi.sizeof("int") assert(band(SIZE, SIZE-1) == 0, "SIZE is not a power of two") ffi.cdef([[ struct interlink { char pad0[]]..CACHELINE..[[]; int read, write; char pad1[]]..CACHELINE-2*INT..[[]; int lwrite, nread; char pad2[]]..CACHELINE-2*INT..[[]; int lread, nwrite; char pad3[]]..CACHELINE-2*INT..[[]; struct packet *packets[]]..SIZE..[[]; }]]) function create (name) local r = shm.create(name, "struct interlink") r.nwrite = link.max -- “full” until initlaized return r end function init (r) -- initialization must be performed by consumer assert(full(r) and empty(r)) -- only satisfied if uninitialized for i = 0, link.max do r.packets[i] = packet.allocate() end r.nwrite = 0 end local function NEXT (r, i) return band(i + 1, link.max) end function full (r) local after_nwrite = NEXT(r, r.nwrite) if after_nwrite == r.lread then if after_nwrite == r.read then return true end r.lread = r.read end end function insert (r, p) packet.free(r.packets[r.nwrite]) r.packets[r.nwrite] = p r.nwrite = NEXT(r, r.nwrite) end function push (r) r.write = r.nwrite end function empty (r) if r.nread == r.lwrite then if r.nread == r.write then return true end r.lwrite = r.write end end function extract (r) local p = r.packets[r.nread] r.packets[r.nread] = packet.allocate() r.nread = NEXT(r, r.nread) return p end function pull (r) r.read = r.nread end
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(...,package.seeall) -- Based on MCRingBuffer, see -- http://www.cse.cuhk.edu.hk/%7Epclee/www/pubs/ipdps10.pdf local shm = require("core.shm") local ffi = require("ffi") local band = require("bit").band local SIZE = link.max + 1 local CACHELINE = 64 -- XXX - make dynamic local INT = ffi.sizeof("int") assert(band(SIZE, SIZE-1) == 0, "SIZE is not a power of two") ffi.cdef([[ struct interlink { char pad0[]]..CACHELINE..[[]; int read, write; char pad1[]]..CACHELINE-2*INT..[[]; int lwrite, nread; char pad2[]]..CACHELINE-2*INT..[[]; int lread, nwrite; char pad3[]]..CACHELINE-2*INT..[[]; struct packet *packets[]]..SIZE..[[]; }]]) function create (name) local r = shm.create(name, "struct interlink") r.nwrite = link.max -- “full” until initlaized return r end function init (r) -- initialization must be performed by consumer assert(r.packets[0] == ffi.new("void *")) -- only satisfied if uninitialized for i = 0, link.max do r.packets[i] = packet.allocate() end r.nwrite = 0 end local function NEXT (r, i) return band(i + 1, link.max) end function full (r) local after_nwrite = NEXT(r, r.nwrite) if after_nwrite == r.lread then if after_nwrite == r.read then return true end r.lread = r.read end end function insert (r, p) packet.free(r.packets[r.nwrite]) r.packets[r.nwrite] = p r.nwrite = NEXT(r, r.nwrite) end function push (r) r.write = r.nwrite end function empty (r) if r.nread == r.lwrite then if r.nread == r.write then return true end r.lwrite = r.write end end function extract (r) local p = r.packets[r.nread] r.packets[r.nread] = packet.allocate() r.nread = NEXT(r, r.nread) return p end function pull (r) r.read = r.nread end
lib.interlink: fix initialization race.
lib.interlink: fix initialization race.
Lua
apache-2.0
eugeneia/snabbswitch,eugeneia/snabb,SnabbCo/snabbswitch,snabbco/snabb,Igalia/snabb,Igalia/snabb,alexandergall/snabbswitch,snabbco/snabb,snabbco/snabb,alexandergall/snabbswitch,dpino/snabbswitch,eugeneia/snabb,Igalia/snabbswitch,Igalia/snabbswitch,dpino/snabbswitch,dpino/snabb,dpino/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,eugeneia/snabbswitch,dpino/snabb,SnabbCo/snabbswitch,Igalia/snabbswitch,snabbco/snabb,Igalia/snabb,SnabbCo/snabbswitch,Igalia/snabb,dpino/snabb,dpino/snabb,Igalia/snabb,Igalia/snabbswitch,eugeneia/snabb,eugeneia/snabb,eugeneia/snabb,snabbco/snabb,snabbco/snabb,dpino/snabb,eugeneia/snabb,alexandergall/snabbswitch,dpino/snabbswitch,snabbco/snabb,eugeneia/snabbswitch,eugeneia/snabb,alexandergall/snabbswitch,Igalia/snabb,snabbco/snabb,Igalia/snabb,alexandergall/snabbswitch,Igalia/snabbswitch,dpino/snabb,alexandergall/snabbswitch,eugeneia/snabb,dpino/snabbswitch,Igalia/snabb,eugeneia/snabbswitch,SnabbCo/snabbswitch
f757587b3d951a2676c08a4d76eb1e19fa9d39fb
hostinfo/packages.lua
hostinfo/packages.lua
--[[ Copyright 2014 Rackspace Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local HostInfo = require('./base').HostInfo local fmt = require('string').format local los = require('los') local sctx = require('sigar').ctx local table = require('table') local execFileToBuffers = require('./misc').execFileToBuffers --[[ Packages Variables ]]-- local Info = HostInfo:extend() function Info:initialize() HostInfo.initialize(self) end function Info:run(callback) if los.type() ~= 'linux' then self._error = 'Unsupported OS for Packages' callback() return end local function execCb(err, exitcode, stdout_data, stderr_data) if exitcode ~= 0 then self._error = fmt("Packages exited with a %d exitcode", exitcode) callback() return end for line in stdout_data:gmatch("[^\r\n]+") do line = line:gsub("^%s*(.-)%s*$", "%1") local _, _, key, value = line:find("(.*)%s(.*)") if key ~= nil then local obj = {} obj[key] = value table.insert(self._params, obj) end end callback() end local sysinfo = sctx:sysinfo() local vendor = sysinfo.vendor:lower() local command local args local options if vendor == 'ubuntu' or vendor == 'debian' then command = 'dpkg-query' args = {'-W'} options = {} elseif vendor == 'rhel' or vendor == 'centos' then command = 'rpm' args = {"-qa", '--queryformat', '%{NAME}: %{VERSION}-%{RELEASE}\n'} options = {} else self._error = 'Could not determine OS for Packages' callback() return end execFileToBuffers(command, args, options, execCb) end function Info:getType() return 'PACKAGES' end return Info
--[[ Copyright 2014 Rackspace Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local HostInfo = require('./base').HostInfo local fmt = require('string').format local los = require('los') local sigar = require('sigar') local table = require('table') local execFileToBuffers = require('./misc').execFileToBuffers --[[ Packages Variables ]]-- local Info = HostInfo:extend() function Info:initialize() HostInfo.initialize(self) end function Info:run(callback) if los.type() ~= 'linux' then self._error = 'Unsupported OS for Packages' callback() return end local function execCb(err, exitcode, stdout_data, stderr_data) if exitcode ~= 0 then self._error = fmt("Packages exited with a %d exitcode", exitcode) callback() return end for line in stdout_data:gmatch("[^\r\n]+") do line = line:gsub("^%s*(.-)%s*$", "%1") local _, _, key, value = line:find("(.*)%s(.*)") if key ~= nil then local obj = {} obj[key] = value table.insert(self._params, obj) end end callback() end local command, args, options, vendor vendor = sigar:new():sysinfo().vendor:lower() if vendor == 'ubuntu' or vendor == 'debian' then command = 'dpkg-query' args = {'-W'} options = {} elseif vendor == 'rhel' or vendor == 'centos' then command = 'rpm' args = {"-qa", '--queryformat', '%{NAME}: %{VERSION}-%{RELEASE}\n'} options = {} else self._error = 'Could not determine OS for Packages' callback() return end execFileToBuffers(command, args, options, execCb) end function Info:getType() return 'PACKAGES' end return Info
fix(hostinfo/packages): This check was broken, need to initialize sigar context with :new, cant just req(sigar).ctx
fix(hostinfo/packages): This check was broken, need to initialize sigar context with :new, cant just req(sigar).ctx refactor(hostinfo/packages): one lined the vendor info getter and a few other variable declarations fix(hostinfo/packages): This check was broken, need to initialize sigar context with :new, cant just req(sigar).ctx refactor(hostinfo/packages): require sigar instead of instantiating only the vendor function
Lua
apache-2.0
AlphaStaxLLC/rackspace-monitoring-agent,AlphaStaxLLC/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent,kaustavha/rackspace-monitoring-agent,virgo-agent-toolkit/rackspace-monitoring-agent
bbe4ccd9490a4b9177b85d75a011dcb0db611a47
modules/freifunk/luasrc/model/cbi/freifunk/public_status.lua
modules/freifunk/luasrc/model/cbi/freifunk/public_status.lua
require "luci.sys" require "luci.tools.webadmin" local uci = luci.model.uci.cursor_state() local ffzone = luci.tools.webadmin.firewall_find_zone("freifunk") local ffznet = ffzone and uci:get("firewall", ffzone, "network") local ffwifs = ffznet and luci.util.split(ffznet, " ") or {} -- System -- f = SimpleForm("system", "System") f.submit = false f.reset = false local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo() local uptime = luci.sys.uptime() f:field(DummyValue, "_system", translate("system")).value = system f:field(DummyValue, "_cpu", translate("m_i_processor")).value = model local load1, load5, load15 = luci.sys.loadavg() f:field(DummyValue, "_la", translate("load")).value = string.format("%.2f, %.2f, %.2f", load1, load5, load15) f:field(DummyValue, "_memtotal", translate("m_i_memory")).value = string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)", tonumber(memtotal) / 1024, 100 * memcached / memtotal, translate("mem_cached") or "", 100 * membuffers / memtotal, translate("mem_buffered") or "", 100 * memfree / memtotal, translate("mem_free") or "") f:field(DummyValue, "_systime", translate("m_i_systemtime")).value = os.date("%c") f:field(DummyValue, "_uptime", translate("m_i_uptime")).value = luci.tools.webadmin.date_format(tonumber(uptime)) -- Wireless -- local wireless = uci:get_all("wireless") local wifidata = luci.sys.wifi.getiwconfig() local ifaces = {} for k, v in pairs(wireless) do if v[".type"] == "wifi-iface" and luci.util.contains(ffwifs, v.device) then table.insert(ifaces, v) end end m = SimpleForm("wireless", "Freifunk WLAN") m.submit = false m.reset = false s = m:section(Table, ifaces, translate("networks")) link = s:option(DummyValue, "_link", translate("link")) function link.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") return wifidata[ifname] and wifidata[ifname]["Link Quality"] or "-" end essid = s:option(DummyValue, "ssid", "ESSID") bssid = s:option(DummyValue, "_bsiid", "BSSID") function bssid.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") return (wifidata[ifname] and (wifidata[ifname].Cell or wifidata[ifname]["Access Point"])) or "-" end channel = s:option(DummyValue, "channel", translate("channel")) function channel.cfgvalue(self, section) return wireless[self.map:get(section, "device")].channel end protocol = s:option(DummyValue, "_mode", translate("protocol")) function protocol.cfgvalue(self, section) local mode = wireless[self.map:get(section, "device")].mode return mode and "802." .. mode end mode = s:option(DummyValue, "mode", translate("mode")) encryption = s:option(DummyValue, "encryption", translate("iwscan_encr")) power = s:option(DummyValue, "_power", translate("power")) function power.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") return wifidata[ifname] and wifidata[ifname]["Tx-Power"] or "-" end scan = s:option(Button, "_scan", translate("scan")) scan.inputstyle = "find" function scan.cfgvalue(self, section) return self.map:get(section, "ifname") or false end t2 = m:section(Table, {}, translate("iwscan"), translate("iwscan1")) function scan.write(self, section) t2.render = t2._render local ifname = self.map:get(section, "ifname") luci.util.update(t2.data, luci.sys.wifi.iwscan(ifname)) end t2._render = t2.render t2.render = function() end t2:option(DummyValue, "Quality", translate("iwscan_link")) essid = t2:option(DummyValue, "ESSID", "ESSID") function essid.cfgvalue(self, section) return luci.util.pcdata(self.map:get(section, "ESSID")) end t2:option(DummyValue, "Address", "BSSID") t2:option(DummyValue, "Mode", translate("mode")) chan = t2:option(DummyValue, "channel", translate("channel")) function chan.cfgvalue(self, section) return self.map:get(section, "Channel") or self.map:get(section, "Frequency") or "-" end t2:option(DummyValue, "Encryption key", translate("iwscan_encr")) t2:option(DummyValue, "Signal level", translate("iwscan_signal")) t2:option(DummyValue, "Noise level", translate("iwscan_noise")) -- Routes -- r = SimpleForm("routes", "Standardrouten") r.submit = false r.reset = false local routes = {} for i, route in ipairs(luci.sys.net.routes()) do if route.dest:prefix() == 0 then routes[#routes+1] = route end end v = r:section(Table, routes) net = v:option(DummyValue, "iface", translate("network")) function net.cfgvalue(self, section) return luci.tools.webadmin.iface_get_network(routes[section].device) or routes[section].device end target = v:option(DummyValue, "target", translate("target")) function target.cfgvalue(self, section) return routes[section].dest:network():string() end netmask = v:option(DummyValue, "netmask", translate("netmask")) function netmask.cfgvalue(self, section) return routes[section].dest:mask():string() end gateway = v:option(DummyValue, "gateway", translate("gateway")) function gateway.cfgvalue(self, section) return routes[section].gateway:string() end metric = v:option(DummyValue, "metric", translate("metric")) function metric.cfgvalue(self, section) return routes[section].metric end local routes6 = {} for i, route in ipairs(luci.sys.net.routes6() or {}) do if route.dest:prefix() == 0 then routes6[#routes6+1] = route end end if #routes6 > 0 then v6 = r:section(Table, routes6) net = v6:option(DummyValue, "iface", translate("network")) function net.cfgvalue(self, section) return luci.tools.webadmin.iface_get_network(routes[section].device) or routes6[section].device end target = v6:option(DummyValue, "target", translate("target")) function target.cfgvalue(self, section) return routes6[section].dest:string() end gateway = v6:option(DummyValue, "gateway6", translate("gateway6")) function gateway.cfgvalue(self, section) return routes6[section].source:string() end metric = v6:option(DummyValue, "metric", translate("metric")) function metric.cfgvalue(self, section) return string.format("%X", routes6[section].metric) end end return f, m, r
require "luci.sys" require "luci.tools.webadmin" local bit = require "bit" local uci = luci.model.uci.cursor_state() local ffzone = luci.tools.webadmin.firewall_find_zone("freifunk") local ffznet = ffzone and uci:get("firewall", ffzone, "network") local ffwifs = ffznet and luci.util.split(ffznet, " ") or {} -- System -- f = SimpleForm("system", "System") f.submit = false f.reset = false local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo() local uptime = luci.sys.uptime() f:field(DummyValue, "_system", translate("system")).value = system f:field(DummyValue, "_cpu", translate("m_i_processor")).value = model local load1, load5, load15 = luci.sys.loadavg() f:field(DummyValue, "_la", translate("load")).value = string.format("%.2f, %.2f, %.2f", load1, load5, load15) f:field(DummyValue, "_memtotal", translate("m_i_memory")).value = string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)", tonumber(memtotal) / 1024, 100 * memcached / memtotal, translate("mem_cached") or "", 100 * membuffers / memtotal, translate("mem_buffered") or "", 100 * memfree / memtotal, translate("mem_free") or "") f:field(DummyValue, "_systime", translate("m_i_systemtime")).value = os.date("%c") f:field(DummyValue, "_uptime", translate("m_i_uptime")).value = luci.tools.webadmin.date_format(tonumber(uptime)) -- Wireless -- local wireless = uci:get_all("wireless") local wifidata = luci.sys.wifi.getiwconfig() local ifaces = {} for k, v in pairs(wireless) do if v[".type"] == "wifi-iface" and luci.util.contains(ffwifs, v.device) then table.insert(ifaces, v) end end m = SimpleForm("wireless", "Freifunk WLAN") m.submit = false m.reset = false s = m:section(Table, ifaces, translate("networks")) link = s:option(DummyValue, "_link", translate("link")) function link.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") return wifidata[ifname] and wifidata[ifname]["Link Quality"] or "-" end essid = s:option(DummyValue, "ssid", "ESSID") bssid = s:option(DummyValue, "_bsiid", "BSSID") function bssid.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") return (wifidata[ifname] and (wifidata[ifname].Cell or wifidata[ifname]["Access Point"])) or "-" end channel = s:option(DummyValue, "channel", translate("channel")) function channel.cfgvalue(self, section) return wireless[self.map:get(section, "device")].channel end protocol = s:option(DummyValue, "_mode", translate("protocol")) function protocol.cfgvalue(self, section) local mode = wireless[self.map:get(section, "device")].mode return mode and "802." .. mode end mode = s:option(DummyValue, "mode", translate("mode")) encryption = s:option(DummyValue, "encryption", translate("iwscan_encr")) power = s:option(DummyValue, "_power", translate("power")) function power.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") return wifidata[ifname] and wifidata[ifname]["Tx-Power"] or "-" end scan = s:option(Button, "_scan", translate("scan")) scan.inputstyle = "find" function scan.cfgvalue(self, section) return self.map:get(section, "ifname") or false end t2 = m:section(Table, {}, translate("iwscan"), translate("iwscan1")) function scan.write(self, section) t2.render = t2._render local ifname = self.map:get(section, "ifname") luci.util.update(t2.data, luci.sys.wifi.iwscan(ifname)) end t2._render = t2.render t2.render = function() end t2:option(DummyValue, "Quality", translate("iwscan_link")) essid = t2:option(DummyValue, "ESSID", "ESSID") function essid.cfgvalue(self, section) return luci.util.pcdata(self.map:get(section, "ESSID")) end t2:option(DummyValue, "Address", "BSSID") t2:option(DummyValue, "Mode", translate("mode")) chan = t2:option(DummyValue, "channel", translate("channel")) function chan.cfgvalue(self, section) return self.map:get(section, "Channel") or self.map:get(section, "Frequency") or "-" end t2:option(DummyValue, "Encryption key", translate("iwscan_encr")) t2:option(DummyValue, "Signal level", translate("iwscan_signal")) t2:option(DummyValue, "Noise level", translate("iwscan_noise")) -- Routes -- r = SimpleForm("routes", "Standardrouten") r.submit = false r.reset = false local routes = {} for i, route in ipairs(luci.sys.net.routes()) do if route.dest:prefix() == 0 then routes[#routes+1] = route end end v = r:section(Table, routes) net = v:option(DummyValue, "iface", translate("network")) function net.cfgvalue(self, section) return luci.tools.webadmin.iface_get_network(routes[section].device) or routes[section].device end target = v:option(DummyValue, "target", translate("target")) function target.cfgvalue(self, section) return routes[section].dest:network():string() end netmask = v:option(DummyValue, "netmask", translate("netmask")) function netmask.cfgvalue(self, section) return routes[section].dest:mask():string() end gateway = v:option(DummyValue, "gateway", translate("gateway")) function gateway.cfgvalue(self, section) return routes[section].gateway:string() end metric = v:option(DummyValue, "metric", translate("metric")) function metric.cfgvalue(self, section) return routes[section].metric end local routes6 = {} for i, route in ipairs(luci.sys.net.routes6() or {}) do if route.dest:prefix() == 0 then routes6[#routes6+1] = route end end if #routes6 > 0 then v6 = r:section(Table, routes6) net = v6:option(DummyValue, "iface", translate("network")) function net.cfgvalue(self, section) return luci.tools.webadmin.iface_get_network(routes[section].device) or routes6[section].device end target = v6:option(DummyValue, "target", translate("target")) function target.cfgvalue(self, section) return routes6[section].dest:string() end gateway = v6:option(DummyValue, "gateway6", translate("gateway6")) function gateway.cfgvalue(self, section) return routes6[section].source:string() end metric = v6:option(DummyValue, "metric", translate("metric")) function metric.cfgvalue(self, section) local metr = routes6[section].metric local lower = bit.band(metr, 0xffff) local higher = bit.rshift(bit.band(metr, 0xffff0000), 16) return "%04X%04X" % {higher, lower} end end return f, m, r
Fix display of v6 Routing metric on Freifunk status pages
Fix display of v6 Routing metric on Freifunk status pages
Lua
apache-2.0
deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci
d05e569fedbeb3343de7d060a0c9cae600056393
gmod_wire_starfall_processor/compiler/parser.lua
gmod_wire_starfall_processor/compiler/parser.lua
/******************************************************************************\ Expression 2 Parser for Garry's Mod Andreas "Syranide" Svensson, me@syranide.com Modified for Starfall By Colonel Thirty Two initrd.gz@gmail.com \******************************************************************************/ AddCSLuaFile("parser.lua") --[[ Not correct - seQuence SeqSPace - "sIF qSP" SeqCOmma - "sIF, qSP" - Statements StmtDeClare - "type var", "type var = sEX" StmtASsign - "var = sEX" StmtEXpr - "eVR" - Expressions ExprPRimitive - strings, numbers, other primitive data types ExprCAll - "var([sEX,...])" ExprVaR - "var" ]] /******************************************************************************/ SF_Parser = {} SF_Parser.__index = SF_Parser function SF_Parser:Process(...) -- instantiate Parser local instance = setmetatable({}, SF_Parser) -- and pcall the new instance's Execute method. return pcall(SF_Parser.Execute, instance, ...) end function SF_Parser:Error(message, token) if token then error(message .. " at line " .. token[4] .. ", char " .. token[5], 0) else error(message .. " at line " .. self.token[4] .. ", char " .. self.token[5], 0) end end function SF_Parser:Execute(tokens, params) self.tokens = tokens self.index = 0 self.count = #tokens PrintTable(tokens) self:NextToken() local tree = self:Root() return tree end /******************************************************************************/ function SF_Parser:GetToken() return self.token end function SF_Parser:GetTokenData() return self.token[2] end function SF_Parser:GetTokenTrace() return {self.token[4], self.token[5]} end function SF_Parser:Instruction(trace, name, ...) return {name, trace, ...} end function SF_Parser:HasTokens() return self.readtoken != nil end function SF_Parser:NextToken() if self.index <= self.count then if self.index > 0 then self.token = self.readtoken else self.token = {"", "", false, 1, 1} end self.index = self.index + 1 self.readtoken = self.tokens[self.index] else self.readtoken = nil end end function SF_Parser:TrackBack() self.index = self.index - 2 self:NextToken() end function SF_Parser:AcceptRoamingToken(name) local token = self.readtoken if not token or token[1] ~= name then return false end self:NextToken() return true end function SF_Parser:AcceptTailingToken(name) local token = self.readtoken if !token or token[3] then return false end return self:AcceptRoamingToken(name) end function SF_Parser:AcceptLeadingToken(name) local token = self.tokens[self.index + 1] if !token or token[3] then return false end return self:AcceptRoamingToken(name) end function SF_Parser:RecurseLeft(func, tbl) local expr = func(self) local hit = true while hit do hit = false for i=1,#tbl do if self:AcceptRoamingToken(tbl[i]) then local trace = self:GetTokenTrace() hit = true expr = self:Instruction(trace, tbl[i], expr, func(self)) break end end end return expr end -- ----------------------------------- -- function SF_Parser:Root() self.loopdepth = 0 local trace = self:GetTokenTrace() local stmts = self:Instruction(trace, "seq") if !self:HasTokens() then Msg("No tokens!\n") return stmts end while true do Msg("Iter\n") if self:AcceptRoamingToken("com") then self:Error("Statement separator (,) must not appear multiple times") end stmts[#stmts + 1] = self:StmtDecl() if !self:HasTokens() then break end if !self:AcceptRoamingToken("com") then if self.readtoken[3] == false then self:Error("Statements must be separated by comma (,) or whitespace") end end end return stmts end function SF_Parser:StmtDecl() if self:AcceptRoamingToken("var") then local trace = self:GetTokenTrace() local typ = self:GetTokenData() if self:AcceptRoamingToken("var") then local var = self:GetTokenData() if not SFLib.types[typ] then self:Error("Unknown type: "..typ, trace) end if self:AcceptRoamingToken("ass") then return self:Instruction(trace, "decl", typ, var, self:StmtExpr()) else return self:Instruction(trace, "decl", typ, var, nil) end else self:TrackBack() end end return SF_Parser:StmtAssign() end function SF_Parser:StmtAssign() if self:AcceptRoamingToken("var") then local trace = self:GetTokenTrace() local var = self:GetTokenData() if self:AcceptRoamingToken("ass") then return self:Instruction(trace, "assign", self:StmtExpr()) else self:TrackBack() end end end function SF_Parser:StmtExpr() return SF_Parser:ExprPrimitive() end -- ----------------------------------- -- function SF_Parser:ExprPrimitive() if self:AcceptRoamingToken("str") then return self:Instruction(self:GetTokenTrace(), "str", self:GetTokenData()) elseif self:AcceptRoamingToken("num") then return self:Instruction(self:GetTokenTrace(), "num", self:GetTokenData()) end return self:ExprVar() end function SF_Parser:ExprCall() local begin = self:ExprCall() if self:AcceptLeadingToken("lpa") then local exprs, tps = {}, {} end end function SF_Parser:ExprVar() if self:AcceptRoamingToken("var") then return self:Instruction(self:GetTokenTrace(), "var", self:GetTokenData()) end return self:ExprError() end function SF_Parser:ExprError() local err if not self:HasTokens() then err = "Further input of code required; incomplete expression" else -- TODO: Put error detection code here end if not err then err = "Unexpected token found: "..self:GetToken()[1] end self:Error(err) end
/******************************************************************************\ Expression 2 Parser for Garry's Mod Andreas "Syranide" Svensson, me@syranide.com Modified for Starfall By Colonel Thirty Two initrd.gz@gmail.com \******************************************************************************/ AddCSLuaFile("parser.lua") --[[ - seQuence SeqSPace - "sIF qSP" SeqCOmma - "sIF, qSP" - Statements StmtDeClare - "type var", "type var = sEX" StmtASsign - "var = sEX" StmtEXpr - "eVR" - Expressions ExprPRimitive - strings, numbers, other primitive data types ExprCAll - "var([sEX,...])" ExprVaR - "var" ]] /******************************************************************************/ SF_Parser = {} SF_Parser.__index = SF_Parser function SF_Parser:Process(...) -- instantiate Parser local instance = setmetatable({}, SF_Parser) -- and pcall the new instance's Execute method. return pcall(SF_Parser.Execute, instance, ...) end function SF_Parser:Error(message, token) if token then error(message .. " at line " .. token[4] .. ", char " .. token[5], 0) else error(message .. " at line " .. self.token[4] .. ", char " .. self.token[5], 0) end end function SF_Parser:Execute(tokens, params) self.tokens = tokens self.index = 0 self.count = #tokens PrintTable(tokens) self:NextToken() local tree = self:Root() return tree end /******************************************************************************/ function SF_Parser:GetToken() return self.token end function SF_Parser:GetTokenData() return self.token[2] end function SF_Parser:GetTokenTrace() return {self.token[4], self.token[5]} end function SF_Parser:Instruction(trace, name, ...) return {name, trace, ...} end function SF_Parser:HasTokens() return self.readtoken != nil end function SF_Parser:NextToken() if self.index <= self.count then Msg("Advancing tokens. Index="..self.index.."... ") if self.index > 0 then Msg("Reading from readtoken\n") self.token = self.readtoken else Msg("Creating fake token\n") self.token = {"", "", false, 1, 1} end self.index = self.index + 1 Msg("New Readtoken: ".. (self.tokens[self.index] or {"nil"})[1] .. ", index = "..self.index.."\n") self.readtoken = self.tokens[self.index] else Msg("No more tokens ("..self.index.."/"..self.count..")\n") self.readtoken = nil end end function SF_Parser:TrackBack() self.index = self.index - 2 self:NextToken() end function SF_Parser:AcceptRoamingToken(name) Msg("Trying to accept token "..name.."...") local token = self.readtoken if not token or token[1] ~= name then Msg(" Failed, token name is "..(token or {"nil"})[1].."\n") return false end Msg(" Accepted.\n") self:NextToken() return true end function SF_Parser:AcceptTailingToken(name) local token = self.readtoken if !token or token[3] then return false end return self:AcceptRoamingToken(name) end function SF_Parser:AcceptLeadingToken(name) local token = self.tokens[self.index + 1] if !token or token[3] then return false end return self:AcceptRoamingToken(name) end function SF_Parser:RecurseLeft(func, tbl) local expr = func(self) local hit = true while hit do hit = false for i=1,#tbl do if self:AcceptRoamingToken(tbl[i]) then local trace = self:GetTokenTrace() hit = true expr = self:Instruction(trace, tbl[i], expr, func(self)) break end end end return expr end -- ----------------------------------- -- function SF_Parser:Root() self.loopdepth = 0 local trace = self:GetTokenTrace() local stmts = self:Instruction(trace, "seq") if !self:HasTokens() then return stmts end local count = 0 while count < 20 do if self:AcceptRoamingToken("com") then self:Error("Statement separator (,) must not appear multiple times") end stmts[#stmts + 1] = self:StmtDecl() if !self:HasTokens() then break end if !self:AcceptRoamingToken("com") then if self.readtoken[3] == false then self:Error("Statements must be separated by comma (,) or whitespace") end end count = count + 1 end if count >= 20 then self:Error("Stupid infinite loop... it's at self:Root()") end return stmts end function SF_Parser:StmtDecl() Msg("--Beginning Declaration statement--\n") if self:AcceptRoamingToken("var") then local trace = self:GetTokenTrace() local typ = self:GetTokenData() if self:AcceptRoamingToken("var") then local var = self:GetTokenData() if not SFLib.types[typ] then self:Error("Unknown type: "..typ, trace) end if self:AcceptRoamingToken("ass") then return self:Instruction(trace, "decl", typ, var, self:StmtExpr()) else return self:Instruction(trace, "decl", typ, var, nil) end else self:TrackBack() end end return self:StmtAssign() end function SF_Parser:StmtAssign() Msg("--Beginning Assignment statement--\n") if self:AcceptRoamingToken("var") then local trace = self:GetTokenTrace() local var = self:GetTokenData() if self:AcceptRoamingToken("ass") then return self:Instruction(trace, "assign", var, self:StmtExpr()) else self:TrackBack() end end return self:StmtExpr() end function SF_Parser:StmtExpr() return self:ExprPrimitive() end -- ----------------------------------- -- function SF_Parser:ExprPrimitive() Msg("--Beginning Primitive expression--\n") if self:AcceptRoamingToken("str") then return self:Instruction(self:GetTokenTrace(), "str", self:GetTokenData()) elseif self:AcceptRoamingToken("num") then return self:Instruction(self:GetTokenTrace(), "num", self:GetTokenData()) end return self:ExprVar() end function SF_Parser:ExprCall() local begin = self:ExprCall() if self:AcceptLeadingToken("lpa") then local exprs, tps = {}, {} end end function SF_Parser:ExprVar() Msg("--Beginning Variable expression--\n") if self:AcceptRoamingToken("var") then return self:Instruction(self:GetTokenTrace(), "var", self:GetTokenData()) end return self:ExprError() end function SF_Parser:ExprError() local err if not self:HasTokens() then err = "Further input of code required; incomplete expression" else -- TODO: Put error detection code here end if err == nil then err = "Unexpected token found: "..self:GetToken()[1] end self:Error(err) end
[Starfall] [parser.lua] Fixed bugs
[Starfall] [parser.lua] Fixed bugs
Lua
bsd-3-clause
Jazzelhawk/Starfall,Ingenious-Gaming/Starfall,Xandaros/Starfall,INPStarfall/Starfall,Jazzelhawk/Starfall,Ingenious-Gaming/Starfall,INPStarfall/Starfall,Xandaros/Starfall
f77317ac254114c1a4379b9696c7532bfd9bade1
utils/kobo_touch_probe.lua
utils/kobo_touch_probe.lua
-- touch probe utility -- usage: ./luajit util/kobo_touch_probe.lua require "defaults" package.path = "common/?.lua;rocks/share/lua/5.1/?.lua;frontend/?.lua;" .. package.path package.cpath = "common/?.so;common/?.dll;/usr/lib/lua/?.so;rocks/lib/lua/5.1/?.so;" .. package.cpath local DocSettings = require("docsettings") local _ = require("gettext") -- read settings and check for language override -- has to be done before requiring other files because -- they might call gettext on load if G_reader_settings == nil then G_reader_settings = DocSettings:open(".reader") end local lang_locale = G_reader_settings:readSetting("language") if lang_locale then _.changeLang(lang_locale) end local InputContainer = require("ui/widget/container/inputcontainer") local CenterContainer = require("ui/widget/container/centercontainer") local FrameContainer = require("ui/widget/container/framecontainer") local RightContainer = require("ui/widget/container/rightcontainer") local OverlapGroup = require("ui/widget/overlapgroup") local ImageWidget = require("ui/widget/imagewidget") local TextWidget = require("ui/widget/textwidget") local GestureRange = require("ui/gesturerange") local UIManager = require("ui/uimanager") local Blitbuffer = require("ffi/blitbuffer") local Geom = require("ui/geometry") local Device = require("device") local Screen = Device.screen local Input = Device.input local Font = require("ui/font") local dbg = require("dbg") --dbg:turnOn() local TouchProbe = InputContainer:new{ curr_probe_step = 1, } function TouchProbe:init() self.ges_events = { TapProbe = { GestureRange:new{ ges = "tap", range = Geom:new{ x = 0, y = 0, w = Screen:getWidth(), h = Screen:getHeight(), }, } }, } self.image_widget = ImageWidget:new{ file = "resources/kobo-touch-probe.png", } local screen_w, screen_h = Screen:getWidth(), Screen:getHeight() local img_w, img_h = self.image_widget:getSize().w, self.image_widget:getSize().h self.probe_steps = { { hint_text = _("Tap the lower right corner"), hint_icon_pos = { x = screen_w-img_w, y = screen_h-img_h, } }, { hint_text = _("Tap the upper right corner"), hint_icon_pos = { x = screen_w-img_w, y = 0, } }, } self.hint_text_widget = TextWidget:new{ text = '', face = Font:getFace("cfont", 30), } self[1] = FrameContainer:new{ bordersize = 0, background = Blitbuffer.COLOR_WHITE, OverlapGroup:new{ dimen = Screen:getSize(), CenterContainer:new{ dimen = Screen:getSize(), self.hint_text_widget, }, self.image_widget, }, } self:updateProbeInstruction() end function TouchProbe:updateProbeInstruction() local probe_step = self.probe_steps[self.curr_probe_step] self.image_widget.overlap_offset = { probe_step.hint_icon_pos.x, probe_step.hint_icon_pos.y, } self.hint_text_widget:setText(probe_step.hint_text) end function TouchProbe:saveSwitchXYSetting(need_to_switch_xy) -- save the settings here so device.input can pick it up G_reader_settings:saveSetting("kobo_touch_switch_xy", need_to_switch_xy) G_reader_settings:flush() UIManager:quit() end function TouchProbe:onTapProbe(arg, ges) if self.curr_probe_step == 1 then local shorter_edge = math.min(Screen:getHeight(), Screen:getWidth()) if math.min(ges.pos.x, ges.pos.y) < shorter_edge/2 then -- x mirrored, x should be close to zero and y should be close to -- screen height local need_to_switch_xy = ges.pos.x > ges.pos.y self:saveSwitchXYSetting(need_to_switch_xy) else -- x not mirroed, need one more probe self.curr_probe_step = 2 self:updateProbeInstruction() UIManager:setDirty(self) end elseif self.curr_probe_step == 2 then -- x not mirrored, y should be close to zero and x should be close -- TouchProbe screen width local need_to_switch_xy = ges.pos.x < ges.pos.y self:saveSwitchXYSetting(need_to_switch_xy) end end return TouchProbe
-- touch probe utility -- usage: ./luajit util/kobo_touch_probe.lua require "defaults" package.path = "common/?.lua;rocks/share/lua/5.1/?.lua;frontend/?.lua;" .. package.path package.cpath = "common/?.so;common/?.dll;/usr/lib/lua/?.so;rocks/lib/lua/5.1/?.so;" .. package.cpath local DocSettings = require("docsettings") local _ = require("gettext") -- read settings and check for language override -- has to be done before requiring other files because -- they might call gettext on load if G_reader_settings == nil then G_reader_settings = DocSettings:open(".reader") end local lang_locale = G_reader_settings:readSetting("language") if lang_locale then _.changeLang(lang_locale) end local InputContainer = require("ui/widget/container/inputcontainer") local CenterContainer = require("ui/widget/container/centercontainer") local FrameContainer = require("ui/widget/container/framecontainer") local RightContainer = require("ui/widget/container/rightcontainer") local OverlapGroup = require("ui/widget/overlapgroup") local ImageWidget = require("ui/widget/imagewidget") local TextWidget = require("ui/widget/textwidget") local GestureRange = require("ui/gesturerange") local UIManager = require("ui/uimanager") local Blitbuffer = require("ffi/blitbuffer") local Geom = require("ui/geometry") local Device = require("device") local Screen = Device.screen local Input = Device.input local Font = require("ui/font") local dbg = require("dbg") --dbg:turnOn() local TouchProbe = InputContainer:new{ curr_probe_step = 1, } function TouchProbe:init() self.ges_events = { TapProbe = { GestureRange:new{ ges = "tap", } }, } self.image_widget = ImageWidget:new{ file = "resources/kobo-touch-probe.png", } local screen_w, screen_h = Screen:getWidth(), Screen:getHeight() local img_w, img_h = self.image_widget:getSize().w, self.image_widget:getSize().h self.probe_steps = { { hint_text = _("Tap the lower right corner"), hint_icon_pos = { x = screen_w-img_w, y = screen_h-img_h, } }, { hint_text = _("Tap the upper right corner"), hint_icon_pos = { x = screen_w-img_w, y = 0, } }, } self.hint_text_widget = TextWidget:new{ text = '', face = Font:getFace("cfont", 30), } self[1] = FrameContainer:new{ bordersize = 0, background = Blitbuffer.COLOR_WHITE, OverlapGroup:new{ dimen = Screen:getSize(), CenterContainer:new{ dimen = Screen:getSize(), self.hint_text_widget, }, self.image_widget, }, } self:updateProbeInstruction() end function TouchProbe:updateProbeInstruction() local probe_step = self.probe_steps[self.curr_probe_step] self.image_widget.overlap_offset = { probe_step.hint_icon_pos.x, probe_step.hint_icon_pos.y, } self.hint_text_widget:setText(probe_step.hint_text) end function TouchProbe:saveSwitchXYSetting(need_to_switch_xy) -- save the settings here so device.input can pick it up G_reader_settings:saveSetting("kobo_touch_switch_xy", need_to_switch_xy) G_reader_settings:flush() UIManager:quit() end function TouchProbe:onTapProbe(arg, ges) if self.curr_probe_step == 1 then local shorter_edge = math.min(Screen:getHeight(), Screen:getWidth()) if math.min(ges.pos.x, ges.pos.y) < shorter_edge/2 then -- x mirrored, x should be close to zero and y should be close to -- screen height local need_to_switch_xy = ges.pos.x > ges.pos.y self:saveSwitchXYSetting(need_to_switch_xy) else -- x not mirroed, need one more probe self.curr_probe_step = 2 self:updateProbeInstruction() UIManager:setDirty(self) end elseif self.curr_probe_step == 2 then -- x not mirrored, y should be close to zero and x should be close -- TouchProbe screen width local need_to_switch_xy = ges.pos.x < ges.pos.y self:saveSwitchXYSetting(need_to_switch_xy) end end return TouchProbe
touch_probe(fix): do not filter probe touch event by range
touch_probe(fix): do not filter probe touch event by range
Lua
agpl-3.0
pazos/koreader,mwoz123/koreader,chihyang/koreader,poire-z/koreader,mihailim/koreader,Hzj-jie/koreader,Frenzie/koreader,robert00s/koreader,frankyifei/koreader,Frenzie/koreader,koreader/koreader,NiLuJe/koreader,NickSavage/koreader,houqp/koreader,apletnev/koreader,Markismus/koreader,poire-z/koreader,lgeek/koreader,NiLuJe/koreader,koreader/koreader
b6458cbe0ce49a87d975dc5e7dde698e16045842
weather-widget/weather.lua
weather-widget/weather.lua
local wibox = require("wibox") local http = require("socket.http") local json = require("json") local naughty = require("naughty") local city = "Montreal,ca" local open_map_key = "<openWeatherMap api key>" local path_to_icons = "/usr/share/icons/Arc/status/symbolic/" local icon_widget = wibox.widget { { id = "icon", resize = false, widget = wibox.widget.imagebox, }, layout = wibox.container.margin(brightness_icon, 0, 0, 3), set_image = function(self, path) self.icon.image = path end, } local temp_widget = wibox.widget{ font = "Play 9", widget = wibox.widget.textbox, } weather_widget = wibox.widget { icon_widget, temp_widget, layout = wibox.layout.fixed.horizontal, } -- helps to map openWeatherMap icons to Arc icons local icon_map = { ["01d"] = "weather-clear-symbolic.svg", ["02d"] = "weather-few-clouds-symbolic.svg", ["03d"] = "weather-clouds-symbolic.svg", ["04d"] = "weather-overcast-symbolic.svg", ["09d"] = "weather-showers-scattered-symbolic.svg", ["10d"] = "weather-showers-symbolic.svg", ["11d"] = "weather-storm-symbolic.svg", ["13d"] = "weather-snow-symbolic.svg", ["50d"] = "weather-fog-symbolic.svg", ["01n"] = "weather-clear-night-symbolic.svg", ["02n"] = "weather-few-clouds-night-symbolic.svg", ["03n"] = "weather-clouds-night-symbolic.svg", ["04n"] = "weather-overcast-symbolic.svg", ["09n"] = "weather-showers-scattered-symbolic.svg", ["10n"] = "weather-showers-symbolic.svg", ["11n"] = "weather-storm-symbolic.svg", ["13n"] = "weather-snow-symbolic.svg", ["50n"] = "weather-fog-symbolic.svg" } -- handy function to convert temperature from Kelvin to Celcius function to_celcius(kelvin) return math.floor(tonumber(kelvin) - 273.15) end local weather_timer = timer({ timeout = 600 }) local resp weather_timer:connect_signal("timeout", function () local resp_json = http.request("http://api.openweathermap.org/data/2.5/weather?q=" .. city .."&appid=" .. open_map_key) resp = json.decode(resp_json) icon_widget.image = path_to_icons .. icon_map[resp.weather[1].icon] temp_widget:set_text(to_celcius(resp.main.temp)) end) weather_timer:emit_signal("timeout") weather_widget:connect_signal("mouse::enter", function() naughty.notify{ icon = path_to_icons .. icon_map[resp.weather[1].icon], icon_size=20, text = '<b>Humidity:</b> ' .. resp.main.humidity .. '%<br><b>Temperature: </b>' .. to_celcius(resp.main.temp), timeout = 5, hover_timeout = 0.5, width = 200, } end)
local wibox = require("wibox") local http = require("socket.http") local json = require("json") local naughty = require("naughty") local city = "Montreal,ca" local open_map_key = "<openWeatherMap api key>" local path_to_icons = "/usr/share/icons/Arc/status/symbolic/" local icon_widget = wibox.widget { { id = "icon", resize = false, widget = wibox.widget.imagebox, }, layout = wibox.container.margin(brightness_icon, 0, 0, 3), set_image = function(self, path) self.icon.image = path end, } local temp_widget = wibox.widget{ font = "Play 9", widget = wibox.widget.textbox, } weather_widget = wibox.widget { icon_widget, temp_widget, layout = wibox.layout.fixed.horizontal, } -- helps to map openWeatherMap icons to Arc icons local icon_map = { ["01d"] = "weather-clear-symbolic.svg", ["02d"] = "weather-few-clouds-symbolic.svg", ["03d"] = "weather-clouds-symbolic.svg", ["04d"] = "weather-overcast-symbolic.svg", ["09d"] = "weather-showers-scattered-symbolic.svg", ["10d"] = "weather-showers-symbolic.svg", ["11d"] = "weather-storm-symbolic.svg", ["13d"] = "weather-snow-symbolic.svg", ["50d"] = "weather-fog-symbolic.svg", ["01n"] = "weather-clear-night-symbolic.svg", ["02n"] = "weather-few-clouds-night-symbolic.svg", ["03n"] = "weather-clouds-night-symbolic.svg", ["04n"] = "weather-overcast-symbolic.svg", ["09n"] = "weather-showers-scattered-symbolic.svg", ["10n"] = "weather-showers-symbolic.svg", ["11n"] = "weather-storm-symbolic.svg", ["13n"] = "weather-snow-symbolic.svg", ["50n"] = "weather-fog-symbolic.svg" } -- handy function to convert temperature from Kelvin to Celcius function to_celcius(kelvin) return math.floor(tonumber(kelvin) - 273.15) end local weather_timer = timer({ timeout = 600 }) local resp weather_timer:connect_signal("timeout", function () local resp_json = http.request("http://api.openweathermap.org/data/2.5/weather?q=" .. city .."&appid=" .. open_map_key) if (resp_json ~= nil) then resp = json.decode(resp_json) icon_widget.image = path_to_icons .. icon_map[resp.weather[1].icon] temp_widget:set_text(to_celcius(resp.main.temp)) end end) weather_timer:emit_signal("timeout") weather_widget:connect_signal("mouse::enter", function() naughty.notify{ icon = path_to_icons .. icon_map[resp.weather[1].icon], icon_size=20, text = '<b>Humidity:</b> ' .. resp.main.humidity .. '%<br><b>Temperature: </b>' .. to_celcius(resp.main.temp), timeout = 5, hover_timeout = 0.5, width = 200, } end)
fix weather widget crash with no internet connection
fix weather widget crash with no internet connection
Lua
mit
streetturtle/AwesomeWM,streetturtle/awesome-wm-widgets,streetturtle/awesome-wm-widgets
1d69218e96489d845b841156a70e81fed4a0c0ac
samples/gtkbuilder.lua
samples/gtkbuilder.lua
#! /usr/bin/env lua -- Note: demo.ui loaded by this example is copied verbatim from gtk3-demo, and -- is probably covered by its appropriate license. -- Import lgi and get Gtk package. local lgi = require 'lgi' local Gtk = lgi.Gtk -- There are two ways to access Gtk.Builder; using standard Gtk API's -- get_object() and get_objects(), or LGI override shortcuts. Both -- can be used, as demonstrated below. local window if gtk_builder_use_standard_api then -- Instantiate Gtk.Builder and load resources from ui file. local builder = Gtk.Builder() assert(builder:add_from_file('demo.ui')) -- Get top-level window from the builder. window = builder:get_object('window1') -- Connect 'Quit' and 'About' actions. builder:get_object('Quit').on_activate = function(action) window:destroy() end builder:get_object('About').on_activate = function(action) local about_dlg = builder:get_object('aboutdialog1') about_dlg:run() about_dlg:hide() end else -- Instantiate builder and load objects. local builder = Gtk.Builder() local ui = assert(builder:add_from_file('demo.ui')).objects -- Get top-level window from the builder. window = ui.window1 -- Connect 'Quit' and 'About' actions. function ui.Quit:on_activate() window:destroy() end function ui.About:on_activate() ui.aboutdialog1:run() ui.aboutdialog1:hide() end end -- Connect 'destroy' signal of the main window, terminates the main loop. window.on_destroy = Gtk.main_quit -- Make sure that main window is visible. window:show_all() -- Start the loop. Gtk.main()
#! /usr/bin/env lua -- Note: demo.ui loaded by this example is copied verbatim from gtk3-demo, and -- is probably covered by its appropriate license. -- Import lgi and get Gtk package. local lgi = require 'lgi' local Gtk = lgi.Gtk -- There are two ways to access Gtk.Builder; using standard Gtk API's -- get_object() and get_objects(), or LGI override shortcuts. Both -- can be used, as demonstrated below. local window if gtk_builder_use_standard_api then -- Instantiate Gtk.Builder and load resources from ui file. local builder = Gtk.Builder() assert(builder:add_from_file('samples/demo.ui')) -- Get top-level window from the builder. window = builder:get_object('window1') -- Connect 'Quit' and 'About' actions. builder:get_object('Quit').on_activate = function(action) window:destroy() end builder:get_object('About').on_activate = function(action) local about_dlg = builder:get_object('aboutdialog1') about_dlg:run() about_dlg:hide() end else -- Instantiate builder and load objects. local builder = Gtk.Builder() assert(builder:add_from_file('samples/demo.ui')) local ui = builder.objects -- Get top-level window from the builder. window = ui.window1 -- Connect 'Quit' and 'About' actions. function ui.Quit:on_activate() window:destroy() end function ui.About:on_activate() ui.aboutdialog1:run() ui.aboutdialog1:hide() end end -- Connect 'destroy' signal of the main window, terminates the main loop. window.on_destroy = Gtk.main_quit -- Make sure that main window is visible. window:show_all() -- Start the loop. Gtk.main()
Fix gtkbuilder sample
Fix gtkbuilder sample Fixes github issue #3.
Lua
mit
zevv/lgi,psychon/lgi,pavouk/lgi
ec9d27052c96550ad2bcba184644c4329cdc4e50
lua-project/src/creator/components/AnimationComponent.lua
lua-project/src/creator/components/AnimationComponent.lua
local cc = cc local DEBUG_VERBOSE = cc.DEBUG_VERBOSE local ccp = cc.p local ccsize = cc.size local ccrect = cc.rect local ComponentBase = cc.import(".ComponentBase") local AnimationComponent = cc.class("cc.Animation", ComponentBase) local _LOOP_NORMAL = 1 local _LOOP_LOOP = 2 AnimationComponent.LOOP_NORMAL = _LOOP_NORMAL AnimationComponent.LOOP_LOOP = _LOOP_LOOP local _animationCache = cc.AnimationCache:getInstance() local function _createAnimation(uuid, assets) local animation = _animationCache:getAnimation(uuid) if animation then return animation end if cc.DEBUG >= DEBUG_VERBOSE then cc.printdebug("[Assets] - [Animation] create animation %s", uuid) end local asset = assets:getAsset(uuid) local sample = asset.sample or 60 local speed = asset.speed or 1 local delay = 1.0 / sample / speed animation = cc.Animation:create() animation:setDelayPerUnit(delay) for _, faval in ipairs(asset["curveData"]["comps"]["cc.Sprite"]["spriteFrame"]) do local frameAsset = assets:getAsset(faval["value"]["__uuid__"]) local spriteFrame = assets:_createObject(frameAsset) animation:addSpriteFrame(spriteFrame) end _animationCache:addAnimation(animation, uuid) animation.loop = _LOOP_NORMAL if asset.wrapMode == 2 then animation.loop = _LOOP_LOOP end return animation end function AnimationComponent:ctor(props, assets) AnimationComponent.super.ctor(self) self.props = props self._animations = {} if not self.props._clips then return end for _, clipaval in ipairs(self.props._clips) do local animation, clip = _createAnimation(clipaval.__uuid__, assets) animation:retain() self._animations[#self._animations + 1] = animation end end function AnimationComponent:start(target) if self.props.playOnLoad then self:play(target) end end function AnimationComponent:play(target, callback) if not target.components or not target.components["cc.Sprite"] then cc.printwarn("[Animation] invalid target %s", target.__type) return end local spriteComponent = target.components["cc.Sprite"] local sprite = spriteComponent.node for _, animation in ipairs(self._animations) do local animate = cc.Animate:create(animation) if animation.loop == _LOOP_LOOP then sprite:runAction(cc.RepeatForever:create(animate)) elseif callback then sprite:runAction(cc.Sequence:create({animate, cc.CallFunc:create(callback)})) else sprite:runAction(animate) end end end function AnimationComponent:onDestroy(target) for _, animation in ipairs(self._animations) do animation:release() end self._animations = nil end return AnimationComponent
local cc = cc local DEBUG_VERBOSE = cc.DEBUG_VERBOSE local ccp = cc.p local ccsize = cc.size local ccrect = cc.rect local ComponentBase = cc.import(".ComponentBase") local AnimationComponent = cc.class("cc.Animation", ComponentBase) local _LOOP_NORMAL = 1 local _LOOP_LOOP = 2 AnimationComponent.LOOP_NORMAL = _LOOP_NORMAL AnimationComponent.LOOP_LOOP = _LOOP_LOOP local _animationCache = cc.AnimationCache:getInstance() local function _createAnimation(uuid, assets) local animation = _animationCache:getAnimation(uuid) if animation then return animation end if cc.DEBUG >= DEBUG_VERBOSE then cc.printdebug("[Assets] - [Animation] create animation %s", uuid) end local asset = assets:getAsset(uuid) local sample = asset.sample or 60 local speed = asset.speed or 1 local delay = 1.0 / sample / speed animation = cc.Animation:create() animation:setDelayPerUnit(delay) if asset["curveData"] and asset["curveData"]["comps"] then for _, faval in ipairs(asset["curveData"]["comps"]["cc.Sprite"]["spriteFrame"]) do local frameAsset = assets:getAsset(faval["value"]["__uuid__"]) local spriteFrame = assets:_createObject(frameAsset) animation:addSpriteFrame(spriteFrame) end end _animationCache:addAnimation(animation, uuid) animation.loop = _LOOP_NORMAL if asset.wrapMode == 2 then animation.loop = _LOOP_LOOP end return animation end function AnimationComponent:ctor(props, assets) AnimationComponent.super.ctor(self) self.props = props self._animations = {} if not self.props._clips then return end for _, clipaval in ipairs(self.props._clips) do local animation, clip = _createAnimation(clipaval.__uuid__, assets) animation:retain() self._animations[#self._animations + 1] = animation end end function AnimationComponent:start(target) if self.props.playOnLoad then self:play(target) end end function AnimationComponent:play(target, callback) if not target.components or not target.components["cc.Sprite"] then cc.printwarn("[Animation] invalid target %s", target.__type) return end local spriteComponent = target.components["cc.Sprite"] local sprite = spriteComponent.node for _, animation in ipairs(self._animations) do local animate = cc.Animate:create(animation) if animation.loop == _LOOP_LOOP then sprite:runAction(cc.RepeatForever:create(animate)) elseif callback then sprite:runAction(cc.Sequence:create({animate, cc.CallFunc:create(callback)})) else sprite:runAction(animate) end end end function AnimationComponent:onDestroy(target) for _, animation in ipairs(self._animations) do animation:release() end self._animations = nil end return AnimationComponent
fix AnimationComponent
fix AnimationComponent
Lua
mit
dualface/creator-lua,dualface/creator-lua,dualface/creator-lua,dualface/creator-lua,dualface/creator-lua
ba84e7431e1b4b2cad599f880ff88ad04414d0f6
plugins/mod_posix.lua
plugins/mod_posix.lua
local want_pposix_version = "0.3.0"; local pposix = assert(require "util.pposix"); if pposix._VERSION ~= want_pposix_version then module:log("warn", "Unknown version (%s) of binary pposix module, expected %s", tostring(pposix._VERSION), want_pposix_version); end local signal = select(2, pcall(require, "util.signal")); if type(signal) == "string" then log("warn", "Couldn't load signal library, won't respond to SIGTERM"); end local config_get = require "core.configmanager".get; local logger_set = require "util.logger".setwriter; module.host = "*"; -- we're a global module local pidfile_written; local function remove_pidfile() if pidfile_written then os.remove(pidfile_written); pidfile_written = nil; end end local function write_pidfile() if pidfile_written then remove_pidfile(); end local pidfile = config.get("*", "core", "pidfile"); if pidfile then local pf, err = io.open(pidfile, "w+"); if not pf then log("error", "Couldn't write pidfile; %s", err); else pf:write(tostring(pposix.getpid())); pf:close(); pidfile_written = pidfile; end end end local syslog_opened function syslog_sink_maker(config) if not syslog_opened then pposix.syslog_open("prosody"); syslog_opened = true; end local syslog, format = pposix.syslog_log, string.format; return function (name, level, message, ...) if ... then syslog(level, format(message, ...)); else syslog(level, message); end end; end require "core.loggingmanager".register_sink_type("syslog", syslog_sink_maker); if not config_get("*", "core", "no_daemonize") then local function daemonize_server() local ok, ret = pposix.daemonize(); if not ok then log("error", "Failed to daemonize: %s", ret); elseif ret and ret > 0 then os.exit(0); else log("info", "Successfully daemonized to PID %d", pposix.getpid()); write_pidfile(); end end module:add_event_hook("server-starting", daemonize_server); else -- Not going to daemonize, so write the pid of this process write_pidfile(); end module:add_event_hook("server-stopped", remove_pidfile); -- Set signal handler if signal.signal then signal.signal("SIGTERM", function () log("warn", "Received SIGTERM..."); unlock_globals(); if prosody_shutdown then prosody_shutdown("Received SIGTERM"); else log("warn", "...no prosody_shutdown(), ignoring."); end lock_globals(); end); end
local want_pposix_version = "0.3.0"; local pposix = assert(require "util.pposix"); if pposix._VERSION ~= want_pposix_version then module:log("warn", "Unknown version (%s) of binary pposix module, expected %s", tostring(pposix._VERSION), want_pposix_version); end local signal = select(2, pcall(require, "util.signal")); if type(signal) == "string" then module:log("warn", "Couldn't load signal library, won't respond to SIGTERM"); end local config_get = require "core.configmanager".get; local logger_set = require "util.logger".setwriter; module.host = "*"; -- we're a global module local pidfile_written; local function remove_pidfile() if pidfile_written then os.remove(pidfile_written); pidfile_written = nil; end end local function write_pidfile() if pidfile_written then remove_pidfile(); end local pidfile = config_get("*", "core", "pidfile"); if pidfile then local pf, err = io.open(pidfile, "w+"); if not pf then module:log("error", "Couldn't write pidfile; %s", err); else pf:write(tostring(pposix.getpid())); pf:close(); pidfile_written = pidfile; end end end local syslog_opened function syslog_sink_maker(config) if not syslog_opened then pposix.syslog_open("prosody"); syslog_opened = true; end local syslog, format = pposix.syslog_log, string.format; return function (name, level, message, ...) if ... then syslog(level, format(message, ...)); else syslog(level, message); end end; end require "core.loggingmanager".register_sink_type("syslog", syslog_sink_maker); if not config_get("*", "core", "no_daemonize") then local function daemonize_server() local ok, ret = pposix.daemonize(); if not ok then module:log("error", "Failed to daemonize: %s", ret); elseif ret and ret > 0 then os.exit(0); else module:log("info", "Successfully daemonized to PID %d", pposix.getpid()); write_pidfile(); end end module:add_event_hook("server-starting", daemonize_server); else -- Not going to daemonize, so write the pid of this process write_pidfile(); end module:add_event_hook("server-stopped", remove_pidfile); -- Set signal handler if signal.signal then signal.signal("SIGTERM", function () module:log("warn", "Received SIGTERM..."); _G.unlock_globals(); if _G.prosody_shutdown then _G.prosody_shutdown("Received SIGTERM"); else module:log("warn", "...no prosody_shutdown(), ignoring."); end _G.lock_globals(); end); end
mod_posix: Fix calls to log() (replace with module:log) and make some global accesses explicit
mod_posix: Fix calls to log() (replace with module:log) and make some global accesses explicit
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
97f230499f0222da368f9f730a5e3f1d6c541d82
murphy/murphy-ivi.lua
murphy/murphy-ivi.lua
zone { name = "driver" } zone { name = "passanger1" } zone { name = "passanger2" } zone { name = "passanger3" } zone { name = "passanger4" } routing_group { name = "default_driver", node_type = node.output, accept = function(self, n) return (n.type ~= node.bluetooth_carkit and n.type ~= node.hdmi) end, compare = builtin.method.compare_default } routing_group { name = "default_passanger1", node_type = node.output, accept = function(self, n) return (n.type == node.hdmi or n.name == 'Silent') end, compare = builtin.method.compare_default } routing_group { name = "phone", node_type = node.input, accept = builtin.method.accept_phone, compare = builtin.method.compare_phone } routing_group { name = "phone", node_type = node.output, accept = builtin.method.accept_phone, compare = builtin.method.compare_phone } application_class { class = "event", node_type = node.event, priority = 6, route = { output = { driver = routing_group.default_driver_output } }, roles = { event = no_resource, speech = no_resource } } application_class { class = "phone", node_type = node.phone, priority = 5, route = { input = { driver = routing_group.phone_input }, output = {driver = routing_group.phone_output } }, roles = { phone = no_resource, carkit = no_resource } } application_class { node_type = node.alert, priority = 4, route = { output = { driver = routing_group.default_driver_output }, }, roles = { ringtone = no_resource, alarm = no_resource } } application_class { class = "navigator", node_type = node.navigator, priority = 3, route = { output = { driver = routing_group.default_driver_output, passanger1 = routing_group.default_passanger1_output } }, roles = { navigator = {0, "autorelease", "mandatory", "shared"} }, binaries = { ['net.zmap.navi'] = { 0, "autorelease", "mandatory", "shared" } } } application_class { class = "game", node_type = node.game, priority = 2, route = { output = { driver = routing_group.default_driver_output, passanger1 = routing_group.default_passanger1_output } }, roles = { game = {0, "mandatory", "exclusive"} } } application_class { class = "player", node_type = node.radio, priority = 1, route = { output = { driver = routing_group.default_driver_output } }, roles = { radio = {1, "mandatory", "exclusive"} }, } application_class { class = "player", node_type = node.player, priority = 1, route = { output = { driver = routing_group.default_driver_output, passanger1 = routing_group.default_passanger1_output } }, roles = { music = {0, "mandatory", "exclusive"}, video = {0, "mandatory", "exclusive"}, test = {0, "mandatory", "exclusive"}, bt_music = no_resource, player = no_resource }, binaries = { ['t8j6HTRpuz.MediaPlayer'] = "music" } } application_class { class = "player", node_type = node.browser, priority = 1, route = { output = { driver = routing_group.default_driver_output, passanger1 = routing_group.default_passanger1_output } }, roles = { browser = {0, "mandatory", "shared"} } } audio_resource { name = { recording = "audio_recording", playback = "audio_playback" }, attributes = { role = {"media.role", mdb.string, "music"}, pid = {"application.process.id", mdb.string, "<unknown>"}, name = {"resource.set.name", mdb.string, "<unknown>"}, appid = {"resource.set.appid", mdb.string, "<unknown>"} } } mdb.import { table = "speedvol", columns = {"value"}, condition = "zone = 'driver' AND device = 'speaker'", maxrow = 1, update = builtin.method.make_volumes } mdb.import { table = "audio_playback_owner", columns = {"zone_id", "application_class", "role"}, condition = "zone_name = 'driver'", maxrow = 1, update = function(self) zid = self[1].zone_id if (zid == nil) then zid = "<nil>" end class = self[1].application_class if (class == nil) then class = "<nil>" end role = self[1].role if (role == nil) then role = "<nil>" end -- print("*** import "..self.table.." update: zone:"..zid.." class:"..class.." role:"..role) end } mdb.import { table = "amb_gear_position", columns = { "value" }, condition = "key = 'GearPosition'", maxrow = 1, update = builtin.method.make_volumes } mdb.import { table = "volume_context", columns = {"value"}, condition = "id = 1", maxrow = 1, update = builtin.method.change_volume_context } volume_limit { name = "speed_adjust", type = volume_limit.generic, limit = mdb.import.speedvol:link(1,"value"), calculate = builtin.method.volume_correct } volume_limit { name = "phone_suppress", type = volume_limit.class, limit = -20, node_type = { node.phone }, calculate = builtin.method.volume_supress } volume_limit { name = "navi_suppress", type = volume_limit.class, limit = -20, node_type = { node.navigator, node.phone }, calculate = builtin.method.volume_supress } volume_limit { name = "navi_maxlim", type = volume_limit.maximum, limit = -10, node_type = { node.navigator } } volume_limit { name = "player_maxlim", type = volume_limit.maximum, limit = -20, node_type = { node.player } } volume_limit { name = "video", type = volume_limit.class, limit = -90, node_type = { node.player, node.game }, calculate = function(self, class, device, mask) -- print("*** limit "..self.name.." class:"..class.." stream:"..device.name) position = mdb.import.amb_gear_position[1].value if (position and position == 128) then return self.limit end return 0 end }
zone { name = "driver" } zone { name = "passanger1" } zone { name = "passanger2" } zone { name = "passanger3" } zone { name = "passanger4" } routing_group { name = "default_driver", node_type = node.output, accept = function(self, n) return (n.type ~= node.bluetooth_carkit and n.type ~= node.hdmi) end, compare = builtin.method.compare_default } routing_group { name = "default_passanger1", node_type = node.output, accept = function(self, n) return (n.type == node.hdmi or n.name == 'Silent') end, compare = builtin.method.compare_default } routing_group { name = "phone", node_type = node.input, accept = builtin.method.accept_phone, compare = builtin.method.compare_phone } routing_group { name = "phone", node_type = node.output, accept = builtin.method.accept_phone, compare = builtin.method.compare_phone } application_class { class = "event", node_type = node.event, priority = 6, route = { output = { driver = routing_group.default_driver_output } }, roles = { event = no_resource } } application_class { class = "phone", node_type = node.phone, priority = 5, route = { input = { driver = routing_group.phone_input }, output = {driver = routing_group.phone_output } }, roles = { phone = no_resource, carkit = no_resource } } application_class { node_type = node.alert, priority = 4, route = { output = { driver = routing_group.default_driver_output }, }, roles = { ringtone = no_resource, alarm = no_resource } } application_class { class = "navigator", node_type = node.navigator, priority = 3, route = { output = { driver = routing_group.default_driver_output, passanger1 = routing_group.default_passanger1_output } }, roles = { navigator = {0, "autorelease", "mandatory", "shared"}, speech = no_resource }, binaries = { ['net.zmap.navi'] = { 0, "autorelease", "mandatory", "shared" } } } application_class { class = "game", node_type = node.game, priority = 2, route = { output = { driver = routing_group.default_driver_output, passanger1 = routing_group.default_passanger1_output } }, roles = { game = {0, "mandatory", "exclusive"} } } application_class { class = "player", node_type = node.radio, priority = 1, route = { output = { driver = routing_group.default_driver_output } }, roles = { radio = {1, "mandatory", "exclusive"} }, } application_class { class = "player", node_type = node.player, priority = 1, route = { output = { driver = routing_group.default_driver_output, passanger1 = routing_group.default_passanger1_output } }, roles = { music = {0, "mandatory", "exclusive"}, video = {0, "mandatory", "exclusive"}, test = {0, "mandatory", "exclusive"}, bt_music = no_resource, player = no_resource }, binaries = { ['t8j6HTRpuz.MediaPlayer'] = "music" } } application_class { class = "player", node_type = node.browser, priority = 1, route = { output = { driver = routing_group.default_driver_output, passanger1 = routing_group.default_passanger1_output } }, roles = { browser = {0, "mandatory", "shared"} } } audio_resource { name = { recording = "audio_recording", playback = "audio_playback" }, attributes = { role = {"media.role", mdb.string, "music"}, pid = {"application.process.id", mdb.string, "<unknown>"}, name = {"resource.set.name", mdb.string, "<unknown>"}, appid = {"resource.set.appid", mdb.string, "<unknown>"} } } mdb.import { table = "speedvol", columns = {"value"}, condition = "zone = 'driver' AND device = 'speaker'", maxrow = 1, update = builtin.method.make_volumes } mdb.import { table = "audio_playback_owner", columns = {"zone_id", "application_class", "role"}, condition = "zone_name = 'driver'", maxrow = 1, update = function(self) zid = self[1].zone_id if (zid == nil) then zid = "<nil>" end class = self[1].application_class if (class == nil) then class = "<nil>" end role = self[1].role if (role == nil) then role = "<nil>" end -- print("*** import "..self.table.." update: zone:"..zid.." class:"..class.." role:"..role) end } mdb.import { table = "amb_gear_position", columns = { "value" }, condition = "key = 'GearPosition'", maxrow = 1, update = builtin.method.make_volumes } mdb.import { table = "volume_context", columns = {"value"}, condition = "id = 1", maxrow = 1, update = builtin.method.change_volume_context } volume_limit { name = "speed_adjust", type = volume_limit.generic, limit = mdb.import.speedvol:link(1,"value"), calculate = builtin.method.volume_correct } volume_limit { name = "phone_suppress", type = volume_limit.class, limit = -20, node_type = { node.phone }, calculate = builtin.method.volume_supress } volume_limit { name = "navi_suppress", type = volume_limit.class, limit = -20, node_type = { node.navigator, node.phone }, calculate = builtin.method.volume_supress } volume_limit { name = "navi_maxlim", type = volume_limit.maximum, limit = -10, node_type = { node.navigator } } volume_limit { name = "player_maxlim", type = volume_limit.maximum, limit = -20, node_type = { node.player } } volume_limit { name = "video", type = volume_limit.class, limit = -90, node_type = { node.player, node.game }, calculate = function(self, class, device, mask) -- print("*** limit "..self.name.." class:"..class.." stream:"..device.name) position = mdb.import.amb_gear_position[1].value if (position and position == 128) then return self.limit end return 0 end }
Make temporary fix for Modello navigator.
Make temporary fix for Modello navigator. Take into account that this fix will make all synthetic speech coming from TTS behaving like it would come from navigator. That means that it is attenuating the underlying music stream and mixing with it. This might actually work for most TTS cases, but not for all. Eventually this has to be fixed in Winthorpe and xwalk TTS plugin. Change-Id: Ie0ee1c7efa99a757a0cbb8002e1fae627ff535ca
Lua
lgpl-2.1
otcshare/pulseaudio-module-murphy-ivi,otcshare/pulseaudio-module-murphy-ivi,otcshare/pulseaudio-module-murphy-ivi,otcshare/pulseaudio-module-murphy-ivi
5510bdabaecfd1bd5d5e7f2b0ffb8114ae3a2dd2
scripts/run_tests.lua
scripts/run_tests.lua
#!/usr/bin/env lua5.1 -- Weee local SCRIPTS_PATH = string.sub(arg[0], 1, -15) dofile(SCRIPTS_PATH .. "/common.lua") require("lfs") local prev_wd = lfs.currentdir() lfs.chdir(SCRIPTS_PATH .. "/..") local ROOT = lfs.currentdir() local group_data = {} group_data["core"] = { excluded = {}, args = {}, } group_data["lua"] = { excluded = {}, args = {}, } local group_names = quanta_libs() local groups = {} table.insert(group_names, "lua") for _, group_name in pairs(group_names) do local root = "lib/" .. group_name .. "/test" local group = { name = group_name, root = ROOT .. "/" .. root, data = group_data[group_name], tests = {}, } for file in iterate_dir(root, "file") do local name, ext = split_path(file) if ext == "elf" or (group_name == "lua" and ext == "lua") then if group.data.excluded[name] then printf("EXCLUDED: %s / %s", group_name, name) else table.insert(group.tests, file) end end end table.insert(groups, group) end function run() for _, group in pairs(groups) do printf("\nGROUP: %s", group.name) lfs.chdir(group.root) for _, path in pairs(group.tests) do local _, ext = split_path(path) local cmd = "./" .. path if ext == "lua" then cmd = "LUA_PATH=\"../src/?.lua;;\" ../../../build/bin/script_host.elf run " .. cmd end local args = group.data.args[path] if args then cmd = cmd .. " " .. args end printf("\nRUNNING: %s", cmd) local exit_code = os.execute(cmd) if exit_code ~= 0 then printf("ERROR: '%s' failed with exit code %d", path, exit_code) return -1 end end end return 0 end local ec = run() lfs.chdir(prev_wd) os.exit(ec)
#!/usr/bin/env lua5.1 -- Weee local SCRIPTS_PATH = string.sub(arg[0], 1, -15) dofile(SCRIPTS_PATH .. "/common.lua") require("lfs") local prev_wd = lfs.currentdir() lfs.chdir(SCRIPTS_PATH .. "/..") local ROOT = lfs.currentdir() local group_data = {} group_data["core"] = { excluded = {}, args = {}, } group_data["lua"] = { excluded = {}, args = {}, } local group_names = quanta_libs() local groups = {} table.insert(group_names, "lua") for _, group_name in pairs(group_names) do local root = "lib/" .. group_name .. "/test" local group = { name = group_name, root = ROOT .. "/" .. root, data = group_data[group_name], tests = {}, } for file in iterate_dir(root, "file") do local name, ext = split_path(file) if ext == "elf" or (group_name == "lua" and ext == "lua") then if group.data.excluded[name] then printf("EXCLUDED: %s / %s", group_name, name) else table.insert(group.tests, {name = name, path = file, ext = ext}) end end end table.insert(groups, group) end function run() for _, group in pairs(groups) do printf("\nGROUP: %s", group.name) lfs.chdir(group.root) for _, test in pairs(group.tests) do local cmd = "./" .. test.path if test.ext == "lua" then cmd = "LUA_PATH=\"../src/?.lua;;\" ../../../build/bin/script_host.elf run " .. cmd end local args = group.data.args[test.name] if args then cmd = cmd .. " " .. args end printf("\nRUNNING: %s", cmd) local exit_code = os.execute(cmd) if exit_code ~= 0 then printf("ERROR: '%s' failed with exit code %d", test.path, exit_code) return -1 end end end return 0 end local ec = run() lfs.chdir(prev_wd) os.exit(ec)
scripts/run_tests.lua: fixed text args lookup; tidy.
scripts/run_tests.lua: fixed text args lookup; tidy.
Lua
mit
komiga/quanta,komiga/quanta,komiga/quanta
5352e3b35483530877b3312d8c9b358aa910bc4b
third_party/gflags.lua
third_party/gflags.lua
group("third_party") project("gflags") uuid("e319da87-75ed-4517-8f65-bd25e9cc02a3") kind("StaticLib") language("C++") links({ }) defines({ "PATH_SEPARATOR=%%27\\\\%%27", "GFLAGS_DLL_DECL=", "GFLAGS_DLL_DEFINE_FLAG=", "GFLAGS_DLL_DECLARE_FLAG=", "_LIB", }) includedirs({ "gflags/src/windows", "gflags/src", }) files({ "gflags/src/gflags.cc", "gflags/src/gflags_completions.cc", "gflags/src/gflags_reporting.cc", "gflags/src/mutex.h", "gflags/src/util.h", "gflags/src/windows/config.h", "gflags/src/windows/gflags/gflags.h", "gflags/src/windows/gflags/gflags_completions.h", "gflags/src/windows/gflags/gflags_declare.h", "gflags/src/windows/port.cc", "gflags/src/windows/port.h", })
group("third_party") project("gflags") uuid("e319da87-75ed-4517-8f65-bd25e9cc02a3") kind("StaticLib") language("C++") links({ }) defines({ "GFLAGS_DLL_DECL=", "GFLAGS_DLL_DEFINE_FLAG=", "GFLAGS_DLL_DECLARE_FLAG=", "_LIB", }) includedirs({ "gflags/src", }) files({ "gflags/src/gflags.cc", "gflags/src/gflags_completions.cc", "gflags/src/gflags_reporting.cc", "gflags/src/mutex.h", "gflags/src/util.h", }) filter("platforms:Windows") defines({ "PATH_SEPARATOR=%%27\\\\%%27", }) includedirs({ "gflags/src/windows", }) files({ "gflags/src/windows/config.h", "gflags/src/windows/gflags/gflags.h", "gflags/src/windows/gflags/gflags_completions.h", "gflags/src/windows/gflags/gflags_declare.h", "gflags/src/windows/port.cc", "gflags/src/windows/port.h", })
Fixing gflags linux build.
Fixing gflags linux build.
Lua
bsd-3-clause
xenia-project/build-tools,xenia-project/build-tools
27138a649892fe30e90246c3fad9cef0132e36f1
modules/admin-full/luasrc/model/cbi/admin_network/dhcp.lua
modules/admin-full/luasrc/model/cbi/admin_network/dhcp.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.model.uci") require("luci.sys") m = Map("dhcp", "DHCP") s = m:section(TypedSection, "dhcp", "") s.addremove = true s.anonymous = true iface = s:option(ListValue, "interface", translate("interface")) luci.model.uci.foreach("network", "interface", function (section) if section[".name"] ~= "loopback" then iface:value(section[".name"]) s:depends("interface", section[".name"]) end end) s:option(Value, "start", translate("start")).rmempty = true s:option(Value, "limit", translate("limit")).rmempty = true s:option(Value, "leasetime").rmempty = true s:option(Flag, "dynamicdhcp").rmempty = true s:option(Value, "name", translate("name")).optional = true s:option(Flag, "ignore").optional = true s:option(Value, "netmask", translate("netmask")).optional = true s:option(Flag, "force").optional = true for i, line in pairs(luci.sys.execl("dnsmasq --help dhcp")) do k, v = line:match("([^ ]+) +([^ ]+)") s:option(Value, "dhcp"..k, v).optional = true end m2 = Map("luci_ethers", translate("luci_ethers")) s = m2:section(TypedSection, "static_lease", "") s.addremove = true s.anonymous = true s.template = "cbi/tblsection" s:option(Value, "macaddr", translate("macaddress")) s:option(Value, "ipaddr", translate("ipaddress")) return m, m2
--[[ 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.model.uci") require("luci.sys") m = Map("dhcp", "DHCP") s = m:section(TypedSection, "dhcp", "") s.addremove = true s.anonymous = true iface = s:option(ListValue, "interface", translate("interface")) luci.model.uci.foreach("network", "interface", function (section) if section[".name"] ~= "loopback" then iface.default = iface.default or section[".name"] iface:value(section[".name"]) s:depends("interface", section[".name"]) end end) s:option(Value, "start", translate("start")).rmempty = true s:option(Value, "limit", translate("limit")).rmempty = true s:option(Value, "leasetime").rmempty = true s:option(Flag, "dynamicdhcp").rmempty = true s:option(Value, "name", translate("name")).optional = true s:option(Flag, "ignore").optional = true s:option(Value, "netmask", translate("netmask")).optional = true s:option(Flag, "force").optional = true for i, line in pairs(luci.sys.execl("dnsmasq --help dhcp")) do k, v = line:match("([^ ]+) +([^ ]+)") s:option(Value, "dhcp"..k, v).optional = true end m2 = Map("luci_ethers", translate("luci_ethers")) s = m2:section(TypedSection, "static_lease", "") s.addremove = true s.anonymous = true s.template = "cbi/tblsection" s:option(Value, "macaddr", translate("macaddress")) s:option(Value, "ipaddr", translate("ipaddress")) return m, m2
* luci/admin-full: fixed bug that prevented creation of interface sections in dhcp page
* luci/admin-full: fixed bug that prevented creation of interface sections in dhcp page git-svn-id: edf5ee79c2c7d29460bbb5b398f55862cc26620d@2711 ab181a69-ba2e-0410-a84d-ff88ab4c47bc
Lua
apache-2.0
stephank/luci,8devices/carambola2-luci,projectbismark/luci-bismark,gwlim/luci,projectbismark/luci-bismark,yeewang/openwrt-luci,ReclaimYourPrivacy/cloak-luci,gwlim/luci,alxhh/piratenluci,Canaan-Creative/luci,yeewang/openwrt-luci,freifunk-gluon/luci,ch3n2k/luci,freifunk-gluon/luci,projectbismark/luci-bismark,vhpham80/luci,jschmidlapp/luci,zwhfly/openwrt-luci,Canaan-Creative/luci,8devices/carambola2-luci,ch3n2k/luci,jschmidlapp/luci,saraedum/luci-packages-old,Canaan-Creative/luci,jschmidlapp/luci,phi-psi/luci,projectbismark/luci-bismark,ThingMesh/openwrt-luci,freifunk-gluon/luci,yeewang/openwrt-luci,stephank/luci,Flexibity/luci,freifunk-gluon/luci,zwhfly/openwrt-luci,Flexibity/luci,zwhfly/openwrt-luci,zwhfly/openwrt-luci,stephank/luci,phi-psi/luci,Flexibity/luci,alxhh/piratenluci,8devices/carambola2-luci,ch3n2k/luci,vhpham80/luci,eugenesan/openwrt-luci,8devices/carambola2-luci,alxhh/piratenluci,Flexibity/luci,yeewang/openwrt-luci,dtaht/cerowrt-luci-3.3,ReclaimYourPrivacy/cloak-luci,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,jschmidlapp/luci,vhpham80/luci,ThingMesh/openwrt-luci,alxhh/piratenluci,alxhh/piratenluci,yeewang/openwrt-luci,phi-psi/luci,stephank/luci,saraedum/luci-packages-old,zwhfly/openwrt-luci,jschmidlapp/luci,phi-psi/luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,ThingMesh/openwrt-luci,saraedum/luci-packages-old,ThingMesh/openwrt-luci,eugenesan/openwrt-luci,ch3n2k/luci,Canaan-Creative/luci,vhpham80/luci,dtaht/cerowrt-luci-3.3,8devices/carambola2-luci,zwhfly/openwrt-luci,dtaht/cerowrt-luci-3.3,vhpham80/luci,phi-psi/luci,freifunk-gluon/luci,zwhfly/openwrt-luci,eugenesan/openwrt-luci,yeewang/openwrt-luci,Flexibity/luci,alxhh/piratenluci,ReclaimYourPrivacy/cloak-luci,vhpham80/luci,dtaht/cerowrt-luci-3.3,gwlim/luci,phi-psi/luci,ReclaimYourPrivacy/cloak-luci,yeewang/openwrt-luci,8devices/carambola2-luci,ch3n2k/luci,zwhfly/openwrt-luci,phi-psi/luci,saraedum/luci-packages-old,eugenesan/openwrt-luci,8devices/carambola2-luci,Canaan-Creative/luci,ThingMesh/openwrt-luci,jschmidlapp/luci,ThingMesh/openwrt-luci,ReclaimYourPrivacy/cloak-luci,eugenesan/openwrt-luci,ReclaimYourPrivacy/cloak-luci,zwhfly/openwrt-luci,gwlim/luci,projectbismark/luci-bismark,stephank/luci,eugenesan/openwrt-luci,freifunk-gluon/luci,gwlim/luci,ReclaimYourPrivacy/cloak-luci,Canaan-Creative/luci,saraedum/luci-packages-old,Canaan-Creative/luci,ch3n2k/luci,Flexibity/luci,alxhh/piratenluci,freifunk-gluon/luci,stephank/luci,jschmidlapp/luci,projectbismark/luci-bismark,projectbismark/luci-bismark,Flexibity/luci,gwlim/luci,dtaht/cerowrt-luci-3.3,dtaht/cerowrt-luci-3.3,jschmidlapp/luci,ch3n2k/luci,gwlim/luci,projectbismark/luci-bismark,saraedum/luci-packages-old,Flexibity/luci,Canaan-Creative/luci,freifunk-gluon/luci
85fdffad70c41332fcb2c5eaf23b8ad62fda097a
conditions/Casting.lua
conditions/Casting.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 OvaleData = Ovale.OvaleData local OvaleSpellBook = Ovale.OvaleSpellBook local OvaleState = Ovale.OvaleState local pairs = pairs local type = type local API_IsHarmfulSpell = IsHarmfulSpell local API_IsHelpfulSpell = IsHelpfulSpell local API_UnitCastingInfo = UnitCastingInfo local API_UnitChannelInfo = UnitChannelInfo local ParseCondition = OvaleCondition.ParseCondition local state = OvaleState.state --- Test if the target is casting the given spell. -- The spell may be specified either by spell ID, spell list name (as defined in SpellList), -- "harmful" for any harmful spell, or "helpful" for any helpful spell. -- @name Casting -- @paramsig boolean -- @param spell The spell to check. -- Valid values: spell ID, spell list name, harmful, helpful -- @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 A boolean value. -- @usage -- Define(maloriak_release_aberrations 77569) -- if target.Casting(maloriak_release_aberrations) -- Spell(pummel) local function Casting(condition) local spellId = condition[1] local target = ParseCondition(condition) -- Get the information about the current spellcast. local start, ending, castSpellId, castSpellName if target == "player" then start = state.startCast ending = state.endCast castSpellId = state.currentSpellId castSpellName = OvaleSpellBook:GetSpellName(castSpellId) else local spellName, _, _, _, startTime, endTime = UnitCastingInfo(target) if not spellName then spellName, _, _, _, startTime, endTime = UnitChannelInfo("unit") end if spellName then castSpellName = spellName start = startTime/1000 ending = endTime/1000 end end local isCasting = false if castSpellId or castSpellName then if not spellId then -- No spell specified, so whatever spell is currently casting. isCasting = true elseif OvaleData.buffSpellList[spellId] then for id in pairs(OvaleData.buffSpellList[spellId]) do if id == castSpellId or OvaleSpellBook:GetSpellName(id) == castSpellName then isCasting = true break end end elseif spellId == "harmful" and API_IsHarmfulSpell(castSpellName) then isCasting = true elseif spellId == "helpful" and API_IsHelpfulSpell(castSpellName) then isCasting = true end end return isCasting end OvaleCondition:RegisterCondition("casting", false, casting) 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 OvaleData = Ovale.OvaleData local OvaleSpellBook = Ovale.OvaleSpellBook local OvaleState = Ovale.OvaleState local pairs = pairs local type = type local API_IsHarmfulSpell = IsHarmfulSpell local API_IsHelpfulSpell = IsHelpfulSpell local API_UnitCastingInfo = UnitCastingInfo local API_UnitChannelInfo = UnitChannelInfo local ParseCondition = OvaleCondition.ParseCondition local state = OvaleState.state --- Test if the target is casting the given spell. -- The spell may be specified either by spell ID, spell list name (as defined in SpellList), -- "harmful" for any harmful spell, or "helpful" for any helpful spell. -- @name Casting -- @paramsig boolean -- @param spell The spell to check. -- Valid values: spell ID, spell list name, harmful, helpful -- @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 A boolean value. -- @usage -- Define(maloriak_release_aberrations 77569) -- if target.Casting(maloriak_release_aberrations) -- Spell(pummel) local function Casting(condition) local spellId = condition[1] local target = ParseCondition(condition) -- Get the information about the current spellcast. local start, ending, castSpellId, castSpellName if target == "player" then start = state.startCast ending = state.endCast castSpellId = state.currentSpellId castSpellName = OvaleSpellBook:GetSpellName(castSpellId) else local spellName, _, _, _, startTime, endTime = UnitCastingInfo(target) if not spellName then spellName, _, _, _, startTime, endTime = UnitChannelInfo("unit") end if spellName then castSpellName = spellName start = startTime/1000 ending = endTime/1000 end end if castSpellId or castSpellName then if not spellId then -- No spell specified, so whatever spell is currently casting. return start, ending elseif OvaleData.buffSpellList[spellId] then for id in pairs(OvaleData.buffSpellList[spellId]) do if id == castSpellId or OvaleSpellBook:GetSpellName(id) == castSpellName then return start, ending end end elseif spellId == "harmful" and API_IsHarmfulSpell(castSpellName) then return start, ending elseif spellId == "helpful" and API_IsHelpfulSpell(castSpellName) then return start, ending end end return nil end OvaleCondition:RegisterCondition("casting", false, Casting) end
Fix Casting() which returned the wrong value for boolean condition.
Fix Casting() which returned the wrong value for boolean condition. In Ovale, proper boolean conditions return time spans that either contain (true) or do not contain (false) the current time. git-svn-id: b2bb544abab4b09d60f88077ac82407cb244c9c9@1498 d5049fe3-3747-40f7-a4b5-f36d6801af5f
Lua
mit
ultijlam/ovale,eXhausted/Ovale,ultijlam/ovale,eXhausted/Ovale,ultijlam/ovale,eXhausted/Ovale,Xeltor/ovale
caf6732d48273335fa79e480136179d4d4075ba6
monster/mon_29_animals.lua
monster/mon_29_animals.lua
require("monster.base.drop") require("monster.base.lookat") require("monster.base.quests") require("base.messages"); module("monster.mon_29_animals", package.seeall) function ini(Monster) init=true; monster.base.quests.iniQuests(); killer={}; --A list that keeps track of who attacked the monster last end function onSpawn(thisPig) if thisPig:getMonsterType()==241 then if thisPig:getMonsterType()==251 then if thisPig:getMonsterType()==252 then if thisPig:getMonsterType()==253 then var=60; red,green,blue=thisPig:getSkinColor(); red=math.min(255,red-var+math.random(2*var)); green=math.min(255,green-var+math.random(2*var)); blue=math.min(255,blue-var+math.random(2*var)); thisPig:setSkinColor(red,green,blue); end end end end function enemyNear(Monster,Enemy) if init==nil then ini(Monster); end return false end function enemyOnSight(Monster,Enemy) if init==nil then ini(Monster); end if monster.base.drop.DefaultSlowdown( Monster ) then return true else return false end end function onAttacked(Monster,Enemy) if init==nil then ini(Monster); end monster.base.kills.setLastAttacker(Monster,Enemy) killer[Monster.id]=Enemy.id; --Keeps track who attacked the monster last end function onCasted(Monster,Enemy) if init==nil then ini(Monster); end monster.base.kills.setLastAttacker(Monster,Enemy) killer[Monster.id]=Enemy.id; --Keeps track who attacked the monster last end function onDeath(Monster) if killer[Monster.id] ~= nil then murderer=getCharForId(killer[Monster.id]); if murderer then --Checking for quests monster.base.quests.checkQuest(murderer,Monster); killer[Monster.id]=nil; murderer=nil; end end monster.base.drop.ClearDropping(); local MonID=Monster:getMonsterType(); if (MonID==181) then --sheep monster.base.drop.AddDropItem(63,1,50,333,0,1); --inners monster.base.drop.AddDropItem(170,10,50,333,0,2); --wool monster.base.drop.AddDropItem(2934,1,100,333,0,3); --lamb meat elseif (MonID==293) then --cow monster.base.drop.AddDropItem(69,1,50,333,0,1); --leather monster.base.drop.AddDropItem(333,1,50,333,0,2); --horn monster.base.drop.AddDropItem(2940,1,100,333,0,3); --steak elseif (MonID==241 or MonID==251 or MonID==252 or MonID==253) then --pig monster.base.drop.AddDropItem(69,1,50,333,0,1); --leather monster.base.drop.AddDropItem(63,1,50,333,0,2); --entrails monster.base.drop.AddDropItem(307,1,100,333,0,3); --pork elseif (MonID==294) then --deer monster.base.drop.AddDropItem(63,1,50,333,0,1); --inners monster.base.drop.AddDropItem(552,1,100,333,0,2); --deer meat elseif (MonID==295) then --bunny monster.base.drop.AddDropItem(63,1,50,333,0,1); --inners monster.base.drop.AddDropItem(553,1,100,333,0,2); --rabbit meat end monster.base.drop.Dropping(Monster); end
require("monster.base.drop") require("monster.base.lookat") require("monster.base.quests") require("base.messages"); module("monster.mon_29_animals", package.seeall) function ini(Monster) init=true; monster.base.quests.iniQuests(); killer={}; --A list that keeps track of who attacked the monster last end function onSpawn(thisPig) if thisPig:getMonsterType()==241 or thisPig:getMonsterType()==251 or thisPig:getMonsterType()==252 or thisPig:getMonsterType()==253 then var=60; red,green,blue=thisPig:getSkinColor(); red=math.min(255,red-var+math.random(2*var)); green=math.min(255,green-var+math.random(2*var)); blue=math.min(255,blue-var+math.random(2*var)); thisPig:setSkinColor(red,green,blue); end end function enemyNear(Monster,Enemy) if init==nil then ini(Monster); end return false end function enemyOnSight(Monster,Enemy) if init==nil then ini(Monster); end if monster.base.drop.DefaultSlowdown( Monster ) then return true else return false end end function onAttacked(Monster,Enemy) if init==nil then ini(Monster); end monster.base.kills.setLastAttacker(Monster,Enemy) killer[Monster.id]=Enemy.id; --Keeps track who attacked the monster last end function onCasted(Monster,Enemy) if init==nil then ini(Monster); end monster.base.kills.setLastAttacker(Monster,Enemy) killer[Monster.id]=Enemy.id; --Keeps track who attacked the monster last end function onDeath(Monster) if killer[Monster.id] ~= nil then murderer=getCharForId(killer[Monster.id]); if murderer then --Checking for quests monster.base.quests.checkQuest(murderer,Monster); killer[Monster.id]=nil; murderer=nil; end end monster.base.drop.ClearDropping(); local MonID=Monster:getMonsterType(); if (MonID==181) then --sheep monster.base.drop.AddDropItem(63,1,50,333,0,1); --inners monster.base.drop.AddDropItem(170,10,50,333,0,2); --wool monster.base.drop.AddDropItem(2934,1,100,333,0,3); --lamb meat elseif (MonID==293) then --cow monster.base.drop.AddDropItem(69,1,50,333,0,1); --leather monster.base.drop.AddDropItem(333,1,50,333,0,2); --horn monster.base.drop.AddDropItem(2940,1,100,333,0,3); --steak elseif (MonID==241 or MonID==251 or MonID==252 or MonID==253) then --pig monster.base.drop.AddDropItem(69,1,50,333,0,1); --leather monster.base.drop.AddDropItem(63,1,50,333,0,2); --entrails monster.base.drop.AddDropItem(307,1,100,333,0,3); --pork elseif (MonID==294) then --deer monster.base.drop.AddDropItem(63,1,50,333,0,1); --inners monster.base.drop.AddDropItem(552,1,100,333,0,2); --deer meat elseif (MonID==295) then --bunny monster.base.drop.AddDropItem(63,1,50,333,0,1); --inners monster.base.drop.AddDropItem(553,1,100,333,0,2); --rabbit meat end monster.base.drop.Dropping(Monster); end
Fixed bug
Fixed bug
Lua
agpl-3.0
Illarion-eV/Illarion-Content,vilarion/Illarion-Content,LaFamiglia/Illarion-Content,KayMD/Illarion-Content,Baylamon/Illarion-Content
775c4ae1c345ae1fd7594f7fd436d0dca442f0e0
packages/luci-app-wifishark/files/usr/lib/lua/luci/controller/openairview/survey.lua
packages/luci-app-wifishark/files/usr/lib/lua/luci/controller/openairview/survey.lua
--[[ LuCI - Lua Configuration Interface Copyright 2013 Nicolas Echaniz <nicoechaniz@altermundi.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 ]]-- module("luci.controller.luci.survey", package.seeall) function index() entry({"luci", "survey"}, alias("luci", "survey", "index"), _("Survey"), 50).index = true entry({"luci", "survey", "index"}, call("action_survey", {autoapply=true}), _("General"), 1) entry({"luci", "survey", "spectral_scan"}, call("action_spectral_scan"), _("Spectral Scan"), 1) end function action_survey() luci.template.render("luci/survey") end function action_spectral_scan() luci.template.render("luci/spectral_scan") end
--[[ LuCI - Lua Configuration Interface Copyright 2013 Nicolas Echaniz <nicoechaniz@altermundi.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 ]]-- module("luci.controller.openairview.survey", package.seeall) function index() entry({"admin", "survey"}, alias("admin", "survey", "index"), _("Survey"), 50).index = true entry({"admin", "survey", "index"}, call("action_survey", {autoapply=true}), _("General"), 1) entry({"admin", "survey", "spectral_scan"}, call("action_spectral_scan"), _("Spectral Scan"), 1) end function action_survey() luci.template.render("openairview/survey") end function action_spectral_scan() luci.template.render("openairview/spectral_scan") end
luci-app-openairview: fix path names on menus
luci-app-openairview: fix path names on menus
Lua
agpl-3.0
libremesh/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,p4u/lime-packages,p4u/lime-packages,libremesh/lime-packages,libremesh/lime-packages,p4u/lime-packages,p4u/lime-packages,libremesh/lime-packages
940935fb16cde82ed673b4fc4cf1f986288e1b8e
tools/migration/migrator/prosody_sql.lua
tools/migration/migrator/prosody_sql.lua
local assert = assert; local have_DBI, DBI = pcall(require,"DBI"); local print = print; local type = type; local next = next; local pairs = pairs; local t_sort = table.sort; local json = require "util.json"; local mtools = require "migrator.mtools"; local tostring = tostring; local tonumber = tonumber; if not have_DBI then error("LuaDBI (required for SQL support) was not found, please see http://prosody.im/doc/depends#luadbi", 0); end module "prosody_sql" local function create_table(connection, params) local create_sql = "CREATE TABLE `prosody` (`host` TEXT, `user` TEXT, `store` TEXT, `key` TEXT, `type` TEXT, `value` TEXT);"; if params.driver == "PostgreSQL" then create_sql = create_sql:gsub("`", "\""); elseif params.driver == "MySQL" then create_sql = create_sql:gsub("`value` TEXT", "`value` MEDIUMTEXT"); end local stmt = connection:prepare(create_sql); if stmt then local ok = stmt:execute(); local commit_ok = connection:commit(); if ok and commit_ok then local index_sql = "CREATE INDEX `prosody_index` ON `prosody` (`host`, `user`, `store`, `key`)"; if params.driver == "PostgreSQL" then index_sql = index_sql:gsub("`", "\""); elseif params.driver == "MySQL" then index_sql = index_sql:gsub("`([,)])", "`(20)%1"); end local stmt, err = connection:prepare(index_sql); local ok, commit_ok, commit_err; if stmt then ok, err = assert(stmt:execute()); commit_ok, commit_err = assert(connection:commit()); end else -- COMPAT: Upgrade tables from 0.8.0 -- Failed to create, but check existing MySQL table here local stmt = connection:prepare("SHOW COLUMNS FROM prosody WHERE Field='value' and Type='text'"); local ok = stmt:execute(); local commit_ok = connection:commit(); if ok and commit_ok then if stmt:rowcount() > 0 then local stmt = connection:prepare("ALTER TABLE prosody MODIFY COLUMN `value` MEDIUMTEXT"); local ok = stmt:execute(); local commit_ok = connection:commit(); if ok and commit_ok then print("Database table automatically upgraded"); end end repeat until not stmt:fetch(); end end end end local function serialize(value) local t = type(value); if t == "string" or t == "boolean" or t == "number" then return t, tostring(value); elseif t == "table" then local value,err = json.encode(value); if value then return "json", value; end return nil, err; end return nil, "Unhandled value type: "..t; end local function deserialize(t, value) if t == "string" then return value; elseif t == "boolean" then if value == "true" then return true; elseif value == "false" then return false; end elseif t == "number" then return tonumber(value); elseif t == "json" then return json.decode(value); end end local function decode_user(item) local userdata = { user = item[1][1].user; host = item[1][1].host; stores = {}; }; for i=1,#item do -- loop over stores local result = {}; local store = item[i]; for i=1,#store do -- loop over store data local row = store[i]; local k = row.key; local v = deserialize(row.type, row.value); if k and v then if k ~= "" then result[k] = v; elseif type(v) == "table" then for a,b in pairs(v) do result[a] = b; end end end userdata.stores[store[1].store] = result; end end return userdata; end function reader(input) local dbh = assert(DBI.Connect( assert(input.driver, "no input.driver specified"), assert(input.database, "no input.database specified"), input.username, input.password, input.host, input.port )); assert(dbh:ping()); local stmt = assert(dbh:prepare("SELECT * FROM prosody")); assert(stmt:execute()); local keys = {"host", "user", "store", "key", "type", "value"}; local f,s,val = stmt:rows(true); -- get SQL rows, sorted local iter = mtools.sorted { reader = function() val = f(s, val); return val; end; filter = function(x) for i=1,#keys do if not x[keys[i]] then return false; end -- TODO log error, missing field end if x.host == "" then x.host = nil; end if x.user == "" then x.user = nil; end if x.store == "" then x.store = nil; end return x; end; sorter = function(a, b) local a_host, a_user, a_store = a.host or "", a.user or "", a.store or ""; local b_host, b_user, b_store = b.host or "", b.user or "", b.store or ""; return a_host > b_host or (a_host==b_host and a_user > b_user) or (a_host==b_host and a_user==b_user and a_store > b_store); end; }; -- merge rows to get stores iter = mtools.merged(iter, function(a, b) return (a.host == b.host and a.user == b.user and a.store == b.store); end); -- merge stores to get users iter = mtools.merged(iter, function(a, b) return (a[1].host == b[1].host and a[1].user == b[1].user); end); return function() local x = iter(); return x and decode_user(x); end; end function writer(output, iter) local dbh = assert(DBI.Connect( assert(output.driver, "no output.driver specified"), assert(output.database, "no output.database specified"), output.username, output.password, output.host, output.port )); assert(dbh:ping()); create_table(dbh, output); local stmt = assert(dbh:prepare("SELECT * FROM prosody")); assert(stmt:execute()); local stmt = assert(dbh:prepare("DELETE FROM prosody")); assert(stmt:execute()); local insert_sql = "INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)"; if output.driver == "PostgreSQL" then insert_sql = insert_sql:gsub("`", "\""); end local insert = assert(dbh:prepare(insert_sql)); return function(item) if not item then assert(dbh:commit()) return dbh:close(); end -- end of input local host = item.host or ""; local user = item.user or ""; for store, data in pairs(item.stores) do -- TODO transactions local extradata = {}; for key, value in pairs(data) do if type(key) == "string" and key ~= "" then local t, value = assert(serialize(value)); local ok, err = assert(insert:execute(host, user, store, key, t, value)); else extradata[key] = value; end end if next(extradata) ~= nil then local t, extradata = assert(serialize(extradata)); local ok, err = assert(insert:execute(host, user, store, "", t, extradata)); end end end; end return _M;
local assert = assert; local have_DBI, DBI = pcall(require,"DBI"); local print = print; local type = type; local next = next; local pairs = pairs; local t_sort = table.sort; local json = require "util.json"; local mtools = require "migrator.mtools"; local tostring = tostring; local tonumber = tonumber; if not have_DBI then error("LuaDBI (required for SQL support) was not found, please see http://prosody.im/doc/depends#luadbi", 0); end module "prosody_sql" local function create_table(connection, params) local create_sql = "CREATE TABLE `prosody` (`host` TEXT, `user` TEXT, `store` TEXT, `key` TEXT, `type` TEXT, `value` TEXT);"; if params.driver == "PostgreSQL" then create_sql = create_sql:gsub("`", "\""); elseif params.driver == "MySQL" then create_sql = create_sql:gsub("`value` TEXT", "`value` MEDIUMTEXT"); end local stmt = connection:prepare(create_sql); if stmt then local ok = stmt:execute(); local commit_ok = connection:commit(); if ok and commit_ok then local index_sql = "CREATE INDEX `prosody_index` ON `prosody` (`host`, `user`, `store`, `key`)"; if params.driver == "PostgreSQL" then index_sql = index_sql:gsub("`", "\""); elseif params.driver == "MySQL" then index_sql = index_sql:gsub("`([,)])", "`(20)%1"); end local stmt, err = connection:prepare(index_sql); local ok, commit_ok, commit_err; if stmt then ok, err = assert(stmt:execute()); commit_ok, commit_err = assert(connection:commit()); end elseif params.driver == "MySQL" then -- COMPAT: Upgrade tables from 0.8.0 -- Failed to create, but check existing MySQL table here local stmt = connection:prepare("SHOW COLUMNS FROM prosody WHERE Field='value' and Type='text'"); local ok = stmt:execute(); local commit_ok = connection:commit(); if ok and commit_ok then if stmt:rowcount() > 0 then local stmt = connection:prepare("ALTER TABLE prosody MODIFY COLUMN `value` MEDIUMTEXT"); local ok = stmt:execute(); local commit_ok = connection:commit(); if ok and commit_ok then print("Database table automatically upgraded"); end end repeat until not stmt:fetch(); end end end end local function serialize(value) local t = type(value); if t == "string" or t == "boolean" or t == "number" then return t, tostring(value); elseif t == "table" then local value,err = json.encode(value); if value then return "json", value; end return nil, err; end return nil, "Unhandled value type: "..t; end local function deserialize(t, value) if t == "string" then return value; elseif t == "boolean" then if value == "true" then return true; elseif value == "false" then return false; end elseif t == "number" then return tonumber(value); elseif t == "json" then return json.decode(value); end end local function decode_user(item) local userdata = { user = item[1][1].user; host = item[1][1].host; stores = {}; }; for i=1,#item do -- loop over stores local result = {}; local store = item[i]; for i=1,#store do -- loop over store data local row = store[i]; local k = row.key; local v = deserialize(row.type, row.value); if k and v then if k ~= "" then result[k] = v; elseif type(v) == "table" then for a,b in pairs(v) do result[a] = b; end end end userdata.stores[store[1].store] = result; end end return userdata; end function reader(input) local dbh = assert(DBI.Connect( assert(input.driver, "no input.driver specified"), assert(input.database, "no input.database specified"), input.username, input.password, input.host, input.port )); assert(dbh:ping()); local stmt = assert(dbh:prepare("SELECT * FROM prosody")); assert(stmt:execute()); local keys = {"host", "user", "store", "key", "type", "value"}; local f,s,val = stmt:rows(true); -- get SQL rows, sorted local iter = mtools.sorted { reader = function() val = f(s, val); return val; end; filter = function(x) for i=1,#keys do if not x[keys[i]] then return false; end -- TODO log error, missing field end if x.host == "" then x.host = nil; end if x.user == "" then x.user = nil; end if x.store == "" then x.store = nil; end return x; end; sorter = function(a, b) local a_host, a_user, a_store = a.host or "", a.user or "", a.store or ""; local b_host, b_user, b_store = b.host or "", b.user or "", b.store or ""; return a_host > b_host or (a_host==b_host and a_user > b_user) or (a_host==b_host and a_user==b_user and a_store > b_store); end; }; -- merge rows to get stores iter = mtools.merged(iter, function(a, b) return (a.host == b.host and a.user == b.user and a.store == b.store); end); -- merge stores to get users iter = mtools.merged(iter, function(a, b) return (a[1].host == b[1].host and a[1].user == b[1].user); end); return function() local x = iter(); return x and decode_user(x); end; end function writer(output, iter) local dbh = assert(DBI.Connect( assert(output.driver, "no output.driver specified"), assert(output.database, "no output.database specified"), output.username, output.password, output.host, output.port )); assert(dbh:ping()); create_table(dbh, output); local stmt = assert(dbh:prepare("SELECT * FROM prosody")); assert(stmt:execute()); local stmt = assert(dbh:prepare("DELETE FROM prosody")); assert(stmt:execute()); local insert_sql = "INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)"; if output.driver == "PostgreSQL" then insert_sql = insert_sql:gsub("`", "\""); end local insert = assert(dbh:prepare(insert_sql)); return function(item) if not item then assert(dbh:commit()) return dbh:close(); end -- end of input local host = item.host or ""; local user = item.user or ""; for store, data in pairs(item.stores) do -- TODO transactions local extradata = {}; for key, value in pairs(data) do if type(key) == "string" and key ~= "" then local t, value = assert(serialize(value)); local ok, err = assert(insert:execute(host, user, store, key, t, value)); else extradata[key] = value; end end if next(extradata) ~= nil then local t, extradata = assert(serialize(extradata)); local ok, err = assert(insert:execute(host, user, store, "", t, extradata)); end end end; end return _M;
migrator/prosody_sql.lua: Fix for compatibility with non-MySQL databases
migrator/prosody_sql.lua: Fix for compatibility with non-MySQL databases
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
5fb9958432c3c02c12dc81d1f520e65aef3b28f6
lua/entities/gmod_wire_screen.lua
lua/entities/gmod_wire_screen.lua
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Screen" ENT.WireDebugName = "Screen" ENT.Editable = true ENT.RenderGroup = RENDERGROUP_BOTH function ENT:SetupDataTables() self:NetworkVar("Bool", 0, "SingleValue", { KeyName = "SingleValue", Edit = { type = "Boolean", title = "#Tool_wire_screen_singlevalue", order = 1 } }) self:NetworkVar("Bool", 1, "SingleBigFont", { KeyName = "SingleBigFont", Edit = { type = "Boolean", title = "#Tool_wire_screen_singlebigfont", order = 2 } }) self:NetworkVar("Bool", 2, "LeftAlign", { KeyName = "LeftAlign", Edit = { type = "Boolean", title = "#Tool_wire_screen_leftalign", order = 3 } }) self:NetworkVar("Bool", 3, "Floor", { KeyName = "Floor", Edit = { type = "Boolean", title = "#Tool_wire_screen_floor", order = 4 } }) self:NetworkVar("Bool", 4, "FormatNumber", { KeyName = "FormatNumber", Edit = { type = "Boolean", title = "#Tool_wire_screen_formatnumber", order = 5 } }) self:NetworkVar("Bool", 5, "FormatTime", { KeyName = "FormatTime", Edit = { type = "Boolean", title = "#Tool_wire_screen_formattime", order = 6 } }) self:NetworkVar("String", 0, "TextA", { KeyName = "TextA", Edit = { type = "Generic", title = "#Tool_wire_screen_texta", order = 7 } }) self:NetworkVar("String", 1, "TextB", { KeyName = "TextB", Edit = { type = "Generic", title = "#Tool_wire_screen_textb", order = 8 } }) if SERVER then self:NetworkVarNotify("SingleValue", function(ent, key, old, single) WireLib.AdjustInputs(self, single and { "A" } or { "A", "B" }) end) end end function ENT:SetDisplayA(float) self:SetNWFloat("DisplayA", float) end function ENT:SetDisplayB(float) self:SetNWFloat("DisplayB", float) end function ENT:GetDisplayA() return self:GetNWFloat("DisplayA") end function ENT:GetDisplayB() return self:GetNWFloat("DisplayB") end if CLIENT then function ENT:Initialize() self.GPU = WireGPU(self, true) end function ENT:OnRemove() self.GPU:Finalize() end local header_color = Color(100,100,150,255) local text_color = Color(255,255,255,255) local background_color = Color(0,0,0,255) local large_font = "Trebuchet36" local small_font = "Trebuchet18" local value_large_font = "screen_font_single" local value_small_font = "screen_font" local small_height = 20 local large_height = 40 function ENT:DrawNumber( header, value, x,y,w,h ) local header_height = small_height local header_font = small_font local value_font = value_small_font if self:GetSingleValue() and self:GetSingleBigFont() then header_height = large_height header_font = large_font value_font = value_large_font end surface.SetDrawColor( header_color ) surface.DrawRect( x, y, w, header_height ) surface.SetFont( header_font ) surface.SetTextColor( text_color ) local _w,_h = surface.GetTextSize( header ) surface.SetTextPos( x + w / 2 - _w / 2, y + 2 ) surface.DrawText( header, header_font ) if self:GetFormatTime() then -- format as time, aka duration - override formatnumber and floor settings value = WireLib.nicenumber.nicetime( value ) elseif self:GetFormatNumber() then if self:GetFloor() then value = WireLib.nicenumber.format( math.floor( value ), 1 ) else value = WireLib.nicenumber.formatDecimal( value ) end elseif self:GetFloor() then value = "" .. math.floor( value ) else -- note: loses precision after ~7 decimals, so don't bother displaying more value = "" .. math.floor( value * 10000000 ) / 10000000 end local align = self:GetLeftAlign() and 0 or 1 surface.SetFont( value_font ) local _w,_h = surface.GetTextSize( value ) surface.SetTextPos( x + (w / 2 - _w / 2) * align, y + header_height ) surface.DrawText( value ) end function ENT:Draw() self:DrawModel() self.GPU:RenderToWorld(nil, 188, function(x, y, w, h) if self:GetSingleValue() then self:DrawNumber( self:GetTextA(), self:GetDisplayA(), x,y,w,h ) else local h = h/2 self:DrawNumber( self:GetTextA(), self:GetDisplayA(), x,y,w,h ) self:DrawNumber( self:GetTextB(), self:GetDisplayB(), x,y+h,w,h ) end end) Wire_Render(self) end function ENT:IsTranslucent() return true end local fontData = { font = "coolvetica", size = 64, weight = 400, antialias = false, additive = false, } surface.CreateFont("screen_font", fontData ) fontData.size = 128 surface.CreateFont("screen_font_single", fontData ) fontData.size = 36 surface.CreateFont("Trebuchet36", fontData ) return -- No more client end -- Server function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.Inputs = WireLib.CreateInputs(self, { "A", "B" }) self.ValueA = 0 self.ValueB = 0 end function ENT:Think() if self.ValueA then self:SetDisplayA( self.ValueA ) self.ValueA = nil end if self.ValueB then self:SetDisplayB( self.ValueB ) self.ValueB = nil end self:NextThink(CurTime() + 0.05) return true end function ENT:TriggerInput(iname, value) if (iname == "A") then self.ValueA = value elseif (iname == "B") then self.ValueB = value end end -- only needed for legacy dupes function ENT:Setup(SingleValue, SingleBigFont, TextA, TextB, LeftAlign, Floor, FormatNumber, FormatTime) if type(TextA) == "string" then self:SetTextA(TextA) end if type(TextB) == "string" then self:SetTextB(TextB) end if SingleBigFont ~= nil then self:SetSingleBigFont(SingleBigFont) end if LeftAlign ~= nil then self:SetLeftAlign(LeftAlign) end if Floor ~= nil then self:SetFloor(Floor) end if SingleValue ~= nil then self:SetSingleValue(SingleValue) end if FormatNumber ~= nil then self:SetFormatNumber(FormatNumber) end if FormatTime ~= nil then self:SetFormatTime(FormatTime) end end duplicator.RegisterEntityClass("gmod_wire_screen", WireLib.MakeWireEnt, "Data", "SingleValue", "SingleBigFont", "TextA", "TextB", "LeftAlign", "Floor", "FormatNumber", "FormatTime")
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Screen" ENT.WireDebugName = "Screen" ENT.Editable = true ENT.RenderGroup = RENDERGROUP_BOTH function ENT:SetupDataTables() self:NetworkVar("Bool", 0, "SingleValue", { KeyName = "SingleValue", Edit = { type = "Boolean", title = "#Tool_wire_screen_singlevalue", order = 1 } }) self:NetworkVar("Bool", 1, "SingleBigFont", { KeyName = "SingleBigFont", Edit = { type = "Boolean", title = "#Tool_wire_screen_singlebigfont", order = 2 } }) self:NetworkVar("Bool", 2, "LeftAlign", { KeyName = "LeftAlign", Edit = { type = "Boolean", title = "#Tool_wire_screen_leftalign", order = 3 } }) self:NetworkVar("Bool", 3, "Floor", { KeyName = "Floor", Edit = { type = "Boolean", title = "#Tool_wire_screen_floor", order = 4 } }) self:NetworkVar("Bool", 4, "FormatNumber", { KeyName = "FormatNumber", Edit = { type = "Boolean", title = "#Tool_wire_screen_formatnumber", order = 5 } }) self:NetworkVar("Bool", 5, "FormatTime", { KeyName = "FormatTime", Edit = { type = "Boolean", title = "#Tool_wire_screen_formattime", order = 6 } }) self:NetworkVar("String", 0, "TextA", { KeyName = "TextA", Edit = { type = "Generic", title = "#Tool_wire_screen_texta", order = 7 } }) self:NetworkVar("String", 1, "TextB", { KeyName = "TextB", Edit = { type = "Generic", title = "#Tool_wire_screen_textb", order = 8 } }) if SERVER then self:NetworkVarNotify("SingleValue", function(ent, key, old, single) WireLib.AdjustInputs(self, single and { "A" } or { "A", "B" }) end) end end function ENT:SetDisplayA(float) self:SetNWFloat("DisplayA", float) end function ENT:SetDisplayB(float) self:SetNWFloat("DisplayB", float) end function ENT:GetDisplayA() return self:GetNWFloat("DisplayA") end function ENT:GetDisplayB() return self:GetNWFloat("DisplayB") end if CLIENT then function ENT:Initialize() self.GPU = WireGPU(self, true) end function ENT:OnRemove() self.GPU:Finalize() end local header_color = Color(100,100,150,255) local text_color = Color(255,255,255,255) local background_color = Color(0,0,0,255) local large_font = "Trebuchet36" local small_font = "Trebuchet18" local value_large_font = "screen_font_single" local value_small_font = "screen_font" local small_height = 20 local large_height = 40 function ENT:DrawNumber( header, value, x,y,w,h ) local header_height = small_height local header_font = small_font local value_font = value_small_font if self:GetSingleValue() and self:GetSingleBigFont() then header_height = large_height header_font = large_font value_font = value_large_font end surface.SetDrawColor( header_color ) surface.DrawRect( x, y, w, header_height ) surface.SetFont( header_font ) surface.SetTextColor( text_color ) local _w,_h = surface.GetTextSize( header ) surface.SetTextPos( x + w / 2 - _w / 2, y + 2 ) surface.DrawText( header, header_font ) if self:GetFormatTime() then -- format as time, aka duration - override formatnumber and floor settings value = WireLib.nicenumber.nicetime( value ) elseif self:GetFormatNumber() then if self:GetFloor() then value = WireLib.nicenumber.format( math.floor( value ), 1 ) else value = WireLib.nicenumber.formatDecimal( value ) end elseif self:GetFloor() then value = "" .. math.floor( value ) else -- note: loses precision after ~7 decimals, so don't bother displaying more value = "" .. math.floor( value * 10000000 ) / 10000000 end local align = self:GetLeftAlign() and 0 or 1 surface.SetFont( value_font ) local _w,_h = surface.GetTextSize( value ) surface.SetTextPos( x + (w / 2 - _w / 2) * align, y + header_height ) surface.DrawText( value ) end function ENT:Draw() self:DrawModel() self.GPU:RenderToWorld(nil, 188, function(x, y, w, h) surface.SetDrawColor(background_color) surface.DrawRect(x, y, w, h) if self:GetSingleValue() then self:DrawNumber( self:GetTextA(), self:GetDisplayA(), x,y,w,h ) else local h = h/2 self:DrawNumber( self:GetTextA(), self:GetDisplayA(), x,y,w,h ) self:DrawNumber( self:GetTextB(), self:GetDisplayB(), x,y+h,w,h ) end end) Wire_Render(self) end function ENT:IsTranslucent() return true end local fontData = { font = "coolvetica", size = 64, weight = 400, antialias = false, additive = false, } surface.CreateFont("screen_font", fontData ) fontData.size = 128 surface.CreateFont("screen_font_single", fontData ) fontData.size = 36 surface.CreateFont("Trebuchet36", fontData ) return -- No more client end -- Server function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.Inputs = WireLib.CreateInputs(self, { "A", "B" }) self.ValueA = 0 self.ValueB = 0 end function ENT:Think() if self.ValueA then self:SetDisplayA( self.ValueA ) self.ValueA = nil end if self.ValueB then self:SetDisplayB( self.ValueB ) self.ValueB = nil end self:NextThink(CurTime() + 0.05) return true end function ENT:TriggerInput(iname, value) if (iname == "A") then self.ValueA = value elseif (iname == "B") then self.ValueB = value end end -- only needed for legacy dupes function ENT:Setup(SingleValue, SingleBigFont, TextA, TextB, LeftAlign, Floor, FormatNumber, FormatTime) if type(TextA) == "string" then self:SetTextA(TextA) end if type(TextB) == "string" then self:SetTextB(TextB) end if SingleBigFont ~= nil then self:SetSingleBigFont(SingleBigFont) end if LeftAlign ~= nil then self:SetLeftAlign(LeftAlign) end if Floor ~= nil then self:SetFloor(Floor) end if SingleValue ~= nil then self:SetSingleValue(SingleValue) end if FormatNumber ~= nil then self:SetFormatNumber(FormatNumber) end if FormatTime ~= nil then self:SetFormatTime(FormatTime) end end duplicator.RegisterEntityClass("gmod_wire_screen", WireLib.MakeWireEnt, "Data", "SingleValue", "SingleBigFont", "TextA", "TextB", "LeftAlign", "Floor", "FormatNumber", "FormatTime")
Update gmod_wire_screen.lua (#2129)
Update gmod_wire_screen.lua (#2129) fix the background
Lua
apache-2.0
Grocel/wire,wiremod/wire,dvdvideo1234/wire
60118c78e1fba6f79957134fe434382f2e3b2b3d
kong/plugins/rate-limiting/daos.lua
kong/plugins/rate-limiting/daos.lua
return { { name = "ratelimiting_metrics", primary_key = { "identifier", "period", "period_date", "service_id", "route_id" }, generate_admin_api = false, ttl = true, fields = { { identifier = { type = "string", required = true, len_min = 0, }, }, { period = { type = "string", required = true, }, }, { period_date = { type = "integer", timestamp = true, required = true, }, }, { service_id = { -- don't make this `foreign` type = "string", uuid = true, required = true, }, }, { route_id = { -- don't make this `foreign` type = "string", uuid = true, required = true, }, }, { value = { type = "integer", required = true, }, }, }, }, }
return { { name = "ratelimiting_metrics", primary_key = { "identifier", "period", "period_date", "service_id", "route_id" }, generate_admin_api = false, ttl = true, db_export = false, fields = { { identifier = { type = "string", required = true, len_min = 0, }, }, { period = { type = "string", required = true, }, }, { period_date = { type = "integer", timestamp = true, required = true, }, }, { service_id = { -- don't make this `foreign` type = "string", uuid = true, required = true, }, }, { route_id = { -- don't make this `foreign` type = "string", uuid = true, required = true, }, }, { value = { type = "integer", required = true, }, }, }, }, }
fix(db) do not export ratelimiting_metrics (#6442)
fix(db) do not export ratelimiting_metrics (#6442) ### Summary Rate-limiting metrics is problematic on db exports / imports as reported by @jeremyjpj0916 on #6310. There are several issues on that, but it seems like the main issue is that Cassandra schema specifies the value of ratelimiting_metrics as `COUNTER`. Also it probably does not make sense to export these anyway as agreed on that issue. ### Issues Resolved Fix #6310
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
599e0fd1df12f65f59f78e0753fb9e49524ddc6a
fontchooser.lua
fontchooser.lua
require "rendertext" require "keys" require "graphics" FontChooser = { -- font for displaying file/dir names face = freetype.newBuiltinFace("sans", 25), fhash = "s25", -- font for page title tface = freetype.newBuiltinFace("Helvetica-BoldOblique", 32), tfhash = "hbo32", -- font for paging display sface = freetype.newBuiltinFace("sans", 16), sfhash = "s16", -- title height title_H = 45, -- spacing between lines spacing = 40, -- foot height foot_H = 27, -- state buffer fonts = {"sans", "cjk", "mono", "Courier", "Courier-Bold", "Courier-Oblique", "Courier-BoldOblique", "Helvetica", "Helvetica-Oblique", "Helvetica-BoldOblique", "Times-Roman", "Times-Bold", "Times-Italic", "Times-BoldItalic",}, items = 14, page = 1, current = 2, oldcurrent = 1, } function FontChooser:init() self.items = #self.fonts table.sort(self.fonts) end function FontChooser:choose(ypos, height) local perpage = math.floor(height / self.spacing) - 2 local pagedirty = true local markerdirty = false local prevItem = function () if self.current == 1 then if self.page > 1 then self.current = perpage self.page = self.page - 1 pagedirty = true end else self.current = self.current - 1 markerdirty = true end end local nextItem = function () if self.current == perpage then if self.page < (self.items / perpage) then self.current = 1 self.page = self.page + 1 pagedirty = true end else if self.page ~= math.floor(self.items / perpage) + 1 or self.current + (self.page-1)*perpage < self.items then self.current = self.current + 1 markerdirty = true end end end -- draw menu title fb.bb:paintRect(0, ypos, fb.bb:getWidth(), height, 0) renderUtf8Text(fb.bb, 30, ypos + self.spacing, self.tface, self.tfhash, "[ Fonts Menu ]", true) fb:refresh(0, 0, ypos, fb.bb:getWidth(), self.title_H) while true do if pagedirty then fb.bb:paintRect(0, ypos, fb.bb:getWidth(), height, 0) --renderUtf8Text(fb.bb, 30, ypos + self.spacing, self.tface, self.tfhash, "[ Fonts Menu ]", true) local c for c = 1, perpage do local i = (self.page - 1) * perpage + c if i <= self.items then y = ypos + self.title_H + (self.spacing * c) renderUtf8Text(fb.bb, 50, y, self.face, self.fhash, self.fonts[i], true) end end y = ypos + self.title_H + (self.spacing * perpage) + self.foot_H x = (fb.bb:getWidth() / 2) - 50 renderUtf8Text(fb.bb, x, y, self.sface, self.sfhash, "Page "..self.page.." of "..(math.floor(self.items / perpage)+1), true) markerdirty = true end if markerdirty then if not pagedirty then if self.oldcurrent > 0 then y = ypos + self.title_H + (self.spacing * self.oldcurrent) + 10 fb.bb:paintRect(30, y, fb.bb:getWidth() - 60, 3, 0) fb:refresh(1, 30, y, fb.bb:getWidth() - 60, 3) end end y = ypos + self.title_H + (self.spacing * self.current) + 10 fb.bb:paintRect(30, y, fb.bb:getWidth() - 60, 3, 15) if not pagedirty then fb:refresh(1, 30, y, fb.bb:getWidth() - 60, 3) end self.oldcurrent = self.current markerdirty = false end if pagedirty then fb:refresh(0, 0, ypos + self.title_H, fb.bb:getWidth(), height - self.title_H) pagedirty = false end local ev = input.waitForEvent() if ev.type == EV_KEY and ev.value == EVENT_VALUE_KEY_PRESS then if ev.code == KEY_FW_UP then prevItem() elseif ev.code == KEY_FW_DOWN then nextItem() elseif ev.code == KEY_PGFWD then if self.page < (self.items / perpage) then if self.current + self.page*perpage > self.items then self.current = self.items - self.page*perpage end self.page = self.page + 1 pagedirty = true else self.current = self.items - (self.page-1)*perpage markerdirty = true end elseif ev.code == KEY_PGBCK then if self.page > 1 then self.page = self.page - 1 pagedirty = true else self.current = 2 markerdirty = true end elseif ev.code == KEY_ENTER or ev.code == KEY_FW_PRESS then local newface = self.fonts[perpage*(self.page-1)+self.current] return newface elseif ev.code == KEY_BACK then return nil end end end end
require "rendertext" require "keys" require "graphics" FontChooser = { -- font for displaying file/dir names face = freetype.newBuiltinFace("sans", 25), fhash = "s25", -- font for page title tface = freetype.newBuiltinFace("Helvetica-BoldOblique", 32), tfhash = "hbo32", -- font for paging display sface = freetype.newBuiltinFace("sans", 16), sfhash = "s16", -- title height title_H = 45, -- spacing between lines spacing = 40, -- foot height foot_H = 27, -- state buffer fonts = {"sans", "cjk", "mono", "Courier", "Courier-Bold", "Courier-Oblique", "Courier-BoldOblique", "Helvetica", "Helvetica-Oblique", "Helvetica-BoldOblique", "Times-Roman", "Times-Bold", "Times-Italic", "Times-BoldItalic",}, items = 14, page = 1, current = 2, oldcurrent = 1, } function FontChooser:init() self.items = #self.fonts table.sort(self.fonts) end function FontChooser:choose(ypos, height) local perpage = math.floor(height / self.spacing) - 2 local pagedirty = true local markerdirty = false local prevItem = function () if self.current == 1 then if self.page > 1 then self.current = perpage self.page = self.page - 1 pagedirty = true end else self.current = self.current - 1 markerdirty = true end end local nextItem = function () if self.current == perpage then if self.page < (self.items / perpage) then self.current = 1 self.page = self.page + 1 pagedirty = true end else if self.page ~= math.floor(self.items / perpage) + 1 or self.current + (self.page-1)*perpage < self.items then self.current = self.current + 1 markerdirty = true end end end while true do if pagedirty then fb.bb:paintRect(0, ypos, fb.bb:getWidth(), height, 0) -- draw menu title renderUtf8Text(fb.bb, 30, ypos + self.title_H, self.tface, self.tfhash, "[ Fonts Menu ]", true) local c for c = 1, perpage do local i = (self.page - 1) * perpage + c if i <= self.items then y = ypos + self.title_H + (self.spacing * c) renderUtf8Text(fb.bb, 50, y, self.face, self.fhash, self.fonts[i], true) end end y = ypos + self.title_H + (self.spacing * perpage) + self.foot_H x = (fb.bb:getWidth() / 2) - 50 renderUtf8Text(fb.bb, x, y, self.sface, self.sfhash, "Page "..self.page.." of "..(math.floor(self.items / perpage)+1), true) markerdirty = true end if markerdirty then if not pagedirty then if self.oldcurrent > 0 then y = ypos + self.title_H + (self.spacing * self.oldcurrent) + 10 fb.bb:paintRect(30, y, fb.bb:getWidth() - 60, 3, 0) fb:refresh(1, 30, y, fb.bb:getWidth() - 60, 3) end end -- draw new marker line y = ypos + self.title_H + (self.spacing * self.current) + 10 fb.bb:paintRect(30, y, fb.bb:getWidth() - 60, 3, 15) if not pagedirty then fb:refresh(1, 30, y, fb.bb:getWidth() - 60, 3) end self.oldcurrent = self.current markerdirty = false end if pagedirty then fb:refresh(0, 0, ypos, fb.bb:getWidth(), height) pagedirty = false end local ev = input.waitForEvent() if ev.type == EV_KEY and ev.value == EVENT_VALUE_KEY_PRESS then if ev.code == KEY_FW_UP then prevItem() elseif ev.code == KEY_FW_DOWN then nextItem() elseif ev.code == KEY_PGFWD then if self.page < (self.items / perpage) then if self.current + self.page*perpage > self.items then self.current = self.items - self.page*perpage end self.page = self.page + 1 pagedirty = true else self.current = self.items - (self.page-1)*perpage markerdirty = true end elseif ev.code == KEY_PGBCK then if self.page > 1 then self.page = self.page - 1 pagedirty = true else self.current = 1 markerdirty = true end elseif ev.code == KEY_ENTER or ev.code == KEY_FW_PRESS then local newface = self.fonts[perpage*(self.page-1)+self.current] return newface elseif ev.code == KEY_BACK then return nil end end end end
fix: do full page refresh to get better user experience
fix: do full page refresh to get better user experience
Lua
agpl-3.0
houqp/koreader-base,NiLuJe/koreader,koreader/koreader-base,frankyifei/koreader-base,houqp/koreader,NickSavage/koreader,koreader/koreader-base,houqp/koreader-base,NiLuJe/koreader-base,Hzj-jie/koreader,robert00s/koreader,lgeek/koreader,frankyifei/koreader,Hzj-jie/koreader-base,frankyifei/koreader-base,Frenzie/koreader-base,NiLuJe/koreader-base,frankyifei/koreader-base,apletnev/koreader-base,houqp/koreader-base,mihailim/koreader,apletnev/koreader-base,NiLuJe/koreader-base,koreader/koreader-base,frankyifei/koreader-base,poire-z/koreader,ashang/koreader,Frenzie/koreader-base,koreader/koreader,pazos/koreader,NiLuJe/koreader-base,chihyang/koreader,Hzj-jie/koreader-base,Hzj-jie/koreader-base,Markismus/koreader,Hzj-jie/koreader-base,Frenzie/koreader,houqp/koreader-base,chrox/koreader,apletnev/koreader,apletnev/koreader-base,apletnev/koreader-base,Frenzie/koreader,koreader/koreader,mwoz123/koreader,Frenzie/koreader-base,ashhher3/koreader,koreader/koreader-base,poire-z/koreader,noname007/koreader,Frenzie/koreader-base,NiLuJe/koreader
3f353a69940ab45a9e0bf65369d82ee704f46da6
xmake/modules/detect/sdks/find_vstudio.lua
xmake/modules/detect/sdks/find_vstudio.lua
--!A cross-platform build utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2018, TBOOX Open Source Group. -- -- @author ruki -- @file find_vstudio.lua -- -- imports import("lib.detect.find_file") -- init vc variables local vcvars = {"path", "lib", "libpath", "include", "DevEnvdir", "VSInstallDir", "VCInstallDir", "WindowsSdkDir", "WindowsLibPath", "WindowsSDKVersion", "WindowsSdkBinPath", "UniversalCRTSdkDir", "UCRTVersion"} -- load vcvarsall environment variables function _load_vcvarsall(vcvarsall, arch) -- make the genvcvars.bat local genvcvars_bat = os.tmpfile() .. "_genvcvars.bat" local genvcvars_dat = os.tmpfile() .. "_genvcvars.txt" local file = io.open(genvcvars_bat, "w") file:print("@echo off") file:print("call \"%s\" %s > nul", vcvarsall, arch) file:print("echo { > %s", genvcvars_dat) for idx, var in ipairs(vcvars) do file:print("echo " .. (idx == 1 and "" or ",") .. " " .. var .. " = \"%%" .. var .. "%%\" >> %s", genvcvars_dat) end file:print("echo } >> %s", genvcvars_dat) file:close() -- run genvcvars.bat os.run(genvcvars_bat) -- replace "\" => "\\" io.gsub(genvcvars_dat, "\\", "\\\\") -- load all envirnoment variables local variables = io.load(genvcvars_dat) if not variables then return end -- remove some empty entries for _, name in ipairs(vcvars) do if variables[name] and #variables[name]:trim() == 0 then variables[name] = nil end end -- fix WindowsSDKVersion local WindowsSDKVersion = variables["WindowsSDKVersion"] if WindowsSDKVersion then WindowsSDKVersion = WindowsSDKVersion:gsub("\\", ""):trim() variables["WindowsSDKVersion"] = WindowsSDKVersion end -- fix UCRTVersion -- -- @note vcvarsall.bat maybe detect error if install WDK and SDK at same time (multi-sdk version exists in include directory). -- local UCRTVersion = variables["UCRTVersion"] if UCRTVersion and UCRTVersion ~= WindowsSDKVersion then local lib = variables["lib"] if lib then lib = lib:gsub(UCRTVersion, WindowsSDKVersion) variables["lib"] = lib end local include = variables["include"] if include then include = include:gsub(UCRTVersion, WindowsSDKVersion) variables["include"] = include end UCRTVersion = WindowsSDKVersion variables["UCRTVersion"] = UCRTVersion end -- ok return variables end -- find vstudio environment -- -- @return { 2008 = {version = "9.0", vcvarsall = {x86 = {path = .., lib = .., include = ..}}} -- , 2017 = {version = "15.0", vcvarsall = {x64 = {path = .., lib = ..}}}} -- function main() -- init vsvers local vsvers = { ["15.0"] = "2017" , ["14.0"] = "2015" , ["12.0"] = "2013" , ["11.0"] = "2012" , ["10.0"] = "2010" , ["9.0"] = "2008" , ["8.0"] = "2005" , ["7.1"] = "2003" , ["7.0"] = "7.0" , ["6.0"] = "6.0" , ["5.0"] = "5.0" , ["4.2"] = "4.2" } -- init vsenvs local vsenvs = { ["14.0"] = "VS140COMNTOOLS" , ["12.0"] = "VS120COMNTOOLS" , ["11.0"] = "VS110COMNTOOLS" , ["10.0"] = "VS100COMNTOOLS" , ["9.0"] = "VS90COMNTOOLS" , ["8.0"] = "VS80COMNTOOLS" , ["7.1"] = "VS71COMNTOOLS" , ["7.0"] = "VS70COMNTOOLS" , ["6.0"] = "VS60COMNTOOLS" , ["5.0"] = "VS50COMNTOOLS" , ["4.2"] = "VS42COMNTOOLS" } -- find vs from environment variables local VCInstallDir = os.getenv("VCInstallDir") local VisualStudioVersion = os.getenv("VisualStudioVersion") if VCInstallDir and VisualStudioVersion then -- find vcvarsall.bat local vcvarsall = path.join(VCInstallDir, "Auxiliary", "Build", "vcvarsall.bat") if os.isfile(vcvarsall) then -- load vcvarsall local vcvarsall_x86 = _load_vcvarsall(vcvarsall, "x86") local vcvarsall_x64 = _load_vcvarsall(vcvarsall, "x64") -- save results local results = {} results[vsvers[VisualStudioVersion]] = {version = VisualStudioVersion, vcvarsall_bat = vcvarsall, vcvarsall = {x86 = vcvarsall_x86, x64 = vcvarsall_x64}} return results end end -- find vs2017 -> vs4.2 local results = {} for _, version in ipairs({"15.0", "14.0", "12.0", "11.0", "10.0", "9.0", "8.0", "7.1", "7.0", "6.0", "5.0", "4.2"}) do -- init pathes local pathes = { format("$(reg HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VS7;%s)\\VC", version), format("$(reg HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\VisualStudio\\SxS\\VS7;%s)\\VC", version), format("$(reg HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VS7;%s)\\VC\\Auxiliary\\Build", version), format("$(reg HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\VisualStudio\\SxS\\VS7;%s)\\VC\\Auxiliary\\Build", version), format("$(env %s)\\..\\..\\VC", vsenvs[version] or "") } -- find vcvarsall.bat local vcvarsall = find_file("vcvarsall.bat", pathes) if vcvarsall then -- load vcvarsall local vcvarsall_x86 = _load_vcvarsall(vcvarsall, "x86") local vcvarsall_x64 = _load_vcvarsall(vcvarsall, "x64") -- save results results[vsvers[version]] = {version = version, vcvarsall_bat = vcvarsall, vcvarsall = {x86 = vcvarsall_x86, x64 = vcvarsall_x64}} end end -- ok? return results end
--!A cross-platform build utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2018, TBOOX Open Source Group. -- -- @author ruki -- @file find_vstudio.lua -- -- imports import("lib.detect.find_file") -- init vc variables local vcvars = {"path", "lib", "libpath", "include", "DevEnvdir", "VSInstallDir", "VCInstallDir", "WindowsSdkDir", "WindowsLibPath", "WindowsSDKVersion", "WindowsSdkBinPath", "UniversalCRTSdkDir", "UCRTVersion"} -- load vcvarsall environment variables function _load_vcvarsall(vcvarsall, arch) -- make the genvcvars.bat local genvcvars_bat = os.tmpfile() .. "_genvcvars.bat" local genvcvars_dat = os.tmpfile() .. "_genvcvars.txt" local file = io.open(genvcvars_bat, "w") file:print("@echo off") file:print("call \"%s\" %s > nul", vcvarsall, arch) file:print("echo { > %s", genvcvars_dat) for idx, var in ipairs(vcvars) do file:print("echo " .. (idx == 1 and "" or ",") .. " " .. var .. " = \"%%" .. var .. "%%\" >> %s", genvcvars_dat) end file:print("echo } >> %s", genvcvars_dat) file:close() -- run genvcvars.bat os.run(genvcvars_bat) -- replace "\" => "\\" io.gsub(genvcvars_dat, "\\", "\\\\") -- load all envirnoment variables local variables = io.load(genvcvars_dat) if not variables then return end -- remove some empty entries for _, name in ipairs(vcvars) do if variables[name] and #variables[name]:trim() == 0 then variables[name] = nil end end -- fix WindowsSDKVersion local WindowsSDKVersion = variables["WindowsSDKVersion"] if WindowsSDKVersion then WindowsSDKVersion = WindowsSDKVersion:gsub("\\", ""):trim() if WindowsSDKVersion ~= "" then variables["WindowsSDKVersion"] = WindowsSDKVersion end end -- fix UCRTVersion -- -- @note vcvarsall.bat maybe detect error if install WDK and SDK at same time (multi-sdk version exists in include directory). -- local UCRTVersion = variables["UCRTVersion"] if UCRTVersion and UCRTVersion ~= WindowsSDKVersion and WindowsSDKVersion ~= "" then local lib = variables["lib"] if lib then lib = lib:gsub(UCRTVersion, WindowsSDKVersion) variables["lib"] = lib end local include = variables["include"] if include then include = include:gsub(UCRTVersion, WindowsSDKVersion) variables["include"] = include end UCRTVersion = WindowsSDKVersion variables["UCRTVersion"] = UCRTVersion end -- ok return variables end -- find vstudio environment -- -- @return { 2008 = {version = "9.0", vcvarsall = {x86 = {path = .., lib = .., include = ..}}} -- , 2017 = {version = "15.0", vcvarsall = {x64 = {path = .., lib = ..}}}} -- function main() -- init vsvers local vsvers = { ["15.0"] = "2017" , ["14.0"] = "2015" , ["12.0"] = "2013" , ["11.0"] = "2012" , ["10.0"] = "2010" , ["9.0"] = "2008" , ["8.0"] = "2005" , ["7.1"] = "2003" , ["7.0"] = "7.0" , ["6.0"] = "6.0" , ["5.0"] = "5.0" , ["4.2"] = "4.2" } -- init vsenvs local vsenvs = { ["14.0"] = "VS140COMNTOOLS" , ["12.0"] = "VS120COMNTOOLS" , ["11.0"] = "VS110COMNTOOLS" , ["10.0"] = "VS100COMNTOOLS" , ["9.0"] = "VS90COMNTOOLS" , ["8.0"] = "VS80COMNTOOLS" , ["7.1"] = "VS71COMNTOOLS" , ["7.0"] = "VS70COMNTOOLS" , ["6.0"] = "VS60COMNTOOLS" , ["5.0"] = "VS50COMNTOOLS" , ["4.2"] = "VS42COMNTOOLS" } -- find vs from environment variables local VCInstallDir = os.getenv("VCInstallDir") local VisualStudioVersion = os.getenv("VisualStudioVersion") if VCInstallDir and VisualStudioVersion then -- find vcvarsall.bat local vcvarsall = path.join(VCInstallDir, "Auxiliary", "Build", "vcvarsall.bat") if os.isfile(vcvarsall) then -- load vcvarsall local vcvarsall_x86 = _load_vcvarsall(vcvarsall, "x86") local vcvarsall_x64 = _load_vcvarsall(vcvarsall, "x64") -- save results local results = {} results[vsvers[VisualStudioVersion]] = {version = VisualStudioVersion, vcvarsall_bat = vcvarsall, vcvarsall = {x86 = vcvarsall_x86, x64 = vcvarsall_x64}} return results end end -- find vs2017 -> vs4.2 local results = {} for _, version in ipairs({"15.0", "14.0", "12.0", "11.0", "10.0", "9.0", "8.0", "7.1", "7.0", "6.0", "5.0", "4.2"}) do -- init pathes local pathes = { format("$(reg HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VS7;%s)\\VC", version), format("$(reg HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\VisualStudio\\SxS\\VS7;%s)\\VC", version), format("$(reg HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VS7;%s)\\VC\\Auxiliary\\Build", version), format("$(reg HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Microsoft\\VisualStudio\\SxS\\VS7;%s)\\VC\\Auxiliary\\Build", version), format("$(env %s)\\..\\..\\VC", vsenvs[version] or "") } -- find vcvarsall.bat local vcvarsall = find_file("vcvarsall.bat", pathes) if vcvarsall then -- load vcvarsall local vcvarsall_x86 = _load_vcvarsall(vcvarsall, "x86") local vcvarsall_x64 = _load_vcvarsall(vcvarsall, "x64") -- save results results[vsvers[version]] = {version = version, vcvarsall_bat = vcvarsall, vcvarsall = {x86 = vcvarsall_x86, x64 = vcvarsall_x64}} end end -- ok? return results end
fix find_vstudio bug
fix find_vstudio bug
Lua
apache-2.0
tboox/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,tboox/xmake,tboox/xmake,waruqi/xmake,tboox/xmake,waruqi/xmake,waruqi/xmake
09c9f8f059e8aa00b0e632028391a7b155436e13
mods/bonemeal/init.lua
mods/bonemeal/init.lua
local plant_tab = { "air", "default:grass_1", "default:grass_2", "default:grass_3", "default:grass_4", "default:grass_5", "flowers:dandelion_white", "flowers:dandelion_yellow", "flowers:geranium", "flowers:rose", "flowers:tulip", "flowers:viola" } local function can_grow(pos) pos.y = pos.y-1 local node_under = minetest.get_node_or_nil(pos) pos.y = pos.y+1 if not node_under then return false end if minetest.get_item_group(node_under.name, "soil") > 0 then return true end end local function tree_grow(pos, node) local sapling = node.name local mapgen = minetest.get_mapgen_params().mgname if sapling == "default:sapling" then if mapgen == "v6" then default.grow_tree(pos, math.random(1, 4) == 1) else default.grow_new_apple_tree(pos) end elseif sapling == "default:junglesapling" then if mapgen == "v6" then default.grow_jungle_tree(pos) else default.grow_new_jungle_tree(pos) end elseif sapling == "default:pine_sapling" then if mapgen == "v6" then default.grow_pine_tree(pos) else default.grow_new_pine_tree(pos) end elseif sapling == "default:acacia_sapling" then default.grow_new_acacia_tree(pos) elseif sapling == "farming_plus:banana_sapling" then farming.generate_tree(pos, "default:tree", "farming_plus:banana_leaves", {"default:dirt", "default:dirt_with_grass"}, {["farming_plus:banana"]=20}) elseif sapling == "farming_plus:cocoa_sapling" then farming.generate_tree(pos, "default:tree", "farming_plus:cocoa_leaves", {"default:sand", "default:desert_sand"}, {["farming_plus:cocoa"]=20}) elseif sapling == "default:cherry_sapling" then default.grow_cherry_tree(pos, math.random(1, 4) == 1, "default:cherry_tree", "default:cherry_blossom_leaves") elseif sapling == "moretrees:apple_tree_sapling" then minetest.remove_node(pos) minetest.spawn_tree(pos, moretrees["apple_tree_model"]) elseif sapling == "moretrees:beech_sapling" then minetest.remove_node(pos) minetest.spawn_tree(pos, moretrees["beech_model"]) elseif sapling == "moretrees:birch_sapling" then moretrees.grow_birch(pos) elseif sapling == "moretrees:fir_sapling" then if minetest.find_node_near(pos, 2, {"default:snow", "default:dirt_with_snow"}) and math.random(1,3) ~= 1 then moretrees.grow_fir_snow(pos) else moretrees.grow_fir(pos) end elseif sapling == "moretrees:oak_sapling" then minetest.remove_node(pos) minetest.spawn_tree(pos, moretrees["oak_model"]) elseif sapling == "moretrees:palm_sapling" then minetest.remove_node(pos) minetest.spawn_tree(pos, moretrees["palm_model"]) elseif sapling == "moretrees:rubber_tree_sapling" then minetest.remove_node(pos) minetest.spawn_tree(pos, moretrees["rubber_tree_model"]) elseif sapling == "moretrees:sequoia_sapling" then minetest.remove_node(pos) minetest.spawn_tree(pos, moretrees["sequoia_model"]) elseif sapling == "moretrees:spruce_sapling" then moretrees.grow_spruce(pos) elseif sapling == "moretrees:willow_sapling" then minetest.remove_node(pos) minetest.spawn_tree(pos, moretrees["willow_model"]) elseif sapling == "nether:tree_sapling" then nether.grow_tree(pos, math.random(1, 4) == 1) end end local function grow(itemstack, user, pointed_thing) local pos = pointed_thing.under if pointed_thing.type ~= "node" or not pos.x then return end local node = minetest.get_node(pos) local random = math.random -- Tree if minetest.get_item_group(node.name, "sapling") >= 1 or node.name:find("farming_plus:") and node.name:find("sapling") or node.name == "nether:tree_sapling" then if can_grow(pos) then tree_grow(pos, node) itemstack:take_item() end -- Seed elseif node.name:find(":seed") then local node = node.name:split(":") local seed = node[2]:split("_") local after_glow_node1 = node[1]..":"..seed[1].."_1" local after_glow_node2 = node[1]..":"..seed[2].."_1" if minetest.registered_nodes[after_glow_node1] then minetest.set_node(pos, {name=after_glow_node1}) itemstack:take_item() elseif minetest.registered_nodes[after_glow_node2] then minetest.set_node(pos, {name=after_glow_node2}) itemstack:take_item() end -- Dirt elseif node.name == "default:dirt_with_grass" then for i = -2, 2 do for j = -2, 2 do pos = pointed_thing.above pos = {x=pos.x+i, y=pos.y, z=pos.z+j} local node = minetest.get_node(pos) local node2 = minetest.get_node({x=pos.x, y=pos.y-1, z=pos.z}) if node.name == "air" and node2.name == "default:dirt_with_grass" then minetest.set_node(pos, {name=plant_tab[random(1, 12)]}) end end end itemstack:take_item() -- Grass and others elseif node.name:find("_") and node.name:find("%d") then local node = node.name:split(":") local name = node[2]:split("_") local next_node = node[1]..":"..name[1].."_"..name[2]+1 local last_node = node[1]..":"..name[1] if minetest.registered_nodes[next_node] then minetest.set_node(pos,{name=next_node}) itemstack:take_item() elseif not minetest.registered_nodes[next_node] and minetest.registered_nodes[last_node] then minetest.set_node(pos, {name=last_node}) itemstack:take_item() end -- Farming Redo elseif farming.mod == "redo" then if node.name == "farming:beanpole" then minetest.set_node(pos, {name="farming:beanpole_1"}) itemstack:take_item() end end return itemstack end minetest.register_craftitem("bonemeal:bonemeal", { description = "Bone Meal", inventory_image = "bonemeal.png", on_use = grow }) minetest.register_craft({ output = "bonemeal:bonemeal", recipe = {{"dye:white"}} }) minetest.register_craft({ output = "dye:white", recipe = {{"bonemeal:bonemeal"}} }) if minetest.get_modpath("charcoal") then minetest.register_craftitem("bonemeal:ash", { description = "Ash", inventory_image = "bonemeal_ash.png", on_use = grow }) minetest.register_craft({ output = "bonemeal:ash", recipe = {{"charcoal:charcoal"}} }) end
local plant_tab = { "air", "default:grass_1", "default:grass_2", "default:grass_3", "default:grass_4", "default:grass_5", "flowers:dandelion_white", "flowers:dandelion_yellow", "flowers:geranium", "flowers:rose", "flowers:tulip", "flowers:viola" } local function can_grow(pos) pos.y = pos.y-1 local node_under = minetest.get_node_or_nil(pos) pos.y = pos.y+1 if not node_under then return false end if minetest.get_item_group(node_under.name, "soil") > 0 then return true else return false end end local function tree_grow(pos, node) local sapling = node.name local mapgen = minetest.get_mapgen_params().mgname if sapling == "default:sapling" then if mapgen == "v6" then default.grow_tree(pos, math.random(1, 4) == 1) else default.grow_new_apple_tree(pos) end elseif sapling == "default:junglesapling" then if mapgen == "v6" then default.grow_jungle_tree(pos) else default.grow_new_jungle_tree(pos) end elseif sapling == "default:pine_sapling" then if mapgen == "v6" then default.grow_pine_tree(pos) else default.grow_new_pine_tree(pos) end elseif sapling == "default:acacia_sapling" then default.grow_new_acacia_tree(pos) elseif sapling == "farming_plus:banana_sapling" then farming.generate_tree(pos, "default:tree", "farming_plus:banana_leaves", {"default:dirt", "default:dirt_with_grass"}, {["farming_plus:banana"]=20}) elseif sapling == "farming_plus:cocoa_sapling" then farming.generate_tree(pos, "default:tree", "farming_plus:cocoa_leaves", {"default:sand", "default:desert_sand"}, {["farming_plus:cocoa"]=20}) elseif sapling == "default:cherry_sapling" then default.grow_cherry_tree(pos, math.random(1, 4) == 1, "default:cherry_tree", "default:cherry_blossom_leaves") elseif sapling == "moretrees:apple_tree_sapling" then minetest.remove_node(pos) minetest.spawn_tree(pos, moretrees["apple_tree_model"]) elseif sapling == "moretrees:beech_sapling" then minetest.remove_node(pos) minetest.spawn_tree(pos, moretrees["beech_model"]) elseif sapling == "moretrees:birch_sapling" then moretrees.grow_birch(pos) elseif sapling == "moretrees:fir_sapling" then if minetest.find_node_near(pos, 2, {"default:snow", "default:dirt_with_snow"}) and math.random(1,3) ~= 1 then moretrees.grow_fir_snow(pos) else moretrees.grow_fir(pos) end elseif sapling == "moretrees:oak_sapling" then minetest.remove_node(pos) minetest.spawn_tree(pos, moretrees["oak_model"]) elseif sapling == "moretrees:palm_sapling" then minetest.remove_node(pos) minetest.spawn_tree(pos, moretrees["palm_model"]) elseif sapling == "moretrees:rubber_tree_sapling" then minetest.remove_node(pos) minetest.spawn_tree(pos, moretrees["rubber_tree_model"]) elseif sapling == "moretrees:sequoia_sapling" then minetest.remove_node(pos) minetest.spawn_tree(pos, moretrees["sequoia_model"]) elseif sapling == "moretrees:spruce_sapling" then moretrees.grow_spruce(pos) elseif sapling == "moretrees:willow_sapling" then minetest.remove_node(pos) minetest.spawn_tree(pos, moretrees["willow_model"]) elseif sapling == "nether:tree_sapling" then nether.grow_tree(pos, math.random(1, 4) == 1) end end local function grow(itemstack, user, pointed_thing) local pos = pointed_thing.under if pointed_thing.type ~= "node" or not pos.x then return end local node = minetest.get_node(pos) local random = math.random -- Tree if minetest.get_item_group(node.name, "sapling") >= 1 or node.name:find("farming_plus:") and node.name:find("sapling") or node.name:find("nether:tree") then print(can_grow(pos)) if can_grow(pos) then tree_grow(pos, node) itemstack:take_item() end -- Seed elseif node.name:find(":seed") then local node = node.name:split(":") local seed = node[2]:split("_") local after_glow_node1 = node[1]..":"..seed[1].."_1" local after_glow_node2 = node[1]..":"..seed[2].."_1" if minetest.registered_nodes[after_glow_node1] then minetest.set_node(pos, {name=after_glow_node1}) itemstack:take_item() elseif minetest.registered_nodes[after_glow_node2] then minetest.set_node(pos, {name=after_glow_node2}) itemstack:take_item() end -- Dirt elseif node.name == "default:dirt_with_grass" then for i = -2, 2 do for j = -2, 2 do pos = pointed_thing.above pos = {x=pos.x+i, y=pos.y, z=pos.z+j} local node = minetest.get_node(pos) local node2 = minetest.get_node({x=pos.x, y=pos.y-1, z=pos.z}) if node.name == "air" and node2.name == "default:dirt_with_grass" then minetest.set_node(pos, {name=plant_tab[random(1, 12)]}) end end end itemstack:take_item() -- Grass and others elseif node.name:find("_") and node.name:find("%d") then local node = node.name:split(":") local name = node[2]:split("_") local next_node = node[1]..":"..name[1].."_"..name[2]+1 local last_node = node[1]..":"..name[1] if minetest.registered_nodes[next_node] then minetest.set_node(pos,{name=next_node}) itemstack:take_item() elseif not minetest.registered_nodes[next_node] and minetest.registered_nodes[last_node] then minetest.set_node(pos, {name=last_node}) itemstack:take_item() end -- Farming Redo elseif farming.mod == "redo" then if node.name == "farming:beanpole" then minetest.set_node(pos, {name="farming:beanpole_1"}) itemstack:take_item() end end return itemstack end minetest.register_craftitem("bonemeal:bonemeal", { description = "Bone Meal", inventory_image = "bonemeal.png", on_use = grow }) minetest.register_craft({ output = "bonemeal:bonemeal", recipe = {{"dye:white"}} }) minetest.register_craft({ output = "dye:white", recipe = {{"bonemeal:bonemeal"}} }) if minetest.get_modpath("charcoal") then minetest.register_craftitem("bonemeal:ash", { description = "Ash", inventory_image = "bonemeal_ash.png", on_use = grow }) minetest.register_craft({ output = "bonemeal:ash", recipe = {{"charcoal:charcoal"}} }) end
[bonemeal] Fix bonemeal
[bonemeal] Fix bonemeal
Lua
unlicense
MinetestForFun/server-minetestforfun-creative,MinetestForFun/server-minetestforfun-creative,MinetestForFun/server-minetestforfun-creative
f297cfe3191e17e1e95429b8b3a5905ff44f6869
util/pluginloader.lua
util/pluginloader.lua
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local plugin_dir = CFG_PLUGINDIR or "./plugins/"; local io_open, os_time = io.open, os.time; local loadstring, pairs = loadstring, pairs; local datamanager = require "util.datamanager"; module "pluginloader" local function load_file(name) local file, err = io_open(plugin_dir..name); if not file then return file, err; end local content = file:read("*a"); file:close(); return content, name; end function load_resource(plugin, resource, loader) if not resource then resource = "mod_"..plugin..".lua"; end loader = loader or load_file; local content, err = loader(plugin.."/"..resource); if not content then content, err = loader(resource); end -- TODO add support for packed plugins return content, err; end function load_code(plugin, resource) local content, err = load_resource(plugin, resource); if not content then return content, err; end return loadstring(content, "@"..err); end return _M;
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local plugin_dir = CFG_PLUGINDIR or "./plugins/"; local io_open, os_time = io.open, os.time; local loadstring, pairs = loadstring, pairs; local datamanager = require "util.datamanager"; module "pluginloader" local function load_file(name) local file, err = io_open(plugin_dir..name); if not file then return file, err; end local content = file:read("*a"); file:close(); return content, name; end function load_resource(plugin, resource, loader) local path, name = plugin:match("([^/]*)/?(.*)"); if name == "" then if not resource then resource = "mod_"..plugin..".lua"; end loader = loader or load_file; local content, err = loader(plugin.."/"..resource); if not content then content, err = loader(resource); end -- TODO add support for packed plugins return content, err; else if not resource then resource = "mod_"..name..".lua"; end loader = loader or load_file; local content, err = loader(plugin.."/"..resource); if not content then content, err = loader(path.."/"..resource); end -- TODO add support for packed plugins return content, err; end end function load_code(plugin, resource) local content, err = load_resource(plugin, resource); if not content then return content, err; end return loadstring(content, "@"..err); end return _M;
util.pluginloader: Fix loading of plugins, plugin libraries and resources in subfolders (e.g., when loading 'a/b', load 'a/mod_b.lua', and not 'mod_a/b.lua').
util.pluginloader: Fix loading of plugins, plugin libraries and resources in subfolders (e.g., when loading 'a/b', load 'a/mod_b.lua', and not 'mod_a/b.lua').
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
13157fde3f274609f48d9e7dc590023d318dc7ee
src/lua-factory/sources/grl-euronews.lua
src/lua-factory/sources/grl-euronews.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 * --]] EURONEWS_URL = 'http://euronews.hexaglobe.com/json/' --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-euronews-lua", name = "Euronews", description = "A source for watching Euronews online", supported_keys = { "id", "title", "url" }, supported_media = 'video', icon = 'resource:///org/gnome/grilo/plugins/euronews/euronews.svg', tags = { 'news', 'tv', 'net:internet', 'net:plaintext' } } ------------------ -- Source utils -- ------------------ function grl_source_browse(media_id) if grl.get_options("skip") > 0 then grl.callback() else grl.fetch(EURONEWS_URL, euronews_fetch_cb) end end ------------------------ -- Callback functions -- ------------------------ -- return all the media found function euronews_fetch_cb(results) local json = {} json = grl.lua.json.string_to_table(results) if not json or json.stat == "fail" or not json.primary then grl.callback() return end for index, item in pairs(json.primary) do local media = create_media(index, item) if media ~= nil then grl.callback(media, -1) end end grl.callback() end ------------- -- Helpers -- ------------- function get_lang(id) local langs = {} langs.ru = "Russian" langs.hu = "Hungarian" langs.de = "German" langs.fa = "Persian" langs.ua = "Ukrainian" langs.ar = "Arabic" langs.es = "Spanish; Castilian" langs.gr = "Greek, Modern (1453-)" langs.tr = "Turkish" langs.pe = "Persian" -- Duplicate? langs.en = "English" langs.it = "Italian" langs.fr = "French" langs.pt = "Portuguese" if not langs[id] then grl.warning('Could not find language ' .. id) return id end return grl.dgettext('iso_639', langs[id]) end function create_media(lang, item) local media = {} if item.rtmp_flash["750"].name == 'UNAVAILABLE' then return nil end media.type = "video" media.id = lang media.title = "Euronews " .. get_lang(lang) media.url = item.rtmp_flash["750"].server .. item.rtmp_flash["750"].name .. " playpath=" .. item.rtmp_flash["750"].name .. " swfVfy=1 " .. "swfUrl=http://euronews.com/media/player_live_1_14.swf ".. "live=1" 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 * --]] LANG_EN = "en" EURONEWS_URL = 'http://%s.euronews.com/api/watchlive.json' local langs = { arabic = "Arabic", de = "German", en = "English", es = "Spanish; Castilian", fa = "Persian", fr = "French", gr = "Greek, Modern (1453-)", hu = "Hungarian", it = "Italian", pt = "Portuguese", ru = "Russian", tr = "Turkish", } local num_callbacks = 0 --------------------------- -- Source initialization -- --------------------------- source = { id = "grl-euronews-lua", name = "Euronews", description = "A source for watching Euronews online", supported_keys = { "id", "title", "url" }, supported_media = 'video', icon = 'resource:///org/gnome/grilo/plugins/euronews/euronews.svg', tags = { 'news', 'tv', 'net:internet', 'net:plaintext' } } ------------------ -- Source utils -- ------------------ function grl_source_browse(media_id) if grl.get_options("skip") > 0 then grl.callback() return end for lang in pairs(langs) do num_callbacks = num_callbacks + 1 end for lang in pairs(langs) do local api_url = get_api_url(lang) grl.fetch(api_url, euronews_initial_fetch_cb, lang) end end ------------------------ -- Callback functions -- ------------------------ function euronews_initial_fetch_cb(results, lang) local json = {} json = grl.lua.json.string_to_table(results) if not json or not json.url then local api_url = get_api_url(lang) grl.warning ("Initial fetch failed for: " .. api_url) callback_done() return end local streaming_lang = json.url:match("://euronews%-(..)%-p%-api") if lang ~= LANG_EN and streaming_lang == LANG_EN then grl.debug("Skipping " .. langs[lang] .. " as it redirects to " .. langs[LANG_EN] .. " stream.") callback_done() return end grl.fetch(json.url, euronews_fetch_cb, lang) end -- return all the media found function euronews_fetch_cb(results, lang) local json = {} json = grl.lua.json.string_to_table(results) if not json or json.status ~= "ok" or not json.primary then local api_url = get_api_url(lang) grl.warning("Fetch failed for: " .. api_url) callback_done() return end local media = create_media(lang, json) if media ~= nil then grl.callback(media, -1) end callback_done() end ------------- -- Helpers -- ------------- function callback_done() num_callbacks = num_callbacks - 1 -- finalize operation if num_callbacks == 0 then grl.callback() end end function get_api_url(id) if not langs[id] then grl.warning('Could not find language ' .. id) return id end return string.format(EURONEWS_URL, id == LANG_EN and "www" or id) end function get_lang(id) if not langs[id] then grl.warning('Could not find language ' .. id) return id end return grl.dgettext('iso_639', langs[id]) end function create_media(lang, item) local media = {} media.type = "video" media.id = lang media.title = "Euronews " .. get_lang(lang) media.url = item.primary return media end
euronews: Fix parsing of metadata
euronews: Fix parsing of metadata The base url of euronews source might depend on the language now. The url previously pointed to flash stream as now it points to a m3u8 playlist, like: | #EXTM3U | #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=2000000,RESOLUTION=1280x720 | ewnsabrdepri_ger_720p.m3u8 | #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=1200000,RESOLUTION=960x540 | ewnsabrdepri_ger_540p.m3u8 | #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=750000,RESOLUTION=640x360 | ewnsabrdepri_ger_360p.m3u8 | #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=512000,RESOLUTION=400x224 | ewnsabrdepri_ger_224p.m3u8 | #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=350000,RESOLUTION=320x180 | ewnsabrdepri_ger_180p.m3u8 | #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=200000,RESOLUTION=160x90 | ewnsabrdepri_ger_90p.m3u8 Closes #3 Signed-off-by: Victor Toso <39b7599ff73bbf5db531748ba5250f21fa7120ff@redhat.com>
Lua
lgpl-2.1
jasuarez/grilo-plugins,GNOME/grilo-plugins,GNOME/grilo-plugins,jasuarez/grilo-plugins,grilofw/grilo-plugins,grilofw/grilo-plugins
4cbb59891663946fc96accf8b9980bca69b9860d
src/elasticsearch/endpoints/Endpoint.lua
src/elasticsearch/endpoints/Endpoint.lua
------------------------------------------------------------------------------- -- Importing modules ------------------------------------------------------------------------------- local parser = require "elasticsearch.parser" ------------------------------------------------------------------------------- -- Declaring module ------------------------------------------------------------------------------- local Endpoint = {} ------------------------------------------------------------------------------- -- Declaring instance variables ------------------------------------------------------------------------------- -- The index Endpoint.index = nil -- The type Endpoint.type = nil -- The id Endpoint.id = nil -- The request params to be sent as GET parameters Endpoint.params = {} -- The body of the request Endpoint.body = nil -- Whether there is a bulk body or not Endpoint.bulkBody = false -- The transport instance Endpoint.transport = nil -- The endpoint specific parameters Endpoint.endpointParams = {} ------------------------------------------------------------------------------- -- Function to set the body parameter -- -- @param body The body to be set ------------------------------------------------------------------------------- function Endpoint:setBody(body) if self.bulkBody == false then self.body = parser.jsonEncode(body) return end -- Bulk body is present self.body = "" for _id, item in pairs(body) do self.body = self.body .. parser.jsonEncode(item) .. "\n" end end ------------------------------------------------------------------------------- -- Function used to set the params to be sent as GET parameters -- -- @param params The params provided by the user -- -- @return string A string if an error is found otherwise nil ------------------------------------------------------------------------------- function Endpoint:setParams(params) for i, v in pairs(params) do if i == "index" then self.index = v elseif i == "type" then self.type = v elseif i == "id" then self.id = v elseif i == "body" then self:setBody(v) else -- Checking whether i is in allowed parameters or not -- Current algorithm is n*m, but n and m are very small local flag = 0; for _, allowedParam in pairs(self.allowedParams) do if allowedParam == i then flag = 1; break; end end if flag == 0 then return i .. " is not an allowed parameter" end self.params[i] = v end end end ------------------------------------------------------------------------------- -- Makes a request using the instance of transport class -- -- @return table The reponse returned ------------------------------------------------------------------------------- function Endpoint:request() local uri, err = self:getUri() if uri == nil then return nil, err end local response, err = self.transport:request(self:getMethod(), uri , self.params, self.body) -- parsing body if response ~= nil and response.body ~= nil and response.body ~= "" then response.body = parser.jsonDecode(response.body) end return response, err end ------------------------------------------------------------------------------- -- Returns an instance of Endpoint class ------------------------------------------------------------------------------- function Endpoint:new(o) o = o or {} setmetatable(o, self) self.__index = self return o end return Endpoint
------------------------------------------------------------------------------- -- Importing modules ------------------------------------------------------------------------------- local parser = require "elasticsearch.parser" ------------------------------------------------------------------------------- -- Declaring module ------------------------------------------------------------------------------- local Endpoint = {} ------------------------------------------------------------------------------- -- Declaring instance variables ------------------------------------------------------------------------------- -- The index Endpoint.index = nil -- The type Endpoint.type = nil -- The id Endpoint.id = nil -- The request params to be sent as GET parameters Endpoint.params = {} -- The body of the request Endpoint.body = nil -- Whether there is a bulk body or not Endpoint.bulkBody = false -- The transport instance Endpoint.transport = nil -- The endpoint specific parameters Endpoint.endpointParams = {} ------------------------------------------------------------------------------- -- Function to set the body parameter -- -- @param body The body to be set ------------------------------------------------------------------------------- function Endpoint:setBody(body) if self.bulkBody == false then self.body = parser.jsonEncode(body) return end -- Bulk body is present self.body = "" for _id, item in pairs(body) do self.body = self.body .. parser.jsonEncode(item) .. "\n" end end ------------------------------------------------------------------------------- -- Function used to set the params to be sent as GET parameters -- -- @param params The params provided by the user -- -- @return string A string if an error is found otherwise nil ------------------------------------------------------------------------------- function Endpoint:setParams(params) -- Clearing existing parameters self.index = nil self.type = nil self.id = nil self.params = {} self.body = nil -- Setting new parameters for i, v in pairs(params) do if i == "index" then self.index = v elseif i == "type" then self.type = v elseif i == "id" then self.id = v elseif i == "body" then self:setBody(v) else -- Checking whether i is in allowed parameters or not -- Current algorithm is n*m, but n and m are very small local flag = 0; for _, allowedParam in pairs(self.allowedParams) do if allowedParam == i then flag = 1; break; end end if flag == 0 then return i .. " is not an allowed parameter" end self.params[i] = v end end end ------------------------------------------------------------------------------- -- Makes a request using the instance of transport class -- -- @return table The reponse returned ------------------------------------------------------------------------------- function Endpoint:request() local uri, err = self:getUri() if uri == nil then return nil, err end local response, err = self.transport:request(self:getMethod(), uri , self.params, self.body) -- parsing body if response ~= nil and response.body ~= nil and response.body ~= "" then response.body = parser.jsonDecode(response.body) end return response, err end ------------------------------------------------------------------------------- -- Returns an instance of Endpoint class ------------------------------------------------------------------------------- function Endpoint:new(o) o = o or {} setmetatable(o, self) self.__index = self return o end return Endpoint
Fixes #15 Cleared parameters before setting them again.
Fixes #15 Cleared parameters before setting them again.
Lua
mit
DhavalKapil/elasticsearch-lua
12481bce0f4dbda9186f1e58e8c7a559fa394a5f
src/patch/ui/hooks/after_stagingroom.lua
src/patch/ui/hooks/after_stagingroom.lua
if _mpPatch and _mpPatch.enabled and _mpPatch.isModding then local startLock = false local StartCountdownOld = StartCountdown function StartCountdown(...) if not Matchmaking.IsHost() then _mpPatch.overrideModsFromPreGame() end return StartCountdownOld(...) end local function cancelOverride() if not Matchmaking.IsHost() then _mpPatch.debugPrint("Cancelling override.") _mpPatch.patch.NetPatch.reset() end end local function OnPreGameDirtyHook(...) if not ContextPtr:IsHidden() then _mpPatch.debugPrint("cancelOverride from OnPreGameDirty") cancelOverride() end return OnPreGameDirtyOld(...) end Events.PreGameDirty.Add(OnPreGameDirtyHook) local DequeuePopup = UIManager.DequeuePopup _mpPatch.patch.globals.rawset(UIManager, "DequeuePopup", function(this, ...) local context = ... if context == ContextPtr then _mpPatch.debugPrint("cancelOverride from DequeuePopup") cancelOverride() end return DequeuePopup(UIManager, ...) end) -- Disable manual launch, helps with countdown related things. Controls.LaunchButton:RegisterCallback(Mouse.eLClick, function() end) end
if _mpPatch and _mpPatch.enabled and _mpPatch.isModding then local confirmChat = "mppatch:gamelaunchcountdown:WgUUz7wWuxWFmjY02WFS0mka53nFDzJvD00zmuQHKyJT2wNHuWZvrDcejHv5rTyl" local gameLaunchSet = false local gameLaunchCountdown = 3 local StartCountdownOld = StartCountdown function StartCountdown(...) if gameLaunchSet then return end return StartCountdownOld(...) end local StopCountdownOld = StopCountdown function StopCountdown(...) if gameLaunchSet then return end return StopCountdownOld(...) end local HandleExitRequestOld = HandleExitRequest function HandleExitRequest(...) if gameLaunchSet then return end return HandleExitRequestOld(...) end local LaunchGameOld = LaunchGame local function LaunchGameCountdown(timeDiff) gameLaunchCountdown = gameLaunchCountdown - timeDiff if gameLaunchCountdown <= 0 then LaunchGameOld() ContextPtr:ClearUpdate() end end function LaunchGame(...) if PreGame.IsHotSeatGame() then return LaunchGameOld(...) else SendChat(confirmChat) ContextPtr:ClearUpdate() gameLaunchSet = true ContextPtr:SetUpdate(LaunchGameCountdown) end end Controls.LaunchButton:RegisterCallback(Mouse.eLClick, LaunchGame) local OnChatOld = OnChat function OnChat(...) local fromPlayer, toPlayer, text = ... if not Matchmaking.IsHost() and fromPlayer == m_HostID and text == confirmChat then gameLaunchSet = true _mpPatch.overrideModsFromPreGame() return end return OnChatOld(...) end local DequeuePopup = UIManager.DequeuePopup _mpPatch.patch.globals.rawset(UIManager, "DequeuePopup", function(this, ...) local context = ... if context == ContextPtr and not Matchmaking.IsHost() then _mpPatch.debugPrint("Cancelling override.") _mpPatch.patch.NetPatch.reset() end return DequeuePopup(UIManager, ...) end) end
Try to fix stagingroom... again.
Try to fix stagingroom... again.
Lua
mit
Lymia/MPPatch,Lymia/MPPatch,Lymia/MultiverseModManager,Lymia/MultiverseModManager,Lymia/CivV_Mod2DLC,Lymia/MPPatch,Lymia/MPPatch
195a3d33fd4b653d11503f4bdd5af29c3949f4ec
misc.lua
misc.lua
-- Assorted global functions that don't belong in their own file. -- 5.3 compatibility local unpack = unpack or table.unpack local loadstring = loadstring or load -- "safe require", returns nil,error if require fails rather than -- throwing an error function srequire(...) local s,r = pcall(require, ...) if s then return r end return nil,r end -- fast one-liner lambda creation function f(src) return assert(loadstring( "return function(" .. src:gsub(" => ", ") return ") .. " end" ))() end -- bind args into function function partial(f, ...) if select('#', ...) == 0 then return f end local head = (...) return partial(function(...) return f(head, ...) end, select(2, ...)) end -- New versions of pairs, ipairs, and type that respect the corresponding -- metamethods. do local function metamethod_wrap(f, name) return function(v) local mm = getmetafield(v, name) if mm then return mm(v) end return f(v) end end rawtype = type type = metamethod_wrap(type, "__type") -- We only need this on Lua 5.1 (5.2+ have it built in). But LuaJIT may also -- have it built in, depending on compilation option. -- If jit is not defined, we're running in stock 5.1. If it is, but so is -- math.mod, we're running luajit without 5.2 extensions (turning on the -- extensions removes math.mod). In either case we need to enable this. if _VERSION:match("Lua 5.1") and (not jit or math.mod) then pairs = metamethod_wrap(pairs, "__pairs") ipairs = metamethod_wrap(ipairs, "__ipairs") end end -- formatting-aware versions of assert and error do -- We call it 'assertf' because things like assert(call()) are common, and -- if call() returns a bunch of stuff format() will get confused. -- This is more for 'assert(precondition, error, ...)' style usage. -- Maybe it should be called check() instead? function assertf(exp, err, ...) return assert(exp, err:format(...)) end local _error = error function error(err, ...) if select('#', ...) > 0 then return _error(err:format(...)) end return _error(err) end end -- Get field from metatable, return nil if no metatable function getmetafield(v, k) local mt = getmetatable(v) return mt and rawget(mt, k) end -- As tonumber/tostring, but casts to bool function toboolean(v) return not not v end
-- Assorted global functions that don't belong in their own file. -- 5.3 compatibility local unpack = unpack or table.unpack local loadstring = loadstring or load -- "safe require", returns nil,error if require fails rather than -- throwing an error function srequire(...) local s,r = pcall(require, ...) if s then return r end return nil,r end -- fast one-liner lambda creation function f(src) return assert(loadstring( "return function(" .. src:gsub(" => ", ") return ") .. " end" ))() end -- bind args into function function partial(f, ...) if select('#', ...) == 0 then return f end local head = (...) return partial(function(...) return f(head, ...) end, select(2, ...)) end -- New versions of pairs, ipairs, and type that respect the corresponding -- metamethods. do local function metamethod_wrap(f, name) return function(v) local mm = getmetafield(v, name) if mm then return mm(v) end return f(v) end end rawtype = type type = metamethod_wrap(type, "__type") -- We only need this on Lua 5.1 (5.2+ have it built in). But LuaJIT may also -- have it built in, depending on compilation option. -- If jit is defined, we're running in luajit. If 5.2 extensions are enabled, -- table.pack will be defined. if _VERSION:match("Lua 5.1") or (jit and not table.pack) then pairs = metamethod_wrap(pairs, "__pairs") ipairs = metamethod_wrap(ipairs, "__ipairs") end end -- formatting-aware versions of assert and error do -- We call it 'assertf' because things like assert(call()) are common, and -- if call() returns a bunch of stuff format() will get confused. -- This is more for 'assert(precondition, error, ...)' style usage. -- Maybe it should be called check() instead? function assertf(exp, err, ...) return assert(exp, err:format(...)) end local _error = error function error(err, ...) if select('#', ...) > 0 then return _error(err:format(...)) end return _error(err) end end -- Get field from metatable, return nil if no metatable function getmetafield(v, k) local mt = getmetatable(v) return mt and rawget(mt, k) end -- As tonumber/tostring, but casts to bool function toboolean(v) return not not v end
Fix luajit-without-5.2 detection
Fix luajit-without-5.2 detection
Lua
mit
ToxicFrog/luautil
7733f20d623ddf39f3cd3fd91ccee145698407b8
src/program/config/common.lua
src/program/config/common.lua
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local S = require("syscall") local ffi = require("ffi") local lib = require("core.lib") local shm = require("core.shm") local rpc = require("lib.yang.rpc") local yang = require("lib.yang.yang") local data = require("lib.yang.data") local path_resolver = require("lib.yang.path").resolver function show_usage(command, status, err_msg) if err_msg then print('error: '..err_msg) end print(require("program.config."..command:gsub('-','_')..".README_inc")) main.exit(status) end local parse_command_line_opts = { command = { required=true }, with_config_file = { default=false }, with_path = { default=false }, with_value = { default=false }, require_schema = { default=false } } local function path_grammar(schema_name, path) local schema = yang.load_schema_by_name(schema_name) local grammar = data.data_grammar_from_schema(schema) local getter, subgrammar = path_resolver(grammar, path) return subgrammar end function data_parser(schema_name, path) return data.data_parser_from_grammar(path_grammar(schema_name, path)) end function parse_command_line(args, opts) opts = lib.parse(opts, parse_command_line_opts) local function err(msg) show_usage(opts.command, 1, msg) end local ret = {} local handlers = {} function handlers.h() show_usage(opts.command, 0) end function handlers.s(arg) ret.schema_name = arg end function handlers.r(arg) ret.revision_date = arg end function handlers.c(arg) ret.socket = arg end args = lib.dogetopt(args, handlers, "hs:r:c:", {help="h", ['schema-name']="s", schema="s", ['revision-date']="r", revision="r", socket="c"}) if #args == 0 then err() end ret.instance_id = table.remove(args, 1) local descr = call_leader(ret.instance_id, 'describe', {}) if not ret.schema_name then if opts.require_schema then err("missing --schema arg") end ret.schema_name = descr.native_schema end require('lib.yang.schema').set_default_capabilities(descr.capability) if opts.with_config_file then if #args == 0 then err("missing config file argument") end local file = table.remove(args, 1) local opts = {schema_name=ret.schema_name, revision_date=ret.revision_date} ret.config_file = file ret.config = yang.load_configuration(file, opts) end if opts.with_path then if #args == 0 then err("missing path argument") end -- FIXME: Validate path? ret.path = table.remove(args, 1) end if opts.with_value then local parser = data_parser(ret.schema_name, ret.path) if #args == 0 then ret.value_str = io.stdin:read('*a') else ret.value_str = table.remove(args, 1) end ret.value = parser(ret.value_str) end if #args ~= 0 then err("too many arguments") end return ret end function open_socket_or_die(instance_id) S.signal('pipe', 'ign') local socket = assert(S.socket("unix", "stream")) local tail = instance_id..'/config-leader-socket' local by_name = S.t.sockaddr_un(shm.root..'/by-name/'..tail) local by_pid = S.t.sockaddr_un(shm.root..'/'..tail) if not socket:connect(by_name) and not socket:connect(by_pid) then io.stderr:write( "Could not connect to config leader socket on Snabb instance '".. instance_id.."'.\n") main.exit(1) end return socket end function serialize_config(config, schema_name, path) local grammar = path_grammar(schema_name, path or '/') local printer = data.data_printer_from_grammar(grammar) return printer(config, yang.string_output_file()) end function send_message(socket, msg_str) socket:write(tostring(#msg_str)..'\n'..msg_str) end local function read_length(socket) local len = 0 while true do local ch = assert(socket:read(nil, 1)) assert(ch ~= '', 'short read') if ch == '\n' then return len end assert(tonumber(ch), 'not a number: '..ch) len = len * 10 + tonumber(ch) assert(len < 1e8, 'length too long: '..len) end end local function read_msg(socket, len) local buf = ffi.new('uint8_t[?]', len) local pos = 0 while pos < len do local count = assert(socket:read(buf+pos, len-pos)) if count == 0 then error('short read') end pos = pos + count end return ffi.string(buf, len) end function recv_message(socket) return read_msg(socket, read_length(socket)) end function call_leader(instance_id, method, args) local caller = rpc.prepare_caller('snabb-config-leader-v1') local socket = open_socket_or_die(instance_id) local msg, parse_reply = rpc.prepare_call(caller, method, args) send_message(socket, msg) local reply = recv_message(socket) socket:close() return parse_reply(reply) end function print_and_exit(response, response_prop) if response.error then print(response.error) elseif response_prop then print(response[response_prop]) end main.exit(response.status) end
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local S = require("syscall") local ffi = require("ffi") local lib = require("core.lib") local shm = require("core.shm") local rpc = require("lib.yang.rpc") local yang = require("lib.yang.yang") local data = require("lib.yang.data") local path_resolver = require("lib.yang.path").resolver function show_usage(command, status, err_msg) if err_msg then print('error: '..err_msg) end print(require("program.config."..command:gsub('-','_')..".README_inc")) main.exit(status) end local parse_command_line_opts = { command = { required=true }, with_config_file = { default=false }, with_path = { default=false }, with_value = { default=false }, require_schema = { default=false } } local function path_grammar(schema_name, path) local schema = yang.load_schema_by_name(schema_name) local grammar = data.data_grammar_from_schema(schema) local getter, subgrammar = path_resolver(grammar, path) return subgrammar end function data_parser(schema_name, path) return data.data_parser_from_grammar(path_grammar(schema_name, path)) end function error_and_quit(err) io.stderr:write(err .. "\n") io.stderr:flush() os.exit(1) end function validate_path(schema_name, path) local succ, err = pcall(path_grammar, schema_name, path) if succ == false then error_and_quit(err) end end function parse_command_line(args, opts) opts = lib.parse(opts, parse_command_line_opts) local function err(msg) show_usage(opts.command, 1, msg) end local ret = {} local handlers = {} function handlers.h() show_usage(opts.command, 0) end function handlers.s(arg) ret.schema_name = arg end function handlers.r(arg) ret.revision_date = arg end function handlers.c(arg) ret.socket = arg end args = lib.dogetopt(args, handlers, "hs:r:c:", {help="h", ['schema-name']="s", schema="s", ['revision-date']="r", revision="r", socket="c"}) if #args == 0 then err() end ret.instance_id = table.remove(args, 1) local descr = call_leader(ret.instance_id, 'describe', {}) if not ret.schema_name then if opts.require_schema then err("missing --schema arg") end ret.schema_name = descr.native_schema end require('lib.yang.schema').set_default_capabilities(descr.capability) if opts.with_config_file then if #args == 0 then err("missing config file argument") end local file = table.remove(args, 1) local opts = {schema_name=ret.schema_name, revision_date=ret.revision_date} ret.config_file = file ret.config = yang.load_configuration(file, opts) end if opts.with_path then if #args == 0 then err("missing path argument") end ret.path = table.remove(args, 1) validate_path(ret.schema_name, ret.path) end if opts.with_value then local parser = data_parser(ret.schema_name, ret.path) if #args == 0 then ret.value_str = io.stdin:read('*a') else ret.value_str = table.remove(args, 1) end ret.value = parser(ret.value_str) end if #args ~= 0 then err("too many arguments") end return ret end function open_socket_or_die(instance_id) S.signal('pipe', 'ign') local socket = assert(S.socket("unix", "stream")) local tail = instance_id..'/config-leader-socket' local by_name = S.t.sockaddr_un(shm.root..'/by-name/'..tail) local by_pid = S.t.sockaddr_un(shm.root..'/'..tail) if not socket:connect(by_name) and not socket:connect(by_pid) then io.stderr:write( "Could not connect to config leader socket on Snabb instance '".. instance_id.."'.\n") main.exit(1) end return socket end function serialize_config(config, schema_name, path) local grammar = path_grammar(schema_name, path or '/') local printer = data.data_printer_from_grammar(grammar) return printer(config, yang.string_output_file()) end function send_message(socket, msg_str) socket:write(tostring(#msg_str)..'\n'..msg_str) end local function read_length(socket) local len = 0 while true do local ch = assert(socket:read(nil, 1)) assert(ch ~= '', 'short read') if ch == '\n' then return len end assert(tonumber(ch), 'not a number: '..ch) len = len * 10 + tonumber(ch) assert(len < 1e8, 'length too long: '..len) end end local function read_msg(socket, len) local buf = ffi.new('uint8_t[?]', len) local pos = 0 while pos < len do local count = assert(socket:read(buf+pos, len-pos)) if count == 0 then error('short read') end pos = pos + count end return ffi.string(buf, len) end function recv_message(socket) return read_msg(socket, read_length(socket)) end function call_leader(instance_id, method, args) local caller = rpc.prepare_caller('snabb-config-leader-v1') local socket = open_socket_or_die(instance_id) local msg, parse_reply = rpc.prepare_call(caller, method, args) send_message(socket, msg) local reply = recv_message(socket) socket:close() return parse_reply(reply) end function print_and_exit(response, response_prop) if response.error then print(response.error) elseif response_prop then print(response[response_prop]) end main.exit(response.status) end
Fix #638 - Validate path on snabb config get
Fix #638 - Validate path on snabb config get
Lua
apache-2.0
dpino/snabb,alexandergall/snabbswitch,eugeneia/snabb,eugeneia/snabb,eugeneia/snabbswitch,Igalia/snabb,dpino/snabbswitch,alexandergall/snabbswitch,Igalia/snabbswitch,Igalia/snabb,Igalia/snabbswitch,SnabbCo/snabbswitch,alexandergall/snabbswitch,eugeneia/snabbswitch,eugeneia/snabb,alexandergall/snabbswitch,SnabbCo/snabbswitch,Igalia/snabb,alexandergall/snabbswitch,dpino/snabb,dpino/snabb,eugeneia/snabb,heryii/snabb,Igalia/snabbswitch,heryii/snabb,dpino/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,alexandergall/snabbswitch,snabbco/snabb,snabbco/snabb,eugeneia/snabb,snabbco/snabb,dpino/snabb,Igalia/snabb,dpino/snabbswitch,Igalia/snabb,snabbco/snabb,Igalia/snabb,SnabbCo/snabbswitch,Igalia/snabb,eugeneia/snabbswitch,heryii/snabb,Igalia/snabb,Igalia/snabbswitch,heryii/snabb,dpino/snabbswitch,eugeneia/snabbswitch,snabbco/snabb,Igalia/snabbswitch,eugeneia/snabb,dpino/snabb,snabbco/snabb,dpino/snabb,heryii/snabb,SnabbCo/snabbswitch,snabbco/snabb,snabbco/snabb,heryii/snabb,dpino/snabbswitch,eugeneia/snabb,eugeneia/snabb
13a3423f61a2d5410679a9cca14d2f70a9dc4075
modules/gmake2/_preload.lua
modules/gmake2/_preload.lua
-- -- Name: gmake2/_preload.lua -- Purpose: Define the gmake2 action. -- Author: Blizzard Entertainment (Tom van Dijck) -- Modified by: Aleksi Juvani -- Vlad Ivanov -- Created: 2016/01/01 -- Copyright: (c) 2016-2017 Jason Perkins, Blizzard Entertainment and the Premake project -- local p = premake newaction { trigger = "gmake2", shortname = "Alternative GNU Make", description = "Generate GNU makefiles for POSIX, MinGW, and Cygwin", valid_kinds = { "ConsoleApp", "WindowedApp", "StaticLib", "SharedLib", "Utility", "Makefile" }, valid_languages = { "C", "C++", "C#" }, valid_tools = { cc = { "clang", "gcc" }, dotnet = { "mono", "msnet", "pnet" } }, onInitialize = function() p.modules.gmake2.cpp.initialize() end, onWorkspace = function(wks) p.escaper(p.modules.gmake2.esc) p.generate(wks, p.modules.gmake2.getmakefilename(wks, false), p.modules.gmake2.generate_workspace) end, onProject = function(prj) p.escaper(p.modules.gmake2.esc) local makefile = p.modules.gmake2.getmakefilename(prj, true) if prj.kind == p.UTILITY then p.generate(prj, makefile, p.modules.gmake2.utility.generate) elseif prj.kind == p.MAKEFILE then p.generate(prj, makefile, p.modules.gmake2.makefile.generate) else if project.isdotnet(prj) then p.generate(prj, makefile, p.modules.gmake2.cs.generate) elseif project.iscpp(prj) then p.generate(prj, makefile, p.modules.gmake2.cpp.generate) end end end, onCleanWorkspace = function(wks) p.clean.file(wks, p.modules.gmake2.getmakefilename(wks, false)) end, onCleanProject = function(prj) p.clean.file(prj, p.modules.gmake2.getmakefilename(prj, true)) end } -- -- Decide when the full module should be loaded. -- return function(cfg) return (_ACTION == "gmake2") end
-- -- Name: gmake2/_preload.lua -- Purpose: Define the gmake2 action. -- Author: Blizzard Entertainment (Tom van Dijck) -- Modified by: Aleksi Juvani -- Vlad Ivanov -- Created: 2016/01/01 -- Copyright: (c) 2016-2017 Jason Perkins, Blizzard Entertainment and the Premake project -- local p = premake local project = p.project newaction { trigger = "gmake2", shortname = "Alternative GNU Make", description = "Generate GNU makefiles for POSIX, MinGW, and Cygwin", valid_kinds = { "ConsoleApp", "WindowedApp", "StaticLib", "SharedLib", "Utility", "Makefile" }, valid_languages = { "C", "C++", "C#" }, valid_tools = { cc = { "clang", "gcc" }, dotnet = { "mono", "msnet", "pnet" } }, onInitialize = function() require("gmake2") p.modules.gmake2.cpp.initialize() end, onWorkspace = function(wks) p.escaper(p.modules.gmake2.esc) p.generate(wks, p.modules.gmake2.getmakefilename(wks, false), p.modules.gmake2.generate_workspace) end, onProject = function(prj) p.escaper(p.modules.gmake2.esc) local makefile = p.modules.gmake2.getmakefilename(prj, true) if prj.kind == p.UTILITY then p.generate(prj, makefile, p.modules.gmake2.utility.generate) elseif prj.kind == p.MAKEFILE then p.generate(prj, makefile, p.modules.gmake2.makefile.generate) else if project.isdotnet(prj) then p.generate(prj, makefile, p.modules.gmake2.cs.generate) elseif project.isc(prj) or project.iscpp(prj) then p.generate(prj, makefile, p.modules.gmake2.cpp.generate) end end end, onCleanWorkspace = function(wks) p.clean.file(wks, p.modules.gmake2.getmakefilename(wks, false)) end, onCleanProject = function(prj) p.clean.file(prj, p.modules.gmake2.getmakefilename(prj, true)) end } -- -- Decide when the full module should be loaded. -- return function(cfg) return (_ACTION == "gmake2") end
A few gmake2 fixes due to it moving into a module.
A few gmake2 fixes due to it moving into a module.
Lua
bsd-3-clause
aleksijuvani/premake-core,sleepingwit/premake-core,Blizzard/premake-core,dcourtois/premake-core,noresources/premake-core,tvandijck/premake-core,Zefiros-Software/premake-core,noresources/premake-core,noresources/premake-core,aleksijuvani/premake-core,premake/premake-core,LORgames/premake-core,TurkeyMan/premake-core,tvandijck/premake-core,TurkeyMan/premake-core,tvandijck/premake-core,sleepingwit/premake-core,LORgames/premake-core,soundsrc/premake-core,premake/premake-core,LORgames/premake-core,mendsley/premake-core,aleksijuvani/premake-core,Zefiros-Software/premake-core,dcourtois/premake-core,mendsley/premake-core,sleepingwit/premake-core,aleksijuvani/premake-core,soundsrc/premake-core,soundsrc/premake-core,dcourtois/premake-core,mandersan/premake-core,sleepingwit/premake-core,dcourtois/premake-core,mandersan/premake-core,TurkeyMan/premake-core,dcourtois/premake-core,starkos/premake-core,soundsrc/premake-core,noresources/premake-core,soundsrc/premake-core,Blizzard/premake-core,starkos/premake-core,starkos/premake-core,premake/premake-core,dcourtois/premake-core,mendsley/premake-core,premake/premake-core,noresources/premake-core,Blizzard/premake-core,noresources/premake-core,starkos/premake-core,TurkeyMan/premake-core,mendsley/premake-core,mandersan/premake-core,premake/premake-core,starkos/premake-core,mendsley/premake-core,starkos/premake-core,sleepingwit/premake-core,premake/premake-core,LORgames/premake-core,Zefiros-Software/premake-core,noresources/premake-core,Blizzard/premake-core,TurkeyMan/premake-core,aleksijuvani/premake-core,mandersan/premake-core,Zefiros-Software/premake-core,Zefiros-Software/premake-core,Blizzard/premake-core,starkos/premake-core,tvandijck/premake-core,mandersan/premake-core,Blizzard/premake-core,dcourtois/premake-core,LORgames/premake-core,premake/premake-core,tvandijck/premake-core
08ecf99df258859c53c982d9fded1c52d06aedd6
openwrt/package/linkmeter/luasrc/linkmeterd.lua
openwrt/package/linkmeter/luasrc/linkmeterd.lua
#! /usr/bin/env lua local io = require("io") local os = require("os") local rrd = require("rrd") local nixio = require("nixio") nixio.fs = require("nixio.fs") local uci = require("uci") local SERIAL_DEVICE = "/dev/ttyS1" local RRD_FILE = "/tmp/hm.rrd" local JSON_FILE = "/tmp/json" local probeNames = { "Pit", "Food Probe1", "Food Probe2", "Ambient" } function rrdCreate() return rrd.create( RRD_FILE, "--step", "2", "DS:sp:GAUGE:30:0:1000", "DS:t0:GAUGE:30:0:1000", "DS:t1:GAUGE:30:0:1000", "DS:t2:GAUGE:30:0:1000", "DS:t3:GAUGE:30:0:1000", "DS:f:GAUGE:30:-1000:100", "RRA:AVERAGE:0.6:5:360", "RRA:AVERAGE:0.6:30:360", "RRA:AVERAGE:0.6:60:360", "RRA:AVERAGE:0.6:90:480" ) end -- This might look a big hokey but rather than build the string -- and discard it every time, just replace the values to reduce -- the load on the garbage collector local JSON_TEMPLATE = { '{"time":', 0, ',"temps":[{"n":"', 'Pit', '","c":', 0, ',"a":', 0, -- probe1 '},{"n":"', 'Food Probe1', '","c":', 0, ',"a":', 0, -- probe2 '},{"n":"', 'Food Probe2', '","c":', 0, ',"a":', 0, -- probe3 '},{"n":"', 'Ambient', '","c":', 0, ',"a":', 0, -- probe4 '}],"set":', 0, ',"lid":', 0, ',"fan":{"c":', 0, ',"a":', 0, '}}' } local JSON_FROM_CSV = {2, 28, 6, 8, 12, 14, 18, 20, 24, 26, 32, 34, 30 } function jsonWrite(vals) local i,v for i,v in ipairs(vals) do JSON_TEMPLATE[JSON_FROM_CSV[i]] = v end return nixio.fs.writefile(JSON_FILE, table.concat(JSON_TEMPLATE)) end local hm = io.open(SERIAL_DEVICE, "rwb") if hm == nil then die("Can not open serial device") end nixio.umask("0022") -- Create database if not nixio.fs.access(RRD_FILE) then rrdCreate() end -- Create json file if not nixio.fs.access("/www/json") then if not nixio.fs.symlink(JSON_FILE, "/www/json") then print("Can not create JSON file link") end end local hmline local lastUpdate = os.time() while true do hmline = hm:read("*l") if hmline == nil then break end if hmline:sub(1,2) ~= "OK" then local vals = {} for i in hmline:gmatch("[0-9.]+") do vals[#vals+1] = i end if #vals == 12 then -- If the time has shifted more than 24 hours since the last update -- the clock has probably just been set from 0 (at boot) to actual -- time. Recreate the rrd to prevent a 40 year long graph local time = os.time() if time - lastUpdate > (24*60*60) then nixio.syslog("notice", "Time jumped forward by "..(time-lastUpdate)..", restarting database") rrdCreate() end lastUpadte = time -- Add the time as the first item table.insert(vals, 1, time) -- vals[9] = gcinfo() jsonWrite(vals) local lid = tonumber(vals[13]) or 0 -- If the lid value is non-zero, it replaces the fan value if lid ~= 0 then vals[11] = lid end table.remove(vals, 13) -- lid table.remove(vals, 12) -- fan avg table.remove(vals, 10) -- amb avg table.remove(vals, 8) -- food2 avg table.remove(vals, 6) -- food1 avg table.remove(vals, 4) -- pit avg rrd.update(RRD_FILE, table.concat(vals, ":")) end end end hm:close() nixio.fs.unlink("/var/run/linkmeterd/pid")
#! /usr/bin/env lua local io = require("io") local os = require("os") local rrd = require("rrd") local nixio = require("nixio") nixio.fs = require("nixio.fs") local uci = require("uci") local SERIAL_DEVICE = "/dev/ttyS1" local RRD_FILE = "/tmp/hm.rrd" local JSON_FILE = "/tmp/json" local probeNames = { "Pit", "Food Probe1", "Food Probe2", "Ambient" } function rrdCreate() return rrd.create( RRD_FILE, "--step", "2", "DS:sp:GAUGE:30:0:1000", "DS:t0:GAUGE:30:0:1000", "DS:t1:GAUGE:30:0:1000", "DS:t2:GAUGE:30:0:1000", "DS:t3:GAUGE:30:0:1000", "DS:f:GAUGE:30:-1000:100", "RRA:AVERAGE:0.6:5:360", "RRA:AVERAGE:0.6:30:360", "RRA:AVERAGE:0.6:60:360", "RRA:AVERAGE:0.6:90:480" ) end -- This might look a big hokey but rather than build the string -- and discard it every time, just replace the values to reduce -- the load on the garbage collector local JSON_TEMPLATE = { '{"time":', i, ',"temps":[{"n":"', 'Pit', '","c":', 0, ',"a":', 0, -- probe1 '},{"n":"', 'Food Probe1', '","c":', 0, ',"a":', 0, -- probe2 '},{"n":"', 'Food Probe2', '","c":', 0, ',"a":', 0, -- probe3 '},{"n":"', 'Ambient', '","c":', 0, ',"a":', 0, -- probe4 '}],"set":', 0, ',"lid":', 0, ',"fan":{"c":', 0, ',"a":', 0, '}}' } local JSON_FROM_CSV = {2, 28, 6, 12, 18, 24, 32, 34, 30 } function jsonWrite(vals) local i,v for i,v in ipairs(vals) do JSON_TEMPLATE[JSON_FROM_CSV[i]] = v end return nixio.fs.writefile(JSON_FILE, table.concat(JSON_TEMPLATE)) end function segSplit(line) local retVal = {} local fieldstart = 1 line = line .. ',' repeat local nexti = line:find(',', fieldstart) retVal[#retVal+1] = line:sub(fieldstart, nexti-1) fieldstart = nexti + 1 until fieldstart > line:len() table.remove(retVal, 1) -- remove the segment name return retVal end function segProbeNames(line) local vals = segSplit(line) if #vals < 4 then return end JSON_TEMPLATE[4] = vals[1] JSON_TEMPLATE[10] = vals[2] JSON_TEMPLATE[16] = vals[3] JSON_TEMPLATE[22] = vals[4] end function segRfUpdate(line) local vals = segSplit(line) local idx = 1 while (idx < #vals) do local nodeId = vals[idx] local signalLevel = vals[idx+1] local lastReceive = vals[idx+2] --nixio.syslog("info", ("RF%s: %d last %s"):format(nodeId, math.floor(signalLevel/2.55), lastReceive)) idx = idx + 3 end end local lastUpdate = os.time() function segStateUpdate(line) local vals = segSplit(line) if #vals == 8 then -- If the time has shifted more than 24 hours since the last update -- the clock has probably just been set from 0 (at boot) to actual -- time. Recreate the rrd to prevent a 40 year long graph local time = os.time() if time - lastUpdate > (24*60*60) then nixio.syslog("notice", "Time jumped forward by "..(time-lastUpdate)..", restarting database") rrdCreate() end lastUpdate = time -- Add the time as the first item table.insert(vals, 1, time) jsonWrite(vals) local lid = tonumber(vals[9]) or 0 -- If the lid value is non-zero, it replaces the fan value if lid ~= 0 then vals[7] = lid end table.remove(vals, 9) -- lid table.remove(vals, 8) -- fan avg rrd.update(RRD_FILE, table.concat(vals, ":")) end end local hm = io.open(SERIAL_DEVICE, "rwb") if hm == nil then die("Can not open serial device") end nixio.umask("0022") -- Create database if not nixio.fs.access(RRD_FILE) then rrdCreate() end -- Create json file if not nixio.fs.access("/www/json") then if not nixio.fs.symlink(JSON_FILE, "/www/json") then print("Can not create JSON file link") end end local segmentMap = { ["$HMSU"] = segStateUpdate, ["$HMPN"] = segProbeNames, ["$HMRF"] = segRfUpdate } while true do local hmline = hm:read("*l") if hmline == nil then break end local segmentFunc = segmentMap[hmline:sub(1,5)]; if segmentFunc ~= nil then segmentFunc(hmline) end end hm:close() nixio.fs.unlink("/var/run/linkmeterd/pid")
[lm] Updated to support new setment ID prefixes. Reads probenames and RF manager data too
[lm] Updated to support new setment ID prefixes. Reads probenames and RF manager data too
Lua
mit
kdakers80/HeaterMeter,kdakers80/HeaterMeter,shmick/HeaterMeter,CapnBry/HeaterMeter,dwright134/HeaterMeter,dwright134/HeaterMeter,kdakers80/HeaterMeter,dwright134/HeaterMeter,shmick/HeaterMeter,shmick/HeaterMeter,CapnBry/HeaterMeter,kdakers80/HeaterMeter,dwright134/HeaterMeter,dwright134/HeaterMeter,shmick/HeaterMeter,CapnBry/HeaterMeter,kdakers80/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,CapnBry/HeaterMeter,shmick/HeaterMeter,kdakers80/HeaterMeter,shmick/HeaterMeter,shmick/HeaterMeter,dwright134/HeaterMeter
0453b2dd967918693b0549b4250a147fd7c801fb
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-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 }, { name = "2016-09-19-oauth2_api_id", up = [[ ALTER TABLE oauth2_authorization_codes ADD COLUMN api_id uuid REFERENCES apis (id) ON DELETE CASCADE; ALTER TABLE oauth2_tokens ADD COLUMN api_id uuid REFERENCES apis (id) ON DELETE CASCADE; ]], down = [[ ALTER TABLE oauth2_authorization_codes DROP COLUMN api_id; ALTER TABLE oauth2_tokens DROP COLUMN api_id; ]] }, { name = "2016-12-15-set_global_credentials", up = function(_, _, dao) local rows, err = dao.plugins:find_all({name = "oauth2"}) if err then return err end for _, row in ipairs(rows) do row.config.global_credentials = true local _, err = dao.plugins:update(row, row) if err then return err end end end } }
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 schema.fields.redirect_uri.type = "array" 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-09-19-oauth2_api_id", up = [[ ALTER TABLE oauth2_authorization_codes ADD COLUMN api_id uuid REFERENCES apis (id) ON DELETE CASCADE; ALTER TABLE oauth2_tokens ADD COLUMN api_id uuid REFERENCES apis (id) ON DELETE CASCADE; ]], down = [[ ALTER TABLE oauth2_authorization_codes DROP COLUMN api_id; ALTER TABLE oauth2_tokens DROP COLUMN api_id; ]] }, { name = "2016-12-15-set_global_credentials", up = function(_, _, dao) local rows, err = dao.plugins:find_all({name = "oauth2"}) if err then return err end for _, row in ipairs(rows) do row.config.global_credentials = true local _, err = dao.plugins:update(row, row) if err then return err end end end } }
fix(oauth2) correct array type for redirect_uri
fix(oauth2) correct array type for redirect_uri An OAuth2 migration switches the type of the `redirect_uri` field to `string`. This would break later validations of this field as we expect it to be iterable via `ipairs`. We now correctly switch it back to `array`.
Lua
apache-2.0
Kong/kong,ccyphers/kong,akh00/kong,icyxp/kong,jebenexer/kong,shiprabehera/kong,salazar/kong,Kong/kong,Mashape/kong,Kong/kong,li-wl/kong
7c1cd884d1c8e5d16698ba4ba612e716bec4a824
mod_lastlog/mod_lastlog.lua
mod_lastlog/mod_lastlog.lua
local datamanager = require "util.datamanager"; local jid = require "util.jid"; local time = os.time; local log_ip = module:get_option_boolean("lastlog_ip_address", false); local host = module.host; module:hook("authentication-success", function(event) local session = event.session; if session.username then datamanager.store(session.username, host, "lastlog", { event = "login"; timestamp = time(), ip = log_ip and session.ip or nil, }); end end); module:hook("resource-unbind", function(event) local session = event.session; if session.username then datamanager.store(session.username, host, "lastlog", { event = "logout"; timestamp = time(), ip = log_ip and session.ip or nil, }); end end); module:hook("user-registered", function(event) local session = event.session; datamanager.store(event.username, host, "lastlog", { event = "registered"; timestamp = time(), ip = log_ip and session.ip or nil, }); end); if module:get_host_type() == "component" then module:hook("message/bare", function(event) local room = jid.split(event.stanza.attr.to); if room then datamanager.store(room, module.host, "lastlog", { event = "message"; timestamp = time(), }); end end); elseif module:get_option_boolean("lastlog_stamp_offline") then local datetime = require"util.datetime".datetime; local function offline_stamp(event) local stanza = event.stanza; local node, to_host = jid.split(stanza.attr.from); if to_host == host and event.origin == hosts[host] and stanza.attr.type == "unavailable" then local data = datamanager.load(node, host, "lastlog"); local timestamp = data and data.timestamp; if timestamp then stanza:tag("delay", { xmlns = "urn:xmpp:delay", from = host, stamp = datetime(timestamp), }):up(); end end end module:hook("pre-presence/bare", offline_stamp); module:hook("pre-presence/full", offline_stamp); end function module.command(arg) if not arg[1] or arg[1] == "--help" then require"util.prosodyctl".show_usage([[mod_lastlog <user@host>]], [[Show when user last logged in or out]]); return 1; end local user, host = jid.prepped_split(table.remove(arg, 1)); require"core.storagemanager".initialize_host(host); local lastlog = datamanager.load(user, host, "lastlog"); if lastlog then print(("Last %s: %s"):format(lastlog.event or "login", lastlog.timestamp and os.date("%Y-%m-%d %H:%M:%S", lastlog.timestamp) or "<unknown>")); if lastlog.ip then print("IP address: "..lastlog.ip); end else print("No record found"); return 1; end return 0; end
local datamanager = require "util.datamanager"; local jid = require "util.jid"; local time = os.time; local log_ip = module:get_option_boolean("lastlog_ip_address", false); local host = module.host; module:hook("authentication-success", function(event) local session = event.session; if session.username then datamanager.store(session.username, host, "lastlog", { event = "login"; timestamp = time(), ip = log_ip and session and session.ip or nil, }); end end); module:hook("resource-unbind", function(event) local session = event.session; if session.username then datamanager.store(session.username, host, "lastlog", { event = "logout"; timestamp = time(), ip = log_ip and session and session.ip or nil, }); end end); module:hook("user-registered", function(event) local session = event.session; datamanager.store(event.username, host, "lastlog", { event = "registered"; timestamp = time(), ip = log_ip and session and session.ip or nil, }); end); if module:get_host_type() == "component" then module:hook("message/bare", function(event) local room = jid.split(event.stanza.attr.to); if room then datamanager.store(room, module.host, "lastlog", { event = "message"; timestamp = time(), }); end end); elseif module:get_option_boolean("lastlog_stamp_offline") then local datetime = require"util.datetime".datetime; local function offline_stamp(event) local stanza = event.stanza; local node, to_host = jid.split(stanza.attr.from); if to_host == host and event.origin == hosts[host] and stanza.attr.type == "unavailable" then local data = datamanager.load(node, host, "lastlog"); local timestamp = data and data.timestamp; if timestamp then stanza:tag("delay", { xmlns = "urn:xmpp:delay", from = host, stamp = datetime(timestamp), }):up(); end end end module:hook("pre-presence/bare", offline_stamp); module:hook("pre-presence/full", offline_stamp); end function module.command(arg) if not arg[1] or arg[1] == "--help" then require"util.prosodyctl".show_usage([[mod_lastlog <user@host>]], [[Show when user last logged in or out]]); return 1; end local user, host = jid.prepped_split(table.remove(arg, 1)); require"core.storagemanager".initialize_host(host); local lastlog = datamanager.load(user, host, "lastlog"); if lastlog then print(("Last %s: %s"):format(lastlog.event or "login", lastlog.timestamp and os.date("%Y-%m-%d %H:%M:%S", lastlog.timestamp) or "<unknown>")); if lastlog.ip then print("IP address: "..lastlog.ip); end else print("No record found"); return 1; end return 0; end
mod_lastlog: Fix traceback if no session included with event (eg from mod_register_web) (thanks biszkopcik)
mod_lastlog: Fix traceback if no session included with event (eg from mod_register_web) (thanks biszkopcik)
Lua
mit
prosody-modules/import,softer/prosody-modules,heysion/prosody-modules,obelisk21/prosody-modules,joewalker/prosody-modules,stephen322/prosody-modules,mardraze/prosody-modules,prosody-modules/import,jkprg/prosody-modules,asdofindia/prosody-modules,vince06fr/prosody-modules,olax/prosody-modules,asdofindia/prosody-modules,cryptotoad/prosody-modules,iamliqiang/prosody-modules,syntafin/prosody-modules,dhotson/prosody-modules,crunchuser/prosody-modules,drdownload/prosody-modules,brahmi2/prosody-modules,drdownload/prosody-modules,olax/prosody-modules,apung/prosody-modules,mmusial/prosody-modules,vfedoroff/prosody-modules,obelisk21/prosody-modules,dhotson/prosody-modules,guilhem/prosody-modules,cryptotoad/prosody-modules,iamliqiang/prosody-modules,Craige/prosody-modules,jkprg/prosody-modules,mmusial/prosody-modules,vfedoroff/prosody-modules,NSAKEY/prosody-modules,guilhem/prosody-modules,drdownload/prosody-modules,1st8/prosody-modules,iamliqiang/prosody-modules,drdownload/prosody-modules,Craige/prosody-modules,Craige/prosody-modules,guilhem/prosody-modules,cryptotoad/prosody-modules,softer/prosody-modules,apung/prosody-modules,jkprg/prosody-modules,mmusial/prosody-modules,brahmi2/prosody-modules,cryptotoad/prosody-modules,vince06fr/prosody-modules,amenophis1er/prosody-modules,either1/prosody-modules,softer/prosody-modules,mmusial/prosody-modules,vince06fr/prosody-modules,dhotson/prosody-modules,amenophis1er/prosody-modules,1st8/prosody-modules,asdofindia/prosody-modules,stephen322/prosody-modules,heysion/prosody-modules,Craige/prosody-modules,vfedoroff/prosody-modules,brahmi2/prosody-modules,stephen322/prosody-modules,Craige/prosody-modules,jkprg/prosody-modules,joewalker/prosody-modules,LanceJenkinZA/prosody-modules,apung/prosody-modules,drdownload/prosody-modules,softer/prosody-modules,LanceJenkinZA/prosody-modules,jkprg/prosody-modules,dhotson/prosody-modules,LanceJenkinZA/prosody-modules,BurmistrovJ/prosody-modules,mardraze/prosody-modules,crunchuser/prosody-modules,apung/prosody-modules,syntafin/prosody-modules,joewalker/prosody-modules,syntafin/prosody-modules,apung/prosody-modules,vfedoroff/prosody-modules,mardraze/prosody-modules,stephen322/prosody-modules,asdofindia/prosody-modules,iamliqiang/prosody-modules,syntafin/prosody-modules,joewalker/prosody-modules,prosody-modules/import,NSAKEY/prosody-modules,either1/prosody-modules,syntafin/prosody-modules,obelisk21/prosody-modules,prosody-modules/import,either1/prosody-modules,heysion/prosody-modules,brahmi2/prosody-modules,mardraze/prosody-modules,crunchuser/prosody-modules,dhotson/prosody-modules,either1/prosody-modules,cryptotoad/prosody-modules,1st8/prosody-modules,mardraze/prosody-modules,NSAKEY/prosody-modules,vince06fr/prosody-modules,guilhem/prosody-modules,prosody-modules/import,NSAKEY/prosody-modules,obelisk21/prosody-modules,amenophis1er/prosody-modules,heysion/prosody-modules,iamliqiang/prosody-modules,stephen322/prosody-modules,heysion/prosody-modules,1st8/prosody-modules,BurmistrovJ/prosody-modules,crunchuser/prosody-modules,LanceJenkinZA/prosody-modules,joewalker/prosody-modules,obelisk21/prosody-modules,1st8/prosody-modules,asdofindia/prosody-modules,olax/prosody-modules,either1/prosody-modules,vince06fr/prosody-modules,vfedoroff/prosody-modules,olax/prosody-modules,amenophis1er/prosody-modules,softer/prosody-modules,LanceJenkinZA/prosody-modules,crunchuser/prosody-modules,brahmi2/prosody-modules,olax/prosody-modules,guilhem/prosody-modules,BurmistrovJ/prosody-modules,NSAKEY/prosody-modules,amenophis1er/prosody-modules,BurmistrovJ/prosody-modules,BurmistrovJ/prosody-modules,mmusial/prosody-modules
ac174f6643982e419323a5de43f98a3632d21730
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 local os_time = os.time local nodeprep = require "util.encodings".stringprep.nodeprep module:depends("http") module:set_global() -- Pick up configuration. local set_realm_name = module:get_option_string("reg_servlet_realm", "Restricted") local base_path = module:get_option_string("reg_servlet_base", "/register_account/") local throttle_time = module:get_option_number("reg_servlet_ttime", nil) local whitelist = module:get_option_set("reg_servlet_wl", {}) local blacklist = module:get_option_set("reg_servlet_bl", {}) local recent_ips = {} -- Begin local function http_response(event, code, message, headers) local response = event.response if headers then for header, data in pairs(headers) do response.headers[header] = data end end response.headers.content_type = "application/json" response.status_code = code response:send(message) end local function handle_req(event) local request = event.request local body = request.body if request.method ~= "POST" then return http_response(event, 405, "Bad method...", {["Allow"] = "POST"}) end if not request.headers["authorization"] then return http_response(event, 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(event, 400, "What's this..?") end local user_node, user_host = jid_split(user) if not hosts[user_host] then return http_response(event, 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(event, 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(event, 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(event, 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(event, 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:contains(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:contains(req_body["ip"]) then if not recent_ips[req_body["ip"]] then recent_ips[req_body["ip"]] = os_time() else if os_time() - recent_ips[req_body["ip"]] < throttle_time then recent_ips[req_body["ip"]] = 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 recent_ips[req_body["ip"]] = os_time() end end -- We first check if the supplied username for registration is already there. -- And nodeprep the username local username = nodeprep(req_body["username"]) if not usermanager.user_exists(username, req_body["host"]) then if not username then module:log("debug", "%s supplied an username containing invalid characters: %s", user, username) return http_response(event, 406, "Supplied username contains invalid characters, see RFC 6122.") else local ok, error = usermanager.create_user(username, req_body["password"], req_body["host"]) if ok then hosts[req_body["host"]].events.fire_event("user-registered", { username = username, host = req_body["host"], source = "mod_register_json", session = { ip = req_body["ip"] } }) module:log("debug", "%s registration data submission for %s@%s is successful", user, username, req_body["host"]) return http_response(event, 200, "Done.") else module:log("error", "user creation failed: "..error) return http_response(event 500, "Encountered server error while creating the user: "..error) end end else module:log("debug", "%s registration data submission for %s failed (user already exists)", user, username) return http_response(event, 409, "User already exists.") end end end end -- Set it up! module:provides("http", { default_path = base_path, route = { ["GET /"] = handle_req, ["POST /"] = handle_req } })
-- 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 local os_time = os.time local nodeprep = require "util.encodings".stringprep.nodeprep module:depends("http") module:set_global() -- Pick up configuration. local secure = module:get_option_boolean("reg_servlet_secure", true) local set_realm_name = module:get_option_string("reg_servlet_realm", "Restricted") local base_path = module:get_option_string("reg_servlet_base", "/register_account/") local throttle_time = module:get_option_number("reg_servlet_ttime", nil) local whitelist = module:get_option_set("reg_servlet_wl", {}) local blacklist = module:get_option_set("reg_servlet_bl", {}) local recent_ips = {} -- Begin local function http_response(event, code, message, headers) local response = event.response if headers then for header, data in pairs(headers) do response.headers[header] = data end end response.headers.content_type = "application/json" response.status_code = code response:send(message) end local function handle_req(event) local request = event.request local body = request.body if request.method ~= "POST" then return http_response(event, 405, "Bad method...", {["Allow"] = "POST"}) end if not request.headers["authorization"] then return http_response(event, 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(event, 400, "What's this..?") end local user_node, user_host = jid_split(user) if not hosts[user_host] then return http_response(event, 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(event, 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(event, 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(event, 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(event, 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:contains(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:contains(req_body["ip"]) then if not recent_ips[req_body["ip"]] then recent_ips[req_body["ip"]] = os_time() else if os_time() - recent_ips[req_body["ip"]] < throttle_time then recent_ips[req_body["ip"]] = 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 recent_ips[req_body["ip"]] = os_time() end end -- We first check if the supplied username for registration is already there. -- And nodeprep the username local username = nodeprep(req_body["username"]) if not usermanager.user_exists(username, req_body["host"]) then if not username then module:log("debug", "%s supplied an username containing invalid characters: %s", user, username) return http_response(event, 406, "Supplied username contains invalid characters, see RFC 6122.") else local ok, error = usermanager.create_user(username, req_body["password"], req_body["host"]) if ok then hosts[req_body["host"]].events.fire_event("user-registered", { username = username, host = req_body["host"], source = "mod_register_json", session = { ip = req_body["ip"] } }) module:log("debug", "%s registration data submission for %s@%s is successful", user, username, req_body["host"]) return http_response(event, 200, "Done.") else module:log("error", "user creation failed: "..error) return http_response(event, 500, "Encountered server error while creating the user: "..error) end end else module:log("debug", "%s registration data submission for %s failed (user already exists)", user, username) return http_response(event, 409, "User already exists.") end end end end -- Set it up! module:provides((secure and "https" or "http"), { default_path = base_path, route = { ["GET /"] = handle_req, ["POST /"] = handle_req } })
mod_register_json: fixed typo, added https/http switch and default value to it.
mod_register_json: fixed typo, added https/http switch and default value to it.
Lua
mit
prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2,prosody-modules/import2
905bae0e17888420c6edd1e420df1a2467a49a79
plugins/mod_compression.lua
plugins/mod_compression.lua
-- Prosody IM -- Copyright (C) 2009 Tobias Markmann -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local st = require "util.stanza"; local zlib = require "zlib"; local print = print local xmlns_compression_feature = "http://jabber.org/features/compress" local xmlns_compression_protocol = "http://jabber.org/protocol/compress" local compression_stream_feature = st.stanza("compression", {xmlns=xmlns_compression_feature}):tag("method"):text("zlib"):up(); module:add_event_hook("stream-features", function (session, features) if not session.compressed then features:add_child(compression_stream_feature); end end ); module:add_handler("c2s_unauthed", "compress", xmlns_compression_protocol, function(session, stanza) -- checking if the compression method is supported local method = stanza:child_with_name("method")[1]; if method == "zlib" then session.log("info", method.." compression selected."); session.send(st.stanza("compressed", {xmlns=xmlns_compression_protocol})); session:reset_stream(); -- create deflate and inflate streams local deflate_stream = zlib.deflate(9); local inflate_stream = zlib.inflate(); -- setup compression for session.w local old_send = session.send; session.send = function(t) local compressed, eof = deflate_stream(tostring(t), 'sync'); old_send(compressed); end; -- setup decompression for session.data local function setup_decompression(session) local old_data = session.data session.data = function(conn, data) local decompressed, eof = inflate_stream(data); old_data(conn, decompressed); end; end setup_decompression(session); local session_reset_stream = session.reset_stream; session.reset_stream = function(session) session_reset_stream(session); setup_decompression(session); return true; end; session.compressed = true; else session.log("info", method.." compression selected. But we don't support it."); local error_st = st.stanza("failure", {xmlns=xmlns_compression_protocol}):tag("unsupported-method"); session.send(error_st); end end );
-- Prosody IM -- Copyright (C) 2009 Tobias Markmann -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local st = require "util.stanza"; local zlib = require "zlib"; local print = print local xmlns_compression_feature = "http://jabber.org/features/compress" local xmlns_compression_protocol = "http://jabber.org/protocol/compress" local compression_stream_feature = st.stanza("compression", {xmlns=xmlns_compression_feature}):tag("method"):text("zlib"):up(); module:add_event_hook("stream-features", function (session, features) if not session.compressed then --FIXME only advertise compression support when TLS layer has no compression enabled features:add_child(compression_stream_feature); end end ); module:add_handler("c2s_unauthed", "compress", xmlns_compression_protocol, function(session, stanza) -- checking if the compression method is supported local method = stanza:child_with_name("method")[1]; if method == "zlib" then session.log("info", method.." compression selected."); session.send(st.stanza("compressed", {xmlns=xmlns_compression_protocol})); session:reset_stream(); -- create deflate and inflate streams local deflate_stream = zlib.deflate(9); local inflate_stream = zlib.inflate(); -- setup compression for session.w local old_send = session.send; session.send = function(t) local compressed, eof = deflate_stream(tostring(t), 'sync'); old_send(compressed); end; -- setup decompression for session.data local function setup_decompression(session) local old_data = session.data session.data = function(conn, data) local decompressed, eof = inflate_stream(data); old_data(conn, decompressed); end; end setup_decompression(session); local session_reset_stream = session.reset_stream; session.reset_stream = function(session) session_reset_stream(session); setup_decompression(session); return true; end; session.compressed = true; else session.log("info", method.." compression selected. But we don't support it."); local error_st = st.stanza("failure", {xmlns=xmlns_compression_protocol}):tag("unsupported-method"); session.send(error_st); end end );
Add FIXME to remember TLS compression detection.
Add FIXME to remember TLS compression detection.
Lua
mit
sarumjanuch/prosody,sarumjanuch/prosody
3ae1f86df11c84f75c9dd452a9716a86081c22f9
MMOCoreORB/bin/scripts/managers/jedi/village/village_jedi_manager_township.lua
MMOCoreORB/bin/scripts/managers/jedi/village/village_jedi_manager_township.lua
-- Additional Includes. -- includeFile("village/fs_experience_converter_conv_handler.lua") local ObjectManager = require("managers.object.object_manager") local ScreenPlay = require("screenplays.screenplay") -- Utils. local Logger = require("utils.logger") require("utils.helpers") VillageJediManagerTownship = ScreenPlay:new { screenplayName = "VillageJediManagerTownship" } local currentPhase = Object:new {phase = nil} VILLAGE_CONFIGURATION_FILE_STRING = "./conf/villagephase.txt" VILLAGE_PHASE_ONE = 1 VILLAGE_PHASE_TWO = 2 VILLAGE_PHASE_THREE = 3 VILLAGE_PHASE_FOUR = 4 VILLAGE_TOTAL_NUMBER_OF_PHASES = 4 local VILLAGE_PHASE_CHANGE_TIME = 120 * 1000 -- Testing value. --local VILLAGE_PHASE_CHANGE_TIME = 3 * 7 * 24 * 60 * 60 * 1000 -- Three Weeks. -- Key is the mobile name, value is the spawn parameters. VillagerMobilesPhaseOne = { quharek = {name="quharek",respawn=60, x=5373, z=78, y=-4181, header=0, cellid=0}, whip = {name="whip",respawn=60, x=5283, z=78, y=-4226, header=0, cellid=0}, captain_sarguillo = {name="captain_sarguillo",respawn=60, x=5313, z=78,y= -4161, header=0, cellid=0}, sivarra_mechaux = {name="sivarra_mechaux",respawn=60, x=5391, z=78, y=-4075, header=0, cellid=0} } VillagerMobiles = { paemos = {name="paemos",respawn=60, x=5289, z=78, y=-4149, header=240, cellid=0}, noldan = {name="noldan",respawn=60, x=5243, z=78, y=-4224, header=0, cellid=0} } -- Set the current Village Phase for the first time. function VillageJediManagerTownship.setCurrentPhaseInit() local phaseChange = hasServerEvent("VillagePhaseChange") if (phaseChange == false) then VillageJediManagerTownship.setCurrentPhase(VILLAGE_PHASE_ONE) createServerEvent(VILLAGE_PHASE_CHANGE_TIME, "VillageJediManagerTownship", "switchToNextPhase", "VillagePhaseChange") end end -- Set the current Village Phase. function VillageJediManagerTownship.setCurrentPhase(nextPhase) currentPhase.phase = nextPhase local file = io.open(VILLAGE_CONFIGURATION_FILE_STRING, "w+") file:write(nextPhase) file:flush() file:close() end function VillageJediManagerTownship.getCurrentPhase() if (currentPhase.phase == nil) then local file = io.open(VILLAGE_CONFIGURATION_FILE_STRING) local thePhase = file:read() VillageJediManagerTownship.setCurrentPhase(thePhase) file:close() end return currentPhase.phase end function VillageJediManagerTownship:switchToNextPhase() local currentPhase = VillageJediManagerTownship.getCurrentPhase() VillageJediManagerTownship:despawnMobiles(currentPhase) currentPhase = currentPhase + 1 % VILLAGE_TOTAL_NUMBER_OF_PHASES VillageJediManagerTownship.setCurrentPhase(currentPhase) VillageJediManagerTownship:spawnMobiles(currentPhase) end function VillageJediManagerTownship:start() if (isZoneEnabled("dathomir")) then Logger:log("Starting the Village Township Screenplay.", LT_INFO) VillageJediManagerTownship.setCurrentPhaseInit() VillageJediManagerTownship:spawnMobiles(VillageJediManagerTownship.getCurrentPhase()) end end -- Spawning functions. function VillageJediManagerTownship:spawnMobiles(pCurrentPhase) foreach(VillagerMobiles, function(mobile) local theSpawnedMobile = spawnMobile("dathomir", mobile.name, mobile.respawn, mobile.x, mobile.z, mobile.y, mobile.header, mobile.cellid) Logger:log("Spawning a Village NPC at " .. mobile.x .. " - " .. mobile.y, LT_INFO) ObjectManager.withSceneObject(theSpawnedMobile, function(villageMobile) writeData("village:npc:oid:" .. mobile.name, villageMobile:getObjectID()) Logger:log("Saving a Village NPC with a objectID of " .. villageMobile:getObjectID(), LT_INFO) end) end) if (pCurrentPhase == VILLAGE_PHASE_ONE) then foreach(VillagerMobilesPhaseOne, function(mobile) local theSpawnedMobile = spawnMobile("dathomir", mobile.name, mobile.respawn, mobile.x, mobile.z, mobile.y, mobile.header, mobile.cellid) Logger:log("Spawning a Village NPC at " .. mobile.x .. " - " .. mobile.y, LT_INFO) ObjectManager.withSceneObject(theSpawnedMobile, function(villageMobile) writeData("village:npc:oid:" .. mobile.name, villageMobile:getObjectID()) Logger:log("Saving a Village NPC with a objectID of " .. villageMobile:getObjectID(), LT_INFO) end) end) end end -- Despawn and cleanup all possible mobiles. function VillageJediManagerTownship:despawnMobiles(pCurrentPhase) foreach(VillagerMobiles, function(mobile) local objectID = readData("village:npc:oid:".. mobile.name) local spawnedLookup = getSceneObject(objectID) ObjectManager.withSceneObject(spawnedLookup, function(villageMobile) villageMobile:destroyObjectFromWorld() villageMobile:destroyObjectFromDatabase() deleteData("village:npc:oid:".. mobile.name) Logger:log("Despawning " .. mobile.name, LT_INFO) end) end) foreach(VillagerMobilesPhaseOne, function(mobile) local objectID = readData("village:npc:oid:".. mobile.name) local spawnedLookup = getSceneObject(objectID) ObjectManager.withSceneObject(spawnedLookup, function(villageMobile) villageMobile:destroyObjectFromWorld() villageMobile:destroyObjectFromDatabase() deleteData("village:npc:oid:".. mobile.name) Logger:log("Despawning " .. mobile.name, LT_INFO) end) end) end registerScreenPlay("VillageJediManagerTownship", true) return VillageJediManagerTownship
local ObjectManager = require("managers.object.object_manager") local ScreenPlay = require("screenplays.screenplay") -- Utils. local Logger = require("utils.logger") require("utils.helpers") VillageJediManagerTownship = ScreenPlay:new { screenplayName = "VillageJediManagerTownship" } VILLAGE_PHASE_ONE = 1 VILLAGE_PHASE_TWO = 2 VILLAGE_PHASE_THREE = 3 VILLAGE_PHASE_FOUR = 4 VILLAGE_TOTAL_NUMBER_OF_PHASES = 4 local VILLAGE_PHASE_CHANGE_TIME = 120 * 1000 -- Testing value. --local VILLAGE_PHASE_CHANGE_TIME = 3 * 7 * 24 * 60 * 60 * 1000 -- Three Weeks. -- Key is the mobile name, value is the spawn parameters. VillagerMobilesPhaseOne = { quharek = {name="quharek",respawn=60, x=5373, z=78, y=-4181, header=0, cellid=0}, whip = {name="whip",respawn=60, x=5283, z=78, y=-4226, header=0, cellid=0}, captain_sarguillo = {name="captain_sarguillo",respawn=60, x=5313, z=78,y= -4161, header=0, cellid=0}, sivarra_mechaux = {name="sivarra_mechaux",respawn=60, x=5391, z=78, y=-4075, header=0, cellid=0} } VillagerMobiles = { paemos = {name="paemos",respawn=60, x=5289, z=78, y=-4149, header=240, cellid=0}, noldan = {name="noldan",respawn=60, x=5243, z=78, y=-4224, header=0, cellid=0} } -- Set the current Village Phase for the first time. function VillageJediManagerTownship.setCurrentPhaseInit() local phaseChange = hasServerEvent("VillagePhaseChange") if (phaseChange == false) then VillageJediManagerTownship.setCurrentPhase(VILLAGE_PHASE_ONE) createServerEvent(VILLAGE_PHASE_CHANGE_TIME, "VillageJediManagerTownship", "switchToNextPhase", "VillagePhaseChange") end end -- Set the current Village Phase. function VillageJediManagerTownship.setCurrentPhase(nextPhase) setQuestStatus("Village:CurrentPhase", nextPhase) end function VillageJediManagerTownship.getCurrentPhase() return getQuestStatus("Village:CurrentPhase") end function VillageJediManagerTownship:switchToNextPhase() local currentPhase = VillageJediManagerTownship.getCurrentPhase() VillageJediManagerTownship:despawnMobiles(currentPhase) currentPhase = currentPhase + 1 % VILLAGE_TOTAL_NUMBER_OF_PHASES VillageJediManagerTownship.setCurrentPhase(currentPhase) VillageJediManagerTownship:spawnMobiles(currentPhase) -- Schedule another persistent event. if (not hasServerEvent("VillagePhaseChange")) then createServerEvent(VILLAGE_PHASE_CHANGE_TIME, "VillageJediManagerTownship", "switchToNextPhase", "VillagePhaseChange") end end function VillageJediManagerTownship:start() if (isZoneEnabled("dathomir")) then Logger:log("Starting the Village Township Screenplay.", LT_INFO) VillageJediManagerTownship.setCurrentPhaseInit() VillageJediManagerTownship:spawnMobiles(VillageJediManagerTownship.getCurrentPhase()) end end -- Spawning functions. function VillageJediManagerTownship:spawnMobiles(pCurrentPhase) foreach(VillagerMobiles, function(mobile) local theSpawnedMobile = spawnMobile("dathomir", mobile.name, mobile.respawn, mobile.x, mobile.z, mobile.y, mobile.header, mobile.cellid) Logger:log("Spawning a Village NPC at " .. mobile.x .. " - " .. mobile.y, LT_INFO) ObjectManager.withSceneObject(theSpawnedMobile, function(villageMobile) writeData("village:npc:oid:" .. mobile.name, villageMobile:getObjectID()) Logger:log("Saving a Village NPC with a objectID of " .. villageMobile:getObjectID(), LT_INFO) end) end) if (pCurrentPhase == VILLAGE_PHASE_ONE) then foreach(VillagerMobilesPhaseOne, function(mobile) local theSpawnedMobile = spawnMobile("dathomir", mobile.name, mobile.respawn, mobile.x, mobile.z, mobile.y, mobile.header, mobile.cellid) Logger:log("Spawning a Village NPC at " .. mobile.x .. " - " .. mobile.y, LT_INFO) ObjectManager.withSceneObject(theSpawnedMobile, function(villageMobile) writeData("village:npc:oid:" .. mobile.name, villageMobile:getObjectID()) Logger:log("Saving a Village NPC with a objectID of " .. villageMobile:getObjectID(), LT_INFO) end) end) end end -- Despawn and cleanup all possible mobiles. function VillageJediManagerTownship:despawnMobiles(pCurrentPhase) foreach(VillagerMobiles, function(mobile) local objectID = readData("village:npc:oid:".. mobile.name) local spawnedLookup = getSceneObject(objectID) ObjectManager.withSceneObject(spawnedLookup, function(villageMobile) villageMobile:destroyObjectFromWorld() villageMobile:destroyObjectFromDatabase() deleteData("village:npc:oid:".. mobile.name) Logger:log("Despawning " .. mobile.name, LT_INFO) end) end) foreach(VillagerMobilesPhaseOne, function(mobile) local objectID = readData("village:npc:oid:".. mobile.name) local spawnedLookup = getSceneObject(objectID) ObjectManager.withSceneObject(spawnedLookup, function(villageMobile) villageMobile:destroyObjectFromWorld() villageMobile:destroyObjectFromDatabase() deleteData("village:npc:oid:".. mobile.name) Logger:log("Despawning " .. mobile.name, LT_INFO) end) end) end registerScreenPlay("VillageJediManagerTownship", true) return VillageJediManagerTownship
[fixed] Village phase change event not rescheduling on long server uptime periods, villagephase conf txt now depreciated.
[fixed] Village phase change event not rescheduling on long server uptime periods, villagephase conf txt now depreciated. Change-Id: I83ebac86817ab85acf00c3213a934c9a1f3e1135
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,Tatwi/legend-of-hondo,lasko2112/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
39fe582678d598746a0e1698a48c9771d8adf6a3
icesl-gallery/twisted.lua
icesl-gallery/twisted.lua
--[[ The MIT License (MIT) Copyright (c) 2015 Loïc Fejoz 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. ]] -- Directly applied from http://www.iquilezles.org/www/articles/distfunctions/distfunctions.htm -- See IceSL's forum for the trick to multiply distance by 0.1. h = 20 twisted = implicit(v(-h,-h,0), v(h,h,2*h), [[ float minDistanceSphereTracing=0.001; float distanceEstimator(vec3 ppp) { precision highp float; // translate (0,0,18) vec3 pp = ppp - vec3(0,0,18); // Twist p to pp float c = cos(radians(20.0 * pp.z)); float s = sin(radians(20.0 * pp.z)); mat2 m = mat2(c, -s, s, c); vec3 p = vec3(m * pp.xy, pp.z); // Torus vec2 t = vec2(12.0, 6.0); vec2 q = vec2(length(p.xz)-t.x, p.y); return 0.1 * (length(q)-t.y); } ]]) emit(twisted) e = 1 emit(translate(0, 0, e/2 + 0.220) * box(20, 20, e)) -- the basement -- emit(translate(0, 0, 0.220/2) * box(20, 20, 0.220), 3) -- for slow first layer printing -- emit(cylinder(30, 0.220), 4) -- for contouring
--[[ The MIT License (MIT) Copyright (c) 2015 Loïc Fejoz 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. ]] -- Directly applied from http://www.iquilezles.org/www/articles/distfunctions/distfunctions.htm -- See IceSL's forum for the trick to multiply distance by 0.1. h = 20 twisted = implicit(v(-h,-h,0), v(h,h,2*h), [[ float distanceEstimator(vec3 ppp) { precision highp float; // translate (0,0,18) vec3 pp = ppp - vec3(0,0,18); // Twist p to pp float c = cos(radians(20.0 * pp.z)); float s = sin(radians(20.0 * pp.z)); mat2 m = mat2(c, -s, s, c); vec3 p = vec3(m * pp.xy, pp.z); // Torus vec2 t = vec2(12.0, 6.0); vec2 q = vec2(length(p.xz)-t.x, p.y); return 0.1 * (length(q)-t.y); } ]]) emit(twisted) e = 1 emit(translate(0, 0, e/2 + 0.220) * box(20, 20, e)) -- the basement -- emit(translate(0, 0, 0.220/2) * box(20, 20, 0.220), 3) -- for slow first layer printing -- emit(cylinder(30, 0.220), 4) -- for contouring
fix(twistted): upgrade to latest version
fix(twistted): upgrade to latest version
Lua
mit
loic-fejoz/loic-fejoz-fabmoments,loic-fejoz/loic-fejoz-fabmoments,loic-fejoz/loic-fejoz-fabmoments
52a573ebcc2ae08ca57f15d2b72463c51001d786
src/lua/log.lua
src/lua/log.lua
-- log.lua -- local ffi = require('ffi') ffi.cdef[[ typedef void (*sayfunc_t)(int level, const char *filename, int line, const char *error, const char *format, ...); extern sayfunc_t _say; extern void say_logrotate(int); enum say_level { S_FATAL, S_SYSERROR, S_ERROR, S_CRIT, S_WARN, S_INFO, S_DEBUG }; ]] local function say(level, fmt, ...) local str args = { ... } if not pcall(function() str = string.format(fmt, unpack(args)) end) then str = fmt .. ' [' for i = 1, select('#', ...) do str = str .. select(i, ...) .. ', ' end str = str .. ']' end local frame = debug.getinfo(3, "Sl") local line = 0 local file = 'eval' if type(frame) == 'table' then line = frame.currentline if not line then line = 0 end file = frame.short_src if not file then file = frame.src end if not file then file = 'eval' end end ffi.C._say(level, file, line, nil, str) end return { warn = function (fmt, ...) say(ffi.C.S_WARN, fmt, ...) end, info = function (fmt, ...) say(ffi.C.S_INFO, fmt, ...) end, debug = function (fmt, ...) say(ffi.C.S_DEBUG, fmt, ...) end, error = function (fmt, ...) say(ffi.C.S_ERROR, fmt, ...) end, rotate = function() ffi.C.say_logrotate(0) end, }
-- log.lua -- local ffi = require('ffi') ffi.cdef[[ typedef void (*sayfunc_t)(int level, const char *filename, int line, const char *error, const char *format, ...); extern sayfunc_t _say; extern void say_logrotate(int); enum say_level { S_FATAL, S_SYSERROR, S_ERROR, S_CRIT, S_WARN, S_INFO, S_DEBUG }; ]] local function say(level, fmt, ...) local str = string.format(fmt, ...) local frame = debug.getinfo(3, "Sl") local line = 0 local file = 'eval' if type(frame) == 'table' then line = frame.currentline if not line then line = 0 end file = frame.short_src if not file then file = frame.src end if not file then file = 'eval' end end ffi.C._say(level, file, line, nil, str) end return { warn = function (fmt, ...) say(ffi.C.S_WARN, fmt, ...) end, info = function (fmt, ...) say(ffi.C.S_INFO, fmt, ...) end, debug = function (fmt, ...) say(ffi.C.S_DEBUG, fmt, ...) end, error = function (fmt, ...) say(ffi.C.S_ERROR, fmt, ...) end, rotate = function() ffi.C.say_logrotate(0) end, }
Fix #659: builtin/log.lua: attempt to concatenate a nil value
Fix #659: builtin/log.lua: attempt to concatenate a nil value
Lua
bsd-2-clause
ocelot-inc/tarantool,nvoron23/tarantool,KlonD90/tarantool,mejedi/tarantool,dkorolev/tarantool,Sannis/tarantool,condor-the-bird/tarantool,Sannis/tarantool,condor-the-bird/tarantool,KlonD90/tarantool,rtsisyk/tarantool,condor-the-bird/tarantool,ocelot-inc/tarantool,vasilenkomike/tarantool,guard163/tarantool,Sannis/tarantool,ocelot-inc/tarantool,vasilenkomike/tarantool,nvoron23/tarantool,vasilenkomike/tarantool,nvoron23/tarantool,KlonD90/tarantool,nvoron23/tarantool,vasilenkomike/tarantool,nvoron23/tarantool,ocelot-inc/tarantool,vasilenkomike/tarantool,KlonD90/tarantool,condor-the-bird/tarantool,guard163/tarantool,dkorolev/tarantool,condor-the-bird/tarantool,KlonD90/tarantool,dkorolev/tarantool,rtsisyk/tarantool,dkorolev/tarantool,guard163/tarantool,mejedi/tarantool,Sannis/tarantool,guard163/tarantool,Sannis/tarantool,mejedi/tarantool,nvoron23/tarantool,guard163/tarantool,rtsisyk/tarantool,rtsisyk/tarantool,mejedi/tarantool,dkorolev/tarantool
65d644c923d69a7a06b9426bf56976d7d13c2b00
packages/nn/LookupTable.lua
packages/nn/LookupTable.lua
local LookupTable, parent = torch.class('nn.LookupTable', 'nn.Module') LookupTable.__version = 2 function LookupTable:__init(nIndex, ...) parent.__init(self) if select('#', ...) == 1 and type(select(1, ...)) ~= "number" then local size = select(1, ...) self.size = torch.LongStorage(#size + 1) for i=1,#size do self.size[i+1] = size[i] end else self.size = torch.LongStorage(select('#', ...)+1) for i=1,select('#',...) do self.size[i+1] = select(i, ...) end end self.size[1] = nIndex self.weight = torch.Tensor(self.size) self.gradWeight = torch.Tensor(self.size) self.currentInputs = {} self:reset() end function LookupTable:reset(stdv) stdv = stdv or 1 self.weight:apply(function() return random.normal(0, stdv) end) end function LookupTable:forward(input) local nIndex = input:size(1) self.size[1] = nIndex self.output:resize(self.size) for i=1,nIndex do self.output:select(1, i):copy(self.weight:select(1, input[i])) end return self.output end function LookupTable:zeroGradParameters() for i=1,#self.currentInputs do local currentInput = self.currentInputs[i] for i=1,currentInput:size(1) do self.gradWeight:select(1, currentInput[i]):zero() end self.currentInputs[i] = nil end end function LookupTable:accGradParameters(input, gradOutput, scale) table.insert(self.currentInputs, input.new(input:size()):copy(input)) for i=1,input:size(1) do self.gradWeight:select(1, input[i]):add(scale, gradOutput:select(1, i)) end end function LookupTable:accUpdateGradParameters(input, gradOutput, lr) for i=1,input:size(1) do self.weight:select(1, input[i]):add(-lr, gradOutput:select(1, i)) end end function LookupTable:updateParameters(learningRate) for i=1,#self.currentInputs do local currentInput = self.currentInputs[i] for i=1,currentInput:size(1) do self.weight:select(1, currentInput[i]):add(-learningRate, self.gradWeight:select(1, currentInput[i])) end end end
local LookupTable, parent = torch.class('nn.LookupTable', 'nn.Module') LookupTable.__version = 2 function LookupTable:__init(nIndex, ...) parent.__init(self) if select('#', ...) == 1 and type(select(1, ...)) ~= "number" then local size = select(1, ...) self.size = torch.LongStorage(#size + 1) for i=1,#size do self.size[i+1] = size[i] end else self.size = torch.LongStorage(select('#', ...)+1) for i=1,select('#',...) do self.size[i+1] = select(i, ...) end end self.size[1] = nIndex self.weight = torch.Tensor(self.size) self.gradWeight = torch.Tensor(self.size):zero() self.inputs = {} self:reset() end function LookupTable:reset(stdv) stdv = stdv or 1 self.weight:apply(function() return random.normal(0, stdv) end) end function LookupTable:forward(input) local nIndex = input:size(1) self.size[1] = nIndex self.output:resize(self.size) for i=1,nIndex do self.output:select(1, i):copy(self.weight:select(1, input[i])) end return self.output end function LookupTable:zeroGradParameters() for k,_ in pairs(self.inputs) do self.gradWeight:select(1, k):zero() end self.inputs = {} end function LookupTable:accGradParameters(input, gradOutput, scale) for i=1,input:size(1) do local k = input[i] self.inputs[k] = true self.gradWeight:select(1, k):add(scale, gradOutput:select(1, i)) end end function LookupTable:accUpdateGradParameters(input, gradOutput, lr) for i=1,input:size(1) do self.weight:select(1, input[i]):add(-lr, gradOutput:select(1, i)) end end function LookupTable:updateParameters(learningRate) for k,_ in pairs(self.inputs) do self.weight:select(1, k):add(-learningRate, self.gradWeight:select(1, k)) end end -- we do not need to accumulate parameters when sharing LookupTable.sharedAccUpdateGradParameters = LookupTable.accUpdateGradParameters
Again, bug corrections in LookupTable $%^&*()_
Again, bug corrections in LookupTable $%^&*()_
Lua
bsd-3-clause
soumith/TH,soumith/TH,soumith/TH,soumith/TH
2084cafad4f76c61eb7b40de342270beee72f3c5
luasrc/mch/logger.lua
luasrc/mch/logger.lua
#!/usr/bin/env lua -- -*- lua -*- -- Copyright 2012 Appwill Inc. -- Author : KDr2 -- -- -- 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("mch.logger", package.seeall) logging = require("logging") mchutil = require("mch.util") mchvars = require("mch.vars") function get_logger(appname) local logger = mchvars.get(appname, "__LOGGER") if logger then return logger end local filename = "/dev/stderr" local level = "DEBUG" -- local log_config = mchutil.get_config(appname, "logger") local log_config = mchutil.get_config("logger") if log_config and type(log_config.file) == "string" then filename = log_config.file end if log_config and type(log_config.level) == "string" then level = log_config.level end local f = io.open(filename, "a") if not f then return nil, string.format("file `%s' could not be opened for writing", filename) end f:setvbuf("line") local function log_appender(self, level, message) local date = os.date("%m-%d %H:%M:%S") local frame = debug.getinfo(4) local s = string.format('[%s] [%s] [%s:%d] %s\n', date, level, frame.currentline, message) f:write(s) return true end logger = logging.new(log_appender) logger:setLevel(level) mchvars.set(appname, "__LOGGER", logger) logger._log = logger.log logger._setLevel = logger.setLevel logger.log = function(self, level, ...) local _logger = get_logger(ngx.var.MOOCHINE_APP_NAME) _logger._log(self, level, ...) end logger.setLevel = function(self, level, ...) local _logger = get_logger(ngx.var.MOOCHINE_APP_NAME) _logger:_log("ERROR", "Can not setLevel") end -- for _, l in ipairs(logging.LEVEL) do -- logging does not export this variable :( local levels = {d = "DEBUG", i = "INFO", w = "WARN", e = "ERROR", f = "FATAL"} for k, l in pairs(levels) do logger[k] = function(self, ...) logger.log(self, l, ...) end logger[string.lower(l)] = logger[k] end logger.tostring = logging.tostring logger.table_print = mchutil.table_print return logger end function logger() local logger = get_logger(ngx.var.MOOCHINE_APP_NAME) return logger end
#!/usr/bin/env lua -- -*- lua -*- -- Copyright 2012 Appwill Inc. -- Author : KDr2 -- -- -- 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("mch.logger", package.seeall) logging = require("logging") mchutil = require("mch.util") mchvars = require("mch.vars") function get_logger(appname) local logger = mchvars.get(appname, "__LOGGER") if logger then return logger end local filename = "/dev/stderr" local level = "DEBUG" -- local log_config = mchutil.get_config(appname, "logger") local log_config = mchutil.get_config("logger") if log_config and type(log_config.file) == "string" then filename = log_config.file end if log_config and type(log_config.level) == "string" then level = log_config.level end local f = io.open(filename, "a") if not f then return nil, string.format("file `%s' could not be opened for writing", filename) end f:setvbuf("line") local function log_appender(self, level, message) local date = os.date("%m-%d %H:%M:%S") local frame = debug.getinfo(4) local s = string.format('[%s] [%s] [%s:%d] %s\n', date, level, frame.short_src, frame.currentline, message) f:write(s) return true end logger = logging.new(log_appender) logger:setLevel(level) mchvars.set(appname, "__LOGGER", logger) logger._log = logger.log logger._setLevel = logger.setLevel logger.log = function(self, level, ...) local _logger = get_logger(ngx.var.MOOCHINE_APP_NAME) _logger._log(self, level, ...) end logger.setLevel = function(self, level, ...) local _logger = get_logger(ngx.var.MOOCHINE_APP_NAME) _logger:_log("ERROR", "Can not setLevel") end -- for _, l in ipairs(logging.LEVEL) do -- logging does not export this variable :( local levels = {d = "DEBUG", i = "INFO", w = "WARN", e = "ERROR", f = "FATAL"} for k, l in pairs(levels) do logger[k] = function(self, ...) logger.log(self, l, ...) end logger[string.lower(l)] = logger[k] end logger.tostring = logging.tostring logger.table_print = mchutil.table_print return logger end function logger() local logger = get_logger(ngx.var.MOOCHINE_APP_NAME) return logger end
fix for previous
fix for previous
Lua
apache-2.0
lilien1010/moochine,appwilldev/moochine,lilien1010/moochine,appwilldev/moochine,lilien1010/moochine
28fcb3d74c28aea3bfb6c2f5dcba371312797362
Interface/AddOns/RayUI/modules/misc/altpower.lua
Interface/AddOns/RayUI/modules/misc/altpower.lua
local R, L, P = unpack(select(2, ...)) --Import: Engine, Locales, ProfileDB, local local M = R:GetModule("Misc") local function LoadFunc() local holder = CreateFrame("Frame", "AltPowerBarHolder", UIParent) holder:SetPoint("BOTTOM", UIParent, "BOTTOM", 0, 100) holder:Size(128, 50) PlayerPowerBarAlt:ClearAllPoints() PlayerPowerBarAlt:SetPoint("CENTER", holder, "CENTER") PlayerPowerBarAlt:SetParent(holder) PlayerPowerBarAlt.ignoreFramePositionManager = true R:CreateMover(holder, "AltPowerBarMover", L["副资源条"]) end M:RegisterMiscModule("AltPower", LoadFunc)
local R, L, P = unpack(select(2, ...)) --Import: Engine, Locales, ProfileDB, local local M = R:GetModule("Misc") local function LoadFunc() local holder = CreateFrame("Frame", "AltPowerBarHolder", UIParent) holder:SetPoint("BOTTOM", UIParent, "BOTTOM", 0, 70) holder:Size(128, 50) PlayerPowerBarAlt:ClearAllPoints() PlayerPowerBarAlt:SetPoint("CENTER", holder, "CENTER") PlayerPowerBarAlt:SetParent(holder) PlayerPowerBarAlt.ignoreFramePositionManager = true hooksecurefunc(PlayerPowerBarAlt, "ClearAllPoints", function(self) self:SetPoint('CENTER', AltPowerBarHolder, 'CENTER') end) R:CreateMover(holder, "AltPowerBarMover", L["副资源条"]) end M:RegisterMiscModule("AltPower", LoadFunc)
Fix altpower
Fix altpower
Lua
mit
fgprodigal/RayUI
90fccf236ba6f2a3e9d9782c05e5936f2602e833
[resources]/GTWfastfood/food_c.lua
[resources]/GTWfastfood/food_c.lua
--[[ ******************************************************************************** Project owner: RageQuit community Project name: GTW-RPG Developers: Mr_Moose Source code: https://github.com/GTWCode/GTW-RPG/ Bugtracker: http://forum.404rq.com/bug-reports/ Suggestions: http://forum.404rq.com/mta-servers-development/ Version: Open source License: BSD 2-Clause Status: Stable release ******************************************************************************** ]]-- -- Define the menu GUI window local sx,sy = guiGetScreenSize() local win_menu = exports.GTWgui:createWindow((sx-320)/2, (sy-297)/2, 320, 297, "Well Stacked Pizza Co. Menu", false) guiSetVisible(win_menu, false) -- Define the menu buttons btn_close = guiCreateButton(210,257,100,36,"Close",false,win_menu) btn_choice_1 = guiCreateButton(10,100,160,36, "Buster("..prices[1].."$)",false,win_menu) btn_choice_2 = guiCreateButton(10,217,160,36, "Double D-Luxe("..prices[2].."$)",false,win_menu) btn_choice_3 = guiCreateButton(170,100,160,36, "Full rack("..prices[3].."$)",false,win_menu) btn_choice_4 = guiCreateButton(170,217,160,36, "Sallad meal("..prices[4].."$)",false,win_menu) -- Apply GTWgui styles exports.GTWgui:setDefaultFont(btn_close, 10) exports.GTWgui:setDefaultFont(btn_choice_1, 10) exports.GTWgui:setDefaultFont(btn_choice_2, 10) exports.GTWgui:setDefaultFont(btn_choice_3, 10) exports.GTWgui:setDefaultFont(btn_choice_4, 10) --[[ Update the GUI depending on restaurant type ]]-- function initialize_menu_choices(r_type) -- Set the text and prices on buttons and window title guiSetText(win_menu, menu_choices[r_type]["title"]) guiSetText(btn_choice_1, menu_choices[r_type]["choice_1"][1]..", "..prices[1].."$") guiSetText(btn_choice_2, menu_choices[r_type]["choice_2"][1]..", "..prices[2].."$)") guiSetText(btn_choice_3, menu_choices[r_type]["choice_3"][1]..", "..prices[3].."$)") guiSetText(btn_choice_4, menu_choices[r_type]["choice_4"][1]..", "..prices[4].."$)") -- Destroy current images if any if img1 and isElement(img1) then destroyElement(img1) end if img2 and isElement(img2) then destroyElement(img2) end if img3 and isElement(img3) then destroyElement(img3) end if img4 and isElement(img4) then destroyElement(img4) end -- Make new images, (load from files when needed) img1 = guiCreateStaticImage(10, 23, 160, 77, menu_choices[r_type]["choice_1"][2], false, win_menu) img2 = guiCreateStaticImage(10,140, 160, 77, menu_choices[r_type]["choice_2"][2], false, win_menu) img3 = guiCreateStaticImage(170, 23, 160, 77, menu_choices[r_type]["choice_3"][2], false, win_menu) img4 = guiCreateStaticImage(170, 140, 160, 77, menu_choices[r_type]["choice_4"][2], false, win_menu) end --[[ Open the menu GUI to choose food ]]-- function open_menu(plr, r_type) initialize_menu_choices(r_type) --[[else if img1 and isElement(img1) then destroyElement(img1) end if img2 and isElement(img2) then destroyElement(img2) end if img3 and isElement(img3) then destroyElement(img3) end if img4 and isElement(img4) then destroyElement(img4) end img1 = guiCreateStaticImage(10, 23, 160, 77, "img/PIZHEAL.png", false, win_menu) img2 = guiCreateStaticImage(10, 140, 160, 77, "img/PIZHIG.png", false, win_menu) img3 = guiCreateStaticImage(170, 23, 160, 77, "img/PIZLOW.png", false, win_menu) img4 = guiCreateStaticImage(170, 140, 160, 77, "img/PIZMED.png", false, win_menu) end]] guiSetVisible(win_menu, true) showCursor(true) end addEvent("GTWfastfood.gui.show",true) addEventHandler("GTWfastfood.gui.show", root, open_menu) function close_menu() guiSetVisible(win_menu, false) showCursor(false) end addEvent("GTWfastfood.gui.hide", true) addEventHandler("GTWfastfood.gui.hide", root, close_menu) --[[ Handle menu click ]]-- function menu_click() -- Make sure that the player can afford his food local money = getPlayerMoney(localPlayer) -- Shall we close this menu? if source == btn_close then guiSetVisible(win_menu, false) showCursor(false) return end -- Alright, let's continue shopping, can I take your order? local ID_choice = 1 if source == btn_choice_1 then ID_choice = 1 end if source == btn_choice_2 then ID_choice = 2 end if source == btn_choice_3 then ID_choice = 3 end if source == btn_choice_4 then ID_choice = 4 end -- Take care of the order server side if money > prices[ID_choice] and not isTimer(cooldown) then triggerServerEvent("GTWfastfood.buy", localPlayer, prices[ID_choice], health[ID_choice]) cooldown = setTimer(function() end, 200, 1) end end addEventHandler("onClientGUIClick", root, menu_click) --[[ Protect fastfood workers from being killed ]]-- function protect_worker(attacker) if not getElementData(source, "GTWfastfood.isWorker") then return end cancelEvent() -- cancel any damage done to peds end addEventHandler("onClientPedWasted", root, protect_worker)
--[[ ******************************************************************************** Project owner: RageQuit community Project name: GTW-RPG Developers: Mr_Moose Source code: https://github.com/GTWCode/GTW-RPG/ Bugtracker: http://forum.404rq.com/bug-reports/ Suggestions: http://forum.404rq.com/mta-servers-development/ Version: Open source License: BSD 2-Clause Status: Stable release ******************************************************************************** ]]-- -- Define the menu GUI window local sx,sy = guiGetScreenSize() local win_menu = exports.GTWgui:createWindow((sx-320)/2, (sy-297)/2, 320, 297, "Well Stacked Pizza Co. Menu", false) guiSetVisible(win_menu, false) -- Define the menu buttons btn_close = guiCreateButton(210,257,100,36,"Close",false,win_menu) btn_choice_1 = guiCreateButton(10,100,160,36, "Buster("..prices[1].."$)",false,win_menu) btn_choice_2 = guiCreateButton(10,217,160,36, "Double D-Luxe("..prices[2].."$)",false,win_menu) btn_choice_3 = guiCreateButton(170,100,160,36, "Full rack("..prices[3].."$)",false,win_menu) btn_choice_4 = guiCreateButton(170,217,160,36, "Sallad meal("..prices[4].."$)",false,win_menu) -- Apply GTWgui styles exports.GTWgui:setDefaultFont(btn_close, 10) exports.GTWgui:setDefaultFont(btn_choice_1, 10) exports.GTWgui:setDefaultFont(btn_choice_2, 10) exports.GTWgui:setDefaultFont(btn_choice_3, 10) exports.GTWgui:setDefaultFont(btn_choice_4, 10) --[[ Update the GUI depending on restaurant type ]]-- function initialize_menu_choices(r_type) -- Set the text and prices on buttons and window title guiSetText(win_menu, menu_choices[r_type]["title"]) guiSetText(btn_choice_1, menu_choices[r_type]["choice_1"][1]..", "..prices[1].."$") guiSetText(btn_choice_2, menu_choices[r_type]["choice_2"][1]..", "..prices[2].."$)") guiSetText(btn_choice_3, menu_choices[r_type]["choice_3"][1]..", "..prices[3].."$)") guiSetText(btn_choice_4, menu_choices[r_type]["choice_4"][1]..", "..prices[4].."$)") -- Destroy current images if any if img1 and isElement(img1) then destroyElement(img1) end if img2 and isElement(img2) then destroyElement(img2) end if img3 and isElement(img3) then destroyElement(img3) end if img4 and isElement(img4) then destroyElement(img4) end -- Make new images, (load from files when needed) img1 = guiCreateStaticImage(10, 23, 160, 77, menu_choices[r_type]["choice_1"][2], false, win_menu) img2 = guiCreateStaticImage(10,140, 160, 77, menu_choices[r_type]["choice_2"][2], false, win_menu) img3 = guiCreateStaticImage(170, 23, 160, 77, menu_choices[r_type]["choice_3"][2], false, win_menu) img4 = guiCreateStaticImage(170, 140, 160, 77, menu_choices[r_type]["choice_4"][2], false, win_menu) end --[[ Open the menu GUI to choose food ]]-- function open_menu(plr, r_type) initialize_menu_choices(r_type) guiSetVisible(win_menu, true) showCursor(true) end addEvent("GTWfastfood.gui.show",true) addEventHandler("GTWfastfood.gui.show", root, open_menu) --[[ Close the menu ]]-- function close_menu() guiSetVisible(win_menu, false) showCursor(false) end addEvent("GTWfastfood.gui.hide", true) addEventHandler("GTWfastfood.gui.hide", root, close_menu) --[[ Handle menu click ]]-- function menu_click() -- Make sure that the player can afford his food local money = getPlayerMoney(localPlayer) -- Shall we close this menu? if source == btn_close then guiSetVisible(win_menu, false) showCursor(false) return end -- Alright, let's continue shopping, can I take your order? local ID_choice = 1 if source == btn_choice_1 then ID_choice = 1 end if source == btn_choice_2 then ID_choice = 2 end if source == btn_choice_3 then ID_choice = 3 end if source == btn_choice_4 then ID_choice = 4 end -- Take care of the order server side if money > prices[ID_choice] and not isTimer(cooldown) then triggerServerEvent("GTWfastfood.buy", localPlayer, prices[ID_choice], health[ID_choice]) cooldown = setTimer(function() end, 200, 1) end end addEventHandler("onClientGUIClick", btn_close, menu_click) addEventHandler("onClientGUIClick", btn_choice_1, menu_click) addEventHandler("onClientGUIClick", btn_choice_2, menu_click) addEventHandler("onClientGUIClick", btn_choice_3, menu_click) addEventHandler("onClientGUIClick", btn_choice_4, menu_click) --[[ Protect fastfood workers from being killed ]]-- function protect_worker(attacker) if not getElementData(source, "GTWfastfood.isWorker") then return end cancelEvent() -- cancel any damage done to peds end addEventHandler("onClientPedWasted", root, protect_worker)
[Patch] Fixed a GUI issue triggering the buy function
[Patch] Fixed a GUI issue triggering the buy function Any button would have triggered the buy function before this patch of an earlier update today where implemented.
Lua
bsd-2-clause
404rq/GTW-RPG,SpRoXx/GTW-RPG,404rq/GTW-RPG,404rq/GTW-RPG,GTWCode/GTW-RPG,GTWCode/GTW-RPG,GTWCode/GTW-RPG,SpRoXx/GTW-RPG
190815e984b0df43d36481a9a64a7dd843ff1423
src/extensions/cp/websocket/frame.lua
src/extensions/cp/websocket/frame.lua
--- === cp.websocket.frame === --- --- Implementation of [RFC-6455](https://tools.ietf.org/html/rfc6455), Section 5 --- --- Reads and writes data to and from websocket frame wire protocol data. local log = require "hs.logger" .new "wsframe" local bytes = require "hs.bytes" local bytesToHex = bytes.bytesToHex local hexToBytes = bytes.hexToBytes local int16be = bytes.int16be local int8 = bytes.int8 local remainder = bytes.remainder local uint16be = bytes.uint16be local uint16le = bytes.uint16le local uint24be = bytes.uint24be local uint32be = bytes.uint32be local uint64be = bytes.unit64be local uint8 = bytes.uint8 local stringbyte = string.byte local mod = {} local FIN = 1 << 7 -- 0b10000000 local RSV1 = 1 << 6 -- 0b01000000 local RSV2 = 1 << 5 -- 0b00100000 local RSV3 = 1 << 4 -- 0b00010000 local OPCODE = 0xF -- 0b00001111 local MASK = 1 << 7 -- 0b10000000 local PAYLOAD_LEN = 0x7F -- 0b01111111 local PAYLOAD_16BIT = 126 local PAYLOAD_64BIT = 127 local function isSet(byte, mask) return (byte & mask) == mask end mod.opcode = { continuation = 0x0, text = 0x1, binary = 0x2, -- 0x3-7 reserved for non-control frames close = 0x8, ping = 0x9, pong = 0xA, -- 0xB-F reserved for control frames } -- payloadLen(data, index) -> number, number -- Function -- -- A `bytes` reader function that reads from the data `string`, starting at `index`, -- returning the total payload length and the next byte `index` to read. -- -- Parameters: -- * data - The `string` of bits to read. -- * index - The index to read from (typically `1`) for this field. local function payloadLen(data, index) local payloadLength = bytes.read(data, index, uint8) & PAYLOAD_LEN local nextByte = index + 1 if payloadLength == PAYLOAD_16BIT then payloadLength = bytes.read(data, nextByte, uint16be) nextByte = nextByte + 2 elseif payloadLength == PAYLOAD_64BIT then payloadLength = bytes.read(data, nextByte, uint64be) nextByte = nextByte + 8 end return payloadLength, nextByte end -- maskData(data, maskingKey) -> string -- Function -- -- Masks (and unmasks) the provided data using the provided 4-byte `table`. -- -- Parameters: -- * data - The data `string` to mask or unmmask. -- * maskingKey - The table of 4 1-byte keys. local function maskData(data, maskingKey) local unmasked = {stringbyte(data, 1, #data)} local key = {maskingKey >> 24 & 0x7, maskingKey >> 16 & 0x7, maskingKey >> 8 & 0x7, maskingKey & 0x7} for i = 1, #unmasked do unmasked[i] = unmasked[i] ~ key[i % 4 + 1] end return string.char(table.unpack(unmasked)) end --- cp.websocket.frame.readFrame(data[, extensionLen]) -> frame | nil --- Function --- --- Reads a Websocket Frame from the provided `string` of binary data. --- --- Parameters: --- * data - The `string` of bytes to read from. --- * extensionLen - An optional number indicating the number of expected extension bytes. --- --- Returns: --- * The `string` of binary payload data, or `nil` if the data was invalid. function mod.readFrame(data, extensionLen) if data:len() < 2 then return nil end local frame = {} -- read the FIN/RSV/OPCODE byte local finOp = bytes.read(data, uint8) local nextIndex = 2 frame.fin = isSet(finOp, FIN) frame.rsv1 = isSet(finOp, RSV1) frame.rsv2 = isSet(finOp, RSV2) frame.rsv3 = isSet(finOp, RSV3) -- Reserved bits only allowed if extensions have been negotiated on the handshake. if extensionLen == nil and (frame.rsv1 or frame.rsv2 or frame.rsv3) then return nil end frame.opcode = finOp & OPCODE -- read the MASK frame.mask = isSet(bytes.read(data, nextIndex, uint8), MASK) -- read the full payload length, taking into account extended bytes. frame.payloadLen = bytes.read(data, nextIndex, payloadLen) nextIndex = nextIndex + 1 if frame.mask then frame.maskingKey = bytes.read(data, nextIndex, uint32be) nextIndex = nextIndex + 4 end local payloadData = string:sub(data, nextIndex) if frame.mask then payloadData = maskData(payloadData, frame.maskingKey) end if extensionLen ~= nil then frame.extensionData = payloadData:sub(1, extensionLen) payloadData = payloadData:sub(extensionLen) end frame.applicationData = payloadData return frame end return mod
--- === cp.websocket.frame === --- --- Implementation of [RFC-6455](https://tools.ietf.org/html/rfc6455), Section 5 --- --- Reads and writes data to and from websocket frame wire protocol data. local log = require "hs.logger" .new "wsframe" local bytes = require "hs.bytes" local bytesToHex = bytes.bytesToHex local hexToBytes = bytes.hexToBytes local int16be = bytes.int16be local int8 = bytes.int8 local remainder = bytes.remainder local uint16be = bytes.uint16be local uint16le = bytes.uint16le local uint24be = bytes.uint24be local uint32be = bytes.uint32be local uint64be = bytes.unit64be local uint8 = bytes.uint8 local stringbyte = string.byte local mod = {} local FIN = 1 << 7 -- 0b10000000 local RSV1 = 1 << 6 -- 0b01000000 local RSV2 = 1 << 5 -- 0b00100000 local RSV3 = 1 << 4 -- 0b00010000 local OPCODE = 0xF -- 0b00001111 local MASK = 1 << 7 -- 0b10000000 local PAYLOAD_LEN = 0x7F -- 0b01111111 local PAYLOAD_16BIT = 126 local PAYLOAD_64BIT = 127 local function isSet(byte, mask) return (byte & mask) == mask end mod.opcode = { continuation = 0x0, text = 0x1, binary = 0x2, -- 0x3-7 reserved for non-control frames close = 0x8, ping = 0x9, pong = 0xA, -- 0xB-F reserved for control frames } -- payloadLen(data, index) -> number, number -- Function -- -- A `bytes` reader function that reads from the data `string`, starting at `index`, -- returning the total payload length and the next byte `index` to read. -- -- Parameters: -- * data - The `string` of bits to read. -- * index - The index to read from (typically `1`) for this field. local function payloadLen(data, index) local payloadLength = bytes.read(data, index, uint8) & PAYLOAD_LEN local nextByte = index + 1 if payloadLength == PAYLOAD_16BIT then payloadLength = bytes.read(data, nextByte, uint16be) nextByte = nextByte + 2 elseif payloadLength == PAYLOAD_64BIT then payloadLength = bytes.read(data, nextByte, uint64be) nextByte = nextByte + 8 end return payloadLength, nextByte end -- maskData(data, maskingKey) -> string -- Function -- -- Masks (and unmasks) the provided data using the provided 4-byte `table`. -- -- Parameters: -- * data - The data `string` to mask or unmmask. -- * maskingKey - The table of 4 1-byte keys. local function maskData(data, maskingKey) local unmasked = {stringbyte(data, 1, #data)} local key = {maskingKey >> 24 & 0x7, maskingKey >> 16 & 0x7, maskingKey >> 8 & 0x7, maskingKey & 0x7} for i = 1, #unmasked do unmasked[i] = unmasked[i] ~ key[i % 4 + 1] end return string.char(table.unpack(unmasked)) end --- cp.websocket.frame.readFrame(data[, extensionLen]) -> frame | nil --- Function --- --- Reads a Websocket Frame from the provided `string` of binary data. --- --- Parameters: --- * data - The `string` of bytes to read from. --- * extensionLen - An optional number indicating the number of expected extension bytes. --- --- Returns: --- * The `string` of binary payload data, or `nil` if the data was invalid. function mod.readFrame(data, extensionLen) if data:len() < 2 then return nil end local frame = {} -- read the FIN/RSV/OPCODE byte local finOp = bytes.read(data, uint8) local nextIndex = 2 frame.fin = isSet(finOp, FIN) frame.rsv1 = isSet(finOp, RSV1) frame.rsv2 = isSet(finOp, RSV2) frame.rsv3 = isSet(finOp, RSV3) -- Reserved bits only allowed if extensions have been negotiated on the handshake. if extensionLen == nil and (frame.rsv1 or frame.rsv2 or frame.rsv3) then return nil end frame.opcode = finOp & OPCODE -- read the MASK frame.mask = isSet(bytes.read(data, nextIndex, uint8), MASK) -- read the full payload length, taking into account extended bytes. frame.payloadLen, nextIndex = payloadLen(data, nextIndex) if frame.mask then frame.maskingKey = bytes.read(data, nextIndex, uint32be) nextIndex = nextIndex + 4 end local payloadData = data:sub(nextIndex) if frame.mask then payloadData = maskData(payloadData, frame.maskingKey) end if extensionLen ~= nil then frame.extensionData = payloadData:sub(1, extensionLen) payloadData = payloadData:sub(extensionLen) end frame.applicationData = payloadData return frame end return mod
* Fixed frame.readFrame
* Fixed frame.readFrame
Lua
mit
fcpxhacks/fcpxhacks,CommandPost/CommandPost,CommandPost/CommandPost,fcpxhacks/fcpxhacks,CommandPost/CommandPost
87d2536b75130f4df596b15fd60de065f7aea8d0
mod_push_appserver_fcm/mod_push_appserver_fcm.lua
mod_push_appserver_fcm/mod_push_appserver_fcm.lua
-- mod_push_appserver_fcm -- -- Copyright (C) 2017 Thilo Molitor -- -- This file is MIT/X11 licensed. -- -- Submodule implementing FCM communication -- -- imports local socket = require "socket"; local https = require "ssl.https"; local ltn12 = require "ltn12"; local string = require "string"; local t_remove = table.remove; local datetime = require "util.datetime"; local json = require "util.json"; local pretty = require "pl.pretty"; -- this is the master module module:depends("push_appserver"); -- configuration local fcm_key = module:get_option_string("push_appserver_fcm_key", nil); --push api key (no default) local capath = module:get_option_string("push_appserver_fcm_capath", "/etc/ssl/certs"); --ca path on debian systems local ciphers = module:get_option_string("push_appserver_fcm_ciphers", "ECDHE-RSA-AES256-GCM-SHA384:".. "ECDHE-ECDSA-AES256-GCM-SHA384:".. "ECDHE-RSA-AES128-GCM-SHA256:".. "ECDHE-ECDSA-AES128-GCM-SHA256" ); --supported ciphers local push_ttl = module:get_option_number("push_appserver_fcm_push_ttl", nil); --no ttl (equals 4 weeks) local push_priority = module:get_option_string("push_appserver_fcm_push_priority", "high"); --high priority pushes (can be "high" or "normal") local push_endpoint = "https://fcm.googleapis.com/fcm/send"; -- low level network functions local function socket_tcp() local socket = socket.tcp(); end -- high level network (https) functions local function send_request(data) local respbody = {} -- for the response body prosody.unlock_globals(); -- unlock globals (https.request() tries to access global PROXY) local result, status_code, headers, status_line = https.request({ method = "POST", url = push_endpoint, source = ltn12.source.string(data), headers = { ["authorization"] = "key="..tostring(fcm_key), ["content-type"] = "application/json", ["content-length"] = tostring(#data) }, sink = ltn12.sink.table(respbody), -- luasec tls options mode = "client", protocol = "tlsv1_2", verify = {"peer", "fail_if_no_peer_cert"}, capath = capath, ciphers = ciphers, options = { "no_sslv2", "no_sslv3", "no_ticket", "no_compression", "cipher_server_preference", "single_dh_use", "single_ecdh_use", }, }); prosody.lock_globals(); -- lock globals again if not result then return nil, status_code; end -- status_code contains the error message in case of failure -- return body as string by concatenating table filled by sink return table.concat(respbody), status_code, status_line, headers; end -- handlers local function fcm_handler(event) local settings = event.settings; local data = { ["to"] = tostring(settings["token"]), ["collapse_key"] = "mod_push_appserver_fcm.collapse", ["priority"] = (push_priority=="high" and "high" or "normal"), ["data"] = {}, }; if push_ttl and push_ttl > 0 then data["time_to_live"] = push_ttl; end -- ttl is optional (google's default: 4 weeks) data = json.encode(data); module:log("debug", "sending to %s, json string: %s", push_endpoint, data); local response, status_code, status_line = send_request(data); if not response then module:log("error", "Could not send FCM request: %s", tostring(status_code)); return tostring(status_code); -- return error message end module:log("debug", "response status code: %s, raw response body: %s", tostring(status_code), response); if status_code ~= 200 then local fcm_error; if status_code == 400 then fcm_error="Invalid JSON or unknown fields."; end if status_code == 401 then fcm_error="There was an error authenticating the sender account."; end if status_code >= 500 and status_code < 600 then fcm_error="Internal server error, please retry again later."; end module:log("error", "Got FCM error: %s", fcm_error); return fcm_error; end response = json.decode(response); module:log("debug", "decoded: %s", pretty.write(response)); -- handle errors if response.failure > 0 then module:log("error", "FCM returned %s failures:", tostring(response.failure)); local fcm_error = true; for k, result in pairs(response.results) do if result.error and #result.error then module:log("error", "Got FCM error:", result.error); fcm_error = tostring(result.error); -- return last error to mod_push_appserver end end return fcm_error; end -- handle success for k, result in pairs(response.results) do if result.message_id then module:log("debug", "got FCM message id: '%s'", tostring(result.message_id)); end end return false; -- no error occured end -- setup module:hook("incoming-push-to-fcm", fcm_handler); module:log("info", "Appserver FCM submodule loaded"); function module.unload() if module.unhook then module:unhook("incoming-push-to-fcm", fcm_handler); end module:log("info", "Appserver FCM submodule unloaded"); end
-- mod_push_appserver_fcm -- -- Copyright (C) 2017 Thilo Molitor -- -- This file is MIT/X11 licensed. -- -- Submodule implementing FCM communication -- -- imports -- unlock prosody globals and allow ltn12 to pollute the global space -- this fixes issue #8 in prosody 0.11, see also https://issues.prosody.im/1033 prosody.unlock_globals() require "ltn12"; prosody.lock_globals() local https = require "ssl.https"; local string = require "string"; local t_remove = table.remove; local datetime = require "util.datetime"; local json = require "util.json"; local pretty = require "pl.pretty"; -- this is the master module module:depends("push_appserver"); -- configuration local fcm_key = module:get_option_string("push_appserver_fcm_key", nil); --push api key (no default) local capath = module:get_option_string("push_appserver_fcm_capath", "/etc/ssl/certs"); --ca path on debian systems local ciphers = module:get_option_string("push_appserver_fcm_ciphers", "ECDHE-RSA-AES256-GCM-SHA384:".. "ECDHE-ECDSA-AES256-GCM-SHA384:".. "ECDHE-RSA-AES128-GCM-SHA256:".. "ECDHE-ECDSA-AES128-GCM-SHA256" ); --supported ciphers local push_ttl = module:get_option_number("push_appserver_fcm_push_ttl", nil); --no ttl (equals 4 weeks) local push_priority = module:get_option_string("push_appserver_fcm_push_priority", "high"); --high priority pushes (can be "high" or "normal") local push_endpoint = "https://fcm.googleapis.com/fcm/send"; -- high level network (https) functions local function send_request(data) local respbody = {} -- for the response body prosody.unlock_globals(); -- unlock globals (https.request() tries to access global PROXY) local result, status_code, headers, status_line = https.request({ method = "POST", url = push_endpoint, source = ltn12.source.string(data), headers = { ["authorization"] = "key="..tostring(fcm_key), ["content-type"] = "application/json", ["content-length"] = tostring(#data) }, sink = ltn12.sink.table(respbody), -- luasec tls options mode = "client", protocol = "tlsv1_2", verify = {"peer", "fail_if_no_peer_cert"}, capath = capath, ciphers = ciphers, options = { "no_sslv2", "no_sslv3", "no_ticket", "no_compression", "cipher_server_preference", "single_dh_use", "single_ecdh_use", }, }); prosody.lock_globals(); -- lock globals again if not result then return nil, status_code; end -- status_code contains the error message in case of failure -- return body as string by concatenating table filled by sink return table.concat(respbody), status_code, status_line, headers; end -- handlers local function fcm_handler(event) local settings = event.settings; local data = { ["to"] = tostring(settings["token"]), ["collapse_key"] = "mod_push_appserver_fcm.collapse", ["priority"] = (push_priority=="high" and "high" or "normal"), ["data"] = {}, }; if push_ttl and push_ttl > 0 then data["time_to_live"] = push_ttl; end -- ttl is optional (google's default: 4 weeks) data = json.encode(data); module:log("debug", "sending to %s, json string: %s", push_endpoint, data); local response, status_code, status_line = send_request(data); if not response then module:log("error", "Could not send FCM request: %s", tostring(status_code)); return tostring(status_code); -- return error message end module:log("debug", "response status code: %s, raw response body: %s", tostring(status_code), response); if status_code ~= 200 then local fcm_error; if status_code == 400 then fcm_error="Invalid JSON or unknown fields."; end if status_code == 401 then fcm_error="There was an error authenticating the sender account."; end if status_code >= 500 and status_code < 600 then fcm_error="Internal server error, please retry again later."; end module:log("error", "Got FCM error: %s", fcm_error); return fcm_error; end response = json.decode(response); module:log("debug", "decoded: %s", pretty.write(response)); -- handle errors if response.failure > 0 then module:log("error", "FCM returned %s failures:", tostring(response.failure)); local fcm_error = true; for k, result in pairs(response.results) do if result.error and #result.error then module:log("error", "Got FCM error:", result.error); fcm_error = tostring(result.error); -- return last error to mod_push_appserver end end return fcm_error; end -- handle success for k, result in pairs(response.results) do if result.message_id then module:log("debug", "got FCM message id: '%s'", tostring(result.message_id)); end end return false; -- no error occured end -- setup module:hook("incoming-push-to-fcm", fcm_handler); module:log("info", "Appserver FCM submodule loaded"); function module.unload() if module.unhook then module:unhook("incoming-push-to-fcm", fcm_handler); end module:log("info", "Appserver FCM submodule unloaded"); end
Fix #8 for prosody 0.11
Fix #8 for prosody 0.11 LuaSocket tries to require "ltn12" and pollutes the global space. Prosody prevents this by default and this fix turns of the protection while loading LuaSocket. See also https://issues.prosody.im/1033 for a similar issue
Lua
mit
tmolitor-stud-tu/mod_push_appserver,tmolitor-stud-tu/mod_push_appserver
425e7f73b42a69eb6319460d8d03183cabefd2cd
libs/sgi-webuci/root/usr/lib/boa/luci.lua
libs/sgi-webuci/root/usr/lib/boa/luci.lua
module("luci-plugin", package.seeall) function normalize(path) local newpath while newpath ~= path do if (newpath) then path = newpath end newpath = string.gsub(path, "/[^/]+/../", "/") end return newpath end function init(path) -- NB: path points to ROOT/usr/lib/boa, change it to /usr/lib/lua root = normalize(path .. '/../../../') path = normalize(path .. '/../lua/') package.cpath = path..'?.so;'..package.cpath package.path = path..'?.lua;'..package.path require("luci.dispatcher") require("luci.sgi.webuci") require("uci") if (root ~= '/') then -- Entering dummy mode uci.set_savedir(root..'/tmp/.uci') uci.set_confdir(root..'/etc/config') luci.sys.hostname = function() return "" end luci.sys.loadavg = function() return 0,0,0,0,0 end luci.sys.reboot = function() return end luci.sys.sysinfo = function() return "","","" end luci.sys.syslog = function() return "" end luci.sys.net.arptable = function() return {} end luci.sys.net.devices = function() return {} end luci.sys.net.routes = function() return {} end luci.sys.wifi.getiwconfig = function() return {} end luci.sys.wifi.iwscan = function() return {} end luci.sys.user.checkpasswd = function() return true end end end function prepare_req(uri) luci.dispatcher.createindex() env = {} env.REQUEST_URI = uri -- TODO: setting luci-plugin.reload = true allows this function to trigger a context reload end function handle_req(context) env.SERVER_PROTOCOL = context.server_proto env.REMOTE_ADDR = context.remote_addr env.REQUEST_METHOD = context.request_method env.PATH_INFO = context.uri env.REMOTE_PORT = context.remote_port env.SERVER_ADDR = context.server_addr env.SCRIPT_NAME = env.REQUEST_URI:sub(1, #env.REQUEST_URI - #env.PATH_INFO) luci.sgi.webuci.initenv(env, vars) luci.dispatcher.httpdispatch() end
module("luci-plugin", package.seeall) function normalize(path) local newpath while newpath ~= path do if (newpath) then path = newpath end newpath = string.gsub(path, "/[^/]+/../", "/") end return newpath end function init(path) -- NB: path points to ROOT/usr/lib/boa, change it to /usr/lib/lua root = normalize(path .. '/../../../') path = normalize(path .. '/../lua/') package.cpath = path..'?.so;'..package.cpath package.path = path..'?.lua;'..package.path require("luci.dispatcher") require("luci.sgi.webuci") require("uci") if (root ~= '/') then -- Entering dummy mode uci.set_savedir(root..'/tmp/.uci') uci.set_confdir(root..'/etc/config') luci.sys.hostname = function() return "" end luci.sys.loadavg = function() return 0,0,0,0,0 end luci.sys.reboot = function() return end luci.sys.sysinfo = function() return "","","" end luci.sys.syslog = function() return "" end luci.sys.net.arptable = function() return {} end luci.sys.net.devices = function() return {} end luci.sys.net.routes = function() return {} end luci.sys.wifi.getiwconfig = function() return {} end luci.sys.wifi.iwscan = function() return {} end luci.sys.user.checkpasswd = function() return true end luci.http.basic_auth = function() return true end end end function prepare_req(uri) luci.dispatcher.createindex() env = {} env.REQUEST_URI = uri -- TODO: setting luci-plugin.reload = true allows this function to trigger a context reload end function handle_req(context) env.SERVER_PROTOCOL = context.server_proto env.REMOTE_ADDR = context.remote_addr env.REQUEST_METHOD = context.request_method env.PATH_INFO = context.uri env.REMOTE_PORT = context.remote_port env.SERVER_ADDR = context.server_addr env.SCRIPT_NAME = env.REQUEST_URI:sub(1, #env.REQUEST_URI - #env.PATH_INFO) luci.sgi.webuci.initenv(env, vars) luci.dispatcher.httpdispatch() end
* Fixed host builds
* Fixed host builds
Lua
apache-2.0
8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,8devices/luci,8devices/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci
18b1130711b6ff7aacba98034e2bd7f4893b33df
applications/luci-app-openvpn/luasrc/model/cbi/openvpn-file.lua
applications/luci-app-openvpn/luasrc/model/cbi/openvpn-file.lua
-- Licensed to the public under the Apache License 2.0. local ip = require("luci.ip") local fs = require("nixio.fs") local util = require("luci.util") local uci = require("luci.model.uci").cursor() local cfg_file = uci:get("openvpn", arg[1], "config") local auth_file = cfg_file:match("(.+)%..+").. ".auth" local m = Map("openvpn") local p = m:section( SimpleSection ) p.template = "openvpn/pageswitch" p.mode = "file" p.instance = arg[1] if not cfg_file or not fs.access(cfg_file) then local f = SimpleForm("error", nil, translatef("The OVPN config file (%s) could not be found, please check your configuration.", cfg_file or "n/a")) f:append(Template("openvpn/ovpn_css")) f.reset = false f.submit = false return m, f end if fs.stat(cfg_file).size >= 102400 then f = SimpleForm("error", nil, translatef("The size of the OVPN config file (%s) is too large for online editing in LuCI (&ge; 100 KB). ", cfg_file) .. translate("Please edit this file directly in a terminal session.")) f:append(Template("openvpn/ovpn_css")) f.reset = false f.submit = false return m, f end f = SimpleForm("cfg", nil) f:append(Template("openvpn/ovpn_css")) f.submit = translate("Save") f.reset = false s = f:section(SimpleSection, nil, translatef("Section to modify the OVPN config file (%s)", cfg_file)) file = s:option(TextValue, "data1") file.datatype = "string" file.rows = 20 function file.cfgvalue() return fs.readfile(cfg_file) or "" end function file.write(self, section, data1) return fs.writefile(cfg_file, "\n" .. util.trim(data1:gsub("\r\n", "\n")) .. "\n") end function file.remove(self, section, value) return fs.writefile(cfg_file, "") end function s.handle(self, state, data1) return true end s = f:section(SimpleSection, nil, translatef("Section to add an optional 'auth-user-pass' file with your credentials (%s)", auth_file)) file = s:option(TextValue, "data2") file.datatype = "string" file.rows = 5 function file.cfgvalue() return fs.readfile(auth_file) or "" end function file.write(self, section, data2) return fs.writefile(auth_file, util.trim(data2:gsub("\r\n", "\n")) .. "\n") end function file.remove(self, section, value) return fs.writefile(auth_file, "") end function s.handle(self, state, data2) return true end return m, f
-- Licensed to the public under the Apache License 2.0. local ip = require("luci.ip") local fs = require("nixio.fs") local util = require("luci.util") local uci = require("luci.model.uci").cursor() local cfg_file = uci:get("openvpn", arg[1], "config") local auth_file = cfg_file:match("(.+)%..+").. ".auth" local function makeForm(id, title, desc) local t = Template("openvpn/pageswitch") t.mode = "file" t.instance = arg[1] local f = SimpleForm(id, title, desc) f:append(t) return f end if not cfg_file or not fs.access(cfg_file) then local f = makeForm("error", nil, translatef("The OVPN config file (%s) could not be found, please check your configuration.", cfg_file or "n/a")) f:append(Template("openvpn/ovpn_css")) f.reset = false f.submit = false return f end if fs.stat(cfg_file).size >= 102400 then local f = makeForm("error", nil, translatef("The size of the OVPN config file (%s) is too large for online editing in LuCI (&ge; 100 KB). ", cfg_file) .. translate("Please edit this file directly in a terminal session.")) f:append(Template("openvpn/ovpn_css")) f.reset = false f.submit = false return f end f = makeForm("cfg", nil) f:append(Template("openvpn/ovpn_css")) f.submit = translate("Save") f.reset = false s = f:section(SimpleSection, nil, translatef("Section to modify the OVPN config file (%s)", cfg_file)) file = s:option(TextValue, "data1") file.datatype = "string" file.rows = 20 function file.cfgvalue() return fs.readfile(cfg_file) or "" end function file.write(self, section, data1) return fs.writefile(cfg_file, "\n" .. util.trim(data1:gsub("\r\n", "\n")) .. "\n") end function file.remove(self, section, value) return fs.writefile(cfg_file, "") end function s.handle(self, state, data1) return true end s = f:section(SimpleSection, nil, translatef("Section to add an optional 'auth-user-pass' file with your credentials (%s)", auth_file)) file = s:option(TextValue, "data2") file.datatype = "string" file.rows = 5 function file.cfgvalue() return fs.readfile(auth_file) or "" end function file.write(self, section, data2) return fs.writefile(auth_file, util.trim(data2:gsub("\r\n", "\n")) .. "\n") end function file.remove(self, section, value) return fs.writefile(auth_file, "") end function s.handle(self, state, data2) return true end return f
luci-app-openvpn: fix stray uci permission warning
luci-app-openvpn: fix stray uci permission warning The OpenVPN file view uses a dummy Map() instance to render the breadcrumb template which triggers a uci permission error since the view is being rendered by a form() action which does not set up the expected permission flags. CBI Map() instances should only be used for cbi() dispatch targets. Solve the issue by appending the breadcrumb template directly to the SimpleForm() instance and by removing the redundant dummy Map() instance. Fixes: #4370 Signed-off-by: Jo-Philipp Wich <bd73d35759d75cc215150d1bbc94f1b1078bee01@mein.io>
Lua
apache-2.0
hnyman/luci,hnyman/luci,hnyman/luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,openwrt/luci,lbthomsen/openwrt-luci,openwrt/luci,hnyman/luci,lbthomsen/openwrt-luci,lbthomsen/openwrt-luci,hnyman/luci,hnyman/luci,openwrt/luci,hnyman/luci,hnyman/luci,openwrt/luci,openwrt/luci,openwrt/luci,openwrt/luci,openwrt/luci
d36a3eabddc9c3ac4019f68914804bec67225478
nvim/lua/mappings.lua
nvim/lua/mappings.lua
local g = vim.g -- a table to access global variables -- see https://github.com/numToStr/Comment.nvim/issues/14#issuecomment-939230851 -- visual comment with custom keyboard shortcut local Ut = require('Comment.utils') local Op = require('Comment.opfunc') function _G.__toggle_visual(vmode) local lcs, rcs = Ut.unwrap_cstr(vim.bo.commentstring) local srow, erow, lines = Ut.get_lines(vmode, Ut.ctype.line) Op.linewise({ cfg = { padding = true, ignore = nil }, cmode = Ut.cmode.toggle, lines = lines, lcs = lcs, rcs = rcs, srow = srow, erow = erow, }) end -- end visual comment local function map(mode, lhs, rhs, opts) local options = { noremap = true } if opts then options = vim.tbl_extend('force', options, opts) end vim.api.nvim_set_keymap(mode, lhs, rhs, options) end function _G.set_terminal_keymaps() local opts = { noremap = true } vim.api.nvim_buf_set_keymap(0, 't', '<esc>', [[<C-\><C-n>]], opts) vim.api.nvim_buf_set_keymap(0, 't', 'jk', [[<C-\><C-n>]], opts) vim.api.nvim_buf_set_keymap(0, 't', '<C-h>', [[<C-\><C-n><C-W>h]], opts) vim.api.nvim_buf_set_keymap(0, 't', '<C-j>', [[<C-\><C-n><C-W>j]], opts) vim.api.nvim_buf_set_keymap(0, 't', '<C-k>', [[<C-\><C-n><C-W>k]], opts) vim.api.nvim_buf_set_keymap(0, 't', '<C-l>', [[<C-\><C-n><C-W>l]], opts) end -- toggle showing whitespace map('n', '<leader>s', ':set nolist!<cr>', { silent = true }) map('n', 'J', '<c-d>') map('x', 'J', '<c-d>') map('n', 'K', '<c-u>') map('x', 'K', '<c-u>') -- up/down work as expected with word wrapping on map('n', 'j', 'gj') map('n', 'k', 'gk') map('n', 'gj', 'j') map('n', 'gj', 'j') map('', 'H', '^') map('', 'L', '$') -- clear search highlighting map('n', '<esc>', ':nohlsearch<cr><esc>', { silent = true }) if not g.vscode then map('', '\\\\', '<esc><cmd>lua __toggle_visual(vim.fn.visualmode())<cr>', { silent = true }) map('', '<c-l>', ':Telescope buffers<cr>') map('', '<c-p>', ':Telescope find_files<cr>') map('n', '<S-l>', ':BufferLineCycleNext<CR>') map('n', '<S-h>', ':BufferLineCyclePrev<CR>') vim.cmd('autocmd! TermOpen term://* lua set_terminal_keymaps()') local wk = require('which-key') wk.register({ f = { '<cmd>Telescope live_grep<cr>', 'Live ripgrep search' }, r = { '<cmd>Telescope oldfiles<cr>', 'Find recently opened files' }, d = { '<cmd>NvimTreeToggle<cr>', 'Toggle directory tree' }, -- Packer p = { name = 'Packer', c = { '<cmd>PackerCompile<cr>', 'Compile' }, i = { '<cmd>PackerInstall<cr>', 'Install' }, r = { "<cmd>lua require('lvim.plugin-loader').recompile()<cr>", 'Re-compile' }, s = { '<cmd>PackerSync<cr>', 'Sync' }, S = { '<cmd>PackerStatus<cr>', 'Status' }, u = { '<cmd>PackerUpdate<cr>', 'Update' }, }, -- Git g = { name = 'Git', j = { "<cmd>lua require 'gitsigns'.next_hunk()<cr>", 'Next Hunk' }, k = { "<cmd>lua require 'gitsigns'.prev_hunk()<cr>", 'Prev Hunk' }, l = { "<cmd>lua require 'gitsigns'.blame_line()<cr>", 'Blame' }, p = { "<cmd>lua require 'gitsigns'.preview_hunk()<cr>", 'Preview Hunk' }, r = { "<cmd>lua require 'gitsigns'.reset_hunk()<cr>", 'Reset Hunk' }, R = { "<cmd>lua require 'gitsigns'.reset_buffer()<cr>", 'Reset Buffer' }, s = { "<cmd>lua require 'gitsigns'.stage_hunk()<cr>", 'Stage Hunk' }, u = { "<cmd>lua require 'gitsigns'.undo_stage_hunk()<cr>", 'Undo Stage Hunk', }, o = { '<cmd>Telescope git_status<cr>', 'Open changed file' }, b = { '<cmd>Telescope git_branches<cr>', 'Checkout branch' }, c = { '<cmd>Telescope git_commits<cr>', 'Checkout commit' }, C = { '<cmd>Telescope git_bcommits<cr>', 'Checkout commit(for current file)', }, d = { '<cmd>Gitsigns diffthis HEAD<cr>', 'Git Diff', }, }, -- LSP l = { name = 'LSP', a = { "<cmd>lua require('lvim.core.telescope').code_actions()<cr>", 'Code Action' }, d = { '<cmd>Telescope lsp_document_diagnostics<cr>', 'Document Diagnostics', }, w = { '<cmd>Telescope lsp_workspace_diagnostics<cr>', 'Workspace Diagnostics', }, f = { '<cmd>lua vim.lsp.buf.formatting()<cr>', 'Format' }, i = { '<cmd>LspInfo<cr>', 'Info' }, I = { '<cmd>LspInstallInfo<cr>', 'Installer Info' }, j = { '<cmd>lua vim.lsp.diagnostic.goto_next({popup_opts = {border = lvim.lsp.popup_border}})<cr>', 'Next Diagnostic', }, k = { '<cmd>lua vim.lsp.diagnostic.goto_prev({popup_opts = {border = lvim.lsp.popup_border}})<cr>', 'Prev Diagnostic', }, l = { '<cmd>lua vim.lsp.codelens.run()<cr>', 'CodeLens Action' }, p = { name = 'Peek', d = { "<cmd>lua require('lvim.lsp.peek').Peek('definition')<cr>", 'Definition' }, t = { "<cmd>lua require('lvim.lsp.peek').Peek('typeDefinition')<cr>", 'Type Definition' }, i = { "<cmd>lua require('lvim.lsp.peek').Peek('implementation')<cr>", 'Implementation' }, }, q = { '<cmd>lua vim.lsp.diagnostic.set_loclist()<cr>', 'Quickfix' }, r = { '<cmd>lua vim.lsp.buf.rename()<cr>', 'Rename' }, s = { '<cmd>Telescope lsp_document_symbols<cr>', 'Document Symbols' }, S = { '<cmd>Telescope lsp_dynamic_workspace_symbols<cr>', 'Workspace Symbols', }, }, -- Trouble toggling t = { name = 'Diagnostics', t = { '<cmd>TroubleToggle<cr>', 'trouble' }, w = { '<cmd>TroubleToggle lsp_workspace_diagnostics<cr>', 'workspace' }, d = { '<cmd>TroubleToggle lsp_document_diagnostics<cr>', 'document' }, q = { '<cmd>TroubleToggle quickfix<cr>', 'quickfix' }, l = { '<cmd>TroubleToggle loclist<cr>', 'loclist' }, r = { '<cmd>TroubleToggle lsp_references<cr>', 'references' }, }, }, { prefix = '<leader>', }) end
local g = vim.g -- a table to access global variables local function map(mode, lhs, rhs, opts) local options = { noremap = true } if opts then options = vim.tbl_extend('force', options, opts) end vim.api.nvim_set_keymap(mode, lhs, rhs, options) end function _G.set_terminal_keymaps() local opts = { noremap = true } vim.api.nvim_buf_set_keymap(0, 't', '<esc>', [[<C-\><C-n>]], opts) vim.api.nvim_buf_set_keymap(0, 't', 'jk', [[<C-\><C-n>]], opts) vim.api.nvim_buf_set_keymap(0, 't', '<C-h>', [[<C-\><C-n><C-W>h]], opts) vim.api.nvim_buf_set_keymap(0, 't', '<C-j>', [[<C-\><C-n><C-W>j]], opts) vim.api.nvim_buf_set_keymap(0, 't', '<C-k>', [[<C-\><C-n><C-W>k]], opts) vim.api.nvim_buf_set_keymap(0, 't', '<C-l>', [[<C-\><C-n><C-W>l]], opts) end -- toggle showing whitespace map('n', '<leader>s', ':set nolist!<cr>', { silent = true }) map('n', 'J', '<c-d>') map('x', 'J', '<c-d>') map('n', 'K', '<c-u>') map('x', 'K', '<c-u>') -- up/down work as expected with word wrapping on map('n', 'j', 'gj') map('n', 'k', 'gk') map('n', 'gj', 'j') map('n', 'gj', 'j') map('', 'H', '^') map('', 'L', '$') -- clear search highlighting map('n', '<esc>', ':nohlsearch<cr><esc>', { silent = true }) if not g.vscode then map('', '\\\\', '<esc><CMD>lua require("Comment.api").toggle_linewise_op(vim.fn.visualmode())<CR>', { silent = true }) map('', '<c-l>', ':Telescope buffers<cr>') map('', '<c-p>', ':Telescope find_files<cr>') map('n', '<S-l>', ':BufferLineCycleNext<CR>') map('n', '<S-h>', ':BufferLineCyclePrev<CR>') vim.cmd('autocmd! TermOpen term://* lua set_terminal_keymaps()') local wk = require('which-key') wk.register({ f = { '<cmd>Telescope live_grep<cr>', 'Live ripgrep search' }, r = { '<cmd>Telescope oldfiles<cr>', 'Find recently opened files' }, d = { '<cmd>NvimTreeToggle<cr>', 'Toggle directory tree' }, -- Packer p = { name = 'Packer', c = { '<cmd>PackerCompile<cr>', 'Compile' }, i = { '<cmd>PackerInstall<cr>', 'Install' }, r = { "<cmd>lua require('lvim.plugin-loader').recompile()<cr>", 'Re-compile' }, s = { '<cmd>PackerSync<cr>', 'Sync' }, S = { '<cmd>PackerStatus<cr>', 'Status' }, u = { '<cmd>PackerUpdate<cr>', 'Update' }, }, -- Git g = { name = 'Git', j = { "<cmd>lua require 'gitsigns'.next_hunk()<cr>", 'Next Hunk' }, k = { "<cmd>lua require 'gitsigns'.prev_hunk()<cr>", 'Prev Hunk' }, l = { "<cmd>lua require 'gitsigns'.blame_line()<cr>", 'Blame' }, p = { "<cmd>lua require 'gitsigns'.preview_hunk()<cr>", 'Preview Hunk' }, r = { "<cmd>lua require 'gitsigns'.reset_hunk()<cr>", 'Reset Hunk' }, R = { "<cmd>lua require 'gitsigns'.reset_buffer()<cr>", 'Reset Buffer' }, s = { "<cmd>lua require 'gitsigns'.stage_hunk()<cr>", 'Stage Hunk' }, u = { "<cmd>lua require 'gitsigns'.undo_stage_hunk()<cr>", 'Undo Stage Hunk', }, o = { '<cmd>Telescope git_status<cr>', 'Open changed file' }, b = { '<cmd>Telescope git_branches<cr>', 'Checkout branch' }, c = { '<cmd>Telescope git_commits<cr>', 'Checkout commit' }, C = { '<cmd>Telescope git_bcommits<cr>', 'Checkout commit(for current file)', }, d = { '<cmd>Gitsigns diffthis HEAD<cr>', 'Git Diff', }, }, -- LSP l = { name = 'LSP', a = { "<cmd>lua require('lvim.core.telescope').code_actions()<cr>", 'Code Action' }, d = { '<cmd>Telescope lsp_document_diagnostics<cr>', 'Document Diagnostics', }, w = { '<cmd>Telescope lsp_workspace_diagnostics<cr>', 'Workspace Diagnostics', }, f = { '<cmd>lua vim.lsp.buf.formatting()<cr>', 'Format' }, i = { '<cmd>LspInfo<cr>', 'Info' }, I = { '<cmd>LspInstallInfo<cr>', 'Installer Info' }, j = { '<cmd>lua vim.lsp.diagnostic.goto_next({popup_opts = {border = lvim.lsp.popup_border}})<cr>', 'Next Diagnostic', }, k = { '<cmd>lua vim.lsp.diagnostic.goto_prev({popup_opts = {border = lvim.lsp.popup_border}})<cr>', 'Prev Diagnostic', }, l = { '<cmd>lua vim.lsp.codelens.run()<cr>', 'CodeLens Action' }, p = { name = 'Peek', d = { "<cmd>lua require('lvim.lsp.peek').Peek('definition')<cr>", 'Definition' }, t = { "<cmd>lua require('lvim.lsp.peek').Peek('typeDefinition')<cr>", 'Type Definition' }, i = { "<cmd>lua require('lvim.lsp.peek').Peek('implementation')<cr>", 'Implementation' }, }, q = { '<cmd>lua vim.lsp.diagnostic.set_loclist()<cr>', 'Quickfix' }, r = { '<cmd>lua vim.lsp.buf.rename()<cr>', 'Rename' }, s = { '<cmd>Telescope lsp_document_symbols<cr>', 'Document Symbols' }, S = { '<cmd>Telescope lsp_dynamic_workspace_symbols<cr>', 'Workspace Symbols', }, }, -- Trouble toggling t = { name = 'Diagnostics', t = { '<cmd>TroubleToggle<cr>', 'trouble' }, w = { '<cmd>TroubleToggle lsp_workspace_diagnostics<cr>', 'workspace' }, d = { '<cmd>TroubleToggle lsp_document_diagnostics<cr>', 'document' }, q = { '<cmd>TroubleToggle quickfix<cr>', 'quickfix' }, l = { '<cmd>TroubleToggle loclist<cr>', 'loclist' }, r = { '<cmd>TroubleToggle lsp_references<cr>', 'references' }, }, }, { prefix = '<leader>', }) end
fix: issue with manual commenting map
fix: issue with manual commenting map
Lua
mit
drmohundro/dotfiles
c5d9497dbb086f0fc9536e2992851b1b33c45445
.config/awesome/widgets/battery.lua
.config/awesome/widgets/battery.lua
local wibox = require("wibox") local awful = require("awful") local gears = require("gears") local naughty = require("naughty") local beautiful = require("beautiful") -- Create a widget and update its content using the output of a shell -- command every 10 seconds: local battery = {} local battery_widget = wibox.widget { { min_value = 0, max_value = 100, value = 0, paddings = 2, border_width = 0, forced_width = 30, forced_height = 0, border_color = "#000000", color = "#76fc98", background_color = "#488e5a", --shape = gears.shape.rounded_bar, id = "mypb0", widget = wibox.widget.progressbar, }, { min_value = 0, max_value = 100, value = 0, paddings = 2, border_width = 0, forced_width = 30, forced_height = 0, border_color = "#000000", color = "#76fc98", background_color = "#488e5a", --shape = gears.shape.rounded_bar, id = "mypb1", widget = wibox.widget.progressbar, }, --{ --id = "mytb", --text = "100%", --font = "Iosevka 6", --widget = wibox.widget.textbox, --align = 'center', --valign = 'center', ----color = "#000000", --}, layout = wibox.layout.align.horizontal, set_battery = function(self, val0, val1) --self.mytb.text = tonumber(val).."%" self.mypb0.value = tonumber(val0) self.mypb1.value = tonumber(val1) end, } local function read_file(path) local file = io.open(path, "rb") -- r read mode and b binary mode if not file then return nil end local content = file:read "*a" -- *a or *all reads the whole file file:close() return content end local function get_battery_status() local bat0 = read_file("/sys/class/power_supply/BAT0/capacity") local bat1 = read_file("/sys/class/power_supply/BAT1/capacity") battery_widget:set_battery(bat0, bat1) end local battery_timer = gears.timer.start_new(10, function() -- battery_widget:set_battery("90") -- naughty.notify({text="battery"}) get_battery_status() return true end ) get_battery_status() return battery_widget
local wibox = require("wibox") local awful = require("awful") local gears = require("gears") local naughty = require("naughty") local beautiful = require("beautiful") -- Create a widget and update its content using the output of a shell -- command every 10 seconds: local battery = {} local battery_widget = wibox.widget { { min_value = 0, max_value = 100, value = 0, paddings = 2, border_width = 0, forced_width = 30, forced_height = 0, border_color = "#000000", color = "#76fc98", background_color = "#488e5a", --shape = gears.shape.rounded_bar, id = "mypb0", widget = wibox.widget.progressbar, }, { min_value = 0, max_value = 100, value = 0, paddings = 2, border_width = 0, forced_width = 30, forced_height = 0, border_color = "#000000", color = "#76fc98", background_color = "#488e5a", --shape = gears.shape.rounded_bar, id = "mypb1", widget = wibox.widget.progressbar, }, --{ --id = "mytb", --text = "100%", --font = "Iosevka 6", --widget = wibox.widget.textbox, --align = 'center', --valign = 'center', ----color = "#000000", --}, layout = wibox.layout.align.horizontal, set_battery = function(self, val0, val1) --self.mytb.text = tonumber(val).."%" self.mypb0.value = tonumber(val0) self.mypb1.value = tonumber(val1) end, } local function read_file(path) local file = io.open(path, "rb") -- r read mode and b binary mode if not file then return nil end local content = file:read("*all") -- *a or *all reads the whole file file:close() return content end local function get_battery_status() local bat0 = read_file("/sys/class/power_supply/BAT0/capacity") local bat1 = read_file("/sys/class/power_supply/BAT1/capacity") battery_widget:set_battery(bat0, bat1) end local battery_timer = gears.timer.start_new(10, function() -- battery_widget:set_battery("90") -- naughty.notify({text="battery"}) get_battery_status() return true end ) local function show_battery_status() local fd = io.popen("acpi") local acpi_output = fd:read("*all") fd:close() return acpi_output end local battery_tooltip = awful.tooltip({ objects = { battery_widget }, timer_function = show_battery_status}) get_battery_status() return battery_widget
AwesomeWM: Fix battery tooltip
AwesomeWM: Fix battery tooltip
Lua
mit
hershsingh/dotfiles,hershsingh/dotfiles
f471a2f900c289bfed4c84a6fbaa36efb29b9ad6
src/plugins/core/tools/caffeinate.lua
src/plugins/core/tools/caffeinate.lua
--- === plugins.core.tools.caffeinate === --- --- Prevents your Mac from going to sleep. local require = require --local log = require("hs.logger").new("caffeinate") local caffeinate = require "hs.caffeinate" local config = require "cp.config" local i18n = require "cp.i18n" local enabled = config.prop("caffeinate.enabled", false):watch(function(value) if value then --log.df("Caffinate Enabled!") caffeinate.set("displayIdle", true) caffeinate.set("systemIdle", true) caffeinate.set("system", true) else --log.df("Caffinate Disabled!") caffeinate.set("displayIdle", false) caffeinate.set("systemIdle", false) caffeinate.set("system", false) end end) local plugin = { id = "core.tools.caffeinate", group = "core", dependencies = { ["core.menu.manager"] = "menu", ["core.commands.global"] = "global", } } function plugin.init(deps) -------------------------------------------------------------------------------- -- Add menu items: -------------------------------------------------------------------------------- local menu = deps.menu menu.tools :addItem(1, function() return { title = i18n("preventMacFromSleeping"), fn = function() enabled:toggle() end, checked = enabled() } end) -------------------------------------------------------------------------------- -- Add actions: -------------------------------------------------------------------------------- local global = deps.global global :add("enablePreventMacFromSleeping") :whenActivated(function() enabled:value(true) end) :titled(i18n("enable") .. " " .. i18n("preventMacFromSleeping")) global :add("disablePreventMacFromSleeping") :whenActivated(function() enabled:value(false) end) :titled(i18n("disable") .. " " .. i18n("preventMacFromSleeping")) global :add("togglePreventMacFromSleeping") :whenActivated(function() enabled:toggle() end) :titled(i18n("toggle") .. " " .. i18n("preventMacFromSleeping")) -------------------------------------------------------------------------------- -- Force an update: -------------------------------------------------------------------------------- enabled:update() end return plugin
--- === plugins.core.tools.caffeinate === --- --- Prevents your Mac from going to sleep. local require = require --local log = require("hs.logger").new("caffeinate") local caffeinate = require "hs.caffeinate" local config = require "cp.config" local i18n = require "cp.i18n" local enabled = config.prop("caffeinate.enabled", false):watch(function(value) if value then --log.df("Caffinate Enabled!") caffeinate.set("displayIdle", true) caffeinate.set("systemIdle", true) caffeinate.set("system", true) else --log.df("Caffinate Disabled!") caffeinate.set("displayIdle", false) caffeinate.set("systemIdle", false) caffeinate.set("system", false) end end) local plugin = { id = "core.tools.caffeinate", group = "core", dependencies = { ["core.menu.manager"] = "menu", ["core.commands.global"] = "global", } } function plugin.init(deps) -------------------------------------------------------------------------------- -- Add menu items: -------------------------------------------------------------------------------- local menu = deps.menu menu.tools :addItem(1, function() return { title = i18n("preventMacFromSleeping"), fn = function() enabled:toggle() end, checked = enabled() } end) -------------------------------------------------------------------------------- -- Add actions: -------------------------------------------------------------------------------- local global = deps.global global :add("enablePreventMacFromSleeping") :whenActivated(function() enabled:value(true) end) :titled(i18n("enable") .. " " .. i18n("preventMacFromSleeping")) global :add("disablePreventMacFromSleeping") :whenActivated(function() enabled:value(false) end) :titled(i18n("disable") .. " " .. i18n("preventMacFromSleeping")) global :add("togglePreventMacFromSleeping") :whenActivated(function() enabled:toggle() end) :titled(i18n("toggle") .. " " .. i18n("preventMacFromSleeping")) -------------------------------------------------------------------------------- -- Force an update: -------------------------------------------------------------------------------- enabled:update() end return plugin
Fix formatting
Fix formatting
Lua
mit
CommandPost/CommandPost,CommandPost/CommandPost,CommandPost/CommandPost
bcc5e06753cb854bb6a12dd871ded7d6765b98a9
MMOCoreORB/bin/scripts/mobile/tatooine/settler.lua
MMOCoreORB/bin/scripts/mobile/tatooine/settler.lua
settler = Creature:new { objectName = "@mob/creature_names:settler", socialGroup = "thug", pvpFaction = "thug", faction = "thug", level = 6, chanceHit = 0.250000, damageMin = 50, damageMax = 55, baseXp = 113, baseHAM = 180, baseHAMmax = 220, 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.000000, ferocity = 0, pvpBitmask = ATTACKABLE, creatureBitmask = NONE, diet = HERBIVORE, templates = {"object/mobile/dressed_tatooine_settler.iff"}, lootGroups = {}, weapons = {"rebel_weapons_light"}, attacks = merge(marksmannovice,brawlernovice) } CreatureTemplates:addCreatureTemplate(settler, "settler")
settler = Creature:new { objectName = "@mob/creature_names:settler", socialGroup = "thug", pvpFaction = "thug", faction = "thug", level = 6, chanceHit = 0.250000, damageMin = 50, damageMax = 55, baseXp = 113, baseHAM = 180, baseHAMmax = 220, 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.000000, ferocity = 0, pvpBitmask = ATTACKABLE, creatureBitmask = NONE, diet = HERBIVORE, templates = { "object/mobile/dressed_commoner_tatooine_bith_female_03.iff", "object/mobile/dressed_commoner_old_human_male_02.iff", "object/mobile/dressed_commoner_naboo_twilek_female_01.iff" }, lootGroups = {}, weapons = {"rebel_weapons_light"}, attacks = merge(marksmannovice,brawlernovice) } CreatureTemplates:addCreatureTemplate(settler, "settler")
(unstable) [fixed] Settler pants missing.
(unstable) [fixed] Settler pants missing. git-svn-id: e4cf3396f21da4a5d638eecf7e3b4dd52b27f938@5642 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,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
f58583f5cfd6cdaf4ed71ccc67775d739ddf629d
applications/luci-statistics/src/model/cbi/admin_statistics/iptables.lua
applications/luci-statistics/src/model/cbi/admin_statistics/iptables.lua
--[[ Luci configuration model for statistics - collectd iptables plugin configuration (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$ ]]-- require("ffluci.sys.iptparser") ip = ffluci.sys.iptparser.IptParser() chains = { } targets = { } for i, rule in ipairs( ip:find() ) do chains[rule.chain] = true targets[rule.target] = true end m = Map("luci_statistics", "Iptables Plugin", [[Das Iptables-Plugin ermöglicht die Überwachung bestimmter Firewallregeln um Werte wie die Anzahl der verarbeiteten Pakete oder die insgesamt erfasste Datenmenge zu speichern.]]) -- collectd_iptables config section s = m:section( NamedSection, "collectd_iptables", "luci_statistics", "Pluginkonfiguration" ) -- collectd_iptables.enable enable = s:option( Flag, "enable", "Plugin aktivieren" ) enable.default = 0 -- collectd_iptables_match config section (Chain directives) rule = m:section( TypedSection, "collectd_iptables_match", "Regel hinzufügen", [[Hier werden die Kriterien festgelegt, nach welchen die Firewall-Regeln zur Überwachung ausgewählt werden.]]) rule.addremove = true rule.anonymous = true -- collectd_iptables_match.name rule_table = rule:option( Value, "name", "Name der Regel", "wird im Diagram verwendet" ) -- collectd_iptables_match.table rule_table = rule:option( ListValue, "table", "Firewall-Tabelle" ) rule_table.default = "filter" rule_table.rmempty = true rule_table.optional = true rule_table:value("") rule_table:value("filter") rule_table:value("nat") rule_table:value("mangle") -- collectd_iptables_match.chain rule_chain = rule:option( ListValue, "chain", "Firewall-Kette (Chain)" ) rule_chain.rmempty = true rule_chain.optional = true rule_chain:value("") for chain, void in pairs( chains ) do rule_chain:value( chain ) end -- collectd_iptables_match.target rule_target = rule:option( ListValue, "target", "Firewall-Aktion (Target)" ) rule_target.rmempty = true rule_target.optional = true rule_target:value("") for target, void in pairs( targets ) do rule_target:value( target ) end -- collectd_iptables_match.protocol rule_protocol = rule:option( ListValue, "protocol", "Netzwerkprotokoll" ) rule_protocol.rmempty = true rule_protocol.optional = true rule_protocol:value("") rule_protocol:value("tcp") rule_protocol:value("udp") rule_protocol:value("icmp") -- collectd_iptables_match.source rule_source = rule:option( Value, "source", "Quell-IP-Bereich", "Bereich in CIDR Notation" ) rule_source.default = "0.0.0.0/0" rule_source.rmempty = true rule_source.optional = true -- collectd_iptables_match.destination rule_destination = rule:option( Value, "destination", "Ziel-IP-Bereich", "Bereich in CIDR Notation" ) rule_destination.default = "0.0.0.0/0" rule_destination.rmempty = true rule_destination.optional = true -- collectd_iptables_match.inputif rule_inputif = rule:option( Value, "inputif", "eingehende Schnittstelle", "z.B. eth0.0" ) rule_inputif.default = "0.0.0.0/0" rule_inputif.rmempty = true rule_inputif.optional = true -- collectd_iptables_match.outputif rule_outputif = rule:option( Value, "outputif", "ausgehende Schnittstelle", "z.B. eth0.1" ) rule_outputif.default = "0.0.0.0/0" rule_outputif.rmempty = true rule_outputif.optional = true -- collectd_iptables_match.options rule_options = rule:option( Value, "options", "Optionen", "z.B. reject-with tcp-reset" ) rule_options.default = "0.0.0.0/0" rule_options.rmempty = true rule_options.optional = true return m
--[[ Luci configuration model for statistics - collectd iptables plugin configuration (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$ ]]-- require("ffluci.sys.iptparser") ip = ffluci.sys.iptparser.IptParser() chains = { } targets = { } for i, rule in ipairs( ip:find() ) do chains[rule.chain] = true targets[rule.target] = true end m = Map("luci_statistics", "Iptables Plugin", [[Das Iptables-Plugin ermöglicht die Überwachung bestimmter Firewallregeln um Werte wie die Anzahl der verarbeiteten Pakete oder die insgesamt erfasste Datenmenge zu speichern.]]) -- collectd_iptables config section s = m:section( NamedSection, "collectd_iptables", "luci_statistics", "Pluginkonfiguration" ) -- collectd_iptables.enable enable = s:option( Flag, "enable", "Plugin aktivieren" ) enable.default = 0 -- collectd_iptables_match config section (Chain directives) rule = m:section( TypedSection, "collectd_iptables_match", "Regel hinzufügen", [[Hier werden die Kriterien festgelegt, nach welchen die Firewall-Regeln zur Überwachung ausgewählt werden.]]) rule.addremove = true rule.anonymous = true -- collectd_iptables_match.name rule_table = rule:option( Value, "name", "Name der Regel", "wird im Diagram verwendet" ) -- collectd_iptables_match.table rule_table = rule:option( ListValue, "table", "Firewall-Tabelle" ) rule_table.default = "filter" rule_table.rmempty = true rule_table.optional = true rule_table:value("") rule_table:value("filter") rule_table:value("nat") rule_table:value("mangle") -- collectd_iptables_match.chain rule_chain = rule:option( ListValue, "chain", "Firewall-Kette (Chain)" ) rule_chain.rmempty = true rule_chain.optional = true rule_chain:value("") for chain, void in pairs( chains ) do rule_chain:value( chain ) end -- collectd_iptables_match.target rule_target = rule:option( ListValue, "target", "Firewall-Aktion (Target)" ) rule_target.rmempty = true rule_target.optional = true rule_target:value("") for target, void in pairs( targets ) do rule_target:value( target ) end -- collectd_iptables_match.protocol rule_protocol = rule:option( ListValue, "protocol", "Netzwerkprotokoll" ) rule_protocol.rmempty = true rule_protocol.optional = true rule_protocol:value("") rule_protocol:value("tcp") rule_protocol:value("udp") rule_protocol:value("icmp") -- collectd_iptables_match.source rule_source = rule:option( Value, "source", "Quell-IP-Bereich", "Bereich in CIDR Notation" ) rule_source.default = "0.0.0.0/0" rule_source.rmempty = true rule_source.optional = true -- collectd_iptables_match.destination rule_destination = rule:option( Value, "destination", "Ziel-IP-Bereich", "Bereich in CIDR Notation" ) rule_destination.default = "0.0.0.0/0" rule_destination.rmempty = true rule_destination.optional = true -- collectd_iptables_match.inputif rule_inputif = rule:option( Value, "inputif", "eingehende Schnittstelle", "z.B. eth0.0" ) rule_inputif.rmempty = true rule_inputif.optional = true -- collectd_iptables_match.outputif rule_outputif = rule:option( Value, "outputif", "ausgehende Schnittstelle", "z.B. eth0.1" ) rule_outputif.rmempty = true rule_outputif.optional = true -- collectd_iptables_match.options rule_options = rule:option( Value, "options", "Optionen", "z.B. reject-with tcp-reset" ) rule_options.rmempty = true rule_options.optional = true return m
* ffluci/statistics: fix c'n'p errors in iptables cbi model
* ffluci/statistics: fix c'n'p errors in iptables cbi model
Lua
apache-2.0
8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,8devices/luci,deepak78/luci,deepak78/luci,deepak78/luci,8devices/luci,8devices/luci,8devices/luci,deepak78/luci
933f775cd7d1cefd4ba16949d765456de4644bb7
.hammerspoon/Spoons/Quitter.spoon/init.lua
.hammerspoon/Spoons/Quitter.spoon/init.lua
--- === Quitter === -- -- Quits configured apps if they have not been used since a specified amount of time. local obj = {} obj.__index = obj -- Metadata obj.name = "Quitter" obj.version = "0.1" obj.author = "Alpha Chen <alpha@kejadlen.dev>" obj.license = "MIT - https://opensource.org/licenses/MIT" obj.logger = hs.logger.new("quitter", "debug") obj.lastFocused = {} --- Quitter.quitAppsAfter --- Variable --- Table of application bundle IDs to quit when unused. Use `mdls -name --- --kMDItemCFBundleIdentifier -r /path/to/app` to find unknown bundle IDs. obj.quitAppsAfter = {} --- Quitter:start() --- Method --- Start Quitter --- --- Parameters: --- * None function obj:start() self:reset() -- Reset if we're waking from sleep self.watcher = hs.caffeinate.watcher.new(function(event) if event ~= hs.caffeinate.watcher.systemDidWake then return end self:reset() end) -- Set last focused time for relevant apps self.windowFilter = hs.window.filter.default:subscribe(hs.window.filter.windowFocused, function(window, appName) local bundleID = window:application():bundleID() if not self.quitAppsAfter[bundleID] then return end self.lastFocused[bundleID] = os.time() end) self.timer = hs.timer.doEvery(60, function() self:reap() end):start() return self end --- Quitter:stop() --- Method --- Stop Quitter --- --- Parameters: --- * None function obj:stop() self.watcher:stop() self.windowFilter:unsubscribe() self.timer:stop() end function obj:reset() hs.fnutils.ieach(hs.application.runningApplications(), function(app) local bundleID = app:bundleID() local duration = self.quitAppsAfter[bundleID] if not duration then return false end self.lastFocused[bundleID] = os.time() end) end function obj:reap() self.logger.d("reaping") local appsToQuit = hs.fnutils.ifilter(hs.application.runningApplications(), function(app) -- Don't quit the currently focused app if app:isFrontmost() then return false end local duration = self.quitAppsAfter[app:bundleID()] if not duration then return false end local lastFocused = self.lastFocused[app:bundleID()] if not lastFocused then return false end self.logger.d("app: " .. app:name() .. " last focused at " .. lastFocused) return (os.time() - lastFocused) > duration end) for _,app in pairs(appsToQuit) do hs.notify.new({ title = "Hammerspoon", informativeText = "Quitting " .. app:name(), withdrawAfter = 2, }):send() app:kill() self.lastFocused[app:bundleID()] = nil end end return obj
--- === Quitter === -- -- Quits configured apps if they have not been used since a specified amount of time. local obj = {} obj.__index = obj -- Metadata obj.name = "Quitter" obj.version = "0.1" obj.author = "Alpha Chen <alpha@kejadlen.dev>" obj.license = "MIT - https://opensource.org/licenses/MIT" obj.logger = hs.logger.new("quitter", "debug") obj.lastFocused = {} --- Quitter.quitAppsAfter --- Variable --- Table of application bundle IDs to quit when unused. Use `mdls -name --- --kMDItemCFBundleIdentifier -r /path/to/app` to find unknown bundle IDs. obj.quitAppsAfter = {} --- Quitter:start() --- Method --- Start Quitter --- --- Parameters: --- * None function obj:start() self:reset() -- Reset if we're waking from sleep self.watcher = hs.caffeinate.watcher.new(function(event) if event ~= hs.caffeinate.watcher.systemDidWake then return end self:reset() end) -- Set last focused time for relevant apps self.windowFilter = hs.window.filter.default:subscribe(hs.window.filter.windowFocused, function(window, appName) local bundleID = window:application():bundleID() if not self.quitAppsAfter[bundleID] then return end self.lastFocused[bundleID] = os.time() end) self.timer = hs.timer.doEvery(60, function() self:reap() end):start() return self end --- Quitter:stop() --- Method --- Stop Quitter --- --- Parameters: --- * None function obj:stop() self.watcher:stop() self.windowFilter:unsubscribe(hs.window.filter.windowFocused) self.timer:stop() end function obj:reset() hs.fnutils.ieach(hs.application.runningApplications(), function(app) local bundleID = app:bundleID() local duration = self.quitAppsAfter[bundleID] if not duration then return false end self.lastFocused[bundleID] = os.time() end) end function obj:reap() self.logger.d("reaping") local appsToQuit = hs.fnutils.ifilter(hs.application.runningApplications(), function(app) -- Don't quit the currently focused app if app:isFrontmost() then return false end local duration = self.quitAppsAfter[app:bundleID()] if not duration then return false end local lastFocused = self.lastFocused[app:bundleID()] if not lastFocused then return false end self.logger.d("app: " .. app:name() .. " last focused at " .. lastFocused) return (os.time() - lastFocused) > duration end) for _,app in pairs(appsToQuit) do hs.notify.new({ title = "Hammerspoon", informativeText = "Quitting " .. app:name(), withdrawAfter = 2, }):send() app:kill() self.lastFocused[app:bundleID()] = nil end end return obj
[hammerspoon] fix stopping Quitter spoon
[hammerspoon] fix stopping Quitter spoon
Lua
mit
kejadlen/dotfiles,kejadlen/dotfiles
2455028e89520e7bb78fbe51442310fdca491a30
src/core/main.lua
src/core/main.lua
module(...,package.seeall) -- Default to not using any Lua code on the filesystem. -- (Can be overridden with -P argument: see below.) package.path = '' local STP = require("lib.lua.StackTracePlus") local ffi = require("ffi") local zone = require("jit.zone") local C = ffi.C require("lib.lua.strict") require("lib.lua.class") -- Reserve names that we want to use for global module. -- (This way we avoid errors from the 'strict' module.) _G.config, _G.engine, _G.memory, _G.link, _G.buffer, _G.packet, _G.timer, _G.main = nil ffi.cdef[[ extern int argc; extern char** argv; ]] local usage = [[ Usage: snabb [options] <module> [args...] Available options are: -P pathspec Set library load path (Lua 'package.path'). -e chunk Execute string 'chunk'. -l name Require library 'name'. -t name Test module 'name' with selftest(). -d Debug unhandled errors with the Lua interactive debugger. -S Print enhanced stack traces with more debug information. -jdump file Trace JIT decisions to 'file'. (Requires LuaJIT jit.* library.) -jp Profile with the LuaJIT statistical profiler. -jp=args[,.output] ]] debug_on_error = false profiling = false -- List of parameters passed on the command line. parameters = {} function main () zone("startup") require "lib.lua.strict" initialize() local args = command_line_args() if #args == 0 then print(usage) os.exit(1) end local i = 1 while i <= #args do if args[i] == '-P' and i < #args then package.path = args[i+1] i = i + 2 elseif args[i] == '-l' and i < #args then require(args[i+1]) i = i + 2 elseif args[i] == '-t' and i < #args then zone("selftest") require(args[i+1]).selftest() zone() i = i + 2 elseif args[i] == '-e' and i < #args then local thunk, error = loadstring(args[i+1]) if thunk then thunk() else print(error) end i = i + 2 elseif args[i] == '-d' then debug_on_error = true i = i + 1 elseif args[i] == '-S' then debug.traceback = STP.stacktrace i = i + 1 elseif (args[i]):match("-jp") then local pargs, poutput = (args[i]):gmatch("-jp=([^,]*),?(.*)")() if poutput == '' then poutput = nil end require("jit.p").start(pargs, poutput) profiling = true i = i + 1 elseif args[i] == '-jdump' and i < #args then local jit_dump = require "jit.dump" jit_dump.start("", args[i+1]) i = i + 2 elseif i <= #args then -- Syntax: <script> [args...] local module = args[i] i = i + 1 while i <= #args do table.insert(parameters, args[i]) i = i + 1 end zone("module "..module) dofile(module) exit(0) else print(usage) os.exit(1) end end exit(0) end function exit (status) if profiling then require("jit.p").stop() end os.exit(status) end --- Globally initialize some things. Module can depend on this being done. function initialize () require("core.lib") require("core.clib_h") require("core.lib_h") if C.geteuid() ~= 0 then print("error: snabb has to run as root.") os.exit(1) end -- Global API _G.config = require("core.config") _G.engine = require("core.app") _G.memory = require("core.memory") _G.link = require("core.link") _G.buffer = require("core.buffer") _G.packet = require("core.packet") _G.timer = require("core.timer") _G.main = getfenv() end function command_line_args() local args = {} for i = 1, C.argc - 1 do args[i] = ffi.string(C.argv[i]) end return args end function handler (reason) print(reason) print(debug.traceback()) if debug_on_error then debug.debug() end os.exit(1) end xpcall(main, handler)
module(...,package.seeall) -- Default to not using any Lua code on the filesystem. -- (Can be overridden with -P argument: see below.) package.path = '' local STP = require("lib.lua.StackTracePlus") local ffi = require("ffi") local zone = require("jit.zone") local C = ffi.C require("lib.lua.strict") require("lib.lua.class") -- Reserve names that we want to use for global module. -- (This way we avoid errors from the 'strict' module.) _G.config, _G.engine, _G.memory, _G.link, _G.buffer, _G.packet, _G.timer, _G.main = nil ffi.cdef[[ extern int argc; extern char** argv; ]] local usage = [[ Usage: snabb [options] <module> [args...] Available options are: -P pathspec Set library load path (Lua 'package.path'). -e chunk Execute string 'chunk'. -l name Require library 'name'. -t name Test module 'name' with selftest(). -d Debug unhandled errors with the Lua interactive debugger. -S Print enhanced stack traces with more debug information. -jdump file Trace JIT decisions to 'file'. (Requires LuaJIT jit.* library.) -jp Profile with the LuaJIT statistical profiler. -jp=args[,.output] ]] debug_on_error = false profiling = false -- List of parameters passed on the command line. parameters = {} function main () zone("startup") require "lib.lua.strict" initialize() local args = command_line_args() if #args == 0 then print(usage) os.exit(1) end local i = 1 while i <= #args do if args[i] == '-P' and i < #args then package.path = args[i+1] i = i + 2 elseif args[i] == '-l' and i < #args then require(args[i+1]) i = i + 2 elseif args[i] == '-t' and i < #args then zone("selftest") require(args[i+1]).selftest() zone() i = i + 2 elseif args[i] == '-e' and i < #args then local thunk, error = loadstring(args[i+1]) if thunk then thunk() else print(error) end i = i + 2 elseif args[i] == '-d' then debug_on_error = true i = i + 1 elseif args[i] == '-S' then debug.traceback = STP.stacktrace i = i + 1 elseif (args[i]):match("-jp") then local pargs, poutput = (args[i]):gmatch("-jp=([^,]*),?(.*)")() if poutput == '' then poutput = nil end require("jit.p").start(pargs, poutput) profiling = true i = i + 1 elseif args[i] == '-jdump' and i < #args then local jit_dump = require "jit.dump" jit_dump.start("", args[i+1]) i = i + 2 elseif i <= #args then -- Syntax: <script> [args...] local module = args[i] i = i + 1 while i <= #args do table.insert(parameters, args[i]) i = i + 1 end zone("module "..module) dofile(module) exit(0) else print(usage) os.exit(1) end end exit(0) end function exit (status) if profiling then require("jit.p").stop() end os.exit(status) end --- Globally initialize some things. Module can depend on this being done. function initialize () require("core.lib") require("core.clib_h") require("core.lib_h") if C.geteuid() ~= 0 then print("error: snabb has to run as root.") os.exit(1) end -- Global API _G.config = require("core.config") _G.engine = require("core.app") _G.memory = require("core.memory") _G.link = require("core.link") _G.buffer = require("core.buffer") _G.packet = require("core.packet") _G.timer = require("core.timer") _G.main = getfenv() end function command_line_args() local args = {} for i = 1, C.argc - 1 do args[i] = ffi.string(C.argv[i]) end return args end function handler (reason) print(reason) print(debug.traceback()) if debug_on_error then debug.debug() end os.exit(1) end xpcall(main, handler)
main.lua: Replace tabs with spaces and fix identation on main().
main.lua: Replace tabs with spaces and fix identation on main().
Lua
apache-2.0
snabbco/snabb,wingo/snabb,justincormack/snabbswitch,wingo/snabbswitch,plajjan/snabbswitch,andywingo/snabbswitch,SnabbCo/snabbswitch,Igalia/snabb,andywingo/snabbswitch,pavel-odintsov/snabbswitch,lukego/snabb,Igalia/snabbswitch,dpino/snabbswitch,heryii/snabb,eugeneia/snabb,kellabyte/snabbswitch,eugeneia/snabb,virtualopensystems/snabbswitch,fhanik/snabbswitch,eugeneia/snabb,javierguerragiraldez/snabbswitch,Igalia/snabb,heryii/snabb,alexandergall/snabbswitch,heryii/snabb,SnabbCo/snabbswitch,snabbnfv-goodies/snabbswitch,dwdm/snabbswitch,snabbnfv-goodies/snabbswitch,wingo/snabbswitch,snabbnfv-goodies/snabbswitch,snabbco/snabb,xdel/snabbswitch,andywingo/snabbswitch,dpino/snabb,alexandergall/snabbswitch,alexandergall/snabbswitch,lukego/snabbswitch,eugeneia/snabbswitch,mixflowtech/logsensor,snabbco/snabb,mixflowtech/logsensor,andywingo/snabbswitch,hb9cwp/snabbswitch,plajjan/snabbswitch,eugeneia/snabbswitch,mixflowtech/logsensor,aperezdc/snabbswitch,plajjan/snabbswitch,alexandergall/snabbswitch,aperezdc/snabbswitch,justincormack/snabbswitch,wingo/snabb,dpino/snabb,SnabbCo/snabbswitch,hb9cwp/snabbswitch,heryii/snabb,snabbco/snabb,Igalia/snabbswitch,kbara/snabb,alexandergall/snabbswitch,dpino/snabbswitch,dpino/snabbswitch,eugeneia/snabb,lukego/snabb,dpino/snabb,Igalia/snabb,pavel-odintsov/snabbswitch,kbara/snabb,alexandergall/snabbswitch,dpino/snabb,javierguerragiraldez/snabbswitch,aperezdc/snabbswitch,lukego/snabb,aperezdc/snabbswitch,wingo/snabbswitch,mixflowtech/logsensor,justincormack/snabbswitch,alexandergall/snabbswitch,javierguerragiraldez/snabbswitch,heryii/snabb,heryii/snabb,pirate/snabbswitch,lukego/snabb,dpino/snabb,snabbco/snabb,plajjan/snabbswitch,snabbco/snabb,virtualopensystems/snabbswitch,xdel/snabbswitch,wingo/snabbswitch,eugeneia/snabbswitch,kbara/snabb,wingo/snabb,eugeneia/snabb,kbara/snabb,eugeneia/snabb,hb9cwp/snabbswitch,lukego/snabbswitch,fhanik/snabbswitch,dpino/snabb,Igalia/snabbswitch,SnabbCo/snabbswitch,dpino/snabb,kellabyte/snabbswitch,kbara/snabb,virtualopensystems/snabbswitch,wingo/snabb,justincormack/snabbswitch,Igalia/snabb,kbara/snabb,alexandergall/snabbswitch,xdel/snabbswitch,Igalia/snabb,Igalia/snabbswitch,Igalia/snabb,pirate/snabbswitch,fhanik/snabbswitch,Igalia/snabbswitch,mixflowtech/logsensor,Igalia/snabb,wingo/snabb,pirate/snabbswitch,snabbco/snabb,pavel-odintsov/snabbswitch,kellabyte/snabbswitch,Igalia/snabb,snabbco/snabb,lukego/snabbswitch,snabbnfv-goodies/snabbswitch,dpino/snabbswitch,hb9cwp/snabbswitch,lukego/snabbswitch,eugeneia/snabb,dwdm/snabbswitch,dwdm/snabbswitch,eugeneia/snabbswitch,eugeneia/snabb,wingo/snabb
c4382d0b25ab7f887cfa363109193ebd114fddc0
luastatic.lua
luastatic.lua
-- The author disclaims copyright to this source code. local infile = arg[1] if not infile then print("usage: luastatic infile.lua") os.exit() end local CC = os.getenv("CC") or "gcc" do local f = io.popen(CC .. " --version") f:read("*all") if not f:close() then print("C compiler not found.") os.exit(1) end end local infd = io.open(infile, "r") if not infd then print(("Lua file not found: %s"):format(infile)) os.exit(1) end function fileToBlob(filename) local basename = filename:match("(.+)%.") local fmt = [[ unsigned char %s_lua[] = { %s }; unsigned int %s_lua_len = %u; ]] local f = io.open(filename, "r") local strdata = f:read("*all") -- load the chunk to check for syntax errors local chunk, err = load(strdata) if not chunk then print(("load: %s"):format(err)) os.exit(1) end local bindata = string.dump(chunk) local hex = {} for b in bindata:gmatch"." do table.insert(hex, ("0x%02x"):format(string.byte(b))) end local hexstr = table.concat(hex, ", ") f:close() return fmt:format(basename, hexstr, basename, #bindata) end --~ local cdata = io.popen(("xxd -i %s"):format(infile)):read("*all") local cdata = fileToBlob(infile) local basename = infile:match("(.+)%.") local cprog = ([[ #include <lauxlib.h> #include <lua.h> #include <lualib.h> #include <stdio.h> %s // copied from lua.c static void createargtable (lua_State *L, char **argv, int argc, int script) { int i, narg; if (script == argc) script = 0; /* no script name? */ narg = argc - (script + 1); /* number of positive indices */ lua_createtable(L, narg, script + 1); for (i = 0; i < argc; i++) { lua_pushstring(L, argv[i]); lua_rawseti(L, -2, i - script); } lua_setglobal(L, "arg"); } int main(int argc, char *argv[]) { lua_State *L = luaL_newstate(); luaL_openlibs(L); if (luaL_loadbuffer(L, (const char*)%s_lua, %s_lua_len, "%s")) { puts(lua_tostring(L, 1)); return 1; } createargtable(L, argv, argc, 0); int err = lua_pcall(L, 0, LUA_MULTRET, 0); if (err != LUA_OK) { puts(lua_tostring(L, 1)); return 1; } return 0; } ]]):format(cdata, basename, basename, basename) local outfile = io.open(("%s.c"):format(infile), "w+") outfile:write(cprog) outfile:close() do -- statically link lua, but dynamically everything else local gccformat = "%s -Os %s.c -Wl,-Bstatic `pkg-config --cflags --libs lua5.2` -Wl,-Bdynamic -lm -ldl -o %s" local gccstr = gccformat:format(CC, infile, basename) --~ print(gccstr) io.popen(gccstr):read("*all") end
-- The author disclaims copyright to this source code. local infile = arg[1] if not infile then print("usage: luastatic infile.lua") os.exit() end local CC = os.getenv("CC") or "gcc" do local f = io.popen(CC .. " --version") f:read("*all") if not f:close() then print("C compiler not found.") os.exit(1) end end local infd = io.open(infile, "r") if not infd then print(("Lua file not found: %s"):format(infile)) os.exit(1) end function fileToBlob(filename) local basename = filename:match("(.+)%.") local fmt = [[ unsigned char %s_lua[] = { %s }; unsigned int %s_lua_len = %u; ]] local f = io.open(filename, "r") local strdata = f:read("*all") -- load the chunk to check for syntax errors local chunk, err = load(strdata) if not chunk then print(("load: %s"):format(err)) os.exit(1) end local bindata = string.dump(chunk) local hex = {} for b in bindata:gmatch"." do table.insert(hex, ("0x%02x"):format(string.byte(b))) end local hexstr = table.concat(hex, ", ") f:close() return fmt:format(basename, hexstr, basename, #bindata) end --~ local cdata = io.popen(("xxd -i %s"):format(infile)):read("*all") local cdata = fileToBlob(infile) local basename = infile:match("(.+)%.") local cprog = ([[ #include <lauxlib.h> #include <lua.h> #include <lualib.h> #include <stdio.h> %s // copied from lua.c static void createargtable (lua_State *L, char **argv, int argc, int script) { int i, narg; if (script == argc) script = 0; /* no script name? */ narg = argc - (script + 1); /* number of positive indices */ lua_createtable(L, narg, script + 1); for (i = 0; i < argc; i++) { lua_pushstring(L, argv[i]); lua_rawseti(L, -2, i - script); } lua_setglobal(L, "arg"); } int main(int argc, char *argv[]) { lua_State *L = luaL_newstate(); luaL_openlibs(L); if (luaL_loadbuffer(L, (const char*)%s_lua, %s_lua_len, "%s")) { puts(lua_tostring(L, 1)); return 1; } createargtable(L, argv, argc, 0); int err = lua_pcall(L, 0, LUA_MULTRET, 0); if (err != LUA_OK) { puts(lua_tostring(L, 1)); return 1; } return 0; } ]]):format(cdata, basename, basename, basename) local outfile = io.open(("%s.c"):format(infile), "w+") outfile:write(cprog) outfile:close() do -- statically link Lua, but dynamically link everything else -- http://lua-users.org/lists/lua-l/2009-05/msg00147.html local gccformat = "%s -Os %s.c -Wl,--export-dynamic -Wl,-Bstatic `pkg-config --cflags --libs lua5.2` -Wl,-Bdynamic -lm -ldl -o %s" local gccstr = gccformat:format(CC, infile, basename) --~ print(gccstr) io.popen(gccstr):read("*all") end
add --export-dynamic to fix dlopen
add --export-dynamic to fix dlopen
Lua
cc0-1.0
ers35/luastatic,ers35/luastatic
daa369e880e944a76090522d32f7bbcfa32a3318
bin/process/PooledEPRel2RelRel.lua
bin/process/PooledEPRel2RelRel.lua
local cmd = torch.CmdLine() cmd:option('-inFile', '', 'input file') cmd:option('-outFile', '', 'out file') cmd:option('-kbMap', '', 'out file') local params = cmd:parse(arg) if params.kbMap ~= '' then local vocab_map = {} for line in io.lines(self.params.vocabFile) do local token, id = string.match(line, "([^\t]+)\t([^\t]+)") if token and id then id = tonumber(id) if id > 1 then vocab_map[token] = id end end end end -- DATA print('loading file: ', params.inFile) local original_data = torch.load(params.inFile) -- prepare new data object dNew local reformatted_data = {num_cols = original_data.num_rels, num_rows = original_data.num_eps, num_col_tokens = original_data.num_tokens, num_row_tokens = original_data.num_tokens} -- LOOP OVER KEYS TO RESTRUCTURE VALUES local i = 0 for num_relations, ep_data in pairs(original_data) do io.write('\rProcessing : '..i); io.flush() i = i + 1 -- other cases: several relations if (type(ep_data) == 'table' and i > 1) then local col, row, col_seq, row_seq -- LOOP OVER RELATIONS TO RESTRUCTURE THEM for s = 1, ep_data.rel:size(2) do -- create new RelTest in ep from ONE dimension of seq row = ep_data.rel:select(2, s) row_seq = ep_data.seq:select(2, s) local range if s == 1 then range = torch.range(s+1, ep_data.rel:size(2)) elseif s == ep_data.rel:size(2) then range = torch.range(1, ep_data.rel:size(2)-1) else range = torch.range(1, s-1):cat(torch.range(s, ep_data.rel:size(2))) end col = ep_data.rel:index(2, range:long()) col = col:view(col:size(1), col:size(2)) col_seq = ep_data.seq:index(2, range:long()) end reformatted_data[num_relations] = {row_seq = row_seq, row = row, count = row_seq:size(1), col_seq = col_seq, col = col } end end print('\nDone') reformatted_data.max_length = i -- SAVE FILE torch.save(params.outFile, reformatted_data)
require 'nn' --[[ Given a file processed by IntFile2PoolRelationsTorch.lua mapping entity pairs to a set of relations creates a new file mapping a single relation to a set of relations ]]-- local cmd = torch.CmdLine() cmd:option('-inFile', '', 'input file') cmd:option('-outFile', '', 'out file') cmd:option('-kbMap', '', 'out file') cmd:option('-kbOnly', false, 'only use kb relations as the single relation') cmd:option('-maxSamples', 0, 'maximum number of samples to take for a given entity pair - 0 = all') local params = cmd:parse(arg) local kb_rels = {} if params.kbMap ~= '' then io.write('Loading kb map... ') for line in io.lines(params.kbMap) do local token, id = string.match(line, "([^\t]+)\t([^\t]+)") if token and id then id = tonumber(id) if id > 1 then table.insert(kb_rels, torch.Tensor(1,1):fill(id)) end end end print('Done') end -- DATA print('loading file: ', params.inFile) local original_data = torch.load(params.inFile) -- prepare new data object dNew local reformatted_data = {num_cols = original_data.num_rels, num_rows = original_data.num_eps, num_col_tokens = original_data.num_tokens, num_row_tokens = original_data.num_tokens} local function extract_example(ep_data, i) local row = ep_data.rel:select(2, i) local row_seq = ep_data.seq:select(2, i) local range if i == 1 then range = torch.range(i+1, ep_data.rel:size(2)) elseif i == ep_data.rel:size(2) then range = torch.range(1, ep_data.rel:size(2)-1) else range = torch.range(1, i-1):cat(torch.range(i+1, ep_data.rel:size(2))) end local col = ep_data.rel:index(2, range:long()) col = col:view(col:size(1), col:size(2)) local col_seq = ep_data.seq:index(2, range:long()) return col, row, col_seq, row_seq end -- for each r in the relation set, create #r examples - take one out and leave the rest local function extract_relations(ep_data) local col_table, row_table, col_seq_table, row_seq_table = {}, {}, {}, {} local shuffle = torch.randperm(ep_data.rel:size(2)) if params.maxSamples > 0 then shuffle = shuffle:narrow(1, 1, math.min(shuffle:size(1), params.maxSamples)) end for i = 1, shuffle:size(1) do local col, row, col_seq, row_seq = extract_example(ep_data, shuffle[i]) table.insert(col_table, col); table.insert(col_seq_table, col_seq) table.insert(row_table, row); table.insert(row_seq_table, row_seq) end return col_table, row_table, col_seq_table, row_seq_table end -- for each kb relation in the relation set, create #kb examples - take one out and leave the rest local function extract_kb_only_relations(ep_data) local col_table, row_table, col_seq_table, row_seq_table = {}, {}, {}, {} for i = 1, ep_data.rel:size(2) do local col, row, col_seq, row_seq = extract_example(ep_data, i) local mask = torch.ByteTensor(row:size(1), 1):fill(0) -- get indices in the row tensor that match any of our kb ids for _, kb_id in pairs(kb_rels) do mask:add(row:eq(kb_id:expandAs(row))) end local index = {} for idx = 1, mask:size(1) do if mask[idx][1] == 1 then table.insert(index, idx) end end if mask:sum() > 0 then table.insert(col_table, col:index(1, torch.LongTensor(index))) table.insert(col_seq_table, col_seq:index(1, torch.LongTensor(index))) table.insert(row_table, row:index(1, torch.LongTensor(index))) table.insert(row_seq_table, row_seq:index(1, torch.LongTensor(index))) end end return col_table, row_table, col_seq_table, row_seq_table end local i = 0 for num_relations, ep_data in pairs(original_data) do -- num_relations = 131 -- ep_data = original_data[num_relations] io.write('\rProcessing : '..i); io.flush(); i = i + 1 if (type(ep_data) == 'table' and i > 1) then local col_table, row_table, col_seq_table, row_seq_table if params.kbOnly then col_table, row_table, col_seq_table, row_seq_table = extract_kb_only_relations(ep_data) else col_table, row_table, col_seq_table, row_seq_table = extract_relations(ep_data) end reformatted_data[num_relations] = { row_seq = nn.JoinTable(1)(row_seq_table), row = nn.JoinTable(1)(row_table), col_seq = nn.JoinTable(1)(col_seq_table), col = nn.JoinTable(1)(col_table) } reformatted_data[num_relations].count = reformatted_data[num_relations].row:size(1) end end print('\nDone') reformatted_data.max_length = i -- SAVE FILE torch.save(params.outFile, reformatted_data)
fix pool relation script
fix pool relation script
Lua
mit
patverga/torch-relation-extraction,patverga/torch-relation-extraction,patverga/torch-relation-extraction
477c2a46c7b1a3779e7e69d4045d79767e67f8aa
mod_extauth/mod_extauth.lua
mod_extauth/mod_extauth.lua
local nodeprep = require "util.encodings".stringprep.nodeprep; local process = require "process"; local script_type = module:get_option("extauth_type"); assert(script_type == "ejabberd"); local command = module:get_option("extauth_command"); assert(type(command) == "string"); local host = module.host; assert(not host:find(":")); local proc; local function send_query(text) if not proc then proc = process.popen(command); end proc:write(text); proc:flush(); return proc:read(4); -- FIXME do properly end function do_query(kind, username, password) if not username then return nil, "not-acceptable"; end username = nodeprep(username); if not username then return nil, "jid-malformed"; end local query = (password and "%s:%s:%s:%s" or "%s:%s:%s"):format(kind, username, host, password); local len = #query if len > 1000 then return nil, "policy-violation"; end local lo = len % 256; local hi = (len - lo) / 256; query = string.char(hi, lo)..query; local response = send_query(query); if response == "\0\2\0\0" then return nil, "not-authorized"; elseif response == "\0\2\0\1" then return true; else proc = nil; -- TODO kill proc return nil, "internal-server-error"; end end local provider = { name = "extauth" }; function provider.test_password(username, password) return do_query("auth", username, password); end function provider.set_password(username, password) return do_query("setpass", username, password); end function provider.user_exists(username) return do_query("isuser", username); end function provider.get_password() return nil, "Passwords not available."; end function provider.create_user(username, password) return nil, "Account creation/modification not available."; end function provider.get_supported_methods() return {["PLAIN"] = true}; end local config = require "core.configmanager"; local usermanager = require "core.usermanager"; local jid_bare = require "util.jid".bare; function provider.is_admin(jid) local admins = config.get(host, "core", "admins"); if admins ~= config.get("*", "core", "admins") then if type(admins) == "table" then jid = jid_bare(jid); for _,admin in ipairs(admins) do if admin == jid then return true; end end elseif admins then log("error", "Option 'admins' for host '%s' is not a table", host); end end return usermanager.is_admin(jid); -- Test whether it's a global admin instead end module:add_item("auth-provider", provider);
-- -- NOTE: currently this uses lpc; when waqas fixes process, it can go back to that -- -- Prosody IM -- Copyright (C) 2010 Waqas Hussain -- Copyright (C) 2010 Jeff Mitchell -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local nodeprep = require "util.encodings".stringprep.nodeprep; --local process = require "process"; local lpc = require "lpc"; local config = require "core.configmanager"; local log = require "util.logger".init("usermanager"); local host = module.host; local script_type = config.get(host, "core", "extauth_type") or "generic"; assert(script_type == "ejabberd" or script_type == "generic"); local command = config.get(host, "core", "extauth_command") or ""; assert(type(command) == "string"); assert(not host:find(":")); local usermanager = require "core.usermanager"; local jid_bare = require "util.jid".bare; --local proc; local pid; local readfile; local writefile; local function send_query(text) -- if not proc then if not pid then log("debug", "EXTAUTH: Opening process"); -- proc = process.popen(command); pid, writefile, readfile = lpc.run(command); end -- if not proc then if not pid then log("debug", "EXTAUTH: Process failed to open"); return nil; end -- proc:write(text); -- proc:flush(); writefile:write(text); writefile:flush(); if script_type == "ejabberd" then -- return proc:read(4); -- FIXME do properly return readfile:read(4); -- FIXME do properly elseif script_type == "generic" then -- return proc:read(1); return readfile:read(); end end function do_query(kind, username, password) if not username then return nil, "not-acceptable"; end username = nodeprep(username); if not username then return nil, "jid-malformed"; end local query = (password and "%s:%s:%s:%s" or "%s:%s:%s"):format(kind, username, host, password); local len = #query if len > 1000 then return nil, "policy-violation"; end if script_type == "ejabberd" then local lo = len % 256; local hi = (len - lo) / 256; query = string.char(hi, lo)..query; end if script_type == "generic" then query = query..'\n'; end local response = send_query(query); if (script_type == "ejabberd" and response == "\0\2\0\0") or (script_type == "generic" and response == "0") then return nil, "not-authorized"; elseif (script_type == "ejabberd" and response == "\0\2\0\1") or (script_type == "generic" and response == "1") then return true; else log("debug", "EXTAUTH: Nonsense back"); --proc:close(); --proc = nil; return nil, "internal-server-error"; end end function new_extauth_provider(host) local provider = { name = "extauth" }; function provider.test_password(username, password) return do_query("auth", username, password); end function provider.set_password(username, password) return do_query("setpass", username, password); end function provider.user_exists(username) return do_query("isuser", username); end function provider.create_user(username, password) return nil, "Account creation/modification not available."; end function provider.get_supported_methods() return {["PLAIN"] = true}; end function provider.is_admin(jid) local admins = config.get(host, "core", "admins"); if admins ~= config.get("*", "core", "admins") then if type(admins) == "table" then jid = jid_bare(jid); for _,admin in ipairs(admins) do if admin == jid then return true; end end elseif admins then log("error", "Option 'admins' for host '%s' is not a table", host); end end return usermanager.is_admin(jid); -- Test whether it's a global admin instead end return provider; end module:add_item("auth-provider", new_extauth_provider(module.host));
Add "generic" script support to mod_extauth, as well as lpc support until waqas fixes process
Add "generic" script support to mod_extauth, as well as lpc support until waqas fixes process
Lua
mit
LanceJenkinZA/prosody-modules,drdownload/prosody-modules,cryptotoad/prosody-modules,drdownload/prosody-modules,jkprg/prosody-modules,BurmistrovJ/prosody-modules,BurmistrovJ/prosody-modules,asdofindia/prosody-modules,stephen322/prosody-modules,LanceJenkinZA/prosody-modules,stephen322/prosody-modules,jkprg/prosody-modules,brahmi2/prosody-modules,BurmistrovJ/prosody-modules,mardraze/prosody-modules,apung/prosody-modules,obelisk21/prosody-modules,vince06fr/prosody-modules,syntafin/prosody-modules,syntafin/prosody-modules,heysion/prosody-modules,BurmistrovJ/prosody-modules,olax/prosody-modules,vfedoroff/prosody-modules,cryptotoad/prosody-modules,crunchuser/prosody-modules,vfedoroff/prosody-modules,mmusial/prosody-modules,Craige/prosody-modules,NSAKEY/prosody-modules,prosody-modules/import,heysion/prosody-modules,crunchuser/prosody-modules,heysion/prosody-modules,dhotson/prosody-modules,Craige/prosody-modules,guilhem/prosody-modules,mardraze/prosody-modules,amenophis1er/prosody-modules,prosody-modules/import,prosody-modules/import,brahmi2/prosody-modules,amenophis1er/prosody-modules,jkprg/prosody-modules,asdofindia/prosody-modules,jkprg/prosody-modules,cryptotoad/prosody-modules,syntafin/prosody-modules,vince06fr/prosody-modules,guilhem/prosody-modules,mardraze/prosody-modules,amenophis1er/prosody-modules,softer/prosody-modules,crunchuser/prosody-modules,1st8/prosody-modules,vfedoroff/prosody-modules,dhotson/prosody-modules,1st8/prosody-modules,amenophis1er/prosody-modules,joewalker/prosody-modules,softer/prosody-modules,asdofindia/prosody-modules,softer/prosody-modules,olax/prosody-modules,1st8/prosody-modules,vince06fr/prosody-modules,syntafin/prosody-modules,brahmi2/prosody-modules,syntafin/prosody-modules,guilhem/prosody-modules,either1/prosody-modules,Craige/prosody-modules,prosody-modules/import,softer/prosody-modules,NSAKEY/prosody-modules,iamliqiang/prosody-modules,BurmistrovJ/prosody-modules,cryptotoad/prosody-modules,prosody-modules/import,guilhem/prosody-modules,mmusial/prosody-modules,asdofindia/prosody-modules,either1/prosody-modules,NSAKEY/prosody-modules,heysion/prosody-modules,heysion/prosody-modules,stephen322/prosody-modules,iamliqiang/prosody-modules,obelisk21/prosody-modules,obelisk21/prosody-modules,drdownload/prosody-modules,cryptotoad/prosody-modules,apung/prosody-modules,joewalker/prosody-modules,drdownload/prosody-modules,crunchuser/prosody-modules,vince06fr/prosody-modules,olax/prosody-modules,Craige/prosody-modules,NSAKEY/prosody-modules,1st8/prosody-modules,iamliqiang/prosody-modules,vfedoroff/prosody-modules,dhotson/prosody-modules,LanceJenkinZA/prosody-modules,obelisk21/prosody-modules,brahmi2/prosody-modules,mardraze/prosody-modules,olax/prosody-modules,apung/prosody-modules,iamliqiang/prosody-modules,vince06fr/prosody-modules,joewalker/prosody-modules,mmusial/prosody-modules,jkprg/prosody-modules,dhotson/prosody-modules,joewalker/prosody-modules,LanceJenkinZA/prosody-modules,either1/prosody-modules,either1/prosody-modules,dhotson/prosody-modules,mardraze/prosody-modules,vfedoroff/prosody-modules,obelisk21/prosody-modules,mmusial/prosody-modules,Craige/prosody-modules,olax/prosody-modules,NSAKEY/prosody-modules,either1/prosody-modules,brahmi2/prosody-modules,joewalker/prosody-modules,drdownload/prosody-modules,apung/prosody-modules,stephen322/prosody-modules,guilhem/prosody-modules,softer/prosody-modules,LanceJenkinZA/prosody-modules,iamliqiang/prosody-modules,1st8/prosody-modules,stephen322/prosody-modules,apung/prosody-modules,mmusial/prosody-modules,crunchuser/prosody-modules,amenophis1er/prosody-modules,asdofindia/prosody-modules
a48dc11063e8c6d88b808945396bd2f80c6f5fba
build/scripts/tools/ndk_server.lua
build/scripts/tools/ndk_server.lua
TOOL.Name = "SDKServer" TOOL.Directory = "../SDK" TOOL.Kind = "Library" TOOL.TargetDirectory = "../lib" TOOL.Defines = { "NDK_BUILD", "NDK_SERVER" } TOOL.Includes = { "../SDK/include", "../SDK/src" } TOOL.Files = { "../SDK/include/NDK/**.hpp", "../SDK/include/NDK/**.inl", "../SDK/src/NDK/**.hpp", "../SDK/src/NDK/**.inl", "../SDK/src/NDK/**.cpp" } -- Excludes client-only files TOOL.FilesExcluded = { "../SDK/**/CameraComponent.*", "../SDK/**/Canvas.*", "../SDK/**/Console.*", "../SDK/**/GraphicsComponent.*", "../SDK/**/LightComponent.*", "../SDK/**/ListenerComponent.*", "../SDK/**/ListenerSystem.*", "../SDK/**/Particle*Component.*", "../SDK/**/ParticleSystem.*", "../SDK/**/RenderSystem.*", "../SDK/**/*Widget*.*", "../SDK/**/LuaBinding_Audio.*", "../SDK/**/LuaBinding_Graphics.*", "../SDK/**/LuaBinding_Renderer.*", "../SDK/**/LuaBinding_Platform.*" } TOOL.Libraries = { "NazaraCore", "NazaraLua", "NazaraNetwork", "NazaraNoise", "NazaraPhysics2D", "NazaraPhysics3D", "NazaraUtility" }
TOOL.Name = "SDKServer" TOOL.Directory = "../SDK" TOOL.Kind = "Library" TOOL.TargetDirectory = "../lib" TOOL.Defines = { "NDK_BUILD", "NDK_SERVER" } TOOL.Includes = { "../SDK/include", "../SDK/src" } TOOL.Files = { "../SDK/include/NDK/**.hpp", "../SDK/include/NDK/**.inl", "../SDK/src/NDK/**.hpp", "../SDK/src/NDK/**.inl", "../SDK/src/NDK/**.cpp" } -- Excludes client-only files TOOL.FilesExcluded = { "../SDK/**/CameraComponent.*", "../SDK/**/Canvas.*", "../SDK/**/Console.*", "../SDK/**/DebugComponent.*", "../SDK/**/DebugSystem.*", "../SDK/**/GraphicsComponent.*", "../SDK/**/LightComponent.*", "../SDK/**/ListenerComponent.*", "../SDK/**/ListenerSystem.*", "../SDK/**/Particle*Component.*", "../SDK/**/ParticleSystem.*", "../SDK/**/RenderSystem.*", "../SDK/**/*Widget*.*", "../SDK/**/LuaBinding_Audio.*", "../SDK/**/LuaBinding_Graphics.*", "../SDK/**/LuaBinding_Renderer.*", "../SDK/**/LuaBinding_Platform.*" } TOOL.Libraries = { "NazaraCore", "NazaraLua", "NazaraNetwork", "NazaraNoise", "NazaraPhysics2D", "NazaraPhysics3D", "NazaraUtility" }
Fix compilation in server mode
Fix compilation in server mode
Lua
mit
DigitalPulseSoftware/NazaraEngine
0134ac3e34bd6ede9c989885e1168d1329b5ed5b
DeveloperTools/data2yaml/data2yaml.lua
DeveloperTools/data2yaml/data2yaml.lua
sptbl = {} print(arg[1]) dofile(string.format("data/%s.lua", arg[1])) YAML = { name=arg[1] } function YAML.tables(self, tbl) if(tbl.params.mandatory == nil) then return end local ftbl = {} local ft = {} for k,v in pairs(tbl.params.mandatory) do if(string.match(v.type, "sp_ftbl")) then ft.name = v.name ft.comment = v.description table.insert(ftbl, ft) end end if(next(ftbl) == nil) then return end io.write("tables:\n") for k,v in pairs(ftbl) do io.write(string.format("- %s: {\n", v.name)) io.write(string.format(" audioKitName: %s,\n", v.name)) io.write(string.format(" comment: \"%s\",\n", v.comment)) io.write(" default: \n") io.write("}\n") end io.write("\n") end function YAML.parameters(self, tbl) if(tbl.params.optional == nil) then return end io.write("parameters:\n") for k,v in pairs(tbl.params.optional) do io.write(string.format("- %s: {\n", v.name)) io.write(string.format(" audioKitName: %s,\n", v.name)) io.write(string.format(" comment: \"%s\",\n", v.description)) io.write(string.format(" default: %s\n", v.default)) io.write("}\n") end io.write("\n") end function YAML.constants(self, tbl) if(tbl.params.mandatory == nil) then return end local constants = {} local c = {} for k,v in pairs(tbl.params.mandatory) do if(string.match(v.type, "sp_ftbl")) then -- ignore else c.name = v.name c.comment = v.description c.default = v.default table.insert(constants, c) end end if(next(constants) == nil) then return end io.write("constants:\n") for k,v in pairs(constants) do io.write(string.format("- %s: {\n", v.name)) io.write(string.format(" audioKitName: %s ,\n", v.name)) io.write(string.format(" comment: \"%s\",\n", v.comment)) io.write(string.format(" default: %s\n", v.default)) io.write("}\n") end io.write("\n") end function YAML.generate(self, tbl) io.write(string.format("sp_name: %s\n\n", self.name)) io.write(string.format("summary: \n\n")); io.write(string.format("shortDescription: \n\n")) io.write(string.format("description: \n\n")) self:tables(tbl) self:parameters(tbl) self:constants(tbl) end YAML:generate(sptbl[arg[1]])
sptbl = {} print(arg[1]) dofile(string.format("data/%s.lua", arg[1])) YAML = { name=arg[1] } function YAML.tables(self, tbl) if(tbl.params.mandatory == nil) then return end local ftbl = {} for k,v in pairs(tbl.params.mandatory) do if(string.match(v.type, "sp_ftbl")) then local ft = {} ft.name = v.name ft.comment = v.description table.insert(ftbl, ft) end end if(next(ftbl) == nil) then return end io.write("tables:\n") for k,v in pairs(ftbl) do io.write(string.format("- %s: {\n", v.name)) io.write(string.format(" audioKitName: %s,\n", v.name)) io.write(string.format(" comment: \"%s\",\n", v.comment)) io.write(" default: \n") io.write("}\n") end io.write("\n") end function YAML.parameters(self, tbl) if(tbl.params.optional == nil) then return end io.write("parameters:\n") for k,v in pairs(tbl.params.optional) do io.write(string.format("- %s: {\n", v.name)) io.write(string.format(" audioKitName: %s,\n", v.name)) io.write(string.format(" comment: \"%s\",\n", v.description)) io.write(string.format(" default: %s\n", v.default)) io.write("}\n") end io.write("\n") end function YAML.constants(self, tbl) if(tbl.params.mandatory == nil) then return end local constants = {} for k,v in pairs(tbl.params.mandatory) do if(string.match(v.type, "sp_ftbl")) then -- ignore else local c = {} c.name = v.name c.comment = v.description c.default = v.default table.insert(constants, c) end end if(next(constants) == nil) then return end io.write("constants:\n") for k,v in pairs(constants) do io.write(string.format("- %s: {\n", v.name)) io.write(string.format(" audioKitName: %s ,\n", v.name)) io.write(string.format(" comment: \"%s\",\n", v.comment)) io.write(string.format(" default: %s\n", v.default)) io.write("}\n") end io.write("\n") end function YAML.generate(self, tbl) io.write(string.format("sp_name: %s\n\n", self.name)) io.write(string.format("summary: \n\n")); io.write(string.format("shortDescription: \n\n")) io.write(string.format("description: \n\n")) self:tables(tbl) self:parameters(tbl) self:constants(tbl) end YAML:generate(sptbl[arg[1]])
data2yaml fixes: repeating constants do not happen now
data2yaml fixes: repeating constants do not happen now
Lua
mit
adamnemecek/AudioKit,eljeff/AudioKit,adamnemecek/AudioKit,adamnemecek/AudioKit,audiokit/AudioKit,eljeff/AudioKit,audiokit/AudioKit,eljeff/AudioKit,eljeff/AudioKit,adamnemecek/AudioKit,audiokit/AudioKit,audiokit/AudioKit
111b8118d14dbb2390af1d911df287019bfb31fc
core/makedeps.lua
core/makedeps.lua
local makeDeps = { _deps = {}, add = function (self, file) if not file and file ~= "nil" then return end self._deps[file] = true end, write = function (self) if type(self.filename) ~= "string" then self.filename = SILE.masterFilename .. ".d" end for dep, _ in pairs(package.loaded) do if dep ~= "_G" then self:add(dep:gsub("%.", "/")) end end local deps = {} for dep, _ in pairs(self._deps) do local resolvedFile = package.searchpath(dep, package.path, "/") if not resolvedFile then resolvedFile = SILE.resolveFile(dep) end if resolvedFile then SU.debug("makedeps", "Resolved required file path", resolvedFile) deps[#deps+1] = resolvedFile else -- SU.warn("Could not resolve dependency path for required file "..file) end end table.sort(deps, function (a, b) return a < b end) local depfile, err = io.open(self.filename, "w") if not depfile then return SU.error(err) end depfile:write(SILE.outputFilename..": "..table.concat(deps, " ").."\n") depfile:close() end } -- Lua 5.1 compatability hack, copied from Penlight's pl.compat library if not package.searchpath then local sep = package.config:sub(1,1) function package.searchpath (mod,path) -- luacheck: ignore mod = mod:gsub('%.',sep) for m in path:gmatch('[^;]+') do local nm = m:gsub('?',mod) local f = io.open(nm,'r') if f then f:close(); return nm end end end end return makeDeps
local makeDeps = { _deps = {}, add = function (self, file) if not file and file ~= "nil" then return end self._deps[file] = true end, write = function (self) if type(self.filename) ~= "string" then self.filename = SILE.masterFilename .. ".d" end for dep, _ in pairs(package.loaded) do if dep ~= "_G" then self:add(dep:gsub("%.", "/")) end end local deps = {} for dep, _ in pairs(self._deps) do local resolvedFile = package.searchpath(dep, package.path, "/") if not resolvedFile then resolvedFile = SILE.resolveFile(dep) end if resolvedFile then SU.debug("makedeps", "Resolved required file path", resolvedFile) deps[#deps+1] = resolvedFile else -- SU.warn("Could not resolve dependency path for required file "..file) end end table.sort(deps, function (a, b) return a < b end) local depfile, err = io.open(self.filename, "w") if not depfile then return SU.error(err) end depfile:write(SILE.outputFilename..": "..table.concat(deps, " ").."\n") depfile:close() end } return makeDeps
Revert "fix(core): Add Lua 5.1 compatibility hack to makedeps code"
Revert "fix(core): Add Lua 5.1 compatibility hack to makedeps code" This reverts commit b6f6b3ea42b910c52ea88ac22166156c8165557c. Compatibility now enabled via pl.compat
Lua
mit
alerque/sile,simoncozens/sile,simoncozens/sile,simoncozens/sile,alerque/sile,alerque/sile,alerque/sile,simoncozens/sile
3fbf4204a71803aefb59fcb76a2026ef6524103e
instacast.lua
instacast.lua
dofile("urlcode.lua") dofile("table_show.lua") local url_count = 0 local tries = 0 local item_type = os.getenv('item_type') local item_value = os.getenv('item_value') 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.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason) local url = urlpos["url"]["url"] local html = urlpos["link_expect_html"] if downloaded[url] == true or addedtolist[url] == true then return false end if (downloaded[url] ~= true or addedtolist[url] ~= true) then if (string.match(url, "/"..item_value.."[a-z0-9]") and string.match(url, "https?://instacastcloud%.com/") and not string.match(url, "/"..item_value.."[a-z0-9][a-z0-9]")) or html == 0 then addedtolist[url] = true return true else return false end end end wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} local html = nil local function check(url) if (downloaded[url] ~= true and addedtolist[url] ~= true) then if string.match(url, "&amp;") then table.insert(urls, { url=string.gsub(url, "&amp;", "&") }) addedtolist[url] = true addedtolist[string.gsub(url, "&amp;", "&")] = true else table.insert(urls, { url=url }) addedtolist[url] = true end end end if string.match(url, item_value) then html = read_file(file) for newurl in string.gmatch(html, 'src="(https?://[^"]+)"') do check(newurl) end for newurl in string.gmatch(html, '"(https?://[^"]+)"') do if (string.match(url, "/"..item_value.."[a-z0-9]") and string.match(url, "https?://instacastcloud%.com/") and not string.match(url, "/"..item_value.."[a-z0-9][a-z0-9]")) then check(newurl) end end for newurl in string.gmatch(html, '"(/[^"]+)"') do if (string.match(url, "/"..item_value.."[a-z0-9]") and string.match(url, "https?://instacastcloud%.com/") and not string.match(url, "/"..item_value.."[a-z0-9][a-z0-9]")) then check("https://instacastcloud.com"..newurl) end 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 status_code = http_stat["statcode"] 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 if string.match(url.url, "https://") then local newurl = string.gsub(url.url, "https://", "http://") downloaded[newurl] = true else downloaded[url.url] = true end end if status_code >= 500 or (status_code >= 400 and status_code ~= 404 and status_code ~= 403 and status_code ~= 400) then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 1") tries = tries + 1 if tries >= 6 then io.stdout:write("\nI give up...\n") io.stdout:flush() tries = 0 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 >= 6 then io.stdout:write("\nI give up...\n") io.stdout:flush() tries = 0 return wget.actions.ABORT else return wget.actions.CONTINUE end end tries = 0 local sleep_time = 0 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 item_type = os.getenv('item_type') local item_value = os.getenv('item_value') local downloaded = {} local addedtolist = {} -- do not download following static files: downloaded["https://instacastcloud.com/bootstrap/css/bootstrap.min.css"] = true downloaded["https://instacastcloud.com/scripts/jquery-1.11.1.min.js"] = true downloaded["https://instacastcloud.com/css/site.css"] = true downloaded["https://instacastcloud.com/mediaelement/mediaelement-and-player.min.js"] = true downloaded["https://instacastcloud.com/mediaelement/mediaelementplayer.min.css"] = true downloaded["https://instacastcloud.com/shared/episode/mediaelement/flashmediaelement.swf"] = true downloaded["https://instacastcloud.com/bootstrap/js/bootstrap.min.js"] = true downloaded["https://instacastcloud.com/dashboard/contact"] = true downloaded["https://instacastcloud.com/signin"] = true downloaded["https://instacastcloud.com/dashboard"] = true downloaded["http://vemedio.com/support/contact"] = true downloaded["http://vemedio.com/discontinued/"] = true downloaded["http://vemedio.com/"] = true downloaded["http://vemedio.com/instacast"] = true downloaded["https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"] = true downloaded["https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"] = true downloaded["https://instacastcloud.com/bootstrap/fonts/glyphicons-halflings-regular.eot"] = true downloaded["https://instacastcloud.com/bootstrap/fonts/glyphicons-halflings-regular.eot?"] = true downloaded["https://instacastcloud.com/bootstrap/fonts/glyphicons-halflings-regular.woff"] = true downloaded["https://instacastcloud.com/bootstrap/fonts/glyphicons-halflings-regular.ttf"] = true downloaded["https://instacastcloud.com/bootstrap/fonts/glyphicons-halflings-regular.svg"] = true downloaded["https://instacastcloud.com/images/icon-50.png"] = true downloaded["https://instacastcloud.com/mediaelement/bigplay.svg"] = true downloaded["https://instacastcloud.com/mediaelement/bigplay.png"] = true downloaded["https://instacastcloud.com/mediaelement/background.png"] = true downloaded["https://instacastcloud.com/mediaelement/loading.gif"] = true downloaded["https://instacastcloud.com/mediaelement/controls.svg"] = true downloaded["https://instacastcloud.com/mediaelement/controls.png"] = true 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.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason) local url = urlpos["url"]["url"] local html = urlpos["link_expect_html"] if downloaded[url] == true or addedtolist[url] == true then return false end if (downloaded[url] ~= true or addedtolist[url] ~= true) then if (string.match(url, "/"..item_value) and string.match(url, "https?://instacastcloud%.com/") and not string.match(url, "/"..item_value.."[a-z0-9]")) or html == 0 then addedtolist[url] = true return true else return false end end end wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} local html = nil if downloaded[url] ~= true then downloaded[url] = true end local function check(url) if (downloaded[url] ~= true and addedtolist[url] ~= true) then if string.match(url, "&amp;") then table.insert(urls, { url=string.gsub(url, "&amp;", "&") }) addedtolist[url] = true addedtolist[string.gsub(url, "&amp;", "&")] = true else table.insert(urls, { url=url }) addedtolist[url] = true end end end if string.match(url, item_value) then html = read_file(file) for newurl in string.gmatch(html, 'src=("https?.//[^"]+)"') do if not string.match(newurl, '"https?://') then check(string.match(newurl, '"(https?)')..":"..string.match(newurl, '"https?.(//.+)')) else check(string.match(newurl, '"(.+)')) end end for newurl in string.gmatch(html, '"(https?://[^"]+)"') do if (string.match(url, "/"..item_value) and string.match(url, "https?://instacastcloud%.com/") and not string.match(url, "/"..item_value.."[a-z0-9]")) then check(newurl) end end for newurl in string.gmatch(html, '"(/[^"]+)"') do if (string.match(url, "/"..item_value) and string.match(url, "https?://instacastcloud%.com/") and not string.match(url, "/"..item_value.."[a-z0-9]")) then check("https://instacastcloud.com"..newurl) end 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 status_code = http_stat["statcode"] 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 if string.match(url.url, "https://") then local newurl = string.gsub(url.url, "https://", "http://") downloaded[newurl] = true else downloaded[url.url] = true end end if status_code >= 500 or (status_code >= 400 and status_code ~= 404 and status_code ~= 403 and status_code ~= 400) then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 1") tries = tries + 1 if tries >= 6 then io.stdout:write("\nI give up...\n") io.stdout:flush() tries = 0 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 >= 6 then io.stdout:write("\nI give up...\n") io.stdout:flush() tries = 0 return wget.actions.ABORT else return wget.actions.CONTINUE end end tries = 0 local sleep_time = 0 if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end
instacast.lua: fixes and additions
instacast.lua: fixes and additions
Lua
unlicense
ArchiveTeam/instacast-grab,ArchiveTeam/instacast-grab
cbe369a714cc1f1155bbcc0a4c9ce2a6d0ac09b6
installer.lua
installer.lua
-- use build.xml to import the zip and json libraries directly local zip = {} local json = {} do local function zip_api_make() @ZIP@ end setfenv(zip_api_make, zip) zip_api_make() local function json_api_make() @JSON@ end setfenv(json_api_make, json) json_api_make() end -- Begin installation local githubApiResponse = http.get("https://api.github.com/repos/Yevano/JVML-JIT/releases") assert(githubApiResponse.getResponseCode() == 200, "Failed github response") print("Got github response") local githubApiJSON = json.decode(githubApiResponse.readAll()) assert(githubApiJSON and githubApiJSON[1] and githubApiJSON[1].assets and githubApiJSON[1].assets[1] and githubApiJSON[1].assets[1].browser_download_url, "Malformed response") print("Got JSON") local zipResponse = http.get(githubApiJSON[1].assets[1].browser_download_url) assert(githubApiResponse.getResponseCode() == 200, "Failed zip response") local zipStr = zipResponse.readAll() local i = 0 local zfs = zip.open({read=function() i = i + 1 return zipStr:sub(i,i) end}) local function copyFilesFromDir(dir) for i,v in ipairs(zfs.list(dir)) do local fullPath = fs.combine(dir, v) if zfs.isDir(fullPath) then copyFilesFromDir(fullPath) else print("Copying file: " .. fullPath) local fh = fs.open(fs.combine(shell.dir(), fullPath), "wb") local zfh = zfs.open(fullPath, "rb") for b in zfh.read do fh.write(b) end fh.close() zfh.close() end end end copyFilesFromDir("") print("Installation complete. It is recommended that you add jvml/bin to your shell's path at startup")
-- use build.xml to import the zip and json libraries directly local zip = setmetatable({}, {__index=getfenv()}) local json = setmetatable({}, {__index=getfenv()}) do local function zip_api_make() @ZIP@ end setfenv(zip_api_make, zip) zip_api_make() local function json_api_make() @JSON@ end setfenv(json_api_make, json) json_api_make() end -- Begin installation local githubApiResponse = http.get("https://api.github.com/repos/Yevano/JVML-JIT/releases") assert(githubApiResponse.getResponseCode() == 200, "Failed github response") print("Got github response") local githubApiJSON = json.decode(githubApiResponse.readAll()) assert(githubApiJSON and githubApiJSON[1] and githubApiJSON[1].assets and githubApiJSON[1].assets[1] and githubApiJSON[1].assets[1].browser_download_url, "Malformed response") print("Got JSON") local zipResponse = http.get(githubApiJSON[1].assets[1].browser_download_url) assert(githubApiResponse.getResponseCode() == 200, "Failed zip response") local zipStr = zipResponse.readAll() local i = 0 local zfs = zip.open({read=function() i = i + 1 return zipStr:sub(i,i) end}) local function copyFilesFromDir(dir) for i,v in ipairs(zfs.list(dir)) do local fullPath = fs.combine(dir, v) if zfs.isDir(fullPath) then copyFilesFromDir(fullPath) else print("Copying file: " .. fullPath) local fh = fs.open(fs.combine(shell.dir(), fullPath), "wb") local zfh = zfs.open(fullPath, "rb") for b in zfh.read do fh.write(b) end fh.close() zfh.close() end end end copyFilesFromDir("") print("Installation complete. It is recommended that you add jvml/bin to your shell's path at startup")
Fixed installer
Fixed installer
Lua
mit
apemanzilla/JVML-JIT,Team-CC-Corp/JVML-JIT
6ec24fe5ce7af67eb5de3d357067bf647dfec329
qwiki.lua
qwiki.lua
dofile("urlcode.lua") dofile("table_show.lua") JSON = (loadfile "JSON.lua")() local url_count = 0 local tries = 0 local item_type = os.getenv('item_type') local item_value = os.getenv('item_value') local downloaded = {} load_json_file = function(file) if file then local f = io.open(file) local data = f:read("*all") f:close() return JSON:decode(data) else return nil end end 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.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason) local url = urlpos["url"]["url"] local html = urlpos["link_expect_html"] local parenturl = parent["url"] local html = nil if item_type == "page" then if string.match(url, "/v/"..item_value) or string.match(url, "cdn[0-9]+%.qwiki%.com") or string.match(url, "p%.typekit%.com") or string.match(url, "use%.typekit%.com") or string.match(url, "[^%.]+%.cloudfront%.net") or string.match(url, "[^%.]+%.amazonaws.com") or string.match(url, "%.json") or string.match(url, "%.m3u8") or string.match(url, "ikiwq%.com") or string.match(url, "/api/") or string.match(url, "/assets/") then return true else return false end end end wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} local html = nil if item_type == "page" then if string.match(url, item_value) or string.match(url, "%.json") or string.match(url, "%.m3u8") then html = read_file(file) for customurl in string.match(html, '"(http[s]?://[^"]+)"') do if string.match(customurl, "/v/"..item_value) or string.match(customurl, "cdn[0-9]+%.qwiki%.com") or string.match(customurl, "p%.typekit%.com") or string.match(customurl, "use%.typekit%.com") or string.match(customurl, "[^%.]+%.cloudfront%.net") or string.match(customurl, "[^%.]+%.amazonaws.com") or string.match(customurl, "%.json") or string.match(customurl, "%.m3u8") or string.match(customurl, "ikiwq%.com") or string.match(customurl, "/api/") or string.match(customurl, "/assets/") then if downloaded[customurl] ~= true then table.insert(urls, { url=customurl }) end end end for customurlnf in string.match(html, '"(/[^"]+)"') do if string.match(customurlnf, "/v/"..item_value) or string.match(customurlnf, "cdn[0-9]+%.qwiki%.com") or string.match(customurlnf, "p%.typekit%.com") or string.match(customurlnf, "use%.typekit%.com") or string.match(customurlnf, "[^%.]+%.cloudfront%.net") or string.match(customurlnf, "[^%.]+%.amazonaws.com") or string.match(customurlnf, "ikiwq%.com") or string.match(customurlnf, "/api/") or string.match(customurlnf, "/assets/") then local base = "http://www.qwiki.com" local customurl = base..customurlnf if downloaded[customurl] ~= true then table.insert(urls, { url=customurl }) end end end for tsurl in string.match(html, "#EXTINF:[0-9]+,[^0123456789abcdefghijklmnopqrstuvwxyz]+([^%.]+%.ts)") do local base = string.match(url, "(http://[^/]+/[^/]+/[^/]+/[^/]+/)") local fulltsurl = base..tsurl if downloaded[fulltsurl] ~= true then table.insert(urls, { url=fulltsurl }) end end 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 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) or status_code == 403 then downloaded[url.url] = true end if status_code >= 500 or (status_code >= 400 and status_code ~= 404 and status_code ~= 403) then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 1") 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(75, 1000) / 100.0) local sleep_time = 0 -- 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") JSON = (loadfile "JSON.lua")() local url_count = 0 local tries = 0 local item_type = os.getenv('item_type') local item_value = os.getenv('item_value') local downloaded = {} load_json_file = function(file) if file then local f = io.open(file) local data = f:read("*all") f:close() return JSON:decode(data) else return nil end end 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.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason) local url = urlpos["url"]["url"] local html = urlpos["link_expect_html"] local parenturl = parent["url"] local html = nil if item_type == "page" then if string.match(url, "/v/"..item_value) or string.match(url, "cdn[0-9]+%.qwiki%.com") or string.match(url, "p%.typekit%.com") or string.match(url, "use%.typekit%.com") or string.match(url, "[^%.]+%.cloudfront%.net") or string.match(url, "[^%.]+%.amazonaws.com") or string.match(url, "%.json") or string.match(url, "%.m3u8") or string.match(url, "ikiwq%.com") or string.match(url, "/api/") or string.match(url, "/assets/") then return true else return false end end end wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} local html = nil if item_type == "page" then if string.match(url, item_value) or string.match(url, "%.json") or string.match(url, "%.m3u8") then html = read_file(file) for customurl in string.match(html, '"(http[s]?://[^"]+)"') do if string.match(customurl, "/v/"..item_value) or string.match(customurl, "cdn[0-9]+%.qwiki%.com") or string.match(customurl, "p%.typekit%.com") or string.match(customurl, "use%.typekit%.com") or string.match(customurl, "[^%.]+%.cloudfront%.net") or string.match(customurl, "[^%.]+%.amazonaws.com") or string.match(customurl, "%.json") or string.match(customurl, "%.m3u8") or string.match(customurl, "ikiwq%.com") or string.match(customurl, "/api/") or string.match(customurl, "/assets/") then if downloaded[customurl] ~= true then table.insert(urls, { url=customurl }) end end end for customurlnf in string.match(html, '"(/[^"]+)"') do if string.match(customurlnf, "/v/"..item_value) or string.match(customurlnf, "cdn[0-9]+%.qwiki%.com") or string.match(customurlnf, "p%.typekit%.com") or string.match(customurlnf, "use%.typekit%.com") or string.match(customurlnf, "[^%.]+%.cloudfront%.net") or string.match(customurlnf, "[^%.]+%.amazonaws.com") or string.match(customurlnf, "ikiwq%.com") or string.match(customurlnf, "/api/") or string.match(customurlnf, "/assets/") then local base = "http://www.qwiki.com" local customurl = base..customurlnf if downloaded[customurl] ~= true then table.insert(urls, { url=customurl }) end end end for tsurl in string.match(html, "#EXTINF:[0-9]+,[^0123456789abcdefghijklmnopqrstuvwxyz]+([^%.]+%.ts)") do local base = string.match(url, "(http://[^/]+/[^/]+/[^/]+/[^/]+/)") local fulltsurl = base..tsurl if downloaded[fulltsurl] ~= true then table.insert(urls, { url=fulltsurl }) end end 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"] 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) or status_code == 403 then downloaded[url.url] = true end if status_code >= 500 or (status_code >= 400 and status_code ~= 404 and status_code ~= 403) then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 1") 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(75, 1000) / 100.0) local sleep_time = 0 -- 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
quizilla.lua: fix
quizilla.lua: fix
Lua
unlicense
ArchiveTeam/qwiki-grab,ArchiveTeam/qwiki-grab
821ea827e0edce8625d47d3a45cbb2daa7dd32cc
core/src/demo/xmake.lua
core/src/demo/xmake.lua
-- add target target("demo") -- add deps add_deps("xmake") -- make as a binary set_kind("binary") -- add defines add_defines("__tb_prefix__=\"xmake\"") -- set the object files directory set_objectdir("$(buildir)/.objs") -- add includes directory add_includedirs("$(projectdir)", "$(projectdir)/src") -- add the common source files add_files("**.c") -- add the resource files (it will be enabled after publishing new version) if is_plat("windows") then add_files("*.rc") end -- add links if is_plat("windows") then add_links("ws2_32", "advapi32", "shell32") add_ldflags("/export:malloc", "/export:free") elseif is_plat("android") then add_links("m", "c") elseif is_plat("macosx") then add_ldflags("-all_load", "-pagezero_size 10000", "-image_base 100000000") else add_links("pthread", "dl", "m", "c") end -- enable xp compatibility mode if is_plat("windows") then if is_arch("x86") then add_ldflags("/subsystem:console,5.01") else add_ldflags("/subsystem:console,5.02") end end -- copy target to the build directory after_build(function (target) os.cp(target:targetfile(), "$(buildir)/xmake.exe") end)
-- add target target("demo") -- add deps add_deps("xmake") -- make as a binary set_kind("binary") -- add defines add_defines("__tb_prefix__=\"xmake\"") -- set the object files directory set_objectdir("$(buildir)/.objs") -- add includes directory add_includedirs("$(projectdir)", "$(projectdir)/src") -- add the common source files add_files("**.c") -- add the resource files (it will be enabled after publishing new version) if is_plat("windows") then add_files("*.rc") end -- add links if is_plat("windows") then add_links("ws2_32", "advapi32", "shell32") add_ldflags("/export:malloc", "/export:free") elseif is_plat("android") then add_links("m", "c") elseif is_plat("macosx") then add_ldflags("-all_load", "-pagezero_size 10000", "-image_base 100000000") else add_links("pthread", "dl", "m", "c") end -- enable xp compatibility mode if is_plat("windows") then if is_arch("x86") then add_ldflags("/subsystem:console,5.01") else add_ldflags("/subsystem:console,5.02") end end -- copy target to the build directory after_build(function (target) os.cp(target:targetfile(), path.join(get_config("buildir"), path.filename(target:targetfile()))) end)
fix core xmake.lua
fix core xmake.lua
Lua
apache-2.0
waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake,waruqi/xmake
68d744f36b34c9111553bffb74726fa87acae190
hammerspoon/layouts/lapseofthought_com.lua
hammerspoon/layouts/lapseofthought_com.lua
-------------------------------------------------------------------------------- -- LAYOUTS -- SINTAX: -- { -- name = "App name" ou { "App name", "App name" } -- title = "Window title" (optional) -- func = function(index, win) -- COMMANDS -- end -- }, -- -- It searches for application "name" and call "func" for each window object -------------------------------------------------------------------------------- local layouts = { { name = "Emacs", func = function(index, win) win:moveToScreen(monitor_2, false, true) end }, { name = "Slack", func = function(index, win) -- first space on 2nd monitor -- spaces.moveWindowToSpace(win:id(), hs.screen.allScreens()[1]:spaces()[1]) if (#hs.screen.allScreens() > 1) then win:moveToScreen(monitor_2, false, true) hsm.windows.moveTopLeft(win) else hsm.windows.moveTopRight(win) end end }, { name = "Adium", func = function(index, win) if (#hs.screen.allScreens() > 1) then -- second space on 1st monitor spaces.moveWindowToSpace(win:id(), hs.screen.allScreens()[2]:spaces()[1]) end hsm.windows.moveBottomLeft(win) end }, { name = "Adium", title = "Contacts", func = function(index, win) if (#hs.screen.allScreens() > 1) then -- second space on 1st monitor spaces.moveWindowToSpace(win:id(), hs.screen.allScreens()[1]:spaces()[2]) end hsm.windows.moveTopLeft(win) end }, { name = "Zoiper", func = function(index, win) hsm.windows.moveTopLeft(win,150,0) end }, } return layouts
-------------------------------------------------------------------------------- -- LAYOUTS -- SINTAX: -- { -- name = "App name" ou { "App name", "App name" } -- title = "Window title" (optional) -- func = function(index, win) -- COMMANDS -- end -- }, -- -- It searches for application "name" and call "func" for each window object -------------------------------------------------------------------------------- local layouts = { { name = "Emacs", func = function(index, win) win:moveToScreen(monitor_2, false, true) end }, { name = "Slack", func = function(index, win) -- first space on 2nd monitor -- spaces.moveWindowToSpace(win:id(), hs.screen.allScreens()[1]:spaces()[1]) if (#hs.screen.allScreens() > 1) then win:moveToScreen(monitor_2, false, true) hsm.windows.moveTopLeft(win) else hsm.windows.moveTopRight(win) end end }, -- { -- name = "Adium", -- func = function(index, win) -- if (#hs.screen.allScreens() > 1) then -- -- second space on 1st monitor -- spaces.moveWindowToSpace(win:id(), hs.screen.allScreens()[2]:spaces()[1]) -- end -- hsm.windows.moveBottomLeft(win) -- end -- }, { name = "Adium", title = "Contacts", func = function(index, win) if (#hs.screen.allScreens() > 1) then -- second space on 1st monitor spaces.moveWindowToSpace(win:id(), hs.screen.allScreens()[1]:spaces()[2]) end hsm.windows.moveTopLeft(win) end }, { name = "Zoiper", func = function(index, win) hsm.windows.moveTopLeft(win,150,0) end }, } return layouts
Fix Adium positioning
Fix Adium positioning
Lua
mit
sjthespian/dotfiles,sjthespian/dotfiles,sjthespian/dotfiles,sjthespian/dotfiles
b977ba6fd0bf1b01431f7d878ca9895c8e2d6712
kong/cmd/migrations.lua
kong/cmd/migrations.lua
local DB = require "kong.db" local log = require "kong.cmd.utils.log" local tty = require "kong.cmd.utils.tty" local meta = require "kong.meta" local conf_loader = require "kong.conf_loader" local kong_global = require "kong.global" local migrations_utils = require "kong.cmd.utils.migrations" local lapp = [[ Usage: kong migrations COMMAND [OPTIONS] Manage database schema migrations. The available commands are: bootstrap Bootstrap the database and run all migrations. up Run any new migrations. finish Finish running any pending migrations after 'up'. list List executed migrations. reset Reset the database. Options: -y,--yes Assume "yes" to prompts and run non-interactively. -q,--quiet Suppress all output. -f,--force Run migrations even if database reports as already executed. --db-timeout (default 60) Timeout, in seconds, for all database operations (including schema consensus for Cassandra). --lock-timeout (default 60) Timeout, in seconds, for nodes waiting on the leader node to finish running migrations. -c,--conf (optional string) Configuration file. ]] local function confirm_prompt(q) local MAX = 3 local ANSWERS = { y = true, Y = true, yes = true, YES = true, n = false, N = false, no = false, NO = false } while MAX > 0 do io.write("> " .. q .. " [Y/n] ") local a = io.read("*l") if ANSWERS[a] ~= nil then return ANSWERS[a] end MAX = MAX - 1 end end local function execute(args) args.db_timeout = args.db_timeout * 1000 args.lock_timeout = args.lock_timeout if args.quiet then log.disable() end local conf = assert(conf_loader(args.conf)) conf.pg_timeout = args.db_timeout -- connect + send + read conf.cassandra_timeout = args.db_timeout -- connect + send + read conf.cassandra_schema_consensus_timeout = args.db_timeout _G.kong = kong_global.new() kong_global.init_pdk(_G.kong, conf, nil) -- nil: latest PDK local db = assert(DB.new(conf)) assert(db:init_connector()) local schema_state = assert(db:schema_state()) if args.command == "list" then if schema_state.needs_bootstrap then log(migrations_utils.NEEDS_BOOTSTRAP_MSG) os.exit(3) end local r = "" if schema_state.executed_migrations then log("Executed migrations:\n%s", schema_state.executed_migrations) r = "\n" end if schema_state.pending_migrations then log("%sPending migrations:\n%s", r, schema_state.pending_migrations) r = "\n" end if schema_state.new_migrations then log("%sNew migrations available:\n%s", r, schema_state.new_migrations) r = "\n" end if schema_state.pending_migrations and schema_state.new_migrations then if r ~= "" then log("") end log.warn("Database has pending migrations from a previous upgrade, " .. "and new migrations from this upgrade (version %s)", tostring(meta._VERSION)) log("\nRun 'kong migrations finish' when ready to complete pending " .. "migrations (%s %s will be incompatible with the previous Kong " .. "version)", db.strategy, db.infos.db_desc) os.exit(4) end if schema_state.pending_migrations then log("\nRun 'kong migrations finish' when ready") os.exit(4) end if schema_state.new_migrations then log("\nRun 'kong migrations up' to proceed") os.exit(5) end -- exit(0) elseif args.command == "bootstrap" then migrations_utils.bootstrap(schema_state, db, args.lock_timeout) elseif args.command == "reset" then if not args.yes then if not tty.isatty() then error("not a tty: invoke 'reset' non-interactively with the --yes flag") end if not confirm_prompt("Are you sure? This operation is irreversible.") then log("cancelled") return end end local ok = migrations_utils.reset(schema_state, db, args.lock_timeout) if not ok then os.exit(1) end os.exit(0) elseif args.command == "up" then migrations_utils.up(schema_state, db, { ttl = args.lock_timeout, force = args.force, abort = true, -- exit the mutex if another node acquired it }) elseif args.command == "finish" then migrations_utils.finish(schema_state, db, { ttl = args.lock_timeout, force = args.force, }) else error("unreachable") end end return { lapp = lapp, execute = execute, sub_commands = { bootstrap = true, up = true, finish = true, list = true, reset = true, } }
local DB = require "kong.db" local log = require "kong.cmd.utils.log" local tty = require "kong.cmd.utils.tty" local meta = require "kong.meta" local conf_loader = require "kong.conf_loader" local kong_global = require "kong.global" local migrations_utils = require "kong.cmd.utils.migrations" local lapp = [[ Usage: kong migrations COMMAND [OPTIONS] Manage database schema migrations. The available commands are: bootstrap Bootstrap the database and run all migrations. up Run any new migrations. finish Finish running any pending migrations after 'up'. list List executed migrations. reset Reset the database. Options: -y,--yes Assume "yes" to prompts and run non-interactively. -q,--quiet Suppress all output. -f,--force Run migrations even if database reports as already executed. --db-timeout (default 60) Timeout, in seconds, for all database operations (including schema consensus for Cassandra). --lock-timeout (default 60) Timeout, in seconds, for nodes waiting on the leader node to finish running migrations. -c,--conf (optional string) Configuration file. ]] local function confirm_prompt(q) local MAX = 3 local ANSWERS = { y = true, Y = true, yes = true, YES = true, n = false, N = false, no = false, NO = false } while MAX > 0 do io.write("> " .. q .. " [Y/n] ") local a = io.read("*l") if ANSWERS[a] ~= nil then return ANSWERS[a] end MAX = MAX - 1 end end local function execute(args) args.db_timeout = args.db_timeout * 1000 args.lock_timeout = args.lock_timeout if args.quiet then log.disable() end local conf = assert(conf_loader(args.conf)) package.path = conf.lua_package_path .. ";" .. package.path conf.pg_timeout = args.db_timeout -- connect + send + read conf.cassandra_timeout = args.db_timeout -- connect + send + read conf.cassandra_schema_consensus_timeout = args.db_timeout _G.kong = kong_global.new() kong_global.init_pdk(_G.kong, conf, nil) -- nil: latest PDK local db = assert(DB.new(conf)) assert(db:init_connector()) local schema_state = assert(db:schema_state()) if args.command == "list" then if schema_state.needs_bootstrap then log(migrations_utils.NEEDS_BOOTSTRAP_MSG) os.exit(3) end local r = "" if schema_state.executed_migrations then log("Executed migrations:\n%s", schema_state.executed_migrations) r = "\n" end if schema_state.pending_migrations then log("%sPending migrations:\n%s", r, schema_state.pending_migrations) r = "\n" end if schema_state.new_migrations then log("%sNew migrations available:\n%s", r, schema_state.new_migrations) r = "\n" end if schema_state.pending_migrations and schema_state.new_migrations then if r ~= "" then log("") end log.warn("Database has pending migrations from a previous upgrade, " .. "and new migrations from this upgrade (version %s)", tostring(meta._VERSION)) log("\nRun 'kong migrations finish' when ready to complete pending " .. "migrations (%s %s will be incompatible with the previous Kong " .. "version)", db.strategy, db.infos.db_desc) os.exit(4) end if schema_state.pending_migrations then log("\nRun 'kong migrations finish' when ready") os.exit(4) end if schema_state.new_migrations then log("\nRun 'kong migrations up' to proceed") os.exit(5) end -- exit(0) elseif args.command == "bootstrap" then migrations_utils.bootstrap(schema_state, db, args.lock_timeout) elseif args.command == "reset" then if not args.yes then if not tty.isatty() then error("not a tty: invoke 'reset' non-interactively with the --yes flag") end if not confirm_prompt("Are you sure? This operation is irreversible.") then log("cancelled") return end end local ok = migrations_utils.reset(schema_state, db, args.lock_timeout) if not ok then os.exit(1) end os.exit(0) elseif args.command == "up" then migrations_utils.up(schema_state, db, { ttl = args.lock_timeout, force = args.force, abort = true, -- exit the mutex if another node acquired it }) elseif args.command == "finish" then migrations_utils.finish(schema_state, db, { ttl = args.lock_timeout, force = args.force, }) else error("unreachable") end end return { lapp = lapp, execute = execute, sub_commands = { bootstrap = true, up = true, finish = true, list = true, reset = true, } }
fix(migrations) include configured Lua path (#5509)
fix(migrations) include configured Lua path (#5509) Include lua_package_path in the package.path when running migrations. This ensures that Kong runs migrations for plugins installed in locations indicated by lua_package_path outside the standard Lua path.
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
0dc6f8d46924d82f22dad4d65c2cf0af5755769b
inventory.lua
inventory.lua
local c = require("component") local sides = require("sides") local inventory = {} function inventory.dropAll(robot, side) -- tries to drop all the robot's inventory into the storage on the given side -- returns true if all if it could be unloaded, false if none or only some could --robot.drop([number]) -- Returns true if at least one item was dropped, false otherwise. local couldDropAll = true for i=1,robot.inventorySize() do local c = robot.count(i) if c > 0 then robot.select(i) robot.drop() -- see if all the items were successfully dropped c = robot.count(i) if c > 0 then -- at least one item couldn't be dropped. -- but we keep trying to drop all so we still drop as much as we can. couldDropAll = false end end end return couldDropAll end function inventory.isIdealTorchSpot(x, z) local isZ = (z % 7) == 0 local isX = (x % 24) == 0 or (x % 24) == 12 if not isZ or not isX then return false end -- we skip every other x torch in the first row local zRow = math.floor(z / 7) % 2 if zRow == 0 and isX == 12 then return false end return true end function inventory.selectItem(robot, name) for i=1,robot.inventorySize() do local stack = component.inventory_controller.getStackInInternalSlot(i) if stack ~= nil and stack.name == name then robot.select(i) return true end end return false end function inventory.placeTorch(robot, side) if inventory.selectItem("minecraft:torch") then local success, what = robot.use(side or sides.bottom) if success and what == 'item_placed' then return true end end return false end return inventory
local c = require("component") local ic = c.inventory_controller local sides = require("sides") local inventory = {} function inventory.dropAll(robot, side) -- tries to drop all the robot's inventory into the storage on the given side -- returns true if all if it could be unloaded, false if none or only some could --robot.drop([number]) -- Returns true if at least one item was dropped, false otherwise. local couldDropAll = true for i=1,robot.inventorySize() do local c = robot.count(i) if c > 0 then robot.select(i) robot.drop() -- see if all the items were successfully dropped c = robot.count(i) if c > 0 then -- at least one item couldn't be dropped. -- but we keep trying to drop all so we still drop as much as we can. couldDropAll = false end end end return couldDropAll end function inventory.isIdealTorchSpot(x, z) local isZ = (z % 7) == 0 local isX = (x % 24) == 0 or (x % 24) == 11 if not isZ or not isX then return false end -- we skip every other x torch in the first row, -- and the 'other' every other torch in the next row local zRow = math.floor(z / 7) % 2 if (zRow == 0 and isX == 11) or (zRow == 1 and isX == 0) then return false end return true end function inventory.selectItem(robot, name) for i=1,robot.inventorySize() do local stack = ic.getStackInInternalSlot(i) if stack ~= nil and stack.name == name then robot.select(i) return true end end return false end function inventory.placeTorch(robot, side) if inventory.selectItem("minecraft:torch") then local success, what = robot.use(side or sides.bottom) if success and what == 'item_placed' then return true end end return false end return inventory
fixes torch placement, wrong var with selectItem
fixes torch placement, wrong var with selectItem
Lua
apache-2.0
InfinitiesLoop/oclib
aa13182afcacd7c7b1208e01e0aff02b356f91d4
src/caching/dependency.lua
src/caching/dependency.lua
local setmetatable = setmetatable local Dependency = {} local mt = {__index=Dependency} local function get_keys(self, master_key) local n = self.cache:get(master_key) if not n then return nil end local keys = {} for i=1, n do keys[i] = master_key .. tostring(i) end local keys2 = self.cache:get_multi(keys) for i=1, #keys2 do keys[#keys+1] = keys2[i] end return keys end function Dependency:next_key(master_key) local i = self.cache:incr(master_key) if not i then self.cache.add(master_key, 0) end i = self.cache:incr(master_key) return master_key .. tostring(i) end function Dependency:add(master_key, key) return self.cache:add(self:next_key(master_key), key, self.time) end function Dependency:delete(master_key) local keys = get_keys(self, master_key) if keys then for i=1, #keys do self.cache.delete(keys[i]) end end end local function new(cache, time) return setmetatable({cache=cache, time=time}, mt) end return { new = new }
local setmetatable = setmetatable local Dependency = {} local mt = {__index=Dependency} local function get_keys(self, master_key) local n = self.cache:get(master_key) if not n then return nil end local keys = {} for i=1, n do keys[i] = master_key .. tostring(i) end local keys2 = self.cache:get_multi(keys) for i=1, #keys do local key = keys2[keys[i]] if key then keys[#keys+1] = key end end return keys end function Dependency:next_key(master_key) local i = self.cache:incr(master_key) if not i then self.cache:add(master_key, 0) i = self.cache:incr(master_key) end return master_key .. tostring(i) end function Dependency:add(master_key, key) return self.cache:add(self:next_key(master_key), key, self.time) end function Dependency:delete(master_key) local keys = get_keys(self, master_key) if keys then for i=1, #keys do self.cache:delete(keys[i]) end end end local function new(cache, time) return setmetatable({cache=cache, time=time}, mt) end return { new = new }
Updated get keys with dependent keys; fixed misprints.
Updated get keys with dependent keys; fixed misprints.
Lua
mit
akornatskyy/lucid
65c12a3af5ea3a149eb1b83d84e89ee9a581f18f
MMOCoreORB/bin/scripts/object/tangible/wearables/armor/bounty_hunter/armor_bounty_hunter_helmet.lua
MMOCoreORB/bin/scripts/object/tangible/wearables/armor/bounty_hunter/armor_bounty_hunter_helmet.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_wearables_armor_bounty_hunter_armor_bounty_hunter_helmet = object_tangible_wearables_armor_bounty_hunter_shared_armor_bounty_hunter_helmet:new { templateType = ARMOROBJECT, playerRaces = { "object/creature/player/bothan_male.iff", "object/creature/player/bothan_female.iff", "object/creature/player/human_male.iff", "object/creature/player/human_female.iff", "object/creature/player/moncal_male.iff", "object/creature/player/moncal_female.iff", "object/creature/player/rodian_male.iff", "object/creature/player/rodian_female.iff", "object/creature/player/sullustan_male.iff", "object/creature/player/sullustan_female.iff", "object/creature/player/trandoshan_male.iff", "object/creature/player/trandoshan_female.iff", "object/creature/player/zabrak_male.iff", "object/creature/player/zabrak_female.iff", "object/mobile/vendor/aqualish_female.iff", "object/mobile/vendor/aqualish_male.iff", "object/mobile/vendor/bothan_female.iff", "object/mobile/vendor/bothan_male.iff", "object/mobile/vendor/devaronian_male.iff", "object/mobile/vendor/human_female.iff", "object/mobile/vendor/human_male.iff", "object/mobile/vendor/moncal_female.iff", "object/mobile/vendor/moncal_male.iff", "object/mobile/vendor/rodian_female.iff", "object/mobile/vendor/rodian_male.iff", "object/mobile/vendor/sullustan_female.iff", "object/mobile/vendor/sullustan_male.iff", "object/mobile/vendor/trandoshan_female.iff", "object/mobile/vendor/trandoshan_male.iff", "object/mobile/vendor/zabrak_female.iff", "object/mobile/vendor/zabrak_male.iff" }, -- The damage types in WeaponObject vulnerability = LIGHTSABER, -- These are default Blue Frog stats healthEncumbrance = 1, actionEncumbrance = 1, mindEncumbrance = 1, -- LIGHT, MEDIUM, HEAVY rating = LIGHT, kinetic = 15, energy = 15, electricity = 15, stun = 15, blast = 15, heat = 15, cold = 15, acid = 15, lightSaber = 0 } ObjectTemplates:addTemplate(object_tangible_wearables_armor_bounty_hunter_armor_bounty_hunter_helmet, "object/tangible/wearables/armor/bounty_hunter/armor_bounty_hunter_helmet.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_wearables_armor_bounty_hunter_armor_bounty_hunter_helmet = object_tangible_wearables_armor_bounty_hunter_shared_armor_bounty_hunter_helmet:new { templateType = ARMOROBJECT, playerRaces = { "object/creature/player/bothan_male.iff", "object/creature/player/bothan_female.iff", "object/creature/player/human_male.iff", "object/creature/player/human_female.iff", "object/creature/player/moncal_male.iff", "object/creature/player/moncal_female.iff", "object/creature/player/rodian_male.iff", "object/creature/player/rodian_female.iff", "object/creature/player/sullustan_male.iff", "object/creature/player/sullustan_female.iff", "object/creature/player/trandoshan_male.iff", "object/creature/player/trandoshan_female.iff", "object/creature/player/twilek_male.iff", "object/creature/player/twilek_female.iff", "object/creature/player/zabrak_male.iff", "object/creature/player/zabrak_female.iff", "object/mobile/vendor/aqualish_female.iff", "object/mobile/vendor/aqualish_male.iff", "object/mobile/vendor/bothan_female.iff", "object/mobile/vendor/bothan_male.iff", "object/mobile/vendor/devaronian_male.iff", "object/mobile/vendor/human_female.iff", "object/mobile/vendor/human_male.iff", "object/mobile/vendor/moncal_female.iff", "object/mobile/vendor/moncal_male.iff", "object/mobile/vendor/rodian_female.iff", "object/mobile/vendor/rodian_male.iff", "object/mobile/vendor/sullustan_female.iff", "object/mobile/vendor/sullustan_male.iff", "object/mobile/vendor/trandoshan_female.iff", "object/mobile/vendor/trandoshan_male.iff", "object/mobile/vendor/twilek_female.iff", "object/mobile/vendor/twilek_male.iff", "object/mobile/vendor/zabrak_female.iff", "object/mobile/vendor/zabrak_male.iff" }, -- The damage types in WeaponObject vulnerability = LIGHTSABER, -- These are default Blue Frog stats healthEncumbrance = 1, actionEncumbrance = 1, mindEncumbrance = 1, -- LIGHT, MEDIUM, HEAVY rating = LIGHT, kinetic = 15, energy = 15, electricity = 15, stun = 15, blast = 15, heat = 15, cold = 15, acid = 15, lightSaber = 0 } ObjectTemplates:addTemplate(object_tangible_wearables_armor_bounty_hunter_armor_bounty_hunter_helmet, "object/tangible/wearables/armor/bounty_hunter/armor_bounty_hunter_helmet.iff")
(unstable) [fixed] equipment issue SWGEMU-349 (Boogles)
(unstable) [fixed] equipment issue SWGEMU-349 (Boogles) git-svn-id: e4cf3396f21da4a5d638eecf7e3b4dd52b27f938@5664 c3d1530f-68f5-4bd0-87dc-8ef779617e40
Lua
agpl-3.0
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,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo,lasko2112/legend-of-hondo,Tatwi/legend-of-hondo
746c511ce9fd64345095a3514b72b07828e83834
deps/process.lua
deps/process.lua
--[[ Copyright 2014 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] exports.name = "luvit/process" exports.version = "1.0.1" local env = require('env') local hooks = require('hooks') local os = require('os') local timer = require('timer') local utils = require('utils') local uv = require('uv') local Emitter = require('core').Emitter local Readable = require('stream').Readable local Writable = require('stream').Writable local pp = require('pretty-print') local function nextTick(...) timer.setImmediate(...) end local function cwd() return uv.cwd() end local lenv = {} function lenv.get(key) return lenv[key] end setmetatable(lenv, { __pairs = function(table) local keys = env.keys() local index = 0 return function(...) index = index + 1 local name = keys[index] if name then return name, table[name] end end end, __index = function(table, key) return env.get(key) end, __newindex = function(table, key, value) if value then env.set(key, value, 1) else env.unset(key) end end }) local function kill(pid, signal) uv.kill(pid, signal or 'sigterm') end local signalWraps = {} local function on(self, _type, listener) if not signalWraps[_type] then local signal = uv.new_signal() signalWraps[_type] = signal uv.unref(signal) uv.signal_start(signal, _type, function() self:emit(_type) end) end Emitter.on(self, _type, listener) end local function removeListener(self, _type, listener) local signal = signalWraps[_type] if not signal then return end signal:stop() uv.close(signal) signalWraps[_type] = nil Emitter.removeListener(self, _type, listener) end local function exit(self, code) code = code or 0 self:emit('exit', code) os.exit(code) end local UvStreamWritable = Writable:extend() function UvStreamWritable:initialize(handle) Writable.initialize(self) self.handle = handle end function UvStreamWritable:_write(data, encoding, callback) uv.write(self.handle, data, callback) end local UvStreamReadable = Readable:extend() function UvStreamReadable:initialize(handle) Readable.initialize(self) self.handle = handle self:on('pause', utils.bind(self._onPause, self)) end function UvStreamReadable:_onPause() uv.read_stop(self.handle) end function UvStreamReadable:_read(n) local function onRead(err, data) if err then return self:emit('error', err) end self:push(data) end if not uv.is_active(self.handle) then uv.read_start(self.handle, onRead) end end local function globalProcess() local process = Emitter:new() process.argv = args process.exitCode = 0 process.nextTick = nextTick process.env = lenv process.cwd = cwd process.kill = kill process.pid = uv.getpid() process.on = on process.exit = exit process.removeListener = removeListener process.stdin = UvStreamReadable:new(pp.stdin) process.stdout = UvStreamWritable:new(pp.stdout) process.stderr = UvStreamWritable:new(pp.stderr) hooks:on('process.exit', utils.bind(process.emit, process, 'exit')) return process end exports.globalProcess = globalProcess
--[[ Copyright 2014 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] exports.name = "luvit/process" exports.version = "1.0.1" local env = require('env') local hooks = require('hooks') local os = require('os') local timer = require('timer') local utils = require('utils') local uv = require('uv') local Emitter = require('core').Emitter local Readable = require('stream').Readable local Writable = require('stream').Writable local pp = require('pretty-print') local function nextTick(...) timer.setImmediate(...) end local function cwd() return uv.cwd() end local lenv = {} function lenv.get(key) return lenv[key] end setmetatable(lenv, { __pairs = function(table) local keys = env.keys() local index = 0 return function(...) index = index + 1 local name = keys[index] if name then return name, table[name] end end end, __index = function(table, key) return env.get(key) end, __newindex = function(table, key, value) if value then env.set(key, value, 1) else env.unset(key) end end }) local function kill(pid, signal) uv.kill(pid, signal or 'sigterm') end local signalWraps = {} local function on(self, _type, listener) if not signalWraps[_type] then local signal = uv.new_signal() signalWraps[_type] = signal uv.unref(signal) uv.signal_start(signal, _type, function() self:emit(_type) end) end Emitter.on(self, _type, listener) end local function removeListener(self, _type, listener) local signal = signalWraps[_type] if not signal then return end signal:stop() uv.close(signal) signalWraps[_type] = nil Emitter.removeListener(self, _type, listener) end local function exit(self, code) code = code or 0 self:emit('exit', code) os.exit(code) end local UvStreamWritable = Writable:extend() function UvStreamWritable:initialize(handle) Writable.initialize(self) self.handle = handle end function UvStreamWritable:_write(data, encoding, callback) uv.write(self.handle, data, callback) end local UvStreamReadable = Readable:extend() function UvStreamReadable:initialize(handle) Readable.initialize(self) self._readableState.reading = false self.handle = handle self:on('pause', utils.bind(self._onPause, self)) end function UvStreamReadable:_onPause() self._readableState.reading = false self.reading = false uv.read_stop(self.handle) end function UvStreamReadable:_read(n) local function onRead(err, data) if err then return self:emit('error', err) end self:push(data) end if not uv.is_active(self.handle) then self.reading = true uv.read_start(self.handle, onRead) end end local function globalProcess() local process = Emitter:new() process.argv = args process.exitCode = 0 process.nextTick = nextTick process.env = lenv process.cwd = cwd process.kill = kill process.pid = uv.getpid() process.on = on process.exit = exit process.removeListener = removeListener process.stdin = UvStreamReadable:new(pp.stdin) process.stdout = UvStreamWritable:new(pp.stdout) process.stderr = UvStreamWritable:new(pp.stderr) hooks:on('process.exit', utils.bind(process.emit, process, 'exit')) return process end exports.globalProcess = globalProcess
process.stdin fixes
process.stdin fixes
Lua
apache-2.0
luvit/luvit,zhaozg/luvit,kaustavha/luvit,GabrielNicolasAvellaneda/luvit-upstream,bsn069/luvit,GabrielNicolasAvellaneda/luvit-upstream,luvit/luvit,kaustavha/luvit,kaustavha/luvit,bsn069/luvit,zhaozg/luvit,GabrielNicolasAvellaneda/luvit-upstream,GabrielNicolasAvellaneda/luvit-upstream,bsn069/luvit
07aefc5be364b98fe2a90a91cabcc2b40061b4b6
pud/component/Component.lua
pud/component/Component.lua
local Class = require 'lib.hump.class' local property = require 'pud.component.property' local message = require 'pud.component.message' -- Component -- local Component = Class{name='Component', function(self, newProperties) self._properties = {} self:_createProperties(newProperties) end } -- destructor function Component:destroy() for k in pairs(self._properties) do self._properties[k] = nil end self._properties = nil if self._attachMessages then for _,msg in pairs(self._attachMessages) do self._mediator:detach(message(msg), self) end self._attachMessages = nil end self._mediator = nil end -- create properties from the given table, add default values if needed function Component:_createProperties(newProperties) if newProperties ~= nil then verify('table', newProperties) for p in pairs(newProperties) do self:_setProperty(p, newProperties[p]) end end -- add missing defaults if self._requiredProperties then verify('table', self._requiredProperties) for _,p in pairs(self._requiredProperties) do if not self._properties[p] then self:_setProperty(p) end end end end -- set the mediator who owns this component function Component:setMediator(mediator) verifyClass('pud.component.ComponentMediator', mediator) self._mediator = mediator end -- attach all of this component's messages to its mediator function Component:attachMessages() if self._attachMessages then for _,msg in pairs(self._attachMessages) do self._mediator:attach(message(msg), self) end end end -- set a property for this component function Component:_setProperty(prop, data) self._properties[property(prop)] = data or property.default(prop) end -- receive a message -- precondition: msg is a valid component message function Component:receive(msg, ...) end -- return the given property if we have it, or nil if we do not -- precondition: p is a valid component property function Component:getProperty(p) return self._properties[p] end -- the class return Component
local Class = require 'lib.hump.class' local property = require 'pud.component.property' local message = require 'pud.component.message' -- Component -- local Component = Class{name='Component', function(self, newProperties) self._properties = {} self:_createProperties(newProperties) end } -- destructor function Component:destroy() for k in pairs(self._properties) do self._properties[k] = nil end self._properties = nil if self._attachMessages then for _,msg in pairs(self._attachMessages) do self._mediator:detach(message(msg), self) end self._attachMessages = nil end self._mediator = nil end -- create properties from the given table, add default values if needed function Component:_createProperties(newProperties) if newProperties ~= nil then verify('table', newProperties) for p in pairs(newProperties) do self:_setProperty(p, newProperties[p]) end end -- add missing defaults if self._requiredProperties then verify('table', self._requiredProperties) for _,p in pairs(self._requiredProperties) do if not self._properties[p] then self:_setProperty(p) end end end end -- set the mediator who owns this component function Component:setMediator(mediator) verifyClass('pud.component.ComponentMediator', mediator) self._mediator = mediator end -- attach all of this component's messages to its mediator function Component:attachMessages() if self._attachMessages then for _,msg in pairs(self._attachMessages) do self._mediator:attach(message(msg), self) end end end -- set a property for this component function Component:_setProperty(prop, data) if data == nil then data = property.default(prop) end self._properties[property(prop)] = data end -- receive a message -- precondition: msg is a valid component message function Component:receive(msg, ...) end -- return the given property if we have it, or nil if we do not -- precondition: p is a valid component property function Component:getProperty(p) return self._properties[p] end -- the class return Component
fix _setProperty to handle setting false boolean value
fix _setProperty to handle setting false boolean value
Lua
mit
scottcs/wyx
6f08f246d1f95a0bb2c27db1fb027aa2a2ca8117
wtest.lua
wtest.lua
print(package.path) package.path = "./frontend/?.lua" require "ui/widget" require "ui/ui" require "ui/readerui" require "ui/menu" require "ui/infomessage" require "ui/confirmbox" require "document/document" TestGrid = Widget:new{} function TestGrid:paintTo(bb) v_line = math.floor(bb:getWidth() / 50) h_line = math.floor(bb:getHeight() / 50) for i=1,h_line do y_num = i*50 renderUtf8Text(bb, 0, y_num+10, Font:getFace("ffont", 12), y_num, true) bb:paintRect(0, y_num, bb:getWidth(), 1, 10) end for i=1,v_line do x_num = i*50 renderUtf8Text(bb, x_num, 10, Font:getFace("ffont", 12), x_num, true) bb:paintRect(x_num, 0, 1, bb:getHeight(), 10) end end -- we create a widget that paints a background: Background = InputContainer:new{ is_always_active = true, -- receive events when other dialogs are active key_events = { OpenDialog = { { "Press" } }, OpenConfirmBox = { { "Del" } }, QuitApplication = { { {"Home","Back"} } } }, -- contains a gray rectangular desktop FrameContainer:new{ background = 3, bordersize = 0, dimen = Screen:getSize() } } function Background:onOpenDialog() UIManager:show(InfoMessage:new{ text = "Example message.", timeout = 10 }) end function Background:onOpenConfirmBox() UIManager:show(ConfirmBox:new{ text = "Please confirm delete" }) end function Background:onInputError() UIManager:quit() end function Background:onQuitApplication() UIManager:quit() end -- example widget: a clock Clock = FrameContainer:new{ background = 0, bordersize = 1, margin = 0, padding = 1 } function Clock:schedFunc() self[1]:free() self[1] = self:getTextWidget() UIManager:setDirty(self) -- reschedule -- TODO: wait until next real second shift UIManager:scheduleIn(1, function() self:schedFunc() end) end function Clock:onShow() self[1] = self:getTextWidget() self:schedFunc() end function Clock:getTextWidget() return CenterContainer:new{ dimen = { w = 300, h = 25 }, TextWidget:new{ text = os.date("%H:%M:%S"), face = Font:getFace("cfont", 12) } } end Quiz = ConfirmBox:new{ text = "Tell me the truth, isn't it COOL?!", width = 300, ok_text = "Yes, of course.", cancel_text = "No, it's ugly.", cancel_callback = function() UIManager:show(InfoMessage:new{ text="You liar!", }) end, } menu_items = { {text = "item1"}, {text = "item2"}, {text = "This is a very very log item whose length should exceed the width of the menu."}, {text = "item3"}, {text = "item4"}, {text = "item5"}, {text = "item6"}, {text = "item7"}, {text = "item8"}, {text = "item9"}, {text = "item10"}, {text = "item11"}, {text = "item12"}, {text = "item13"}, {text = "item14"}, {text = "item15"}, {text = "item16"}, {text = "item17"}, } M = Menu:new{ title = "Test Menu", item_table = menu_items, width = 500, height = 600, } readerwindow = CenterContainer:new{ dimen = Screen:getSize(), FrameContainer:new{ background = 0 } } reader = ReaderUI:new{ dialog = readerwindow, dimen = Geom:new{ w = Screen:getWidth() - 100, h = Screen:getHeight() - 100 }, document = DocumentRegistry:openDocument("test/2col.pdf") --document = DocumentRegistry:openDocument("test/djvu3spec.djvu") --document = DocumentRegistry:openDocument("./README.TXT") } readerwindow[1][1] = reader UIManager:show(Background:new()) UIManager:show(TestGrid) UIManager:show(Clock:new()) UIManager:show(M) UIManager:show(Quiz) UIManager:show(readerwindow) UIManager:run()
print(package.path) package.path = "./frontend/?.lua" require "ui/widget" require "ui/ui" require "ui/readerui" require "ui/menu" require "ui/infomessage" require "ui/confirmbox" require "document/document" ----------------------------------------------------- -- widget that paints the grid on the background ----------------------------------------------------- TestGrid = Widget:new{} function TestGrid:paintTo(bb) v_line = math.floor(bb:getWidth() / 50) h_line = math.floor(bb:getHeight() / 50) for i=1,h_line do y_num = i*50 renderUtf8Text(bb, 0, y_num+10, Font:getFace("ffont", 12), y_num, true) bb:paintRect(0, y_num, bb:getWidth(), 1, 10) end for i=1,v_line do x_num = i*50 renderUtf8Text(bb, x_num, 10, Font:getFace("ffont", 12), x_num, true) bb:paintRect(x_num, 0, 1, bb:getHeight(), 10) end end ----------------------------------------------------- -- we create a widget that paints a background: ----------------------------------------------------- Background = InputContainer:new{ is_always_active = true, -- receive events when other dialogs are active key_events = { OpenDialog = { { "Press" } }, OpenConfirmBox = { { "Del" } }, QuitApplication = { { {"Home","Back"} } } }, -- contains a gray rectangular desktop FrameContainer:new{ background = 3, bordersize = 0, dimen = Screen:getSize(), Widget:new{ dimen = { w = Screen:getWidth(), h = Screen:getHeight(), } }, } } function Background:onOpenDialog() UIManager:show(InfoMessage:new{ text = "Example message.", timeout = 10 }) end function Background:onOpenConfirmBox() UIManager:show(ConfirmBox:new{ text = "Please confirm delete" }) end function Background:onInputError() UIManager:quit() end function Background:onQuitApplication() UIManager:quit() end ----------------------------------------------------- -- example widget: a clock ----------------------------------------------------- Clock = FrameContainer:new{ background = 0, bordersize = 1, margin = 0, padding = 1 } function Clock:schedFunc() self[1]:free() self[1] = self:getTextWidget() UIManager:setDirty(self) -- reschedule -- TODO: wait until next real second shift UIManager:scheduleIn(1, function() self:schedFunc() end) end function Clock:onShow() self[1] = self:getTextWidget() self:schedFunc() end function Clock:getTextWidget() return CenterContainer:new{ dimen = { w = 300, h = 25 }, TextWidget:new{ text = os.date("%H:%M:%S"), face = Font:getFace("cfont", 12) } } end ----------------------------------------------------- -- a confirmbox box widget ----------------------------------------------------- Quiz = ConfirmBox:new{ text = "Tell me the truth, isn't it COOL?!", width = 300, ok_text = "Yes, of course.", cancel_text = "No, it's ugly.", cancel_callback = function() UIManager:show(InfoMessage:new{ text="You liar!", }) end, } ----------------------------------------------------- -- a menu widget ----------------------------------------------------- menu_items = { {text = "item1"}, {text = "item2"}, {text = "This is a very very log item whose length should exceed the width of the menu."}, {text = "item3"}, {text = "item4"}, {text = "item5"}, {text = "item6"}, {text = "item7"}, {text = "item8"}, {text = "item9"}, {text = "item10"}, {text = "item11"}, {text = "item12"}, {text = "item13"}, {text = "item14"}, {text = "item15"}, {text = "item16"}, {text = "item17"}, } M = Menu:new{ title = "Test Menu", item_table = menu_items, width = 500, height = 600, } ----------------------------------------------------- -- a reader view widget ----------------------------------------------------- readerwindow = CenterContainer:new{ dimen = Screen:getSize(), FrameContainer:new{ background = 0 } } reader = ReaderUI:new{ dialog = readerwindow, dimen = Geom:new{ w = Screen:getWidth() - 100, h = Screen:getHeight() - 100 }, document = DocumentRegistry:openDocument("test/2col.pdf") --document = DocumentRegistry:openDocument("test/djvu3spec.djvu") --document = DocumentRegistry:openDocument("./README.TXT") } readerwindow[1][1] = reader ----------------------------------------------------------------------- -- you may want to uncomment following show calls to see the changes ----------------------------------------------------------------------- UIManager:show(Background:new()) UIManager:show(TestGrid) UIManager:show(Clock:new()) UIManager:show(M) UIManager:show(Quiz) UIManager:show(readerwindow) UIManager:run()
fix crash in wtest.lua
fix crash in wtest.lua
Lua
agpl-3.0
koreader/koreader-base,koreader/koreader-base,houqp/koreader-base,mwoz123/koreader,NickSavage/koreader,frankyifei/koreader,houqp/koreader,Hzj-jie/koreader,houqp/koreader-base,lgeek/koreader,Hzj-jie/koreader-base,chrox/koreader,frankyifei/koreader-base,Hzj-jie/koreader-base,Frenzie/koreader-base,Frenzie/koreader-base,apletnev/koreader-base,Frenzie/koreader,mihailim/koreader,Frenzie/koreader,NiLuJe/koreader,noname007/koreader,Hzj-jie/koreader-base,koreader/koreader-base,Frenzie/koreader-base,koreader/koreader-base,apletnev/koreader,Hzj-jie/koreader-base,apletnev/koreader-base,NiLuJe/koreader-base,apletnev/koreader-base,NiLuJe/koreader-base,koreader/koreader,poire-z/koreader,ashhher3/koreader,Frenzie/koreader-base,NiLuJe/koreader,frankyifei/koreader-base,houqp/koreader-base,Markismus/koreader,NiLuJe/koreader-base,koreader/koreader,robert00s/koreader,NiLuJe/koreader-base,ashang/koreader,frankyifei/koreader-base,pazos/koreader,houqp/koreader-base,poire-z/koreader,chihyang/koreader,frankyifei/koreader-base,apletnev/koreader-base
fb1576ca9a4329d80fa11670b9a35d9b3b09c744
groupped-list.lua
groupped-list.lua
-- cached id list key local idListKey = KEYS[1]; -- meta key local metadataKey = KEYS[2]; -- stringified [key]: [aggregateMethod] pairs local aggregates = ARGV[1]; -- local cache local rcall = redis.call; local tinsert = table.insert; local jsonAggregates = cjson.decode(aggregates); local aggregateKeys = {}; local result = {}; local function try(what) local status, result = pcall(what[1]); if not status then return what[2](result); end return result; end local function catch(what) return what[1] end local function anynumber(a) return try { function() local num = tonumber(a); return num ~= nil and num or tonumber(cjson.decode(a)); end, catch { function() return nil; end } } end local function aggregateSum(value1, value2) local num1 = anynumber(value1) or 0; local num2 = anynumber(value2) or 0; return num1 + num2; end local aggregateType = { sum = aggregateSum }; for key, method in pairs(jsonAggregates) do tinsert(aggregateKeys, key); result[key] = 0; if type(aggregateType[method]) ~= "function" then return error("not supported op: " .. method); end end local valuesToGroup = rcall("LRANGE", idListKey, 0, -1); -- group for _, id in ipairs(valuesToGroup) do -- metadata is stored here local metaKey = metadataKey:gsub("*", id, 1); -- pull information about required aggregate keys -- only 1 operation is supported now - sum -- but we can calculate multiple values local values = rcall("HMGET", metaKey, unpack(aggregateKeys)); for i, aggregateKey in ipairs(aggregateKeys) do local aggregateMethod = aggregateType[jsonAggregates[aggregateKey]]; local value = tonumber(values[i] or 0); result[aggregateKey] = aggregateMethod(result[aggregateKey], value); end end return cjson.encode(result);
-- cached id list key local idListKey = KEYS[1]; -- meta key local metadataKey = KEYS[2]; -- stringified [key]: [aggregateMethod] pairs local aggregates = ARGV[1]; -- local cache local rcall = redis.call; local tinsert = table.insert; local jsonAggregates = cjson.decode(aggregates); local aggregateKeys = {}; local result = {}; local function try(what) local status, result = pcall(what[1]); if not status then return what[2](result); end return result; end local function catch(what) return what[1] end local function anynumber(a) return try { function() local num = tonumber(a); return num ~= nil and num or tonumber(cjson.decode(a)); end, catch { function() return nil; end } } end local function aggregateSum(value1, value2) return value1 + value2; end local aggregateType = { sum = aggregateSum }; for key, method in pairs(jsonAggregates) do tinsert(aggregateKeys, key); result[key] = 0; if type(aggregateType[method]) ~= "function" then return error("not supported op: " .. method); end end local valuesToGroup = rcall("LRANGE", idListKey, 0, -1); -- group for _, id in ipairs(valuesToGroup) do -- metadata is stored here local metaKey = metadataKey:gsub("*", id, 1); -- pull information about required aggregate keys -- only 1 operation is supported now - sum -- but we can calculate multiple values local values = rcall("HMGET", metaKey, unpack(aggregateKeys)); for i, aggregateKey in ipairs(aggregateKeys) do local aggregateMethod = aggregateType[jsonAggregates[aggregateKey]]; local value = anynumber(values[i]) or 0; result[aggregateKey] = aggregateMethod(result[aggregateKey], value); end end return cjson.encode(result);
fix: coerce to number earlier
fix: coerce to number earlier
Lua
mit
makeomatic/redis-filtered-sort,makeomatic/redis-filtered-sort
67e56973d1c0e0c3e73acc84d3f10ff71e15ae62
kong/db/migrations/core/013_220_to_230.lua
kong/db/migrations/core/013_220_to_230.lua
local utils = require("kong.tools.utils") local CLUSTER_ID = utils.uuid() return { postgres = { up = string.format([[ CREATE TABLE IF NOT EXISTS "parameters" ( key TEXT PRIMARY KEY, value TEXT NOT NULL, created_at TIMESTAMP WITH TIME ZONE ); INSERT INTO parameters (key, value) VALUES('cluster_id', '%s') ON CONFLICT DO NOTHING; DO $$ BEGIN ALTER TABLE IF EXISTS ONLY "certificates" ADD "cert_alt" TEXT; EXCEPTION WHEN DUPLICATE_COLUMN THEN -- Do nothing, accept existing state END; $$; DO $$ BEGIN ALTER TABLE IF EXISTS ONLY "certificates" ADD "key_alt" TEXT; EXCEPTION WHEN DUPLICATE_COLUMN THEN -- Do nothing, accept existing state END; $$; DO $$ BEGIN ALTER TABLE IF EXISTS ONLY "clustering_data_planes" ADD "version" TEXT; EXCEPTION WHEN DUPLICATE_COLUMN THEN -- Do nothing, accept existing state END; $$; DO $$ BEGIN ALTER TABLE IF EXISTS ONLY "clustering_data_planes" ADD "sync_status" TEXT NOT NULL DEFAULT 'unknown'; EXCEPTION WHEN DUPLICATE_COLUMN THEN -- Do nothing, accept existing state END; $$; ]], CLUSTER_ID), }, cassandra = { up = string.format([[ CREATE TABLE IF NOT EXISTS parameters( key text, value text, created_at timestamp, PRIMARY KEY (key) ); INSERT INTO parameters (key, value) VALUES('cluster_id', '%s') IF NOT EXISTS; ALTER TABLE certificates ADD cert_alt TEXT; ALTER TABLE certificates ADD key_alt TEXT; ALTER TABLE clustering_data_planes ADD version text; ALTER TABLE clustering_data_planes ADD sync_status text; ]], CLUSTER_ID), } }
local utils = require("kong.tools.utils") local CLUSTER_ID = utils.uuid() return { postgres = { up = string.format([[ CREATE TABLE IF NOT EXISTS "parameters" ( key TEXT PRIMARY KEY, value TEXT NOT NULL, created_at TIMESTAMP WITH TIME ZONE ); INSERT INTO parameters (key, value) VALUES('cluster_id', '%s') ON CONFLICT DO NOTHING; DO $$ BEGIN ALTER TABLE IF EXISTS ONLY "certificates" ADD "cert_alt" TEXT; EXCEPTION WHEN DUPLICATE_COLUMN THEN -- Do nothing, accept existing state END; $$; DO $$ BEGIN ALTER TABLE IF EXISTS ONLY "certificates" ADD "key_alt" TEXT; EXCEPTION WHEN DUPLICATE_COLUMN THEN -- Do nothing, accept existing state END; $$; DO $$ BEGIN ALTER TABLE IF EXISTS ONLY "clustering_data_planes" ADD "version" TEXT; EXCEPTION WHEN DUPLICATE_COLUMN THEN -- Do nothing, accept existing state END; $$; DO $$ BEGIN ALTER TABLE IF EXISTS ONLY "clustering_data_planes" ADD "sync_status" TEXT NOT NULL DEFAULT 'unknown'; EXCEPTION WHEN DUPLICATE_COLUMN THEN -- Do nothing, accept existing state END; $$; ]], CLUSTER_ID), }, cassandra = { up = [[ CREATE TABLE IF NOT EXISTS parameters( key text, value text, created_at timestamp, PRIMARY KEY (key) ); ALTER TABLE certificates ADD cert_alt TEXT; ALTER TABLE certificates ADD key_alt TEXT; ALTER TABLE clustering_data_planes ADD version text; ALTER TABLE clustering_data_planes ADD sync_status text; ]], teardown = function(connector) local coordinator = assert(connector:get_stored_connection()) local cassandra = require "cassandra" local _, err = coordinator:execute( "INSERT INTO parameters (key, value) VALUES (?, ?)", { cassandra.text("cluster_id"), cassandra.text(CLUSTER_ID) } ) if err then return nil, err end return true end, } }
fix(migrations) ensure inserts are performed after schema agreement (#7667)
fix(migrations) ensure inserts are performed after schema agreement (#7667) When bootstrapping a multi-node Apache Cassandra cluster, the CREATE TABLE response from the coordinator node does guarantee that the schema altering statement will result in schema agreement across the cluster. This update moves the insert statement to occur after the CREATE TABLE statement to ensure schema agreement occurs before executing the insert statement.
Lua
apache-2.0
Kong/kong,Kong/kong,Kong/kong
cb44d0852c02f97c229d687cc3d249a2db687ddb
SVUI_UnitFrames/class_resources/paladin.lua
SVUI_UnitFrames/class_resources/paladin.lua
--[[ ########################################################## S V U I By: Failcoder ########################################################## LOCALIZED LUA FUNCTIONS ########################################################## ]]-- --[[ GLOBALS ]]-- local _G = _G; local unpack = _G.unpack; local select = _G.select; local pairs = _G.pairs; local ipairs = _G.ipairs; local type = _G.type; local error = _G.error; local pcall = _G.pcall; local tostring = _G.tostring; local tonumber = _G.tonumber; local assert = _G.assert; local math = _G.math; --[[ MATH METHODS ]]-- local random = math.random; --[[ ########################################################## GET ADDON DATA ########################################################## ]]-- local SV = _G['SVUI'] local L = SV.L; local LSM = _G.LibStub("LibSharedMedia-3.0") local MOD = SV.UnitFrames if(not MOD) then return end local oUF_SVUI = MOD.oUF assert(oUF_SVUI, "SVUI UnitFrames: unable to locate oUF.") if(SV.class ~= "PALADIN") then return end --SV.SpecialFX:Register("holypower", [[Spells\Holy_missile_low.m2]], -12, 12, 12, -12, 1.5, 0, 0) SV.SpecialFX:Register("holypower", [[Spells\Holylight_impact_head.m2]], -12, 12, 12, -12, 1.5, 0, -0.4) --SV.SpecialFX:Register("holypower", [[Spells\Paladin_healinghands_state_01.m2]], -12, 12, 12, -12, 1.2, 0, 0) --[[ ########################################################## LOCAL FUNCTIONS ########################################################## ]]-- --[[ ########################################################## POSITIONING ########################################################## ]]-- local OnMove = function() SV.db.UnitFrames.player.classbar.detachFromFrame = true end local Reposition = function(self) local db = SV.db.UnitFrames.player local bar = self.HolyPower; local max = self.MaxClassPower; local size = db.classbar.height + 4; local width = size * max; bar.Holder:SetSize(width, size) if(not db.classbar.detachFromFrame) then SV:ResetAnchors(L["Classbar"]) end local holderUpdate = bar.Holder:GetScript('OnSizeChanged') if holderUpdate then holderUpdate(bar.Holder) end bar:ClearAllPoints() bar:SetAllPoints(bar.Holder) for i = 1, max do bar[i].holder:ClearAllPoints() bar[i].holder:SetHeight(size) bar[i].holder:SetWidth(size) bar[i]:GetStatusBarTexture():SetHorizTile(false) if i==1 then bar[i].holder:SetPoint("TOPLEFT", bar, "TOPLEFT", 0, 0) else bar[i].holder:SetPoint("LEFT", bar[i - 1].holder, "RIGHT", -4, 0) end end end local Update = function(self, event, unit, powerType) if self.unit ~= unit or (powerType and powerType ~= 'HOLY_POWER') then return end local bar = self.HolyPower; local baseCount = UnitPower('player',HOLY_POWER) local maxCount = UnitPowerMax('player',HOLY_POWER) for i=1,maxCount do if i <= baseCount then bar[i]:SetAlpha(1) if(not bar[i].holder.FX:IsShown()) then bar[i].holder.FX:Show() bar[i].holder.FX:UpdateEffect() end else bar[i]:SetAlpha(0) bar[i].holder.FX:Hide() end if i > maxCount then bar[i]:Hide() else bar[i]:Show() end end self.MaxClassPower = maxCount end --[[ ########################################################## PALADIN ########################################################## ]]-- local ShowLink = function(self) self.holder:Show() end local HideLink = function(self) self.holder:Hide() end function MOD:CreateClassBar(playerFrame) local max = 5 local bar = CreateFrame("Frame", nil, playerFrame) bar:SetFrameLevel(playerFrame.TextGrip:GetFrameLevel() + 30) for i = 1, max do local underlay = CreateFrame("Frame", nil, bar); SV.SpecialFX:SetFXFrame(underlay, "holypower", true) underlay.FX:SetFrameStrata("BACKGROUND") underlay.FX:SetFrameLevel(0) bar[i] = CreateFrame("StatusBar", nil, underlay) bar[i]:SetAllPoints(underlay) bar[i]:SetStatusBarTexture("Interface\\AddOns\\SVUI_UnitFrames\\assets\\Class\\PALADIN-HAMMER-FG") bar[i]:GetStatusBarTexture():SetHorizTile(false) bar[i]:SetStatusBarColor(0.9,0.9,0.8) -- bar[i].bg = underlay:CreateTexture(nil,"BORDER") -- bar[i].bg:SetAllPoints(underlay) -- bar[i].bg:SetTexture("Interface\\AddOns\\SVUI_UnitFrames\\assets\\Class\\PALADIN-HAMMER-BG") -- bar[i].bg:SetVertexColor(0,0,0) bar[i].holder = underlay --bar[i]:SetScript("OnShow", ShowLink) --bar[i]:SetScript("OnHide", HideLink) end bar.Override = Update; local classBarHolder = CreateFrame("Frame", "Player_ClassBar", bar) classBarHolder:SetPoint("TOPLEFT", playerFrame, "BOTTOMLEFT", 0, -2) bar:SetPoint("TOPLEFT", classBarHolder, "TOPLEFT", 0, 0) bar.Holder = classBarHolder SV:NewAnchor(bar.Holder, L["Classbar"], OnMove) playerFrame.MaxClassPower = max; playerFrame.RefreshClassBar = Reposition; playerFrame.HolyPower = bar return 'HolyPower' end
--[[ ########################################################## S V U I By: Failcoder ########################################################## LOCALIZED LUA FUNCTIONS ########################################################## ]]-- --[[ GLOBALS ]]-- local _G = _G; local unpack = _G.unpack; local select = _G.select; local pairs = _G.pairs; local ipairs = _G.ipairs; local type = _G.type; local error = _G.error; local pcall = _G.pcall; local tostring = _G.tostring; local tonumber = _G.tonumber; local assert = _G.assert; local math = _G.math; --[[ MATH METHODS ]]-- local random = math.random; --[[ ########################################################## GET ADDON DATA ########################################################## ]]-- local SV = _G['SVUI'] local L = SV.L; local LSM = _G.LibStub("LibSharedMedia-3.0") local MOD = SV.UnitFrames if(not MOD) then return end local oUF_SVUI = MOD.oUF assert(oUF_SVUI, "SVUI UnitFrames: unable to locate oUF.") if(SV.class ~= "PALADIN") then return end --SV.SpecialFX:Register("holypower", [[Spells\Holy_missile_low.m2]], -12, 12, 12, -12, 1.5, 0, 0) SV.SpecialFX:Register("holypower", [[Spells\Holylight_impact_head.m2]], -12, 12, 12, -12, 1.5, 0, -0.4) --SV.SpecialFX:Register("holypower", [[Spells\Paladin_healinghands_state_01.m2]], -12, 12, 12, -12, 1.2, 0, 0) --[[ ########################################################## LOCAL FUNCTIONS ########################################################## ]]-- --[[ ########################################################## POSITIONING ########################################################## ]]-- local OnMove = function() SV.db.UnitFrames.player.classbar.detachFromFrame = true end local Reposition = function(self) local db = SV.db.UnitFrames.player local bar = self.HolyPower; local max = self.MaxClassPower; local size = db.classbar.height + 4; local width = size * max; bar.Holder:SetSize(width, size) if(not db.classbar.detachFromFrame) then SV:ResetAnchors(L["Classbar"]) end local holderUpdate = bar.Holder:GetScript('OnSizeChanged') if holderUpdate then holderUpdate(bar.Holder) end bar:ClearAllPoints() bar:SetAllPoints(bar.Holder) for i = 1, max do bar[i].holder:ClearAllPoints() bar[i].holder:SetHeight(size) bar[i].holder:SetWidth(size) bar[i]:GetStatusBarTexture():SetHorizTile(false) if i==1 then bar[i].holder:SetPoint("TOPLEFT", bar, "TOPLEFT", 0, 0) else bar[i].holder:SetPoint("LEFT", bar[i - 1].holder, "RIGHT", -4, 0) end end end local Update = function(self, event, unit, powerType) if self.unit ~= unit or (powerType and powerType ~= 'HOLY_POWER') then return end local bar = self.HolyPower; local baseCount = UnitPower('player',Enum.PowerType.HolyPower) local maxCount = UnitPowerMax('player',Enum.PowerType.HolyPower) for i=1,maxCount do if i <= baseCount then bar[i]:SetAlpha(1) if(not bar[i].holder.FX:IsShown()) then bar[i].holder.FX:Show() bar[i].holder.FX:UpdateEffect() end else bar[i]:SetAlpha(0) bar[i].holder.FX:Hide() end if i > maxCount then bar[i]:Hide() else bar[i]:Show() end end self.MaxClassPower = maxCount end --[[ ########################################################## PALADIN ########################################################## ]]-- local ShowLink = function(self) self.holder:Show() end local HideLink = function(self) self.holder:Hide() end function MOD:CreateClassBar(playerFrame) local max = 5 local bar = CreateFrame("Frame", nil, playerFrame) bar:SetFrameLevel(playerFrame.TextGrip:GetFrameLevel() + 30) for i = 1, max do local underlay = CreateFrame("Frame", nil, bar); SV.SpecialFX:SetFXFrame(underlay, "holypower", true) underlay.FX:SetFrameStrata("BACKGROUND") underlay.FX:SetFrameLevel(0) bar[i] = CreateFrame("StatusBar", nil, underlay) bar[i]:SetAllPoints(underlay) bar[i]:SetStatusBarTexture("Interface\\AddOns\\SVUI_UnitFrames\\assets\\Class\\PALADIN-HAMMER-FG") bar[i]:GetStatusBarTexture():SetHorizTile(false) bar[i]:SetStatusBarColor(0.9,0.9,0.8) -- bar[i].bg = underlay:CreateTexture(nil,"BORDER") -- bar[i].bg:SetAllPoints(underlay) -- bar[i].bg:SetTexture("Interface\\AddOns\\SVUI_UnitFrames\\assets\\Class\\PALADIN-HAMMER-BG") -- bar[i].bg:SetVertexColor(0,0,0) bar[i].holder = underlay --bar[i]:SetScript("OnShow", ShowLink) --bar[i]:SetScript("OnHide", HideLink) end bar.Override = Update; local classBarHolder = CreateFrame("Frame", "Player_ClassBar", bar) classBarHolder:SetPoint("TOPLEFT", playerFrame, "BOTTOMLEFT", 0, -2) bar:SetPoint("TOPLEFT", classBarHolder, "TOPLEFT", 0, 0) bar.Holder = classBarHolder SV:NewAnchor(bar.Holder, L["Classbar"], OnMove) playerFrame.MaxClassPower = max; playerFrame.RefreshClassBar = Reposition; playerFrame.HolyPower = bar return 'HolyPower' end
Paladin Power Fix
Paladin Power Fix For real this time...
Lua
mit
finalsliver/supervillain-ui,FailcoderAddons/supervillain-ui
115bf08364683502777d3c54905dc0d5a4a5d916
modules/game_cooldown/cooldown.lua
modules/game_cooldown/cooldown.lua
local ProgressCallback = { update = 1, finish = 2 } cooldownWindow = nil cooldownButton = nil contentsPanel = nil cooldownPanel = nil lastPlayer = nil function init() connect(g_game, { onGameStart = online, onSpellGroupCooldown = onSpellGroupCooldown, onSpellCooldown = onSpellCooldown }) cooldownButton = modules.client_topmenu.addRightGameToggleButton('cooldownButton', tr('Cooldowns'), '/images/topbuttons/cooldowns', toggle) cooldownButton:setOn(true) cooldownButton:hide() cooldownWindow = g_ui.loadUI('cooldown', modules.game_interface.getRightPanel()) cooldownWindow:disableResize() cooldownWindow:setup() contentsPanel = cooldownWindow:getChildById('contentsPanel') cooldownPanel = contentsPanel:getChildById('cooldownPanel') -- preload cooldown images for k,v in pairs(SpelllistSettings) do g_textures.preload(v.iconFile) end if g_game.isOnline() then online() end end function terminate() disconnect(g_game, { onGameStart = online, onSpellGroupCooldown = onSpellGroupCooldown, onSpellCooldown = onSpellCooldown }) cooldownWindow:destroy() cooldownButton:destroy() end function loadIcon(iconId) local spell, profile, spellName = Spells.getSpellByIcon(iconId) if not spellName then return end clientIconId = Spells.getClientId(spellName) if not clientIconId then return end local icon = cooldownPanel:getChildById(iconId) if not icon then icon = g_ui.createWidget('SpellIcon') icon:setId(iconId) end icon:setImageSource(SpelllistSettings[profile].iconFile) icon:setImageClip(Spells.getImageClip(clientIconId, profile)) return icon end function onMiniWindowClose() cooldownButton:setOn(false) end function toggle() if cooldownButton:isOn() then cooldownWindow:close() cooldownButton:setOn(false) else cooldownWindow:open() cooldownButton:setOn(true) end end function online() if g_game.getFeature(GameSpellList) then cooldownButton:show() else cooldownButton:hide() cooldownWindow:close() end if not lastPlayer or lastPlayer ~= g_game.getCharacterName() then refresh() lastPlayer = g_game.getCharacterName() end end function refresh() cooldownPanel:destroyChildren() end function removeCooldown(progressRect) removeEvent(progressRect.event) if progressRect.icon then progressRect.icon:destroy() progressRect.icon = nil end progressRect = nil end function turnOffCooldown(progressRect) removeEvent(progressRect.event) if progressRect.icon then progressRect.icon:setOn(false) progressRect.icon = nil end -- create particles --[[local particle = g_ui.createWidget('GroupCooldownParticles', progressRect) particle:fill('parent') scheduleEvent(function() particle:destroy() end, 1000) -- hack until onEffectEnd]] progressRect = nil end function initCooldown(progressRect, updateCallback, finishCallback) progressRect:setPercent(0) progressRect.callback = {} progressRect.callback[ProgressCallback.update] = updateCallback progressRect.callback[ProgressCallback.finish] = finishCallback updateCallback() end function updateCooldown(progressRect, interval) progressRect:setPercent(progressRect:getPercent() + 5) if progressRect:getPercent() < 100 then removeEvent(progressRect.event) progressRect.event = scheduleEvent(function() progressRect.callback[ProgressCallback.update]() end, interval) else progressRect.callback[ProgressCallback.finish]() end end function onSpellCooldown(iconId, duration) local icon = loadIcon(iconId) if not icon then return end icon:setParent(cooldownPanel) local progressRect = icon:getChildById(iconId) if not progressRect then progressRect = g_ui.createWidget('SpellProgressRect', icon) progressRect:setId(iconId) progressRect.icon = icon progressRect:fill('parent') else progressRect:setPercent(0) end progressRect:setTooltip(spellName) local updateFunc = function() updateCooldown(progressRect, duration/19) end local finishFunc = function() removeCooldown(progressRect) end initCooldown(progressRect, updateFunc, finishFunc) end function onSpellGroupCooldown(groupId, duration) if not SpellGroups[groupId] then return end local icon = contentsPanel:getChildById('groupIcon' .. SpellGroups[groupId]) local progressRect = contentsPanel:getChildById('progressRect' .. SpellGroups[groupId]) if icon then icon:setOn(true) removeEvent(icon.event) end progressRect.icon = icon if progressRect then removeEvent(progressRect.event) local updateFunc = function() updateCooldown(progressRect, duration/19) end local finishFunc = function() turnOffCooldown(progressRect) end initCooldown(progressRect, updateFunc, finishFunc) end end
local ProgressCallback = { update = 1, finish = 2 } cooldownWindow = nil cooldownButton = nil contentsPanel = nil cooldownPanel = nil lastPlayer = nil function init() connect(g_game, { onGameStart = online, onSpellGroupCooldown = onSpellGroupCooldown, onSpellCooldown = onSpellCooldown }) cooldownButton = modules.client_topmenu.addRightGameToggleButton('cooldownButton', tr('Cooldowns'), '/images/topbuttons/cooldowns', toggle) cooldownButton:setOn(true) cooldownButton:hide() cooldownWindow = g_ui.loadUI('cooldown', modules.game_interface.getRightPanel()) cooldownWindow:disableResize() cooldownWindow:setup() contentsPanel = cooldownWindow:getChildById('contentsPanel') cooldownPanel = contentsPanel:getChildById('cooldownPanel') -- preload cooldown images for k,v in pairs(SpelllistSettings) do g_textures.preload(v.iconFile) end if g_game.isOnline() then online() end end function terminate() disconnect(g_game, { onGameStart = online, onSpellGroupCooldown = onSpellGroupCooldown, onSpellCooldown = onSpellCooldown }) cooldownWindow:destroy() cooldownButton:destroy() end function loadIcon(iconId) local spell, profile, spellName = Spells.getSpellByIcon(iconId) if not spellName then return end clientIconId = Spells.getClientId(spellName) if not clientIconId then return end local icon = cooldownPanel:getChildById(iconId) if not icon then icon = g_ui.createWidget('SpellIcon') icon:setId(iconId) end icon:setImageSource(SpelllistSettings[profile].iconFile) icon:setImageClip(Spells.getImageClip(clientIconId, profile)) return icon end function onMiniWindowClose() cooldownButton:setOn(false) end function toggle() if cooldownButton:isOn() then cooldownWindow:close() cooldownButton:setOn(false) else cooldownWindow:open() cooldownButton:setOn(true) end end function online() if g_game.getFeature(GameSpellList) then cooldownButton:show() else cooldownButton:hide() cooldownWindow:close() end if not lastPlayer or lastPlayer ~= g_game.getCharacterName() then refresh() lastPlayer = g_game.getCharacterName() end end function refresh() cooldownPanel:destroyChildren() end function removeCooldown(progressRect) removeEvent(progressRect.event) if progressRect.icon then progressRect.icon:destroy() progressRect.icon = nil end progressRect = nil end function turnOffCooldown(progressRect) removeEvent(progressRect.event) if progressRect.icon then progressRect.icon:setOn(false) progressRect.icon = nil end -- create particles --[[local particle = g_ui.createWidget('GroupCooldownParticles', progressRect) particle:fill('parent') scheduleEvent(function() particle:destroy() end, 1000) -- hack until onEffectEnd]] progressRect = nil end function initCooldown(progressRect, updateCallback, finishCallback) progressRect:setPercent(0) progressRect.callback = {} progressRect.callback[ProgressCallback.update] = updateCallback progressRect.callback[ProgressCallback.finish] = finishCallback updateCallback() end function updateCooldown(progressRect, duration) progressRect:setPercent(progressRect:getPercent() + 10000/duration) if progressRect:getPercent() < 100 then removeEvent(progressRect.event) progressRect.event = scheduleEvent(function() progressRect.callback[ProgressCallback.update]() end, 100) else progressRect.callback[ProgressCallback.finish]() end end function onSpellCooldown(iconId, duration) local icon = loadIcon(iconId) if not icon then return end icon:setParent(cooldownPanel) local progressRect = icon:getChildById(iconId) if not progressRect then progressRect = g_ui.createWidget('SpellProgressRect', icon) progressRect:setId(iconId) progressRect.icon = icon progressRect:fill('parent') else progressRect:setPercent(0) end progressRect:setTooltip(spellName) local updateFunc = function() updateCooldown(progressRect, duration) end local finishFunc = function() removeCooldown(progressRect) end initCooldown(progressRect, updateFunc, finishFunc) end function onSpellGroupCooldown(groupId, duration) if not SpellGroups[groupId] then return end local icon = contentsPanel:getChildById('groupIcon' .. SpellGroups[groupId]) local progressRect = contentsPanel:getChildById('progressRect' .. SpellGroups[groupId]) if icon then icon:setOn(true) removeEvent(icon.event) end progressRect.icon = icon if progressRect then removeEvent(progressRect.event) local updateFunc = function() updateCooldown(progressRect, duration) end local finishFunc = function() turnOffCooldown(progressRect) end initCooldown(progressRect, updateFunc, finishFunc) end end
Fix spell cooldown timer
Fix spell cooldown timer
Lua
mit
dreamsxin/otclient,kwketh/otclient,gpedro/otclient,dreamsxin/otclient,Cavitt/otclient_mapgen,Cavitt/otclient_mapgen,Radseq/otclient,gpedro/otclient,dreamsxin/otclient,gpedro/otclient,kwketh/otclient,Radseq/otclient